id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,600 | williamgilpin/pypdb | pypdb/pypdb.py | get_seq_cluster | def get_seq_cluster(pdb_id_chain):
"""Get the sequence cluster of a PDB ID plus a pdb_id plus a chain,
Parameters
----------
pdb_id_chain : string
A string denoting a 4 character PDB ID plus a one character chain
offset with a dot: XXXX.X, as in 2F5N.A
Returns
-------
out : dict
A dictionary containing the sequence cluster associated with the PDB
entry and chain
Examples
--------
>>> sclust = get_seq_cluster('2F5N.A')
>>> print(sclust['pdbChain'][:10])
[{'@name': '4PD2.A', '@rank': '1'},
{'@name': '3U6P.A', '@rank': '2'},
{'@name': '4PCZ.A', '@rank': '3'},
{'@name': '3GPU.A', '@rank': '4'},
{'@name': '3JR5.A', '@rank': '5'},
{'@name': '3SAU.A', '@rank': '6'},
{'@name': '3GQ4.A', '@rank': '7'},
{'@name': '1R2Z.A', '@rank': '8'},
{'@name': '3U6E.A', '@rank': '9'},
{'@name': '2XZF.A', '@rank': '10'}]
"""
url_root = 'http://www.rcsb.org/pdb/rest/sequenceCluster?structureId='
out = get_info(pdb_id_chain, url_root = url_root)
out = to_dict(out)
return remove_at_sign(out['sequenceCluster']) | python | def get_seq_cluster(pdb_id_chain):
url_root = 'http://www.rcsb.org/pdb/rest/sequenceCluster?structureId='
out = get_info(pdb_id_chain, url_root = url_root)
out = to_dict(out)
return remove_at_sign(out['sequenceCluster']) | [
"def",
"get_seq_cluster",
"(",
"pdb_id_chain",
")",
":",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/sequenceCluster?structureId='",
"out",
"=",
"get_info",
"(",
"pdb_id_chain",
",",
"url_root",
"=",
"url_root",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"retu... | Get the sequence cluster of a PDB ID plus a pdb_id plus a chain,
Parameters
----------
pdb_id_chain : string
A string denoting a 4 character PDB ID plus a one character chain
offset with a dot: XXXX.X, as in 2F5N.A
Returns
-------
out : dict
A dictionary containing the sequence cluster associated with the PDB
entry and chain
Examples
--------
>>> sclust = get_seq_cluster('2F5N.A')
>>> print(sclust['pdbChain'][:10])
[{'@name': '4PD2.A', '@rank': '1'},
{'@name': '3U6P.A', '@rank': '2'},
{'@name': '4PCZ.A', '@rank': '3'},
{'@name': '3GPU.A', '@rank': '4'},
{'@name': '3JR5.A', '@rank': '5'},
{'@name': '3SAU.A', '@rank': '6'},
{'@name': '3GQ4.A', '@rank': '7'},
{'@name': '1R2Z.A', '@rank': '8'},
{'@name': '3U6E.A', '@rank': '9'},
{'@name': '2XZF.A', '@rank': '10'}] | [
"Get",
"the",
"sequence",
"cluster",
"of",
"a",
"PDB",
"ID",
"plus",
"a",
"pdb_id",
"plus",
"a",
"chain"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L757-L795 |
24,601 | williamgilpin/pypdb | pypdb/pypdb.py | get_pfam | def get_pfam(pdb_id):
"""Return PFAM annotations of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the PFAM annotations for the specified PDB ID
Examples
--------
>>> pfam_info = get_pfam('2LME')
>>> print(pfam_info)
{'pfamHit': {'@pfamAcc': 'PF03895.10', '@pfamName': 'YadA_anchor',
'@structureId': '2LME', '@pdbResNumEnd': '105', '@pdbResNumStart': '28',
'@pfamDesc': 'YadA-like C-terminal region', '@eValue': '5.0E-22', '@chainId': 'A'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/hmmer?structureId=')
out = to_dict(out)
if not out['hmmer3']:
return dict()
return remove_at_sign(out['hmmer3']) | python | def get_pfam(pdb_id):
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/hmmer?structureId=')
out = to_dict(out)
if not out['hmmer3']:
return dict()
return remove_at_sign(out['hmmer3']) | [
"def",
"get_pfam",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/hmmer?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"if",
"not",
"out",
"[",
"'hmmer3'",
"]",
":",
"return"... | Return PFAM annotations of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the PFAM annotations for the specified PDB ID
Examples
--------
>>> pfam_info = get_pfam('2LME')
>>> print(pfam_info)
{'pfamHit': {'@pfamAcc': 'PF03895.10', '@pfamName': 'YadA_anchor',
'@structureId': '2LME', '@pdbResNumEnd': '105', '@pdbResNumStart': '28',
'@pfamDesc': 'YadA-like C-terminal region', '@eValue': '5.0E-22', '@chainId': 'A'}} | [
"Return",
"PFAM",
"annotations",
"of",
"given",
"PDB_ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L844-L873 |
24,602 | williamgilpin/pypdb | pypdb/pypdb.py | get_clusters | def get_clusters(pdb_id):
"""Return cluster related web services of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the representative clusters for the specified PDB ID
Examples
--------
>>> clusts = get_clusters('4hhb.A')
>>> print(clusts)
{'pdbChain': {'@name': '2W72.A'}}
"""
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/representatives?structureId=')
out = to_dict(out)
return remove_at_sign(out['representatives']) | python | def get_clusters(pdb_id):
out = get_info(pdb_id, url_root = 'http://www.rcsb.org/pdb/rest/representatives?structureId=')
out = to_dict(out)
return remove_at_sign(out['representatives']) | [
"def",
"get_clusters",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/representatives?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"return",
"remove_at_sign",
"(",
"out",
"[",
... | Return cluster related web services of given PDB_ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing the representative clusters for the specified PDB ID
Examples
--------
>>> clusts = get_clusters('4hhb.A')
>>> print(clusts)
{'pdbChain': {'@name': '2W72.A'}} | [
"Return",
"cluster",
"related",
"web",
"services",
"of",
"given",
"PDB_ID"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L875-L900 |
24,603 | williamgilpin/pypdb | pypdb/pypdb.py | find_results_gen | def find_results_gen(search_term, field='title'):
'''
Return a generator of the results returned by a search of
the protein data bank. This generator is used internally.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
Examples
--------
>>> result_gen = find_results_gen('bleb')
>>> pprint.pprint([item for item in result_gen][:5])
['MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-ALF4',
'DICTYOSTELIUM DISCOIDEUM MYOSIN II MOTOR DOMAIN S456E WITH BOUND MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456E BOUND WITH MGADP-ALF4',
'The structural basis of blebbistatin inhibition and specificity for myosin '
'II']
'''
scan_params = make_query(search_term, querytype='AdvancedKeywordQuery')
search_result_ids = do_search(scan_params)
all_titles = []
for pdb_result in search_result_ids:
result= describe_pdb(pdb_result)
if field in result.keys():
yield result[field] | python | def find_results_gen(search_term, field='title'):
'''
Return a generator of the results returned by a search of
the protein data bank. This generator is used internally.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
Examples
--------
>>> result_gen = find_results_gen('bleb')
>>> pprint.pprint([item for item in result_gen][:5])
['MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-ALF4',
'DICTYOSTELIUM DISCOIDEUM MYOSIN II MOTOR DOMAIN S456E WITH BOUND MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456E BOUND WITH MGADP-ALF4',
'The structural basis of blebbistatin inhibition and specificity for myosin '
'II']
'''
scan_params = make_query(search_term, querytype='AdvancedKeywordQuery')
search_result_ids = do_search(scan_params)
all_titles = []
for pdb_result in search_result_ids:
result= describe_pdb(pdb_result)
if field in result.keys():
yield result[field] | [
"def",
"find_results_gen",
"(",
"search_term",
",",
"field",
"=",
"'title'",
")",
":",
"scan_params",
"=",
"make_query",
"(",
"search_term",
",",
"querytype",
"=",
"'AdvancedKeywordQuery'",
")",
"search_result_ids",
"=",
"do_search",
"(",
"scan_params",
")",
"all_... | Return a generator of the results returned by a search of
the protein data bank. This generator is used internally.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
Examples
--------
>>> result_gen = find_results_gen('bleb')
>>> pprint.pprint([item for item in result_gen][:5])
['MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456Y BOUND WITH MGADP-ALF4',
'DICTYOSTELIUM DISCOIDEUM MYOSIN II MOTOR DOMAIN S456E WITH BOUND MGADP-BEFX',
'MYOSIN II DICTYOSTELIUM DISCOIDEUM MOTOR DOMAIN S456E BOUND WITH MGADP-ALF4',
'The structural basis of blebbistatin inhibition and specificity for myosin '
'II'] | [
"Return",
"a",
"generator",
"of",
"the",
"results",
"returned",
"by",
"a",
"search",
"of",
"the",
"protein",
"data",
"bank",
".",
"This",
"generator",
"is",
"used",
"internally",
"."
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L904-L938 |
24,604 | williamgilpin/pypdb | pypdb/pypdb.py | parse_results_gen | def parse_results_gen(search_term, field='title', max_results = 100, sleep_time=.1):
'''
Query the PDB with a search term and field while respecting the query frequency
limitations of the API.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
max_results : int
The maximum number of results to search through when
determining the top results
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
all_data_raw : list of str
'''
if max_results*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(max_results*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
all_data_raw = find_results_gen(search_term, field=field)
all_data =list()
while len(all_data) < max_results:
all_data.append(all_data_raw.send(None))
time.sleep(sleep_time)
return all_data | python | def parse_results_gen(search_term, field='title', max_results = 100, sleep_time=.1):
'''
Query the PDB with a search term and field while respecting the query frequency
limitations of the API.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
max_results : int
The maximum number of results to search through when
determining the top results
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
all_data_raw : list of str
'''
if max_results*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(max_results*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
all_data_raw = find_results_gen(search_term, field=field)
all_data =list()
while len(all_data) < max_results:
all_data.append(all_data_raw.send(None))
time.sleep(sleep_time)
return all_data | [
"def",
"parse_results_gen",
"(",
"search_term",
",",
"field",
"=",
"'title'",
",",
"max_results",
"=",
"100",
",",
"sleep_time",
"=",
".1",
")",
":",
"if",
"max_results",
"*",
"sleep_time",
">",
"30",
":",
"warnings",
".",
"warn",
"(",
"\"Because of API limi... | Query the PDB with a search term and field while respecting the query frequency
limitations of the API.
Parameters
----------
search_term : str
The search keyword
field : str
The type of information to record about each entry
max_results : int
The maximum number of results to search through when
determining the top results
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
all_data_raw : list of str | [
"Query",
"the",
"PDB",
"with",
"a",
"search",
"term",
"and",
"field",
"while",
"respecting",
"the",
"query",
"frequency",
"limitations",
"of",
"the",
"API",
"."
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L940-L982 |
24,605 | williamgilpin/pypdb | pypdb/pypdb.py | find_papers | def find_papers(search_term, **kwargs):
'''
Return an ordered list of the top papers returned by a keyword search of
the RCSB PDB
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
all_papers : list of strings
A descending-order list containing the top papers associated with
the search term in the PDB
Examples
--------
>>> matching_papers = find_papers('crispr',max_results=3)
>>> print(matching_papers)
['Crystal structure of a CRISPR-associated protein from thermus thermophilus',
'CRYSTAL STRUCTURE OF HYPOTHETICAL PROTEIN SSO1404 FROM SULFOLOBUS SOLFATARICUS P2',
'NMR solution structure of a CRISPR repeat binding protein']
'''
all_papers = parse_results_gen(search_term, field='title', **kwargs)
return remove_dupes(all_papers) | python | def find_papers(search_term, **kwargs):
'''
Return an ordered list of the top papers returned by a keyword search of
the RCSB PDB
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
all_papers : list of strings
A descending-order list containing the top papers associated with
the search term in the PDB
Examples
--------
>>> matching_papers = find_papers('crispr',max_results=3)
>>> print(matching_papers)
['Crystal structure of a CRISPR-associated protein from thermus thermophilus',
'CRYSTAL STRUCTURE OF HYPOTHETICAL PROTEIN SSO1404 FROM SULFOLOBUS SOLFATARICUS P2',
'NMR solution structure of a CRISPR repeat binding protein']
'''
all_papers = parse_results_gen(search_term, field='title', **kwargs)
return remove_dupes(all_papers) | [
"def",
"find_papers",
"(",
"search_term",
",",
"*",
"*",
"kwargs",
")",
":",
"all_papers",
"=",
"parse_results_gen",
"(",
"search_term",
",",
"field",
"=",
"'title'",
",",
"*",
"*",
"kwargs",
")",
"return",
"remove_dupes",
"(",
"all_papers",
")"
] | Return an ordered list of the top papers returned by a keyword search of
the RCSB PDB
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
all_papers : list of strings
A descending-order list containing the top papers associated with
the search term in the PDB
Examples
--------
>>> matching_papers = find_papers('crispr',max_results=3)
>>> print(matching_papers)
['Crystal structure of a CRISPR-associated protein from thermus thermophilus',
'CRYSTAL STRUCTURE OF HYPOTHETICAL PROTEIN SSO1404 FROM SULFOLOBUS SOLFATARICUS P2',
'NMR solution structure of a CRISPR repeat binding protein'] | [
"Return",
"an",
"ordered",
"list",
"of",
"the",
"top",
"papers",
"returned",
"by",
"a",
"keyword",
"search",
"of",
"the",
"RCSB",
"PDB"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L985-L1017 |
24,606 | williamgilpin/pypdb | pypdb/pypdb.py | find_authors | def find_authors(search_term, **kwargs):
'''Return an ordered list of the top authors returned by a keyword search of
the RCSB PDB
This function is based on the number of unique PDB entries a given author has
his or her name associated with, and not author order or the ranking of the
entry in the keyword search results. So if an author tends to publish on topics
related to the search_term a lot, even if those papers are not the best match for
the exact search, he or she will have priority in this function over an author
who wrote the one paper that is most relevant to the search term. For the latter
option, just do a standard keyword search using do_search.
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
out : list of str
Examples
--------
>>> top_authors = find_authors('crispr',max_results=100)
>>> print(top_authors[:10])
['Doudna, J.A.', 'Jinek, M.', 'Ke, A.', 'Li, H.', 'Nam, K.H.']
'''
all_individuals = parse_results_gen(search_term, field='citation_authors', **kwargs)
full_author_list = []
for individual in all_individuals:
individual = individual.replace('.,', '.;')
author_list_clean = [x.strip() for x in individual.split(';')]
full_author_list+=author_list_clean
out = list(chain.from_iterable(repeat(ii, c) for ii,c in Counter(full_author_list).most_common()))
return remove_dupes(out) | python | def find_authors(search_term, **kwargs):
'''Return an ordered list of the top authors returned by a keyword search of
the RCSB PDB
This function is based on the number of unique PDB entries a given author has
his or her name associated with, and not author order or the ranking of the
entry in the keyword search results. So if an author tends to publish on topics
related to the search_term a lot, even if those papers are not the best match for
the exact search, he or she will have priority in this function over an author
who wrote the one paper that is most relevant to the search term. For the latter
option, just do a standard keyword search using do_search.
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
out : list of str
Examples
--------
>>> top_authors = find_authors('crispr',max_results=100)
>>> print(top_authors[:10])
['Doudna, J.A.', 'Jinek, M.', 'Ke, A.', 'Li, H.', 'Nam, K.H.']
'''
all_individuals = parse_results_gen(search_term, field='citation_authors', **kwargs)
full_author_list = []
for individual in all_individuals:
individual = individual.replace('.,', '.;')
author_list_clean = [x.strip() for x in individual.split(';')]
full_author_list+=author_list_clean
out = list(chain.from_iterable(repeat(ii, c) for ii,c in Counter(full_author_list).most_common()))
return remove_dupes(out) | [
"def",
"find_authors",
"(",
"search_term",
",",
"*",
"*",
"kwargs",
")",
":",
"all_individuals",
"=",
"parse_results_gen",
"(",
"search_term",
",",
"field",
"=",
"'citation_authors'",
",",
"*",
"*",
"kwargs",
")",
"full_author_list",
"=",
"[",
"]",
"for",
"i... | Return an ordered list of the top authors returned by a keyword search of
the RCSB PDB
This function is based on the number of unique PDB entries a given author has
his or her name associated with, and not author order or the ranking of the
entry in the keyword search results. So if an author tends to publish on topics
related to the search_term a lot, even if those papers are not the best match for
the exact search, he or she will have priority in this function over an author
who wrote the one paper that is most relevant to the search term. For the latter
option, just do a standard keyword search using do_search.
Parameters
----------
search_term : str
The search keyword
max_results : int
The maximum number of results to return
Returns
-------
out : list of str
Examples
--------
>>> top_authors = find_authors('crispr',max_results=100)
>>> print(top_authors[:10])
['Doudna, J.A.', 'Jinek, M.', 'Ke, A.', 'Li, H.', 'Nam, K.H.'] | [
"Return",
"an",
"ordered",
"list",
"of",
"the",
"top",
"authors",
"returned",
"by",
"a",
"keyword",
"search",
"of",
"the",
"RCSB",
"PDB"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1019-L1065 |
24,607 | williamgilpin/pypdb | pypdb/pypdb.py | list_taxa | def list_taxa(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated species
This function digs through the search results returned
by the get_all_info() function and returns any information on
taxonomy included within the description.
The PDB website description of each entry includes the name
of the species (and sometimes details of organ or body part)
for each protein structure sample.
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
taxa : list of str
A list of the names or classifictions of species
associated with entries
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_taxa(crispr_results[:10]))
['Thermus thermophilus',
'Sulfolobus solfataricus P2',
'Hyperthermus butylicus DSM 5456',
'unidentified phage',
'Sulfolobus solfataricus P2',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Sulfolobus solfataricus',
'Thermus thermophilus HB8']
'''
if len(pdb_list)*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
taxa = []
for pdb_id in pdb_list:
all_info = get_all_info(pdb_id)
species_results = walk_nested_dict(all_info, 'Taxonomy', maxdepth=25,outputs=[])
first_result = walk_nested_dict(species_results,'@name',outputs=[])
if first_result:
taxa.append(first_result[-1])
else:
taxa.append('Unknown')
time.sleep(sleep_time)
return taxa | python | def list_taxa(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated species
This function digs through the search results returned
by the get_all_info() function and returns any information on
taxonomy included within the description.
The PDB website description of each entry includes the name
of the species (and sometimes details of organ or body part)
for each protein structure sample.
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
taxa : list of str
A list of the names or classifictions of species
associated with entries
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_taxa(crispr_results[:10]))
['Thermus thermophilus',
'Sulfolobus solfataricus P2',
'Hyperthermus butylicus DSM 5456',
'unidentified phage',
'Sulfolobus solfataricus P2',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Sulfolobus solfataricus',
'Thermus thermophilus HB8']
'''
if len(pdb_list)*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
taxa = []
for pdb_id in pdb_list:
all_info = get_all_info(pdb_id)
species_results = walk_nested_dict(all_info, 'Taxonomy', maxdepth=25,outputs=[])
first_result = walk_nested_dict(species_results,'@name',outputs=[])
if first_result:
taxa.append(first_result[-1])
else:
taxa.append('Unknown')
time.sleep(sleep_time)
return taxa | [
"def",
"list_taxa",
"(",
"pdb_list",
",",
"sleep_time",
"=",
".1",
")",
":",
"if",
"len",
"(",
"pdb_list",
")",
"*",
"sleep_time",
">",
"30",
":",
"warnings",
".",
"warn",
"(",
"\"Because of API limitations, this function\\\n will take at least \"",
"+",
"s... | Given a list of PDB IDs, look up their associated species
This function digs through the search results returned
by the get_all_info() function and returns any information on
taxonomy included within the description.
The PDB website description of each entry includes the name
of the species (and sometimes details of organ or body part)
for each protein structure sample.
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
taxa : list of str
A list of the names or classifictions of species
associated with entries
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_taxa(crispr_results[:10]))
['Thermus thermophilus',
'Sulfolobus solfataricus P2',
'Hyperthermus butylicus DSM 5456',
'unidentified phage',
'Sulfolobus solfataricus P2',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Pseudomonas aeruginosa UCBPP-PA14',
'Sulfolobus solfataricus',
'Thermus thermophilus HB8'] | [
"Given",
"a",
"list",
"of",
"PDB",
"IDs",
"look",
"up",
"their",
"associated",
"species"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1095-L1162 |
24,608 | williamgilpin/pypdb | pypdb/pypdb.py | list_types | def list_types(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
infotypes : list of str
A list of the structure types associated with each PDB
in the list. For many entries in the RCSB PDB, this defaults
to 'protein'
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_types(crispr_results[:5]))
['protein', 'protein', 'protein', 'protein', 'protein']
'''
if len(pdb_list)*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
infotypes = []
for pdb_id in pdb_list:
all_info = get_all_info(pdb_id)
type_results = walk_nested_dict(all_info, '@type', maxdepth=25,outputs=[])
if type_results:
infotypes.append(type_results[-1])
else:
infotypes.append('Unknown')
time.sleep(sleep_time)
return infotypes | python | def list_types(pdb_list, sleep_time=.1):
'''Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
infotypes : list of str
A list of the structure types associated with each PDB
in the list. For many entries in the RCSB PDB, this defaults
to 'protein'
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_types(crispr_results[:5]))
['protein', 'protein', 'protein', 'protein', 'protein']
'''
if len(pdb_list)*sleep_time > 30:
warnings.warn("Because of API limitations, this function\
will take at least " + str(len(pdb_list)*sleep_time) + " seconds to return results.\
If you need greater speed, try modifying the optional argument sleep_time=.1, (although \
this may cause the search to time out)" )
infotypes = []
for pdb_id in pdb_list:
all_info = get_all_info(pdb_id)
type_results = walk_nested_dict(all_info, '@type', maxdepth=25,outputs=[])
if type_results:
infotypes.append(type_results[-1])
else:
infotypes.append('Unknown')
time.sleep(sleep_time)
return infotypes | [
"def",
"list_types",
"(",
"pdb_list",
",",
"sleep_time",
"=",
".1",
")",
":",
"if",
"len",
"(",
"pdb_list",
")",
"*",
"sleep_time",
">",
"30",
":",
"warnings",
".",
"warn",
"(",
"\"Because of API limitations, this function\\\n will take at least \"",
"+",
"... | Given a list of PDB IDs, look up their associated structure type
Parameters
----------
pdb_list : list of str
List of PDB IDs
sleep_time : float
Time (in seconds) to wait between requests. If this number is too small
the API will stop working, but it appears to vary among different systems
Returns
-------
infotypes : list of str
A list of the structure types associated with each PDB
in the list. For many entries in the RCSB PDB, this defaults
to 'protein'
Examples
--------
>>> crispr_query = make_query('crispr')
>>> crispr_results = do_search(crispr_query)
>>> print(list_types(crispr_results[:5]))
['protein', 'protein', 'protein', 'protein', 'protein'] | [
"Given",
"a",
"list",
"of",
"PDB",
"IDs",
"look",
"up",
"their",
"associated",
"structure",
"type"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1164-L1212 |
24,609 | williamgilpin/pypdb | pypdb/pypdb.py | remove_dupes | def remove_dupes(list_with_dupes):
'''Remove duplicate entries from a list while preserving order
This function uses Python's standard equivalence testing methods in
order to determine if two elements of a list are identical. So if in the list [a,b,c]
the condition a == b is True, then regardless of whether a and b are strings, ints,
or other, then b will be removed from the list: [a, c]
Parameters
----------
list_with_dupes : list
A list containing duplicate elements
Returns
-------
out : list
The list with the duplicate entries removed by the order preserved
Examples
--------
>>> a = [1,3,2,4,2]
>>> print(remove_dupes(a))
[1,3,2,4]
'''
visited = set()
visited_add = visited.add
out = [ entry for entry in list_with_dupes if not (entry in visited or visited_add(entry))]
return out | python | def remove_dupes(list_with_dupes):
'''Remove duplicate entries from a list while preserving order
This function uses Python's standard equivalence testing methods in
order to determine if two elements of a list are identical. So if in the list [a,b,c]
the condition a == b is True, then regardless of whether a and b are strings, ints,
or other, then b will be removed from the list: [a, c]
Parameters
----------
list_with_dupes : list
A list containing duplicate elements
Returns
-------
out : list
The list with the duplicate entries removed by the order preserved
Examples
--------
>>> a = [1,3,2,4,2]
>>> print(remove_dupes(a))
[1,3,2,4]
'''
visited = set()
visited_add = visited.add
out = [ entry for entry in list_with_dupes if not (entry in visited or visited_add(entry))]
return out | [
"def",
"remove_dupes",
"(",
"list_with_dupes",
")",
":",
"visited",
"=",
"set",
"(",
")",
"visited_add",
"=",
"visited",
".",
"add",
"out",
"=",
"[",
"entry",
"for",
"entry",
"in",
"list_with_dupes",
"if",
"not",
"(",
"entry",
"in",
"visited",
"or",
"vis... | Remove duplicate entries from a list while preserving order
This function uses Python's standard equivalence testing methods in
order to determine if two elements of a list are identical. So if in the list [a,b,c]
the condition a == b is True, then regardless of whether a and b are strings, ints,
or other, then b will be removed from the list: [a, c]
Parameters
----------
list_with_dupes : list
A list containing duplicate elements
Returns
-------
out : list
The list with the duplicate entries removed by the order preserved
Examples
--------
>>> a = [1,3,2,4,2]
>>> print(remove_dupes(a))
[1,3,2,4] | [
"Remove",
"duplicate",
"entries",
"from",
"a",
"list",
"while",
"preserving",
"order"
] | bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15 | https://github.com/williamgilpin/pypdb/blob/bfb9e1b15b4ad097c5add50c4c176ac6cb28ee15/pypdb/pypdb.py#L1268-L1298 |
24,610 | ndrplz/google-drive-downloader | google_drive_downloader/google_drive_downloader.py | GoogleDriveDownloader.download_file_from_google_drive | def download_file_from_google_drive(file_id, dest_path, overwrite=False, unzip=False, showsize=False):
"""
Downloads a shared file from google drive into a given folder.
Optionally unzips it.
Parameters
----------
file_id: str
the file identifier.
You can obtain it from the sharable link.
dest_path: str
the destination where to save the downloaded file.
Must be a path (for example: './downloaded_file.txt')
overwrite: bool
optional, if True forces re-download and overwrite.
unzip: bool
optional, if True unzips a file.
If the file is not a zip file, ignores it.
showsize: bool
optional, if True print the current download size.
Returns
-------
None
"""
destination_directory = dirname(dest_path)
if not exists(destination_directory):
makedirs(destination_directory)
if not exists(dest_path) or overwrite:
session = requests.Session()
print('Downloading {} into {}... '.format(file_id, dest_path), end='')
stdout.flush()
response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params={'id': file_id}, stream=True)
token = GoogleDriveDownloader._get_confirm_token(response)
if token:
params = {'id': file_id, 'confirm': token}
response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params=params, stream=True)
if showsize:
print() # Skip to the next line
current_download_size = [0]
GoogleDriveDownloader._save_response_content(response, dest_path, showsize, current_download_size)
print('Done.')
if unzip:
try:
print('Unzipping...', end='')
stdout.flush()
with zipfile.ZipFile(dest_path, 'r') as z:
z.extractall(destination_directory)
print('Done.')
except zipfile.BadZipfile:
warnings.warn('Ignoring `unzip` since "{}" does not look like a valid zip file'.format(file_id)) | python | def download_file_from_google_drive(file_id, dest_path, overwrite=False, unzip=False, showsize=False):
destination_directory = dirname(dest_path)
if not exists(destination_directory):
makedirs(destination_directory)
if not exists(dest_path) or overwrite:
session = requests.Session()
print('Downloading {} into {}... '.format(file_id, dest_path), end='')
stdout.flush()
response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params={'id': file_id}, stream=True)
token = GoogleDriveDownloader._get_confirm_token(response)
if token:
params = {'id': file_id, 'confirm': token}
response = session.get(GoogleDriveDownloader.DOWNLOAD_URL, params=params, stream=True)
if showsize:
print() # Skip to the next line
current_download_size = [0]
GoogleDriveDownloader._save_response_content(response, dest_path, showsize, current_download_size)
print('Done.')
if unzip:
try:
print('Unzipping...', end='')
stdout.flush()
with zipfile.ZipFile(dest_path, 'r') as z:
z.extractall(destination_directory)
print('Done.')
except zipfile.BadZipfile:
warnings.warn('Ignoring `unzip` since "{}" does not look like a valid zip file'.format(file_id)) | [
"def",
"download_file_from_google_drive",
"(",
"file_id",
",",
"dest_path",
",",
"overwrite",
"=",
"False",
",",
"unzip",
"=",
"False",
",",
"showsize",
"=",
"False",
")",
":",
"destination_directory",
"=",
"dirname",
"(",
"dest_path",
")",
"if",
"not",
"exist... | Downloads a shared file from google drive into a given folder.
Optionally unzips it.
Parameters
----------
file_id: str
the file identifier.
You can obtain it from the sharable link.
dest_path: str
the destination where to save the downloaded file.
Must be a path (for example: './downloaded_file.txt')
overwrite: bool
optional, if True forces re-download and overwrite.
unzip: bool
optional, if True unzips a file.
If the file is not a zip file, ignores it.
showsize: bool
optional, if True print the current download size.
Returns
-------
None | [
"Downloads",
"a",
"shared",
"file",
"from",
"google",
"drive",
"into",
"a",
"given",
"folder",
".",
"Optionally",
"unzips",
"it",
"."
] | be1aba9e2e43b2375475f19d8214ca50a8621bd6 | https://github.com/ndrplz/google-drive-downloader/blob/be1aba9e2e43b2375475f19d8214ca50a8621bd6/google_drive_downloader/google_drive_downloader.py#L20-L78 |
24,611 | python-hyper/wsproto | example/synchronous_server.py | handle_connection | def handle_connection(stream):
'''
Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket stream
'''
ws = WSConnection(ConnectionType.SERVER)
# events is a generator that yields websocket event objects. Usually you
# would say `for event in ws.events()`, but the synchronous nature of this
# server requires us to use next(event) instead so that we can interleave
# the network I/O.
events = ws.events()
running = True
while running:
# 1) Read data from network
in_data = stream.recv(RECEIVE_BYTES)
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data)
# 2) Get next wsproto event
try:
event = next(events)
except StopIteration:
print('Client connection dropped unexpectedly')
return
# 3) Handle event
if isinstance(event, Request):
# Negotiate new WebSocket connection
print('Accepting WebSocket upgrade')
out_data = ws.send(AcceptConnection())
elif isinstance(event, CloseConnection):
# Print log message and break out
print('Connection closed: code={}/{} reason={}'.format(
event.code.value, event.code.name, event.reason))
out_data = ws.send(event.response())
running = False
elif isinstance(event, TextMessage):
# Reverse text and send it back to wsproto
print('Received request and sending response')
out_data = ws.send(Message(data=event.data[::-1]))
elif isinstance(event, Ping):
# wsproto handles ping events for you by placing a pong frame in
# the outgoing buffer. You should not call pong() unless you want to
# send an unsolicited pong frame.
print('Received ping and sending pong')
out_data = ws.send(event.response())
else:
print('Unknown event: {!r}'.format(event))
# 4) Send data from wsproto to network
print('Sending {} bytes'.format(len(out_data)))
stream.send(out_data) | python | def handle_connection(stream):
'''
Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket stream
'''
ws = WSConnection(ConnectionType.SERVER)
# events is a generator that yields websocket event objects. Usually you
# would say `for event in ws.events()`, but the synchronous nature of this
# server requires us to use next(event) instead so that we can interleave
# the network I/O.
events = ws.events()
running = True
while running:
# 1) Read data from network
in_data = stream.recv(RECEIVE_BYTES)
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data)
# 2) Get next wsproto event
try:
event = next(events)
except StopIteration:
print('Client connection dropped unexpectedly')
return
# 3) Handle event
if isinstance(event, Request):
# Negotiate new WebSocket connection
print('Accepting WebSocket upgrade')
out_data = ws.send(AcceptConnection())
elif isinstance(event, CloseConnection):
# Print log message and break out
print('Connection closed: code={}/{} reason={}'.format(
event.code.value, event.code.name, event.reason))
out_data = ws.send(event.response())
running = False
elif isinstance(event, TextMessage):
# Reverse text and send it back to wsproto
print('Received request and sending response')
out_data = ws.send(Message(data=event.data[::-1]))
elif isinstance(event, Ping):
# wsproto handles ping events for you by placing a pong frame in
# the outgoing buffer. You should not call pong() unless you want to
# send an unsolicited pong frame.
print('Received ping and sending pong')
out_data = ws.send(event.response())
else:
print('Unknown event: {!r}'.format(event))
# 4) Send data from wsproto to network
print('Sending {} bytes'.format(len(out_data)))
stream.send(out_data) | [
"def",
"handle_connection",
"(",
"stream",
")",
":",
"ws",
"=",
"WSConnection",
"(",
"ConnectionType",
".",
"SERVER",
")",
"# events is a generator that yields websocket event objects. Usually you",
"# would say `for event in ws.events()`, but the synchronous nature of this",
"# serv... | Handle a connection.
The server operates a request/response cycle, so it performs a synchronous
loop:
1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network
:param stream: a socket stream | [
"Handle",
"a",
"connection",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/example/synchronous_server.py#L44-L106 |
24,612 | python-hyper/wsproto | wsproto/connection.py | Connection.receive_data | def receive_data(self, data):
# type: (bytes) -> None
"""
Pass some received data to the connection for handling.
A list of events that the remote peer triggered by sending this data can
be retrieved with :meth:`~wsproto.connection.Connection.events`.
:param data: The data received from the remote peer on the network.
:type data: ``bytes``
"""
if data is None:
# "If _The WebSocket Connection is Closed_ and no Close control
# frame was received by the endpoint (such as could occur if the
# underlying transport connection is lost), _The WebSocket
# Connection Close Code_ is considered to be 1006."
self._events.append(CloseConnection(code=CloseReason.ABNORMAL_CLOSURE))
self._state = ConnectionState.CLOSED
return
if self.state in (ConnectionState.OPEN, ConnectionState.LOCAL_CLOSING):
self._proto.receive_bytes(data)
elif self.state is ConnectionState.CLOSED:
raise LocalProtocolError("Connection already closed.") | python | def receive_data(self, data):
# type: (bytes) -> None
if data is None:
# "If _The WebSocket Connection is Closed_ and no Close control
# frame was received by the endpoint (such as could occur if the
# underlying transport connection is lost), _The WebSocket
# Connection Close Code_ is considered to be 1006."
self._events.append(CloseConnection(code=CloseReason.ABNORMAL_CLOSURE))
self._state = ConnectionState.CLOSED
return
if self.state in (ConnectionState.OPEN, ConnectionState.LOCAL_CLOSING):
self._proto.receive_bytes(data)
elif self.state is ConnectionState.CLOSED:
raise LocalProtocolError("Connection already closed.") | [
"def",
"receive_data",
"(",
"self",
",",
"data",
")",
":",
"# type: (bytes) -> None",
"if",
"data",
"is",
"None",
":",
"# \"If _The WebSocket Connection is Closed_ and no Close control",
"# frame was received by the endpoint (such as could occur if the",
"# underlying transport conne... | Pass some received data to the connection for handling.
A list of events that the remote peer triggered by sending this data can
be retrieved with :meth:`~wsproto.connection.Connection.events`.
:param data: The data received from the remote peer on the network.
:type data: ``bytes`` | [
"Pass",
"some",
"received",
"data",
"to",
"the",
"connection",
"for",
"handling",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/connection.py#L92-L116 |
24,613 | python-hyper/wsproto | wsproto/connection.py | Connection.events | def events(self):
# type: () -> Generator[Event, None, None]
"""
Return a generator that provides any events that have been generated
by protocol activity.
:returns: generator of :class:`Event <wsproto.events.Event>` subclasses
"""
while self._events:
yield self._events.popleft()
try:
for frame in self._proto.received_frames():
if frame.opcode is Opcode.PING:
assert frame.frame_finished and frame.message_finished
yield Ping(payload=frame.payload)
elif frame.opcode is Opcode.PONG:
assert frame.frame_finished and frame.message_finished
yield Pong(payload=frame.payload)
elif frame.opcode is Opcode.CLOSE:
code, reason = frame.payload
if self.state is ConnectionState.LOCAL_CLOSING:
self._state = ConnectionState.CLOSED
else:
self._state = ConnectionState.REMOTE_CLOSING
yield CloseConnection(code=code, reason=reason)
elif frame.opcode is Opcode.TEXT:
yield TextMessage(
data=frame.payload,
frame_finished=frame.frame_finished,
message_finished=frame.message_finished,
)
elif frame.opcode is Opcode.BINARY:
yield BytesMessage(
data=frame.payload,
frame_finished=frame.frame_finished,
message_finished=frame.message_finished,
)
except ParseFailed as exc:
yield CloseConnection(code=exc.code, reason=str(exc)) | python | def events(self):
# type: () -> Generator[Event, None, None]
while self._events:
yield self._events.popleft()
try:
for frame in self._proto.received_frames():
if frame.opcode is Opcode.PING:
assert frame.frame_finished and frame.message_finished
yield Ping(payload=frame.payload)
elif frame.opcode is Opcode.PONG:
assert frame.frame_finished and frame.message_finished
yield Pong(payload=frame.payload)
elif frame.opcode is Opcode.CLOSE:
code, reason = frame.payload
if self.state is ConnectionState.LOCAL_CLOSING:
self._state = ConnectionState.CLOSED
else:
self._state = ConnectionState.REMOTE_CLOSING
yield CloseConnection(code=code, reason=reason)
elif frame.opcode is Opcode.TEXT:
yield TextMessage(
data=frame.payload,
frame_finished=frame.frame_finished,
message_finished=frame.message_finished,
)
elif frame.opcode is Opcode.BINARY:
yield BytesMessage(
data=frame.payload,
frame_finished=frame.frame_finished,
message_finished=frame.message_finished,
)
except ParseFailed as exc:
yield CloseConnection(code=exc.code, reason=str(exc)) | [
"def",
"events",
"(",
"self",
")",
":",
"# type: () -> Generator[Event, None, None]",
"while",
"self",
".",
"_events",
":",
"yield",
"self",
".",
"_events",
".",
"popleft",
"(",
")",
"try",
":",
"for",
"frame",
"in",
"self",
".",
"_proto",
".",
"received_fra... | Return a generator that provides any events that have been generated
by protocol activity.
:returns: generator of :class:`Event <wsproto.events.Event>` subclasses | [
"Return",
"a",
"generator",
"that",
"provides",
"any",
"events",
"that",
"have",
"been",
"generated",
"by",
"protocol",
"activity",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/connection.py#L118-L161 |
24,614 | python-hyper/wsproto | wsproto/handshake.py | server_extensions_handshake | def server_extensions_handshake(requested, supported):
# type: (List[str], List[Extension]) -> Optional[bytes]
"""Agree on the extensions to use returning an appropriate header value.
This returns None if there are no agreed extensions
"""
accepts = {}
for offer in requested:
name = offer.split(";", 1)[0].strip()
for extension in supported:
if extension.name == name:
accept = extension.accept(offer)
if accept is True:
accepts[extension.name] = True
elif accept is not False and accept is not None:
accepts[extension.name] = accept.encode("ascii")
if accepts:
extensions = []
for name, params in accepts.items():
if params is True:
extensions.append(name.encode("ascii"))
else:
# py34 annoyance: doesn't support bytestring formatting
params = params.decode("ascii")
if params == "":
extensions.append(("%s" % (name)).encode("ascii"))
else:
extensions.append(("%s; %s" % (name, params)).encode("ascii"))
return b", ".join(extensions)
return None | python | def server_extensions_handshake(requested, supported):
# type: (List[str], List[Extension]) -> Optional[bytes]
accepts = {}
for offer in requested:
name = offer.split(";", 1)[0].strip()
for extension in supported:
if extension.name == name:
accept = extension.accept(offer)
if accept is True:
accepts[extension.name] = True
elif accept is not False and accept is not None:
accepts[extension.name] = accept.encode("ascii")
if accepts:
extensions = []
for name, params in accepts.items():
if params is True:
extensions.append(name.encode("ascii"))
else:
# py34 annoyance: doesn't support bytestring formatting
params = params.decode("ascii")
if params == "":
extensions.append(("%s" % (name)).encode("ascii"))
else:
extensions.append(("%s; %s" % (name, params)).encode("ascii"))
return b", ".join(extensions)
return None | [
"def",
"server_extensions_handshake",
"(",
"requested",
",",
"supported",
")",
":",
"# type: (List[str], List[Extension]) -> Optional[bytes]",
"accepts",
"=",
"{",
"}",
"for",
"offer",
"in",
"requested",
":",
"name",
"=",
"offer",
".",
"split",
"(",
"\";\"",
",",
... | Agree on the extensions to use returning an appropriate header value.
This returns None if there are no agreed extensions | [
"Agree",
"on",
"the",
"extensions",
"to",
"use",
"returning",
"an",
"appropriate",
"header",
"value",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/handshake.py#L411-L442 |
24,615 | python-hyper/wsproto | wsproto/handshake.py | H11Handshake.initiate_upgrade_connection | def initiate_upgrade_connection(self, headers, path):
# type: (List[Tuple[bytes, bytes]], str) -> None
"""Initiate an upgrade connection.
This should be used if the request has already be received and
parsed.
"""
if self.client:
raise LocalProtocolError(
"Cannot initiate an upgrade connection when acting as the client"
)
upgrade_request = h11.Request(method=b"GET", target=path, headers=headers)
h11_client = h11.Connection(h11.CLIENT)
self.receive_data(h11_client.send(upgrade_request)) | python | def initiate_upgrade_connection(self, headers, path):
# type: (List[Tuple[bytes, bytes]], str) -> None
if self.client:
raise LocalProtocolError(
"Cannot initiate an upgrade connection when acting as the client"
)
upgrade_request = h11.Request(method=b"GET", target=path, headers=headers)
h11_client = h11.Connection(h11.CLIENT)
self.receive_data(h11_client.send(upgrade_request)) | [
"def",
"initiate_upgrade_connection",
"(",
"self",
",",
"headers",
",",
"path",
")",
":",
"# type: (List[Tuple[bytes, bytes]], str) -> None",
"if",
"self",
".",
"client",
":",
"raise",
"LocalProtocolError",
"(",
"\"Cannot initiate an upgrade connection when acting as the client... | Initiate an upgrade connection.
This should be used if the request has already be received and
parsed. | [
"Initiate",
"an",
"upgrade",
"connection",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/handshake.py#L61-L75 |
24,616 | python-hyper/wsproto | wsproto/handshake.py | H11Handshake.send | def send(self, event):
# type(Event) -> bytes
"""Send an event to the remote.
This will return the bytes to send based on the event or raise
a LocalProtocolError if the event is not valid given the
state.
"""
data = b""
if isinstance(event, Request):
data += self._initiate_connection(event)
elif isinstance(event, AcceptConnection):
data += self._accept(event)
elif isinstance(event, RejectConnection):
data += self._reject(event)
elif isinstance(event, RejectData):
data += self._send_reject_data(event)
else:
raise LocalProtocolError(
"Event {} cannot be sent during the handshake".format(event)
)
return data | python | def send(self, event):
# type(Event) -> bytes
data = b""
if isinstance(event, Request):
data += self._initiate_connection(event)
elif isinstance(event, AcceptConnection):
data += self._accept(event)
elif isinstance(event, RejectConnection):
data += self._reject(event)
elif isinstance(event, RejectData):
data += self._send_reject_data(event)
else:
raise LocalProtocolError(
"Event {} cannot be sent during the handshake".format(event)
)
return data | [
"def",
"send",
"(",
"self",
",",
"event",
")",
":",
"# type(Event) -> bytes",
"data",
"=",
"b\"\"",
"if",
"isinstance",
"(",
"event",
",",
"Request",
")",
":",
"data",
"+=",
"self",
".",
"_initiate_connection",
"(",
"event",
")",
"elif",
"isinstance",
"(",... | Send an event to the remote.
This will return the bytes to send based on the event or raise
a LocalProtocolError if the event is not valid given the
state. | [
"Send",
"an",
"event",
"to",
"the",
"remote",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/handshake.py#L77-L99 |
24,617 | python-hyper/wsproto | wsproto/handshake.py | H11Handshake.receive_data | def receive_data(self, data):
# type: (bytes) -> None
"""Receive data from the remote.
A list of events that the remote peer triggered by sending
this data can be retrieved with :meth:`events`.
"""
self._h11_connection.receive_data(data)
while True:
try:
event = self._h11_connection.next_event()
except h11.RemoteProtocolError:
raise RemoteProtocolError(
"Bad HTTP message", event_hint=RejectConnection()
)
if (
isinstance(event, h11.ConnectionClosed)
or event is h11.NEED_DATA
or event is h11.PAUSED
):
break
if self.client:
if isinstance(event, h11.InformationalResponse):
if event.status_code == 101:
self._events.append(self._establish_client_connection(event))
else:
self._events.append(
RejectConnection(
headers=event.headers,
status_code=event.status_code,
has_body=False,
)
)
self._state = ConnectionState.CLOSED
elif isinstance(event, h11.Response):
self._state = ConnectionState.REJECTING
self._events.append(
RejectConnection(
headers=event.headers,
status_code=event.status_code,
has_body=True,
)
)
elif isinstance(event, h11.Data):
self._events.append(
RejectData(data=event.data, body_finished=False)
)
elif isinstance(event, h11.EndOfMessage):
self._events.append(RejectData(data=b"", body_finished=True))
self._state = ConnectionState.CLOSED
else:
if isinstance(event, h11.Request):
self._events.append(self._process_connection_request(event)) | python | def receive_data(self, data):
# type: (bytes) -> None
self._h11_connection.receive_data(data)
while True:
try:
event = self._h11_connection.next_event()
except h11.RemoteProtocolError:
raise RemoteProtocolError(
"Bad HTTP message", event_hint=RejectConnection()
)
if (
isinstance(event, h11.ConnectionClosed)
or event is h11.NEED_DATA
or event is h11.PAUSED
):
break
if self.client:
if isinstance(event, h11.InformationalResponse):
if event.status_code == 101:
self._events.append(self._establish_client_connection(event))
else:
self._events.append(
RejectConnection(
headers=event.headers,
status_code=event.status_code,
has_body=False,
)
)
self._state = ConnectionState.CLOSED
elif isinstance(event, h11.Response):
self._state = ConnectionState.REJECTING
self._events.append(
RejectConnection(
headers=event.headers,
status_code=event.status_code,
has_body=True,
)
)
elif isinstance(event, h11.Data):
self._events.append(
RejectData(data=event.data, body_finished=False)
)
elif isinstance(event, h11.EndOfMessage):
self._events.append(RejectData(data=b"", body_finished=True))
self._state = ConnectionState.CLOSED
else:
if isinstance(event, h11.Request):
self._events.append(self._process_connection_request(event)) | [
"def",
"receive_data",
"(",
"self",
",",
"data",
")",
":",
"# type: (bytes) -> None",
"self",
".",
"_h11_connection",
".",
"receive_data",
"(",
"data",
")",
"while",
"True",
":",
"try",
":",
"event",
"=",
"self",
".",
"_h11_connection",
".",
"next_event",
"(... | Receive data from the remote.
A list of events that the remote peer triggered by sending
this data can be retrieved with :meth:`events`. | [
"Receive",
"data",
"from",
"the",
"remote",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/wsproto/handshake.py#L101-L155 |
24,618 | python-hyper/wsproto | example/synchronous_client.py | net_send | def net_send(out_data, conn):
''' Write pending data from websocket to network. '''
print('Sending {} bytes'.format(len(out_data)))
conn.send(out_data) | python | def net_send(out_data, conn):
''' Write pending data from websocket to network. '''
print('Sending {} bytes'.format(len(out_data)))
conn.send(out_data) | [
"def",
"net_send",
"(",
"out_data",
",",
"conn",
")",
":",
"print",
"(",
"'Sending {} bytes'",
".",
"format",
"(",
"len",
"(",
"out_data",
")",
")",
")",
"conn",
".",
"send",
"(",
"out_data",
")"
] | Write pending data from websocket to network. | [
"Write",
"pending",
"data",
"from",
"websocket",
"to",
"network",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/example/synchronous_client.py#L106-L109 |
24,619 | python-hyper/wsproto | example/synchronous_client.py | net_recv | def net_recv(ws, conn):
''' Read pending data from network into websocket. '''
in_data = conn.recv(RECEIVE_BYTES)
if not in_data:
# A receive of zero bytes indicates the TCP socket has been closed. We
# need to pass None to wsproto to update its internal state.
print('Received 0 bytes (connection closed)')
ws.receive_data(None)
else:
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data) | python | def net_recv(ws, conn):
''' Read pending data from network into websocket. '''
in_data = conn.recv(RECEIVE_BYTES)
if not in_data:
# A receive of zero bytes indicates the TCP socket has been closed. We
# need to pass None to wsproto to update its internal state.
print('Received 0 bytes (connection closed)')
ws.receive_data(None)
else:
print('Received {} bytes'.format(len(in_data)))
ws.receive_data(in_data) | [
"def",
"net_recv",
"(",
"ws",
",",
"conn",
")",
":",
"in_data",
"=",
"conn",
".",
"recv",
"(",
"RECEIVE_BYTES",
")",
"if",
"not",
"in_data",
":",
"# A receive of zero bytes indicates the TCP socket has been closed. We",
"# need to pass None to wsproto to update its internal... | Read pending data from network into websocket. | [
"Read",
"pending",
"data",
"from",
"network",
"into",
"websocket",
"."
] | a7abcc5a9f7ad126668afb0cc9932da08c87f40f | https://github.com/python-hyper/wsproto/blob/a7abcc5a9f7ad126668afb0cc9932da08c87f40f/example/synchronous_client.py#L112-L122 |
24,620 | ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.check_filter | def check_filter(filter, layer=Layer.NETWORK):
"""
Checks if the given packet filter string is valid with respect to the filter language.
The remapped function is WinDivertHelperCheckFilter::
BOOL WinDivertHelperCheckFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__out_opt const char **errorStr,
__out_opt UINT *errorPos
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_check_filter
:return: A tuple (res, pos, msg) with check result in 'res' human readable description of the error in 'msg' and the error's position in 'pos'.
"""
res, pos, msg = False, c_uint(), c_char_p()
try:
res = windivert_dll.WinDivertHelperCheckFilter(filter.encode(), layer, byref(msg), byref(pos))
except OSError:
pass
return res, pos.value, msg.value.decode() | python | def check_filter(filter, layer=Layer.NETWORK):
res, pos, msg = False, c_uint(), c_char_p()
try:
res = windivert_dll.WinDivertHelperCheckFilter(filter.encode(), layer, byref(msg), byref(pos))
except OSError:
pass
return res, pos.value, msg.value.decode() | [
"def",
"check_filter",
"(",
"filter",
",",
"layer",
"=",
"Layer",
".",
"NETWORK",
")",
":",
"res",
",",
"pos",
",",
"msg",
"=",
"False",
",",
"c_uint",
"(",
")",
",",
"c_char_p",
"(",
")",
"try",
":",
"res",
"=",
"windivert_dll",
".",
"WinDivertHelpe... | Checks if the given packet filter string is valid with respect to the filter language.
The remapped function is WinDivertHelperCheckFilter::
BOOL WinDivertHelperCheckFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__out_opt const char **errorStr,
__out_opt UINT *errorPos
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_check_filter
:return: A tuple (res, pos, msg) with check result in 'res' human readable description of the error in 'msg' and the error's position in 'pos'. | [
"Checks",
"if",
"the",
"given",
"packet",
"filter",
"string",
"is",
"valid",
"with",
"respect",
"to",
"the",
"filter",
"language",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L102-L124 |
24,621 | ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.recv | def recv(self, bufsize=DEFAULT_PACKET_BUFFER_SIZE):
"""
Receives a diverted packet that matched the filter.
The remapped function is WinDivertRecv::
BOOL WinDivertRecv(
__in HANDLE handle,
__out PVOID pPacket,
__in UINT packetLen,
__out_opt PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *recvLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_recv
:return: The return value is a `pydivert.Packet`.
"""
if self._handle is None:
raise RuntimeError("WinDivert handle is not open")
packet = bytearray(bufsize)
packet_ = (c_char * bufsize).from_buffer(packet)
address = windivert_dll.WinDivertAddress()
recv_len = c_uint(0)
windivert_dll.WinDivertRecv(self._handle, packet_, bufsize, byref(address), byref(recv_len))
return Packet(
memoryview(packet)[:recv_len.value],
(address.IfIdx, address.SubIfIdx),
Direction(address.Direction)
) | python | def recv(self, bufsize=DEFAULT_PACKET_BUFFER_SIZE):
if self._handle is None:
raise RuntimeError("WinDivert handle is not open")
packet = bytearray(bufsize)
packet_ = (c_char * bufsize).from_buffer(packet)
address = windivert_dll.WinDivertAddress()
recv_len = c_uint(0)
windivert_dll.WinDivertRecv(self._handle, packet_, bufsize, byref(address), byref(recv_len))
return Packet(
memoryview(packet)[:recv_len.value],
(address.IfIdx, address.SubIfIdx),
Direction(address.Direction)
) | [
"def",
"recv",
"(",
"self",
",",
"bufsize",
"=",
"DEFAULT_PACKET_BUFFER_SIZE",
")",
":",
"if",
"self",
".",
"_handle",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"WinDivert handle is not open\"",
")",
"packet",
"=",
"bytearray",
"(",
"bufsize",
")",
"p... | Receives a diverted packet that matched the filter.
The remapped function is WinDivertRecv::
BOOL WinDivertRecv(
__in HANDLE handle,
__out PVOID pPacket,
__in UINT packetLen,
__out_opt PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *recvLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_recv
:return: The return value is a `pydivert.Packet`. | [
"Receives",
"a",
"diverted",
"packet",
"that",
"matched",
"the",
"filter",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L172-L202 |
24,622 | ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.send | def send(self, packet, recalculate_checksum=True):
"""
Injects a packet into the network stack.
Recalculates the checksum before sending unless recalculate_checksum=False is passed.
The injected packet may be one received from recv(), or a modified version, or a completely new packet.
Injected packets can be captured and diverted again by other WinDivert handles with lower priorities.
The remapped function is WinDivertSend::
BOOL WinDivertSend(
__in HANDLE handle,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *sendLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_send
:return: The return value is the number of bytes actually sent.
"""
if recalculate_checksum:
packet.recalculate_checksums()
send_len = c_uint(0)
if PY2:
# .from_buffer(memoryview) does not work on PY2
buff = bytearray(packet.raw)
else:
buff = packet.raw
buff = (c_char * len(packet.raw)).from_buffer(buff)
windivert_dll.WinDivertSend(self._handle, buff, len(packet.raw), byref(packet.wd_addr),
byref(send_len))
return send_len | python | def send(self, packet, recalculate_checksum=True):
if recalculate_checksum:
packet.recalculate_checksums()
send_len = c_uint(0)
if PY2:
# .from_buffer(memoryview) does not work on PY2
buff = bytearray(packet.raw)
else:
buff = packet.raw
buff = (c_char * len(packet.raw)).from_buffer(buff)
windivert_dll.WinDivertSend(self._handle, buff, len(packet.raw), byref(packet.wd_addr),
byref(send_len))
return send_len | [
"def",
"send",
"(",
"self",
",",
"packet",
",",
"recalculate_checksum",
"=",
"True",
")",
":",
"if",
"recalculate_checksum",
":",
"packet",
".",
"recalculate_checksums",
"(",
")",
"send_len",
"=",
"c_uint",
"(",
"0",
")",
"if",
"PY2",
":",
"# .from_buffer(me... | Injects a packet into the network stack.
Recalculates the checksum before sending unless recalculate_checksum=False is passed.
The injected packet may be one received from recv(), or a modified version, or a completely new packet.
Injected packets can be captured and diverted again by other WinDivert handles with lower priorities.
The remapped function is WinDivertSend::
BOOL WinDivertSend(
__in HANDLE handle,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr,
__out_opt UINT *sendLen
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_send
:return: The return value is the number of bytes actually sent. | [
"Injects",
"a",
"packet",
"into",
"the",
"network",
"stack",
".",
"Recalculates",
"the",
"checksum",
"before",
"sending",
"unless",
"recalculate_checksum",
"=",
"False",
"is",
"passed",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L204-L238 |
24,623 | ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.get_param | def get_param(self, name):
"""
Get a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is WinDivertGetParam::
BOOL WinDivertGetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__out UINT64 *pValue
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_get_param
:return: The parameter value.
"""
value = c_uint64(0)
windivert_dll.WinDivertGetParam(self._handle, name, byref(value))
return value.value | python | def get_param(self, name):
value = c_uint64(0)
windivert_dll.WinDivertGetParam(self._handle, name, byref(value))
return value.value | [
"def",
"get_param",
"(",
"self",
",",
"name",
")",
":",
"value",
"=",
"c_uint64",
"(",
"0",
")",
"windivert_dll",
".",
"WinDivertGetParam",
"(",
"self",
".",
"_handle",
",",
"name",
",",
"byref",
"(",
"value",
")",
")",
"return",
"value",
".",
"value"
... | Get a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is WinDivertGetParam::
BOOL WinDivertGetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__out UINT64 *pValue
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_get_param
:return: The parameter value. | [
"Get",
"a",
"WinDivert",
"parameter",
".",
"See",
"pydivert",
".",
"Param",
"for",
"the",
"list",
"of",
"parameters",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L240-L258 |
24,624 | ffalcinelli/pydivert | pydivert/windivert.py | WinDivert.set_param | def set_param(self, name, value):
"""
Set a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is DivertSetParam::
BOOL WinDivertSetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__in UINT64 value
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_set_param
"""
return windivert_dll.WinDivertSetParam(self._handle, name, value) | python | def set_param(self, name, value):
return windivert_dll.WinDivertSetParam(self._handle, name, value) | [
"def",
"set_param",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"return",
"windivert_dll",
".",
"WinDivertSetParam",
"(",
"self",
".",
"_handle",
",",
"name",
",",
"value",
")"
] | Set a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is DivertSetParam::
BOOL WinDivertSetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__in UINT64 value
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_set_param | [
"Set",
"a",
"WinDivert",
"parameter",
".",
"See",
"pydivert",
".",
"Param",
"for",
"the",
"list",
"of",
"parameters",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert.py#L260-L274 |
24,625 | ffalcinelli/pydivert | pydivert/windivert_dll/__init__.py | _init | def _init():
"""
Lazy-load DLL, replace proxy functions with actual ones.
"""
i = instance()
for funcname in WINDIVERT_FUNCTIONS:
func = getattr(i, funcname)
func = raise_on_error(func)
setattr(_module, funcname, func) | python | def _init():
i = instance()
for funcname in WINDIVERT_FUNCTIONS:
func = getattr(i, funcname)
func = raise_on_error(func)
setattr(_module, funcname, func) | [
"def",
"_init",
"(",
")",
":",
"i",
"=",
"instance",
"(",
")",
"for",
"funcname",
"in",
"WINDIVERT_FUNCTIONS",
":",
"func",
"=",
"getattr",
"(",
"i",
",",
"funcname",
")",
"func",
"=",
"raise_on_error",
"(",
"func",
")",
"setattr",
"(",
"_module",
",",... | Lazy-load DLL, replace proxy functions with actual ones. | [
"Lazy",
"-",
"load",
"DLL",
"replace",
"proxy",
"functions",
"with",
"actual",
"ones",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert_dll/__init__.py#L99-L107 |
24,626 | ffalcinelli/pydivert | pydivert/windivert_dll/__init__.py | _mkprox | def _mkprox(funcname):
"""
Make lazy-init proxy function.
"""
def prox(*args, **kwargs):
_init()
return getattr(_module, funcname)(*args, **kwargs)
return prox | python | def _mkprox(funcname):
def prox(*args, **kwargs):
_init()
return getattr(_module, funcname)(*args, **kwargs)
return prox | [
"def",
"_mkprox",
"(",
"funcname",
")",
":",
"def",
"prox",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_init",
"(",
")",
"return",
"getattr",
"(",
"_module",
",",
"funcname",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return... | Make lazy-init proxy function. | [
"Make",
"lazy",
"-",
"init",
"proxy",
"function",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/windivert_dll/__init__.py#L110-L119 |
24,627 | ffalcinelli/pydivert | pydivert/packet/ip.py | IPHeader.src_addr | def src_addr(self):
"""
The packet source address.
"""
try:
return socket.inet_ntop(self._af, self.raw[self._src_addr].tobytes())
except (ValueError, socket.error):
pass | python | def src_addr(self):
try:
return socket.inet_ntop(self._af, self.raw[self._src_addr].tobytes())
except (ValueError, socket.error):
pass | [
"def",
"src_addr",
"(",
"self",
")",
":",
"try",
":",
"return",
"socket",
".",
"inet_ntop",
"(",
"self",
".",
"_af",
",",
"self",
".",
"raw",
"[",
"self",
".",
"_src_addr",
"]",
".",
"tobytes",
"(",
")",
")",
"except",
"(",
"ValueError",
",",
"sock... | The packet source address. | [
"The",
"packet",
"source",
"address",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/ip.py#L29-L36 |
24,628 | ffalcinelli/pydivert | pydivert/packet/ip.py | IPHeader.dst_addr | def dst_addr(self):
"""
The packet destination address.
"""
try:
return socket.inet_ntop(self._af, self.raw[self._dst_addr].tobytes())
except (ValueError, socket.error):
pass | python | def dst_addr(self):
try:
return socket.inet_ntop(self._af, self.raw[self._dst_addr].tobytes())
except (ValueError, socket.error):
pass | [
"def",
"dst_addr",
"(",
"self",
")",
":",
"try",
":",
"return",
"socket",
".",
"inet_ntop",
"(",
"self",
".",
"_af",
",",
"self",
".",
"raw",
"[",
"self",
".",
"_dst_addr",
"]",
".",
"tobytes",
"(",
")",
")",
"except",
"(",
"ValueError",
",",
"sock... | The packet destination address. | [
"The",
"packet",
"destination",
"address",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/ip.py#L43-L50 |
24,629 | ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.icmpv4 | def icmpv4(self):
"""
- An ICMPv4Header instance, if the packet is valid ICMPv4.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.ICMP:
return ICMPv4Header(self, proto_start) | python | def icmpv4(self):
ipproto, proto_start = self.protocol
if ipproto == Protocol.ICMP:
return ICMPv4Header(self, proto_start) | [
"def",
"icmpv4",
"(",
"self",
")",
":",
"ipproto",
",",
"proto_start",
"=",
"self",
".",
"protocol",
"if",
"ipproto",
"==",
"Protocol",
".",
"ICMP",
":",
"return",
"ICMPv4Header",
"(",
"self",
",",
"proto_start",
")"
] | - An ICMPv4Header instance, if the packet is valid ICMPv4.
- None, otherwise. | [
"-",
"An",
"ICMPv4Header",
"instance",
"if",
"the",
"packet",
"is",
"valid",
"ICMPv4",
".",
"-",
"None",
"otherwise",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L176-L183 |
24,630 | ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.icmpv6 | def icmpv6(self):
"""
- An ICMPv6Header instance, if the packet is valid ICMPv6.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.ICMPV6:
return ICMPv6Header(self, proto_start) | python | def icmpv6(self):
ipproto, proto_start = self.protocol
if ipproto == Protocol.ICMPV6:
return ICMPv6Header(self, proto_start) | [
"def",
"icmpv6",
"(",
"self",
")",
":",
"ipproto",
",",
"proto_start",
"=",
"self",
".",
"protocol",
"if",
"ipproto",
"==",
"Protocol",
".",
"ICMPV6",
":",
"return",
"ICMPv6Header",
"(",
"self",
",",
"proto_start",
")"
] | - An ICMPv6Header instance, if the packet is valid ICMPv6.
- None, otherwise. | [
"-",
"An",
"ICMPv6Header",
"instance",
"if",
"the",
"packet",
"is",
"valid",
"ICMPv6",
".",
"-",
"None",
"otherwise",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L186-L193 |
24,631 | ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.tcp | def tcp(self):
"""
- An TCPHeader instance, if the packet is valid TCP.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.TCP:
return TCPHeader(self, proto_start) | python | def tcp(self):
ipproto, proto_start = self.protocol
if ipproto == Protocol.TCP:
return TCPHeader(self, proto_start) | [
"def",
"tcp",
"(",
"self",
")",
":",
"ipproto",
",",
"proto_start",
"=",
"self",
".",
"protocol",
"if",
"ipproto",
"==",
"Protocol",
".",
"TCP",
":",
"return",
"TCPHeader",
"(",
"self",
",",
"proto_start",
")"
] | - An TCPHeader instance, if the packet is valid TCP.
- None, otherwise. | [
"-",
"An",
"TCPHeader",
"instance",
"if",
"the",
"packet",
"is",
"valid",
"TCP",
".",
"-",
"None",
"otherwise",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L204-L211 |
24,632 | ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.udp | def udp(self):
"""
- An TCPHeader instance, if the packet is valid UDP.
- None, otherwise.
"""
ipproto, proto_start = self.protocol
if ipproto == Protocol.UDP:
return UDPHeader(self, proto_start) | python | def udp(self):
ipproto, proto_start = self.protocol
if ipproto == Protocol.UDP:
return UDPHeader(self, proto_start) | [
"def",
"udp",
"(",
"self",
")",
":",
"ipproto",
",",
"proto_start",
"=",
"self",
".",
"protocol",
"if",
"ipproto",
"==",
"Protocol",
".",
"UDP",
":",
"return",
"UDPHeader",
"(",
"self",
",",
"proto_start",
")"
] | - An TCPHeader instance, if the packet is valid UDP.
- None, otherwise. | [
"-",
"An",
"TCPHeader",
"instance",
"if",
"the",
"packet",
"is",
"valid",
"UDP",
".",
"-",
"None",
"otherwise",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L214-L221 |
24,633 | ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet._payload | def _payload(self):
"""header that implements PayloadMixin"""
return self.tcp or self.udp or self.icmpv4 or self.icmpv6 | python | def _payload(self):
return self.tcp or self.udp or self.icmpv4 or self.icmpv6 | [
"def",
"_payload",
"(",
"self",
")",
":",
"return",
"self",
".",
"tcp",
"or",
"self",
".",
"udp",
"or",
"self",
".",
"icmpv4",
"or",
"self",
".",
"icmpv6"
] | header that implements PayloadMixin | [
"header",
"that",
"implements",
"PayloadMixin"
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L229-L231 |
24,634 | ffalcinelli/pydivert | pydivert/packet/__init__.py | Packet.matches | def matches(self, filter, layer=Layer.NETWORK):
"""
Evaluates the packet against the given packet filter string.
The remapped function is::
BOOL WinDivertHelperEvalFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_eval_filter
:param filter: The filter string.
:param layer: The network layer.
:return: True if the packet matches, and False otherwise.
"""
buff, buff_ = self.__to_buffers()
return windivert_dll.WinDivertHelperEvalFilter(filter.encode(), layer, ctypes.byref(buff_), len(self.raw),
ctypes.byref(self.wd_addr)) | python | def matches(self, filter, layer=Layer.NETWORK):
buff, buff_ = self.__to_buffers()
return windivert_dll.WinDivertHelperEvalFilter(filter.encode(), layer, ctypes.byref(buff_), len(self.raw),
ctypes.byref(self.wd_addr)) | [
"def",
"matches",
"(",
"self",
",",
"filter",
",",
"layer",
"=",
"Layer",
".",
"NETWORK",
")",
":",
"buff",
",",
"buff_",
"=",
"self",
".",
"__to_buffers",
"(",
")",
"return",
"windivert_dll",
".",
"WinDivertHelperEvalFilter",
"(",
"filter",
".",
"encode",... | Evaluates the packet against the given packet filter string.
The remapped function is::
BOOL WinDivertHelperEvalFilter(
__in const char *filter,
__in WINDIVERT_LAYER layer,
__in PVOID pPacket,
__in UINT packetLen,
__in PWINDIVERT_ADDRESS pAddr
);
See: https://reqrypt.org/windivert-doc.html#divert_helper_eval_filter
:param filter: The filter string.
:param layer: The network layer.
:return: True if the packet matches, and False otherwise. | [
"Evaluates",
"the",
"packet",
"against",
"the",
"given",
"packet",
"filter",
"string",
"."
] | f75eba4126c527b5a43ace0a49369c7479cf5ee8 | https://github.com/ffalcinelli/pydivert/blob/f75eba4126c527b5a43ace0a49369c7479cf5ee8/pydivert/packet/__init__.py#L328-L350 |
24,635 | floydhub/floyd-cli | floyd/cli/experiment.py | init | def init(project_name):
"""
Initialize new project at the current path.
After this you can run other FloydHub commands like status and run.
"""
project_obj = ProjectClient().get_by_name(project_name)
if not project_obj:
namespace, name = get_namespace_from_name(project_name)
create_project_base_url = "{}/projects/create".format(floyd.floyd_web_host)
create_project_url = "{}?name={}&namespace={}".format(create_project_base_url, name, namespace)
floyd_logger.info(('Project name does not yet exist on floydhub.com. '
'Create your new project on floydhub.com:\n\t%s'),
create_project_base_url)
webbrowser.open(create_project_url)
name = click.prompt('Press ENTER to use project name "%s" or enter a different name' % project_name, default=project_name, show_default=False)
project_name = name.strip() or project_name
project_obj = ProjectClient().get_by_name(project_name)
if not project_obj:
raise FloydException('Project "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % project_name)
namespace, name = get_namespace_from_name(project_name)
experiment_config = ExperimentConfig(name=name,
namespace=namespace,
family_id=project_obj.id)
ExperimentConfigManager.set_config(experiment_config)
FloydIgnoreManager.init()
yaml_config = read_yaml_config()
if not yaml_config:
copyfile(os.path.join(os.path.dirname(__file__), 'default_floyd.yml'), 'floyd.yml')
floyd_logger.info("Project \"%s\" initialized in current directory", project_name) | python | def init(project_name):
project_obj = ProjectClient().get_by_name(project_name)
if not project_obj:
namespace, name = get_namespace_from_name(project_name)
create_project_base_url = "{}/projects/create".format(floyd.floyd_web_host)
create_project_url = "{}?name={}&namespace={}".format(create_project_base_url, name, namespace)
floyd_logger.info(('Project name does not yet exist on floydhub.com. '
'Create your new project on floydhub.com:\n\t%s'),
create_project_base_url)
webbrowser.open(create_project_url)
name = click.prompt('Press ENTER to use project name "%s" or enter a different name' % project_name, default=project_name, show_default=False)
project_name = name.strip() or project_name
project_obj = ProjectClient().get_by_name(project_name)
if not project_obj:
raise FloydException('Project "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % project_name)
namespace, name = get_namespace_from_name(project_name)
experiment_config = ExperimentConfig(name=name,
namespace=namespace,
family_id=project_obj.id)
ExperimentConfigManager.set_config(experiment_config)
FloydIgnoreManager.init()
yaml_config = read_yaml_config()
if not yaml_config:
copyfile(os.path.join(os.path.dirname(__file__), 'default_floyd.yml'), 'floyd.yml')
floyd_logger.info("Project \"%s\" initialized in current directory", project_name) | [
"def",
"init",
"(",
"project_name",
")",
":",
"project_obj",
"=",
"ProjectClient",
"(",
")",
".",
"get_by_name",
"(",
"project_name",
")",
"if",
"not",
"project_obj",
":",
"namespace",
",",
"name",
"=",
"get_namespace_from_name",
"(",
"project_name",
")",
"cre... | Initialize new project at the current path.
After this you can run other FloydHub commands like status and run. | [
"Initialize",
"new",
"project",
"at",
"the",
"current",
"path",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L40-L77 |
24,636 | floydhub/floyd-cli | floyd/cli/experiment.py | status | def status(id):
"""
View status of all jobs in a project.
The command also accepts a specific job name.
"""
if id:
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
print_experiments([experiment])
else:
experiments = ExperimentClient().get_all()
print_experiments(experiments) | python | def status(id):
if id:
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
print_experiments([experiment])
else:
experiments = ExperimentClient().get_all()
print_experiments(experiments) | [
"def",
"status",
"(",
"id",
")",
":",
"if",
"id",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
"... | View status of all jobs in a project.
The command also accepts a specific job name. | [
"View",
"status",
"of",
"all",
"jobs",
"in",
"a",
"project",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L82-L97 |
24,637 | floydhub/floyd-cli | floyd/cli/experiment.py | print_experiments | def print_experiments(experiments):
"""
Prints job details in a table. Includes urls and mode parameters
"""
headers = ["JOB NAME", "CREATED", "STATUS", "DURATION(s)", "INSTANCE", "DESCRIPTION", "METRICS"]
expt_list = []
for experiment in experiments:
expt_list.append([normalize_job_name(experiment.name),
experiment.created_pretty, experiment.state,
experiment.duration_rounded, experiment.instance_type_trimmed,
experiment.description, format_metrics(experiment.latest_metrics)])
floyd_logger.info(tabulate(expt_list, headers=headers)) | python | def print_experiments(experiments):
headers = ["JOB NAME", "CREATED", "STATUS", "DURATION(s)", "INSTANCE", "DESCRIPTION", "METRICS"]
expt_list = []
for experiment in experiments:
expt_list.append([normalize_job_name(experiment.name),
experiment.created_pretty, experiment.state,
experiment.duration_rounded, experiment.instance_type_trimmed,
experiment.description, format_metrics(experiment.latest_metrics)])
floyd_logger.info(tabulate(expt_list, headers=headers)) | [
"def",
"print_experiments",
"(",
"experiments",
")",
":",
"headers",
"=",
"[",
"\"JOB NAME\"",
",",
"\"CREATED\"",
",",
"\"STATUS\"",
",",
"\"DURATION(s)\"",
",",
"\"INSTANCE\"",
",",
"\"DESCRIPTION\"",
",",
"\"METRICS\"",
"]",
"expt_list",
"=",
"[",
"]",
"for",... | Prints job details in a table. Includes urls and mode parameters | [
"Prints",
"job",
"details",
"in",
"a",
"table",
".",
"Includes",
"urls",
"and",
"mode",
"parameters"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L100-L111 |
24,638 | floydhub/floyd-cli | floyd/cli/experiment.py | clone | def clone(id, path):
"""
- Download all files from a job
Eg: alice/projects/mnist/1/
Note: This will download the files that were originally uploaded at
the start of the job.
- Download files in a specific path from a job
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
task_instance_id = get_module_task_instance_id(experiment.task_instances)
task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None
if not task_instance:
sys.exit("Cannot clone this version of the job. Try a different version.")
module = ModuleClient().get(task_instance.module_id) if task_instance else None
if path:
# Download a directory from Code
code_url = "{}/api/v1/download/artifacts/code/{}?is_dir=true&path={}".format(floyd.floyd_host,
experiment.id,
path)
else:
# Download the full Code
code_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
module.resource_id)
ExperimentClient().download_tar(url=code_url,
untar=True,
delete_after_untar=True) | python | def clone(id, path):
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
task_instance_id = get_module_task_instance_id(experiment.task_instances)
task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None
if not task_instance:
sys.exit("Cannot clone this version of the job. Try a different version.")
module = ModuleClient().get(task_instance.module_id) if task_instance else None
if path:
# Download a directory from Code
code_url = "{}/api/v1/download/artifacts/code/{}?is_dir=true&path={}".format(floyd.floyd_host,
experiment.id,
path)
else:
# Download the full Code
code_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
module.resource_id)
ExperimentClient().download_tar(url=code_url,
untar=True,
delete_after_untar=True) | [
"def",
"clone",
"(",
"id",
",",
"path",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
",",
"use_config",
"=",
"False",
")",
")",
"except",
"FloydException",
":",
"experiment",
"="... | - Download all files from a job
Eg: alice/projects/mnist/1/
Note: This will download the files that were originally uploaded at
the start of the job.
- Download files in a specific path from a job
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1 | [
"-",
"Download",
"all",
"files",
"from",
"a",
"job"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L124-L161 |
24,639 | floydhub/floyd-cli | floyd/cli/experiment.py | info | def info(job_name_or_id):
"""
View detailed information of a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(job_name_or_id))
except FloydException:
experiment = ExperimentClient().get(job_name_or_id)
task_instance_id = get_module_task_instance_id(experiment.task_instances)
task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None
normalized_job_name = normalize_job_name(experiment.name)
table = [["Job name", normalized_job_name],
["Created", experiment.created_pretty],
["Status", experiment.state], ["Duration(s)", experiment.duration_rounded],
["Instance", experiment.instance_type_trimmed],
["Description", experiment.description],
["Metrics", format_metrics(experiment.latest_metrics)]]
if task_instance and task_instance.mode in ['jupyter', 'serving']:
table.append(["Mode", task_instance.mode])
table.append(["Url", experiment.service_url])
if experiment.tensorboard_url:
table.append(["TensorBoard", experiment.tensorboard_url])
floyd_logger.info(tabulate(table)) | python | def info(job_name_or_id):
try:
experiment = ExperimentClient().get(normalize_job_name(job_name_or_id))
except FloydException:
experiment = ExperimentClient().get(job_name_or_id)
task_instance_id = get_module_task_instance_id(experiment.task_instances)
task_instance = TaskInstanceClient().get(task_instance_id) if task_instance_id else None
normalized_job_name = normalize_job_name(experiment.name)
table = [["Job name", normalized_job_name],
["Created", experiment.created_pretty],
["Status", experiment.state], ["Duration(s)", experiment.duration_rounded],
["Instance", experiment.instance_type_trimmed],
["Description", experiment.description],
["Metrics", format_metrics(experiment.latest_metrics)]]
if task_instance and task_instance.mode in ['jupyter', 'serving']:
table.append(["Mode", task_instance.mode])
table.append(["Url", experiment.service_url])
if experiment.tensorboard_url:
table.append(["TensorBoard", experiment.tensorboard_url])
floyd_logger.info(tabulate(table)) | [
"def",
"info",
"(",
"job_name_or_id",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"job_name_or_id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")... | View detailed information of a job. | [
"View",
"detailed",
"information",
"of",
"a",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L166-L189 |
24,640 | floydhub/floyd-cli | floyd/cli/experiment.py | follow_logs | def follow_logs(instance_log_id, sleep_duration=1):
"""
Follow the logs until Job termination.
"""
cur_idx = 0
job_terminated = False
while not job_terminated:
# Get the logs in a loop and log the new lines
log_file_contents = ResourceClient().get_content(instance_log_id)
print_output = log_file_contents[cur_idx:]
# Get the status of the Job from the current log line
job_terminated = any(terminal_output in print_output for terminal_output in TERMINATION_OUTPUT_LIST)
cur_idx += len(print_output)
sys.stdout.write(print_output)
sleep(sleep_duration) | python | def follow_logs(instance_log_id, sleep_duration=1):
cur_idx = 0
job_terminated = False
while not job_terminated:
# Get the logs in a loop and log the new lines
log_file_contents = ResourceClient().get_content(instance_log_id)
print_output = log_file_contents[cur_idx:]
# Get the status of the Job from the current log line
job_terminated = any(terminal_output in print_output for terminal_output in TERMINATION_OUTPUT_LIST)
cur_idx += len(print_output)
sys.stdout.write(print_output)
sleep(sleep_duration) | [
"def",
"follow_logs",
"(",
"instance_log_id",
",",
"sleep_duration",
"=",
"1",
")",
":",
"cur_idx",
"=",
"0",
"job_terminated",
"=",
"False",
"while",
"not",
"job_terminated",
":",
"# Get the logs in a loop and log the new lines",
"log_file_contents",
"=",
"ResourceClie... | Follow the logs until Job termination. | [
"Follow",
"the",
"logs",
"until",
"Job",
"termination",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L212-L227 |
24,641 | floydhub/floyd-cli | floyd/cli/experiment.py | logs | def logs(id, url, follow, sleep_duration=1):
"""
View the logs of a job.
To follow along a job in real time, use the --follow flag
"""
instance_log_id = get_log_id(id)
if url:
log_url = "{}/api/v1/resources/{}?content=true".format(
floyd.floyd_host, instance_log_id)
floyd_logger.info(log_url)
return
if follow:
floyd_logger.info("Launching job ...")
follow_logs(instance_log_id, sleep_duration)
else:
log_file_contents = ResourceClient().get_content(instance_log_id)
if len(log_file_contents.strip()):
floyd_logger.info(log_file_contents.rstrip())
else:
floyd_logger.info("Launching job now. Try after a few seconds.") | python | def logs(id, url, follow, sleep_duration=1):
instance_log_id = get_log_id(id)
if url:
log_url = "{}/api/v1/resources/{}?content=true".format(
floyd.floyd_host, instance_log_id)
floyd_logger.info(log_url)
return
if follow:
floyd_logger.info("Launching job ...")
follow_logs(instance_log_id, sleep_duration)
else:
log_file_contents = ResourceClient().get_content(instance_log_id)
if len(log_file_contents.strip()):
floyd_logger.info(log_file_contents.rstrip())
else:
floyd_logger.info("Launching job now. Try after a few seconds.") | [
"def",
"logs",
"(",
"id",
",",
"url",
",",
"follow",
",",
"sleep_duration",
"=",
"1",
")",
":",
"instance_log_id",
"=",
"get_log_id",
"(",
"id",
")",
"if",
"url",
":",
"log_url",
"=",
"\"{}/api/v1/resources/{}?content=true\"",
".",
"format",
"(",
"floyd",
... | View the logs of a job.
To follow along a job in real time, use the --follow flag | [
"View",
"the",
"logs",
"of",
"a",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L234-L256 |
24,642 | floydhub/floyd-cli | floyd/cli/experiment.py | output | def output(id, url):
"""
View the files from a job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
output_dir_url = "%s/%s/files" % (floyd.floyd_web_host, experiment.name)
if url:
floyd_logger.info(output_dir_url)
else:
floyd_logger.info("Opening output path in your browser ...")
webbrowser.open(output_dir_url) | python | def output(id, url):
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
output_dir_url = "%s/%s/files" % (floyd.floyd_web_host, experiment.name)
if url:
floyd_logger.info(output_dir_url)
else:
floyd_logger.info("Opening output path in your browser ...")
webbrowser.open(output_dir_url) | [
"def",
"output",
"(",
"id",
",",
"url",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
"... | View the files from a job. | [
"View",
"the",
"files",
"from",
"a",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L262-L276 |
24,643 | floydhub/floyd-cli | floyd/cli/experiment.py | stop | def stop(id):
"""
Stop a running job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
if experiment.state not in ["queued", "queue_scheduled", "running"]:
floyd_logger.info("Job in {} state cannot be stopped".format(experiment.state))
sys.exit(1)
if not ExperimentClient().stop(experiment.id):
floyd_logger.error("Failed to stop job")
sys.exit(1)
floyd_logger.info("Experiment shutdown request submitted. Check status to confirm shutdown") | python | def stop(id):
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
if experiment.state not in ["queued", "queue_scheduled", "running"]:
floyd_logger.info("Job in {} state cannot be stopped".format(experiment.state))
sys.exit(1)
if not ExperimentClient().stop(experiment.id):
floyd_logger.error("Failed to stop job")
sys.exit(1)
floyd_logger.info("Experiment shutdown request submitted. Check status to confirm shutdown") | [
"def",
"stop",
"(",
"id",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"("... | Stop a running job. | [
"Stop",
"a",
"running",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L281-L298 |
24,644 | floydhub/floyd-cli | floyd/cli/experiment.py | delete | def delete(names, yes):
"""
Delete a training job.
"""
failures = False
for name in names:
try:
experiment = ExperimentClient().get(normalize_job_name(name))
except FloydException:
experiment = ExperimentClient().get(name)
if not experiment:
failures = True
continue
if not yes and not click.confirm("Delete Job: {}?".format(experiment.name),
abort=False,
default=False):
floyd_logger.info("Job {}: Skipped.".format(experiment.name))
continue
if not ExperimentClient().delete(experiment.id):
failures = True
else:
floyd_logger.info("Job %s Deleted", experiment.name)
if failures:
sys.exit(1) | python | def delete(names, yes):
failures = False
for name in names:
try:
experiment = ExperimentClient().get(normalize_job_name(name))
except FloydException:
experiment = ExperimentClient().get(name)
if not experiment:
failures = True
continue
if not yes and not click.confirm("Delete Job: {}?".format(experiment.name),
abort=False,
default=False):
floyd_logger.info("Job {}: Skipped.".format(experiment.name))
continue
if not ExperimentClient().delete(experiment.id):
failures = True
else:
floyd_logger.info("Job %s Deleted", experiment.name)
if failures:
sys.exit(1) | [
"def",
"delete",
"(",
"names",
",",
"yes",
")",
":",
"failures",
"=",
"False",
"for",
"name",
"in",
"names",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"name",
")",
")",
"except",
"Floy... | Delete a training job. | [
"Delete",
"a",
"training",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/experiment.py#L304-L331 |
24,645 | floydhub/floyd-cli | floyd/cli/version.py | version | def version():
"""
View the current version of the CLI.
"""
import pkg_resources
version = pkg_resources.require(PROJECT_NAME)[0].version
floyd_logger.info(version) | python | def version():
import pkg_resources
version = pkg_resources.require(PROJECT_NAME)[0].version
floyd_logger.info(version) | [
"def",
"version",
"(",
")",
":",
"import",
"pkg_resources",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"PROJECT_NAME",
")",
"[",
"0",
"]",
".",
"version",
"floyd_logger",
".",
"info",
"(",
"version",
")"
] | View the current version of the CLI. | [
"View",
"the",
"current",
"version",
"of",
"the",
"CLI",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/version.py#L21-L27 |
24,646 | floydhub/floyd-cli | floyd/cli/data.py | init | def init(dataset_name):
"""
Initialize a new dataset at the current dir.
Then run the upload command to copy all the files in this
directory to FloydHub.
floyd data upload
"""
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
namespace, name = get_namespace_from_name(dataset_name)
create_dataset_base_url = "{}/datasets/create".format(floyd.floyd_web_host)
create_dataset_url = "{}?name={}&namespace={}".format(create_dataset_base_url, name, namespace)
floyd_logger.info(("Dataset name does not match your list of datasets. "
"Create your new dataset in the web dashboard:\n\t%s"),
create_dataset_base_url)
webbrowser.open(create_dataset_url)
name = click.prompt('Press ENTER to use dataset name "%s" or enter a different name' % dataset_name, default=dataset_name, show_default=False)
dataset_name = name.strip() or dataset_name
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
raise FloydException('Dataset "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % dataset_name)
namespace, name = get_namespace_from_name(dataset_name)
data_config = DataConfig(name=name,
namespace=namespace,
family_id=dataset_obj.id)
DataConfigManager.set_config(data_config)
floyd_logger.info("Data source \"{}\" initialized in current directory".format(dataset_name))
floyd_logger.info("""
You can now upload your data to Floyd by:
floyd data upload
""") | python | def init(dataset_name):
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
namespace, name = get_namespace_from_name(dataset_name)
create_dataset_base_url = "{}/datasets/create".format(floyd.floyd_web_host)
create_dataset_url = "{}?name={}&namespace={}".format(create_dataset_base_url, name, namespace)
floyd_logger.info(("Dataset name does not match your list of datasets. "
"Create your new dataset in the web dashboard:\n\t%s"),
create_dataset_base_url)
webbrowser.open(create_dataset_url)
name = click.prompt('Press ENTER to use dataset name "%s" or enter a different name' % dataset_name, default=dataset_name, show_default=False)
dataset_name = name.strip() or dataset_name
dataset_obj = DatasetClient().get_by_name(dataset_name)
if not dataset_obj:
raise FloydException('Dataset "%s" does not exist on floydhub.com. Ensure it exists before continuing.' % dataset_name)
namespace, name = get_namespace_from_name(dataset_name)
data_config = DataConfig(name=name,
namespace=namespace,
family_id=dataset_obj.id)
DataConfigManager.set_config(data_config)
floyd_logger.info("Data source \"{}\" initialized in current directory".format(dataset_name))
floyd_logger.info("""
You can now upload your data to Floyd by:
floyd data upload
""") | [
"def",
"init",
"(",
"dataset_name",
")",
":",
"dataset_obj",
"=",
"DatasetClient",
"(",
")",
".",
"get_by_name",
"(",
"dataset_name",
")",
"if",
"not",
"dataset_obj",
":",
"namespace",
",",
"name",
"=",
"get_namespace_from_name",
"(",
"dataset_name",
")",
"cre... | Initialize a new dataset at the current dir.
Then run the upload command to copy all the files in this
directory to FloydHub.
floyd data upload | [
"Initialize",
"a",
"new",
"dataset",
"at",
"the",
"current",
"dir",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L37-L74 |
24,647 | floydhub/floyd-cli | floyd/cli/data.py | upload | def upload(resume, message):
"""
Upload files in the current dir to FloydHub.
"""
data_config = DataConfigManager.get_config()
if not upload_is_resumable(data_config) or not opt_to_resume(resume):
abort_previous_upload(data_config)
access_token = AuthConfigManager.get_access_token()
initialize_new_upload(data_config, access_token, message)
complete_upload(data_config) | python | def upload(resume, message):
data_config = DataConfigManager.get_config()
if not upload_is_resumable(data_config) or not opt_to_resume(resume):
abort_previous_upload(data_config)
access_token = AuthConfigManager.get_access_token()
initialize_new_upload(data_config, access_token, message)
complete_upload(data_config) | [
"def",
"upload",
"(",
"resume",
",",
"message",
")",
":",
"data_config",
"=",
"DataConfigManager",
".",
"get_config",
"(",
")",
"if",
"not",
"upload_is_resumable",
"(",
"data_config",
")",
"or",
"not",
"opt_to_resume",
"(",
"resume",
")",
":",
"abort_previous_... | Upload files in the current dir to FloydHub. | [
"Upload",
"files",
"in",
"the",
"current",
"dir",
"to",
"FloydHub",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L82-L93 |
24,648 | floydhub/floyd-cli | floyd/cli/data.py | status | def status(id):
"""
View status of all versions in a dataset.
The command also accepts a specific dataset version.
"""
if id:
data_source = get_data_object(id, use_data_config=False)
print_data([data_source] if data_source else [])
else:
data_sources = DataClient().get_all()
print_data(data_sources) | python | def status(id):
if id:
data_source = get_data_object(id, use_data_config=False)
print_data([data_source] if data_source else [])
else:
data_sources = DataClient().get_all()
print_data(data_sources) | [
"def",
"status",
"(",
"id",
")",
":",
"if",
"id",
":",
"data_source",
"=",
"get_data_object",
"(",
"id",
",",
"use_data_config",
"=",
"False",
")",
"print_data",
"(",
"[",
"data_source",
"]",
"if",
"data_source",
"else",
"[",
"]",
")",
"else",
":",
"da... | View status of all versions in a dataset.
The command also accepts a specific dataset version. | [
"View",
"status",
"of",
"all",
"versions",
"in",
"a",
"dataset",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L98-L109 |
24,649 | floydhub/floyd-cli | floyd/cli/data.py | get_data_object | def get_data_object(data_id, use_data_config=True):
"""
Normalize the data_id and query the server.
If that is unavailable try the raw ID
"""
normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config)
client = DataClient()
data_obj = client.get(normalized_data_reference)
# Try with the raw ID
if not data_obj and data_id != normalized_data_reference:
data_obj = client.get(data_id)
return data_obj | python | def get_data_object(data_id, use_data_config=True):
normalized_data_reference = normalize_data_name(data_id, use_data_config=use_data_config)
client = DataClient()
data_obj = client.get(normalized_data_reference)
# Try with the raw ID
if not data_obj and data_id != normalized_data_reference:
data_obj = client.get(data_id)
return data_obj | [
"def",
"get_data_object",
"(",
"data_id",
",",
"use_data_config",
"=",
"True",
")",
":",
"normalized_data_reference",
"=",
"normalize_data_name",
"(",
"data_id",
",",
"use_data_config",
"=",
"use_data_config",
")",
"client",
"=",
"DataClient",
"(",
")",
"data_obj",
... | Normalize the data_id and query the server.
If that is unavailable try the raw ID | [
"Normalize",
"the",
"data_id",
"and",
"query",
"the",
"server",
".",
"If",
"that",
"is",
"unavailable",
"try",
"the",
"raw",
"ID"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L112-L125 |
24,650 | floydhub/floyd-cli | floyd/cli/data.py | print_data | def print_data(data_sources):
"""
Print dataset information in tabular form
"""
if not data_sources:
return
headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"]
data_list = []
for data_source in data_sources:
data_list.append([data_source.name,
data_source.created_pretty,
data_source.state, data_source.size])
floyd_logger.info(tabulate(data_list, headers=headers)) | python | def print_data(data_sources):
if not data_sources:
return
headers = ["DATA NAME", "CREATED", "STATUS", "DISK USAGE"]
data_list = []
for data_source in data_sources:
data_list.append([data_source.name,
data_source.created_pretty,
data_source.state, data_source.size])
floyd_logger.info(tabulate(data_list, headers=headers)) | [
"def",
"print_data",
"(",
"data_sources",
")",
":",
"if",
"not",
"data_sources",
":",
"return",
"headers",
"=",
"[",
"\"DATA NAME\"",
",",
"\"CREATED\"",
",",
"\"STATUS\"",
",",
"\"DISK USAGE\"",
"]",
"data_list",
"=",
"[",
"]",
"for",
"data_source",
"in",
"... | Print dataset information in tabular form | [
"Print",
"dataset",
"information",
"in",
"tabular",
"form"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L128-L141 |
24,651 | floydhub/floyd-cli | floyd/cli/data.py | clone | def clone(id, path):
"""
- Download all files in a dataset or from a Job output
Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/
Using /output will download the files that are saved at the end of the job.
Note: This will download the files that are saved at
the end of the job.
- Download a directory from a dataset or from Job output
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1
"""
data_source = get_data_object(id, use_data_config=False)
if not data_source:
if 'output' in id:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
if path:
# Download a directory from Dataset or Files
# Get the type of data resource from the id (foo/projects/bar/ or foo/datasets/bar/)
if '/datasets/' in id:
resource_type = 'data'
resource_id = data_source.id
else:
resource_type = 'files'
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
resource_id = experiment.id
data_url = "{}/api/v1/download/artifacts/{}/{}?is_dir=true&path={}".format(floyd.floyd_host,
resource_type,
resource_id,
path)
else:
# Download the full Dataset
data_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
data_source.resource_id)
DataClient().download_tar(url=data_url,
untar=True,
delete_after_untar=True) | python | def clone(id, path):
data_source = get_data_object(id, use_data_config=False)
if not data_source:
if 'output' in id:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
if path:
# Download a directory from Dataset or Files
# Get the type of data resource from the id (foo/projects/bar/ or foo/datasets/bar/)
if '/datasets/' in id:
resource_type = 'data'
resource_id = data_source.id
else:
resource_type = 'files'
try:
experiment = ExperimentClient().get(normalize_job_name(id, use_config=False))
except FloydException:
experiment = ExperimentClient().get(id)
resource_id = experiment.id
data_url = "{}/api/v1/download/artifacts/{}/{}?is_dir=true&path={}".format(floyd.floyd_host,
resource_type,
resource_id,
path)
else:
# Download the full Dataset
data_url = "{}/api/v1/resources/{}?content=true&download=true".format(floyd.floyd_host,
data_source.resource_id)
DataClient().download_tar(url=data_url,
untar=True,
delete_after_untar=True) | [
"def",
"clone",
"(",
"id",
",",
"path",
")",
":",
"data_source",
"=",
"get_data_object",
"(",
"id",
",",
"use_data_config",
"=",
"False",
")",
"if",
"not",
"data_source",
":",
"if",
"'output'",
"in",
"id",
":",
"floyd_logger",
".",
"info",
"(",
"\"Note: ... | - Download all files in a dataset or from a Job output
Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/
Using /output will download the files that are saved at the end of the job.
Note: This will download the files that are saved at
the end of the job.
- Download a directory from a dataset or from Job output
Specify the path to a directory and download all its files and subdirectories.
Eg: --path models/checkpoint1 | [
"-",
"Download",
"all",
"files",
"in",
"a",
"dataset",
"or",
"from",
"a",
"Job",
"output"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L148-L196 |
24,652 | floydhub/floyd-cli | floyd/cli/data.py | listfiles | def listfiles(data_name):
"""
List files in a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
# Depth-first search
dirs = ['']
paths = []
while dirs:
cur_dir = dirs.pop()
url = "/resources/{}/{}?content=true".format(data_source.resource_id, cur_dir)
response = DataClient().request("GET", url).json()
if response['skipped_files'] > 0:
floyd_logger.info("Warning: in directory '%s', %s/%s files skipped (too many files)", cur_dir, response['skipped_files'], response['total_files'])
files = response['files']
files.sort(key=lambda f: f['name'])
for f in files:
path = os.path.join(cur_dir, f['name'])
if f['type'] == 'directory':
path += os.sep
paths.append(path)
if f['type'] == 'directory':
dirs.append(os.path.join(cur_dir, f['name']))
for path in paths:
floyd_logger.info(path) | python | def listfiles(data_name):
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
# Depth-first search
dirs = ['']
paths = []
while dirs:
cur_dir = dirs.pop()
url = "/resources/{}/{}?content=true".format(data_source.resource_id, cur_dir)
response = DataClient().request("GET", url).json()
if response['skipped_files'] > 0:
floyd_logger.info("Warning: in directory '%s', %s/%s files skipped (too many files)", cur_dir, response['skipped_files'], response['total_files'])
files = response['files']
files.sort(key=lambda f: f['name'])
for f in files:
path = os.path.join(cur_dir, f['name'])
if f['type'] == 'directory':
path += os.sep
paths.append(path)
if f['type'] == 'directory':
dirs.append(os.path.join(cur_dir, f['name']))
for path in paths:
floyd_logger.info(path) | [
"def",
"listfiles",
"(",
"data_name",
")",
":",
"data_source",
"=",
"get_data_object",
"(",
"data_name",
",",
"use_data_config",
"=",
"False",
")",
"if",
"not",
"data_source",
":",
"if",
"'output'",
"in",
"data_name",
":",
"floyd_logger",
".",
"info",
"(",
"... | List files in a dataset. | [
"List",
"files",
"in",
"a",
"dataset",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L201-L235 |
24,653 | floydhub/floyd-cli | floyd/cli/data.py | getfile | def getfile(data_name, path):
"""
Download a specific file from a dataset.
"""
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
url = "{}/api/v1/resources/{}/{}?content=true".format(floyd.floyd_host, data_source.resource_id, path)
fname = os.path.basename(path)
DataClient().download(url, filename=fname)
floyd_logger.info("Download finished") | python | def getfile(data_name, path):
data_source = get_data_object(data_name, use_data_config=False)
if not data_source:
if 'output' in data_name:
floyd_logger.info("Note: You cannot clone the output of a running job. You need to wait for it to finish.")
sys.exit()
url = "{}/api/v1/resources/{}/{}?content=true".format(floyd.floyd_host, data_source.resource_id, path)
fname = os.path.basename(path)
DataClient().download(url, filename=fname)
floyd_logger.info("Download finished") | [
"def",
"getfile",
"(",
"data_name",
",",
"path",
")",
":",
"data_source",
"=",
"get_data_object",
"(",
"data_name",
",",
"use_data_config",
"=",
"False",
")",
"if",
"not",
"data_source",
":",
"if",
"'output'",
"in",
"data_name",
":",
"floyd_logger",
".",
"in... | Download a specific file from a dataset. | [
"Download",
"a",
"specific",
"file",
"from",
"a",
"dataset",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L241-L256 |
24,654 | floydhub/floyd-cli | floyd/cli/data.py | output | def output(id, url):
"""
View the files from a dataset.
"""
data_source = get_data_object(id, use_data_config=False)
if not data_source:
sys.exit()
data_url = "%s/%s" % (floyd.floyd_web_host, data_source.name)
if url:
floyd_logger.info(data_url)
else:
floyd_logger.info("Opening output directory in your browser ...")
webbrowser.open(data_url) | python | def output(id, url):
data_source = get_data_object(id, use_data_config=False)
if not data_source:
sys.exit()
data_url = "%s/%s" % (floyd.floyd_web_host, data_source.name)
if url:
floyd_logger.info(data_url)
else:
floyd_logger.info("Opening output directory in your browser ...")
webbrowser.open(data_url) | [
"def",
"output",
"(",
"id",
",",
"url",
")",
":",
"data_source",
"=",
"get_data_object",
"(",
"id",
",",
"use_data_config",
"=",
"False",
")",
"if",
"not",
"data_source",
":",
"sys",
".",
"exit",
"(",
")",
"data_url",
"=",
"\"%s/%s\"",
"%",
"(",
"floyd... | View the files from a dataset. | [
"View",
"the",
"files",
"from",
"a",
"dataset",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L263-L277 |
24,655 | floydhub/floyd-cli | floyd/cli/data.py | delete | def delete(ids, yes):
"""
Delete datasets.
"""
failures = False
for id in ids:
data_source = get_data_object(id, use_data_config=True)
if not data_source:
failures = True
continue
data_name = normalize_data_name(data_source.name)
suffix = data_name.split('/')[-1]
if not suffix.isdigit():
failures = True
floyd_logger.error('%s is not a dataset, skipped.', id)
if suffix == 'output':
floyd_logger.error('To delete job output, please delete the job itself.')
continue
if not yes and not click.confirm("Delete Data: {}?".format(data_name),
abort=False,
default=False):
floyd_logger.info("Data %s: Skipped", data_name)
continue
if not DataClient().delete(data_source.id):
failures = True
else:
floyd_logger.info("Data %s: Deleted", data_name)
if failures:
sys.exit(1) | python | def delete(ids, yes):
failures = False
for id in ids:
data_source = get_data_object(id, use_data_config=True)
if not data_source:
failures = True
continue
data_name = normalize_data_name(data_source.name)
suffix = data_name.split('/')[-1]
if not suffix.isdigit():
failures = True
floyd_logger.error('%s is not a dataset, skipped.', id)
if suffix == 'output':
floyd_logger.error('To delete job output, please delete the job itself.')
continue
if not yes and not click.confirm("Delete Data: {}?".format(data_name),
abort=False,
default=False):
floyd_logger.info("Data %s: Skipped", data_name)
continue
if not DataClient().delete(data_source.id):
failures = True
else:
floyd_logger.info("Data %s: Deleted", data_name)
if failures:
sys.exit(1) | [
"def",
"delete",
"(",
"ids",
",",
"yes",
")",
":",
"failures",
"=",
"False",
"for",
"id",
"in",
"ids",
":",
"data_source",
"=",
"get_data_object",
"(",
"id",
",",
"use_data_config",
"=",
"True",
")",
"if",
"not",
"data_source",
":",
"failures",
"=",
"T... | Delete datasets. | [
"Delete",
"datasets",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L284-L318 |
24,656 | floydhub/floyd-cli | floyd/cli/data.py | add | def add(source):
"""
Create a new dataset version from the contents of a job.
This will create a new dataset version with the job output.
Use the full job name: foo/projects/bar/1/code, foo/projects/bar/1/files or foo/projects/bar/1/output
"""
new_data = DatasetClient().add_data(source)
print_data([DataClient().get(new_data['data_id'])]) | python | def add(source):
new_data = DatasetClient().add_data(source)
print_data([DataClient().get(new_data['data_id'])]) | [
"def",
"add",
"(",
"source",
")",
":",
"new_data",
"=",
"DatasetClient",
"(",
")",
".",
"add_data",
"(",
"source",
")",
"print_data",
"(",
"[",
"DataClient",
"(",
")",
".",
"get",
"(",
"new_data",
"[",
"'data_id'",
"]",
")",
"]",
")"
] | Create a new dataset version from the contents of a job.
This will create a new dataset version with the job output.
Use the full job name: foo/projects/bar/1/code, foo/projects/bar/1/files or foo/projects/bar/1/output | [
"Create",
"a",
"new",
"dataset",
"version",
"from",
"the",
"contents",
"of",
"a",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/data.py#L323-L331 |
24,657 | floydhub/floyd-cli | floyd/cli/auth.py | login | def login(token, apikey, username, password):
"""
Login to FloydHub.
"""
if manual_login_success(token, username, password):
return
if not apikey:
if has_browser():
apikey = wait_for_apikey()
else:
floyd_logger.error(
"No browser found, please login manually by creating login key at %s/settings/apikey.",
floyd.floyd_web_host)
sys.exit(1)
if apikey:
user = AuthClient().get_user(apikey, is_apikey=True)
AuthConfigManager.set_apikey(username=user.username, apikey=apikey)
floyd_logger.info("Login Successful as %s", user.username)
else:
floyd_logger.error("Login failed, please see --help for other login options.") | python | def login(token, apikey, username, password):
if manual_login_success(token, username, password):
return
if not apikey:
if has_browser():
apikey = wait_for_apikey()
else:
floyd_logger.error(
"No browser found, please login manually by creating login key at %s/settings/apikey.",
floyd.floyd_web_host)
sys.exit(1)
if apikey:
user = AuthClient().get_user(apikey, is_apikey=True)
AuthConfigManager.set_apikey(username=user.username, apikey=apikey)
floyd_logger.info("Login Successful as %s", user.username)
else:
floyd_logger.error("Login failed, please see --help for other login options.") | [
"def",
"login",
"(",
"token",
",",
"apikey",
",",
"username",
",",
"password",
")",
":",
"if",
"manual_login_success",
"(",
"token",
",",
"username",
",",
"password",
")",
":",
"return",
"if",
"not",
"apikey",
":",
"if",
"has_browser",
"(",
")",
":",
"... | Login to FloydHub. | [
"Login",
"to",
"FloydHub",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/auth.py#L77-L98 |
24,658 | floydhub/floyd-cli | floyd/main.py | check_cli_version | def check_cli_version():
"""
Check if the current cli version satisfies the server requirements
"""
should_exit = False
server_version = VersionClient().get_cli_version()
current_version = get_cli_version()
if LooseVersion(current_version) < LooseVersion(server_version.min_version):
print("\nYour version of CLI (%s) is no longer compatible with server." % current_version)
should_exit = True
elif LooseVersion(current_version) < LooseVersion(server_version.latest_version):
print("\nNew version of CLI (%s) is now available." % server_version.latest_version)
else:
return
# new version is ready
if should_exit and click.confirm('\nDo you want to upgrade to version %s now?' % server_version.latest_version):
auto_upgrade()
sys.exit(0)
else:
msg_parts = []
msg_parts.append("\nTo manually upgrade run:")
msg_parts.append(" pip install -U floyd-cli")
if is_conda_env():
msg_parts.append("Or if you prefer to use conda:")
msg_parts.append(" conda install -y -c conda-forge -c floydhub floyd-cli")
print("\n".join(msg_parts))
print("")
if should_exit:
sys.exit(0) | python | def check_cli_version():
should_exit = False
server_version = VersionClient().get_cli_version()
current_version = get_cli_version()
if LooseVersion(current_version) < LooseVersion(server_version.min_version):
print("\nYour version of CLI (%s) is no longer compatible with server." % current_version)
should_exit = True
elif LooseVersion(current_version) < LooseVersion(server_version.latest_version):
print("\nNew version of CLI (%s) is now available." % server_version.latest_version)
else:
return
# new version is ready
if should_exit and click.confirm('\nDo you want to upgrade to version %s now?' % server_version.latest_version):
auto_upgrade()
sys.exit(0)
else:
msg_parts = []
msg_parts.append("\nTo manually upgrade run:")
msg_parts.append(" pip install -U floyd-cli")
if is_conda_env():
msg_parts.append("Or if you prefer to use conda:")
msg_parts.append(" conda install -y -c conda-forge -c floydhub floyd-cli")
print("\n".join(msg_parts))
print("")
if should_exit:
sys.exit(0) | [
"def",
"check_cli_version",
"(",
")",
":",
"should_exit",
"=",
"False",
"server_version",
"=",
"VersionClient",
"(",
")",
".",
"get_cli_version",
"(",
")",
"current_version",
"=",
"get_cli_version",
"(",
")",
"if",
"LooseVersion",
"(",
"current_version",
")",
"<... | Check if the current cli version satisfies the server requirements | [
"Check",
"if",
"the",
"current",
"cli",
"version",
"satisfies",
"the",
"server",
"requirements"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/main.py#L36-L67 |
24,659 | floydhub/floyd-cli | floyd/client/base.py | FloydHttpClient.request | def request(self,
method,
url,
params=None,
data=None,
files=None,
json=None,
timeout=5,
headers=None,
skip_auth=False):
"""
Execute the request using requests library
"""
request_url = self.base_url + url
floyd_logger.debug("Starting request to url: %s with params: %s, data: %s", request_url, params, data)
request_headers = {'x-floydhub-cli-version': get_cli_version()}
# Auth headers if present
if self.auth_header:
request_headers["Authorization"] = self.auth_header
# Add any additional headers
if headers:
request_headers.update(headers)
try:
response = requests.request(method,
request_url,
params=params,
data=data,
json=json,
headers=request_headers,
files=files,
timeout=timeout)
except requests.exceptions.ConnectionError as exception:
floyd_logger.debug("Exception: %s", exception, exc_info=True)
sys.exit("Cannot connect to the Floyd server. Check your internet connection.")
except requests.exceptions.Timeout as exception:
floyd_logger.debug("Exception: %s", exception, exc_info=True)
sys.exit("Connection to FloydHub server timed out. Please retry or check your internet connection.")
floyd_logger.debug("Response Content: %s, Headers: %s" % (response.content, response.headers))
self.check_response_status(response)
return response | python | def request(self,
method,
url,
params=None,
data=None,
files=None,
json=None,
timeout=5,
headers=None,
skip_auth=False):
request_url = self.base_url + url
floyd_logger.debug("Starting request to url: %s with params: %s, data: %s", request_url, params, data)
request_headers = {'x-floydhub-cli-version': get_cli_version()}
# Auth headers if present
if self.auth_header:
request_headers["Authorization"] = self.auth_header
# Add any additional headers
if headers:
request_headers.update(headers)
try:
response = requests.request(method,
request_url,
params=params,
data=data,
json=json,
headers=request_headers,
files=files,
timeout=timeout)
except requests.exceptions.ConnectionError as exception:
floyd_logger.debug("Exception: %s", exception, exc_info=True)
sys.exit("Cannot connect to the Floyd server. Check your internet connection.")
except requests.exceptions.Timeout as exception:
floyd_logger.debug("Exception: %s", exception, exc_info=True)
sys.exit("Connection to FloydHub server timed out. Please retry or check your internet connection.")
floyd_logger.debug("Response Content: %s, Headers: %s" % (response.content, response.headers))
self.check_response_status(response)
return response | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"files",
"=",
"None",
",",
"json",
"=",
"None",
",",
"timeout",
"=",
"5",
",",
"headers",
"=",
"None",
",",
"skip_auth",
"=",
"Fa... | Execute the request using requests library | [
"Execute",
"the",
"request",
"using",
"requests",
"library"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/base.py#L30-L72 |
24,660 | floydhub/floyd-cli | floyd/client/base.py | FloydHttpClient.download | def download(self, url, filename, relative=False, headers=None, timeout=5):
"""
Download the file from the given url at the current path
"""
request_url = self.base_url + url if relative else url
floyd_logger.debug("Downloading file from url: {}".format(request_url))
# Auth headers if present
request_headers = {}
if self.auth_header:
request_headers["Authorization"] = self.auth_header
# Add any additional headers
if headers:
request_headers.update(headers)
try:
response = requests.get(request_url,
headers=request_headers,
timeout=timeout,
stream=True)
self.check_response_status(response)
with open(filename, 'wb') as f:
# chunk mode response doesn't have content-length so we are
# using a custom header here
content_length = response.headers.get('x-floydhub-content-length')
if not content_length:
content_length = response.headers.get('content-length')
if content_length:
for chunk in progress.bar(response.iter_content(chunk_size=1024),
expected_size=(int(content_length) / 1024) + 1):
if chunk:
f.write(chunk)
else:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
return filename
except requests.exceptions.ConnectionError as exception:
floyd_logger.debug("Exception: {}".format(exception))
sys.exit("Cannot connect to the Floyd server. Check your internet connection.") | python | def download(self, url, filename, relative=False, headers=None, timeout=5):
request_url = self.base_url + url if relative else url
floyd_logger.debug("Downloading file from url: {}".format(request_url))
# Auth headers if present
request_headers = {}
if self.auth_header:
request_headers["Authorization"] = self.auth_header
# Add any additional headers
if headers:
request_headers.update(headers)
try:
response = requests.get(request_url,
headers=request_headers,
timeout=timeout,
stream=True)
self.check_response_status(response)
with open(filename, 'wb') as f:
# chunk mode response doesn't have content-length so we are
# using a custom header here
content_length = response.headers.get('x-floydhub-content-length')
if not content_length:
content_length = response.headers.get('content-length')
if content_length:
for chunk in progress.bar(response.iter_content(chunk_size=1024),
expected_size=(int(content_length) / 1024) + 1):
if chunk:
f.write(chunk)
else:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
return filename
except requests.exceptions.ConnectionError as exception:
floyd_logger.debug("Exception: {}".format(exception))
sys.exit("Cannot connect to the Floyd server. Check your internet connection.") | [
"def",
"download",
"(",
"self",
",",
"url",
",",
"filename",
",",
"relative",
"=",
"False",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"5",
")",
":",
"request_url",
"=",
"self",
".",
"base_url",
"+",
"url",
"if",
"relative",
"else",
"url",
"fl... | Download the file from the given url at the current path | [
"Download",
"the",
"file",
"from",
"the",
"given",
"url",
"at",
"the",
"current",
"path"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/base.py#L74-L113 |
24,661 | floydhub/floyd-cli | floyd/client/base.py | FloydHttpClient.download_tar | def download_tar(self, url, untar=True, delete_after_untar=False, destination_dir='.'):
"""
Download and optionally untar the tar file from the given url
"""
try:
floyd_logger.info("Downloading the tar file to the current directory ...")
filename = self.download(url=url, filename='output.tar')
if filename and untar:
floyd_logger.info("Untarring the contents of the file ...")
tar = tarfile.open(filename)
tar.extractall(path=destination_dir)
tar.close()
if delete_after_untar:
floyd_logger.info("Cleaning up the tar file ...")
os.remove(filename)
return filename
except FloydException as e:
floyd_logger.info("Download URL ERROR! {}".format(e.message))
return False | python | def download_tar(self, url, untar=True, delete_after_untar=False, destination_dir='.'):
try:
floyd_logger.info("Downloading the tar file to the current directory ...")
filename = self.download(url=url, filename='output.tar')
if filename and untar:
floyd_logger.info("Untarring the contents of the file ...")
tar = tarfile.open(filename)
tar.extractall(path=destination_dir)
tar.close()
if delete_after_untar:
floyd_logger.info("Cleaning up the tar file ...")
os.remove(filename)
return filename
except FloydException as e:
floyd_logger.info("Download URL ERROR! {}".format(e.message))
return False | [
"def",
"download_tar",
"(",
"self",
",",
"url",
",",
"untar",
"=",
"True",
",",
"delete_after_untar",
"=",
"False",
",",
"destination_dir",
"=",
"'.'",
")",
":",
"try",
":",
"floyd_logger",
".",
"info",
"(",
"\"Downloading the tar file to the current directory ...... | Download and optionally untar the tar file from the given url | [
"Download",
"and",
"optionally",
"untar",
"the",
"tar",
"file",
"from",
"the",
"given",
"url"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/base.py#L115-L133 |
24,662 | floydhub/floyd-cli | floyd/client/base.py | FloydHttpClient.check_response_status | def check_response_status(self, response):
"""
Check if response is successful. Else raise Exception.
"""
if not (200 <= response.status_code < 300):
try:
message = response.json()["errors"]
except Exception:
message = None
floyd_logger.debug("Error received : status_code: {}, message: {}".format(response.status_code,
message or response.content))
if response.status_code == 400:
raise BadRequestException(response)
elif response.status_code == 401:
raise AuthenticationException()
elif response.status_code == 403:
raise AuthorizationException(response)
elif response.status_code == 404:
raise NotFoundException()
elif response.status_code == 429:
raise OverLimitException(response.json().get("message"))
elif response.status_code == 502:
raise BadGatewayException()
elif response.status_code == 504:
raise GatewayTimeoutException()
elif response.status_code == 423:
raise LockedException()
elif 500 <= response.status_code < 600:
if 'Server under maintenance' in response.content.decode():
raise ServerException('Server under maintenance, please try again later.')
else:
raise ServerException()
else:
msg = "An error occurred. Server response: {}".format(response.status_code)
raise FloydException(message=msg) | python | def check_response_status(self, response):
if not (200 <= response.status_code < 300):
try:
message = response.json()["errors"]
except Exception:
message = None
floyd_logger.debug("Error received : status_code: {}, message: {}".format(response.status_code,
message or response.content))
if response.status_code == 400:
raise BadRequestException(response)
elif response.status_code == 401:
raise AuthenticationException()
elif response.status_code == 403:
raise AuthorizationException(response)
elif response.status_code == 404:
raise NotFoundException()
elif response.status_code == 429:
raise OverLimitException(response.json().get("message"))
elif response.status_code == 502:
raise BadGatewayException()
elif response.status_code == 504:
raise GatewayTimeoutException()
elif response.status_code == 423:
raise LockedException()
elif 500 <= response.status_code < 600:
if 'Server under maintenance' in response.content.decode():
raise ServerException('Server under maintenance, please try again later.')
else:
raise ServerException()
else:
msg = "An error occurred. Server response: {}".format(response.status_code)
raise FloydException(message=msg) | [
"def",
"check_response_status",
"(",
"self",
",",
"response",
")",
":",
"if",
"not",
"(",
"200",
"<=",
"response",
".",
"status_code",
"<",
"300",
")",
":",
"try",
":",
"message",
"=",
"response",
".",
"json",
"(",
")",
"[",
"\"errors\"",
"]",
"except"... | Check if response is successful. Else raise Exception. | [
"Check",
"if",
"response",
"is",
"successful",
".",
"Else",
"raise",
"Exception",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/base.py#L135-L169 |
24,663 | floydhub/floyd-cli | floyd/development/dev.py | cli | def cli(verbose):
"""
Floyd CLI interacts with FloydHub server and executes your commands.
More help is available under each command listed below.
"""
floyd.floyd_host = floyd.floyd_web_host = "https://dev.floydhub.com"
floyd.tus_server_endpoint = "https://upload-v2-dev.floydhub.com/api/v1/upload/"
configure_logger(verbose)
check_cli_version() | python | def cli(verbose):
floyd.floyd_host = floyd.floyd_web_host = "https://dev.floydhub.com"
floyd.tus_server_endpoint = "https://upload-v2-dev.floydhub.com/api/v1/upload/"
configure_logger(verbose)
check_cli_version() | [
"def",
"cli",
"(",
"verbose",
")",
":",
"floyd",
".",
"floyd_host",
"=",
"floyd",
".",
"floyd_web_host",
"=",
"\"https://dev.floydhub.com\"",
"floyd",
".",
"tus_server_endpoint",
"=",
"\"https://upload-v2-dev.floydhub.com/api/v1/upload/\"",
"configure_logger",
"(",
"verbo... | Floyd CLI interacts with FloydHub server and executes your commands.
More help is available under each command listed below. | [
"Floyd",
"CLI",
"interacts",
"with",
"FloydHub",
"server",
"and",
"executes",
"your",
"commands",
".",
"More",
"help",
"is",
"available",
"under",
"each",
"command",
"listed",
"below",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/development/dev.py#L10-L18 |
24,664 | floydhub/floyd-cli | floyd/client/files.py | get_unignored_file_paths | def get_unignored_file_paths(ignore_list=None, whitelist=None):
"""
Given an ignore_list and a whitelist of glob patterns, returns the list of
unignored file paths in the current directory and its subdirectories
"""
unignored_files = []
if ignore_list is None:
ignore_list = []
if whitelist is None:
whitelist = []
for root, dirs, files in os.walk("."):
floyd_logger.debug("Root:%s, Dirs:%s", root, dirs)
if ignore_path(unix_style_path(root), ignore_list, whitelist):
# Reset dirs to avoid going further down this directory.
# Then continue to the next iteration of os.walk, which causes
# everything in this directory to be ignored.
#
# Note that whitelisted files that are within directories that are
# ignored will not be whitelisted. This follows the expected
# behavior established by .gitignore logic:
# "It is not possible to re-include a file if a parent directory of
# that file is excluded."
# https://git-scm.com/docs/gitignore#_pattern_format
dirs[:] = []
floyd_logger.debug("Ignoring directory : %s", root)
continue
for file_name in files:
file_path = unix_style_path(os.path.join(root, file_name))
if ignore_path(file_path, ignore_list, whitelist):
floyd_logger.debug("Ignoring file : %s", file_name)
continue
unignored_files.append(os.path.join(root, file_name))
return unignored_files | python | def get_unignored_file_paths(ignore_list=None, whitelist=None):
unignored_files = []
if ignore_list is None:
ignore_list = []
if whitelist is None:
whitelist = []
for root, dirs, files in os.walk("."):
floyd_logger.debug("Root:%s, Dirs:%s", root, dirs)
if ignore_path(unix_style_path(root), ignore_list, whitelist):
# Reset dirs to avoid going further down this directory.
# Then continue to the next iteration of os.walk, which causes
# everything in this directory to be ignored.
#
# Note that whitelisted files that are within directories that are
# ignored will not be whitelisted. This follows the expected
# behavior established by .gitignore logic:
# "It is not possible to re-include a file if a parent directory of
# that file is excluded."
# https://git-scm.com/docs/gitignore#_pattern_format
dirs[:] = []
floyd_logger.debug("Ignoring directory : %s", root)
continue
for file_name in files:
file_path = unix_style_path(os.path.join(root, file_name))
if ignore_path(file_path, ignore_list, whitelist):
floyd_logger.debug("Ignoring file : %s", file_name)
continue
unignored_files.append(os.path.join(root, file_name))
return unignored_files | [
"def",
"get_unignored_file_paths",
"(",
"ignore_list",
"=",
"None",
",",
"whitelist",
"=",
"None",
")",
":",
"unignored_files",
"=",
"[",
"]",
"if",
"ignore_list",
"is",
"None",
":",
"ignore_list",
"=",
"[",
"]",
"if",
"whitelist",
"is",
"None",
":",
"whit... | Given an ignore_list and a whitelist of glob patterns, returns the list of
unignored file paths in the current directory and its subdirectories | [
"Given",
"an",
"ignore_list",
"and",
"a",
"whitelist",
"of",
"glob",
"patterns",
"returns",
"the",
"list",
"of",
"unignored",
"file",
"paths",
"in",
"the",
"current",
"directory",
"and",
"its",
"subdirectories"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/files.py#L22-L59 |
24,665 | floydhub/floyd-cli | floyd/client/files.py | ignore_path | def ignore_path(path, ignore_list=None, whitelist=None):
"""
Returns a boolean indicating if a path should be ignored given an
ignore_list and a whitelist of glob patterns.
"""
if ignore_list is None:
return True
should_ignore = matches_glob_list(path, ignore_list)
if whitelist is None:
return should_ignore
return should_ignore and not matches_glob_list(path, whitelist) | python | def ignore_path(path, ignore_list=None, whitelist=None):
if ignore_list is None:
return True
should_ignore = matches_glob_list(path, ignore_list)
if whitelist is None:
return should_ignore
return should_ignore and not matches_glob_list(path, whitelist) | [
"def",
"ignore_path",
"(",
"path",
",",
"ignore_list",
"=",
"None",
",",
"whitelist",
"=",
"None",
")",
":",
"if",
"ignore_list",
"is",
"None",
":",
"return",
"True",
"should_ignore",
"=",
"matches_glob_list",
"(",
"path",
",",
"ignore_list",
")",
"if",
"w... | Returns a boolean indicating if a path should be ignored given an
ignore_list and a whitelist of glob patterns. | [
"Returns",
"a",
"boolean",
"indicating",
"if",
"a",
"path",
"should",
"be",
"ignored",
"given",
"an",
"ignore_list",
"and",
"a",
"whitelist",
"of",
"glob",
"patterns",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/files.py#L62-L74 |
24,666 | floydhub/floyd-cli | floyd/client/files.py | matches_glob_list | def matches_glob_list(path, glob_list):
"""
Given a list of glob patterns, returns a boolean
indicating if a path matches any glob in the list
"""
for glob in glob_list:
try:
if PurePath(path).match(glob):
return True
except TypeError:
pass
return False | python | def matches_glob_list(path, glob_list):
for glob in glob_list:
try:
if PurePath(path).match(glob):
return True
except TypeError:
pass
return False | [
"def",
"matches_glob_list",
"(",
"path",
",",
"glob_list",
")",
":",
"for",
"glob",
"in",
"glob_list",
":",
"try",
":",
"if",
"PurePath",
"(",
"path",
")",
".",
"match",
"(",
"glob",
")",
":",
"return",
"True",
"except",
"TypeError",
":",
"pass",
"retu... | Given a list of glob patterns, returns a boolean
indicating if a path matches any glob in the list | [
"Given",
"a",
"list",
"of",
"glob",
"patterns",
"returns",
"a",
"boolean",
"indicating",
"if",
"a",
"path",
"matches",
"any",
"glob",
"in",
"the",
"list"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/files.py#L77-L88 |
24,667 | floydhub/floyd-cli | floyd/client/files.py | get_files_in_current_directory | def get_files_in_current_directory(file_type):
"""
Gets the list of files in the current directory and subdirectories.
Respects .floydignore file if present
"""
local_files = []
total_file_size = 0
ignore_list, whitelist = FloydIgnoreManager.get_lists()
floyd_logger.debug("Ignoring: %s", ignore_list)
floyd_logger.debug("Whitelisting: %s", whitelist)
file_paths = get_unignored_file_paths(ignore_list, whitelist)
for file_path in file_paths:
local_files.append((file_type, (unix_style_path(file_path), open(file_path, 'rb'), 'text/plain')))
total_file_size += os.path.getsize(file_path)
return (local_files, total_file_size) | python | def get_files_in_current_directory(file_type):
local_files = []
total_file_size = 0
ignore_list, whitelist = FloydIgnoreManager.get_lists()
floyd_logger.debug("Ignoring: %s", ignore_list)
floyd_logger.debug("Whitelisting: %s", whitelist)
file_paths = get_unignored_file_paths(ignore_list, whitelist)
for file_path in file_paths:
local_files.append((file_type, (unix_style_path(file_path), open(file_path, 'rb'), 'text/plain')))
total_file_size += os.path.getsize(file_path)
return (local_files, total_file_size) | [
"def",
"get_files_in_current_directory",
"(",
"file_type",
")",
":",
"local_files",
"=",
"[",
"]",
"total_file_size",
"=",
"0",
"ignore_list",
",",
"whitelist",
"=",
"FloydIgnoreManager",
".",
"get_lists",
"(",
")",
"floyd_logger",
".",
"debug",
"(",
"\"Ignoring: ... | Gets the list of files in the current directory and subdirectories.
Respects .floydignore file if present | [
"Gets",
"the",
"list",
"of",
"files",
"in",
"the",
"current",
"directory",
"and",
"subdirectories",
".",
"Respects",
".",
"floydignore",
"file",
"if",
"present"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/files.py#L91-L110 |
24,668 | floydhub/floyd-cli | floyd/client/files.py | DataCompressor.__get_nfiles_to_compress | def __get_nfiles_to_compress(self):
"""
Return the number of files to compress
Note: it should take about 0.1s for counting 100k files on a dual core machine
"""
floyd_logger.info("Get number of files to compress... (this could take a few seconds)")
paths = [self.source_dir]
try:
# Traverse each subdirs of source_dir and count files/dirs
while paths:
path = paths.pop()
for item in scandir(path):
if item.is_dir():
paths.append(item.path)
self.__files_to_compress += 1
elif item.is_file():
self.__files_to_compress += 1
except OSError as e:
# OSError: [Errno 13] Permission denied
if e.errno == errno.EACCES:
self.source_dir = os.getcwd() if self.source_dir == '.' else self.source_dir # Expand cwd
sys.exit(("Permission denied. Make sure to have read permission "
"for all the files and directories in the path: %s")
% (self.source_dir))
floyd_logger.info("Compressing %d files", self.__files_to_compress) | python | def __get_nfiles_to_compress(self):
floyd_logger.info("Get number of files to compress... (this could take a few seconds)")
paths = [self.source_dir]
try:
# Traverse each subdirs of source_dir and count files/dirs
while paths:
path = paths.pop()
for item in scandir(path):
if item.is_dir():
paths.append(item.path)
self.__files_to_compress += 1
elif item.is_file():
self.__files_to_compress += 1
except OSError as e:
# OSError: [Errno 13] Permission denied
if e.errno == errno.EACCES:
self.source_dir = os.getcwd() if self.source_dir == '.' else self.source_dir # Expand cwd
sys.exit(("Permission denied. Make sure to have read permission "
"for all the files and directories in the path: %s")
% (self.source_dir))
floyd_logger.info("Compressing %d files", self.__files_to_compress) | [
"def",
"__get_nfiles_to_compress",
"(",
"self",
")",
":",
"floyd_logger",
".",
"info",
"(",
"\"Get number of files to compress... (this could take a few seconds)\"",
")",
"paths",
"=",
"[",
"self",
".",
"source_dir",
"]",
"try",
":",
"# Traverse each subdirs of source_dir a... | Return the number of files to compress
Note: it should take about 0.1s for counting 100k files on a dual core machine | [
"Return",
"the",
"number",
"of",
"files",
"to",
"compress"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/files.py#L153-L178 |
24,669 | floydhub/floyd-cli | floyd/client/files.py | DataCompressor.create_tarfile | def create_tarfile(self):
"""
Create a tar file with the contents of the current directory
"""
floyd_logger.info("Compressing data...")
# Show progress bar (file_compressed/file_to_compress)
self.__compression_bar = ProgressBar(expected_size=self.__files_to_compress, filled_char='=')
# Auxiliary functions
def dfilter_file_counter(tarinfo):
"""
Dummy filter function used to track the progression at file levels.
"""
self.__compression_bar.show(self.__files_compressed)
self.__files_compressed += 1
return tarinfo
def warn_purge_exit(info_msg, filename, progress_bar, exit_msg):
"""
Warn the user that's something went wrong,
remove the tarball and provide an exit message.
"""
progress_bar.done()
floyd_logger.info(info_msg)
rmtree(os.path.dirname(filename))
sys.exit(exit_msg)
try:
# Define the default signal handler for catching: Ctrl-C
signal.signal(signal.SIGINT, signal.default_int_handler)
with tarfile.open(self.filename, "w:gz") as tar:
tar.add(self.source_dir, arcname=os.path.basename(self.source_dir), filter=dfilter_file_counter)
self.__compression_bar.done()
except (OSError, IOError) as e:
# OSError: [Errno 13] Permission denied
if e.errno == errno.EACCES:
self.source_dir = os.getcwd() if self.source_dir == '.' else self.source_dir # Expand cwd
warn_purge_exit(info_msg="Permission denied. Removing compressed data...",
filename=self.filename,
progress_bar=self.__compression_bar,
exit_msg=("Permission denied. Make sure to have read permission "
"for all the files and directories in the path: %s")
% (self.source_dir))
# OSError: [Errno 28] No Space Left on Device (IOError on python2.7)
elif e.errno == errno.ENOSPC:
dir_path = os.path.dirname(self.filename)
warn_purge_exit(info_msg="No space left. Removing compressed data...",
filename=self.filename,
progress_bar=self.__compression_bar,
exit_msg=("No space left when compressing your data in: %s.\n"
"Make sure to have enough space before uploading your data.")
% (os.path.abspath(dir_path)))
except KeyboardInterrupt: # Purge tarball on Ctrl-C
warn_purge_exit(info_msg="Ctrl-C signal detected: Removing compressed data...",
filename=self.filename,
progress_bar=self.__compression_bar,
exit_msg="Stopped the data upload gracefully.") | python | def create_tarfile(self):
floyd_logger.info("Compressing data...")
# Show progress bar (file_compressed/file_to_compress)
self.__compression_bar = ProgressBar(expected_size=self.__files_to_compress, filled_char='=')
# Auxiliary functions
def dfilter_file_counter(tarinfo):
"""
Dummy filter function used to track the progression at file levels.
"""
self.__compression_bar.show(self.__files_compressed)
self.__files_compressed += 1
return tarinfo
def warn_purge_exit(info_msg, filename, progress_bar, exit_msg):
"""
Warn the user that's something went wrong,
remove the tarball and provide an exit message.
"""
progress_bar.done()
floyd_logger.info(info_msg)
rmtree(os.path.dirname(filename))
sys.exit(exit_msg)
try:
# Define the default signal handler for catching: Ctrl-C
signal.signal(signal.SIGINT, signal.default_int_handler)
with tarfile.open(self.filename, "w:gz") as tar:
tar.add(self.source_dir, arcname=os.path.basename(self.source_dir), filter=dfilter_file_counter)
self.__compression_bar.done()
except (OSError, IOError) as e:
# OSError: [Errno 13] Permission denied
if e.errno == errno.EACCES:
self.source_dir = os.getcwd() if self.source_dir == '.' else self.source_dir # Expand cwd
warn_purge_exit(info_msg="Permission denied. Removing compressed data...",
filename=self.filename,
progress_bar=self.__compression_bar,
exit_msg=("Permission denied. Make sure to have read permission "
"for all the files and directories in the path: %s")
% (self.source_dir))
# OSError: [Errno 28] No Space Left on Device (IOError on python2.7)
elif e.errno == errno.ENOSPC:
dir_path = os.path.dirname(self.filename)
warn_purge_exit(info_msg="No space left. Removing compressed data...",
filename=self.filename,
progress_bar=self.__compression_bar,
exit_msg=("No space left when compressing your data in: %s.\n"
"Make sure to have enough space before uploading your data.")
% (os.path.abspath(dir_path)))
except KeyboardInterrupt: # Purge tarball on Ctrl-C
warn_purge_exit(info_msg="Ctrl-C signal detected: Removing compressed data...",
filename=self.filename,
progress_bar=self.__compression_bar,
exit_msg="Stopped the data upload gracefully.") | [
"def",
"create_tarfile",
"(",
"self",
")",
":",
"floyd_logger",
".",
"info",
"(",
"\"Compressing data...\"",
")",
"# Show progress bar (file_compressed/file_to_compress)",
"self",
".",
"__compression_bar",
"=",
"ProgressBar",
"(",
"expected_size",
"=",
"self",
".",
"__f... | Create a tar file with the contents of the current directory | [
"Create",
"a",
"tar",
"file",
"with",
"the",
"contents",
"of",
"the",
"current",
"directory"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/files.py#L180-L237 |
24,670 | floydhub/floyd-cli | floyd/client/data.py | DataClient.create | def create(self, data):
"""
Create a temporary directory for the tar file that will be removed at
the end of the operation.
"""
try:
floyd_logger.info("Making create request to server...")
post_body = data.to_dict()
post_body["resumable"] = True
response = self.request("POST", self.url, json=post_body)
return response.json()
except BadRequestException as e:
if 'Dataset not found, ID' in e.message:
floyd_logger.error(
'Data create: ERROR! Please run "floyd data init DATASET_NAME" before upload.')
else:
floyd_logger.error('Data create: ERROR! %s', e.message)
return None
except FloydException as e:
floyd_logger.error("Data create: ERROR! %s", e.message)
return None | python | def create(self, data):
try:
floyd_logger.info("Making create request to server...")
post_body = data.to_dict()
post_body["resumable"] = True
response = self.request("POST", self.url, json=post_body)
return response.json()
except BadRequestException as e:
if 'Dataset not found, ID' in e.message:
floyd_logger.error(
'Data create: ERROR! Please run "floyd data init DATASET_NAME" before upload.')
else:
floyd_logger.error('Data create: ERROR! %s', e.message)
return None
except FloydException as e:
floyd_logger.error("Data create: ERROR! %s", e.message)
return None | [
"def",
"create",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"floyd_logger",
".",
"info",
"(",
"\"Making create request to server...\"",
")",
"post_body",
"=",
"data",
".",
"to_dict",
"(",
")",
"post_body",
"[",
"\"resumable\"",
"]",
"=",
"True",
"respon... | Create a temporary directory for the tar file that will be removed at
the end of the operation. | [
"Create",
"a",
"temporary",
"directory",
"for",
"the",
"tar",
"file",
"that",
"will",
"be",
"removed",
"at",
"the",
"end",
"of",
"the",
"operation",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/client/data.py#L27-L47 |
24,671 | floydhub/floyd-cli | floyd/cli/run.py | get_command_line | def get_command_line(instance_type, env, message, data, mode, open_notebook, command_str):
"""
Return a string representing the full floyd command entered in the command line
"""
floyd_command = ["floyd", "run"]
if instance_type:
floyd_command.append('--' + INSTANCE_NAME_MAP[instance_type])
if env and not env == DEFAULT_ENV:
floyd_command += ["--env", env]
if message:
floyd_command += ["--message", shell_quote(message)]
if data:
for data_item in data:
parts = data_item.split(':')
if len(parts) > 1:
data_item = normalize_data_name(parts[0], use_data_config=False) + ':' + parts[1]
floyd_command += ["--data", data_item]
if mode and mode != "job":
floyd_command += ["--mode", mode]
if mode == 'jupyter':
if not open_notebook:
floyd_command.append("--no-open")
else:
if command_str:
floyd_command.append(shell_quote(command_str))
return ' '.join(floyd_command) | python | def get_command_line(instance_type, env, message, data, mode, open_notebook, command_str):
floyd_command = ["floyd", "run"]
if instance_type:
floyd_command.append('--' + INSTANCE_NAME_MAP[instance_type])
if env and not env == DEFAULT_ENV:
floyd_command += ["--env", env]
if message:
floyd_command += ["--message", shell_quote(message)]
if data:
for data_item in data:
parts = data_item.split(':')
if len(parts) > 1:
data_item = normalize_data_name(parts[0], use_data_config=False) + ':' + parts[1]
floyd_command += ["--data", data_item]
if mode and mode != "job":
floyd_command += ["--mode", mode]
if mode == 'jupyter':
if not open_notebook:
floyd_command.append("--no-open")
else:
if command_str:
floyd_command.append(shell_quote(command_str))
return ' '.join(floyd_command) | [
"def",
"get_command_line",
"(",
"instance_type",
",",
"env",
",",
"message",
",",
"data",
",",
"mode",
",",
"open_notebook",
",",
"command_str",
")",
":",
"floyd_command",
"=",
"[",
"\"floyd\"",
",",
"\"run\"",
"]",
"if",
"instance_type",
":",
"floyd_command",... | Return a string representing the full floyd command entered in the command line | [
"Return",
"a",
"string",
"representing",
"the",
"full",
"floyd",
"command",
"entered",
"in",
"the",
"command",
"line"
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/run.py#L353-L380 |
24,672 | floydhub/floyd-cli | floyd/cli/run.py | restart | def restart(ctx, job_name, data, open_notebook, env, message, gpu, cpu, gpup, cpup, command):
"""
Restart a finished job as a new job.
"""
# Error early if more than one --env is passed. Then get the first/only
# --env out of the list so all other operations work normally (they don't
# expect an iterable). For details on this approach, see the comment above
# the --env click option
if len(env) > 1:
floyd_logger.error(
"You passed more than one environment: {}. Please specify a single environment.".format(env)
)
sys.exit(1)
env = env[0]
parameters = {}
expt_client = ExperimentClient()
try:
job = expt_client.get(normalize_job_name(job_name))
except FloydException:
job = expt_client.get(job_name)
if gpu:
instance_type = G1_INSTANCE_TYPE
elif cpu:
instance_type = C1_INSTANCE_TYPE
else:
instance_type = job.instance_type
if instance_type is not None:
parameters['instance_type'] = instance_type
else:
instance_type = job.instance_type
if env is not None:
arch = INSTANCE_ARCH_MAP[instance_type]
if not validate_env(env, arch):
sys.exit(1)
parameters['env'] = env
success, data_ids, show_data_info = process_data_ids(data)
if not success:
sys.exit(1)
if data_ids:
parameters['data_ids'] = data_ids
if message:
parameters['description'] = message
if command:
parameters['command'] = ' '.join(command)
floyd_logger.info('Restarting job %s...', job_name)
new_job_info = expt_client.restart(job.id, parameters=parameters)
if not new_job_info:
floyd_logger.error("Failed to restart job")
sys.exit(1)
show_new_job_info(expt_client, new_job_info['name'], new_job_info, job.mode, open_notebook, show_data_info) | python | def restart(ctx, job_name, data, open_notebook, env, message, gpu, cpu, gpup, cpup, command):
# Error early if more than one --env is passed. Then get the first/only
# --env out of the list so all other operations work normally (they don't
# expect an iterable). For details on this approach, see the comment above
# the --env click option
if len(env) > 1:
floyd_logger.error(
"You passed more than one environment: {}. Please specify a single environment.".format(env)
)
sys.exit(1)
env = env[0]
parameters = {}
expt_client = ExperimentClient()
try:
job = expt_client.get(normalize_job_name(job_name))
except FloydException:
job = expt_client.get(job_name)
if gpu:
instance_type = G1_INSTANCE_TYPE
elif cpu:
instance_type = C1_INSTANCE_TYPE
else:
instance_type = job.instance_type
if instance_type is not None:
parameters['instance_type'] = instance_type
else:
instance_type = job.instance_type
if env is not None:
arch = INSTANCE_ARCH_MAP[instance_type]
if not validate_env(env, arch):
sys.exit(1)
parameters['env'] = env
success, data_ids, show_data_info = process_data_ids(data)
if not success:
sys.exit(1)
if data_ids:
parameters['data_ids'] = data_ids
if message:
parameters['description'] = message
if command:
parameters['command'] = ' '.join(command)
floyd_logger.info('Restarting job %s...', job_name)
new_job_info = expt_client.restart(job.id, parameters=parameters)
if not new_job_info:
floyd_logger.error("Failed to restart job")
sys.exit(1)
show_new_job_info(expt_client, new_job_info['name'], new_job_info, job.mode, open_notebook, show_data_info) | [
"def",
"restart",
"(",
"ctx",
",",
"job_name",
",",
"data",
",",
"open_notebook",
",",
"env",
",",
"message",
",",
"gpu",
",",
"cpu",
",",
"gpup",
",",
"cpup",
",",
"command",
")",
":",
"# Error early if more than one --env is passed. Then get the first/only",
"... | Restart a finished job as a new job. | [
"Restart",
"a",
"finished",
"job",
"as",
"a",
"new",
"job",
"."
] | ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c | https://github.com/floydhub/floyd-cli/blob/ea6b9521119cbde2dfc71ce0cc87c0d9c143fc6c/floyd/cli/run.py#L405-L466 |
24,673 | yvesalexandre/bandicoot | bandicoot/helper/group.py | filter_user | def filter_user(user, using='records', interaction=None,
part_of_week='allweek', part_of_day='allday'):
"""
Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
'records' or 'recharges'
part_of_week : {'allweek', 'weekday', 'weekend'}, default 'allweek'
* 'weekend': keep only the weekend records
* 'weekday': keep only the weekdays records
* 'allweek': use all the records
part_of_day : {'allday', 'day', 'night'}, default 'allday'
* 'day': keep only the records during the day
* 'night': keep only the records during the night
* 'allday': use all the records
interaction : object
The interaction to filter records:
* "callandtext", for only callandtext;
* a string, to filter for one type;
* None, to use all records.
"""
if using == 'recharges':
records = user.recharges
else:
records = user.records
if interaction == 'callandtext':
records = filter(
lambda r: r.interaction in ['call', 'text'], records)
elif interaction is not None:
records = filter(lambda r: r.interaction == interaction, records)
if part_of_week == 'weekday':
records = filter(
lambda r: r.datetime.isoweekday() not in user.weekend, records)
elif part_of_week == 'weekend':
records = filter(
lambda r: r.datetime.isoweekday() in user.weekend, records)
elif part_of_week != 'allweek':
raise KeyError(
"{} is not a valid value for part_of_week. it should be 'weekday', "
"'weekend' or 'allweek'.".format(part_of_week))
if user.night_start < user.night_end:
night_filter = lambda r: user.night_end > r.datetime.time(
) > user.night_start
else:
night_filter = lambda r: not(
user.night_end < r.datetime.time() < user.night_start)
if part_of_day == 'day':
records = filter(lambda r: not(night_filter(r)), records)
elif part_of_day == 'night':
records = filter(night_filter, records)
elif part_of_day != 'allday':
raise KeyError(
"{} is not a valid value for part_of_day. It should be 'day', 'night' or 'allday'.".format(part_of_day))
return list(records) | python | def filter_user(user, using='records', interaction=None,
part_of_week='allweek', part_of_day='allday'):
if using == 'recharges':
records = user.recharges
else:
records = user.records
if interaction == 'callandtext':
records = filter(
lambda r: r.interaction in ['call', 'text'], records)
elif interaction is not None:
records = filter(lambda r: r.interaction == interaction, records)
if part_of_week == 'weekday':
records = filter(
lambda r: r.datetime.isoweekday() not in user.weekend, records)
elif part_of_week == 'weekend':
records = filter(
lambda r: r.datetime.isoweekday() in user.weekend, records)
elif part_of_week != 'allweek':
raise KeyError(
"{} is not a valid value for part_of_week. it should be 'weekday', "
"'weekend' or 'allweek'.".format(part_of_week))
if user.night_start < user.night_end:
night_filter = lambda r: user.night_end > r.datetime.time(
) > user.night_start
else:
night_filter = lambda r: not(
user.night_end < r.datetime.time() < user.night_start)
if part_of_day == 'day':
records = filter(lambda r: not(night_filter(r)), records)
elif part_of_day == 'night':
records = filter(night_filter, records)
elif part_of_day != 'allday':
raise KeyError(
"{} is not a valid value for part_of_day. It should be 'day', 'night' or 'allday'.".format(part_of_day))
return list(records) | [
"def",
"filter_user",
"(",
"user",
",",
"using",
"=",
"'records'",
",",
"interaction",
"=",
"None",
",",
"part_of_week",
"=",
"'allweek'",
",",
"part_of_day",
"=",
"'allday'",
")",
":",
"if",
"using",
"==",
"'recharges'",
":",
"records",
"=",
"user",
".",
... | Filter records of a User objects by interaction, part of week and day.
Parameters
----------
user : User
a bandicoot User object
type : str, default 'records'
'records' or 'recharges'
part_of_week : {'allweek', 'weekday', 'weekend'}, default 'allweek'
* 'weekend': keep only the weekend records
* 'weekday': keep only the weekdays records
* 'allweek': use all the records
part_of_day : {'allday', 'day', 'night'}, default 'allday'
* 'day': keep only the records during the day
* 'night': keep only the records during the night
* 'allday': use all the records
interaction : object
The interaction to filter records:
* "callandtext", for only callandtext;
* a string, to filter for one type;
* None, to use all records. | [
"Filter",
"records",
"of",
"a",
"User",
"objects",
"by",
"interaction",
"part",
"of",
"week",
"and",
"day",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/group.py#L43-L105 |
24,674 | yvesalexandre/bandicoot | bandicoot/helper/group.py | positions_binning | def positions_binning(records):
"""
Bin records by chunks of 30 minutes, returning the most prevalent position.
If multiple positions have the same number of occurrences
(during 30 minutes), we select the last one.
"""
def get_key(d):
return (d.year, d.day, d.hour, d.minute // 30)
chunks = itertools.groupby(records, key=lambda r: get_key(r.datetime))
for _, items in chunks:
positions = [i.position for i in items]
# Given the low number of positions per chunk of 30 minutes, and
# the need for a deterministic value, we use max and not Counter
yield max(positions, key=positions.count) | python | def positions_binning(records):
def get_key(d):
return (d.year, d.day, d.hour, d.minute // 30)
chunks = itertools.groupby(records, key=lambda r: get_key(r.datetime))
for _, items in chunks:
positions = [i.position for i in items]
# Given the low number of positions per chunk of 30 minutes, and
# the need for a deterministic value, we use max and not Counter
yield max(positions, key=positions.count) | [
"def",
"positions_binning",
"(",
"records",
")",
":",
"def",
"get_key",
"(",
"d",
")",
":",
"return",
"(",
"d",
".",
"year",
",",
"d",
".",
"day",
",",
"d",
".",
"hour",
",",
"d",
".",
"minute",
"//",
"30",
")",
"chunks",
"=",
"itertools",
".",
... | Bin records by chunks of 30 minutes, returning the most prevalent position.
If multiple positions have the same number of occurrences
(during 30 minutes), we select the last one. | [
"Bin",
"records",
"by",
"chunks",
"of",
"30",
"minutes",
"returning",
"the",
"most",
"prevalent",
"position",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/group.py#L108-L124 |
24,675 | yvesalexandre/bandicoot | bandicoot/helper/group.py | _group_range | def _group_range(records, method):
"""
Yield the range of all dates between the extrema of
a list of records, separated by a given time delta.
"""
start_date = records[0].datetime
end_date = records[-1].datetime
_fun = DATE_GROUPERS[method]
d = start_date
# Day and week use timedelta
if method not in ["month", "year"]:
def increment(i):
return i + timedelta(**{method + 's': 1})
elif method == "month":
def increment(i):
year, month = divmod(i.month + 1, 12)
if month == 0:
month = 12
year = year - 1
return d.replace(year=d.year + year, month=month)
elif method == "year":
def increment(i):
return d.replace(year=d.year + 1)
while _fun(d) <= _fun(end_date):
yield d
d = increment(d) | python | def _group_range(records, method):
start_date = records[0].datetime
end_date = records[-1].datetime
_fun = DATE_GROUPERS[method]
d = start_date
# Day and week use timedelta
if method not in ["month", "year"]:
def increment(i):
return i + timedelta(**{method + 's': 1})
elif method == "month":
def increment(i):
year, month = divmod(i.month + 1, 12)
if month == 0:
month = 12
year = year - 1
return d.replace(year=d.year + year, month=month)
elif method == "year":
def increment(i):
return d.replace(year=d.year + 1)
while _fun(d) <= _fun(end_date):
yield d
d = increment(d) | [
"def",
"_group_range",
"(",
"records",
",",
"method",
")",
":",
"start_date",
"=",
"records",
"[",
"0",
"]",
".",
"datetime",
"end_date",
"=",
"records",
"[",
"-",
"1",
"]",
".",
"datetime",
"_fun",
"=",
"DATE_GROUPERS",
"[",
"method",
"]",
"d",
"=",
... | Yield the range of all dates between the extrema of
a list of records, separated by a given time delta. | [
"Yield",
"the",
"range",
"of",
"all",
"dates",
"between",
"the",
"extrema",
"of",
"a",
"list",
"of",
"records",
"separated",
"by",
"a",
"given",
"time",
"delta",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/group.py#L127-L158 |
24,676 | yvesalexandre/bandicoot | bandicoot/helper/group.py | group_records | def group_records(records, groupby='week'):
"""
Group records by year, month, week, or day.
Parameters
----------
records : iterator
An iterator over records
groupby : Default is 'week':
* 'week': group all records by year and week
* None: records are not grouped. This is useful if you don't want to
divide records in chunks
* "day", "month", and "year" also accepted
"""
def _group_date(records, _fun):
for _, chunk in itertools.groupby(records, key=lambda r: _fun(r.datetime)):
yield list(chunk)
return _group_date(records, DATE_GROUPERS[groupby]) | python | def group_records(records, groupby='week'):
def _group_date(records, _fun):
for _, chunk in itertools.groupby(records, key=lambda r: _fun(r.datetime)):
yield list(chunk)
return _group_date(records, DATE_GROUPERS[groupby]) | [
"def",
"group_records",
"(",
"records",
",",
"groupby",
"=",
"'week'",
")",
":",
"def",
"_group_date",
"(",
"records",
",",
"_fun",
")",
":",
"for",
"_",
",",
"chunk",
"in",
"itertools",
".",
"groupby",
"(",
"records",
",",
"key",
"=",
"lambda",
"r",
... | Group records by year, month, week, or day.
Parameters
----------
records : iterator
An iterator over records
groupby : Default is 'week':
* 'week': group all records by year and week
* None: records are not grouped. This is useful if you don't want to
divide records in chunks
* "day", "month", and "year" also accepted | [
"Group",
"records",
"by",
"year",
"month",
"week",
"or",
"day",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/group.py#L186-L206 |
24,677 | yvesalexandre/bandicoot | bandicoot/helper/group.py | infer_type | def infer_type(data):
"""
Infer the type of objects returned by indicators.
infer_type returns:
- 'scalar' for a number or None,
- 'summarystats' for a SummaryStats object,
- 'distribution_scalar' for a list of scalars,
- 'distribution_summarystats' for a list of SummaryStats objects
"""
if isinstance(data, (type(None), numbers.Number)):
return 'scalar'
if isinstance(data, SummaryStats):
return 'summarystats'
if hasattr(data, "__len__"): # list or numpy array
data = [x for x in data if x is not None]
if len(data) == 0 or isinstance(data[0], numbers.Number):
return 'distribution_scalar'
if isinstance(data[0], SummaryStats):
return 'distribution_summarystats'
raise TypeError(
"{} is not a valid input. It should be a number, a SummaryStats "
"object, or None".format(data[0]))
raise TypeError(
"{} is not a valid input. It should be a number, a SummaryStats "
"object, or a list".format(data)) | python | def infer_type(data):
if isinstance(data, (type(None), numbers.Number)):
return 'scalar'
if isinstance(data, SummaryStats):
return 'summarystats'
if hasattr(data, "__len__"): # list or numpy array
data = [x for x in data if x is not None]
if len(data) == 0 or isinstance(data[0], numbers.Number):
return 'distribution_scalar'
if isinstance(data[0], SummaryStats):
return 'distribution_summarystats'
raise TypeError(
"{} is not a valid input. It should be a number, a SummaryStats "
"object, or None".format(data[0]))
raise TypeError(
"{} is not a valid input. It should be a number, a SummaryStats "
"object, or a list".format(data)) | [
"def",
"infer_type",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"(",
"type",
"(",
"None",
")",
",",
"numbers",
".",
"Number",
")",
")",
":",
"return",
"'scalar'",
"if",
"isinstance",
"(",
"data",
",",
"SummaryStats",
")",
":",
"retu... | Infer the type of objects returned by indicators.
infer_type returns:
- 'scalar' for a number or None,
- 'summarystats' for a SummaryStats object,
- 'distribution_scalar' for a list of scalars,
- 'distribution_summarystats' for a list of SummaryStats objects | [
"Infer",
"the",
"type",
"of",
"objects",
"returned",
"by",
"indicators",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/group.py#L209-L239 |
24,678 | yvesalexandre/bandicoot | bandicoot/helper/group.py | grouping | def grouping(f=None, interaction=['call', 'text'], summary='default',
user_kwd=False):
"""
``grouping`` is a decorator for indicator functions, used to simplify the
source code.
Parameters
----------
f : function
The function to decorate
user_kwd : boolean
If user_kwd is True, the user object will be passed to the decorated
function
interaction : 'call', 'text', 'location', or a list
By default, all indicators use only 'call' and 'text' records, but the
interaction keywords filters the records passed to the function.
summary: 'default', 'extended', None
An indicator returns data statistics, ether *mean* and *std* by
default, more with 'extended', or the inner distribution with None.
See :meth:`~bandicoot.helper.group.statistics` for more details.
See :ref:`new-indicator-label` to learn how to write an indicator with
this decorator.
"""
if f is None:
return partial(grouping, user_kwd=user_kwd, interaction=interaction,
summary=summary)
def wrapper(user, groupby='week', interaction=interaction, summary=summary,
split_week=False, split_day=False, filter_empty=True,
datatype=None, **kwargs):
if interaction is None:
interaction = ['call', 'text']
parameters = divide_parameters(split_week, split_day, interaction)
operations = {
'grouping': {
'using': 'records',
'binning': False,
'groupby': groupby,
'filter_empty': filter_empty,
'divide_by': parameters
}, 'apply': {
'user_kwd': user_kwd,
'summary': summary,
'kwargs': kwargs
}
}
for i in parameters['interaction']:
if i not in ['callandtext', 'call', 'text', 'location']:
raise ValueError("%s is not a valid interaction value. Only "
"'call', 'text', and 'location' are accepted."
% i)
return _generic_wrapper(f, user, operations, datatype)
return advanced_wrap(f, wrapper) | python | def grouping(f=None, interaction=['call', 'text'], summary='default',
user_kwd=False):
if f is None:
return partial(grouping, user_kwd=user_kwd, interaction=interaction,
summary=summary)
def wrapper(user, groupby='week', interaction=interaction, summary=summary,
split_week=False, split_day=False, filter_empty=True,
datatype=None, **kwargs):
if interaction is None:
interaction = ['call', 'text']
parameters = divide_parameters(split_week, split_day, interaction)
operations = {
'grouping': {
'using': 'records',
'binning': False,
'groupby': groupby,
'filter_empty': filter_empty,
'divide_by': parameters
}, 'apply': {
'user_kwd': user_kwd,
'summary': summary,
'kwargs': kwargs
}
}
for i in parameters['interaction']:
if i not in ['callandtext', 'call', 'text', 'location']:
raise ValueError("%s is not a valid interaction value. Only "
"'call', 'text', and 'location' are accepted."
% i)
return _generic_wrapper(f, user, operations, datatype)
return advanced_wrap(f, wrapper) | [
"def",
"grouping",
"(",
"f",
"=",
"None",
",",
"interaction",
"=",
"[",
"'call'",
",",
"'text'",
"]",
",",
"summary",
"=",
"'default'",
",",
"user_kwd",
"=",
"False",
")",
":",
"if",
"f",
"is",
"None",
":",
"return",
"partial",
"(",
"grouping",
",",
... | ``grouping`` is a decorator for indicator functions, used to simplify the
source code.
Parameters
----------
f : function
The function to decorate
user_kwd : boolean
If user_kwd is True, the user object will be passed to the decorated
function
interaction : 'call', 'text', 'location', or a list
By default, all indicators use only 'call' and 'text' records, but the
interaction keywords filters the records passed to the function.
summary: 'default', 'extended', None
An indicator returns data statistics, ether *mean* and *std* by
default, more with 'extended', or the inner distribution with None.
See :meth:`~bandicoot.helper.group.statistics` for more details.
See :ref:`new-indicator-label` to learn how to write an indicator with
this decorator. | [
"grouping",
"is",
"a",
"decorator",
"for",
"indicator",
"functions",
"used",
"to",
"simplify",
"the",
"source",
"code",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/group.py#L396-L456 |
24,679 | yvesalexandre/bandicoot | bandicoot/helper/maths.py | kurtosis | def kurtosis(data):
"""
Return the kurtosis for ``data``.
"""
if len(data) == 0:
return None
num = moment(data, 4)
denom = moment(data, 2) ** 2.
return num / denom if denom != 0 else 0 | python | def kurtosis(data):
if len(data) == 0:
return None
num = moment(data, 4)
denom = moment(data, 2) ** 2.
return num / denom if denom != 0 else 0 | [
"def",
"kurtosis",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"None",
"num",
"=",
"moment",
"(",
"data",
",",
"4",
")",
"denom",
"=",
"moment",
"(",
"data",
",",
"2",
")",
"**",
"2.",
"return",
"num",
"/",
... | Return the kurtosis for ``data``. | [
"Return",
"the",
"kurtosis",
"for",
"data",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/maths.py#L44-L55 |
24,680 | yvesalexandre/bandicoot | bandicoot/helper/maths.py | skewness | def skewness(data):
"""
Returns the skewness of ``data``.
"""
if len(data) == 0:
return None
num = moment(data, 3)
denom = moment(data, 2) ** 1.5
return num / denom if denom != 0 else 0. | python | def skewness(data):
if len(data) == 0:
return None
num = moment(data, 3)
denom = moment(data, 2) ** 1.5
return num / denom if denom != 0 else 0. | [
"def",
"skewness",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"None",
"num",
"=",
"moment",
"(",
"data",
",",
"3",
")",
"denom",
"=",
"moment",
"(",
"data",
",",
"2",
")",
"**",
"1.5",
"return",
"num",
"/",
... | Returns the skewness of ``data``. | [
"Returns",
"the",
"skewness",
"of",
"data",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/maths.py#L58-L69 |
24,681 | yvesalexandre/bandicoot | bandicoot/helper/maths.py | median | def median(data):
"""
Return the median of numeric data, unsing the "mean of middle two" method.
If ``data`` is empty, ``0`` is returned.
Examples
--------
>>> median([1, 3, 5])
3.0
When the number of data points is even, the median is interpolated:
>>> median([1, 3, 5, 7])
4.0
"""
if len(data) == 0:
return None
data = sorted(data)
return float((data[len(data) // 2] + data[(len(data) - 1) // 2]) / 2.) | python | def median(data):
if len(data) == 0:
return None
data = sorted(data)
return float((data[len(data) // 2] + data[(len(data) - 1) // 2]) / 2.) | [
"def",
"median",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"None",
"data",
"=",
"sorted",
"(",
"data",
")",
"return",
"float",
"(",
"(",
"data",
"[",
"len",
"(",
"data",
")",
"//",
"2",
"]",
"+",
"data",
... | Return the median of numeric data, unsing the "mean of middle two" method.
If ``data`` is empty, ``0`` is returned.
Examples
--------
>>> median([1, 3, 5])
3.0
When the number of data points is even, the median is interpolated:
>>> median([1, 3, 5, 7])
4.0 | [
"Return",
"the",
"median",
"of",
"numeric",
"data",
"unsing",
"the",
"mean",
"of",
"middle",
"two",
"method",
".",
"If",
"data",
"is",
"empty",
"0",
"is",
"returned",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/maths.py#L88-L108 |
24,682 | yvesalexandre/bandicoot | bandicoot/helper/maths.py | entropy | def entropy(data):
"""
Compute the Shannon entropy, a measure of uncertainty.
"""
if len(data) == 0:
return None
n = sum(data)
_op = lambda f: f * math.log(f)
return - sum(_op(float(i) / n) for i in data) | python | def entropy(data):
if len(data) == 0:
return None
n = sum(data)
_op = lambda f: f * math.log(f)
return - sum(_op(float(i) / n) for i in data) | [
"def",
"entropy",
"(",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"None",
"n",
"=",
"sum",
"(",
"data",
")",
"_op",
"=",
"lambda",
"f",
":",
"f",
"*",
"math",
".",
"log",
"(",
"f",
")",
"return",
"-",
"sum",
... | Compute the Shannon entropy, a measure of uncertainty. | [
"Compute",
"the",
"Shannon",
"entropy",
"a",
"measure",
"of",
"uncertainty",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/maths.py#L206-L217 |
24,683 | yvesalexandre/bandicoot | bandicoot/helper/tools.py | advanced_wrap | def advanced_wrap(f, wrapper):
"""
Wrap a decorated function while keeping the same keyword arguments
"""
f_sig = list(inspect.getargspec(f))
wrap_sig = list(inspect.getargspec(wrapper))
# Update the keyword arguments of the wrapper
if f_sig[3] is None or f_sig[3] == []:
f_sig[3], f_kwargs = [], []
else:
f_kwargs = f_sig[0][-len(f_sig[3]):]
for key, default in zip(f_kwargs, f_sig[3]):
wrap_sig[0].append(key)
wrap_sig[3] = wrap_sig[3] + (default, )
wrap_sig[2] = None # Remove kwargs
src = "lambda %s: " % (inspect.formatargspec(*wrap_sig)[1:-1])
new_args = inspect.formatargspec(
wrap_sig[0], wrap_sig[1], wrap_sig[2], f_kwargs,
formatvalue=lambda x: '=' + x)
src += 'wrapper%s\n' % new_args
decorated = eval(src, locals())
decorated.func = f
return update_wrapper(decorated, f) | python | def advanced_wrap(f, wrapper):
f_sig = list(inspect.getargspec(f))
wrap_sig = list(inspect.getargspec(wrapper))
# Update the keyword arguments of the wrapper
if f_sig[3] is None or f_sig[3] == []:
f_sig[3], f_kwargs = [], []
else:
f_kwargs = f_sig[0][-len(f_sig[3]):]
for key, default in zip(f_kwargs, f_sig[3]):
wrap_sig[0].append(key)
wrap_sig[3] = wrap_sig[3] + (default, )
wrap_sig[2] = None # Remove kwargs
src = "lambda %s: " % (inspect.formatargspec(*wrap_sig)[1:-1])
new_args = inspect.formatargspec(
wrap_sig[0], wrap_sig[1], wrap_sig[2], f_kwargs,
formatvalue=lambda x: '=' + x)
src += 'wrapper%s\n' % new_args
decorated = eval(src, locals())
decorated.func = f
return update_wrapper(decorated, f) | [
"def",
"advanced_wrap",
"(",
"f",
",",
"wrapper",
")",
":",
"f_sig",
"=",
"list",
"(",
"inspect",
".",
"getargspec",
"(",
"f",
")",
")",
"wrap_sig",
"=",
"list",
"(",
"inspect",
".",
"getargspec",
"(",
"wrapper",
")",
")",
"# Update the keyword arguments o... | Wrap a decorated function while keeping the same keyword arguments | [
"Wrap",
"a",
"decorated",
"function",
"while",
"keeping",
"the",
"same",
"keyword",
"arguments"
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L67-L93 |
24,684 | yvesalexandre/bandicoot | bandicoot/helper/tools.py | percent_records_missing_location | def percent_records_missing_location(user, method=None):
"""
Return the percentage of records missing a location parameter.
"""
if len(user.records) == 0:
return 0.
missing_locations = sum([1 for record in user.records if record.position._get_location(user) is None])
return float(missing_locations) / len(user.records) | python | def percent_records_missing_location(user, method=None):
if len(user.records) == 0:
return 0.
missing_locations = sum([1 for record in user.records if record.position._get_location(user) is None])
return float(missing_locations) / len(user.records) | [
"def",
"percent_records_missing_location",
"(",
"user",
",",
"method",
"=",
"None",
")",
":",
"if",
"len",
"(",
"user",
".",
"records",
")",
"==",
"0",
":",
"return",
"0.",
"missing_locations",
"=",
"sum",
"(",
"[",
"1",
"for",
"record",
"in",
"user",
... | Return the percentage of records missing a location parameter. | [
"Return",
"the",
"percentage",
"of",
"records",
"missing",
"a",
"location",
"parameter",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L198-L207 |
24,685 | yvesalexandre/bandicoot | bandicoot/helper/tools.py | percent_overlapping_calls | def percent_overlapping_calls(records, min_gab=300):
"""
Return the percentage of calls that overlap with the next call.
Parameters
----------
records : list
The records for a single user.
min_gab : int
Number of seconds that the calls must overlap to be considered an issue.
Defaults to 5 minutes.
"""
calls = [r for r in records if r.interaction == "call"]
if len(calls) == 0:
return 0.
overlapping_calls = 0
for i, r in enumerate(calls):
if i <= len(calls) - 2:
if r.datetime + timedelta(seconds=r.call_duration - min_gab) >= calls[i + 1].datetime:
overlapping_calls += 1
return (float(overlapping_calls) / len(calls)) | python | def percent_overlapping_calls(records, min_gab=300):
calls = [r for r in records if r.interaction == "call"]
if len(calls) == 0:
return 0.
overlapping_calls = 0
for i, r in enumerate(calls):
if i <= len(calls) - 2:
if r.datetime + timedelta(seconds=r.call_duration - min_gab) >= calls[i + 1].datetime:
overlapping_calls += 1
return (float(overlapping_calls) / len(calls)) | [
"def",
"percent_overlapping_calls",
"(",
"records",
",",
"min_gab",
"=",
"300",
")",
":",
"calls",
"=",
"[",
"r",
"for",
"r",
"in",
"records",
"if",
"r",
".",
"interaction",
"==",
"\"call\"",
"]",
"if",
"len",
"(",
"calls",
")",
"==",
"0",
":",
"retu... | Return the percentage of calls that overlap with the next call.
Parameters
----------
records : list
The records for a single user.
min_gab : int
Number of seconds that the calls must overlap to be considered an issue.
Defaults to 5 minutes. | [
"Return",
"the",
"percentage",
"of",
"calls",
"that",
"overlap",
"with",
"the",
"next",
"call",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L210-L234 |
24,686 | yvesalexandre/bandicoot | bandicoot/helper/tools.py | antennas_missing_locations | def antennas_missing_locations(user, Method=None):
"""
Return the number of antennas missing locations in the records of a given user.
"""
unique_antennas = set([record.position.antenna for record in user.records
if record.position.antenna is not None])
return sum([1 for antenna in unique_antennas if user.antennas.get(antenna) is None]) | python | def antennas_missing_locations(user, Method=None):
unique_antennas = set([record.position.antenna for record in user.records
if record.position.antenna is not None])
return sum([1 for antenna in unique_antennas if user.antennas.get(antenna) is None]) | [
"def",
"antennas_missing_locations",
"(",
"user",
",",
"Method",
"=",
"None",
")",
":",
"unique_antennas",
"=",
"set",
"(",
"[",
"record",
".",
"position",
".",
"antenna",
"for",
"record",
"in",
"user",
".",
"records",
"if",
"record",
".",
"position",
".",... | Return the number of antennas missing locations in the records of a given user. | [
"Return",
"the",
"number",
"of",
"antennas",
"missing",
"locations",
"in",
"the",
"records",
"of",
"a",
"given",
"user",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L237-L243 |
24,687 | yvesalexandre/bandicoot | bandicoot/helper/tools.py | bandicoot_code_signature | def bandicoot_code_signature():
"""
Returns a unique hash of the Python source code in the current bandicoot
module, using the cryptographic hash function SHA-1.
"""
checksum = hashlib.sha1()
for root, dirs, files in os.walk(MAIN_DIRECTORY):
for filename in sorted(files):
if not filename.endswith('.py'):
continue
f_path = os.path.join(root, filename)
f_size = os.path.getsize(f_path)
with open(f_path, 'rb') as f:
while f.tell() != f_size:
checksum.update(f.read(0x40000))
return checksum.hexdigest() | python | def bandicoot_code_signature():
checksum = hashlib.sha1()
for root, dirs, files in os.walk(MAIN_DIRECTORY):
for filename in sorted(files):
if not filename.endswith('.py'):
continue
f_path = os.path.join(root, filename)
f_size = os.path.getsize(f_path)
with open(f_path, 'rb') as f:
while f.tell() != f_size:
checksum.update(f.read(0x40000))
return checksum.hexdigest() | [
"def",
"bandicoot_code_signature",
"(",
")",
":",
"checksum",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"MAIN_DIRECTORY",
")",
":",
"for",
"filename",
"in",
"sorted",
"(",
"files",
")... | Returns a unique hash of the Python source code in the current bandicoot
module, using the cryptographic hash function SHA-1. | [
"Returns",
"a",
"unique",
"hash",
"of",
"the",
"Python",
"source",
"code",
"in",
"the",
"current",
"bandicoot",
"module",
"using",
"the",
"cryptographic",
"hash",
"function",
"SHA",
"-",
"1",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L280-L298 |
24,688 | yvesalexandre/bandicoot | bandicoot/helper/tools.py | _AnsiColorizer.supported | def supported(cls, stream=sys.stdout):
"""
A class method that returns True if the current platform supports
coloring terminal output using this method. Returns False otherwise.
"""
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
except ImportError:
return False
else:
try:
try:
return curses.tigetnum("colors") > 2
except curses.error:
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
raise
# guess false in case of error
return False | python | def supported(cls, stream=sys.stdout):
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
except ImportError:
return False
else:
try:
try:
return curses.tigetnum("colors") > 2
except curses.error:
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
raise
# guess false in case of error
return False | [
"def",
"supported",
"(",
"cls",
",",
"stream",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"not",
"stream",
".",
"isatty",
"(",
")",
":",
"return",
"False",
"# auto color only on TTYs",
"try",
":",
"import",
"curses",
"except",
"ImportError",
":",
"return",... | A class method that returns True if the current platform supports
coloring terminal output using this method. Returns False otherwise. | [
"A",
"class",
"method",
"that",
"returns",
"True",
"if",
"the",
"current",
"platform",
"supports",
"coloring",
"terminal",
"output",
"using",
"this",
"method",
".",
"Returns",
"False",
"otherwise",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L147-L168 |
24,689 | yvesalexandre/bandicoot | bandicoot/helper/tools.py | _AnsiColorizer.write | def write(self, text, color):
"""
Write the given text to the stream in the given color.
"""
color = self._colors[color]
self.stream.write('\x1b[{}m{}\x1b[0m'.format(color, text)) | python | def write(self, text, color):
color = self._colors[color]
self.stream.write('\x1b[{}m{}\x1b[0m'.format(color, text)) | [
"def",
"write",
"(",
"self",
",",
"text",
",",
"color",
")",
":",
"color",
"=",
"self",
".",
"_colors",
"[",
"color",
"]",
"self",
".",
"stream",
".",
"write",
"(",
"'\\x1b[{}m{}\\x1b[0m'",
".",
"format",
"(",
"color",
",",
"text",
")",
")"
] | Write the given text to the stream in the given color. | [
"Write",
"the",
"given",
"text",
"to",
"the",
"stream",
"in",
"the",
"given",
"color",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/tools.py#L170-L175 |
24,690 | yvesalexandre/bandicoot | bandicoot/spatial.py | percent_at_home | def percent_at_home(positions, user):
"""
The percentage of interactions the user had while he was at home.
.. note::
The position of the home is computed using
:meth:`User.recompute_home <bandicoot.core.User.recompute_home>`.
If no home can be found, the percentage of interactions at home
will be ``None``.
"""
if not user.has_home:
return None
total_home = sum(1 for p in positions if p == user.home)
return float(total_home) / len(positions) if len(positions) != 0 else 0 | python | def percent_at_home(positions, user):
if not user.has_home:
return None
total_home = sum(1 for p in positions if p == user.home)
return float(total_home) / len(positions) if len(positions) != 0 else 0 | [
"def",
"percent_at_home",
"(",
"positions",
",",
"user",
")",
":",
"if",
"not",
"user",
".",
"has_home",
":",
"return",
"None",
"total_home",
"=",
"sum",
"(",
"1",
"for",
"p",
"in",
"positions",
"if",
"p",
"==",
"user",
".",
"home",
")",
"return",
"f... | The percentage of interactions the user had while he was at home.
.. note::
The position of the home is computed using
:meth:`User.recompute_home <bandicoot.core.User.recompute_home>`.
If no home can be found, the percentage of interactions at home
will be ``None``. | [
"The",
"percentage",
"of",
"interactions",
"the",
"user",
"had",
"while",
"he",
"was",
"at",
"home",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/spatial.py#L34-L49 |
24,691 | yvesalexandre/bandicoot | bandicoot/spatial.py | entropy_of_antennas | def entropy_of_antennas(positions, normalize=False):
"""
The entropy of visited antennas.
Parameters
----------
normalize: boolean, default is False
Returns a normalized entropy between 0 and 1.
"""
counter = Counter(p for p in positions)
raw_entropy = entropy(list(counter.values()))
n = len(counter)
if normalize and n > 1:
return raw_entropy / math.log(n)
else:
return raw_entropy | python | def entropy_of_antennas(positions, normalize=False):
counter = Counter(p for p in positions)
raw_entropy = entropy(list(counter.values()))
n = len(counter)
if normalize and n > 1:
return raw_entropy / math.log(n)
else:
return raw_entropy | [
"def",
"entropy_of_antennas",
"(",
"positions",
",",
"normalize",
"=",
"False",
")",
":",
"counter",
"=",
"Counter",
"(",
"p",
"for",
"p",
"in",
"positions",
")",
"raw_entropy",
"=",
"entropy",
"(",
"list",
"(",
"counter",
".",
"values",
"(",
")",
")",
... | The entropy of visited antennas.
Parameters
----------
normalize: boolean, default is False
Returns a normalized entropy between 0 and 1. | [
"The",
"entropy",
"of",
"visited",
"antennas",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/spatial.py#L88-L103 |
24,692 | yvesalexandre/bandicoot | bandicoot/spatial.py | churn_rate | def churn_rate(user, summary='default', **kwargs):
"""
Computes the frequency spent at every towers each week, and returns the
distribution of the cosine similarity between two consecutives week.
.. note:: The churn rate is always computed between pairs of weeks.
"""
if len(user.records) == 0:
return statistics([], summary=summary)
query = {
'groupby': 'week',
'divide_by': OrderedDict([
('part_of_week', ['allweek']),
('part_of_day', ['allday'])
]),
'using': 'records',
'filter_empty': True,
'binning': True
}
rv = grouping_query(user, query)
weekly_positions = rv[0][1]
all_positions = list(set(p for l in weekly_positions for p in l))
frequencies = {}
cos_dist = []
for week, week_positions in enumerate(weekly_positions):
count = Counter(week_positions)
total = sum(count.values())
frequencies[week] = [count.get(p, 0) / total for p in all_positions]
all_indexes = range(len(all_positions))
for f_1, f_2 in pairwise(list(frequencies.values())):
num = sum(f_1[a] * f_2[a] for a in all_indexes)
denom_1 = sum(f ** 2 for f in f_1)
denom_2 = sum(f ** 2 for f in f_2)
cos_dist.append(1 - num / (denom_1 ** .5 * denom_2 ** .5))
return statistics(cos_dist, summary=summary) | python | def churn_rate(user, summary='default', **kwargs):
if len(user.records) == 0:
return statistics([], summary=summary)
query = {
'groupby': 'week',
'divide_by': OrderedDict([
('part_of_week', ['allweek']),
('part_of_day', ['allday'])
]),
'using': 'records',
'filter_empty': True,
'binning': True
}
rv = grouping_query(user, query)
weekly_positions = rv[0][1]
all_positions = list(set(p for l in weekly_positions for p in l))
frequencies = {}
cos_dist = []
for week, week_positions in enumerate(weekly_positions):
count = Counter(week_positions)
total = sum(count.values())
frequencies[week] = [count.get(p, 0) / total for p in all_positions]
all_indexes = range(len(all_positions))
for f_1, f_2 in pairwise(list(frequencies.values())):
num = sum(f_1[a] * f_2[a] for a in all_indexes)
denom_1 = sum(f ** 2 for f in f_1)
denom_2 = sum(f ** 2 for f in f_2)
cos_dist.append(1 - num / (denom_1 ** .5 * denom_2 ** .5))
return statistics(cos_dist, summary=summary) | [
"def",
"churn_rate",
"(",
"user",
",",
"summary",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"user",
".",
"records",
")",
"==",
"0",
":",
"return",
"statistics",
"(",
"[",
"]",
",",
"summary",
"=",
"summary",
")",
"query... | Computes the frequency spent at every towers each week, and returns the
distribution of the cosine similarity between two consecutives week.
.. note:: The churn rate is always computed between pairs of weeks. | [
"Computes",
"the",
"frequency",
"spent",
"at",
"every",
"towers",
"each",
"week",
"and",
"returns",
"the",
"distribution",
"of",
"the",
"cosine",
"similarity",
"between",
"two",
"consecutives",
"week",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/spatial.py#L133-L173 |
24,693 | yvesalexandre/bandicoot | bandicoot/core.py | User.describe | def describe(self):
"""
Generates a short description of the object, and writes it to the
standard output.
Examples
--------
>>> import bandicoot as bc
>>> user = bc.User()
>>> user.records = bc.tests.generate_user.random_burst(5)
>>> user.describe()
[x] 5 records from 2014-01-01 10:41:00 to 2014-01-01 11:21:00
5 contacts
[x] 1 attribute
"""
def format_int(name, n):
if n == 0 or n == 1:
return "%i %s" % (n, name[:-1])
else:
return "%i %s" % (n, name)
empty_box = Colors.OKGREEN + '[ ]' + Colors.ENDC + ' '
filled_box = Colors.OKGREEN + '[x]' + Colors.ENDC + ' '
if self.start_time is None:
print(empty_box + "No records stored")
else:
print((filled_box + format_int("records", len(self.records)) +
" from %s to %s" % (self.start_time, self.end_time)))
nb_contacts = bc.individual.number_of_contacts(
self, interaction='callandtext', groupby=None)
nb_contacts = nb_contacts['allweek']['allday']['callandtext']
if nb_contacts:
print(filled_box + format_int("contacts", nb_contacts))
else:
print(empty_box + "No contacts")
if self.has_attributes:
print(filled_box + format_int("attributes", len(self.attributes)))
else:
print(empty_box + "No attribute stored")
if len(self.antennas) == 0:
print(empty_box + "No antenna stored")
else:
print(filled_box + format_int("antennas", len(self.antennas)))
if self.has_recharges:
print(filled_box + format_int("recharges", len(self.recharges)))
else:
print(empty_box + "No recharges")
if self.has_home:
print(filled_box + "Has home")
else:
print(empty_box + "No home")
if self.has_text:
print(filled_box + "Has texts")
else:
print(empty_box + "No texts")
if self.has_call:
print(filled_box + "Has calls")
else:
print(empty_box + "No calls")
if self.has_network:
print(filled_box + "Has network")
else:
print(empty_box + "No network") | python | def describe(self):
def format_int(name, n):
if n == 0 or n == 1:
return "%i %s" % (n, name[:-1])
else:
return "%i %s" % (n, name)
empty_box = Colors.OKGREEN + '[ ]' + Colors.ENDC + ' '
filled_box = Colors.OKGREEN + '[x]' + Colors.ENDC + ' '
if self.start_time is None:
print(empty_box + "No records stored")
else:
print((filled_box + format_int("records", len(self.records)) +
" from %s to %s" % (self.start_time, self.end_time)))
nb_contacts = bc.individual.number_of_contacts(
self, interaction='callandtext', groupby=None)
nb_contacts = nb_contacts['allweek']['allday']['callandtext']
if nb_contacts:
print(filled_box + format_int("contacts", nb_contacts))
else:
print(empty_box + "No contacts")
if self.has_attributes:
print(filled_box + format_int("attributes", len(self.attributes)))
else:
print(empty_box + "No attribute stored")
if len(self.antennas) == 0:
print(empty_box + "No antenna stored")
else:
print(filled_box + format_int("antennas", len(self.antennas)))
if self.has_recharges:
print(filled_box + format_int("recharges", len(self.recharges)))
else:
print(empty_box + "No recharges")
if self.has_home:
print(filled_box + "Has home")
else:
print(empty_box + "No home")
if self.has_text:
print(filled_box + "Has texts")
else:
print(empty_box + "No texts")
if self.has_call:
print(filled_box + "Has calls")
else:
print(empty_box + "No calls")
if self.has_network:
print(filled_box + "Has network")
else:
print(empty_box + "No network") | [
"def",
"describe",
"(",
"self",
")",
":",
"def",
"format_int",
"(",
"name",
",",
"n",
")",
":",
"if",
"n",
"==",
"0",
"or",
"n",
"==",
"1",
":",
"return",
"\"%i %s\"",
"%",
"(",
"n",
",",
"name",
"[",
":",
"-",
"1",
"]",
")",
"else",
":",
"... | Generates a short description of the object, and writes it to the
standard output.
Examples
--------
>>> import bandicoot as bc
>>> user = bc.User()
>>> user.records = bc.tests.generate_user.random_burst(5)
>>> user.describe()
[x] 5 records from 2014-01-01 10:41:00 to 2014-01-01 11:21:00
5 contacts
[x] 1 attribute | [
"Generates",
"a",
"short",
"description",
"of",
"the",
"object",
"and",
"writes",
"it",
"to",
"the",
"standard",
"output",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/core.py#L294-L365 |
24,694 | yvesalexandre/bandicoot | bandicoot/core.py | User.recompute_home | def recompute_home(self):
"""
Return the antenna where the user spends most of his time at night.
None is returned if there are no candidates for a home antenna
"""
if self.night_start < self.night_end:
night_filter = lambda r: self.night_end > r.datetime.time(
) > self.night_start
else:
night_filter = lambda r: not(
self.night_end < r.datetime.time() < self.night_start)
# Bin positions by chunks of 30 minutes
candidates = list(
positions_binning(filter(night_filter, self._records)))
if len(candidates) == 0:
self.home = None
else:
self.home = Counter(candidates).most_common()[0][0]
self.reset_cache()
return self.home | python | def recompute_home(self):
if self.night_start < self.night_end:
night_filter = lambda r: self.night_end > r.datetime.time(
) > self.night_start
else:
night_filter = lambda r: not(
self.night_end < r.datetime.time() < self.night_start)
# Bin positions by chunks of 30 minutes
candidates = list(
positions_binning(filter(night_filter, self._records)))
if len(candidates) == 0:
self.home = None
else:
self.home = Counter(candidates).most_common()[0][0]
self.reset_cache()
return self.home | [
"def",
"recompute_home",
"(",
"self",
")",
":",
"if",
"self",
".",
"night_start",
"<",
"self",
".",
"night_end",
":",
"night_filter",
"=",
"lambda",
"r",
":",
"self",
".",
"night_end",
">",
"r",
".",
"datetime",
".",
"time",
"(",
")",
">",
"self",
".... | Return the antenna where the user spends most of his time at night.
None is returned if there are no candidates for a home antenna | [
"Return",
"the",
"antenna",
"where",
"the",
"user",
"spends",
"most",
"of",
"his",
"time",
"at",
"night",
".",
"None",
"is",
"returned",
"if",
"there",
"are",
"no",
"candidates",
"for",
"a",
"home",
"antenna"
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/core.py#L367-L390 |
24,695 | yvesalexandre/bandicoot | bandicoot/core.py | User.set_home | def set_home(self, new_home):
"""
Sets the user's home. The argument can be a Position object or a
tuple containing location data.
"""
if type(new_home) is Position:
self.home = new_home
elif type(new_home) is tuple:
self.home = Position(location=new_home)
else:
self.home = Position(antenna=new_home)
self.reset_cache() | python | def set_home(self, new_home):
if type(new_home) is Position:
self.home = new_home
elif type(new_home) is tuple:
self.home = Position(location=new_home)
else:
self.home = Position(antenna=new_home)
self.reset_cache() | [
"def",
"set_home",
"(",
"self",
",",
"new_home",
")",
":",
"if",
"type",
"(",
"new_home",
")",
"is",
"Position",
":",
"self",
".",
"home",
"=",
"new_home",
"elif",
"type",
"(",
"new_home",
")",
"is",
"tuple",
":",
"self",
".",
"home",
"=",
"Position"... | Sets the user's home. The argument can be a Position object or a
tuple containing location data. | [
"Sets",
"the",
"user",
"s",
"home",
".",
"The",
"argument",
"can",
"be",
"a",
"Position",
"object",
"or",
"a",
"tuple",
"containing",
"location",
"data",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/core.py#L417-L431 |
24,696 | yvesalexandre/bandicoot | bandicoot/recharge.py | interevent_time_recharges | def interevent_time_recharges(recharges):
"""
Return the distribution of time between consecutive recharges
of the user.
"""
time_pairs = pairwise(r.datetime for r in recharges)
times = [(new - old).total_seconds() for old, new in time_pairs]
return summary_stats(times) | python | def interevent_time_recharges(recharges):
time_pairs = pairwise(r.datetime for r in recharges)
times = [(new - old).total_seconds() for old, new in time_pairs]
return summary_stats(times) | [
"def",
"interevent_time_recharges",
"(",
"recharges",
")",
":",
"time_pairs",
"=",
"pairwise",
"(",
"r",
".",
"datetime",
"for",
"r",
"in",
"recharges",
")",
"times",
"=",
"[",
"(",
"new",
"-",
"old",
")",
".",
"total_seconds",
"(",
")",
"for",
"old",
... | Return the distribution of time between consecutive recharges
of the user. | [
"Return",
"the",
"distribution",
"of",
"time",
"between",
"consecutive",
"recharges",
"of",
"the",
"user",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/recharge.py#L39-L46 |
24,697 | yvesalexandre/bandicoot | bandicoot/recharge.py | percent_pareto_recharges | def percent_pareto_recharges(recharges, percentage=0.8):
"""
Percentage of recharges that account for 80% of total recharged amount.
"""
amounts = sorted([r.amount for r in recharges], reverse=True)
total_sum = sum(amounts)
partial_sum = 0
for count, a in enumerate(amounts):
partial_sum += a
if partial_sum >= percentage * total_sum:
break
return (count + 1) / len(recharges) | python | def percent_pareto_recharges(recharges, percentage=0.8):
amounts = sorted([r.amount for r in recharges], reverse=True)
total_sum = sum(amounts)
partial_sum = 0
for count, a in enumerate(amounts):
partial_sum += a
if partial_sum >= percentage * total_sum:
break
return (count + 1) / len(recharges) | [
"def",
"percent_pareto_recharges",
"(",
"recharges",
",",
"percentage",
"=",
"0.8",
")",
":",
"amounts",
"=",
"sorted",
"(",
"[",
"r",
".",
"amount",
"for",
"r",
"in",
"recharges",
"]",
",",
"reverse",
"=",
"True",
")",
"total_sum",
"=",
"sum",
"(",
"a... | Percentage of recharges that account for 80% of total recharged amount. | [
"Percentage",
"of",
"recharges",
"that",
"account",
"for",
"80%",
"of",
"total",
"recharged",
"amount",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/recharge.py#L50-L63 |
24,698 | yvesalexandre/bandicoot | bandicoot/recharge.py | average_balance_recharges | def average_balance_recharges(user, **kwargs):
"""
Return the average daily balance estimated from all recharges. We assume a
linear usage between two recharges, and an empty balance before a recharge.
The average balance can be seen as the area under the curve delimited by
all recharges.
"""
balance = 0
for r1, r2 in pairwise(user.recharges):
# If the range is less than 1 day, cap at 1
balance += r1.amount * min(1, (r2.datetime - r1.datetime).days) / 2
first_recharge = user.recharges[0]
last_recharge = user.recharges[-1]
duration = (last_recharge.datetime - first_recharge.datetime).days
return balance / min(1, duration) | python | def average_balance_recharges(user, **kwargs):
balance = 0
for r1, r2 in pairwise(user.recharges):
# If the range is less than 1 day, cap at 1
balance += r1.amount * min(1, (r2.datetime - r1.datetime).days) / 2
first_recharge = user.recharges[0]
last_recharge = user.recharges[-1]
duration = (last_recharge.datetime - first_recharge.datetime).days
return balance / min(1, duration) | [
"def",
"average_balance_recharges",
"(",
"user",
",",
"*",
"*",
"kwargs",
")",
":",
"balance",
"=",
"0",
"for",
"r1",
",",
"r2",
"in",
"pairwise",
"(",
"user",
".",
"recharges",
")",
":",
"# If the range is less than 1 day, cap at 1",
"balance",
"+=",
"r1",
... | Return the average daily balance estimated from all recharges. We assume a
linear usage between two recharges, and an empty balance before a recharge.
The average balance can be seen as the area under the curve delimited by
all recharges. | [
"Return",
"the",
"average",
"daily",
"balance",
"estimated",
"from",
"all",
"recharges",
".",
"We",
"assume",
"a",
"linear",
"usage",
"between",
"two",
"recharges",
"and",
"an",
"empty",
"balance",
"before",
"a",
"recharge",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/recharge.py#L74-L91 |
24,699 | yvesalexandre/bandicoot | bandicoot/network.py | _round_half_hour | def _round_half_hour(record):
"""
Round a time DOWN to half nearest half-hour.
"""
k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))
return datetime(k.year, k.month, k.day, k.hour, k.minute, 0) | python | def _round_half_hour(record):
k = record.datetime + timedelta(minutes=-(record.datetime.minute % 30))
return datetime(k.year, k.month, k.day, k.hour, k.minute, 0) | [
"def",
"_round_half_hour",
"(",
"record",
")",
":",
"k",
"=",
"record",
".",
"datetime",
"+",
"timedelta",
"(",
"minutes",
"=",
"-",
"(",
"record",
".",
"datetime",
".",
"minute",
"%",
"30",
")",
")",
"return",
"datetime",
"(",
"k",
".",
"year",
",",... | Round a time DOWN to half nearest half-hour. | [
"Round",
"a",
"time",
"DOWN",
"to",
"half",
"nearest",
"half",
"-",
"hour",
"."
] | 73a658f6f17331541cf0b1547028db9b70e8d58a | https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/network.py#L36-L41 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.