query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
The name of the application that is associated with this environment.
def application_name(self) -> pulumi.Output[str]: return pulumi.get(self, "application_name")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def app_name(self) -> str:\n return self._app_name", "def app_name(self):\n return self._app_name", "def app_name(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"app_name\")", "def app_name(self): # pylint:disable=function-redefined\n return self._app_name", ...
[ "0.8760097", "0.8733922", "0.8601743", "0.8560242", "0.8511749", "0.8471325", "0.8393377", "0.8365738", "0.8314625", "0.8314625", "0.8314625", "0.8314625", "0.811715", "0.8087263", "0.8060348", "0.8050741", "0.80447793", "0.80227804", "0.80048144", "0.79946846", "0.7801479", ...
0.8621024
3
If specified, the environment attempts to use this value as the prefix for the CNAME in your Elastic Beanstalk environment URL. If not specified, the CNAME is generated automatically by appending a random alphanumeric string to the environment name.
def cname_prefix(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "cname_prefix")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_env_prefix(instrument):\n return \"crds://\"", "def create_r53_name ( base_name, name ) :\n env = get_env_type( base_name )\n if env :\n env = env.lower( )\n if ( env == 'prod' ) :\n return name\n\n return name + '.' + env", "def env_name(self):\n return f\"{self.project_nam...
[ "0.6500855", "0.5895467", "0.5876529", "0.5587471", "0.55460733", "0.5484087", "0.5324461", "0.5320309", "0.5279635", "0.5274285", "0.52700907", "0.52646524", "0.5225509", "0.5187014", "0.5178442", "0.5177224", "0.5163091", "0.5162621", "0.5136999", "0.51282483", "0.5125458",...
0.52051395
13
Your description for this environment.
def description(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "description")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def describe(self):\r\n print( self.name + \" is here!\" )\r\n print( self.description )", "def description(self):\n pass", "def description(self):\n pass", "def description():", "def description(self) -> str:\n pass", "def describe(self):\n print(self.descriptio...
[ "0.76594716", "0.7642881", "0.7642881", "0.7590907", "0.75673366", "0.754099", "0.754099", "0.74186075", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0.73050547", "0....
0.0
-1
A unique name for the environment.
def environment_name(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "environment_name")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def name(self):\n return self._env_name", "def name(self):\n return get_env_name(self.tool_name,\n self._python,\n self._requirements,\n self._tagged_env_vars)", "def env_name(self):\n return f\"{self.project_...
[ "0.79474497", "0.75676024", "0.7346393", "0.71637094", "0.69561476", "0.69324404", "0.6864522", "0.6832018", "0.6827754", "0.66545093", "0.66468686", "0.65825635", "0.6506662", "0.6461384", "0.6451408", "0.64490986", "0.6430531", "0.6412154", "0.6346107", "0.6341232", "0.6337...
0.7082336
4
The Amazon Resource Name (ARN) of an existing IAM role to be used as the environment's operations role.
def operations_role(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "operations_role")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def role_arn(self) -> str:\n return pulumi.get(self, \"role_arn\")", "def iam_role_arn(self) -> str:\n return pulumi.get(self, \"iam_role_arn\")", "def role_arn(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"role_arn\")", "def role_arn(self) -> pulumi.Input[str]:\n ...
[ "0.7611145", "0.7547483", "0.7543366", "0.7487498", "0.7469303", "0.7469303", "0.7371766", "0.7371766", "0.73421746", "0.73421746", "0.73421746", "0.73421746", "0.7280896", "0.7280896", "0.72515625", "0.70219666", "0.69590557", "0.6927607", "0.69078577", "0.6905639", "0.68344...
0.7117283
15
Keyvalue pairs defining configuration options for this environment, such as the instance type.
def option_settings(self) -> pulumi.Output[Optional[Sequence['outputs.EnvironmentOptionSetting']]]: return pulumi.get(self, "option_settings")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def define_options(self):\n return {\n 'basename': OptionDef(required=True, default_value='keycloak', allowed_types=[str]),\n 'namespace': OptionDef(required=True, default_value='default', allowed_types=[str]),\n 'config': {\n 'service_port': OptionDef(require...
[ "0.6605203", "0.65723705", "0.65408826", "0.65288186", "0.651911", "0.649711", "0.6480811", "0.64501303", "0.6391103", "0.6391103", "0.6391103", "0.6328672", "0.6306278", "0.63004625", "0.6244758", "0.62443846", "0.624185", "0.6222133", "0.6206737", "0.6206737", "0.6205525", ...
0.0
-1
The Amazon Resource Name (ARN) of the custom platform to use with the environment.
def platform_arn(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "platform_arn")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def platform_arn(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"platform_arn\")", "def platform(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"platform\")", "def platform():\n return \"micaz\"", "def PlatformName():\n if override_platform_name:\n return overr...
[ "0.7735306", "0.66278744", "0.6624211", "0.6606932", "0.6323558", "0.6283941", "0.6234539", "0.61513674", "0.6081606", "0.60462385", "0.60026896", "0.5988347", "0.598575", "0.59628206", "0.5962734", "0.59611076", "0.59324396", "0.59225625", "0.59225625", "0.5922316", "0.59223...
0.7835914
0
The name of an Elastic Beanstalk solution stack (platform version) to use with the environment.
def solution_stack_name(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "solution_stack_name")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def solution_stack_name(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"solution_stack_name\")", "def stackname(self):\n return self.BASE_NAME.format(**self.conf)", "def stack_name(self) -> str:\n return jsii.get(self, \"stackName\")", "def env_name(self):\n retu...
[ "0.6874254", "0.68344885", "0.6518337", "0.65035015", "0.6400849", "0.62462306", "0.61668295", "0.6154686", "0.6143118", "0.6137554", "0.61008966", "0.6086461", "0.60863656", "0.60621977", "0.60092354", "0.5980697", "0.5922324", "0.5898759", "0.5881433", "0.58511484", "0.5829...
0.6848552
1
Specifies the tags applied to resources in the environment.
def tags(self) -> pulumi.Output[Optional[Sequence['outputs.EnvironmentTag']]]: return pulumi.get(self, "tags")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tags(self, tags):\n self._tags = tags", "def tags(self, tags):\n self._tags = tags", "def tags(self, tags):\n self._tags = tags", "def tags(self, tags):\n\n self._tags = tags", "def tags(self, tags):\n\n self._tags = tags", "def tags(self, tags):\n\n self._ta...
[ "0.72549057", "0.72549057", "0.72549057", "0.71421885", "0.71421885", "0.71421885", "0.71421885", "0.71421885", "0.71421885", "0.71421885", "0.71421885", "0.71421885", "0.71421885", "0.7037167", "0.6819578", "0.6523886", "0.65198076", "0.6484716", "0.63857216", "0.6372989", "...
0.60345477
36
The name of the Elastic Beanstalk configuration template to use with the environment.
def template_name(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "template_name")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_configuration_template(self):\n return CONFIG_TEMPLATE", "def template_name(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"template_name\")", "def inspect_template_name(self) -> str:\n return pulumi.get(self, \"inspect_template_name\")", "def template(self):\n ret...
[ "0.674576", "0.65179414", "0.6502485", "0.64848953", "0.6403082", "0.6380132", "0.6355327", "0.63501006", "0.63139427", "0.6292424", "0.62733996", "0.6261383", "0.6251333", "0.61383086", "0.61321324", "0.610607", "0.60788184", "0.60778415", "0.60102946", "0.6002426", "0.59737...
0.6263441
11
Specifies the tier to use in creating this environment. The environment tier that you choose determines whether Elastic Beanstalk provisions resources to support a web application that handles HTTP(S) requests or a web application that handles backgroundprocessing tasks.
def tier(self) -> pulumi.Output[Optional['outputs.EnvironmentTier']]: return pulumi.get(self, "tier")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tier(self) -> Optional[pulumi.Input['EnvironmentTierArgs']]:\n return pulumi.get(self, \"tier\")", "def tier(self):\n\n if not hasattr(self, \"_tier\"):\n self._tier = self.opts.get(\"tier\")\n return self._tier", "def set_tier(self, tier):\n self.single_selection_fro...
[ "0.7523294", "0.697658", "0.64992577", "0.6451572", "0.6353276", "0.6353276", "0.6353276", "0.62764174", "0.62093973", "0.61662465", "0.61662465", "0.61662465", "0.61662465", "0.6111787", "0.6032573", "0.6006158", "0.59823996", "0.5843192", "0.5832442", "0.5829042", "0.577708...
0.68612045
2
The name of the application version to deploy.
def version_label(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "version_label")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def version_name(self) -> str:\n return pulumi.get(self, \"version_name\")", "def app_version(self) -> str:\n return pulumi.get(self, \"app_version\")", "def version_name(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"version_name\")", "def get_package_name(self):\n ...
[ "0.79674184", "0.752541", "0.7301922", "0.7259704", "0.72298706", "0.71760947", "0.7097202", "0.7067314", "0.7017301", "0.69222665", "0.69211406", "0.6917922", "0.6909662", "0.6909662", "0.6832326", "0.6825434", "0.67636746", "0.6756408", "0.67505723", "0.67250407", "0.670931...
0.6369655
59
The game algorithm, using continuation for a pure linear Python code
def go(self, comp): self.attempt = 1 number = random.randint(1, 20) comp.call(util.Confirm('I choose a number between 1 and 20. Try to guess it')) while True: x = comp.call(util.Ask('Try #%d: ' % self.attempt)) if not x.isdigit(): continue x = int(x) if x > number: comp.call(util.Confirm('Choose a lower number')) if x < number: comp.call(util.Confirm('Choose a greater number')) if x == number: comp.call(util.Confirm(self.final_text % self.attempt)) break self.attempt += 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def play_game():\n board = create_board()\n while True:\n for player in [1, 2]:\n random_place(board, player)\n result = evaluate(board)\n if result != 0:\n return result", "def __run_game(game):\n\n while not game['lost']:\n\n game['move'], ...
[ "0.66346675", "0.6546741", "0.6394211", "0.63758504", "0.636938", "0.6360782", "0.6356706", "0.6337687", "0.633712", "0.63219684", "0.6298109", "0.6297704", "0.629413", "0.62893116", "0.6288498", "0.6279202", "0.6278614", "0.62572694", "0.6235934", "0.6230041", "0.6225665", ...
0.0
-1
open the router's port to enable external connection
def check_and_open_port_by_upnp(external_port, internal_port, protocol): request_url = cast_rooter_request() if request_url is None: log.debug("node is not in local network protected by a router") return soap_url = get_soap_url(request_url) internal_client = get_localhost_ip() # check existence for mapping in soap_get_mapping(soap_url): if mapping.enabled == 1 and \ mapping.external_port == external_port and \ mapping.internal_port == internal_port and \ mapping.protocol == protocol and \ mapping.external_client == internal_client: return # open port soap_add_mapping(soap_url, external_port, internal_port, internal_client, protocol) log.info(f"open port by upnp {internal_port} -> {external_port}")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _open(self):\n \n # Open Device\n try:\n logger.debug(\"%s: TCP port opening started...\" % \\\n self.__class__.__name__)\n self._tcp_socket.bind(tuple(['',self._port]))\n self._tcp_socket.listen(self._max)\n logger.debug(...
[ "0.70109576", "0.7003254", "0.6999157", "0.694705", "0.6878419", "0.67956185", "0.6750625", "0.67262423", "0.66802317", "0.6659476", "0.65642065", "0.65545535", "0.6504106", "0.6492532", "0.64708275", "0.6456751", "0.6438551", "0.6426962", "0.6417681", "0.63918823", "0.635597...
0.6510023
12
get external ip address
def get_external_ip(soap_url) -> str: s_o_a_p = '<?xml version="1.0"?>\r\n' s_o_a_p += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle=' \ '"http://schemas.xmlsoap.org/soap/encoding/">\r\n' s_o_a_p += '<s:Body>\r\n' s_o_a_p += '<u:GetExternalIPAddress xmlns:u="urn:schemas-upnp-org:service:WANPPPConnection:1">\r\n' s_o_a_p += '</u:GetExternalIPAddress>\r\n' s_o_a_p += '</s:Body>\r\n' s_o_a_p += '</s:Envelope>\r\n' try: req = Request(soap_url) req.add_header('Content-Type', 'text/xml; charset="utf-8"') req.add_header('SOAPACTION', '"urn:schemas-upnp-org:service:WANPPPConnection:1#GetExternalIPAddress"') req.data = s_o_a_p.encode('utf8') result = xmltodict.parse(urlopen(req).read().decode()) return result['s:Envelope']['s:Body']['u:GetExternalIPAddressResponse']['NewExternalIPAddress'] except Exception: log.debug("get_external_ip exception", exc_info=True)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def GetExternalIp():\n h = httplib2.Http(tempfile.gettempdir(), timeout=10)\n url = 'http://whatismyip.akamai.com'\n resp, content = h.request(url, 'GET')\n if resp.status == 200:\n return content\n for provider in (UltraDNSAuth(), MyResolverInfo()):\n answer = provider.GetClientIp()\n if answer:\n ...
[ "0.83233213", "0.8125571", "0.7973399", "0.7969459", "0.7911862", "0.79069215", "0.78181463", "0.78089017", "0.7789853", "0.7779208", "0.7745145", "0.7729852", "0.77084523", "0.769121", "0.76832366", "0.76812357", "0.7676216", "0.7659212", "0.76183903", "0.7610075", "0.760447...
0.7011273
87
get local ip address
def get_localhost_ip(): try: return [ (s.connect((NAME_SERVER, 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)] ][0][1] except Exception: return '127.0.0.1'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_local_host_ip(self) -> str:", "def get_local_ip():\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.connect((\"8.8.8.8\", 80))\n local_ip = sock.getsockname()[0]\n sock.close()\n\n return local_ip", "def getLocalIpAddress() :\n \n if (platform.system() == 'Linux') :...
[ "0.8890761", "0.86365914", "0.85778904", "0.846305", "0.84425664", "0.8404775", "0.8378487", "0.8368668", "0.8304376", "0.8284258", "0.80766225", "0.806916", "0.8051856", "0.79896796", "0.79758286", "0.79521865", "0.79032815", "0.78887117", "0.78794074", "0.7868217", "0.78568...
0.74135506
47
get global ip address
def get_global_ip(): network_info_providers = [ 'http://api.ipify.org/', 'http://myip.dnsomatic.com', 'http://inet-ip.info/ip', 'http://v4.ident.me/', ] random.shuffle(network_info_providers) for url in network_info_providers: try: return requests.get(url).text.lstrip().rstrip() except Exception: continue else: log.info('cannot find global ip') return ""
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_global_ip() -> str:\n return urllib.request.urlopen(\"https://icanhazip.com\").read().decode().strip()", "def get_ip(self):", "def get_host_ip_addr():\n return nova_conf.my_ip", "def get_local_host_ip(self) -> str:", "def get_IP(): \n \n return socket.gethostbyname(socket.gethostn...
[ "0.8177861", "0.78713524", "0.7836615", "0.7808784", "0.7742288", "0.7727455", "0.7672631", "0.76301765", "0.7592437", "0.7556169", "0.7501851", "0.749981", "0.74838996", "0.7455439", "0.7448763", "0.7436739", "0.74339193", "0.74294287", "0.7428558", "0.73813033", "0.73690134...
0.82571846
0
get global ipv6 address
def get_global_ip_ipv6(): network_info_providers = [ 'http://v6.ipv6-test.com/api/myip.php', 'http://v6.ident.me/', ] random.shuffle(network_info_providers) for url in network_info_providers: try: return requests.get(url).text.lstrip().rstrip() except Exception: continue else: log.info('cannot find global ipv6 ip') return ""
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_main_ipv6():\n try:\n # No data is actually transmitted (UDP)\n s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)\n s.connect( ('2001:4860:4860::8888', 53) )\n real_ip = s.getsockname()[0]\n s.close()\n return real_ip\n except socket.error as e:\n logging.error(\"Cannot retrieve ...
[ "0.8276269", "0.82484275", "0.7695294", "0.7630343", "0.7439502", "0.7352564", "0.7306042", "0.7292912", "0.72007406", "0.7183485", "0.71534765", "0.71408135", "0.7075447", "0.7072936", "0.7067728", "0.700647", "0.6943251", "0.6901189", "0.68371254", "0.68331796", "0.6820401"...
0.8327801
0
The column labels of the DataFrame. Returns orca.Index The column labels of each column.
def columns(self): return self._columns # return Index(self._data_columns)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def labels(self):\n \n return self.column_labels", "def column_labels(self):\n return tuple(self._columns.keys())", "def get_labels(self) -> {int: str}:\n return {x: col.label for x, col in self._cols.items()}", "def get_label_indices(df: DataFrame, labels: list):\n return [idx...
[ "0.7897917", "0.76980937", "0.7478725", "0.69867", "0.6826641", "0.68240386", "0.6750179", "0.6732042", "0.6705691", "0.66914195", "0.6630234", "0.65252477", "0.6519194", "0.64722145", "0.6469839", "0.64630276", "0.6462272", "0.6409666", "0.6367081", "0.63438576", "0.62805796...
0.6088458
41
Return an int representing the number of axes / array dimensions. Returns int Return 1 if Series. Otherwise return 2 if DataFrame.
def ndim(self): return 2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def size(self)->int:\n\n return np.prod([axes if is_integer(axes) else len(axes) for axes in self._dim_axes])", "def count_dims(da):\n return len(da.dims)", "def get_num_dimensions(self):\n dimensions = self.data.shape\n return dimensions[1]", "def _get_ndim(self):\n return len...
[ "0.788396", "0.7611212", "0.7602772", "0.7502887", "0.74729747", "0.7424244", "0.7378051", "0.7378051", "0.73681766", "0.7364678", "0.7358198", "0.73216796", "0.7290911", "0.7280701", "0.726153", "0.7236144", "0.7176368", "0.71549875", "0.71549875", "0.71549875", "0.71549875"...
0.6780645
56
Implementation of binary operator between DataFrames on different indices. A new DataFrame representing an inmemory DolphinDB table is returned. It is garenteed that both DataFrames have no where_expr.
def _binary_op_on_different_indices(self, other, func, axis): # TODO: add axis check def merge_columns(self_columns, other_columns): """ Align the input columns, filling the missing columns with None -------- Examples -------- >>> merge_columns( ... ["a", "b", "ba", "d", "f"], ... ["e", "c", "d", "g", "ga", "a"] ... ) (('a','a'),('b',None),('ba',None),(None,c),('d','d'),(None,'e'),('f',None),(None,'g'),(None,'ga')) """ sorted_self_columns, sorted_other_columns = sorted(self_columns), sorted(other_columns) self_idx = other_idx = 0 self_len, other_len = len(self_columns), len(other_columns) while self_idx < self_len and other_idx < other_len: curr_self_column, curr_other_column = sorted_self_columns[self_idx], sorted_other_columns[other_idx] if curr_self_column == curr_other_column: yield curr_self_column, curr_other_column self_idx += 1 other_idx += 1 elif curr_self_column < curr_other_column: yield curr_self_column, None self_idx += 1 else: yield None, curr_other_column other_idx += 1 while self_idx < self_len: yield sorted_self_columns[self_idx], None self_idx += 1 while other_idx < other_len: yield None, sorted_other_columns[other_idx] other_idx += 1 assert isinstance(self, _Frame) assert isinstance(other, _Frame) if ((not self._in_memory and len(self._index_columns) == 0) or (not other._in_memory and len(other._index_columns) == 0)): raise ValueError("Frame has no default index if it is not in memory") session = self._session self_var_name, other_var_name = self._var_name, other._var_name if other._is_dataframe_like: self_data_columns = self._data_columns other_data_columns = other._data_columns index_list, from_clause = _generate_joiner( self_var_name, other_var_name, self._index_columns, other._index_columns) if self_data_columns == other_data_columns: select_list = (f"{func}({self_var_name}.{c}, {other_var_name}.{c}) as {c}" for c in self_data_columns) data_columns = self_data_columns else: merged_columns = list(merge_columns(self_data_columns, other_data_columns)) select_list = (f"00f as {s if o is None else o}" if s is None or o is None else f"{func}({self_var_name}.{s}, {other_var_name}.{s}) as {s}" for s, o in merged_columns) data_columns = [s if o is None else o for s, o in merged_columns] select_list = itertools.chain(index_list, select_list) script = sql_select(select_list, from_clause) elif other._is_series_like: self_data_columns = self._data_columns other_data_column = other._data_columns[0] index_list, from_clause = _generate_joiner( self._var_name, other._var_name, self._index_columns, other._index_columns) select_list = (f"{func}({self_var_name}.{c}, {other_var_name}.{other_data_column}) as {c}" for c in self_data_columns) data_columns = self_data_columns select_list = itertools.chain(index_list, select_list) script = sql_select(select_list, from_clause) return self._get_from_script( session, script, data_columns=data_columns, index_map=self._index_map, index=self._index)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def where(self, cond, other, **kwargs): # noqa: PR02\n return DataFrameDefault.register(pandas.DataFrame.where)(\n self, cond=cond, other=other, **kwargs\n )", "def union_all(x: DataFrame, y: DataFrame) -> DataFrame:\n _check_xy(x, y)\n return bind_rows(x, y, __calling_env=Calling...
[ "0.5993737", "0.59794873", "0.5897485", "0.5851102", "0.5847667", "0.58340734", "0.57924235", "0.5676979", "0.564678", "0.56334287", "0.54969245", "0.5460089", "0.5447747", "0.544339", "0.5425218", "0.5419818", "0.5405718", "0.5401967", "0.53926265", "0.5366445", "0.5351063",...
0.6160066
0
Align the input columns, filling the missing columns with None Examples >>> merge_columns( ... ["a", "b", "ba", "d", "f"], ... ["e", "c", "d", "g", "ga", "a"] ... ) (('a','a'),('b',None),('ba',None),(None,c),('d','d'),(None,'e'),('f',None),(None,'g'),(None,'ga'))
def merge_columns(self_columns, other_columns): sorted_self_columns, sorted_other_columns = sorted(self_columns), sorted(other_columns) self_idx = other_idx = 0 self_len, other_len = len(self_columns), len(other_columns) while self_idx < self_len and other_idx < other_len: curr_self_column, curr_other_column = sorted_self_columns[self_idx], sorted_other_columns[other_idx] if curr_self_column == curr_other_column: yield curr_self_column, curr_other_column self_idx += 1 other_idx += 1 elif curr_self_column < curr_other_column: yield curr_self_column, None self_idx += 1 else: yield None, curr_other_column other_idx += 1 while self_idx < self_len: yield sorted_self_columns[self_idx], None self_idx += 1 while other_idx < other_len: yield None, sorted_other_columns[other_idx] other_idx += 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def combine_columns(allowed_columns):\n\n v_columns = [v for v in allowed_columns if v in df.columns]\n v_columns.sort()\n for i in range(1, len(v_columns)):\n df[v_columns[0]] = df[v_columns[0]].fillna(df[v_columns[i]])\n df.drop(v_columns[i], 1, inplace=True)\n return v_columns[0]", "def merge_column...
[ "0.6452826", "0.59999216", "0.5639353", "0.53557676", "0.5288406", "0.51761496", "0.50632006", "0.5041874", "0.5031121", "0.49720797", "0.49664128", "0.49384537", "0.49003986", "0.4899783", "0.48729792", "0.4778065", "0.47356743", "0.47148484", "0.46847248", "0.4650927", "0.4...
0.5532568
3
r""" Write object to a commaseparated values (csv) file.
def to_csv( self, path_or_buf=None, sep=",", na_rep="", float_format=None, columns=None, header=True, index=True, index_label=None, mode="w", encoding=None, compression="infer", quoting=None, quotechar='"', line_terminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal=".", engine="dolphindb", append=False, ): if engine == "pandas": df = self.to_pandas() from pandas.io.formats.csvs import CSVFormatter formatter = CSVFormatter( df, path_or_buf, line_terminator=line_terminator, sep=sep, encoding=encoding, compression=compression, quoting=quoting, na_rep=na_rep, float_format=float_format, cols=columns, header=header, index=index, index_label=index_label, mode=mode, chunksize=chunksize, quotechar=quotechar, date_format=date_format, doublequote=doublequote, escapechar=escapechar, decimal=decimal, ) formatter.save() if path_or_buf is None: return formatter.path_or_buf.getvalue() elif engine == "dolphindb": append = 'true' if append else 'false' self_script = self._to_script(ignore_index=True) script = f"saveText({self_script},'{path_or_buf}', '{sep}', {append})" self._session.run(script) else: raise ValueError("Unsupport type engine " + engine) return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_to_csv(self):\r\n # Save the read values to a csv file\r\n with open(self.fname, \"a\") as f:\r\n wr = csv.writer(f, dialect='excel')\r\n wr.writerow([self.set_time, self.read_time_P_ac, self.read_time_P_bat,\r\n self.soc0, self.set_val, self.P_a...
[ "0.7310468", "0.7034704", "0.6893769", "0.6833797", "0.68261456", "0.6813147", "0.67906994", "0.6789112", "0.6752092", "0.67305475", "0.6667265", "0.6658432", "0.66504896", "0.66496783", "0.6628684", "0.66130286", "0.66057646", "0.65871006", "0.6575944", "0.65313613", "0.6530...
0.0
-1
Find the stack frame of the caller so that we can note the source file name, line number and function name.
def file_descriptor(self): f = frame() # On some versions of IronPython, currentframe() returns None if # IronPython isn't run with -X:Frames. if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)" while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename).capitalize() if filename == _srcfile: f = f.f_back continue rv = (co.co_filename, f.f_lineno, co.co_name) break self.line = "{0}:{2}[{1}]".format(*rv)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _findCaller(stack_info=False):\n f = logging.currentframe()\n #On some versions of IronPython, currentframe() returns None if\n #IronPython isn't run with -X:Frames.\n if f is not None:\n f = f.f_back\n rv = \"(unknown file)\", 0, \"(unknown function)\", None\n while hasattr(f, \"f_cod...
[ "0.79303205", "0.7862949", "0.77929926", "0.77833045", "0.7717962", "0.7654662", "0.75871235", "0.75725806", "0.749834", "0.7496779", "0.74145174", "0.73589015", "0.7355899", "0.7281678", "0.72635937", "0.72341293", "0.7191653", "0.71636987", "0.7156922", "0.7154463", "0.7148...
0.0
-1
Open a window to compose an email, with the edi invoice dian template message loaded by default
def action_invoice_dian_resend(self): self.ensure_one() template = self.env.ref('l10n_co_e-invoice.email_template_edi_invoice_dian', False) compose_form = self.env.ref('mail.email_compose_message_wizard_form', False) ctx = dict( default_model='account.invoice', default_res_id=self.id, default_use_template=bool(template), default_template_id=template and template.id or False, default_composition_mode='comment', mark_invoice_as_sent=True, ) return { 'name': _('Compose Email'), 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'mail.compose.message', 'views': [(compose_form.id, 'form')], 'view_id': compose_form.id, 'target': 'new', 'context': ctx, }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def send_by_email(self):\r\n ir_model_data = self.env['ir.model.data']\r\n try:\r\n template_id = ir_model_data.get_object_reference(\r\n 'ng_church', 'email_template_church_pledge_report')[1]\r\n except ValueError:\r\n template_id = False\r\n try:\r...
[ "0.73784035", "0.647709", "0.6436048", "0.6249949", "0.6230297", "0.61297333", "0.60587174", "0.59738946", "0.5970479", "0.59629035", "0.57741827", "0.5760959", "0.5647457", "0.5546402", "0.55030817", "0.5446904", "0.53914595", "0.536303", "0.5356848", "0.5346636", "0.5345804...
0.6925168
1
spark up an instance
def __init__(self): self.stats = {} self.stats['hits'] = 0 self.stats['operations'] = {} self.stats['operations']['GetCapabilities'] = {} self.stats['operations']['GetCapabilities']['hits'] = 0 self.stats['operations']['POST'] = {} self.stats['operations']['POST']['hits'] = 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n spark_it_up()", "def spark(self, *args, **kwargs):\n self.spark_submit(*args, **kwargs)", "def up(\n context,\n user=get_local_user(),\n remote=False,\n instance=None,\n stack=None,\n services=None,\n):\n command = \"up --build\"\n\n if remote:\n command =...
[ "0.7255347", "0.58859587", "0.578518", "0.57325435", "0.57292104", "0.5720284", "0.56871897", "0.5679635", "0.5546256", "0.54448164", "0.5438893", "0.5424962", "0.541132", "0.54103553", "0.53980225", "0.5390525", "0.53686017", "0.5367046", "0.53380203", "0.5331934", "0.528623...
0.0
-1
spark up an instance
def __init__(self): OWSReport.__init__(self) self.stats['type'] = 'OGC:WMS' self.stats['operations']['GetMap'] = {} self.stats['operations']['GetMap']['hits'] = 0 self.stats['operations']['GetMap']['resource'] = {} self.stats['operations']['GetMap']['resource']['param'] = 'layers' self.stats['operations']['GetMap']['resource']['list'] = {} self.stats['operations']['GetFeatureInfo'] = {} self.stats['operations']['GetFeatureInfo']['hits'] = 0 self.stats['operations']['GetLegendGraphic'] = {} self.stats['operations']['GetLegendGraphic']['hits'] = 0 self.stats['operations']['GetStyles'] = {} self.stats['operations']['GetStyles']['hits'] = 0 self.stats['operations']['DescribeLayer'] = {} self.stats['operations']['DescribeLayer']['hits'] = 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n spark_it_up()", "def spark(self, *args, **kwargs):\n self.spark_submit(*args, **kwargs)", "def up(\n context,\n user=get_local_user(),\n remote=False,\n instance=None,\n stack=None,\n services=None,\n):\n command = \"up --build\"\n\n if remote:\n command =...
[ "0.7255299", "0.5885112", "0.57854474", "0.5732422", "0.5728568", "0.57188094", "0.5686993", "0.56795335", "0.55460984", "0.54442745", "0.54389185", "0.54236734", "0.5411601", "0.5410782", "0.539766", "0.53900146", "0.5368531", "0.53666943", "0.53366995", "0.53314143", "0.528...
0.0
-1
spark up an instance
def __init__(self): OWSReport.__init__(self) self.stats['type'] = 'OGC:WFS' self.stats['operations']['GetFeature'] = {} self.stats['operations']['GetFeature']['hits'] = 0 self.stats['operations']['GetFeature']['resource'] = {} self.stats['operations']['GetFeature']['resource']['param'] = 'typename' self.stats['operations']['GetFeature']['resource']['list'] = {} self.stats['operations']['DescribeFeatureType'] = {} self.stats['operations']['DescribeFeatureType']['hits'] = 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n spark_it_up()", "def spark(self, *args, **kwargs):\n self.spark_submit(*args, **kwargs)", "def up(\n context,\n user=get_local_user(),\n remote=False,\n instance=None,\n stack=None,\n services=None,\n):\n command = \"up --build\"\n\n if remote:\n command =...
[ "0.7255299", "0.5885112", "0.57854474", "0.5732422", "0.5728568", "0.57188094", "0.5686993", "0.56795335", "0.55460984", "0.54442745", "0.54389185", "0.54236734", "0.5411601", "0.5410782", "0.539766", "0.53900146", "0.5368531", "0.53666943", "0.53366995", "0.53314143", "0.528...
0.0
-1
spark up an instance
def __init__(self): OWSReport.__init__(self) self.stats['type'] = 'OGC:WCS' self.stats['operations']['GetCoverage'] = {} self.stats['operations']['GetCoverage']['hits'] = 0 self.stats['operations']['GetCoverage']['resource'] = {} self.stats['operations']['GetCoverage']['resource']['param'] = 'coverage' self.stats['operations']['GetCoverage']['resource']['list'] = {} self.stats['operations']['DescribeCoverage'] = {} self.stats['operations']['DescribeCoverage']['hits'] = 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n spark_it_up()", "def spark(self, *args, **kwargs):\n self.spark_submit(*args, **kwargs)", "def up(\n context,\n user=get_local_user(),\n remote=False,\n instance=None,\n stack=None,\n services=None,\n):\n command = \"up --build\"\n\n if remote:\n command =...
[ "0.7255299", "0.5885112", "0.57854474", "0.5732422", "0.5728568", "0.57188094", "0.5686993", "0.56795335", "0.55460984", "0.54442745", "0.54389185", "0.54236734", "0.5411601", "0.5410782", "0.539766", "0.53900146", "0.5368531", "0.53666943", "0.53366995", "0.53314143", "0.528...
0.0
-1
spark up an instance
def __init__(self): OWSReport.__init__(self) self.stats['type'] = 'OGC:SOS' self.stats['operations']['GetObservation'] = {} self.stats['operations']['GetObservation']['hits'] = 0 self.stats['operations']['GetObservation']['resource'] = {} self.stats['operations']['GetObservation']['resource']['param'] = 'observedproperty' self.stats['operations']['GetObservation']['resource']['list'] = {} self.stats['operations']['DescribeSensor'] = {} self.stats['operations']['DescribeSensor']['hits'] = 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main():\n spark_it_up()", "def spark(self, *args, **kwargs):\n self.spark_submit(*args, **kwargs)", "def up(\n context,\n user=get_local_user(),\n remote=False,\n instance=None,\n stack=None,\n services=None,\n):\n command = \"up --build\"\n\n if remote:\n command =...
[ "0.7255347", "0.58859587", "0.578518", "0.57325435", "0.57292104", "0.5720284", "0.56871897", "0.5679635", "0.5546256", "0.54448164", "0.5438893", "0.5424962", "0.541132", "0.54103553", "0.53980225", "0.5390525", "0.53686017", "0.5367046", "0.53380203", "0.5331934", "0.528623...
0.0
-1
Estimate covariance matrix with POET algorithm
def poet_known(self, K, tau): # check K and tau if K < 0 or K >= self.N: raise RuntimeError("Invalid value for K, number of factors.") if tau < 0 or tau > 1: raise RuntimeError("Invalid value for tau, which should be between 0 and 1.") # mean centering and calculate SVD for pca Rc = self.R.T - np.mean(self.R, axis=1) u, s, vt = np.linalg.svd(Rc/np.sqrt(self.T-1)) eigvecs = vt.T eigvals = s**2 # decomposition of covariance matrix cov_pca = eigvecs[:,:K] @ np.diag(eigvals[:K]) @ eigvecs[:,:K].T Rk = self.cov - cov_pca # thresholding the complement matrix rii = np.diag(Rk) tauij = np.sqrt(np.outer(rii, rii))*tau RkT = Rk*(Rk > tauij) # combine the two terms result = cov_pca + RkT return result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _mn_cov_ ( self , size = -1 , root = False ) :\n #\n if size <= 0 : size = len ( self )\n size = min ( size , len ( self ) ) \n #\n from array import array\n matrix = array ( 'd' , [ 0 for i in range(0, size * size) ] )\n self.mnemat ( matrix , size )\n #\n import ostap.math.linalg\...
[ "0.7217029", "0.7027655", "0.6832015", "0.67822325", "0.66628355", "0.6503905", "0.6372194", "0.6335945", "0.63327277", "0.6318015", "0.6316783", "0.6251822", "0.62356293", "0.6194071", "0.6187514", "0.6178875", "0.615046", "0.6149075", "0.6138903", "0.61331916", "0.61278504"...
0.0
-1
greedily select boxes with high confidence and overlap with current maximum = thresh
def nms_mxnet(self, boxes, scores, thresh): x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] #scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return keep
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def apply_non_max_suppression(boxes, scores, iou_thresh=.45, top_k=200):\n\n selected_indices = np.zeros(shape=len(scores))\n if boxes is None or len(boxes) == 0:\n return selected_indices\n x_min = boxes[:, 0]\n y_min = boxes[:, 1]\n x_max = boxes[:, 2]\n y_max = boxes[:, 3]\n areas = ...
[ "0.7311329", "0.7284363", "0.7052062", "0.69620794", "0.6808659", "0.67591953", "0.67545897", "0.6637153", "0.6572565", "0.6438189", "0.6292309", "0.6280824", "0.6277976", "0.62647426", "0.6221004", "0.6205099", "0.6132621", "0.61210424", "0.6105146", "0.6104222", "0.60812354...
0.0
-1
Fill a dataframe row with the others
def filldf(df, response, sorted_selection, params_selection, constant=True, verbose=True): selections_iter = iter(sorted_selection) params_iter = iter(params_selection) idxmissing = df[response][df[response].isnull() == True].index # slect where their is missing data print("Filling .... ") while len(idxmissing) > 0: print("Their is [" + str(len(idxmissing)) + "] events missing") try: # Try if their is still other stations to fill with selection = next(selections_iter) param = next(params_iter) except StopIteration: print("NO MORE SELECTED STATIONS") break try: Y = df.loc[:, response] X1 = df.loc[:, selection[0]] X2 = df.loc[:, selection[1]] select = pd.concat([X1, X2], keys=['X1', 'X2'], axis=1, join='inner').dropna() if constant: newdata = param[0] + param[1] * select['X1'] + param[2] * select['X2'] # reconstruct the data else: newdata = param[0] * select['X1'] + param[1] * select['X2'] # reconstruct the data df.loc[idxmissing, response] = newdata.loc[idxmissing] idxmissing = df[response][df[response].isnull() == True].index # slect where their is missing data except KeyError: if verbose: print('Selected stations ' + str(selection) + 'did not fill any events') else: pass except ValueError: if verbose: print('The variable ' + var + "Does not exist or no data to do the multilinear regression ") else: pass return df.loc[:, response]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_row(df, row):\n df.loc[df.shape[0]] = row", "def augment_dataframe(self, df: pd.DataFrame) -> pd.DataFrame:", "def fill_row(row, x):\n row.append(x)\n return row", "def insert_row(self, row_value, index):\n row = pd.DataFrame(row_value, columns=['lat', 'long', 'alt', 'descr'])\n ...
[ "0.65674084", "0.64855564", "0.64138365", "0.61660343", "0.6115377", "0.5761364", "0.5706634", "0.57038164", "0.56266713", "0.56095374", "0.5561263", "0.5560726", "0.55440325", "0.55188113", "0.5499481", "0.54974097", "0.5496469", "0.54918057", "0.549143", "0.54893225", "0.54...
0.0
-1
Get preditors base on their distance The predictors are selected as following [1,2], [1,3], [1,4], [2,3], [2,4], [2,5], [2,6]
def getpredictors_distance( staname, distance): distfromsta = distance[staname] try: del distfromsta[staname] # remove the station to be fill from the dataframe except: pass distfromsta = distfromsta.sort_values() stations = distfromsta.index sel1 = [(i, e) for i, e in zip(stations[0:-1], stations[1:])] # selction predictors with spacing 1 sel2 = [(i, e) for i, e in zip(stations[0:-2], stations[2:])] # selction predictors with spacing 2 selection= [None] * (len(sel1) + len(sel2)) selection[::2] = sel1 selection[1::2] = sel2 return selection[:4]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __getpredictors_distance(self, staname, distance):\n\n distfromsta = distance[staname]\n del distfromsta[staname] # remove the station to be fill from the dataframe\n distfromsta = distfromsta.sort_values()\n\n stations = self.network.getsta(distfromsta.index.values)\n # ...
[ "0.63841313", "0.59920394", "0.5903511", "0.5846713", "0.5797452", "0.5794031", "0.5764465", "0.57157874", "0.57146764", "0.571108", "0.5700389", "0.56553006", "0.5652828", "0.5636438", "0.56238115", "0.5598508", "0.55349874", "0.55291295", "0.55164886", "0.5492974", "0.54692...
0.6556841
0
DESCRIPTION Check every variable of every stations and try to fill them with the variables of the two nearest station for every time. INPUT
def fillstation(self, stanames, all=None, plot=None, summary=None, From=None, To=None, by=None, how='mean', variables=None, distance=None, sort_cor=True, constant=True, cor_lim=None): if all == True: stations = self.network.getsta([], all=True).values() else: stations = self.network.getsta(stanames) for station in stations: staname = station.getpara('stanames') if variables == None: newdataframe = station.getData(reindex=True, From=From, To=To, by=by, how=how) # Dataframe which stock the new data of the stations newdataframe['U m/s'] = station.getData('U m/s', reindex=True, From=From, To=To, by=by, how=how) newdataframe['V m/s'] = station.getData('V m/s', reindex=True, From=From, To=To, by=by, how=how) newdataframe['Ua g/kg'] = station.getData('Ua g/kg', reindex=True, From=From, To=To, by=by, how=how) newdataframe['Theta C'] = station.getData('Theta C', reindex=True, From=From, To=To, by=by, how=how) variables_name = newdataframe.columns else: newdataframe = station.getData(var=variables, reindex=True, From=From, To=To, by=by, how=how) # Dataframe which stock the new data of the stations variables_name = variables # select and sort nearest stations selections, selectionsnames = self.__getpredictors_distance(staname, distance) for var in variables_name: print("I" * 30) print("variable -> " + var) try: selections, params = self.__sort_predictors_by_corr(station, selections, var, From, To, by, how, constant=constant, selectionsnames=selectionsnames, sort_cor=sort_cor, cor_lim=cor_lim) selections_iter = iter(selections) params_iter = iter(params) # print newdataframe idxmissing = newdataframe[var][ newdataframe[var].isnull() == True].index # slect where their is missing data while len(idxmissing) > 0: print("Their is [" + str(len(idxmissing)) + "] events missing") try: # Try if their is still other stations to fill with selection = selections_iter.next() param = params_iter.next() except StopIteration: print("NO MORE SELECTED STATIONS") break try: Y = station.getData(var, From=From, To=To, by=by, how=how) # variable to be filled X1 = selection[0].getData(var, From=From, To=To, by=by, how=how) # stations variable used to fill X2 = selection[1].getData(var, From=From, To=To, by=by, how=how) # stations variable used to fill select = pd.concat([X1, X2], keys=['X1', 'X2'], axis=1, join='inner').dropna() if constant: newdata = param[0] + param[1] * select['X1'] + param[2] * select[ 'X2'] # reconstruct the data else: newdata = param[0] * select['X1'] + param[1] * select['X2'] # reconstruct the data newdataframe.loc[idxmissing, var] = newdata.loc[idxmissing, var] idxmissing = newdataframe[var][ newdataframe[var].isnull() == True].index # slect where their is missing data except KeyError: print("&" * 60) print('Selected stations did not fill any events') except ValueError: print('The variable ' + var + "Does not exist or no data to do the multilinear regression ") if plot == True: df = pd.concat([Y, X1, X2, newdata, newdataframe[var]], keys=['Y', 'X1', 'X2', 'estimated data', 'Estimated replaced'], axis=1, join='outer') self.plotcomparison(df) print("Their is [" + str(len(idxmissing)) + "] FINALLY events missing") # Recalculate the wind direction and speed from the U an V components try: speed, dir = cart2pol(newdataframe['U m/s'], newdataframe['V m/s']) newdataframe['Dm G'] = dir newdataframe['Sm m/s'] = speed except ValueError: print 'No wind found in the dataframe' except KeyError: print('No wind found in the dataframe') self.newdataframes[staname] = newdataframe
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_nearest(self):\n dist = station.nearest(28.43, -81.31)\n stn = dist.pop(\"station\")\n self.assertIsInstance(stn, station.Station)\n self.assertEqual(stn.icao, \"KMCO\")\n for val in dist.values():\n self.assertIsInstance(val, float)\n for *params, coun...
[ "0.6480234", "0.6318352", "0.6269479", "0.6215623", "0.6206157", "0.6110717", "0.60025865", "0.5942108", "0.5934246", "0.5904729", "0.5811288", "0.5711787", "0.57106215", "0.56911725", "0.5684194", "0.5649491", "0.5626808", "0.56212485", "0.55674076", "0.5553363", "0.5552577"...
0.6406745
1
DESCRIPTION Write the bootstraped in a file
def WriteDataFrames(self, Outpath): newdataframes = self.newdataframes for staname in newdataframes.keys(): fname = staname + '.TXT' newdataframes[staname].to_csv(Outpath + fname, float_format="%.2f") print('--------------------') print('Writing dataframe') print('--------------------')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def write_bootstrap(self):\n\n for line in Bootstrap.BOOTSTRAP:\n self.write_line(line)\n\n self.write_call(\"Sys.init\", 0)", "def write_bootstrap(output_file, curr_function):\n # initialize stack\n output_file.write(\"@256\" + \"\\n\" +\n \"D = A\" + \"\\n\" ...
[ "0.71933657", "0.68223804", "0.6309295", "0.62452126", "0.6161541", "0.6161541", "0.60435784", "0.60038215", "0.59648716", "0.5935721", "0.5925566", "0.58335197", "0.5824003", "0.58197004", "0.58056873", "0.58021903", "0.5799778", "0.57911575", "0.57786596", "0.57492787", "0....
0.0
-1
Get preditors base on their distance The predictors are selected as following [1,2], [1,3], [1,4], [2,3], [2,4], [2,5], [2,6]
def __getpredictors_distance(self, staname, distance): distfromsta = distance[staname] del distfromsta[staname] # remove the station to be fill from the dataframe distfromsta = distfromsta.sort_values() stations = self.network.getsta(distfromsta.index.values) # station = self.network.getsta(staname) # Only 3 closest stations # sel1 = [ (i,e) for i,e in zip(stations[0:2], stations[1:3])] # selction predictors with spacing 1 # sel2 = [ (i,e) for i,e in zip(stations[0:2], stations[2:4])] # selction predictors with spacing 2 # Use all stations sel1 = [(i, e) for i, e in zip(stations[0:-1], stations[1:])] # selction predictors with spacing 1 sel2 = [(i, e) for i, e in zip(stations[0:-2], stations[2:])] # selction predictors with spacing 2 # sel3 = [ (i,e) for i,e in zip(stations[0:-3], stations[3:])] # selction predictors with spacing 3 # sel4 = [ (i,e) for i,e in zip(stations[0:-4], stations[4:])] # selction predictors with spacing 4 # Only 3 closest stations # sel1names = [ (i.getpara('stanames'),e.getpara('stanames')) for i,e in zip(stations[0:2], stations[1:3])] # selction predictors with spacing 1 # sel2names = [ (i.getpara('stanames'),e.getpara('stanames')) for i,e in zip(stations[0:2], stations[2:4])] # selction predictors with spacing 1 # using all stations sel1names = [(i.getpara('stanames'), e.getpara('stanames')) for i, e in zip(stations[0:-1], stations[1:])] # selction predictors with spacing 1 sel2names = [(i.getpara('stanames'), e.getpara('stanames')) for i, e in zip(stations[0:-2], stations[2:])] # selction predictors with spacing 1 # sel3names = [ (i.getpara('stanames'),e.getpara('stanames')) for i,e in zip(stations[0:-3], stations[3:])] # selction predictors with spacing 1 # sel4names = [ (i.getpara('stanames'),e.getpara('stanames')) for i,e in zip(stations[0:-4], stations[4:])] # selction predictors with spacing 1 selection = [x for x in itertools.chain.from_iterable(itertools.izip_longest(sel1, sel2)) if x] selectionnames = [x for x in itertools.chain.from_iterable(itertools.izip_longest(sel1names, sel2names)) if x] return selection, selectionnames
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getpredictors_distance( staname, distance):\n\n distfromsta = distance[staname]\n try:\n del distfromsta[staname] # remove the station to be fill from the dataframe\n except:\n pass\n distfromsta = distfromsta.sort_values()\n\n stations = distfromsta.index\n\n sel1 = [(i, e) fo...
[ "0.65554714", "0.59923244", "0.5906513", "0.5849182", "0.5799373", "0.5795326", "0.5768941", "0.5718649", "0.57175404", "0.5713419", "0.5701458", "0.5656988", "0.5656353", "0.56391543", "0.562515", "0.56004006", "0.553719", "0.5531781", "0.55137074", "0.5489938", "0.5472367",...
0.63834083
1
Return a sorted selections by the correlation rsquared scores
def __sort_predictors_by_corr(self, station, selections, var, From, To, by, how, constant=True, selectionsnames=None, sort_cor=True, cor_lim=None): scores_corel = pd.DataFrame(index=np.arange(0, len(selections)), columns=['corel', 'selections', 'params', 'selectionname']) # correlation of each selections and variables for i, (selection, selectionname) in enumerate(zip(selections, selectionsnames)): try: Y = station.getData(var, From=From, To=To, by=by, how=how) # variable to be filled X1 = selection[0].getData(var, From=From, To=To, by=by, how=how) # stations variable used to fill X2 = selection[1].getData(var, From=From, To=To, by=by, how=how) # stations variable used to fill data = pd.concat([Y, X1, X2], keys=['Y', 'X1', 'X2'], axis=1, join='outer').dropna() est = self.__MLR(data[['X1', 'X2']], data['Y'], constant=constant) rsquared = est.rsquared scores_corel.loc[i, 'corel'] = rsquared scores_corel.loc[i, 'selections'] = selection scores_corel.loc[i, 'selectionname'] = selectionname if constant: scores_corel.loc[i, 'params'] = [est.params[0], est.params[1], est.params[2]] else: scores_corel.loc[i, 'params'] = [est.params[0], est.params[1]] except ValueError: print('No data to do the multilinear regression. Put correlation = 0') scores_corel.loc[i, 'selections'] = selection scores_corel.loc[i, 'selectionname'] = selectionname scores_corel.loc[i, 'corel'] = 0 scores_corel.loc[i, 'params'] = np.nan if sort_cor: scores_corel = scores_corel.sort_values('corel', ascending=False) if cor_lim: scores_corel = scores_corel[scores_corel['corel'] > cor_lim] else: scores_corel = scores_corel[scores_corel['corel'] > 0] scores_corel.index = np.arange(0, len(scores_corel.index)) selections = scores_corel['selections'].values params = scores_corel['params'].values print("u" * 30) print("Correlation coefficient of the multilinear regression") print("u" * 30) print(scores_corel[['corel', 'selectionname']]) print("u" * 30) return selections, params
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def corr_list(self):\n c = self.df.corr().abs()\n s = c.unstack()\n so = s.sort_values(ascending=False)\n i = int(len(so) ** (1/2))\n charts = so[i:]\n charts = charts[::2]\n if len(charts) > 3:\n charts = charts[:3]\n return charts.index, charts.v...
[ "0.5838652", "0.55438906", "0.5539825", "0.5511799", "0.5483375", "0.54549277", "0.54273504", "0.5422278", "0.5394091", "0.536099", "0.53258604", "0.53121966", "0.5309838", "0.5289699", "0.52868915", "0.5261606", "0.5250422", "0.52314734", "0.5225502", "0.5213998", "0.5203932...
0.62526226
0
Gets a remote file of a bucket using a connection
def _get(conn, remote_file, bucket_name=BUCKET_NAME): contents = None try: reply = conn.get(bucket_name, remote_file) contents = reply.body if reply.http_response.status != 200: print 'Failed to fetch current_remote metadata' contents = None except: contents = None return contents
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def s3_get(url, temp_file):\n s3_resource = boto3.resource(\"s3\")\n bucket_name, s3_path = split_s3_path(url)\n s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)", "def s3_get(url, temp_file):\n s3_resource = boto3.resource(\"s3\")\n bucket_name, s3_path = split_s3_path(url)\n ...
[ "0.68474334", "0.68474334", "0.6793478", "0.6766179", "0.6609071", "0.6568017", "0.6541442", "0.6517729", "0.6445589", "0.64432293", "0.64367956", "0.6386914", "0.6360486", "0.630485", "0.62856895", "0.62814856", "0.62789845", "0.62708944", "0.62665856", "0.62540734", "0.6238...
0.7393641
0
Put some contents into a remote_file of a bucket usign connection conn. Optionally the headers can be specified.
def _put(conn, remote_file, contents, bucket_name=BUCKET_NAME, headers=None): error_msg = 'Failed to upload to %s' % remote_file try: reply = conn.put(bucket_name, remote_file, S3.S3Object(contents), headers) if reply.http_response.status != 200: print error_msg except: print error_msg
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def upload_file(bucket, local_file_path, remote_destination_path):\n bucket = get_bucket(bucket)\n k = Key(bucket)\n k.key = remote_destination_path\n k.set_contents_from_filename(local_file_path)", "def upload_file(conn, filename_local, filename_s3, gzip=False):\n\n filename_s3 = filename_s3.lstr...
[ "0.6534801", "0.6233578", "0.6144909", "0.6129894", "0.5970255", "0.59591484", "0.59422994", "0.5909662", "0.5902494", "0.58096933", "0.57955354", "0.5794321", "0.57661766", "0.5737979", "0.57304716", "0.5720829", "0.5701128", "0.5676588", "0.56659216", "0.56574786", "0.56344...
0.7733097
0
Get headers for this type of file. Also, put the correct content encoding.
def _get_headers(content_type): headers = {'x-amz-acl': 'public-read', 'Content-Type': content_type, 'Cache-Control': 'public,max-age=31536000'} return headers
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_headers(self):\r\n raise NotImplementedError", "def set_headers(self, headers):\n self.headers = headers\n process_headers(self)\n self.character_encoding = self.parsed_headers.get(\n 'content-type', (None, {})\n )[1].get('charset', 'utf-8') # default isn't U...
[ "0.65006596", "0.6416231", "0.6409983", "0.62817407", "0.6232245", "0.61517215", "0.6136782", "0.61335945", "0.6095595", "0.60901326", "0.6061071", "0.6038231", "0.602917", "0.59930795", "0.5944638", "0.59071773", "0.5892869", "0.5888837", "0.58837026", "0.58729154", "0.58251...
0.59786826
14
Guess the content_type, by using its file descriptor
def _get_content_type(file_descriptor): content_type = mimetypes.guess_type(file_descriptor.name)[0] if not content_type: content_type = 'text/plain' return content_type
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_content_type(filename):\n return mimetypes.guess_type(filename)[0] or 'application/octet-stream'", "def guess_content_type ( self, path_info ) :\n _type, _enc = guess_type ( path_info )\n return _type", "def guess_content_type(filename):\n return mimetypes.guess_type(filename)[0...
[ "0.7407128", "0.74055415", "0.7343658", "0.7118253", "0.70626557", "0.7053132", "0.70111525", "0.6947122", "0.68888956", "0.68175477", "0.6781097", "0.67605287", "0.67187476", "0.6655244", "0.6640195", "0.66329396", "0.660614", "0.66005784", "0.65136355", "0.6447863", "0.6439...
0.7975829
0
Asserts if a given file (w/ name filename) can be compressed. content_type is optional and can speed up assertion. Should return True if it is a Text Type (CSS/JS)
def _file_can_be_compressed(filename): content_type = '' with open(filename, 'rb') as f: content_type = _get_content_type(f) return content_type in TEXT_TYPES
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def isgzip(filename):\n magic_number = b'\\x1f\\x8b\\x08'\n with open(filename, 'rb') as f:\n file_start = f.read(len(magic_number))\n\n if magic_number == file_start:\n return True\n return False", "def is_archive(afile):\n return file_ext(os.path.basename(afile)) in ARCHIVE_COMPRES...
[ "0.64723974", "0.64621985", "0.6352601", "0.6308476", "0.6298893", "0.62387055", "0.617346", "0.6168313", "0.613196", "0.6075621", "0.6057141", "0.6023388", "0.59639585", "0.59618855", "0.59406054", "0.5932078", "0.5916286", "0.5899778", "0.5892047", "0.5887669", "0.5869888",...
0.8202419
0
Compress the content string passed. Should be called when gzip is enabled to compress text types. There is no real advantage in using this with images, since most are already nicely compressed by some image processing algorithm.
def _compress_string(content): zbuf = StringIO() zfile = GzipFile(mode='wb', compresslevel=6, fileobj=zbuf) zfile.write(content) zfile.close() return zbuf.getvalue()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compress(string):", "def compress(string):", "def _compress_content(self, content):\n zbuf = io.BytesIO()\n zfile = gzip.GzipFile(mode=\"wb\", compresslevel=9, fileobj=zbuf)\n\n try:\n zfile.write(content.read())\n finally:\n zfile.close()\n\n conten...
[ "0.727991", "0.727991", "0.7271702", "0.7243655", "0.72023225", "0.7170906", "0.71320665", "0.6685947", "0.6557357", "0.64971095", "0.6466577", "0.63694817", "0.6278639", "0.624268", "0.6192079", "0.61507696", "0.6118266", "0.59070766", "0.57896465", "0.5700065", "0.5692797",...
0.7453164
0
Returns the sha metada of a local file
def _get_sha_metadata(filename): with open(filename) as f: return hashlib.sha1(f.read()).hexdigest()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_file_sha(full_path):\n in_file = open(full_path, 'rb')\n try:\n # Bug: why doesn't this use sha_func?\n sha_value = sha1()\n while True:\n bytes = in_file.read(READ_CHUNK_LEN)\n if bytes == \"\":\n break\n sha_value.update(bytes)\n ...
[ "0.7884196", "0.78605366", "0.7665543", "0.7652545", "0.76196074", "0.7603502", "0.75687635", "0.75554144", "0.75554144", "0.75550866", "0.754885", "0.7488408", "0.74789304", "0.746627", "0.7455596", "0.74492663", "0.74489915", "0.7430027", "0.7418533", "0.7417911", "0.741318...
0.7672078
2
Build the metadata local file with all sha information about files. File location is computed based on home kwargument.
def _build_local_metadata_file(files, home=''): filepaths = [os.path.join(home, f) for f in files] shas = [_get_sha_metadata(f) for f in filepaths] metadata = dict(zip(files, shas)) with open(LOCAL_METADATA_FILE, 'w') as f: f.write(json.dumps(metadata))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_metadata(self):\n self.metadata = {\n 'title': os.path.basename(self.source_file).rsplit('.', 1)[0],\n 'url': self.relative_destination_file,\n 'full_path': os.path.dirname(self.relative_destination_file),\n 'short_path': self.shorten_path(\n ...
[ "0.61526465", "0.6049966", "0.5853711", "0.5817837", "0.5641126", "0.5638058", "0.5613152", "0.5524916", "0.5511576", "0.5498614", "0.54815716", "0.54704076", "0.5461879", "0.5444722", "0.54036105", "0.53994805", "0.53729725", "0.5360554", "0.53537804", "0.53431183", "0.53139...
0.7596386
0
Uploads a file to S3 bucket. If gzip=True, compress and upload the gzipped version of the file instead of the original one. If gzip=True and it is not possible to compress, then quit the upload process (don't upload at all). So you should always pass the correct gzip info into this function, in order to get a upload.
def upload_file(conn, filename_local, filename_s3, gzip=False): filename_s3 = filename_s3.lstrip('./') file_descriptor = open(filename_local, 'rb') content = file_descriptor.read() content_type = _get_content_type(file_descriptor) headers = _get_headers(content_type) #should compress if the file is compressable and gzip is enabled can_be_gzipped = _file_can_be_compressed(filename_local) if gzip and can_be_gzipped: content = _compress_string(content) headers['Content-Length'] = str(len(content)) headers['Content-Encoding'] = 'gzip' extension = mimetypes.guess_extension(content_type) #we should not overwrite the original file in the server. #We change extensions: style.css --> style.gz.css, for instance filename_s3 = filename_s3.rstrip(extension) + '.gz' + extension #if gzip is enabled and it is not compressable, don't upload nothing at all elif gzip and not can_be_gzipped: return #upload print 'Uploading %s to %s' % (filename_local, filename_s3) _put(conn, filename_s3, content, headers=headers) file_descriptor.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def upload_file(file_obj, filename, session, samples_resource, log_to, metadata, tags):\n upload_args = {\n 'filename': filename,\n 'size': 1, # because we don't have the actually uploaded size yet b/c we're gziping it\n 'upload_type': 'standard' # This is multipart form data\n }\n ...
[ "0.695896", "0.68229353", "0.68038195", "0.6781243", "0.67778784", "0.6743604", "0.6743087", "0.67419064", "0.6726084", "0.67161316", "0.6695823", "0.6695823", "0.66937494", "0.66827035", "0.667724", "0.6662698", "0.66604984", "0.6652789", "0.66431695", "0.66219", "0.6605921"...
0.78993046
0
Returns a recursive list of all files inside folder. The list element is a string w/ file path relative to folder. If any file is found with the same name as LOCAL_METADATA_FILE, then do not append it to the list.
def _get_file_list(folder): tree = [x for x in os.walk(folder)] files = [os.path.join(t[0], y) for t in tree for y in t[2]] return [os.path.relpath(x, start=folder) for x in files if x != LOCAL_METADATA_FILE]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def files_in_folder(folder):\n files = []\n for f in glob.glob(folder):\n if os.path.isdir(f):\n files.extend(files_in_folder(f + os.sep + \"**\"))\n else:\n files.append(f)\n return files", "def ReadFolder(folder: str) -> List[str]:\n\n onlyfiles = [f for f in lis...
[ "0.66013783", "0.6589332", "0.6403268", "0.63590515", "0.6349886", "0.6340192", "0.6325134", "0.62352633", "0.61990255", "0.61880994", "0.618564", "0.61627126", "0.61410564", "0.6138895", "0.6138895", "0.6132723", "0.6122742", "0.610428", "0.60967124", "0.6089745", "0.6074586...
0.81068176
0
Fetches the metadata remote file REMOTE_METADATA_FILE and returns the metadata dict equivalent.
def _fetch_current_remote_metadata(conn): content = _get(conn, REMOTE_METADATA_FILE) metadata = json.loads(content) if content else {} return metadata
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get(conn, remote_file, bucket_name=BUCKET_NAME):\n contents = None\n try:\n reply = conn.get(bucket_name, remote_file)\n contents = reply.body\n if reply.http_response.status != 200:\n print 'Failed to fetch current_remote metadata'\n contents = None\n excep...
[ "0.743946", "0.6923274", "0.638175", "0.6271817", "0.6228844", "0.62113637", "0.6208526", "0.6199531", "0.6125181", "0.61230326", "0.6048329", "0.5846718", "0.5833795", "0.58308524", "0.5800759", "0.57391906", "0.5727758", "0.5712721", "0.5698382", "0.5687096", "0.5684791", ...
0.79775
0
Fetches the metadata local file LOCAL_METADATA_FILE and returns the metadata dict equivalent.
def _fetch_current_local_metadata(): if not os.path.exists(LOCAL_METADATA_FILE): return {} with open(LOCAL_METADATA_FILE) as f: return json.loads(f.read())
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _fetch_current_remote_metadata(conn):\n content = _get(conn, REMOTE_METADATA_FILE)\n metadata = json.loads(content) if content else {}\n return metadata", "def get_downloads_metadata():\n global _METADATA\n if _METADATA is None:\n _METADATA = yaml.safe_load(resource_string(__name__, \"d...
[ "0.68818545", "0.6417708", "0.63122565", "0.62646693", "0.62405384", "0.62042487", "0.6080648", "0.6028128", "0.6001734", "0.59823257", "0.5974274", "0.5929091", "0.59028894", "0.5869242", "0.5845099", "0.5817974", "0.5808917", "0.57907844", "0.5776373", "0.5760592", "0.57372...
0.84643173
0
Based on comparison of local and remote metada dictionaries, filter files to retain only the files which doesn't exist on remote metadata dict or have different content and same filename. Also, based on IGNORE_DIRS and IGNORE_EXTENSIONS, filter the net file list.
def _filter_file_list(files, local_metadata, remote_metadata): def _is_tracked(filename, metadata): """ Is the filename tracked in the remote metadata dict. The file may be not even locally tracked yet """ current_local_sha = local_metadata.get(filename, None) current_remote_sha = metadata.get(filename, None) return current_local_sha is not None \ and current_remote_sha is not None \ and current_local_sha == current_remote_sha def _is_inside_ignored_dir(filename): """ Is the filename inside any of the IGNORE_DIRS list """ ignore_dirs = ['./' + x for x in IGNORE_DIRS] return any([filename.startswith(x) for x in ignore_dirs]) def _has_ignored_extension(filename): return any([ext in IGNORE_EXTENSIONS for ext in filename.split('.')[1:]]) files = [f for f in files if not _is_inside_ignored_dir(f) and not _has_ignored_extension(f) and not _is_tracked(f, remote_metadata)] return files
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def preprocess_raw_remote_files(self, raw_remote_files):\n return [xfile for xfile in raw_remote_files if not xfile.exists()]", "def find_remote_files(product, date, channel, fs, mesoregion=None):\n if 'L1' in product:\n files = [fs.glob('gcp-public-data-goes-16/' + product + '/' + str(date.year...
[ "0.6446468", "0.59767133", "0.5730664", "0.5725296", "0.5656467", "0.5532549", "0.55086225", "0.55084115", "0.5492199", "0.5476868", "0.54651487", "0.5445001", "0.5409476", "0.54082286", "0.53627706", "0.53226095", "0.5322206", "0.53167725", "0.5312311", "0.52992505", "0.5283...
0.74489295
0
Is the filename tracked in the remote metadata dict. The file may be not even locally tracked yet
def _is_tracked(filename, metadata): current_local_sha = local_metadata.get(filename, None) current_remote_sha = metadata.get(filename, None) return current_local_sha is not None \ and current_remote_sha is not None \ and current_local_sha == current_remote_sha
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_remote_cached(cls, target_filename):\n is_cached = None\n cache = cls.CACHE_BACKEND()\n for file_name, file_id in cache.search():\n if file_name == os.path.basename(target_filename):\n is_cached = file_id\n logger.debug('File %r already cached at...
[ "0.7122534", "0.6666199", "0.6614642", "0.6477976", "0.6251149", "0.6231352", "0.61951226", "0.6183894", "0.6110177", "0.6092684", "0.6037549", "0.6031686", "0.60248667", "0.6003988", "0.598465", "0.59665877", "0.59620124", "0.594347", "0.5927977", "0.58981687", "0.58882433",...
0.811574
0
Is the filename inside any of the IGNORE_DIRS list
def _is_inside_ignored_dir(filename): ignore_dirs = ['./' + x for x in IGNORE_DIRS] return any([filename.startswith(x) for x in ignore_dirs])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def ignore(ignored_dirs, path):\n return any([normpath(path).startswith(ignore_dir) for ignore_dir in ignored_dirs])", "def ignore(directory):\n for pattern in ignore_patterns:\n if pattern in directory:\n return True\n\n return False", "def _is_ignored(self, full_path):\n for...
[ "0.7432789", "0.742647", "0.7269846", "0.7173609", "0.7124053", "0.6995675", "0.69607145", "0.6938394", "0.69038445", "0.68344337", "0.6772172", "0.6730275", "0.6686163", "0.65734845", "0.6516576", "0.6510022", "0.6423632", "0.6392135", "0.637968", "0.6378461", "0.63330704", ...
0.81426775
0
Walks through all the subfolders in static_root, and uploads everything valid found to S3. If Gzip is enabled, also tries to compress and upload the compressed version of the static asset.
def upload_all_to_s3(static_root): conn = _get_connection() files = _get_file_list(static_root) _build_local_metadata_file(files, home=static_root) local_metadata = _fetch_current_local_metadata() remote_metadata = _fetch_current_remote_metadata(conn) files_to_upload = _filter_file_list(files, local_metadata, remote_metadata) start_time = time.time() print 'Upload start: Landing in BUCKET_NAME: %s' % BUCKET_NAME for f in files_to_upload: #Upload to Bucket upload_file(conn, os.path.join(static_root, f), f) #Upload Gzip css/js version if gzip is enabled can_be_gzipped = _file_can_be_compressed(os.path.join(static_root, f)) if GZIP_ENABLED and can_be_gzipped: upload_file(conn, os.path.join(static_root, f), f, gzip=True) #Extra files if EXTRA_FILES: print 'Now, uploading extra files outside public/static' for filename_local, filename_s3 in EXTRA_FILES.items(): upload_file(conn, filename_local, filename_s3) end_time = time.time() print 'Upload finished: \ Time elapsed: %s s' % round(end_time - start_time, 3) # refresh metadata file on the server print 'Uploading local metadata file' upload_file(conn, LOCAL_METADATA_FILE, REMOTE_METADATA_FILE) print 'Uploading process DONE'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def s3_sync(s3_bucket, s3_prefix, sync_path=\".\"):\n # Get bucket\n s3_resource = boto3.resource(\"s3\")\n bucket = s3_resource.Bucket(s3_bucket)\n\n # Walk paths and subdirectories, uploading files\n for path, subdirs, files in os.walk(sync_path):\n # Get relative path prefix\n relpa...
[ "0.6210542", "0.61488205", "0.5865301", "0.585198", "0.58491004", "0.58321655", "0.5650139", "0.5592172", "0.5504334", "0.54761356", "0.5457472", "0.5440076", "0.54384625", "0.5431056", "0.5406941", "0.5380988", "0.5366491", "0.53493273", "0.5324381", "0.53202146", "0.5297198...
0.81745136
0
Returns a |random value| <= SHIFT_MAX_VAL
def get_shift() -> int: return random.randint(low = -1 *SHIFT_MAX_VAL, high = SHIFT_MAX_VAL)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_next_random(value, max_value, min_value, max_delta):\n # Determine if sensor delta should be added or substracted.\n if value == max_value:\n add = False\n elif value == min_value:\n add = True\n else:\n add = random.random() > 0.5\n\n # Calculate a new delta.\n delta...
[ "0.6203564", "0.60628116", "0.600135", "0.59833807", "0.59038484", "0.58453417", "0.58328253", "0.5776378", "0.5762465", "0.575023", "0.5747984", "0.57101095", "0.57073265", "0.57069814", "0.5686693", "0.5646487", "0.5634794", "0.5613866", "0.5598931", "0.559132", "0.55743605...
0.7717284
0
load batch of cifar
def load_cifar10_batch(directory): with open(directory, 'rb') as fo: datadict = pickle.load(fo, encoding='bytes') X = np.array(datadict[b'data']) Y = np.array(datadict[b'labels']) return X, Y
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_batch(n):\r\n print ('Loadng one batch...')\r\n batchfilename = flist[n - 1] + '.pkl'\r\n if not os.path.exists(batchfilename):\r\n set_batch_data()\r\n with open(batchfilename, 'rb') as cifar_pickle:\r\n data = six.moves.cPickle.load(cifar_pickle)\r\n return data", "def Loa...
[ "0.75140995", "0.73830444", "0.7317707", "0.72487396", "0.7237417", "0.7199762", "0.7171292", "0.7150728", "0.7141205", "0.7108447", "0.7081937", "0.7059933", "0.70378613", "0.7027403", "0.70267695", "0.6988743", "0.69326067", "0.6907136", "0.68534076", "0.68343514", "0.68166...
0.6843012
19
load all of cifar
def load_cifar10(directory): train_data = [] train_labels = [] for b in range(1, 6): f = os.path.join(directory, 'data_batch_%d' % (b,)) X, Y = load_cifar10_batch(f) train_data.append(X) train_labels.append(Y) train_data = np.concatenate(train_data) train_labels = np.concatenate(train_labels) del X, Y test_data, test_labels = load_cifar10_batch(os.path.join(directory, 'test_batch')) return train_data, train_labels, test_data, test_labels
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_cifar():\n print('==> Preparing data..')\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ])\n\n transform_test ...
[ "0.725037", "0.6986756", "0.69127166", "0.6820187", "0.6604054", "0.6501504", "0.6451561", "0.6348957", "0.62728024", "0.62693584", "0.6159214", "0.6103224", "0.60536623", "0.60487705", "0.60397464", "0.6020603", "0.60159737", "0.5978324", "0.5949136", "0.59246045", "0.591188...
0.5888813
22
load all of cifar as image form
def load_cifar10_img_form(directory): train_data, train_labels, test_data, test_labels = load_cifar10(directory) R, testR = train_data[:, :1024].reshape(-1, 32, 32, 1), test_data[:, :1024].reshape(-1, 32, 32, 1) G, testG = train_data[:, 1024:2048].reshape(-1, 32, 32, 1), test_data[:, 1024:2048].reshape(-1, 32, 32, 1) B, testB = train_data[:, 2048:].reshape(-1, 32, 32, 1), test_data[:, 2048:].reshape(-1, 32, 32, 1) train_data, test_data = np.concatenate((R, G, B), axis=3), np.concatenate((testR, testG, testB), axis=3) return train_data, train_labels, test_data, test_labels
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getimgs():", "def load_images(self):\n for image in self.gltf.images:\n self.images.append(image.load(self.path.parent))", "def load_images(self):\r\n self.standing_frame = [load_image(\"cat1.png\")]\r\n self.walk_frames_r = [load_image(\"cat2.png\"), load_image(\"cat3.png\"...
[ "0.68525964", "0.6523401", "0.6510388", "0.6463343", "0.6404395", "0.6381195", "0.6346877", "0.6258412", "0.6138871", "0.6138871", "0.6138871", "0.6136035", "0.60968804", "0.60725594", "0.6004178", "0.5993124", "0.59865046", "0.59833163", "0.5981841", "0.5942361", "0.5926865"...
0.6069607
14
load all of imagenet data as flat vector
def load_imagenet(directory): path_train, path_val = directory + '/ILSVRC2012_img_train', directory + '/ILSVRC2012_img_val' train_labels = os.listdir(path_train) train_data = [] for label in train_labels: imgs_path = os.path.join(path_train, label) imgs = os.listdir(imgs_path) for img_name in imgs: img_path = os.path.join(imgs_path, img_name) img = cv2.imread(img_path) b, g, r = cv2.split(img) img = cv2.merge([r,g,b]).reshape(-1, 64, 64, 3) train_data.append(img) train_labels.append(label) train_data = np.concatenate(train_data) train_labels = np.array(train_labels, dtype='str') test_labels = os.listdir(path_val) test_data = [] for label in test_labels: imgs_path = os.path.join(path_val, label) for img_name in imgs: img_path = os.path.join(imgs_path, img_name) img = cv2.imread(img_path) b, g, r = cv2.split(img) img = cv2.merge([r,g,b]).reshape(-1, 64, 64, 3) test_data.append(img) test_labels.append(label) test_data = np.concatenate(test_data) test_labels = np.array(test_labels, dtype='str') _, train_labels = np.unique(train_labels, return_inverse=True) _, test_labels = np.unique(test_labels, return_inverse=True) del r, g, b, imgs_path, img_name, img, imgs return train_data, train_labels, test_data, test_labels
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_imagenet_data(net):\r\n\r\n # get a list of all the images (note that we use networks trained on ImageNet data)\r\n img_list = os.listdir(path_data)\r\n\r\n # throw away files that are not in the allowed format (png or jpg)\r\n for img_file in img_list[:]:\r\n if not (img_file.endswith(\...
[ "0.6885546", "0.6619148", "0.6589122", "0.6569712", "0.65382355", "0.6508243", "0.6401413", "0.6387084", "0.63791114", "0.6374463", "0.6297042", "0.6268717", "0.6249637", "0.6221783", "0.61718935", "0.61413294", "0.6102105", "0.6062337", "0.6045171", "0.60450935", "0.6041338"...
0.6851224
1
load all of imagenet data as flat vector
def load_tiny_imagenet(directory): path_train, path_val, path_test = directory + '/train', directory + '/val', directory + '/test' labels = os.listdir(path_train) train_data = [] train_labels = [] for label in labels: imgs_path = os.path.join(path_train, label, 'images') imgs = os.listdir(imgs_path) for img_name in imgs: img_path = os.path.join(imgs_path, img_name) img = cv2.imread(img_path) b, g, r = cv2.split(img) img = cv2.merge([r,g,b]).reshape(-1, 64, 64, 3) train_data.append(img) train_labels.append(label) train_data = np.concatenate(train_data) train_labels = np.array(train_labels, dtype='str') test_data = [] test_labels = [] with open(path_val+'/val_annotations.txt', 'r') as f: val_annotations = [line.strip().split('\t') for line in f] val_annotations = np.array(val_annotations) imgs_path = os.path.join(path_val, 'images') imgs = os.listdir(imgs_path) for img_name in imgs: img_path = os.path.join(imgs_path, img_name) img = cv2.imread(img_path) b, g, r = cv2.split(img) img = cv2.merge([r,g,b]).reshape(-1, 64, 64, 3) test_data.append(img) label = val_annotations[val_annotations[:, 0] == img_name, 1].astype('U9') test_labels.append(label) test_data = np.concatenate(test_data) test_labels = np.concatenate(test_labels) test_labels = np.array(test_labels, dtype='str') _, train_labels = np.unique(train_labels, return_inverse=True) _, test_labels = np.unique(test_labels, return_inverse=True) del r, g, b, label, labels, imgs_path, img_name, img, imgs, val_annotations return train_data, train_labels, test_data, test_labels
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_imagenet_data(net):\r\n\r\n # get a list of all the images (note that we use networks trained on ImageNet data)\r\n img_list = os.listdir(path_data)\r\n\r\n # throw away files that are not in the allowed format (png or jpg)\r\n for img_file in img_list[:]:\r\n if not (img_file.endswith(\...
[ "0.6884788", "0.6850081", "0.6620506", "0.65908414", "0.65704596", "0.65394974", "0.6508061", "0.6400126", "0.63884264", "0.6374563", "0.62975335", "0.6268397", "0.62499464", "0.62215036", "0.61717916", "0.61417174", "0.6101497", "0.6063292", "0.60463053", "0.60456073", "0.60...
0.63781524
9
Take as input a Keras ImageGen (Iterator) and generate random crops from the image batches generated by the original iterator.
def random_crop_generator(batches, crop_length): while True: batch_x, batch_y = next(batches) batch_crops = np.zeros((batch_x.shape[0], crop_length, crop_length, 3)) for i in range(batch_x.shape[0]): batch_crops[i] = random_crop(batch_x[i], (crop_length, crop_length)) yield (batch_crops, batch_y)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def crop_generator(batches, crop_length):\n while True:\n batch_x, batch_y = next(batches)\n batch_crops = np.zeros((batch_x.shape[0], crop_length, crop_length, 3))\n for i in range(batch_x.shape[0]):\n batch_crops[i] = random_crop(batch_x[i], (crop_length, crop_length))\n ...
[ "0.75824314", "0.6719259", "0.63412005", "0.6340442", "0.6336577", "0.6271357", "0.62369394", "0.61656475", "0.6124723", "0.61019236", "0.6051693", "0.6036598", "0.59852403", "0.5972355", "0.596388", "0.5952421", "0.5929974", "0.59115386", "0.5901182", "0.5863039", "0.5820809...
0.74894965
1
To be used in conjunction with loss.binary_xentropy_with_sigmoid
def sigmoid_with_binary_xentropy(z): return sigmoid(z)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def sigmoid(x):\r\n #pred_x = (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))\r\n pred_x = 1.0 / (1.0 + np.exp(-x))\r\n return pred_x\r\n pass", "def test_sigmoid_cross_entropy(self):\n loss_op = pointwise_losses.SigmoidCrossEntropy()\n\n y_pred = loss_op.final_activation_op({\n ...
[ "0.7591269", "0.75822216", "0.7455182", "0.74292374", "0.74232256", "0.74232256", "0.74083984", "0.74083984", "0.74083984", "0.74083984", "0.74083984", "0.74083984", "0.7393072", "0.73908216", "0.73857445", "0.73740834", "0.73655087", "0.73640925", "0.73640925", "0.73588455", ...
0.8279197
0
To be used in conjunction with loss.xentropy_with_softmax
def softmax_with_xentropy(z): return softmax(z)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def loss(params: hk.Params, batch, label) -> jnp.ndarray:\r\n logits = net.apply(params, batch)\r\n labels = jax.nn.one_hot(label, n_classes)\r\n\r\n # Cross Entropy Loss\r\n softmax_xent = -jnp.sum(labels * jax.nn.log_softmax(logits))\r\n softmax_xent /= labels.shape[0]\r\n ...
[ "0.726201", "0.7222704", "0.7183105", "0.7172407", "0.7157092", "0.7130719", "0.7100268", "0.7088628", "0.70864207", "0.7078267", "0.70732236", "0.7006741", "0.7004395", "0.7000175", "0.69368124", "0.6921162", "0.69102913", "0.6891329", "0.6883931", "0.68837404", "0.68784714"...
0.7691633
0
Reshapes 2D arrays to 1D
def resh(x): a = x.shape[0] b = x.shape[1] return x.reshape(a*b, 1), a, b
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def numpyReshape(array):\n return np.array(array, dtype = float).reshape(1, len(array))", "def flatten_numpy(ndarray):\n return np.reshape(ndarray, (-1,), 'F')", "def unstack(a, axis=0):\n shape = a.shape\n return [jnp.squeeze(b, axis=axis) for b in \\\n jnp.split(a, shape[axis], a...
[ "0.74482", "0.71689045", "0.69794905", "0.6903017", "0.6864476", "0.68438625", "0.6818894", "0.67829883", "0.67705846", "0.6595469", "0.6590507", "0.6587642", "0.65708774", "0.65608907", "0.6499275", "0.64894766", "0.6464098", "0.6438216", "0.64029455", "0.63895625", "0.63455...
0.6693302
9
Iterative function that enumerates the set of all sequences of outcomes of given length.
def gen_all_sequences(outcomes, length): answer_set = set([()]) for dummy_idx in range(length): temp_set = set() for partial_sequence in answer_set: for item in outcomes: new_sequence = list(partial_sequence) new_sequence.append(item) temp_set.add(tuple(new_sequence)) answer_set = temp_set return answer_set
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gen_all_sequences(outcomes, length):\r\n \r\n ans = set([()])\r\n for dummy_idx in range(length):\r\n temp = set()\r\n for seq in ans:\r\n for item in outcomes:\r\n new_seq = list(seq)\r\n new_seq.append(item)\r\n temp.add(tuple(new...
[ "0.72901285", "0.72600734", "0.72600734", "0.723398", "0.7221575", "0.7214704", "0.7166947", "0.66999054", "0.66996527", "0.6592231", "0.6587351", "0.6566868", "0.63469136", "0.62606", "0.6040663", "0.6040663", "0.6040663", "0.596155", "0.59232736", "0.58177376", "0.5734803",...
0.7217363
6
Compute the maximal score for a Yahtzee hand according to the upper section of the Yahtzee score card.
def score(hand): max_score = [] for dice in hand: max_score.append(hand.count(dice) * dice) return max(max_score)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def score(hand):\n if (hand==()):\n return 0\n score_board=[0,0,0,0,0,0,0,0,0,0,0,0]\n for dice in hand:\n score_board[dice-1]+=dice\n max_score=max(score_board)\n return max_score", "def max_score(self):\n return self.raw_possible", "def highCard(self):\n return max(...
[ "0.7198057", "0.69047964", "0.6868163", "0.68407416", "0.68071705", "0.67827207", "0.67775255", "0.6729456", "0.6722615", "0.67012155", "0.66802895", "0.66660815", "0.6656922", "0.6642546", "0.6636847", "0.66343987", "0.66135156", "0.6605659", "0.65514874", "0.6536933", "0.65...
0.6956893
1
Compute the expected value based on held_dice given that there are num_free_dice to be rolled, each with num_die_sides.
def expected_value(held_dice, num_die_sides, num_free_dice): scores = [] die_sides = [(die + 1) for die in range(num_die_sides)] pos_outcomes = gen_all_sequences(die_sides, num_free_dice) for outcome in pos_outcomes: scores.append(score(held_dice + outcome)) expected_result = float(sum(scores))/len(scores) return expected_result
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def expected_value(held_dice, num_die_sides, num_free_dice):\n outcomes = get_outcomes(num_die_sides)\n print \"outcomes:\", outcomes\n\n # generate all possible sequences of rolls\n all_rolls = list(gen_all_sequences(outcomes, num_free_dice))\n results = [max_repeats(roll) for roll in all_rolls]\n ...
[ "0.8766034", "0.8516424", "0.84216785", "0.8412181", "0.82945627", "0.8200519", "0.8118519", "0.7291412", "0.7017441", "0.6975462", "0.6942069", "0.6937762", "0.69110143", "0.6777357", "0.67685777", "0.67684424", "0.67683524", "0.6656086", "0.6635097", "0.6356114", "0.6343377...
0.8236513
5
Generate all possible choices of dice from hand to hold.
def gen_all_holds(hand): held_dice = [()] for dice in hand: for dummy_dice in held_dice: held_dice = held_dice + [tuple(dummy_dice) + (dice, )] return set(held_dice)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gen_all_holds(hand):\r\n possible_holds = set([()])\r\n \r\n for dice in hand:\r\n temp_holds = possible_holds.copy()\r\n for hold in temp_holds:\r\n temp_seq = list(hold)\r\n temp_seq.append(dice)\r\n possible_holds.add(tuple(temp_seq))\r\n \r\n re...
[ "0.66850966", "0.6451011", "0.6337711", "0.63297033", "0.63039804", "0.6226844", "0.6226421", "0.62156814", "0.6166249", "0.61634064", "0.61588705", "0.61474586", "0.6074418", "0.60378057", "0.6029834", "0.60106313", "0.598691", "0.59858495", "0.594391", "0.59296936", "0.5920...
0.7070763
0
Compute the hold that maximizes the expected value when the discarded dice are rolled.
def strategy(hand, num_die_sides): best_hold = (0.0, ()) current_score = 0 for held_dice in gen_all_holds(hand): score = expected_value(held_dice, num_die_sides, len(hand) - len(held_dice)) if score > current_score: current_score = score best_hold = (current_score, held_dice) return best_hold
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def expected_value(held_dice, num_die_sides, num_free_dice):\n outcomes = get_outcomes(num_die_sides)\n print \"outcomes:\", outcomes\n\n # generate all possible sequences of rolls\n all_rolls = list(gen_all_sequences(outcomes, num_free_dice))\n results = [max_repeats(roll) for roll in all_rolls]\n ...
[ "0.7388774", "0.70694953", "0.69726455", "0.696321", "0.69587135", "0.6900279", "0.6876599", "0.6836615", "0.67820185", "0.67149234", "0.67129946", "0.6587366", "0.65404105", "0.6535527", "0.65227497", "0.6499015", "0.62842536", "0.6144699", "0.60962355", "0.6076315", "0.5911...
0.7348299
1
Compute the dice to hold and expected score for an example hand
def run_example(): num_die_sides = 6 hand = (1, 1, 1, 5, 6) hand_score, hold = strategy(hand, num_die_sides) print "Best strategy for hand", hand, "is to hold", hold, "with expected score", hand_score
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def strategy(hand, num_die_sides):\n\n possible_holds = gen_all_holds(hand)\n best_val = 0\n best_score = 0\n dice_to_hold = []\n\n for hold in possible_holds:\n hold_val = expected_value(hold, NUM_DIE_SIDES, NUM_DICE - len(hold))\n\n hand_score = score(hold) + score(hand)\n if ...
[ "0.7691115", "0.76907384", "0.7485615", "0.7483924", "0.7410487", "0.740706", "0.7378829", "0.72477937", "0.7241062", "0.72278166", "0.72267485", "0.72267485", "0.72267485", "0.7205913", "0.71917546", "0.71524763", "0.70465297", "0.70109093", "0.69958997", "0.6902083", "0.689...
0.7173642
16
Find names in a sentence based on a FIRST_NAMES file
def find_names(sentence=None, last_names_enabled=True, no_names_enabled=False): if not sentence: raise Exception(ParameterMissing, "This method requires sentence as input") if not isinstance(sentence, str): raise Exception(TypeError, "This method requires string as input") first_names = get_first_names_pack() if not first_names: raise Exception(VariableNotSet, "Variable FIRST_NAMES is not set in settings.py") if last_names_enabled: last_names = get_last_names_pack() if not last_names: raise Exception(VariableNotSet, "Variable LAST_NAMES is not set in settings.py") first_names = list(set(first_names).union(set(last_names))) if no_names_enabled: no_names = get_no_names_pack() if not no_names: raise Exception(VariableNotSet, "Variable NO_NAMES is not set in settings.py") first_names = list(set(first_names).difference(set(no_names))) punctuation = '!@#$%^&*()_+<>?:.,;' for c in sentence: if c in punctuation: sentence = sentence.replace(c, " ") words = sentence.lower().split() res = set(words).intersection(first_names) to_return = [w.title() for w in res] return to_return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find_names(text):\n\n names = []\n\n # spacy doc\n doc = nlp(text)\n\n # pattern\n pattern = [{'LOWER': 'prime'},\n {'LOWER': 'minister'},\n {'POS': 'ADP', 'OP': '?'},\n {'POS': 'PROPN'}]\n\n # Matcher class object\n matcher = Matcher(nlp.vocab)\n ...
[ "0.6360774", "0.6280207", "0.6206798", "0.6189551", "0.6042509", "0.5802803", "0.5793913", "0.5733172", "0.57170224", "0.5716283", "0.56726676", "0.56491053", "0.563351", "0.5597997", "0.5563706", "0.5563537", "0.55441076", "0.55139315", "0.5505184", "0.5496029", "0.54784536"...
0.6673137
0
Find names position in a sentence based on a FIRST_NAMES file
def find_names_position(sentence=None, last_names_enabled=True, no_names_enabled=False): if not sentence: raise Exception(ParameterMissing, "This method requires sentence as input") if not isinstance(sentence, str): raise Exception(TypeError, "This method requires string as input") names_found = find_names(sentence, last_names_enabled=last_names_enabled, no_names_enabled=no_names_enabled) to_return = [] for name in names_found: begin_positions = [m.start() for m in re.finditer(name, sentence)] for begin in begin_positions: to_return.append((begin, begin + len(name))) # begin = sentence.lower().index(name.lower()) # end = begin + len(name) # to_return.append((begin, end)) return to_return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_names(lines): \n next = False \n names = []\n for line in lines:\n if next:\n if len(line) == 1:\n break\n else:\n tmp = line.split()\n names.append(tmp[1])\n if line.startswith('Sequences loaded ...'):\n n...
[ "0.5892083", "0.58443296", "0.5784747", "0.57840866", "0.5768939", "0.5741232", "0.5701107", "0.5652323", "0.54787356", "0.5471315", "0.53691196", "0.5327336", "0.53244394", "0.5305583", "0.5301656", "0.5268954", "0.5267728", "0.5263014", "0.5252052", "0.5240446", "0.5232655"...
0.70489156
0
Find names in a sentence based on a FIRST_NAMES file and replace them
def replace_names(sentence=None, to_replace="X", fixed_size=0, last_names_enabled=True, no_names_enabled=False): if not sentence: raise Exception(ParameterMissing, "This method requires sentence as input") if not isinstance(sentence, str): raise Exception(TypeError, "This method requires string as input") positions_found = find_names_position(sentence, last_names_enabled=last_names_enabled, no_names_enabled=no_names_enabled) words_to_do = set() for position in positions_found: begin, end = position word = sentence[begin: end] words_to_do.add(word) for word in words_to_do: if fixed_size > 0: size = fixed_size else: size = end - begin replace = to_replace * size sentence = sentence.replace(word, replace) return sentence
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def clean_names(text):\n new_text = text\n for p, r in names_mapping:\n new_text = p.sub(r, new_text)\n return new_text", "def process_names():\n with open(input_names_file, 'r') as data:\n plaintext = data.read()\n name_array = plaintext.split('\\n')\n\n # Final name list\n fi...
[ "0.59615916", "0.58315635", "0.57794553", "0.568856", "0.56879234", "0.5680582", "0.5637345", "0.56369686", "0.5613315", "0.5589724", "0.5437056", "0.5363194", "0.5351406", "0.53407454", "0.5291481", "0.52826524", "0.5278052", "0.52475464", "0.52253675", "0.5195565", "0.51936...
0.5814242
2
Display messages based on the window
def displayMessages(window,messages=['']): # update messages text message_in_line = '' for msg in messages: message_in_line += '\n'+msg window['messages'].update(f'{message_in_line}')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def showMessage(self):", "def display_message(self, message):\n if self.web_crawler_window is None and self.webpage_classifier_window is None:\n self.machine_learner_window.display_message(message)\n elif self.web_crawler_window is None and self.machine_learner_window is None:\n ...
[ "0.74672174", "0.740839", "0.7318725", "0.7254243", "0.72349834", "0.71429914", "0.6881725", "0.6847033", "0.6815938", "0.6629776", "0.6621973", "0.66084623", "0.6538907", "0.652988", "0.6500956", "0.6434533", "0.64031684", "0.6329774", "0.63157547", "0.630548", "0.62997496",...
0.7462986
1
Ensure we don't include the same file twice.
def test_unique_keplerids(): total_count = query_one("SELECT COUNT(*) FROM tpf;") filename_count = query_one("SELECT COUNT(DISTINCT filename) FROM tpf;") assert total_count == filename_count
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_file_conflict(self):\n dir0, dir1 = self.make_temp_dirs(2)\n self.write_file(dir0, \"foo\")\n self.sync_all()\n\n self.write_file(dir0, \"foo\", \"bar\")\n time.sleep(0.1)\n self.write_file(dir1, \"foo\", \"baz\")\n self.sync_all()\n # File with late...
[ "0.6422824", "0.6178515", "0.61354905", "0.6065656", "0.6057481", "0.6002684", "0.5994762", "0.5943255", "0.5886908", "0.5771777", "0.56517184", "0.5636331", "0.561987", "0.5594352", "0.5577625", "0.55584747", "0.5556574", "0.5552825", "0.5539634", "0.5462027", "0.5457787", ...
0.0
-1
Normalize samples individually to unit norm. Each sample (i.e. each row of the data matrix) with at least one non zero component is rescaled independently of other samples so that its norm (l1 or l2) equals one.
def normalize(array, norm="l2"): scaler = Normalizer(copy=True, norm=norm) return scaler.fit_transform(array)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def normalize_all(self):\n #for i, vector in enumerate(self.real_vectors):\n # self.real_vectors[i] /= np.linalg.norm(vector)\n self.vectors /= np.linalg.norm(self.vectors, axis=1).reshape(-1,1)\n for i, vector in enumerate(self.real_vectors):\n vector.set(self.vectors[i])...
[ "0.7402892", "0.7139929", "0.7094509", "0.70395654", "0.7027736", "0.6996117", "0.6938368", "0.6919151", "0.6916701", "0.6915404", "0.68970287", "0.6822748", "0.6807383", "0.6790507", "0.6774343", "0.676279", "0.6744965", "0.6737617", "0.67026675", "0.66677684", "0.6663399", ...
0.0
-1
Normalise an array between a given range.
def normalize_range(array, floor=0, ceil=1): scaler = MinMaxScaler(feature_range=(floor, ceil), copy=True) return scaler.fit_transform(array)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def normalize(array):\n high = array.max()\n low = array.min()\n rng = high - low\n array[:] = 1.0 - ((high - array) / rng)", "def normalize(arr):\n m = np.min(arr)\n arr = arr - m\n M = np.max(arr)\n arr = arr / M\n return arr", "def _normalize(array):\n\treturn (array - np.min(arra...
[ "0.79416615", "0.78045434", "0.75153875", "0.74919647", "0.74441695", "0.74441695", "0.74232936", "0.7257156", "0.71199733", "0.7106798", "0.7072435", "0.6989358", "0.6980073", "0.6953394", "0.69305813", "0.691604", "0.69146186", "0.68793344", "0.68729293", "0.6854594", "0.68...
0.7987929
0
Normalise an array by its maximum absolute value. Scales and translates each feature individually such that the maximal absolute value of each feature in the array will be 1.0. It does not shift/center the data, and thus does not destroy any sparsity.
def normalize_max_absolute(array): scaler = MaxAbsScaler(copy=True) return scaler.fit_transform(array)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def max_normalization(array):\n return 1/np.max(array) * array.squeeze(axis=1)", "def normalize(array):\n\treturn array/np.max(array)", "def normalize(my_array: np.ndarray) -> np.ndarray:\n\n return np.abs(my_array)/np.max(np.abs(my_array))", "def maxabs_scale(X, *, axis=..., copy=...):\n ...", "d...
[ "0.7536234", "0.71070904", "0.70744723", "0.6854876", "0.6705524", "0.66903067", "0.6577902", "0.6577724", "0.65433544", "0.6540987", "0.63960224", "0.63942844", "0.638665", "0.63782936", "0.6344834", "0.6317285", "0.62940407", "0.62483877", "0.6247812", "0.6247812", "0.61893...
0.8425474
0
Return a diagonal mask computed from an array. Useful when the data is the same if you transpose the array, eg in a heatmap.
def get_diagonal_mask(data): mask = np.zeros_like(data, dtype=np.bool) mask[np.triu_indices_from(mask)] = True return mask
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_diagonal(self, array):\n diags = [array[::-1, :].diagonal(i) for i in range(-array.shape[0] + 1, array.shape[1])]\n\n # Now back to the original array to get the upper-left-to-lower-right diagonals,\n # starting from the right, so the range needed for shape (x,y) was y-1 to -x+1 descen...
[ "0.72953194", "0.61421484", "0.6136961", "0.58667374", "0.5818971", "0.558432", "0.5531007", "0.55216306", "0.5488027", "0.5458054", "0.5457682", "0.5436873", "0.54321617", "0.5413237", "0.54027534", "0.5357985", "0.5352605", "0.53214806", "0.53060347", "0.5296002", "0.528144...
0.706273
1
Generate a generator that input a group of example in numpy.array and their labels, return the examples and labels by the given batch size.
def minibatches(inputs=None, targets=None, batch_size=None, allow_dynamic_batch_size=False, shuffle=True): if len(inputs) != len(targets): raise AssertionError( "The length of inputs and targets should be equal") if shuffle: indices = np.arange(len(inputs)) np.random.shuffle(indices) # for start_idx in range(0, len(inputs) - batch_size + 1, batch_size): # chulei: handling the case where the number of samples is not a multiple # of batch_size, avoiding wasting samples for start_idx in range(0, len(inputs), batch_size): end_idx = start_idx + batch_size if end_idx > len(inputs): if allow_dynamic_batch_size: end_idx = len(inputs) else: break if shuffle: excerpt = indices[start_idx:end_idx] else: excerpt = slice(start_idx, end_idx) if (isinstance(inputs, list) or isinstance(targets, list)) and shuffle: # zsdonghao: for list indexing when shuffle==True yield [inputs[i] for i in excerpt], [targets[i] for i in excerpt] else: yield inputs[excerpt], targets[excerpt]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generator(features, labels, batch_size):\n \n # Create empty arrays to contain batch of features and labels#\n batch_features = np.zeros((batch_size, 160, 320, 3))\n batch_labels = np.zeros((batch_size, 1))\n while True:\n for i in range(batch_size):\n # choose random index in ...
[ "0.7450385", "0.70173806", "0.6942358", "0.6913882", "0.68870944", "0.6886947", "0.68810886", "0.68509597", "0.67483735", "0.6738463", "0.67325974", "0.6717352", "0.6699821", "0.66986203", "0.66865635", "0.66477764", "0.6606987", "0.65960824", "0.6584885", "0.65848434", "0.65...
0.0
-1
|coro| Refetches the inventory.
async def update(self) -> None: data = await self._state.http.get_user_inventory(self.owner.id64, self.game.app_id, self.game.context_id) self._update(data)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_inventory(self):\n for item in self.items:\n self.rooms[int(item.initial_room_id) - 1].inventory.add(item)", "def getitem(self):\n self.inventory += 1", "def inventory(self, time: int) -> Inventory:\n self.refreshDroneStatus(time)\n return self.__inventory", "a...
[ "0.6672313", "0.6481613", "0.64376086", "0.6390931", "0.6384816", "0.63713384", "0.6365049", "0.60815936", "0.6057353", "0.6050127", "0.60095286", "0.59535676", "0.5945936", "0.5925097", "0.5903476", "0.5844133", "0.5825453", "0.58238333", "0.580484", "0.57929665", "0.5770575...
0.65848404
1
A helper function that filters and removes items by name from the inventory.
def filter_items(self, *names: str, **kwargs) -> List[Item]: limit: int = kwargs.get("limit") if limit and names: raise ValueError("Cannot pass a limit with multiple items") items = [item for item in self if item.name in names] items = items if limit is None else items[:limit] for item in items: self.items.remove(item) return items
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_item_by_name(name):\n item_found = False\n for item in INVENTORY.copy():\n if name == item['name']:\n item_found = True\n print(f'[INFO] Removing item {item}')\n remove_item(item)\n\n if not item_found:\n print(f'Sorry, we did not find {name} in in...
[ "0.80733", "0.69468737", "0.66359633", "0.64539057", "0.6433509", "0.6354961", "0.63414466", "0.6290945", "0.6256641", "0.6235117", "0.6185239", "0.616043", "0.6142811", "0.61316514", "0.6110784", "0.6085078", "0.6080392", "0.6080392", "0.6016932", "0.5994718", "0.5987538", ...
0.622253
10
A helper function that gets and removes an item by name from the inventory.
def get_item(self, name: str) -> Optional[Item]: item = self.filter_items(name, limit=1) return item[0] if item else None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_item_by_name(name):\n item_found = False\n for item in INVENTORY.copy():\n if name == item['name']:\n item_found = True\n print(f'[INFO] Removing item {item}')\n remove_item(item)\n\n if not item_found:\n print(f'Sorry, we did not find {name} in in...
[ "0.8047145", "0.76232535", "0.7482074", "0.7447906", "0.7443081", "0.7161624", "0.70240676", "0.70180637", "0.6955937", "0.6908558", "0.67728066", "0.6741749", "0.6689494", "0.6678281", "0.6673457", "0.6673457", "0.6643998", "0.6608023", "0.65964246", "0.64536357", "0.6442856...
0.0
-1
Retrieve one or more instance of OSLicence with the given key or criteria
def find(key): return ItopapiPrototype.find(ItopapiOSLicence, key)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def find(self, key, condition) -> list:\n pass", "def get_objs_with_key_and_typeclass(self, oname, otypeclass_path):\n return self.filter(db_key__iexact=oname).filter(db_typeclass_path__exact=otypeclass_path)", "def getSpecific(self, keyword, key):", "def _get_criteria(self):\n for molec...
[ "0.58318734", "0.5569626", "0.55302393", "0.5516962", "0.5510297", "0.5305333", "0.5302881", "0.5301674", "0.52550256", "0.52309424", "0.517999", "0.51336336", "0.5116383", "0.5070057", "0.5061014", "0.5043086", "0.50324726", "0.5003754", "0.49889943", "0.49371323", "0.493549...
0.54087424
5
Retrieve all instance of OSLicence
def find_all(): return ItopapiPrototype.find_all(ItopapiOSLicence)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_soma_objects(self):\n\n msg_store = MessageStoreProxy(database=\"soma2data\", collection=\"soma2\")\n objs = msg_store.query(SOMA2Object._type, message_query={\"map_name\":self.soma_map,\"config\":self.soma_conf})\n print \"queried soma2 objects >> \", objs\n self.soma_objects =...
[ "0.6234363", "0.5961881", "0.595799", "0.59259844", "0.5838429", "0.57797927", "0.5702275", "0.57011425", "0.5666823", "0.5649265", "0.5632733", "0.56231284", "0.5603241", "0.54869276", "0.5477077", "0.5447893", "0.54415894", "0.5405049", "0.540362", "0.5400546", "0.5390554",...
0.60590714
1
Retrieve the ItopapiOSVersion corresponding to this server
def find_os_version(self): if self.osversion_id is not None: ItopapiPrototype.get_itop_class('OSVersion').find(self.osfamily_id) return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_os_version(self):\n\t\treturn call_sdk_function('PrlSrvInfo_GetOsVersion', self.handle)", "def get_osversion(self):\n\t\treturn call_sdk_function('PrlFoundVmInfo_GetOSVersion', self.handle)", "def get_os_version(self):\n\t\treturn call_sdk_function('PrlVmCfg_GetOsVersion', self.handle)", "def os_vers...
[ "0.8168305", "0.7857166", "0.7728561", "0.76559675", "0.7597805", "0.7398409", "0.7351898", "0.7313755", "0.7304044", "0.7298166", "0.7229817", "0.7214568", "0.7212459", "0.719492", "0.7193201", "0.71634763", "0.7163448", "0.7133119", "0.7087612", "0.7079623", "0.70749295", ...
0.7123767
18
Retrieve the ItopapiOrganization corresponding to this server
def find_organization(self): if self.org_id is not None: ItopapiPrototype.get_itop_class('Organization').find(self.org_id) return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def organization(self):\n return self._tower.get_organization_by_id(self._data.get('organization'))", "def get_organization(self):\n return self.reference[REF_ORGANIZATION][REF_VALUE]", "def getOrganization(self):\n return _libsbml.ModelCreator_getOrganization(self)", "def get_organizati...
[ "0.7651209", "0.71187073", "0.7091516", "0.68542224", "0.6810734", "0.680332", "0.67780435", "0.6712279", "0.6706957", "0.66816705", "0.6667797", "0.6625002", "0.65964967", "0.6589382", "0.6561183", "0.6561183", "0.6561183", "0.65521574", "0.6543021", "0.64575344", "0.6378819...
0.75703514
1
Create mock coroutine function.
def mock_coro(return_value=None, **kwargs): async def wrapped(*args, **kwargs): return return_value return MagicMock(wraps=wrapped, **kwargs)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def async(function):\n function = asyncio.coroutine(function)\n\n @wraps(function)\n def wrapper(self, *args, **kwargs):\n @asyncio.coroutine\n def c():\n # Run test\n yield from function(self, *args, **kwargs)\n self.loop.run_until_complete(c())\n return wrap...
[ "0.68554175", "0.6837", "0.6691568", "0.6626183", "0.6579949", "0.65167445", "0.6472262", "0.64584243", "0.6420148", "0.6401542", "0.637773", "0.6373077", "0.6311976", "0.62048763", "0.61998427", "0.61998427", "0.61998427", "0.6194855", "0.6184243", "0.6151873", "0.6118671", ...
0.63443387
12
Places the robot on position .
def set_base_xpos(self, pos): node = self.worldbody.find("./body[@name='base']") node.set("pos", array_to_string(pos - self.bottom_offset))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def move():\n Robot.move()", "def locateRobot(self):\n logging.info(\"Display Carte : {}\".format(self.name))\n for r, row in enumerate(self.map):\n #print(row)\n for c, cell in enumerate(row):\n if (cell == \"X\"):\n logging.info(\"r={} / ...
[ "0.7640588", "0.7587472", "0.72154766", "0.71969634", "0.71969634", "0.719446", "0.69888204", "0.6888003", "0.6881876", "0.6855027", "0.6762757", "0.67011625", "0.66731703", "0.6627563", "0.66041356", "0.6589483", "0.6580823", "0.65348256", "0.65167373", "0.65115154", "0.6504...
0.0
-1
Places the robot on position .
def set_base_xquat(self, quat): node = self.worldbody.find("./body[@name='base']") node.set("quat", array_to_string(quat))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def move():\n Robot.move()", "def locateRobot(self):\n logging.info(\"Display Carte : {}\".format(self.name))\n for r, row in enumerate(self.map):\n #print(row)\n for c, cell in enumerate(row):\n if (cell == \"X\"):\n logging.info(\"r={} / ...
[ "0.76408446", "0.7587763", "0.7215272", "0.71969175", "0.71969175", "0.7194924", "0.6987033", "0.68881804", "0.68799406", "0.68528825", "0.6761995", "0.6702392", "0.66734", "0.66272604", "0.6603478", "0.658863", "0.65802443", "0.65351194", "0.651352", "0.65125144", "0.6502403...
0.0
-1
Determine whether a Roman token is the next logical Roman token. This test is for Roman levels 3 or 6, and checks whether the next token is both a Roman numeral and the next bigger Roman numeral. For instance 'v' is a valid Roman numeral. But unless the current Roman evaluates to 4, the 'v' must be a level1 alpha marker.
def roman_surf_test(self, token, next_token): if not token: return False for each in [token, next_token]: if not roman_to_int(each): return False return roman_to_int(next_token) == roman_to_int(token) + 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_roman_numeral(s: str) -> bool:\n if not isinstance(s, str):\n raise TypeError(\"Only strings may be tested \")\n return bool(_romanNumeralPattern.match(s))", "def roman_numerals_decoder(roman):\n roman_numerals = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n result...
[ "0.5724986", "0.55127585", "0.53830534", "0.52930975", "0.5107975", "0.5093595", "0.49485403", "0.49321708", "0.4916438", "0.49055704", "0.48494673", "0.48381567", "0.48101753", "0.47975814", "0.47125", "0.47098485", "0.46954077", "0.46896818", "0.46814248", "0.46712714", "0....
0.6816487
0
Initializes an FDSN Web Service client. >>> client = Client("TAPS")
def __init__(self, base_url="TAPS", major_versions=None, user=None, password=None, user_agent=DEFAULT_USER_AGENT, debug=False, timeout=120, service_mappings=None, jwt_access_token=None, jwt_refresh_token=None): self.debug = debug self.user = user self.timeout = timeout # Cache for the webservice versions. This makes interactive use of # the client more convenient. self.__version_cache = {} if base_url.upper() in URL_MAPPINGS: url_mapping = base_url.upper() base_url = URL_MAPPINGS[url_mapping] url_subpath = URL_DEFAULT_SUBPATH else: if base_url.isalpha(): msg = "The FDSN service shortcut `{}` is unknown."\ .format(base_url) raise ValueError(msg) url_subpath = URL_DEFAULT_SUBPATH # Make sure the base_url does not end with a slash. base_url = base_url.strip("/") # Catch invalid URLs to avoid confusing error messages if not self._validate_base_url(base_url): msg = "The FDSN service base URL `{}` is not a valid URL."\ .format(base_url) raise ValueError(msg) self.base_url = base_url self.url_subpath = url_subpath self._set_opener(user, password) self.request_headers = {"User-Agent": user_agent} # Avoid mutable kwarg. if major_versions is None: major_versions = {} # Make a copy to avoid overwriting the default service versions. self.major_versions = DEFAULT_SERVICE_VERSIONS.copy() self.major_versions.update(major_versions) # Avoid mutable kwarg. if service_mappings is None: service_mappings = {} self._service_mappings = service_mappings if self.debug is True: print("Base URL: %s" % self.base_url) if self._service_mappings: print("Custom service mappings:") for key, value in self._service_mappings.items(): print("\t%s: '%s'" % (key, value)) print("Request Headers: %s" % str(self.request_headers)) self.services = DEFAULT_SERVICES self.jwt_access_token = jwt_access_token self.jwt_refresh_token = jwt_refresh_token
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def client_setup(self):\n self.client = Client()", "def service_client_initialization(self) -> global___Snippet.ClientInitialization:", "def init_client(self, client):\n self.client = client", "def __init__(self, client=None):\n self._client = client", "def __init__(self, client):\n ...
[ "0.68235403", "0.67337793", "0.65410775", "0.6467698", "0.6393337", "0.63824844", "0.6354962", "0.6354742", "0.632095", "0.63021624", "0.61219805", "0.6116711", "0.60593694", "0.5988456", "0.59749275", "0.5955179", "0.5946236", "0.594365", "0.59188706", "0.59016854", "0.58997...
0.6459557
4
Set user and password resulting in subsequent web service requests for waveforms being authenticated for potential access to restricted data. This will overwrite any previously setup credentials/authentication.
def set_credentials(self, user, password): self.user = user self._set_opener(user, password)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def set_credentials():", "def setAuthenticationCredentials(self, username, password):\n self.PDFreactorConfiguration.in1[\"authenticationUsername\"] = username\n self.PDFreactorConfiguration.in1[\"authenticationPassword\"] = password", "def set_credentials(self, *args, **kwargs):\n pass", ...
[ "0.75870895", "0.7177658", "0.67700595", "0.6669403", "0.64879966", "0.6485973", "0.6440404", "0.6395458", "0.6339234", "0.6270898", "0.62019813", "0.6158831", "0.6129935", "0.60635895", "0.6046939", "0.6014322", "0.59898496", "0.59827876", "0.5884749", "0.5865817", "0.585317...
0.69228536
2
Fetch token from the server using the provided user, password resulting in subsequent web service requests for waveforms being authenticated for potential access to restricted data.
def _retrieve_jwt_token(self, user, password): # force https so that we don't send around tokens unsecurely url = 'https://{}/api/token'.format(urlparse(self.base_url).netloc) # paranoid: check again that we only send the token to https if urlparse(url).scheme != "https": msg = 'This should not happen, please file a bug report.' raise Exception(msg) # convert to json data = json.dumps({"username": user, "password": password}) # encode data = bytes(data, "utf-8") headers = {"Content-Type": "application/json"} html = urllib_request.Request(url, data=data, headers=headers) # decode('utf-8') result = urllib_request.urlopen(html).read().decode("utf-8") dic = json.loads(result) # get token self.jwt_access_token = dic['access'] self.jwt_refresh_token = dic['refresh'] if self.debug: print('Got temporary access/refresh: {}/{}'.format(self.jwt_access_token, self.jwt_refresh_token)) return
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def fetch_token(self, user_id, password):\n url = buildCommandUrl(self.server, \"/as/user/token\")\n result = json_request(\"POST\", url, {\n \"userId\": user_id,\n \"password\": password\n })\n return result[\"token\"]", "def _request_token(self):\n respo...
[ "0.68086314", "0.6705352", "0.660126", "0.6583421", "0.6583421", "0.6573778", "0.645508", "0.6440794", "0.64196825", "0.64065206", "0.6396614", "0.63819987", "0.63676745", "0.63418996", "0.63418996", "0.6296961", "0.62778217", "0.62672204", "0.6247356", "0.6242239", "0.619417...
0.6948478
0
A check if the jwt token is valid
def _validate_jwt_token(self): # force https so that we don't send around tokens unsecurely url = 'https://{}/api/token/verify'.format(urlparse(self.base_url).netloc) # paranoid: check again that we only send the token to https if urlparse(url).scheme != "https": msg = 'This should not happen, please file a bug report.' raise Exception(msg) if not self.jwt_access_token: raise FDSNUnauthorizedException("Unauthorized, authentication " "required.", ) # convert to json data = json.dumps({"token": self.jwt_access_token}) # encode data = bytes(data, "utf-8") headers = {"Content-Type": "application/json"} html = urllib_request.Request(url, data=data, headers=headers) # decode('utf-8') try: result = urllib_request.urlopen(html).read().decode("utf-8") dic = json.loads(result) valid = not bool(dic) if self.debug: print('Valid token : {}'.format(valid)) return valid except urllib_error.HTTPError as e: return False
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def isValid(token):\n try:\n decoded = jwt.decode(token, SECRET_KEY)\n return True\n except:\n return False", "def __token_is_valid(self):\n\n if not self.__login_token or len(self.__login_token) < 10:\n # Token is not set or totally invalid\n return False\...
[ "0.8520996", "0.8204527", "0.80866903", "0.7793878", "0.7776991", "0.7762956", "0.77588475", "0.7680332", "0.7579834", "0.7543709", "0.74756145", "0.74731255", "0.74194485", "0.7321448", "0.7219745", "0.71922845", "0.7190927", "0.71824664", "0.7138779", "0.7125586", "0.712098...
0.8363303
1
Get access token from refresh token
def _refresh_access_token(self): # force https so that we don't send around tokens unsecurely url = 'https://{}/api/token/refresh'.format(urlparse(self.base_url).netloc) # paranoid: check again that we only send the token to https if urlparse(url).scheme != "https": msg = 'This should not happen, please file a bug report.' raise Exception(msg) if not self.jwt_refresh_token: raise FDSNUnauthorizedException("Unauthorized, authentication " "required.", ) # convert to json data = json.dumps({"refresh": self.jwt_refresh_token}) # encode data = bytes(data, "utf-8") headers = {"Content-Type": "application/json"} html = urllib_request.Request(url, data=data, headers=headers) # decode('utf-8') try: result = urllib_request.urlopen(html).read().decode("utf-8") dic = json.loads(result) self.jwt_access_token = dic['access'] if self.debug: print('Got temporary access/refresh: {}/{}'.format(self.jwt_access_token, self.jwt_refresh_token)) return except: raise FDSNUnauthorizedException("Unauthorized, authentication " "expired. Please set your credentials again.", )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_access_token(self, refresh=False):\n return self._token_man.get_access_token(refresh)", "def get_access_token(client_id, refresh_token):\n h = {\n \"content-type\": 'application/x-www-form-urlencoded'\n }\n\n d = {\n \"grant_type\": \"refresh_token\",\n \"refresh_toke...
[ "0.8227711", "0.80836374", "0.79436207", "0.7837815", "0.7809161", "0.77488285", "0.7722438", "0.7707735", "0.7651722", "0.76375973", "0.76296955", "0.7606603", "0.7567231", "0.7512205", "0.74993056", "0.7455479", "0.7370668", "0.7347706", "0.7344518", "0.7326517", "0.7323279...
0.68015915
54
Query the dataselect service of the client.
def get_waveforms(self, network, station, location, channel, starttime, endtime, quality=None, minimumlength=None, longestonly=None, filename=None, attach_response=False, **kwargs): if "dataselect" not in self.services: msg = "The current client does not have a dataselect service." raise ValueError(msg) locs = locals() setup_query_dict('dataselect', locs, kwargs) # Special location handling. Convert empty strings to "--". if "location" in kwargs and not kwargs["location"]: kwargs["location"] = "--" url = self._create_url_from_parameters( "dataselect", DEFAULT_PARAMETERS['dataselect'], kwargs) # Gzip not worth it for MiniSEED and most likely disabled for this # route in any case. if not self._validate_jwt_token(): self._refresh_access_token() data_stream = self._download(url, use_gzip=False, use_jwt=self.jwt_access_token) data_stream.seek(0, 0) if filename: self._write_to_file_object(filename, data_stream) data_stream.close() else: st = obspy.read(data_stream, format="MSEED") data_stream.close() if attach_response: self._attach_responses(st) self._attach_dataselect_url_to_stream(st) st.trim(starttime, endtime) return st
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select(self):\n pass", "def select(self):\n pass", "def _run_select(self):\n return self._connection.select(\n self.to_sql(),\n self.get_bindings(),\n not self._use_write_connection\n )", "def select(self):\n return", "def query(self) ...
[ "0.5689811", "0.5689811", "0.5676971", "0.56546783", "0.56363803", "0.56242454", "0.5599584", "0.5577287", "0.5566766", "0.55223155", "0.54716337", "0.54475677", "0.5439183", "0.543774", "0.5430872", "0.54283375", "0.5352924", "0.53037834", "0.52550447", "0.524659", "0.524617...
0.0
-1
Helper method to fetch response via get_stations() and attach it to each trace in stream.
def _attach_responses(self, st): netids = {} for tr in st: if tr.id not in netids: netids[tr.id] = (tr.stats.starttime, tr.stats.endtime) continue netids[tr.id] = ( min(tr.stats.starttime, netids[tr.id][0]), max(tr.stats.endtime, netids[tr.id][1])) inventories = [] for key, value in netids.items(): net, sta, loc, chan = key.split(".") starttime, endtime = value try: inventories.append(self.get_stations( network=net, station=sta, location=loc, channel=chan, starttime=starttime, endtime=endtime, level="response")) except Exception as e: warnings.warn(str(e)) st.attach_response(inventories)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def get_stations(response: Response,\n source: StationSourceEnum = StationSourceEnum.UNSPECIFIED):\n try:\n logger.info('/stations/')\n\n weather_stations = await get_stations_as_geojson(source)\n response.headers[\"Cache-Control\"] = no_cache\n\n return W...
[ "0.6360263", "0.6021909", "0.59900856", "0.5956896", "0.5865758", "0.56059825", "0.5558574", "0.548664", "0.5460832", "0.54202706", "0.53476536", "0.5343625", "0.5334587", "0.5327473", "0.52983934", "0.52805454", "0.5267272", "0.525761", "0.52528024", "0.52523386", "0.5234326...
0.7019285
0
Builds the correct URL. Replaces "query" with "queryauth" if client has authentication information.
def _build_url(self, service, resource_type, parameters={}): # authenticated dataselect queries have different target URL if self.user is not None: if service == "dataselect" and resource_type == "query": resource_type = "queryauth" return build_url(self.base_url, service, self.major_versions[service], resource_type, parameters, service_mappings=self._service_mappings, subpath=self.url_subpath)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_url(self, request, action, **query):\n base = urlparse.urljoin(request['base_url'], self.auth_prefix + '/' + action)\n return appendArgs(base, query)", "def construct_url(self):\n path = [self.path]\n path.extend([str(x) for x in self.params])\n\n url = self.client.ba...
[ "0.7369034", "0.7334827", "0.72362584", "0.7071104", "0.7013484", "0.6760965", "0.65050304", "0.6447025", "0.6425153", "0.63879895", "0.6378408", "0.6330067", "0.63281715", "0.62623614", "0.62623614", "0.62423044", "0.62401664", "0.62292403", "0.6221821", "0.61912405", "0.615...
0.660301
6
Get full version information of webservice (as a tuple of ints). This method is cached and will only be called once for each service per client object.
def get_webservice_version(self, service): if service is not None and service not in self.services: msg = "Service '%s' not available for current client." % service raise ValueError(msg) if service not in FDSNWS: msg = "Service '%s is not a valid FDSN web service." % service raise ValueError(msg) # Access cache. if service in self.__version_cache: return self.__version_cache[service] url = self._build_url(service, "version") version = self._download(url, return_string=True) version = list(map(int, version.split(b"."))) # Store in cache. self.__version_cache[service] = version return version
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_version(self):\n return self.http_call(\"get\", url=f\"{self.base_url}/version\").json()", "def get_version(self):\r\n if not self.endpoint_checker(self.endpointurl):\r\n raise Exception(\"Please use a valid ESRI REST url\")\r\n\r\n parsedurl = urlparse(self.endpointurl)\r...
[ "0.6870342", "0.6858191", "0.67632425", "0.6721903", "0.66590106", "0.66541", "0.6623657", "0.65979606", "0.6570758", "0.65674907", "0.6525932", "0.6500156", "0.6479931", "0.6434038", "0.64299476", "0.64263636", "0.6411924", "0.64047104", "0.6403968", "0.6381451", "0.6369189"...
0.67635494
2