query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Sets the current track position in microseconds . | def SetPosition ( self , track_id , position ) : self . iface . SetPosition ( convert2dbus ( track_id , 'o' ) , convert2dbus ( position , 'x' ) ) | 5,200 | https://github.com/wistful/pympris/blob/4bd64a1f0d151f2adfc392ab34fd9b38894786cb/pympris/Player.py#L79-L91 | [
"def",
"_get_sg_name_dict",
"(",
"self",
",",
"data",
",",
"page_size",
",",
"no_nameconv",
")",
":",
"if",
"no_nameconv",
":",
"return",
"{",
"}",
"neutron_client",
"=",
"self",
".",
"get_client",
"(",
")",
"search_opts",
"=",
"{",
"'fields'",
":",
"[",
"'id'",
",",
"'name'",
"]",
"}",
"if",
"self",
".",
"pagination_support",
":",
"if",
"page_size",
":",
"search_opts",
".",
"update",
"(",
"{",
"'limit'",
":",
"page_size",
"}",
")",
"sec_group_ids",
"=",
"set",
"(",
")",
"for",
"rule",
"in",
"data",
":",
"for",
"key",
"in",
"self",
".",
"replace_rules",
":",
"if",
"rule",
".",
"get",
"(",
"key",
")",
":",
"sec_group_ids",
".",
"add",
"(",
"rule",
"[",
"key",
"]",
")",
"sec_group_ids",
"=",
"list",
"(",
"sec_group_ids",
")",
"def",
"_get_sec_group_list",
"(",
"sec_group_ids",
")",
":",
"search_opts",
"[",
"'id'",
"]",
"=",
"sec_group_ids",
"return",
"neutron_client",
".",
"list_security_groups",
"(",
"*",
"*",
"search_opts",
")",
".",
"get",
"(",
"'security_groups'",
",",
"[",
"]",
")",
"try",
":",
"secgroups",
"=",
"_get_sec_group_list",
"(",
"sec_group_ids",
")",
"except",
"exceptions",
".",
"RequestURITooLong",
"as",
"uri_len_exc",
":",
"# Length of a query filter on security group rule id",
"# id=<uuid>& (with len(uuid)=36)",
"sec_group_id_filter_len",
"=",
"40",
"# The URI is too long because of too many sec_group_id filters",
"# Use the excess attribute of the exception to know how many",
"# sec_group_id filters can be inserted into a single request",
"sec_group_count",
"=",
"len",
"(",
"sec_group_ids",
")",
"max_size",
"=",
"(",
"(",
"sec_group_id_filter_len",
"*",
"sec_group_count",
")",
"-",
"uri_len_exc",
".",
"excess",
")",
"chunk_size",
"=",
"max_size",
"//",
"sec_group_id_filter_len",
"secgroups",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"sec_group_count",
",",
"chunk_size",
")",
":",
"secgroups",
".",
"extend",
"(",
"_get_sec_group_list",
"(",
"sec_group_ids",
"[",
"i",
":",
"i",
"+",
"chunk_size",
"]",
")",
")",
"return",
"dict",
"(",
"[",
"(",
"sg",
"[",
"'id'",
"]",
",",
"sg",
"[",
"'name'",
"]",
")",
"for",
"sg",
"in",
"secgroups",
"if",
"sg",
"[",
"'name'",
"]",
"]",
")"
] |
Do any preprocessing of the lists . | def process_lists ( self ) : for l1_idx , obj1 in enumerate ( self . l1 ) : for l2_idx , obj2 in enumerate ( self . l2 ) : if self . equal ( obj1 , obj2 ) : self . matches . add ( ( l1_idx , l2_idx ) ) | 5,201 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/comparator.py#L45-L50 | [
"def",
"etcd",
"(",
"url",
"=",
"DEFAULT_URL",
",",
"mock",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mock",
":",
"from",
"etc",
".",
"adapters",
".",
"mock",
"import",
"MockAdapter",
"adapter_class",
"=",
"MockAdapter",
"else",
":",
"from",
"etc",
".",
"adapters",
".",
"etcd",
"import",
"EtcdAdapter",
"adapter_class",
"=",
"EtcdAdapter",
"return",
"Client",
"(",
"adapter_class",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
")"
] |
Get elements equal to the idx th in src from the other list . | def get_matches ( self , src , src_idx ) : if src not in ( 'l1' , 'l2' ) : raise ValueError ( 'Must have one of "l1" or "l2" as src' ) if src == 'l1' : target_list = self . l2 else : target_list = self . l1 comparator = { 'l1' : lambda s_idx , t_idx : ( s_idx , t_idx ) in self . matches , 'l2' : lambda s_idx , t_idx : ( t_idx , s_idx ) in self . matches , } [ src ] return [ ( trg_idx , obj ) for trg_idx , obj in enumerate ( target_list ) if comparator ( src_idx , trg_idx ) ] | 5,202 | https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/comparator.py#L56-L74 | [
"def",
"create_stream_subscription",
"(",
"self",
",",
"stream",
",",
"on_data",
",",
"timeout",
"=",
"60",
")",
":",
"options",
"=",
"rest_pb2",
".",
"StreamSubscribeRequest",
"(",
")",
"options",
".",
"stream",
"=",
"stream",
"manager",
"=",
"WebSocketSubscriptionManager",
"(",
"self",
".",
"_client",
",",
"resource",
"=",
"'stream'",
",",
"options",
"=",
"options",
")",
"# Represent subscription as a future",
"subscription",
"=",
"WebSocketSubscriptionFuture",
"(",
"manager",
")",
"wrapped_callback",
"=",
"functools",
".",
"partial",
"(",
"_wrap_callback_parse_stream_data",
",",
"subscription",
",",
"on_data",
")",
"manager",
".",
"open",
"(",
"wrapped_callback",
",",
"instance",
"=",
"self",
".",
"_instance",
")",
"# Wait until a reply or exception is received",
"subscription",
".",
"reply",
"(",
"timeout",
"=",
"timeout",
")",
"return",
"subscription"
] |
This function defines the ligand atoms that are closest to the residues that will be plotted in the final graph . | def find_the_closest_atoms ( self , topology ) : # The measurements are made to ligand molecule without hydrogen atoms (ligand_noH) because the # hydrogen atoms are not plotted in the final graph self . universe . load_new ( topology ) self . universe . ligand_noH = self . universe . ligand . select_atoms ( "not name H*" ) ligand_positions = self . universe . ligand_noH . positions for residue in self . dict_of_plotted_res . keys ( ) : residue_selection = self . universe . select_atoms ( "resname " + residue [ 0 ] + " and resid " + residue [ 1 ] + " and segid " + residue [ 2 ] ) residue_positions = residue_selection . positions dist_array = MDAnalysis . analysis . distances . distance_array ( ligand_positions , residue_positions ) min_values_per_atom = { } i = 0 for atom in self . universe . ligand_noH : min_values_per_atom [ atom . name ] = dist_array [ i ] . min ( ) i += 1 sorted_min_values = sorted ( min_values_per_atom . items ( ) , key = operator . itemgetter ( 1 ) ) self . closest_atoms [ residue ] = [ ( sorted_min_values [ 0 ] [ 0 ] , sorted_min_values [ 0 ] [ 1 ] ) ] | 5,203 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L130-L152 | [
"def",
"calc_regenerated",
"(",
"self",
",",
"lastvotetime",
")",
":",
"delta",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"-",
"datetime",
".",
"strptime",
"(",
"lastvotetime",
",",
"'%Y-%m-%dT%H:%M:%S'",
")",
"td",
"=",
"delta",
".",
"days",
"ts",
"=",
"delta",
".",
"seconds",
"tt",
"=",
"(",
"td",
"*",
"86400",
")",
"+",
"ts",
"return",
"tt",
"*",
"10000",
"/",
"86400",
"/",
"5"
] |
This function loads all relevant data - except trajectories since those are dealt with one at a time . Therefore this process only needs to be done once and every time a trajectory needs to be loaded it can be loaded seperataly and the Data object can be shared across LINTools processes . | def load_data ( self , topology , mol_file , ligand_name , offset = 0 ) : self . load_topology ( topology ) self . renumber_system ( offset ) self . rename_ligand ( ligand_name , mol_file ) self . load_mol ( mol_file ) | 5,204 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L153-L163 | [
"def",
"update_encoding",
"(",
"self",
",",
"encoding",
")",
":",
"value",
"=",
"str",
"(",
"encoding",
")",
".",
"upper",
"(",
")",
"self",
".",
"set_value",
"(",
"value",
")"
] |
In case user wants to analyse only a single topology file this process will determine the residues that should be plotted and find the ligand atoms closest to these residues . | def analyse_topology ( self , topology , cutoff = 3.5 ) : self . define_residues_for_plotting_topology ( cutoff ) self . find_the_closest_atoms ( topology ) | 5,205 | https://github.com/ldomic/lintools/blob/d825a4a7b35f3f857d3b81b46c9aee72b0ec697a/lintools/data.py#L165-L172 | [
"def",
"metadata",
"(",
"self",
",",
"delete",
"=",
"False",
")",
":",
"if",
"delete",
":",
"return",
"self",
".",
"_session",
".",
"delete",
"(",
"self",
".",
"__v1",
"(",
")",
"+",
"\"/metadata\"",
")",
".",
"json",
"(",
")",
"else",
":",
"return",
"self",
".",
"_session",
".",
"get",
"(",
"self",
".",
"__v1",
"(",
")",
"+",
"\"/metadata\"",
")",
".",
"json",
"(",
")"
] |
Parse the header and return a header object | def get_header ( vcf_file_path ) : logger . info ( "Parsing header of file {0}" . format ( vcf_file_path ) ) head = HeaderParser ( ) handle = get_vcf_handle ( infile = vcf_file_path ) # Parse the header for line in handle : line = line . rstrip ( ) if line . startswith ( '#' ) : if line . startswith ( '##' ) : head . parse_meta_data ( line ) else : head . parse_header_line ( line ) else : break handle . close ( ) return head | 5,206 | https://github.com/robinandeer/puzzle/blob/9476f05b416d3a5135d25492cb31411fdf831c58/puzzle/utils/headers.py#L20-L45 | [
"def",
"delete_vmss_vms",
"(",
"access_token",
",",
"subscription_id",
",",
"resource_group",
",",
"vmss_name",
",",
"vm_ids",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourceGroups/'",
",",
"resource_group",
",",
"'/providers/Microsoft.Compute/virtualMachineScaleSets/'",
",",
"vmss_name",
",",
"'/delete?api-version='",
",",
"COMP_API",
"]",
")",
"body",
"=",
"'{\"instanceIds\" : '",
"+",
"vm_ids",
"+",
"'}'",
"return",
"do_post",
"(",
"endpoint",
",",
"body",
",",
"access_token",
")"
] |
Sample 2D distribution of points in lon lat | def sample_lonlat ( self , n ) : # From http://en.wikipedia.org/wiki/Ellipse#General_parametric_form # However, Martin et al. (2009) use PA theta "from North to East" # Definition of phi (position angle) is offset by pi/4 # Definition of t (eccentric anamoly) remains the same (x,y-frame usual) # In the end, everything is trouble because we use glon, glat... radius = self . sample_radius ( n ) a = radius b = self . jacobian * radius t = 2. * np . pi * np . random . rand ( n ) cost , sint = np . cos ( t ) , np . sin ( t ) phi = np . pi / 2. - np . deg2rad ( self . theta ) cosphi , sinphi = np . cos ( phi ) , np . sin ( phi ) x = a * cost * cosphi - b * sint * sinphi y = a * cost * sinphi + b * sint * cosphi if self . projector is None : logger . debug ( "Creating AITOFF projector for sampling" ) projector = Projector ( self . lon , self . lat , 'ait' ) else : projector = self . projector lon , lat = projector . imageToSphere ( x , y ) return lon , lat | 5,207 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/kernel.py#L196-L222 | [
"def",
"guess_manifest_media_type",
"(",
"content",
")",
":",
"encoding",
"=",
"guess_json_utf",
"(",
"content",
")",
"try",
":",
"manifest",
"=",
"json",
".",
"loads",
"(",
"content",
".",
"decode",
"(",
"encoding",
")",
")",
"except",
"(",
"ValueError",
",",
"# Not valid JSON",
"TypeError",
",",
"# Not an object",
"UnicodeDecodeError",
")",
":",
"# Unable to decode the bytes",
"logger",
".",
"exception",
"(",
"\"Unable to decode JSON\"",
")",
"logger",
".",
"debug",
"(",
"\"response content (%s): %r\"",
",",
"encoding",
",",
"content",
")",
"return",
"None",
"try",
":",
"return",
"manifest",
"[",
"'mediaType'",
"]",
"except",
"KeyError",
":",
"# no mediaType key",
"if",
"manifest",
".",
"get",
"(",
"'schemaVersion'",
")",
"==",
"1",
":",
"return",
"get_manifest_media_type",
"(",
"'v1'",
")",
"logger",
".",
"warning",
"(",
"\"no mediaType or schemaVersion=1 in manifest, keys: %s\"",
",",
"manifest",
".",
"keys",
"(",
")",
")"
] |
groupby which sorts the input discards the key and returns the output as a sequence of lists . | def group ( iterable , key ) : for _ , grouped in groupby ( sorted ( iterable , key = key ) , key = key ) : yield list ( grouped ) | 5,208 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/aggregate.py#L41-L47 | [
"def",
"match_url",
"(",
"self",
",",
"request",
")",
":",
"matched",
"=",
"False",
"if",
"self",
".",
"exact_url",
":",
"if",
"re",
".",
"match",
"(",
"\"%s$\"",
"%",
"(",
"self",
".",
"url",
",",
")",
",",
"request",
".",
"path",
")",
":",
"matched",
"=",
"True",
"elif",
"re",
".",
"match",
"(",
"\"%s\"",
"%",
"self",
".",
"url",
",",
"request",
".",
"path",
")",
":",
"matched",
"=",
"True",
"return",
"matched"
] |
Straightforward sum of the given keyname . | def aggregate_count ( keyname ) : def inner ( docs ) : return sum ( doc [ keyname ] for doc in docs ) return keyname , inner | 5,209 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/aggregate.py#L50-L57 | [
"def",
"get_resource_or_collection",
"(",
"cls",
",",
"request_args",
",",
"id",
"=",
"None",
")",
":",
"if",
"id",
":",
"try",
":",
"r",
"=",
"cls",
".",
"get_resource",
"(",
"request_args",
")",
"except",
"DoesNotExist",
":",
"r",
"=",
"application_codes",
".",
"error_response",
"(",
"[",
"application_codes",
".",
"RESOURCE_NOT_FOUND",
"]",
")",
"else",
":",
"try",
":",
"r",
"=",
"cls",
".",
"get_collection",
"(",
"request_args",
")",
"except",
"Exception",
"as",
"e",
":",
"r",
"=",
"application_codes",
".",
"error_response",
"(",
"[",
"application_codes",
".",
"BAD_FORMAT_VIOLATION",
"]",
")",
"return",
"r"
] |
Compute an aggregate rate for rate_key weighted according to count_rate . | def aggregate_rate ( rate_key , count_key ) : def inner ( docs ) : total = sum ( doc [ count_key ] for doc in docs ) weighted_total = sum ( doc [ rate_key ] * doc [ count_key ] for doc in docs ) total_rate = weighted_total / total return total_rate return rate_key , inner | 5,210 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/aggregate.py#L60-L71 | [
"def",
"download_listing",
"(",
"self",
",",
"file",
":",
"Optional",
"[",
"IO",
"]",
",",
"duration_timeout",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
")",
"->",
"ListingResponse",
":",
"if",
"self",
".",
"_session_state",
"!=",
"SessionState",
".",
"directory_request_sent",
":",
"raise",
"RuntimeError",
"(",
"'File request not sent'",
")",
"self",
".",
"_session_state",
"=",
"SessionState",
".",
"file_request_sent",
"yield",
"from",
"self",
".",
"download",
"(",
"file",
"=",
"file",
",",
"rewind",
"=",
"False",
",",
"duration_timeout",
"=",
"duration_timeout",
")",
"try",
":",
"if",
"self",
".",
"_response",
".",
"body",
".",
"tell",
"(",
")",
"==",
"0",
":",
"listings",
"=",
"(",
")",
"elif",
"self",
".",
"_listing_type",
"==",
"'mlsd'",
":",
"self",
".",
"_response",
".",
"body",
".",
"seek",
"(",
"0",
")",
"machine_listings",
"=",
"wpull",
".",
"protocol",
".",
"ftp",
".",
"util",
".",
"parse_machine_listing",
"(",
"self",
".",
"_response",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
",",
"errors",
"=",
"'surrogateescape'",
")",
",",
"convert",
"=",
"True",
",",
"strict",
"=",
"False",
")",
"listings",
"=",
"list",
"(",
"wpull",
".",
"protocol",
".",
"ftp",
".",
"util",
".",
"machine_listings_to_file_entries",
"(",
"machine_listings",
")",
")",
"else",
":",
"self",
".",
"_response",
".",
"body",
".",
"seek",
"(",
"0",
")",
"file",
"=",
"io",
".",
"TextIOWrapper",
"(",
"self",
".",
"_response",
".",
"body",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'surrogateescape'",
")",
"listing_parser",
"=",
"ListingParser",
"(",
"file",
"=",
"file",
")",
"listings",
"=",
"list",
"(",
"listing_parser",
".",
"parse_input",
"(",
")",
")",
"_logger",
".",
"debug",
"(",
"'Listing detected as %s'",
",",
"listing_parser",
".",
"type",
")",
"# We don't want the file to be closed when exiting this function",
"file",
".",
"detach",
"(",
")",
"except",
"(",
"ListingError",
",",
"ValueError",
")",
"as",
"error",
":",
"raise",
"ProtocolError",
"(",
"*",
"error",
".",
"args",
")",
"from",
"error",
"self",
".",
"_response",
".",
"files",
"=",
"listings",
"self",
".",
"_response",
".",
"body",
".",
"seek",
"(",
"0",
")",
"self",
".",
"_session_state",
"=",
"SessionState",
".",
"response_received",
"return",
"self",
".",
"_response"
] |
Given docs and aggregations return a single document with the aggregations applied . | def make_aggregate ( docs , aggregations ) : new_doc = dict ( docs [ 0 ] ) for keyname , aggregation_function in aggregations : new_doc [ keyname ] = aggregation_function ( docs ) return new_doc | 5,211 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/ga/plugins/aggregate.py#L74-L84 | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"(",
"yield",
"from",
"super",
"(",
")",
".",
"close",
"(",
")",
")",
":",
"return",
"False",
"for",
"adapter",
"in",
"self",
".",
"_ethernet_adapters",
".",
"values",
"(",
")",
":",
"if",
"adapter",
"is",
"not",
"None",
":",
"for",
"nio",
"in",
"adapter",
".",
"ports",
".",
"values",
"(",
")",
":",
"if",
"nio",
"and",
"isinstance",
"(",
"nio",
",",
"NIOUDP",
")",
":",
"self",
".",
"manager",
".",
"port_manager",
".",
"release_udp_port",
"(",
"nio",
".",
"lport",
",",
"self",
".",
"_project",
")",
"try",
":",
"self",
".",
"acpi_shutdown",
"=",
"False",
"yield",
"from",
"self",
".",
"stop",
"(",
")",
"except",
"VMwareError",
":",
"pass",
"if",
"self",
".",
"linked_clone",
":",
"yield",
"from",
"self",
".",
"manager",
".",
"remove_from_vmware_inventory",
"(",
"self",
".",
"_vmx_path",
")"
] |
Sanitize the JSON string using the Bleach HTML tag remover | def json ( value ) : uncleaned = jsonlib . dumps ( value ) clean = bleach . clean ( uncleaned ) return mark_safe ( clean ) | 5,212 | https://github.com/MasterKale/django-cra-helper/blob/ba50c643c181a18b80ee9bbdbea74b58abd6daad/cra_helper/templatetags/cra_helper_tags.py#L15-L21 | [
"def",
"dump_zone_file",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"for",
"zone",
"in",
"sorted",
"(",
"self",
",",
"key",
"=",
"attrgetter",
"(",
"'country'",
")",
")",
":",
"text",
"=",
"[",
"'%s\t%s\t%s'",
"%",
"(",
"zone",
".",
"country",
",",
"utils",
".",
"to_iso6709",
"(",
"zone",
".",
"latitude",
",",
"zone",
".",
"longitude",
",",
"format",
"=",
"'dms'",
")",
"[",
":",
"-",
"1",
"]",
",",
"zone",
".",
"zone",
")",
",",
"]",
"if",
"zone",
".",
"comments",
":",
"text",
".",
"append",
"(",
"'\t%s'",
"%",
"', '",
".",
"join",
"(",
"zone",
".",
"comments",
")",
")",
"data",
".",
"append",
"(",
"''",
".",
"join",
"(",
"text",
")",
")",
"return",
"data"
] |
Finds a subset of nondominated individuals in a given list | def find_pareto_front ( population ) : pareto_front = set ( range ( len ( population ) ) ) for i in range ( len ( population ) ) : if i not in pareto_front : continue ind1 = population [ i ] for j in range ( i + 1 , len ( population ) ) : ind2 = population [ j ] # if individuals are equal on all objectives, mark one of them (the first encountered one) as dominated # to prevent excessive growth of the Pareto front if ind2 . fitness . dominates ( ind1 . fitness ) or ind1 . fitness == ind2 . fitness : pareto_front . discard ( i ) if ind1 . fitness . dominates ( ind2 . fitness ) : pareto_front . discard ( j ) return pareto_front | 5,213 | https://github.com/cfusting/fastgp/blob/6cf3c5d14abedaea064feef6ca434ee806a11756/fastgp/algorithms/afpo.py#L28-L53 | [
"def",
"_ParseLogonApplications",
"(",
"self",
",",
"parser_mediator",
",",
"registry_key",
")",
":",
"for",
"application",
"in",
"self",
".",
"_LOGON_APPLICATIONS",
":",
"command_value",
"=",
"registry_key",
".",
"GetValueByName",
"(",
"application",
")",
"if",
"not",
"command_value",
":",
"continue",
"values_dict",
"=",
"{",
"'Application'",
":",
"application",
",",
"'Command'",
":",
"command_value",
".",
"GetDataAsObject",
"(",
")",
",",
"'Trigger'",
":",
"'Logon'",
"}",
"event_data",
"=",
"windows_events",
".",
"WindowsRegistryEventData",
"(",
")",
"event_data",
".",
"key_path",
"=",
"registry_key",
".",
"path",
"event_data",
".",
"offset",
"=",
"registry_key",
".",
"offset",
"event_data",
".",
"regvalue",
"=",
"values_dict",
"event_data",
".",
"source_append",
"=",
"': Winlogon'",
"event",
"=",
"time_events",
".",
"DateTimeValuesEvent",
"(",
"registry_key",
".",
"last_written_time",
",",
"definitions",
".",
"TIME_DESCRIPTION_WRITTEN",
")",
"parser_mediator",
".",
"ProduceEventWithEventData",
"(",
"event",
",",
"event_data",
")"
] |
Casts Python lists and tuples to a numpy array or raises an AssertionError . | def _to_ndarray ( self , a ) : if isinstance ( a , ( list , tuple ) ) : a = numpy . array ( a ) if not is_ndarray ( a ) : raise TypeError ( "Expected an ndarray but got object of type '{}' instead" . format ( type ( a ) ) ) return a | 5,214 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L310-L319 | [
"def",
"_CalculateDigestHash",
"(",
"self",
",",
"file_entry",
",",
"data_stream_name",
")",
":",
"file_object",
"=",
"file_entry",
".",
"GetFileObject",
"(",
"data_stream_name",
"=",
"data_stream_name",
")",
"if",
"not",
"file_object",
":",
"return",
"None",
"try",
":",
"file_object",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"hasher_object",
"=",
"hashers_manager",
".",
"HashersManager",
".",
"GetHasher",
"(",
"'sha256'",
")",
"data",
"=",
"file_object",
".",
"read",
"(",
"self",
".",
"_READ_BUFFER_SIZE",
")",
"while",
"data",
":",
"hasher_object",
".",
"Update",
"(",
"data",
")",
"data",
"=",
"file_object",
".",
"read",
"(",
"self",
".",
"_READ_BUFFER_SIZE",
")",
"finally",
":",
"file_object",
".",
"close",
"(",
")",
"return",
"hasher_object",
".",
"GetStringDigest",
"(",
")"
] |
Return the absolute value of a number . | def fn_abs ( self , value ) : if is_ndarray ( value ) : return numpy . absolute ( value ) else : return abs ( value ) | 5,215 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L321-L332 | [
"def",
"union",
"(",
"self",
",",
"*",
"dstreams",
")",
":",
"if",
"not",
"dstreams",
":",
"raise",
"ValueError",
"(",
"\"should have at least one DStream to union\"",
")",
"if",
"len",
"(",
"dstreams",
")",
"==",
"1",
":",
"return",
"dstreams",
"[",
"0",
"]",
"if",
"len",
"(",
"set",
"(",
"s",
".",
"_jrdd_deserializer",
"for",
"s",
"in",
"dstreams",
")",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"All DStreams should have same serializer\"",
")",
"if",
"len",
"(",
"set",
"(",
"s",
".",
"_slideDuration",
"for",
"s",
"in",
"dstreams",
")",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"All DStreams should have same slide duration\"",
")",
"cls",
"=",
"SparkContext",
".",
"_jvm",
".",
"org",
".",
"apache",
".",
"spark",
".",
"streaming",
".",
"api",
".",
"java",
".",
"JavaDStream",
"jdstreams",
"=",
"SparkContext",
".",
"_gateway",
".",
"new_array",
"(",
"cls",
",",
"len",
"(",
"dstreams",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"dstreams",
")",
")",
":",
"jdstreams",
"[",
"i",
"]",
"=",
"dstreams",
"[",
"i",
"]",
".",
"_jdstream",
"return",
"DStream",
"(",
"self",
".",
"_jssc",
".",
"union",
"(",
"jdstreams",
")",
",",
"self",
",",
"dstreams",
"[",
"0",
"]",
".",
"_jrdd_deserializer",
")"
] |
Return an array mask . | def fn_get_mask ( self , value ) : value = self . _to_ndarray ( value ) if numpy . ma . is_masked ( value ) : return value . mask else : return numpy . zeros ( value . shape ) . astype ( bool ) | 5,216 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L334-L347 | [
"def",
"_schedule_sending_init_updates",
"(",
"self",
")",
":",
"def",
"_enqueue_non_rtc_init_updates",
"(",
")",
":",
"LOG",
".",
"debug",
"(",
"'Scheduled queuing of initial Non-RTC UPDATEs'",
")",
"tm",
"=",
"self",
".",
"_core_service",
".",
"table_manager",
"self",
".",
"comm_all_best_paths",
"(",
"tm",
".",
"global_tables",
")",
"self",
".",
"_sent_init_non_rtc_update",
"=",
"True",
"# Stop the timer as we have handled RTC EOR",
"self",
".",
"_rtc_eor_timer",
".",
"stop",
"(",
")",
"self",
".",
"_rtc_eor_timer",
"=",
"None",
"self",
".",
"_sent_init_non_rtc_update",
"=",
"False",
"self",
".",
"_rtc_eor_timer",
"=",
"self",
".",
"_create_timer",
"(",
"Peer",
".",
"RTC_EOR_TIMER_NAME",
",",
"_enqueue_non_rtc_init_updates",
")",
"# Start timer for sending initial updates",
"self",
".",
"_rtc_eor_timer",
".",
"start",
"(",
"const",
".",
"RTC_EOR_DEFAULT_TIME",
",",
"now",
"=",
"False",
")",
"LOG",
".",
"debug",
"(",
"'Scheduled sending of initial Non-RTC UPDATEs after:'",
"' %s sec'",
",",
"const",
".",
"RTC_EOR_DEFAULT_TIME",
")"
] |
Return the minimum of an array ignoring any NaNs . | def fn_min ( self , a , axis = None ) : return numpy . nanmin ( self . _to_ndarray ( a ) , axis = axis ) | 5,217 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L349-L357 | [
"def",
"get_ldap_users",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"conf_LDAP_SYNC_USER",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"user_keys",
"=",
"set",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_ATTRIBUTES",
".",
"keys",
"(",
")",
")",
"user_keys",
".",
"update",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_EXTRA_ATTRIBUTES",
")",
"uri_users_server",
",",
"users",
"=",
"self",
".",
"ldap_search",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_FILTER",
",",
"user_keys",
",",
"self",
".",
"conf_LDAP_SYNC_USER_INCREMENTAL",
",",
"self",
".",
"conf_LDAP_SYNC_USER_FILTER_INCREMENTAL",
")",
"logger",
".",
"debug",
"(",
"\"Retrieved %d users from %s LDAP server\"",
"%",
"(",
"len",
"(",
"users",
")",
",",
"uri_users_server",
")",
")",
"return",
"(",
"uri_users_server",
",",
"users",
")"
] |
Return the maximum of an array ignoring any NaNs . | def fn_max ( self , a , axis = None ) : return numpy . nanmax ( self . _to_ndarray ( a ) , axis = axis ) | 5,218 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L370-L378 | [
"def",
"get_ldap_users",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"conf_LDAP_SYNC_USER",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"user_keys",
"=",
"set",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_ATTRIBUTES",
".",
"keys",
"(",
")",
")",
"user_keys",
".",
"update",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_EXTRA_ATTRIBUTES",
")",
"uri_users_server",
",",
"users",
"=",
"self",
".",
"ldap_search",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_FILTER",
",",
"user_keys",
",",
"self",
".",
"conf_LDAP_SYNC_USER_INCREMENTAL",
",",
"self",
".",
"conf_LDAP_SYNC_USER_FILTER_INCREMENTAL",
")",
"logger",
".",
"debug",
"(",
"\"Retrieved %d users from %s LDAP server\"",
"%",
"(",
"len",
"(",
"users",
")",
",",
"uri_users_server",
")",
")",
"return",
"(",
"uri_users_server",
",",
"users",
")"
] |
Compute the median of an array ignoring NaNs . | def fn_median ( self , a , axis = None ) : return numpy . nanmedian ( self . _to_ndarray ( a ) , axis = axis ) | 5,219 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L380-L388 | [
"def",
"get_ldap_users",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"conf_LDAP_SYNC_USER",
")",
":",
"return",
"(",
"None",
",",
"None",
")",
"user_keys",
"=",
"set",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_ATTRIBUTES",
".",
"keys",
"(",
")",
")",
"user_keys",
".",
"update",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_EXTRA_ATTRIBUTES",
")",
"uri_users_server",
",",
"users",
"=",
"self",
".",
"ldap_search",
"(",
"self",
".",
"conf_LDAP_SYNC_USER_FILTER",
",",
"user_keys",
",",
"self",
".",
"conf_LDAP_SYNC_USER_INCREMENTAL",
",",
"self",
".",
"conf_LDAP_SYNC_USER_FILTER_INCREMENTAL",
")",
"logger",
".",
"debug",
"(",
"\"Retrieved %d users from %s LDAP server\"",
"%",
"(",
"len",
"(",
"users",
")",
",",
"uri_users_server",
")",
")",
"return",
"(",
"uri_users_server",
",",
"users",
")"
] |
Compute the arithmetic mean of an array ignoring NaNs . | def fn_mean ( self , a , axis = None ) : return numpy . nanmean ( self . _to_ndarray ( a ) , axis = axis ) | 5,220 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L390-L398 | [
"def",
"create_rpc_request_header",
"(",
"self",
")",
":",
"rpcheader",
"=",
"RpcRequestHeaderProto",
"(",
")",
"rpcheader",
".",
"rpcKind",
"=",
"2",
"# rpcheaderproto.RpcKindProto.Value('RPC_PROTOCOL_BUFFER')",
"rpcheader",
".",
"rpcOp",
"=",
"0",
"# rpcheaderproto.RpcPayloadOperationProto.Value('RPC_FINAL_PACKET')",
"rpcheader",
".",
"callId",
"=",
"self",
".",
"call_id",
"rpcheader",
".",
"retryCount",
"=",
"-",
"1",
"rpcheader",
".",
"clientId",
"=",
"self",
".",
"client_id",
"[",
"0",
":",
"16",
"]",
"if",
"self",
".",
"call_id",
"==",
"-",
"3",
":",
"self",
".",
"call_id",
"=",
"0",
"else",
":",
"self",
".",
"call_id",
"+=",
"1",
"# Serialize delimited",
"s_rpcHeader",
"=",
"rpcheader",
".",
"SerializeToString",
"(",
")",
"log_protobuf_message",
"(",
"\"RpcRequestHeaderProto (len: %d)\"",
"%",
"(",
"len",
"(",
"s_rpcHeader",
")",
")",
",",
"rpcheader",
")",
"return",
"s_rpcHeader"
] |
Compute the standard deviation of an array ignoring NaNs . | def fn_std ( self , a , axis = None ) : return numpy . nanstd ( self . _to_ndarray ( a ) , axis = axis ) | 5,221 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L400-L408 | [
"def",
"configure",
"(",
"self",
",",
"pipe_config",
")",
":",
"# Create a context for evaluating the code for each pipeline. This removes the need",
"# to qualify the class names with the module",
"import",
"ambry",
".",
"etl",
"import",
"sys",
"# ambry.build comes from ambry.bundle.files.PythonSourceFile#import_bundle",
"eval_locals",
"=",
"dict",
"(",
"list",
"(",
"locals",
"(",
")",
".",
"items",
"(",
")",
")",
"+",
"list",
"(",
"ambry",
".",
"etl",
".",
"__dict__",
".",
"items",
"(",
")",
")",
"+",
"list",
"(",
"sys",
".",
"modules",
"[",
"'ambry.build'",
"]",
".",
"__dict__",
".",
"items",
"(",
")",
")",
")",
"replacements",
"=",
"{",
"}",
"def",
"eval_pipe",
"(",
"pipe",
")",
":",
"if",
"isinstance",
"(",
"pipe",
",",
"string_types",
")",
":",
"try",
":",
"return",
"eval",
"(",
"pipe",
",",
"{",
"}",
",",
"eval_locals",
")",
"except",
"SyntaxError",
"as",
"e",
":",
"raise",
"SyntaxError",
"(",
"\"SyntaxError while parsing pipe '{}' from metadata: {}\"",
".",
"format",
"(",
"pipe",
",",
"e",
")",
")",
"else",
":",
"return",
"pipe",
"def",
"pipe_location",
"(",
"pipe",
")",
":",
"\"\"\"Return a location prefix from a pipe, or None if there isn't one \"\"\"",
"if",
"not",
"isinstance",
"(",
"pipe",
",",
"string_types",
")",
":",
"return",
"None",
"elif",
"pipe",
"[",
"0",
"]",
"in",
"'+-$!'",
":",
"return",
"pipe",
"[",
"0",
"]",
"else",
":",
"return",
"None",
"for",
"segment_name",
",",
"pipes",
"in",
"list",
"(",
"pipe_config",
".",
"items",
"(",
")",
")",
":",
"if",
"segment_name",
"==",
"'final'",
":",
"# The 'final' segment is actually a list of names of Bundle methods to call afer the pipeline",
"# completes",
"super",
"(",
"Pipeline",
",",
"self",
")",
".",
"__setattr__",
"(",
"'final'",
",",
"pipes",
")",
"elif",
"segment_name",
"==",
"'replace'",
":",
"for",
"frm",
",",
"to",
"in",
"iteritems",
"(",
"pipes",
")",
":",
"self",
".",
"replace",
"(",
"eval_pipe",
"(",
"frm",
")",
",",
"eval_pipe",
"(",
"to",
")",
")",
"else",
":",
"# Check if any of the pipes have a location command. If not, the pipe",
"# is cleared and the set of pipes replaces the ones that are there.",
"if",
"not",
"any",
"(",
"bool",
"(",
"pipe_location",
"(",
"pipe",
")",
")",
"for",
"pipe",
"in",
"pipes",
")",
":",
"# Nope, they are all clean",
"self",
"[",
"segment_name",
"]",
"=",
"[",
"eval_pipe",
"(",
"pipe",
")",
"for",
"pipe",
"in",
"pipes",
"]",
"else",
":",
"for",
"i",
",",
"pipe",
"in",
"enumerate",
"(",
"pipes",
")",
":",
"if",
"pipe_location",
"(",
"pipe",
")",
":",
"# The pipe is prefixed with a location command",
"location",
"=",
"pipe_location",
"(",
"pipe",
")",
"pipe",
"=",
"pipe",
"[",
"1",
":",
"]",
"else",
":",
"raise",
"PipelineError",
"(",
"'If any pipes in a section have a location command, they all must'",
"' Segment: {} pipes: {}'",
".",
"format",
"(",
"segment_name",
",",
"pipes",
")",
")",
"ep",
"=",
"eval_pipe",
"(",
"pipe",
")",
"if",
"location",
"==",
"'+'",
":",
"# append to the segment",
"self",
"[",
"segment_name",
"]",
".",
"append",
"(",
"ep",
")",
"elif",
"location",
"==",
"'-'",
":",
"# Prepend to the segment",
"self",
"[",
"segment_name",
"]",
".",
"prepend",
"(",
"ep",
")",
"elif",
"location",
"==",
"'!'",
":",
"# Replace a pipe of the same class",
"if",
"isinstance",
"(",
"ep",
",",
"type",
")",
":",
"repl_class",
"=",
"ep",
"else",
":",
"repl_class",
"=",
"ep",
".",
"__class__",
"self",
".",
"replace",
"(",
"repl_class",
",",
"ep",
",",
"segment_name",
")"
] |
Compute the variance of an array ignoring NaNs . | def fn_var ( self , a , axis = None ) : return numpy . nanvar ( self . _to_ndarray ( a ) , axis = axis ) | 5,222 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L410-L418 | [
"def",
"regenerate_recovery_code",
"(",
"self",
",",
"user_id",
")",
":",
"url",
"=",
"self",
".",
"_url",
"(",
"'{}/recovery-code-regeneration'",
".",
"format",
"(",
"user_id",
")",
")",
"return",
"self",
".",
"client",
".",
"post",
"(",
"url",
")"
] |
Return the ceiling of a number . | def fn_ceil ( self , value ) : if is_ndarray ( value ) or isinstance ( value , ( list , tuple ) ) : return numpy . ceil ( self . _to_ndarray ( value ) ) else : return math . ceil ( value ) | 5,223 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L433-L444 | [
"def",
"_ProcessRegistryKeySource",
"(",
"self",
",",
"source",
")",
":",
"keys",
"=",
"source",
".",
"base_source",
".",
"attributes",
".",
"get",
"(",
"\"keys\"",
",",
"[",
"]",
")",
"if",
"not",
"keys",
":",
"return",
"interpolated_paths",
"=",
"artifact_utils",
".",
"InterpolateListKbAttributes",
"(",
"input_list",
"=",
"keys",
",",
"knowledge_base",
"=",
"self",
".",
"knowledge_base",
",",
"ignore_errors",
"=",
"self",
".",
"ignore_interpolation_errors",
")",
"glob_expressions",
"=",
"map",
"(",
"rdf_paths",
".",
"GlobExpression",
",",
"interpolated_paths",
")",
"patterns",
"=",
"[",
"]",
"for",
"pattern",
"in",
"glob_expressions",
":",
"patterns",
".",
"extend",
"(",
"pattern",
".",
"Interpolate",
"(",
"knowledge_base",
"=",
"self",
".",
"knowledge_base",
")",
")",
"patterns",
".",
"sort",
"(",
"key",
"=",
"len",
",",
"reverse",
"=",
"True",
")",
"file_finder_action",
"=",
"rdf_file_finder",
".",
"FileFinderAction",
".",
"Stat",
"(",
")",
"request",
"=",
"rdf_file_finder",
".",
"FileFinderArgs",
"(",
"paths",
"=",
"patterns",
",",
"action",
"=",
"file_finder_action",
",",
"follow_links",
"=",
"True",
",",
"pathtype",
"=",
"rdf_paths",
".",
"PathSpec",
".",
"PathType",
".",
"REGISTRY",
")",
"action",
"=",
"vfs_file_finder",
".",
"RegistryKeyFromClient",
"yield",
"action",
",",
"request"
] |
Return the value cast to an int . | def fn_int ( self , value ) : if is_ndarray ( value ) or isinstance ( value , ( list , tuple ) ) : return self . _to_ndarray ( value ) . astype ( 'int' ) else : return int ( value ) | 5,224 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L446-L457 | [
"def",
"_find_start_time",
"(",
"hdr",
",",
"s_freq",
")",
":",
"start_time",
"=",
"hdr",
"[",
"'stc'",
"]",
"[",
"'creation_time'",
"]",
"for",
"one_stamp",
"in",
"hdr",
"[",
"'stamps'",
"]",
":",
"if",
"one_stamp",
"[",
"'segment_name'",
"]",
".",
"decode",
"(",
")",
"==",
"hdr",
"[",
"'erd'",
"]",
"[",
"'filename'",
"]",
":",
"offset",
"=",
"one_stamp",
"[",
"'start_stamp'",
"]",
"break",
"erd_time",
"=",
"(",
"hdr",
"[",
"'erd'",
"]",
"[",
"'creation_time'",
"]",
"-",
"timedelta",
"(",
"seconds",
"=",
"offset",
"/",
"s_freq",
")",
")",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
"stc_erd_diff",
"=",
"(",
"start_time",
"-",
"erd_time",
")",
".",
"total_seconds",
"(",
")",
"if",
"stc_erd_diff",
">",
"START_TIME_TOL",
":",
"lg",
".",
"warn",
"(",
"'Time difference between ERD and STC is {} s so using ERD time'",
"' at {}'",
".",
"format",
"(",
"stc_erd_diff",
",",
"erd_time",
")",
")",
"start_time",
"=",
"erd_time",
"return",
"start_time"
] |
Return the value cast to a float . | def fn_float ( self , value ) : if is_ndarray ( value ) or isinstance ( value , ( list , tuple ) ) : return self . _to_ndarray ( value ) . astype ( 'float' ) else : return float ( value ) | 5,225 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L511-L522 | [
"def",
"returnJobReqs",
"(",
"self",
",",
"jobReqs",
")",
":",
"# Since we are only reading this job's specific values from the state file, we don't",
"# need a lock",
"jobState",
"=",
"self",
".",
"_JobState",
"(",
"self",
".",
"_CacheState",
".",
"_load",
"(",
"self",
".",
"cacheStateFile",
")",
".",
"jobState",
"[",
"self",
".",
"jobID",
"]",
")",
"for",
"x",
"in",
"list",
"(",
"jobState",
".",
"jobSpecificFiles",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"deleteLocalFile",
"(",
"x",
")",
"with",
"self",
".",
"_CacheState",
".",
"open",
"(",
"self",
")",
"as",
"cacheInfo",
":",
"cacheInfo",
".",
"sigmaJob",
"-=",
"jobReqs"
] |
Coerce a datetime or string into datetime . datetime object | def make_datetime ( dt , date_parser = parse_date ) : if ( isinstance ( dt , ( datetime . datetime , datetime . date , datetime . time , pd . Timestamp , np . datetime64 ) ) or dt in ( float ( 'nan' ) , float ( 'inf' ) , float ( '-inf' ) , None , '' ) ) : return dt if isinstance ( dt , ( float , int ) ) : return datetime_from_ordinal_float ( dt ) if isinstance ( dt , datetime . date ) : return datetime . datetime ( dt . year , dt . month , dt . day ) if isinstance ( dt , datetime . time ) : return datetime . datetime ( 1 , 1 , 1 , dt . hour , dt . minute , dt . second , dt . microsecond ) if not dt : return datetime . datetime ( 1970 , 1 , 1 ) if isinstance ( dt , basestring ) : try : return date_parser ( dt ) except ValueError : print ( 'Unable to make_datetime({})' . format ( dt ) ) raise try : return datetime . datetime ( * dt . timetuple ( ) [ : 7 ] ) except AttributeError : try : dt = list ( dt ) if 0 < len ( dt ) < 7 : try : return datetime . datetime ( * dt [ : 7 ] ) except ( TypeError , IndexError , ValueError ) : pass except ( TypeError , IndexError , ValueError , AttributeError ) : # dt is not iterable return dt return [ make_datetime ( val , date_parser = date_parser ) for val in dt ] | 5,226 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L140-L192 | [
"def",
"load_writer_configs",
"(",
"writer_configs",
",",
"ppp_config_dir",
",",
"*",
"*",
"writer_kwargs",
")",
":",
"try",
":",
"writer_info",
"=",
"read_writer_config",
"(",
"writer_configs",
")",
"writer_class",
"=",
"writer_info",
"[",
"'writer'",
"]",
"except",
"(",
"ValueError",
",",
"KeyError",
",",
"yaml",
".",
"YAMLError",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid writer configs: \"",
"\"'{}'\"",
".",
"format",
"(",
"writer_configs",
")",
")",
"init_kwargs",
",",
"kwargs",
"=",
"writer_class",
".",
"separate_init_kwargs",
"(",
"writer_kwargs",
")",
"writer",
"=",
"writer_class",
"(",
"ppp_config_dir",
"=",
"ppp_config_dir",
",",
"config_files",
"=",
"writer_configs",
",",
"*",
"*",
"init_kwargs",
")",
"return",
"writer",
",",
"kwargs"
] |
Quantize a datetime to integer years months days hours minutes seconds or microseconds | def quantize_datetime ( dt , resolution = None ) : # FIXME: this automatically truncates off microseconds just because timtuple() only goes out to sec resolution = int ( resolution or 6 ) if hasattr ( dt , 'timetuple' ) : dt = dt . timetuple ( ) # strips timezone info if isinstance ( dt , time . struct_time ) : # strip last 3 fields (tm_wday, tm_yday, tm_isdst) dt = list ( dt ) [ : 6 ] # struct_time has no microsecond, but accepts float seconds dt += [ int ( ( dt [ 5 ] - int ( dt [ 5 ] ) ) * 1000000 ) ] dt [ 5 ] = int ( dt [ 5 ] ) return datetime . datetime ( * ( dt [ : resolution ] + [ 1 ] * max ( 3 - resolution , 0 ) ) ) if isinstance ( dt , tuple ) and len ( dt ) <= 9 and all ( isinstance ( val , ( float , int ) ) for val in dt ) : dt = list ( dt ) + [ 0 ] * ( max ( 6 - len ( dt ) , 0 ) ) # if the 6th element of the tuple looks like a float set of seconds need to add microseconds if len ( dt ) == 6 and isinstance ( dt [ 5 ] , float ) : dt = list ( dt ) + [ 1000000 * ( dt [ 5 ] - int ( dt [ 5 ] ) ) ] dt [ 5 ] = int ( dt [ 5 ] ) dt = tuple ( int ( val ) for val in dt ) return datetime . datetime ( * ( dt [ : resolution ] + [ 1 ] * max ( resolution - 3 , 0 ) ) ) return [ quantize_datetime ( value ) for value in dt ] | 5,227 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L229-L266 | [
"def",
"load_module",
"(",
"self",
",",
"path",
",",
"init_func",
")",
":",
"try",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"self",
".",
"_obj",
".",
"load_module",
"(",
"path",
",",
"init_func",
")",
"!=",
"RTC",
".",
"RTC_OK",
":",
"raise",
"exceptions",
".",
"FailedToLoadModuleError",
"(",
"path",
")",
"except",
"CORBA",
".",
"UNKNOWN",
"as",
"e",
":",
"if",
"e",
".",
"args",
"[",
"0",
"]",
"==",
"UNKNOWN_UserException",
":",
"raise",
"exceptions",
".",
"FailedToLoadModuleError",
"(",
"path",
",",
"'CORBA User Exception'",
")",
"else",
":",
"raise"
] |
Generate a date - time tag suitable for appending to a file name . | def timetag_str ( dt = None , sep = '-' , filler = '0' , resolution = 6 ) : resolution = int ( resolution or 6 ) if sep in ( None , False ) : sep = '' sep = str ( sep ) dt = datetime . datetime . now ( ) if dt is None else dt # FIXME: don't use timetuple which truncates microseconds return sep . join ( ( '{0:' + filler + ( '2' if filler else '' ) + 'd}' ) . format ( i ) for i in tuple ( dt . timetuple ( ) [ : resolution ] ) ) | 5,228 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L319-L339 | [
"def",
"Majority",
"(",
"*",
"xs",
",",
"simplify",
"=",
"True",
",",
"conj",
"=",
"False",
")",
":",
"xs",
"=",
"[",
"Expression",
".",
"box",
"(",
"x",
")",
".",
"node",
"for",
"x",
"in",
"xs",
"]",
"if",
"conj",
":",
"terms",
"=",
"list",
"(",
")",
"for",
"_xs",
"in",
"itertools",
".",
"combinations",
"(",
"xs",
",",
"(",
"len",
"(",
"xs",
")",
"+",
"1",
")",
"//",
"2",
")",
":",
"terms",
".",
"append",
"(",
"exprnode",
".",
"or_",
"(",
"*",
"_xs",
")",
")",
"y",
"=",
"exprnode",
".",
"and_",
"(",
"*",
"terms",
")",
"else",
":",
"terms",
"=",
"list",
"(",
")",
"for",
"_xs",
"in",
"itertools",
".",
"combinations",
"(",
"xs",
",",
"len",
"(",
"xs",
")",
"//",
"2",
"+",
"1",
")",
":",
"terms",
".",
"append",
"(",
"exprnode",
".",
"and_",
"(",
"*",
"_xs",
")",
")",
"y",
"=",
"exprnode",
".",
"or_",
"(",
"*",
"terms",
")",
"if",
"simplify",
":",
"y",
"=",
"y",
".",
"simplify",
"(",
")",
"return",
"_expr",
"(",
"y",
")"
] |
Add timezone information to a datetime object only if it is naive . | def make_tz_aware ( dt , tz = 'UTC' , is_dst = None ) : # make sure dt is a datetime, time, or list of datetime/times dt = make_datetime ( dt ) if not isinstance ( dt , ( list , datetime . datetime , datetime . date , datetime . time , pd . Timestamp ) ) : return dt # TODO: deal with sequence of timezones try : tz = dt . tzinfo or tz except ( ValueError , AttributeError , TypeError ) : pass try : tzstr = str ( tz ) . strip ( ) . upper ( ) if tzstr in TZ_ABBREV_NAME : is_dst = is_dst or tzstr . endswith ( 'DT' ) tz = TZ_ABBREV_NAME . get ( tzstr , tz ) except ( ValueError , AttributeError , TypeError ) : pass try : tz = pytz . timezone ( tz ) except ( ValueError , AttributeError , TypeError ) : # from traceback import print_exc # print_exc() pass try : return tz . localize ( dt , is_dst = is_dst ) except ( ValueError , AttributeError , TypeError ) : # from traceback import print_exc # print_exc() # TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta' pass # could be datetime.time, which can't be localized. Insted `replace` the TZ # don't try/except in case dt is not a datetime or time type -- should raise an exception if not isinstance ( dt , list ) : return dt . replace ( tzinfo = tz ) return [ make_tz_aware ( dt0 , tz = tz , is_dst = is_dst ) for dt0 in dt ] | 5,229 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/tutil.py#L349-L408 | [
"def",
"ledger",
"(",
"self",
",",
"ledger_id",
")",
":",
"endpoint",
"=",
"'/ledgers/{ledger_id}'",
".",
"format",
"(",
"ledger_id",
"=",
"ledger_id",
")",
"return",
"self",
".",
"query",
"(",
"endpoint",
")"
] |
decorator to translate the addressType field . | def translate_addresstype ( f ) : @ wraps ( f ) def wr ( r , pc ) : at = r [ "addressType" ] try : r . update ( { "addressType" : POSTCODE_API_TYPEDEFS_ADDRESS_TYPES [ at ] } ) except : logger . warning ( "Warning: {}: " "unknown 'addressType': {}" . format ( pc , at ) ) return f ( r , pc ) return wr | 5,230 | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/typedefs.py#L55-L72 | [
"def",
"spawn_viewer",
"(",
"viewer",
",",
"img",
",",
"filename",
",",
"grace",
")",
":",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'imgdiff-'",
")",
"try",
":",
"imgfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempdir",
",",
"filename",
")",
"img",
".",
"save",
"(",
"imgfile",
")",
"started",
"=",
"time",
".",
"time",
"(",
")",
"subprocess",
".",
"call",
"(",
"[",
"viewer",
",",
"imgfile",
"]",
")",
"elapsed",
"=",
"time",
".",
"time",
"(",
")",
"-",
"started",
"if",
"elapsed",
"<",
"grace",
":",
"# Program exited too quickly. I think it forked and so may not",
"# have had enough time to even start looking for the temp file",
"# we just created. Wait a bit before removing the temp file.",
"time",
".",
"sleep",
"(",
"grace",
"-",
"elapsed",
")",
"finally",
":",
"shutil",
".",
"rmtree",
"(",
"tempdir",
")"
] |
decorator to translate the purposes field . | def translate_purposes ( f ) : @ wraps ( f ) def wr ( r , pc ) : tmp = [ ] for P in r [ "purposes" ] : try : tmp . append ( POSTCODE_API_TYPEDEFS_PURPOSES [ P ] ) except : logger . warning ( "Warning: {}: " "cannot translate 'purpose': {}" . format ( pc , P ) ) tmp . append ( P ) r . update ( { "purposes" : tmp } ) return f ( r , pc ) return wr | 5,231 | https://github.com/hootnot/postcode-api-wrapper/blob/42359cb9402f84a06f7d58f889f1156d653f5ea9/postcodepy/typedefs.py#L75-L95 | [
"def",
"public_broadcaster",
"(",
")",
":",
"while",
"__websocket_server_running__",
":",
"pipein",
"=",
"open",
"(",
"PUBLIC_PIPE",
",",
"'r'",
")",
"line",
"=",
"pipein",
".",
"readline",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"if",
"line",
"!=",
"''",
":",
"WebSocketHandler",
".",
"broadcast",
"(",
"line",
")",
"print",
"line",
"remaining_lines",
"=",
"pipein",
".",
"read",
"(",
")",
"pipein",
".",
"close",
"(",
")",
"pipeout",
"=",
"open",
"(",
"PUBLIC_PIPE",
",",
"'w'",
")",
"pipeout",
".",
"write",
"(",
"remaining_lines",
")",
"pipeout",
".",
"close",
"(",
")",
"else",
":",
"pipein",
".",
"close",
"(",
")",
"time",
".",
"sleep",
"(",
"0.05",
")"
] |
Calculate quantile breaks . | def quantile ( data , num_breaks ) : def scipy_mquantiles ( a , prob = list ( [ .25 , .5 , .75 ] ) , alphap = .4 , betap = .4 , axis = None , limit = ( ) ) : """ function copied from scipy 0.13.3::scipy.stats.mstats.mquantiles """ def _quantiles1D ( data , m , p ) : x = numpy . sort ( data . compressed ( ) ) n = len ( x ) if n == 0 : return numpy . ma . array ( numpy . empty ( len ( p ) , dtype = float ) , mask = True ) elif n == 1 : return numpy . ma . array ( numpy . resize ( x , p . shape ) , mask = numpy . ma . nomask ) aleph = ( n * p + m ) k = numpy . floor ( aleph . clip ( 1 , n - 1 ) ) . astype ( int ) gamma = ( aleph - k ) . clip ( 0 , 1 ) return ( 1. - gamma ) * x [ ( k - 1 ) . tolist ( ) ] + gamma * x [ k . tolist ( ) ] # Initialization & checks --------- data = numpy . ma . array ( a , copy = False ) if data . ndim > 2 : raise TypeError ( "Array should be 2D at most !" ) # if limit : condition = ( limit [ 0 ] < data ) & ( data < limit [ 1 ] ) data [ ~ condition . filled ( True ) ] = numpy . ma . masked # p = numpy . array ( prob , copy = False , ndmin = 1 ) m = alphap + p * ( 1. - alphap - betap ) # Computes quantiles along axis (or globally) if ( axis is None ) : return _quantiles1D ( data , m , p ) return numpy . ma . apply_along_axis ( _quantiles1D , axis , data , m , p ) return scipy_mquantiles ( data , numpy . linspace ( 1.0 / num_breaks , 1 , num_breaks ) ) | 5,232 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/data/classify.py#L91-L131 | [
"def",
"_csr_matrix_from_definition",
"(",
"data",
",",
"indices",
",",
"indptr",
",",
"shape",
"=",
"None",
",",
"ctx",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"indices_type",
"=",
"None",
",",
"indptr_type",
"=",
"None",
")",
":",
"# pylint: disable= no-member, protected-access",
"storage_type",
"=",
"'csr'",
"# context",
"ctx",
"=",
"current_context",
"(",
")",
"if",
"ctx",
"is",
"None",
"else",
"ctx",
"# types",
"dtype",
"=",
"_prepare_default_dtype",
"(",
"data",
",",
"dtype",
")",
"indptr_type",
"=",
"_STORAGE_AUX_TYPES",
"[",
"storage_type",
"]",
"[",
"0",
"]",
"if",
"indptr_type",
"is",
"None",
"else",
"indptr_type",
"indices_type",
"=",
"_STORAGE_AUX_TYPES",
"[",
"storage_type",
"]",
"[",
"1",
"]",
"if",
"indices_type",
"is",
"None",
"else",
"indices_type",
"# prepare src array and types",
"data",
"=",
"_prepare_src_array",
"(",
"data",
",",
"dtype",
")",
"indptr",
"=",
"_prepare_src_array",
"(",
"indptr",
",",
"indptr_type",
")",
"indices",
"=",
"_prepare_src_array",
"(",
"indices",
",",
"indices_type",
")",
"# TODO(junwu): Convert data, indptr, and indices to mxnet NDArrays",
"# if they are not for now. In the future, we should provide a c-api",
"# to accept np.ndarray types to copy from to result.data and aux_data",
"if",
"not",
"isinstance",
"(",
"data",
",",
"NDArray",
")",
":",
"data",
"=",
"_array",
"(",
"data",
",",
"ctx",
",",
"dtype",
")",
"if",
"not",
"isinstance",
"(",
"indptr",
",",
"NDArray",
")",
":",
"indptr",
"=",
"_array",
"(",
"indptr",
",",
"ctx",
",",
"indptr_type",
")",
"if",
"not",
"isinstance",
"(",
"indices",
",",
"NDArray",
")",
":",
"indices",
"=",
"_array",
"(",
"indices",
",",
"ctx",
",",
"indices_type",
")",
"if",
"shape",
"is",
"None",
":",
"if",
"indices",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'invalid shape'",
")",
"shape",
"=",
"(",
"len",
"(",
"indptr",
")",
"-",
"1",
",",
"op",
".",
"max",
"(",
"indices",
")",
".",
"asscalar",
"(",
")",
"+",
"1",
")",
"# verify shapes",
"aux_shapes",
"=",
"[",
"indptr",
".",
"shape",
",",
"indices",
".",
"shape",
"]",
"if",
"data",
".",
"ndim",
"!=",
"1",
"or",
"indptr",
".",
"ndim",
"!=",
"1",
"or",
"indices",
".",
"ndim",
"!=",
"1",
"or",
"indptr",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
"or",
"len",
"(",
"shape",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'invalid shape'",
")",
"result",
"=",
"CSRNDArray",
"(",
"_new_alloc_handle",
"(",
"storage_type",
",",
"shape",
",",
"ctx",
",",
"False",
",",
"dtype",
",",
"[",
"indptr_type",
",",
"indices_type",
"]",
",",
"aux_shapes",
")",
")",
"check_call",
"(",
"_LIB",
".",
"MXNDArraySyncCopyFromNDArray",
"(",
"result",
".",
"handle",
",",
"data",
".",
"handle",
",",
"ctypes",
".",
"c_int",
"(",
"-",
"1",
")",
")",
")",
"check_call",
"(",
"_LIB",
".",
"MXNDArraySyncCopyFromNDArray",
"(",
"result",
".",
"handle",
",",
"indptr",
".",
"handle",
",",
"ctypes",
".",
"c_int",
"(",
"0",
")",
")",
")",
"check_call",
"(",
"_LIB",
".",
"MXNDArraySyncCopyFromNDArray",
"(",
"result",
".",
"handle",
",",
"indices",
".",
"handle",
",",
"ctypes",
".",
"c_int",
"(",
"1",
")",
")",
")",
"return",
"result"
] |
Calculate equal interval breaks . | def equal ( data , num_breaks ) : step = ( numpy . amax ( data ) - numpy . amin ( data ) ) / num_breaks return numpy . linspace ( numpy . amin ( data ) + step , numpy . amax ( data ) , num_breaks ) | 5,233 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/data/classify.py#L134-L144 | [
"def",
"add_text",
"(",
"self",
",",
"coords",
",",
"text",
",",
"color",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
")",
":",
"source",
"=",
"vtk",
".",
"vtkVectorText",
"(",
")",
"source",
".",
"SetText",
"(",
"text",
")",
"mapper",
"=",
"vtk",
".",
"vtkPolyDataMapper",
"(",
")",
"mapper",
".",
"SetInputConnection",
"(",
"source",
".",
"GetOutputPort",
"(",
")",
")",
"follower",
"=",
"vtk",
".",
"vtkFollower",
"(",
")",
"follower",
".",
"SetMapper",
"(",
"mapper",
")",
"follower",
".",
"GetProperty",
"(",
")",
".",
"SetColor",
"(",
"color",
")",
"follower",
".",
"SetPosition",
"(",
"coords",
")",
"follower",
".",
"SetScale",
"(",
"0.5",
")",
"self",
".",
"ren",
".",
"AddActor",
"(",
"follower",
")",
"follower",
".",
"SetCamera",
"(",
"self",
".",
"ren",
".",
"GetActiveCamera",
"(",
")",
")"
] |
Add a column to a FITS file . | def add_column ( filename , column , formula , force = False ) : columns = parse_formula ( formula ) logger . info ( "Running file: %s" % filename ) logger . debug ( " Reading columns: %s" % columns ) data = fitsio . read ( filename , columns = columns ) logger . debug ( ' Evaluating formula: %s' % formula ) col = eval ( formula ) col = np . asarray ( col , dtype = [ ( column , col . dtype ) ] ) insert_columns ( filename , col , force = force ) return True | 5,234 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L70-L85 | [
"def",
"reject_record",
"(",
"self",
",",
"record",
")",
":",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"req",
"=",
"InclusionRequest",
".",
"get",
"(",
"self",
".",
"id",
",",
"record",
".",
"id",
")",
"if",
"req",
"is",
"None",
":",
"raise",
"InclusionRequestMissingError",
"(",
"community",
"=",
"self",
",",
"record",
"=",
"record",
")",
"req",
".",
"delete",
"(",
")"
] |
Load a set of FITS files with kwargs . | def load_files ( filenames , multiproc = False , * * kwargs ) : filenames = np . atleast_1d ( filenames ) logger . debug ( "Loading %s files..." % len ( filenames ) ) kwargs = [ dict ( filename = f , * * kwargs ) for f in filenames ] if multiproc : from multiprocessing import Pool processes = multiproc if multiproc > 0 else None p = Pool ( processes , maxtasksperchild = 1 ) out = p . map ( load_file , kwargs ) else : out = [ load_file ( kw ) for kw in kwargs ] dtype = out [ 0 ] . dtype for i , d in enumerate ( out ) : if d . dtype != dtype : # ADW: Not really safe... logger . warn ( "Casting input data to same type." ) out [ i ] = d . astype ( dtype , copy = False ) logger . debug ( 'Concatenating arrays...' ) return np . concatenate ( out ) | 5,235 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/fileio.py#L98-L121 | [
"def",
"loadSessions",
"(",
"self",
",",
"callback",
",",
"bare_jid",
",",
"device_ids",
")",
":",
"if",
"self",
".",
"is_async",
":",
"self",
".",
"__loadSessionsAsync",
"(",
"callback",
",",
"bare_jid",
",",
"device_ids",
",",
"{",
"}",
")",
"else",
":",
"return",
"self",
".",
"__loadSessionsSync",
"(",
"bare_jid",
",",
"device_ids",
")"
] |
We want to enforce minimum fracdet for a satellite to be considered detectable | def applyFracdet ( self , lon , lat ) : self . loadFracdet ( ) fracdet_core = meanFracdet ( self . m_fracdet , lon , lat , np . tile ( 0.1 , len ( lon ) ) ) fracdet_wide = meanFracdet ( self . m_fracdet , lon , lat , np . tile ( 0.5 , len ( lon ) ) ) return ( fracdet_core >= self . config [ self . algorithm ] [ 'fracdet_core_threshold' ] ) & ( fracdet_core >= self . config [ self . algorithm ] [ 'fracdet_core_threshold' ] ) | 5,236 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L385-L395 | [
"def",
"values",
"(",
"self",
")",
":",
"self",
".",
"expired",
"(",
")",
"values",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"_dict",
".",
"keys",
"(",
")",
":",
"try",
":",
"value",
"=",
"self",
".",
"_dict",
"[",
"key",
"]",
".",
"get",
"(",
")",
"values",
".",
"append",
"(",
"value",
")",
"except",
":",
"continue",
"return",
"values"
] |
Exclude objects that are too close to hotspot | def applyHotspot ( self , lon , lat ) : self . loadRealResults ( ) cut_detect_real = ( self . data_real [ 'SIG' ] >= self . config [ self . algorithm ] [ 'sig_threshold' ] ) lon_real = self . data_real [ 'RA' ] [ cut_detect_real ] lat_real = self . data_real [ 'DEC' ] [ cut_detect_real ] cut_hotspot = np . tile ( True , len ( lon ) ) for ii in range ( 0 , len ( lon ) ) : cut_hotspot [ ii ] = ~ np . any ( angsep ( lon [ ii ] , lat [ ii ] , lon_real , lat_real ) < self . config [ self . algorithm ] [ 'hotspot_angsep_threshold' ] ) return cut_hotspot | 5,237 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L397-L412 | [
"def",
"deserialize_footer",
"(",
"stream",
",",
"verifier",
"=",
"None",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting footer deserialization\"",
")",
"signature",
"=",
"b\"\"",
"if",
"verifier",
"is",
"None",
":",
"return",
"MessageFooter",
"(",
"signature",
"=",
"signature",
")",
"try",
":",
"(",
"sig_len",
",",
")",
"=",
"unpack_values",
"(",
"\">H\"",
",",
"stream",
")",
"(",
"signature",
",",
")",
"=",
"unpack_values",
"(",
"\">{sig_len}s\"",
".",
"format",
"(",
"sig_len",
"=",
"sig_len",
")",
",",
"stream",
")",
"except",
"SerializationError",
":",
"raise",
"SerializationError",
"(",
"\"No signature found in message\"",
")",
"if",
"verifier",
":",
"verifier",
".",
"verify",
"(",
"signature",
")",
"return",
"MessageFooter",
"(",
"signature",
"=",
"signature",
")"
] |
distance abs_mag r_physical | def predict ( self , lon , lat , * * kwargs ) : assert self . classifier is not None , 'ERROR' pred = np . zeros ( len ( lon ) ) cut_geometry , flags_geometry = self . applyGeometry ( lon , lat ) x_test = [ ] for key , operation in self . config [ 'operation' ] [ 'params_intrinsic' ] : assert operation . lower ( ) in [ 'linear' , 'log' ] , 'ERROR' if operation . lower ( ) == 'linear' : x_test . append ( kwargs [ key ] ) else : x_test . append ( np . log10 ( kwargs [ key ] ) ) x_test = np . vstack ( x_test ) . T #import pdb; pdb.set_trace() pred [ cut_geometry ] = self . classifier . predict_proba ( x_test [ cut_geometry ] ) [ : , 1 ] self . validatePredict ( pred , flags_geometry , lon , lat , kwargs [ 'r_physical' ] , kwargs [ 'abs_mag' ] , kwargs [ 'distance' ] ) return pred , flags_geometry | 5,238 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/scratch/simulation/survey_selection_function.py#L425-L449 | [
"def",
"request",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"cookiejar",
"=",
"None",
",",
")",
":",
"# The aim of this function is to be a limited lightweight replacement",
"# for the requests library but using only pythons standard libs.",
"# IMPORTANT NOTICE",
"# This function is excluded from private variable hiding as it is",
"# likely to need api keys etc which people may have obfuscated.",
"# Therefore it is important that no logging is done in this function",
"# that might reveal this information.",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"}",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"getattr",
"(",
"self",
".",
"_py3status_module",
",",
"\"request_timeout\"",
",",
"10",
")",
"if",
"\"User-Agent\"",
"not",
"in",
"headers",
":",
"headers",
"[",
"\"User-Agent\"",
"]",
"=",
"\"py3status/{} {}\"",
".",
"format",
"(",
"version",
",",
"self",
".",
"_uid",
")",
"return",
"HttpResponse",
"(",
"url",
",",
"params",
"=",
"params",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"timeout",
"=",
"timeout",
",",
"auth",
"=",
"auth",
",",
"cookiejar",
"=",
"cookiejar",
",",
")"
] |
Factory for various catalogs . | def catalogFactory ( name , * * kwargs ) : fn = lambda member : inspect . isclass ( member ) and member . __module__ == __name__ catalogs = odict ( inspect . getmembers ( sys . modules [ __name__ ] , fn ) ) if name not in list ( catalogs . keys ( ) ) : msg = "%s not found in catalogs:\n %s" % ( name , list ( kernels . keys ( ) ) ) logger . error ( msg ) msg = "Unrecognized catalog: %s" % name raise Exception ( msg ) return catalogs [ name ] ( * * kwargs ) | 5,239 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/candidate/associate.py#L447-L460 | [
"def",
"set_nonblock",
"(",
"self",
",",
"set_flag",
"=",
"True",
")",
":",
"# Get the current flags",
"if",
"self",
".",
"fd_flags",
"is",
"None",
":",
"try",
":",
"self",
".",
"fd_flags",
"=",
"fcntl",
".",
"fcntl",
"(",
"self",
".",
"ins",
",",
"fcntl",
".",
"F_GETFL",
")",
"except",
"IOError",
":",
"warning",
"(",
"\"Cannot get flags on this file descriptor !\"",
")",
"return",
"# Set the non blocking flag",
"if",
"set_flag",
":",
"new_fd_flags",
"=",
"self",
".",
"fd_flags",
"|",
"os",
".",
"O_NONBLOCK",
"else",
":",
"new_fd_flags",
"=",
"self",
".",
"fd_flags",
"&",
"~",
"os",
".",
"O_NONBLOCK",
"try",
":",
"fcntl",
".",
"fcntl",
"(",
"self",
".",
"ins",
",",
"fcntl",
".",
"F_SETFL",
",",
"new_fd_flags",
")",
"self",
".",
"fd_flags",
"=",
"new_fd_flags",
"except",
"Exception",
":",
"warning",
"(",
"\"Can't set flags on this file descriptor !\"",
")"
] |
Package everything nicely | def write_results ( filename , config , srcfile , samples ) : results = createResults ( config , srcfile , samples = samples ) results . write ( filename ) | 5,240 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L347-L350 | [
"def",
"get_product_info",
"(",
"self",
",",
"apps",
"=",
"[",
"]",
",",
"packages",
"=",
"[",
"]",
",",
"timeout",
"=",
"15",
")",
":",
"if",
"not",
"apps",
"and",
"not",
"packages",
":",
"return",
"message",
"=",
"MsgProto",
"(",
"EMsg",
".",
"ClientPICSProductInfoRequest",
")",
"for",
"app",
"in",
"apps",
":",
"app_info",
"=",
"message",
".",
"body",
".",
"apps",
".",
"add",
"(",
")",
"app_info",
".",
"only_public",
"=",
"False",
"if",
"isinstance",
"(",
"app",
",",
"tuple",
")",
":",
"app_info",
".",
"appid",
",",
"app_info",
".",
"access_token",
"=",
"app",
"else",
":",
"app_info",
".",
"appid",
"=",
"app",
"for",
"package",
"in",
"packages",
":",
"package_info",
"=",
"message",
".",
"body",
".",
"packages",
".",
"add",
"(",
")",
"if",
"isinstance",
"(",
"package",
",",
"tuple",
")",
":",
"package_info",
".",
"appid",
",",
"package_info",
".",
"access_token",
"=",
"package",
"else",
":",
"package_info",
".",
"packageid",
"=",
"package",
"message",
".",
"body",
".",
"meta_data_only",
"=",
"False",
"job_id",
"=",
"self",
".",
"send_job",
"(",
"message",
")",
"data",
"=",
"dict",
"(",
"apps",
"=",
"{",
"}",
",",
"packages",
"=",
"{",
"}",
")",
"while",
"True",
":",
"chunk",
"=",
"self",
".",
"wait_event",
"(",
"job_id",
",",
"timeout",
"=",
"timeout",
")",
"if",
"chunk",
"is",
"None",
":",
"return",
"chunk",
"=",
"chunk",
"[",
"0",
"]",
".",
"body",
"for",
"app",
"in",
"chunk",
".",
"apps",
":",
"data",
"[",
"'apps'",
"]",
"[",
"app",
".",
"appid",
"]",
"=",
"vdf",
".",
"loads",
"(",
"app",
".",
"buffer",
"[",
":",
"-",
"1",
"]",
".",
"decode",
"(",
"'utf-8'",
",",
"'replace'",
")",
")",
"[",
"'appinfo'",
"]",
"for",
"pkg",
"in",
"chunk",
".",
"packages",
":",
"data",
"[",
"'packages'",
"]",
"[",
"pkg",
".",
"packageid",
"]",
"=",
"vdf",
".",
"binary_loads",
"(",
"pkg",
".",
"buffer",
"[",
"4",
":",
"]",
")",
"[",
"str",
"(",
"pkg",
".",
"packageid",
")",
"]",
"if",
"not",
"chunk",
".",
"response_pending",
":",
"break",
"return",
"data"
] |
Estimate parameter value and uncertainties | def estimate ( self , param , burn = None , clip = 10.0 , alpha = 0.32 ) : # FIXME: Need to add age and metallicity to composite isochrone params (currently properties) if param not in list ( self . samples . names ) + list ( self . source . params ) + [ 'age' , 'metallicity' ] : msg = 'Unrecognized parameter: %s' % param raise KeyError ( msg ) # If the parameter is in the samples if param in self . samples . names : if param . startswith ( 'position_angle' ) : return self . estimate_position_angle ( param , burn = burn , clip = clip , alpha = alpha ) return self . samples . peak_interval ( param , burn = burn , clip = clip , alpha = alpha ) mle = self . get_mle ( ) errors = [ np . nan , np . nan ] # Set default value to the MLE value if param in self . source . params : err = self . source . params [ param ] . errors if err is not None : errors = err # For age and metallicity from composite isochrone return [ float ( mle [ param ] ) , errors ] | 5,241 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L57-L81 | [
"def",
"_hex_to_rgb",
"(",
"color",
":",
"str",
")",
"->",
"Tuple",
"[",
"int",
",",
"...",
"]",
":",
"if",
"color",
".",
"startswith",
"(",
"'#'",
")",
":",
"color",
"=",
"color",
".",
"lstrip",
"(",
"'#'",
")",
"return",
"tuple",
"(",
"int",
"(",
"color",
"[",
"i",
":",
"i",
"+",
"2",
"]",
",",
"16",
")",
"for",
"i",
"in",
"(",
"0",
",",
"2",
",",
"4",
")",
")"
] |
Estimate all source parameters | def estimate_params ( self , burn = None , clip = 10.0 , alpha = 0.32 ) : mle = self . get_mle ( ) out = odict ( ) for param in mle . keys ( ) : out [ param ] = self . estimate ( param , burn = burn , clip = clip , alpha = alpha ) return out | 5,242 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L92-L98 | [
"def",
"move_vobject",
"(",
"self",
",",
"uid",
",",
"from_file",
",",
"to_file",
")",
":",
"if",
"from_file",
"not",
"in",
"self",
".",
"_reminders",
"or",
"to_file",
"not",
"in",
"self",
".",
"_reminders",
":",
"return",
"uid",
"=",
"uid",
".",
"split",
"(",
"'@'",
")",
"[",
"0",
"]",
"with",
"self",
".",
"_lock",
":",
"rem",
"=",
"open",
"(",
"from_file",
")",
".",
"readlines",
"(",
")",
"for",
"(",
"index",
",",
"line",
")",
"in",
"enumerate",
"(",
"rem",
")",
":",
"if",
"uid",
"==",
"md5",
"(",
"line",
"[",
":",
"-",
"1",
"]",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
":",
"del",
"rem",
"[",
"index",
"]",
"open",
"(",
"from_file",
",",
"'w'",
")",
".",
"writelines",
"(",
"rem",
")",
"open",
"(",
"to_file",
",",
"'a'",
")",
".",
"write",
"(",
"line",
")",
"break"
] |
Estimate the position angle from the posterior dealing with periodicity . | def estimate_position_angle ( self , param = 'position_angle' , burn = None , clip = 10.0 , alpha = 0.32 ) : # Transform so peak in the middle of the distribution pa = self . samples . get ( param , burn = burn , clip = clip ) peak = ugali . utils . stats . kde_peak ( pa ) shift = 180. * ( ( pa + 90 - peak ) > 180 ) pa -= shift # Get the kde interval ret = ugali . utils . stats . peak_interval ( pa , alpha ) if ret [ 0 ] < 0 : ret [ 0 ] += 180. ret [ 1 ] [ 0 ] += 180. ret [ 1 ] [ 1 ] += 180. return ret | 5,243 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/results.py#L100-L113 | [
"def",
"removeAllEntitlements",
"(",
"self",
",",
"appId",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"appId\"",
":",
"appId",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/licenses/removeAllEntitlements\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Get the start and end formatted for query or the last hour if none specified . Unlike reports this does not aggregate periods and so it is possible to just query a range and parse out the individual hours . | def date_range_for_webtrends ( cls , start_at = None , end_at = None ) : if start_at and end_at : start_date = cls . parse_standard_date_string_to_date ( start_at ) end_date = cls . parse_standard_date_string_to_date ( end_at ) return [ ( cls . parse_date_for_query ( start_date ) , cls . parse_date_for_query ( end_date ) ) ] else : return [ ( "current_hour-1" , "current_hour-1" ) ] | 5,244 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/webtrends/keymetrics.py#L15-L32 | [
"def",
"copy_meta_from",
"(",
"self",
",",
"ido",
")",
":",
"self",
".",
"_active_scalar_info",
"=",
"ido",
".",
"active_scalar_info",
"self",
".",
"_active_vectors_info",
"=",
"ido",
".",
"active_vectors_info",
"if",
"hasattr",
"(",
"ido",
",",
"'_textures'",
")",
":",
"self",
".",
"_textures",
"=",
"ido",
".",
"_textures"
] |
Get the path to the ugali data directory from the environment | def get_ugali_dir ( ) : dirname = os . getenv ( 'UGALIDIR' ) # Get the HOME directory if not dirname : dirname = os . path . join ( os . getenv ( 'HOME' ) , '.ugali' ) if not os . path . exists ( dirname ) : from ugali . utils . logger import logger msg = "Creating UGALIDIR:\n%s" % dirname logger . warning ( msg ) return mkdir ( dirname ) | 5,245 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/shell.py#L48-L62 | [
"def",
"updateRecordValues",
"(",
"self",
")",
":",
"record",
"=",
"self",
".",
"record",
"(",
")",
"if",
"not",
"record",
":",
"return",
"# update the record information\r",
"tree",
"=",
"self",
".",
"treeWidget",
"(",
")",
"if",
"not",
"isinstance",
"(",
"tree",
",",
"XTreeWidget",
")",
":",
"return",
"for",
"column",
"in",
"record",
".",
"schema",
"(",
")",
".",
"columns",
"(",
")",
":",
"c",
"=",
"tree",
".",
"column",
"(",
"column",
".",
"displayName",
"(",
")",
")",
"if",
"c",
"==",
"-",
"1",
":",
"continue",
"elif",
"tree",
".",
"isColumnHidden",
"(",
"c",
")",
":",
"continue",
"else",
":",
"val",
"=",
"record",
".",
"recordValue",
"(",
"column",
".",
"name",
"(",
")",
")",
"self",
".",
"updateColumnValue",
"(",
"column",
",",
"val",
",",
"c",
")",
"# update the record state information\r",
"if",
"not",
"record",
".",
"isRecord",
"(",
")",
":",
"self",
".",
"addRecordState",
"(",
"XOrbRecordItem",
".",
"State",
".",
"New",
")",
"elif",
"record",
".",
"isModified",
"(",
")",
":",
"self",
".",
"addRecordState",
"(",
"XOrbRecordItem",
".",
"State",
".",
"Modified",
")"
] |
Get the ugali isochrone directory . | def get_iso_dir ( ) : dirname = os . path . join ( get_ugali_dir ( ) , 'isochrones' ) if not os . path . exists ( dirname ) : from ugali . utils . logger import logger msg = "Isochrone directory not found:\n%s" % dirname logger . warning ( msg ) return dirname | 5,246 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/shell.py#L64-L73 | [
"def",
"bargraph",
"(",
"data",
",",
"max_key_width",
"=",
"30",
")",
":",
"lines",
"=",
"[",
"]",
"max_length",
"=",
"min",
"(",
"max",
"(",
"len",
"(",
"key",
")",
"for",
"key",
"in",
"data",
".",
"keys",
"(",
")",
")",
",",
"max_key_width",
")",
"max_val",
"=",
"max",
"(",
"data",
".",
"values",
"(",
")",
")",
"max_val_length",
"=",
"max",
"(",
"len",
"(",
"_style_value",
"(",
"val",
")",
")",
"for",
"val",
"in",
"data",
".",
"values",
"(",
")",
")",
"term_width",
"=",
"get_terminal_size",
"(",
")",
"[",
"0",
"]",
"max_bar_width",
"=",
"term_width",
"-",
"MARGIN",
"-",
"(",
"max_length",
"+",
"3",
"+",
"max_val_length",
"+",
"3",
")",
"template",
"=",
"u\"{key:{key_width}} [ {value:{val_width}} ] {bar}\"",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"try",
":",
"bar",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"max_bar_width",
"*",
"value",
"/",
"max_val",
")",
")",
"*",
"TICK",
"except",
"ZeroDivisionError",
":",
"bar",
"=",
"''",
"line",
"=",
"template",
".",
"format",
"(",
"key",
"=",
"key",
"[",
":",
"max_length",
"]",
",",
"value",
"=",
"_style_value",
"(",
"value",
")",
",",
"bar",
"=",
"bar",
",",
"key_width",
"=",
"max_length",
",",
"val_width",
"=",
"max_val_length",
")",
"lines",
".",
"append",
"(",
"line",
")",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] |
Registers a parser to parse configuration inputs . | def registerParser ( self , parser ) : if not isinstance ( parser , Subparser ) : raise TypeError ( "%s is not an instance of a subparser." % parser ) self . parsers . append ( parser ) | 5,247 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/Config.py#L65-L73 | [
"def",
"local_regon_checksum",
"(",
"digits",
")",
":",
"weights_for_check_digit",
"=",
"[",
"2",
",",
"4",
",",
"8",
",",
"5",
",",
"0",
",",
"9",
",",
"7",
",",
"3",
",",
"6",
",",
"1",
",",
"2",
",",
"4",
",",
"8",
"]",
"check_digit",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"13",
")",
":",
"check_digit",
"+=",
"weights_for_check_digit",
"[",
"i",
"]",
"*",
"digits",
"[",
"i",
"]",
"check_digit",
"%=",
"11",
"if",
"check_digit",
"==",
"10",
":",
"check_digit",
"=",
"0",
"return",
"check_digit"
] |
Adds the given configuration option to the ConfigManager . | def addConfig ( self , name , default = None , cast = None , required = False , description = None ) : # Validate the name if not self . configNameRE . match ( name ) : raise InvalidConfigurationException ( "Invalid configuration name: %s" % name ) self . configs [ self . _sanitizeName ( name ) ] = { 'default' : default , 'cast' : cast , 'required' : required , 'description' : description } | 5,248 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/Config.py#L75-L98 | [
"async",
"def",
"stream",
"(",
"self",
",",
"version",
"=",
"\"1.1\"",
",",
"keep_alive",
"=",
"False",
",",
"keep_alive_timeout",
"=",
"None",
")",
":",
"headers",
"=",
"self",
".",
"get_headers",
"(",
"version",
",",
"keep_alive",
"=",
"keep_alive",
",",
"keep_alive_timeout",
"=",
"keep_alive_timeout",
",",
")",
"self",
".",
"protocol",
".",
"push_data",
"(",
"headers",
")",
"await",
"self",
".",
"protocol",
".",
"drain",
"(",
")",
"await",
"self",
".",
"streaming_fn",
"(",
"self",
")",
"self",
".",
"protocol",
".",
"push_data",
"(",
"b\"0\\r\\n\\r\\n\"",
")"
] |
Executes the registered parsers to parse input configurations . | def parse ( self ) : self . _config = _Config ( ) self . _setDefaults ( ) for parser in self . parsers : for key , value in parser . parse ( self , self . _config ) . items ( ) : key = self . _sanitizeName ( key ) if key not in self . configs : raise UnknownConfigurationException ( key ) if value is not None : self . _setConfig ( key , value ) self . _ensureRequired ( ) self . _cast ( ) return self . _config | 5,249 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/Config.py#L100-L120 | [
"def",
"cleanup_lib",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"using_openmp",
":",
"#this if statement is necessary because shared libraries that use",
"#OpenMP will core dump when unloaded, this is a well-known issue with OpenMP",
"logging",
".",
"debug",
"(",
"'unloading shared library'",
")",
"_ctypes",
".",
"dlclose",
"(",
"self",
".",
"lib",
".",
"_handle",
")"
] |
Sets all the expected configuration options on the config object as either the requested default value or None . | def _setDefaults ( self ) : for configName , configDict in self . configs . items ( ) : self . _setConfig ( configName , configDict [ 'default' ] ) | 5,250 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/Config.py#L122-L128 | [
"def",
"to_shared_lib",
"(",
"name",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'linux'",
")",
":",
"return",
"name",
"+",
"'.so'",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'darwin'",
")",
":",
"return",
"name",
"+",
"'.dylib'",
"elif",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"return",
"name",
"+",
"'.dll'",
"else",
":",
"sys",
".",
"exit",
"(",
"1",
")"
] |
Iterates through our parsed configuration options and cast any options with marked cast types . | def _cast ( self ) : for configName , configDict in self . configs . items ( ) : if configDict [ 'cast' ] is not None : configValue = getattr ( self . _config , configName ) if configValue is not None : try : self . _setConfig ( configName , configDict [ 'cast' ] ( configValue ) ) except : raise InvalidConfigurationException ( "%s: %r" % ( configName , configValue ) ) | 5,251 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/Config.py#L141-L154 | [
"def",
"salt_hash_from_plaintext",
"(",
"password",
")",
":",
"init_pbkdf2_salt",
"=",
"seed_generator",
"(",
"app_settings",
".",
"PBKDF2_SALT_LENGTH",
")",
"pbkdf2_temp_hash",
"=",
"hexlify_pbkdf2",
"(",
"password",
",",
"salt",
"=",
"init_pbkdf2_salt",
",",
"iterations",
"=",
"app_settings",
".",
"ITERATIONS1",
",",
"length",
"=",
"app_settings",
".",
"PBKDF2_BYTE_LENGTH",
")",
"first_pbkdf2_part",
"=",
"pbkdf2_temp_hash",
"[",
":",
"PBKDF2_HALF_HEX_LENGTH",
"]",
"second_pbkdf2_part",
"=",
"pbkdf2_temp_hash",
"[",
"PBKDF2_HALF_HEX_LENGTH",
":",
"]",
"encrypted_part",
"=",
"xor_crypt",
".",
"encrypt",
"(",
"first_pbkdf2_part",
",",
"key",
"=",
"second_pbkdf2_part",
")",
"# log.debug(\"locals():\\n%s\", pprint.pformat(locals()))",
"return",
"init_pbkdf2_salt",
",",
"encrypted_part"
] |
Get the logged in user s models from the JIMM controller . | def list_models ( self , macaroons ) : return make_request ( "{}model" . format ( self . url ) , timeout = self . timeout , client = self . _client , cookies = self . cookies ) | 5,252 | https://github.com/juju/theblues/blob/f4431f29e43d04fc32f38f4f86cea45cd4e6ae98/theblues/jimm.py#L31-L38 | [
"def",
"extract",
"(",
"self",
",",
"item",
")",
":",
"article_candidates",
"=",
"[",
"]",
"for",
"extractor",
"in",
"self",
".",
"extractor_list",
":",
"article_candidates",
".",
"append",
"(",
"extractor",
".",
"extract",
"(",
"item",
")",
")",
"article_candidates",
"=",
"self",
".",
"cleaner",
".",
"clean",
"(",
"article_candidates",
")",
"article",
"=",
"self",
".",
"comparer",
".",
"compare",
"(",
"item",
",",
"article_candidates",
")",
"item",
"[",
"'article_title'",
"]",
"=",
"article",
".",
"title",
"item",
"[",
"'article_description'",
"]",
"=",
"article",
".",
"description",
"item",
"[",
"'article_text'",
"]",
"=",
"article",
".",
"text",
"item",
"[",
"'article_image'",
"]",
"=",
"article",
".",
"topimage",
"item",
"[",
"'article_author'",
"]",
"=",
"article",
".",
"author",
"item",
"[",
"'article_publish_date'",
"]",
"=",
"article",
".",
"publish_date",
"item",
"[",
"'article_language'",
"]",
"=",
"article",
".",
"language",
"return",
"item"
] |
Composes chapters and writes the novel to a text file | def write ( self , novel_title = 'novel' , filetype = 'txt' ) : self . _compose_chapters ( ) self . _write_to_file ( novel_title , filetype ) | 5,253 | https://github.com/accraze/python-markov-novel/blob/ff451639e93a3ac11fb0268b92bc0cffc00bfdbe/src/markov_novel/novel.py#L15-L21 | [
"def",
"find_steam_location",
"(",
")",
":",
"if",
"registry",
"is",
"None",
":",
"return",
"None",
"key",
"=",
"registry",
".",
"CreateKey",
"(",
"registry",
".",
"HKEY_CURRENT_USER",
",",
"\"Software\\Valve\\Steam\"",
")",
"return",
"registry",
".",
"QueryValueEx",
"(",
"key",
",",
"\"SteamPath\"",
")",
"[",
"0",
"]"
] |
Creates a chapters and appends them to list | def _compose_chapters ( self ) : for count in range ( self . chapter_count ) : chapter_num = count + 1 c = Chapter ( self . markov , chapter_num ) self . chapters . append ( c ) | 5,254 | https://github.com/accraze/python-markov-novel/blob/ff451639e93a3ac11fb0268b92bc0cffc00bfdbe/src/markov_novel/novel.py#L23-L31 | [
"def",
"_sys_mgr",
"(",
")",
":",
"thrift_port",
"=",
"six",
".",
"text_type",
"(",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'cassandra.THRIFT_PORT'",
")",
")",
"host",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'cassandra.host'",
")",
"return",
"SystemManager",
"(",
"'{0}:{1}'",
".",
"format",
"(",
"host",
",",
"thrift_port",
")",
")"
] |
Determines whether the specified address string is valid . | def valid_address ( address ) : if not address : return False components = str ( address ) . split ( ':' ) if len ( components ) > 2 or not valid_hostname ( components [ 0 ] ) : return False if len ( components ) == 2 and not valid_port ( components [ 1 ] ) : return False return True | 5,255 | https://github.com/joeyespo/path-and-address/blob/f8193a09f4b785574d920e8a2aeeb55ea6ff4e20/path_and_address/validation.py#L7-L21 | [
"def",
"iter_series",
"(",
"self",
",",
"workbook",
",",
"row",
",",
"col",
")",
":",
"for",
"series",
"in",
"self",
".",
"__series",
":",
"series",
"=",
"dict",
"(",
"series",
")",
"series",
"[",
"\"values\"",
"]",
"=",
"series",
"[",
"\"values\"",
"]",
".",
"get_formula",
"(",
"workbook",
",",
"row",
",",
"col",
")",
"if",
"\"categories\"",
"in",
"series",
":",
"series",
"[",
"\"categories\"",
"]",
"=",
"series",
"[",
"\"categories\"",
"]",
".",
"get_formula",
"(",
"workbook",
",",
"row",
",",
"col",
")",
"yield",
"series"
] |
Returns whether the specified string is a valid hostname . | def valid_hostname ( host ) : if len ( host ) > 255 : return False if host [ - 1 : ] == '.' : host = host [ : - 1 ] return all ( _hostname_re . match ( c ) for c in host . split ( '.' ) ) | 5,256 | https://github.com/joeyespo/path-and-address/blob/f8193a09f4b785574d920e8a2aeeb55ea6ff4e20/path_and_address/validation.py#L24-L34 | [
"def",
"assume",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"_arch",
"=",
"other",
".",
"_arch",
"self",
".",
"_bits",
"=",
"other",
".",
"_bits",
"self",
".",
"_endian",
"=",
"other",
".",
"_endian",
"self",
".",
"_mode",
"=",
"other",
".",
"_mode"
] |
Sample initial mass values between mass_min and mass_max following the IMF distribution . | def sample ( self , n , mass_min = 0.1 , mass_max = 10. , steps = 10000 , seed = None ) : if seed is not None : np . random . seed ( seed ) d_mass = ( mass_max - mass_min ) / float ( steps ) mass = np . linspace ( mass_min , mass_max , steps ) cdf = np . insert ( np . cumsum ( d_mass * self . pdf ( mass [ 1 : ] , log_mode = False ) ) , 0 , 0. ) cdf = cdf / cdf [ - 1 ] f = scipy . interpolate . interp1d ( cdf , mass ) return f ( np . random . uniform ( size = n ) ) | 5,257 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/imf.py#L56-L81 | [
"async",
"def",
"refresh_data",
"(",
"self",
")",
":",
"queue",
"=",
"await",
"self",
".",
"get_queue",
"(",
")",
"history",
"=",
"await",
"self",
".",
"get_history",
"(",
")",
"totals",
"=",
"{",
"}",
"for",
"k",
"in",
"history",
":",
"if",
"k",
"[",
"-",
"4",
":",
"]",
"==",
"'size'",
":",
"totals",
"[",
"k",
"]",
"=",
"self",
".",
"_convert_size",
"(",
"history",
".",
"get",
"(",
"k",
")",
")",
"self",
".",
"queue",
"=",
"{",
"*",
"*",
"totals",
",",
"*",
"*",
"queue",
"}"
] |
PDF for the Kroupa IMF . | def pdf ( cls , mass , log_mode = True ) : log_mass = np . log10 ( mass ) # From Eq 2 mb = mbreak = [ 0.08 , 0.5 ] # Msun a = alpha = [ 0.3 , 1.3 , 2.3 ] # alpha # Normalization set from 0.1 -- 100 Msun norm = 0.27947743949440446 b = 1. / norm c = b * mbreak [ 0 ] ** ( alpha [ 1 ] - alpha [ 0 ] ) d = c * mbreak [ 1 ] ** ( alpha [ 2 ] - alpha [ 1 ] ) dn_dm = b * ( mass < 0.08 ) * mass ** ( - alpha [ 0 ] ) dn_dm += c * ( 0.08 <= mass ) * ( mass < 0.5 ) * mass ** ( - alpha [ 1 ] ) dn_dm += d * ( 0.5 <= mass ) * mass ** ( - alpha [ 2 ] ) if log_mode : # Number per logarithmic mass range, i.e., dN/dlog(M) return dn_dm * ( mass * np . log ( 10 ) ) else : # Number per linear mass range, i.e., dN/dM return dn_dm | 5,258 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/imf.py#L155-L181 | [
"def",
"start_rest_api",
"(",
"host",
",",
"port",
",",
"connection",
",",
"timeout",
",",
"registry",
",",
"client_max_size",
"=",
"None",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"connection",
".",
"open",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
"loop",
"=",
"loop",
",",
"client_max_size",
"=",
"client_max_size",
")",
"app",
".",
"on_cleanup",
".",
"append",
"(",
"lambda",
"app",
":",
"connection",
".",
"close",
"(",
")",
")",
"# Add routes to the web app",
"LOGGER",
".",
"info",
"(",
"'Creating handlers for validator at %s'",
",",
"connection",
".",
"url",
")",
"handler",
"=",
"RouteHandler",
"(",
"loop",
",",
"connection",
",",
"timeout",
",",
"registry",
")",
"app",
".",
"router",
".",
"add_post",
"(",
"'/batches'",
",",
"handler",
".",
"submit_batches",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/batch_statuses'",
",",
"handler",
".",
"list_statuses",
")",
"app",
".",
"router",
".",
"add_post",
"(",
"'/batch_statuses'",
",",
"handler",
".",
"list_statuses",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/state'",
",",
"handler",
".",
"list_state",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/state/{address}'",
",",
"handler",
".",
"fetch_state",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/blocks'",
",",
"handler",
".",
"list_blocks",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/blocks/{block_id}'",
",",
"handler",
".",
"fetch_block",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/batches'",
",",
"handler",
".",
"list_batches",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/batches/{batch_id}'",
",",
"handler",
".",
"fetch_batch",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/transactions'",
",",
"handler",
".",
"list_transactions",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/transactions/{transaction_id}'",
",",
"handler",
".",
"fetch_transaction",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/receipts'",
",",
"handler",
".",
"list_receipts",
")",
"app",
".",
"router",
".",
"add_post",
"(",
"'/receipts'",
",",
"handler",
".",
"list_receipts",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/peers'",
",",
"handler",
".",
"fetch_peers",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/status'",
",",
"handler",
".",
"fetch_status",
")",
"subscriber_handler",
"=",
"StateDeltaSubscriberHandler",
"(",
"connection",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/subscriptions'",
",",
"subscriber_handler",
".",
"subscriptions",
")",
"app",
".",
"on_shutdown",
".",
"append",
"(",
"lambda",
"app",
":",
"subscriber_handler",
".",
"on_shutdown",
"(",
")",
")",
"# Start app",
"LOGGER",
".",
"info",
"(",
"'Starting REST API on %s:%s'",
",",
"host",
",",
"port",
")",
"web",
".",
"run_app",
"(",
"app",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"access_log",
"=",
"LOGGER",
",",
"access_log_format",
"=",
"'%r: %s status, %b size, in %Tf s'",
")"
] |
PDF for the Salpeter IMF . | def pdf ( cls , mass , log_mode = True ) : alpha = 2.35 a = 0.060285569480482866 dn_dm = a * mass ** ( - alpha ) if log_mode : # Number per logarithmic mass range, i.e., dN/dlog(M) return dn_dm * ( mass * np . log ( 10 ) ) else : # Number per linear mass range, i.e., dN/dM return dn_dm | 5,259 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/imf.py#L191-L206 | [
"def",
"console_wait_for_keypress",
"(",
"flush",
":",
"bool",
")",
"->",
"Key",
":",
"key",
"=",
"Key",
"(",
")",
"lib",
".",
"TCOD_console_wait_for_keypress_wrapper",
"(",
"key",
".",
"key_p",
",",
"flush",
")",
"return",
"key"
] |
Retrieves a file descriptor to a configuration file to process . | def _getConfigFile ( self , config ) : joinPath = lambda p : ( os . path . join ( p ) if isinstance ( p , ( tuple , list ) ) else p ) if self . filepathConfig is not None and self . filenameConfig is not None : if hasattr ( config , self . filepathConfig ) and hasattr ( config , self . filenameConfig ) : path = joinPath ( getattr ( config , self . filepathConfig ) ) name = getattr ( config , self . filenameConfig ) if os . path . isfile ( os . path . join ( path , name ) ) : return open ( os . path . join ( path , name ) , 'r' ) if self . filepath is not None and self . filename is not None : path = joinPath ( self . filepath ) name = self . filename if os . path . isfile ( os . path . join ( path , name ) ) : return open ( os . path . join ( path , name ) , 'r' ) | 5,260 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/subparsers/_subparser.py#L83-L107 | [
"def",
"uunion1d",
"(",
"arr1",
",",
"arr2",
")",
":",
"v",
"=",
"np",
".",
"union1d",
"(",
"arr1",
",",
"arr2",
")",
"v",
"=",
"_validate_numpy_wrapper_units",
"(",
"v",
",",
"[",
"arr1",
",",
"arr2",
"]",
")",
"return",
"v"
] |
Counts the citations in an aux - file . | def _count_citations ( aux_file ) : counter = defaultdict ( int ) with open ( aux_file ) as fobj : content = fobj . read ( ) for match in CITE_PATTERN . finditer ( content ) : name = match . groups ( ) [ 0 ] counter [ name ] += 1 return counter | 5,261 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L429-L443 | [
"def",
"connect",
"(",
"self",
")",
":",
"distributed_logger",
".",
"info",
"(",
"'Connecting registry proxy to ZMQ socket %s'",
",",
"self",
".",
"socket_addr",
")",
"self",
".",
"zmq_context",
"=",
"zmq",
".",
"Context",
"(",
")",
"sock",
"=",
"self",
".",
"zmq_context",
".",
"socket",
"(",
"zmq",
".",
"PUB",
")",
"sock",
".",
"set_hwm",
"(",
"0",
")",
"sock",
".",
"setsockopt",
"(",
"zmq",
".",
"LINGER",
",",
"0",
")",
"sock",
".",
"connect",
"(",
"self",
".",
"socket_addr",
")",
"distributed_logger",
".",
"info",
"(",
"'Connected registry proxy to ZMQ socket %s'",
",",
"self",
".",
"socket_addr",
")",
"def",
"_reset_socket",
"(",
"values",
")",
":",
"for",
"value",
"in",
"values",
":",
"try",
":",
"_reset_socket",
"(",
"value",
".",
"values",
"(",
")",
")",
"except",
"AttributeError",
":",
"value",
".",
"socket",
"=",
"sock",
"distributed_logger",
".",
"debug",
"(",
"'Resetting socket on metrics proxies'",
")",
"_reset_socket",
"(",
"self",
".",
"stats",
".",
"values",
"(",
")",
")",
"self",
".",
"socket",
"=",
"sock",
"distributed_logger",
".",
"debug",
"(",
"'Reset socket on metrics proxies'",
")"
] |
Set up a logger . | def _setup_logger ( self ) : log = logging . getLogger ( 'latexmk.py' ) handler = logging . StreamHandler ( ) log . addHandler ( handler ) if self . opt . verbose : log . setLevel ( logging . INFO ) return log | 5,262 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L84-L93 | [
"def",
"ttl",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"*",
"1000",
"if",
"self",
".",
"_need_update",
":",
"ttl",
"=",
"0",
"else",
":",
"metadata_age",
"=",
"now",
"-",
"self",
".",
"_last_successful_refresh_ms",
"ttl",
"=",
"self",
".",
"config",
"[",
"'metadata_max_age_ms'",
"]",
"-",
"metadata_age",
"retry_age",
"=",
"now",
"-",
"self",
".",
"_last_refresh_ms",
"next_retry",
"=",
"self",
".",
"config",
"[",
"'retry_backoff_ms'",
"]",
"-",
"retry_age",
"return",
"max",
"(",
"ttl",
",",
"next_retry",
",",
"0",
")"
] |
Read the project name from the texlipse config file . texlipse . | def _parse_texlipse_config ( self ) : # If Eclipse's workspace refresh, the # ".texlipse"-File will be newly created, # so try again after short sleep if # the file is still missing. if not os . path . isfile ( '.texlipse' ) : time . sleep ( 0.1 ) if not os . path . isfile ( '.texlipse' ) : self . log . error ( '! Fatal error: File .texlipse is missing.' ) self . log . error ( '! Exiting...' ) sys . exit ( 1 ) with open ( '.texlipse' ) as fobj : content = fobj . read ( ) match = TEXLIPSE_MAIN_PATTERN . search ( content ) if match : project_name = match . groups ( ) [ 0 ] self . log . info ( 'Found inputfile in ".texlipse": %s.tex' % project_name ) return project_name else : self . log . error ( '! Fatal error: Parsing .texlipse failed.' ) self . log . error ( '! Exiting...' ) sys . exit ( 1 ) | 5,263 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L95-L122 | [
"def",
"compare_values",
"(",
"values0",
",",
"values1",
")",
":",
"values0",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values0",
"}",
"values1",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values1",
"}",
"created",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values1",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"values0",
"]",
"deleted",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values0",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"values1",
"]",
"modified",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values0",
".",
"items",
"(",
")",
"if",
"v",
"!=",
"values1",
".",
"get",
"(",
"k",
",",
"None",
")",
"]",
"return",
"created",
",",
"deleted",
",",
"modified"
] |
Check if some latex output files exist before first latex run process them and return the generated data . | def _read_latex_files ( self ) : if os . path . isfile ( '%s.aux' % self . project_name ) : cite_counter = self . generate_citation_counter ( ) self . read_glossaries ( ) else : cite_counter = { '%s.aux' % self . project_name : defaultdict ( int ) } fname = '%s.toc' % self . project_name if os . path . isfile ( fname ) : with open ( fname ) as fobj : toc_file = fobj . read ( ) else : toc_file = '' gloss_files = dict ( ) for gloss in self . glossaries : ext = self . glossaries [ gloss ] [ 1 ] filename = '%s.%s' % ( self . project_name , ext ) if os . path . isfile ( filename ) : with open ( filename ) as fobj : gloss_files [ gloss ] = fobj . read ( ) return cite_counter , toc_file , gloss_files | 5,264 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L124-L158 | [
"def",
"cluster_types",
"(",
"types",
",",
"max_clust",
"=",
"12",
")",
":",
"if",
"len",
"(",
"types",
")",
"<",
"max_clust",
":",
"max_clust",
"=",
"len",
"(",
"types",
")",
"# Do actual clustering",
"cluster_dict",
"=",
"do_clustering",
"(",
"types",
",",
"max_clust",
")",
"cluster_ranks",
"=",
"rank_clusters",
"(",
"cluster_dict",
")",
"# Create a dictionary mapping binary numbers to indices",
"ranks",
"=",
"{",
"}",
"for",
"key",
"in",
"cluster_dict",
":",
"for",
"typ",
"in",
"cluster_dict",
"[",
"key",
"]",
":",
"ranks",
"[",
"typ",
"]",
"=",
"cluster_ranks",
"[",
"key",
"]",
"return",
"ranks"
] |
Read all existing glossaries in the main aux - file . | def read_glossaries ( self ) : filename = '%s.aux' % self . project_name with open ( filename ) as fobj : main_aux = fobj . read ( ) pattern = r'\\@newglossary\{(.*)\}\{.*\}\{(.*)\}\{(.*)\}' for match in re . finditer ( pattern , main_aux ) : name , ext_i , ext_o = match . groups ( ) self . glossaries [ name ] = ( ext_i , ext_o ) | 5,265 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L204-L215 | [
"def",
"equivalent_diameter",
"(",
"target",
",",
"pore_volume",
"=",
"'pore.volume'",
",",
"pore_shape",
"=",
"'sphere'",
")",
":",
"from",
"scipy",
".",
"special",
"import",
"cbrt",
"pore_vols",
"=",
"target",
"[",
"pore_volume",
"]",
"if",
"pore_shape",
".",
"startswith",
"(",
"'sph'",
")",
":",
"value",
"=",
"cbrt",
"(",
"6",
"*",
"pore_vols",
"/",
"_np",
".",
"pi",
")",
"elif",
"pore_shape",
".",
"startswith",
"(",
"'cub'",
")",
":",
"value",
"=",
"cbrt",
"(",
"pore_vols",
")",
"return",
"value"
] |
Check if errors occured during a latex run by scanning the output . | def check_errors ( self ) : errors = ERROR_PATTTERN . findall ( self . out ) # "errors" is a list of tuples if errors : self . log . error ( '! Errors occurred:' ) self . log . error ( '\n' . join ( [ error . replace ( '\r' , '' ) . strip ( ) for error in chain ( * errors ) if error . strip ( ) ] ) ) self . log . error ( '! See "%s.log" for details.' % self . project_name ) if self . opt . exit_on_error : self . log . error ( '! Exiting...' ) sys . exit ( 1 ) | 5,266 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L217-L236 | [
"def",
"fix_auth_url_version_prefix",
"(",
"auth_url",
")",
":",
"auth_url",
"=",
"_augment_url_with_version",
"(",
"auth_url",
")",
"url_fixed",
"=",
"False",
"if",
"get_keystone_version",
"(",
")",
">=",
"3",
"and",
"has_in_url_path",
"(",
"auth_url",
",",
"[",
"\"/v2.0\"",
"]",
")",
":",
"url_fixed",
"=",
"True",
"auth_url",
"=",
"url_path_replace",
"(",
"auth_url",
",",
"\"/v2.0\"",
",",
"\"/v3\"",
",",
"1",
")",
"return",
"auth_url",
",",
"url_fixed"
] |
Generate dictionary with the number of citations in all included files . If this changes after the first latex run you have to run bibtex . | def generate_citation_counter ( self ) : cite_counter = dict ( ) filename = '%s.aux' % self . project_name with open ( filename ) as fobj : main_aux = fobj . read ( ) cite_counter [ filename ] = _count_citations ( filename ) for match in re . finditer ( r'\\@input\{(.*.aux)\}' , main_aux ) : filename = match . groups ( ) [ 0 ] try : counter = _count_citations ( filename ) except IOError : pass else : cite_counter [ filename ] = counter return cite_counter | 5,267 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L238-L259 | [
"def",
"not_storable",
"(",
"_type",
")",
":",
"return",
"Storable",
"(",
"_type",
",",
"handlers",
"=",
"StorableHandler",
"(",
"poke",
"=",
"fake_poke",
",",
"peek",
"=",
"fail_peek",
"(",
"_type",
")",
")",
")"
] |
Start latex run . | def latex_run ( self ) : self . log . info ( 'Running %s...' % self . latex_cmd ) cmd = [ self . latex_cmd ] cmd . extend ( LATEX_FLAGS ) cmd . append ( '%s.tex' % self . project_name ) try : with open ( os . devnull , 'w' ) as null : Popen ( cmd , stdout = null , stderr = null ) . wait ( ) except OSError : self . log . error ( NO_LATEX_ERROR % self . latex_cmd ) self . latex_run_counter += 1 fname = '%s.log' % self . project_name with codecs . open ( fname , 'r' , 'utf-8' , 'replace' ) as fobj : self . out = fobj . read ( ) self . check_errors ( ) | 5,268 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L261-L279 | [
"def",
"unbind",
"(",
"self",
",",
"devices_to_unbind",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"api/0.1.0/subscribe/unbind\"",
"headers",
"=",
"{",
"\"apikey\"",
":",
"self",
".",
"entity_api_key",
"}",
"data",
"=",
"{",
"\"exchange\"",
":",
"\"amq.topic\"",
",",
"\"keys\"",
":",
"devices_to_unbind",
",",
"\"queue\"",
":",
"self",
".",
"entity_id",
"}",
"with",
"self",
".",
"no_ssl_verification",
"(",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"print",
"(",
"r",
")",
"response",
"=",
"dict",
"(",
")",
"if",
"\"No API key\"",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"[",
"'message'",
"]",
"elif",
"'unbind'",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"response",
"[",
"\"response\"",
"]",
"=",
"str",
"(",
"r",
")",
"return",
"response"
] |
Start bibtex run . | def bibtex_run ( self ) : self . log . info ( 'Running bibtex...' ) try : with open ( os . devnull , 'w' ) as null : Popen ( [ 'bibtex' , self . project_name ] , stdout = null ) . wait ( ) except OSError : self . log . error ( NO_LATEX_ERROR % 'bibtex' ) sys . exit ( 1 ) shutil . copy ( '%s.bib' % self . bib_file , '%s.bib.old' % self . bib_file ) | 5,269 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L281-L294 | [
"def",
"inducingpoint_wrapper",
"(",
"feat",
",",
"Z",
")",
":",
"if",
"feat",
"is",
"not",
"None",
"and",
"Z",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot pass both an InducingFeature instance and Z values\"",
")",
"# pragma: no cover",
"elif",
"feat",
"is",
"None",
"and",
"Z",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"You must pass either an InducingFeature instance or Z values\"",
")",
"# pragma: no cover",
"elif",
"Z",
"is",
"not",
"None",
":",
"feat",
"=",
"InducingPoints",
"(",
"Z",
")",
"elif",
"isinstance",
"(",
"feat",
",",
"np",
".",
"ndarray",
")",
":",
"feat",
"=",
"InducingPoints",
"(",
"feat",
")",
"else",
":",
"assert",
"isinstance",
"(",
"feat",
",",
"InducingFeature",
")",
"# pragma: no cover",
"return",
"feat"
] |
Check for each glossary if it has to be regenerated with makeindex . | def makeindex_runs ( self , gloss_files ) : gloss_changed = False for gloss in self . glossaries : make_gloss = False ext_i , ext_o = self . glossaries [ gloss ] fname_in = '%s.%s' % ( self . project_name , ext_i ) fname_out = '%s.%s' % ( self . project_name , ext_o ) if re . search ( 'No file %s.' % fname_in , self . out ) : make_gloss = True if not os . path . isfile ( fname_out ) : make_gloss = True else : with open ( fname_out ) as fobj : try : if gloss_files [ gloss ] != fobj . read ( ) : make_gloss = True except KeyError : make_gloss = True if make_gloss : self . log . info ( 'Running makeindex (%s)...' % gloss ) try : cmd = [ 'makeindex' , '-q' , '-s' , '%s.ist' % self . project_name , '-o' , fname_in , fname_out ] with open ( os . devnull , 'w' ) as null : Popen ( cmd , stdout = null ) . wait ( ) except OSError : self . log . error ( NO_LATEX_ERROR % 'makeindex' ) sys . exit ( 1 ) gloss_changed = True return gloss_changed | 5,270 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L296-L334 | [
"def",
"line_line_collide",
"(",
"line1",
",",
"line2",
")",
":",
"s",
",",
"t",
",",
"success",
"=",
"segment_intersection",
"(",
"line1",
"[",
":",
",",
"0",
"]",
",",
"line1",
"[",
":",
",",
"1",
"]",
",",
"line2",
"[",
":",
",",
"0",
"]",
",",
"line2",
"[",
":",
",",
"1",
"]",
")",
"if",
"success",
":",
"return",
"_helpers",
".",
"in_interval",
"(",
"s",
",",
"0.0",
",",
"1.0",
")",
"and",
"_helpers",
".",
"in_interval",
"(",
"t",
",",
"0.0",
",",
"1.0",
")",
"else",
":",
"disjoint",
",",
"_",
"=",
"parallel_lines_parameters",
"(",
"line1",
"[",
":",
",",
"0",
"]",
",",
"line1",
"[",
":",
",",
"1",
"]",
",",
"line2",
"[",
":",
",",
"0",
"]",
",",
"line2",
"[",
":",
",",
"1",
"]",
")",
"return",
"not",
"disjoint"
] |
Try to open a preview of the generated document . Currently only supported on Windows . | def open_preview ( self ) : self . log . info ( 'Opening preview...' ) if self . opt . pdf : ext = 'pdf' else : ext = 'dvi' filename = '%s.%s' % ( self . project_name , ext ) if sys . platform == 'win32' : try : os . startfile ( filename ) except OSError : self . log . error ( 'Preview-Error: Extension .%s is not linked to a ' 'specific application!' % ext ) elif sys . platform == 'darwin' : call ( [ 'open' , filename ] ) else : self . log . error ( 'Preview-Error: Preview function is currently not ' 'supported on Linux.' ) | 5,271 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L336-L361 | [
"def",
"_perform_unbinds",
"(",
"self",
",",
"binds",
")",
":",
"for",
"bind",
"in",
"binds",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Unbinding queue {0} from exchange {1} with key {2}\"",
".",
"format",
"(",
"bind",
"[",
"'queue'",
"]",
",",
"bind",
"[",
"'exchange'",
"]",
",",
"bind",
"[",
"'routing_key'",
"]",
")",
")",
"self",
".",
"channel",
".",
"queue_unbind",
"(",
"*",
"*",
"bind",
")"
] |
Test for all rerun patterns if they match the output . | def need_latex_rerun ( self ) : for pattern in LATEX_RERUN_PATTERNS : if pattern . search ( self . out ) : return True return False | 5,272 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L363-L370 | [
"def",
"_init_rabit",
"(",
")",
":",
"if",
"_LIB",
"is",
"not",
"None",
":",
"_LIB",
".",
"RabitGetRank",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"_LIB",
".",
"RabitGetWorldSize",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"_LIB",
".",
"RabitIsDistributed",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"_LIB",
".",
"RabitVersionNumber",
".",
"restype",
"=",
"ctypes",
".",
"c_int"
] |
Run the LaTeX compilation . | def run ( self ) : # store files self . old_dir = [ ] if self . opt . clean : self . old_dir = os . listdir ( '.' ) cite_counter , toc_file , gloss_files = self . _read_latex_files ( ) self . latex_run ( ) self . read_glossaries ( ) gloss_changed = self . makeindex_runs ( gloss_files ) if gloss_changed or self . _is_toc_changed ( toc_file ) : self . latex_run ( ) if self . _need_bib_run ( cite_counter ) : self . bibtex_run ( ) self . latex_run ( ) while ( self . latex_run_counter < MAX_RUNS ) : if not self . need_latex_rerun ( ) : break self . latex_run ( ) if self . opt . check_cite : cites = set ( ) with open ( '%s.aux' % self . project_name ) as fobj : aux_content = fobj . read ( ) for match in BIBCITE_PATTERN . finditer ( aux_content ) : name = match . groups ( ) [ 0 ] cites . add ( name ) with open ( '%s.bib' % self . bib_file ) as fobj : bib_content = fobj . read ( ) for match in BIBENTRY_PATTERN . finditer ( bib_content ) : name = match . groups ( ) [ 0 ] if name not in cites : self . log . info ( 'Bib entry not cited: "%s"' % name ) if self . opt . clean : ending = '.dvi' if self . opt . pdf : ending = '.pdf' for fname in os . listdir ( '.' ) : if not ( fname in self . old_dir or fname . endswith ( ending ) ) : try : os . remove ( fname ) except IOError : pass if self . opt . preview : self . open_preview ( ) | 5,273 | https://github.com/schlamar/latexmk.py/blob/88baba40ff3e844e4542de60d2032503e206d996/latexmake.py#L372-L426 | [
"def",
"hz2cents",
"(",
"freq_hz",
",",
"base_frequency",
"=",
"10.0",
")",
":",
"freq_cent",
"=",
"np",
".",
"zeros",
"(",
"freq_hz",
".",
"shape",
"[",
"0",
"]",
")",
"freq_nonz_ind",
"=",
"np",
".",
"flatnonzero",
"(",
"freq_hz",
")",
"normalized_frequency",
"=",
"np",
".",
"abs",
"(",
"freq_hz",
"[",
"freq_nonz_ind",
"]",
")",
"/",
"base_frequency",
"freq_cent",
"[",
"freq_nonz_ind",
"]",
"=",
"1200",
"*",
"np",
".",
"log2",
"(",
"normalized_frequency",
")",
"return",
"freq_cent"
] |
Generate the command for running the likelihood scan . | def command ( self , outfile , configfile , pix ) : params = dict ( script = self . config [ 'scan' ] [ 'script' ] , config = configfile , outfile = outfile , nside = self . nside_likelihood , pix = pix , verbose = '-v' if self . verbose else '' ) cmd = '%(script)s %(config)s %(outfile)s --hpx %(nside)i %(pix)i %(verbose)s' % params return cmd | 5,274 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/farm.py#L47-L56 | [
"def",
"swapaxes",
"(",
"vari",
",",
"ax1",
",",
"ax2",
")",
":",
"if",
"isinstance",
"(",
"vari",
",",
"Poly",
")",
":",
"core",
"=",
"vari",
".",
"A",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"vari",
".",
"keys",
":",
"core",
"[",
"key",
"]",
"=",
"swapaxes",
"(",
"core",
"[",
"key",
"]",
",",
"ax1",
",",
"ax2",
")",
"return",
"Poly",
"(",
"core",
",",
"vari",
".",
"dim",
",",
"None",
",",
"vari",
".",
"dtype",
")",
"return",
"numpy",
".",
"swapaxes",
"(",
"vari",
",",
"ax1",
",",
"ax2",
")"
] |
Submit likelihood analyses on a set of coordinates . If coords is None submit all coordinates in the footprint . | def submit_all ( self , coords = None , queue = None , debug = False ) : if coords is None : pixels = np . arange ( hp . nside2npix ( self . nside_likelihood ) ) else : coords = np . asarray ( coords ) if coords . ndim == 1 : coords = np . array ( [ coords ] ) if coords . shape [ 1 ] == 2 : lon , lat = coords . T radius = np . zeros ( len ( lon ) ) elif coords . shape [ 1 ] == 3 : lon , lat , radius = coords . T else : raise Exception ( "Unrecognized coords shape:" + str ( coords . shape ) ) #ADW: targets is still in glon,glat if self . config [ 'coords' ] [ 'coordsys' ] . lower ( ) == 'cel' : lon , lat = gal2cel ( lon , lat ) vec = ang2vec ( lon , lat ) pixels = np . zeros ( 0 , dtype = int ) for v , r in zip ( vec , radius ) : pix = query_disc ( self . nside_likelihood , v , r , inclusive = True , fact = 32 ) pixels = np . hstack ( [ pixels , pix ] ) #pixels = np.unique(pixels) inside = ugali . utils . skymap . inFootprint ( self . config , pixels ) if inside . sum ( ) != len ( pixels ) : logger . warning ( "Ignoring pixels outside survey footprint:\n" + str ( pixels [ ~ inside ] ) ) if inside . sum ( ) == 0 : logger . warning ( "No pixels inside footprint." ) return # Only write the configfile once outdir = mkdir ( self . config [ 'output' ] [ 'likedir' ] ) # Actually copy config instead of re-writing shutil . copy ( self . config . filename , outdir ) configfile = join ( outdir , os . path . basename ( self . config . filename ) ) pixels = pixels [ inside ] self . submit ( pixels , queue = queue , debug = debug , configfile = configfile ) | 5,275 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/farm.py#L104-L153 | [
"def",
"Disconnect",
"(",
"self",
")",
":",
"device_path",
"=",
"self",
".",
"path",
"if",
"device_path",
"not",
"in",
"mockobject",
".",
"objects",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBusException",
"(",
"'No such device.'",
",",
"name",
"=",
"'org.bluez.Error.NoSuchDevice'",
")",
"device",
"=",
"mockobject",
".",
"objects",
"[",
"device_path",
"]",
"try",
":",
"device",
".",
"props",
"[",
"AUDIO_IFACE",
"]",
"[",
"'State'",
"]",
"=",
"dbus",
".",
"String",
"(",
"\"disconnected\"",
",",
"variant_level",
"=",
"1",
")",
"device",
".",
"EmitSignal",
"(",
"AUDIO_IFACE",
",",
"'PropertyChanged'",
",",
"'sv'",
",",
"[",
"'State'",
",",
"dbus",
".",
"String",
"(",
"\"disconnected\"",
",",
"variant_level",
"=",
"1",
")",
",",
"]",
")",
"except",
"KeyError",
":",
"pass",
"device",
".",
"props",
"[",
"DEVICE_IFACE",
"]",
"[",
"'Connected'",
"]",
"=",
"dbus",
".",
"Boolean",
"(",
"False",
",",
"variant_level",
"=",
"1",
")",
"device",
".",
"EmitSignal",
"(",
"DEVICE_IFACE",
",",
"'PropertyChanged'",
",",
"'sv'",
",",
"[",
"'Connected'",
",",
"dbus",
".",
"Boolean",
"(",
"False",
",",
"variant_level",
"=",
"1",
")",
",",
"]",
")"
] |
Class method to check every settings . | def check ( cls ) : if cls == AppSettings : return None exceptions = [ ] for setting in cls . settings . values ( ) : try : setting . check ( ) # pylama:ignore=W0703 except Exception as e : exceptions . append ( str ( e ) ) if exceptions : raise ImproperlyConfigured ( "\n" . join ( exceptions ) ) | 5,276 | https://github.com/Genida/django-appsettings/blob/f98867d133558af7dc067f12b44fc1ee4edd4239/src/appsettings/__init__.py#L192-L209 | [
"def",
"loadTFRecords",
"(",
"sc",
",",
"input_dir",
",",
"binary_features",
"=",
"[",
"]",
")",
":",
"import",
"tensorflow",
"as",
"tf",
"tfr_rdd",
"=",
"sc",
".",
"newAPIHadoopFile",
"(",
"input_dir",
",",
"\"org.tensorflow.hadoop.io.TFRecordFileInputFormat\"",
",",
"keyClass",
"=",
"\"org.apache.hadoop.io.BytesWritable\"",
",",
"valueClass",
"=",
"\"org.apache.hadoop.io.NullWritable\"",
")",
"# infer Spark SQL types from tf.Example",
"record",
"=",
"tfr_rdd",
".",
"take",
"(",
"1",
")",
"[",
"0",
"]",
"example",
"=",
"tf",
".",
"train",
".",
"Example",
"(",
")",
"example",
".",
"ParseFromString",
"(",
"bytes",
"(",
"record",
"[",
"0",
"]",
")",
")",
"schema",
"=",
"infer_schema",
"(",
"example",
",",
"binary_features",
")",
"# convert serialized protobuf to tf.Example to Row",
"example_rdd",
"=",
"tfr_rdd",
".",
"mapPartitions",
"(",
"lambda",
"x",
":",
"fromTFExample",
"(",
"x",
",",
"binary_features",
")",
")",
"# create a Spark DataFrame from RDD[Row]",
"df",
"=",
"example_rdd",
".",
"toDF",
"(",
"schema",
")",
"# save reference of this dataframe",
"loadedDF",
"[",
"df",
"]",
"=",
"input_dir",
"return",
"df"
] |
Parse command line argument for a collector | def parse_args ( name = "" , args = None ) : def _load_json_file ( path ) : with open ( path ) as f : json_data = json . load ( f ) json_data [ 'path_to_json_file' ] = path return json_data parser = argparse . ArgumentParser ( description = "%s collector for sending" " data to the performance" " platform" % name ) parser . add_argument ( '-c' , '--credentials' , dest = 'credentials' , type = _load_json_file , help = 'JSON file containing credentials ' 'for the collector' , required = True ) group = parser . add_mutually_exclusive_group ( required = True ) group . add_argument ( '-l' , '--collector' , dest = 'collector_slug' , type = str , help = 'Collector slug to query the API for the ' 'collector config' ) group . add_argument ( '-q' , '--query' , dest = 'query' , type = _load_json_file , help = 'JSON file containing details ' 'about the query to make ' 'against the source API ' 'and the target data-set' ) parser . add_argument ( '-t' , '--token' , dest = 'token' , type = _load_json_file , help = 'JSON file containing token ' 'for the collector' , required = True ) parser . add_argument ( '-b' , '--performanceplatform' , dest = 'performanceplatform' , type = _load_json_file , help = 'JSON file containing the Performance Platform ' 'config for the collector' , required = True ) parser . add_argument ( '-s' , '--start' , dest = 'start_at' , type = parse_date , help = 'Date to start collection from' ) parser . add_argument ( '-e' , '--end' , dest = 'end_at' , type = parse_date , help = 'Date to end collection' ) parser . add_argument ( '--console-logging' , dest = 'console_logging' , action = 'store_true' , help = 'Output logging to the console rather than file' ) parser . add_argument ( '--dry-run' , dest = 'dry_run' , action = 'store_true' , help = 'Instead of pushing to the Performance Platform ' 'the collector will print out what would have ' 'been pushed' ) parser . set_defaults ( console_logging = False , dry_run = False ) args = parser . parse_args ( args ) return args | 5,277 | https://github.com/alphagov/performanceplatform-collector/blob/de68ab4aa500c31e436e050fa1268fa928c522a5/performanceplatform/collector/arguments.py#L6-L63 | [
"def",
"_openResources",
"(",
"self",
")",
":",
"try",
":",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"True",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
"ex",
")",
"logger",
".",
"warning",
"(",
"\"Unable to read wav with memmory mapping. Trying without now.\"",
")",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"False",
")",
"self",
".",
"_array",
"=",
"data",
"self",
".",
"attributes",
"[",
"'rate'",
"]",
"=",
"rate"
] |
Returns a hash of this render configuration from the variable renderer and time_index parameters . Used for caching the full - extent native projection render so that subsequent requests can be served by a warp operation only . | def hash ( self ) : renderer_str = "{}|{}|{}|{}" . format ( self . renderer . __class__ . __name__ , self . renderer . colormap , self . renderer . fill_value , self . renderer . background_color ) if isinstance ( self . renderer , StretchedRenderer ) : renderer_str = "{}|{}|{}" . format ( renderer_str , self . renderer . method , self . renderer . colorspace ) elif isinstance ( self . renderer , UniqueValuesRenderer ) : renderer_str = "{}|{}" . format ( renderer_str , self . renderer . labels ) return hash ( "{}/{}/{}" . format ( self . variable . pk , renderer_str , self . time_index ) ) | 5,278 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/config.py#L54-L70 | [
"def",
"read_associations",
"(",
"assoc_fn",
",",
"anno_type",
"=",
"'id2gos'",
",",
"*",
"*",
"kws",
")",
":",
"# kws get_objanno: taxids hdr_only prt allow_missing_symbol",
"obj",
"=",
"get_objanno",
"(",
"assoc_fn",
",",
"anno_type",
",",
"*",
"*",
"kws",
")",
"# kws get_id2gos: ev_include ev_exclude keep_ND keep_NOT b_geneid2gos go2geneids",
"return",
"obj",
".",
"get_id2gos",
"(",
"*",
"*",
"kws",
")"
] |
Factory for creating objects . Arguments are passed directly to the constructor of the chosen class . | def factory ( type , module = None , * * kwargs ) : cls = type if module is None : module = __name__ fn = lambda member : inspect . isclass ( member ) and member . __module__ == module classes = odict ( inspect . getmembers ( sys . modules [ module ] , fn ) ) members = odict ( [ ( k . lower ( ) , v ) for k , v in classes . items ( ) ] ) lower = cls . lower ( ) if lower not in list ( members . keys ( ) ) : msg = "Unrecognized class: %s.%s" % ( module , cls ) raise KeyError ( msg ) return members [ lower ] ( * * kwargs ) | 5,279 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/factory.py#L9-L23 | [
"def",
"get_dbs",
"(",
")",
":",
"url",
"=",
"posixpath",
".",
"join",
"(",
"config",
".",
"db_index_url",
",",
"'DBS'",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"dbs",
"=",
"response",
".",
"content",
".",
"decode",
"(",
"'ascii'",
")",
".",
"splitlines",
"(",
")",
"dbs",
"=",
"[",
"re",
".",
"sub",
"(",
"'\\t{2,}'",
",",
"'\\t'",
",",
"line",
")",
".",
"split",
"(",
"'\\t'",
")",
"for",
"line",
"in",
"dbs",
"]",
"return",
"dbs"
] |
Returns a dictionary definition of the given renderer | def get_definition_from_renderer ( renderer ) : config = { 'colors' : [ [ x [ 0 ] , x [ 1 ] . to_hex ( ) ] for x in renderer . colormap ] , 'options' : { } } if renderer . fill_value : config [ 'options' ] [ 'fill_value' ] = renderer . fill_value if isinstance ( renderer , StretchedRenderer ) : config [ 'type' ] = 'stretched' config [ 'options' ] [ 'color_space' ] = renderer . colorspace elif isinstance ( renderer , UniqueValuesRenderer ) : config [ 'type' ] = 'unique' if renderer . labels : config [ 'options' ] [ 'labels' ] = renderer . labels elif isinstance ( renderer , ClassifiedRenderer ) : config [ 'type' ] = 'classified' else : raise ValueError ( '{0} is not a valid renderer type' . format ( renderer . __class__ . __name__ ) ) return config | 5,280 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/interfaces/arcgis_extended/utils.py#L46-L69 | [
"def",
"readAnnotations",
"(",
"self",
")",
":",
"annot",
"=",
"self",
".",
"read_annotation",
"(",
")",
"annot",
"=",
"np",
".",
"array",
"(",
"annot",
")",
"if",
"(",
"annot",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
",",
"np",
".",
"array",
"(",
"[",
"]",
")",
",",
"np",
".",
"array",
"(",
"[",
"]",
")",
"ann_time",
"=",
"self",
".",
"_get_float",
"(",
"annot",
"[",
":",
",",
"0",
"]",
")",
"ann_text",
"=",
"annot",
"[",
":",
",",
"2",
"]",
"ann_text_out",
"=",
"[",
"\"\"",
"for",
"x",
"in",
"range",
"(",
"len",
"(",
"annot",
"[",
":",
",",
"1",
"]",
")",
")",
"]",
"for",
"i",
"in",
"np",
".",
"arange",
"(",
"len",
"(",
"annot",
"[",
":",
",",
"1",
"]",
")",
")",
":",
"ann_text_out",
"[",
"i",
"]",
"=",
"self",
".",
"_convert_string",
"(",
"ann_text",
"[",
"i",
"]",
")",
"if",
"annot",
"[",
"i",
",",
"1",
"]",
"==",
"''",
":",
"annot",
"[",
"i",
",",
"1",
"]",
"=",
"'-1'",
"ann_duration",
"=",
"self",
".",
"_get_float",
"(",
"annot",
"[",
":",
",",
"1",
"]",
")",
"return",
"ann_time",
"/",
"10000000",
",",
"ann_duration",
",",
"np",
".",
"array",
"(",
"ann_text_out",
")"
] |
Set a model . | def set_model ( self , name , model ) : # Careful to not use `hasattr` # https://hynek.me/articles/hasattr/ try : self . __getattribute__ ( 'models' ) except AttributeError : object . __setattr__ ( self , 'models' , odict ( ) ) self . models [ name ] = model | 5,281 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/source.py#L170-L188 | [
"def",
"OnAdjustVolume",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"volume",
"=",
"self",
".",
"player",
".",
"audio_get_volume",
"(",
")",
"if",
"event",
".",
"GetWheelRotation",
"(",
")",
"<",
"0",
":",
"self",
".",
"volume",
"=",
"max",
"(",
"0",
",",
"self",
".",
"volume",
"-",
"10",
")",
"elif",
"event",
".",
"GetWheelRotation",
"(",
")",
">",
"0",
":",
"self",
".",
"volume",
"=",
"min",
"(",
"200",
",",
"self",
".",
"volume",
"+",
"10",
")",
"self",
".",
"player",
".",
"audio_set_volume",
"(",
"self",
".",
"volume",
")"
] |
Set the parameter values | def set_params ( self , * * kwargs ) : for key , value in list ( kwargs . items ( ) ) : setattr ( self , key , value ) | 5,282 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/source.py#L196-L199 | [
"def",
"serverinfo",
"(",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
")",
":",
"data",
"=",
"_wget",
"(",
"'serverinfo'",
",",
"{",
"}",
",",
"url",
",",
"timeout",
"=",
"timeout",
")",
"if",
"data",
"[",
"'res'",
"]",
"is",
"False",
":",
"return",
"{",
"'error'",
":",
"data",
"[",
"'msg'",
"]",
"}",
"ret",
"=",
"{",
"}",
"data",
"[",
"'msg'",
"]",
".",
"pop",
"(",
"0",
")",
"for",
"line",
"in",
"data",
"[",
"'msg'",
"]",
":",
"tmp",
"=",
"line",
".",
"split",
"(",
"':'",
")",
"ret",
"[",
"tmp",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"]",
"=",
"tmp",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"return",
"ret"
] |
Get an odict of the parameter names and values | def get_params ( self ) : return odict ( [ ( key , param . value ) for key , param in self . params . items ( ) ] ) | 5,283 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/source.py#L201-L203 | [
"def",
"_getLPA",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
".",
"line",
")",
"+",
"\":\"",
"+",
"str",
"(",
"self",
".",
"pos",
")",
"+",
"\":\"",
"+",
"str",
"(",
"self",
".",
"absPosition",
")"
] |
Get an odict of free parameter names and values | def get_free_params ( self ) : return odict ( [ ( key , param . value ) for key , param in self . params . items ( ) if param . free ] ) | 5,284 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/analysis/source.py#L205-L207 | [
"def",
"remove_mentions",
"(",
"self",
",",
"string",
")",
":",
"def",
"replace",
"(",
"obj",
",",
"*",
",",
"transforms",
"=",
"self",
".",
"MENTION_TRANSFORMS",
")",
":",
"return",
"transforms",
".",
"get",
"(",
"obj",
".",
"group",
"(",
"0",
")",
",",
"'@invalid'",
")",
"return",
"self",
".",
"MENTION_PATTERN",
".",
"sub",
"(",
"replace",
",",
"string",
")"
] |
Generate all matches found within a string for a regex and yield each match as a string | def iter_finds ( regex_obj , s ) : if isinstance ( regex_obj , str ) : for m in re . finditer ( regex_obj , s ) : yield m . group ( ) else : for m in regex_obj . finditer ( s ) : yield m . group ( ) | 5,285 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/regexes.py#L292-L299 | [
"def",
"to_ip",
"(",
"self",
")",
":",
"if",
"'chargeability'",
"in",
"self",
".",
"data",
".",
"columns",
":",
"tdip",
"=",
"reda",
".",
"TDIP",
"(",
"data",
"=",
"self",
".",
"data",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Missing column \"chargeability\"'",
")",
"return",
"tdip"
] |
Decorator for wrapping functions that calculate a weighted sum | def composite_decorator ( func ) : @ wraps ( func ) def wrapper ( self , * args , * * kwargs ) : total = [ ] for weight , iso in zip ( self . weights , self . isochrones ) : subfunc = getattr ( iso , func . __name__ ) total . append ( weight * subfunc ( * args , * * kwargs ) ) return np . sum ( total , axis = 0 ) return wrapper | 5,286 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/isochrone/composite.py#L83-L94 | [
"def",
"process_mutect_vcf",
"(",
"job",
",",
"mutect_vcf",
",",
"work_dir",
",",
"univ_options",
")",
":",
"mutect_vcf",
"=",
"job",
".",
"fileStore",
".",
"readGlobalFile",
"(",
"mutect_vcf",
")",
"with",
"open",
"(",
"mutect_vcf",
",",
"'r'",
")",
"as",
"infile",
",",
"open",
"(",
"mutect_vcf",
"+",
"'mutect_parsed.tmp'",
",",
"'w'",
")",
"as",
"outfile",
":",
"for",
"line",
"in",
"infile",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"print",
"(",
"line",
",",
"file",
"=",
"outfile",
")",
"continue",
"line",
"=",
"line",
".",
"split",
"(",
"'\\t'",
")",
"if",
"line",
"[",
"6",
"]",
"!=",
"'REJECT'",
":",
"print",
"(",
"'\\t'",
".",
"join",
"(",
"line",
")",
",",
"file",
"=",
"outfile",
")",
"return",
"outfile",
".",
"name"
] |
Merge a list of Catalogs . | def mergeCatalogs ( catalog_list ) : # Check the columns for c in catalog_list : if c . data . dtype . names != catalog_list [ 0 ] . data . dtype . names : msg = "Catalog data columns not the same." raise Exception ( msg ) data = np . concatenate ( [ c . data for c in catalog_list ] ) config = catalog_list [ 0 ] . config return Catalog ( config , data = data ) | 5,287 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/catalog.py#L254-L273 | [
"def",
"where_ends_with",
"(",
"self",
",",
"field_name",
",",
"value",
")",
":",
"if",
"field_name",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"None field_name is invalid\"",
")",
"field_name",
"=",
"Query",
".",
"escape_if_needed",
"(",
"field_name",
")",
"self",
".",
"_add_operator_if_needed",
"(",
")",
"self",
".",
"negate_if_needed",
"(",
"field_name",
")",
"self",
".",
"last_equality",
"=",
"{",
"field_name",
":",
"value",
"}",
"token",
"=",
"_Token",
"(",
"field_name",
"=",
"field_name",
",",
"token",
"=",
"\"endsWith\"",
",",
"value",
"=",
"self",
".",
"add_query_parameter",
"(",
"value",
")",
")",
"token",
".",
"write",
"=",
"self",
".",
"rql_where_write",
"(",
"token",
")",
"self",
".",
"_where_tokens",
".",
"append",
"(",
"token",
")",
"return",
"self"
] |
Return a new catalog which is a subset of objects selected using the input cut array . | def applyCut ( self , cut ) : return Catalog ( self . config , data = self . data [ cut ] ) | 5,288 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/catalog.py#L54-L61 | [
"def",
"load_config",
"(",
"logdir",
")",
":",
"# pylint: disable=missing-raises-doc",
"config_path",
"=",
"logdir",
"and",
"os",
".",
"path",
".",
"join",
"(",
"logdir",
",",
"'config.yaml'",
")",
"if",
"not",
"config_path",
"or",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"config_path",
")",
":",
"message",
"=",
"(",
"'Cannot resume an existing run since the logging directory does not '",
"'contain a configuration file.'",
")",
"raise",
"IOError",
"(",
"message",
")",
"with",
"tf",
".",
"gfile",
".",
"FastGFile",
"(",
"config_path",
",",
"'r'",
")",
"as",
"file_",
":",
"config",
"=",
"yaml",
".",
"load",
"(",
"file_",
",",
"Loader",
"=",
"yaml",
".",
"Loader",
")",
"message",
"=",
"'Resume run and write summaries and checkpoints to {}.'",
"tf",
".",
"logging",
".",
"info",
"(",
"message",
".",
"format",
"(",
"config",
".",
"logdir",
")",
")",
"return",
"config"
] |
Return a random catalog by boostrapping the colors of the objects in the current catalog . | def bootstrap ( self , mc_bit = 0x10 , seed = None ) : if seed is not None : np . random . seed ( seed ) data = copy . deepcopy ( self . data ) idx = np . random . randint ( 0 , len ( data ) , len ( data ) ) data [ self . config [ 'catalog' ] [ 'mag_1_field' ] ] [ : ] = self . mag_1 [ idx ] data [ self . config [ 'catalog' ] [ 'mag_err_1_field' ] ] [ : ] = self . mag_err_1 [ idx ] data [ self . config [ 'catalog' ] [ 'mag_2_field' ] ] [ : ] = self . mag_2 [ idx ] data [ self . config [ 'catalog' ] [ 'mag_err_2_field' ] ] [ : ] = self . mag_err_2 [ idx ] data [ self . config [ 'catalog' ] [ 'mc_source_id_field' ] ] [ : ] |= mc_bit return Catalog ( self . config , data = data ) | 5,289 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/catalog.py#L63-L75 | [
"def",
"from_path",
"(",
"cls",
",",
"path",
":",
"pathlib",
".",
"Path",
")",
"->",
"'Entity'",
":",
"if",
"path",
".",
"is_file",
"(",
")",
":",
"return",
"File",
".",
"from_path",
"(",
"path",
")",
"return",
"Directory",
".",
"from_path",
"(",
"path",
")"
] |
Project coordinates on sphere to image plane using Projector class . | def project ( self , projector = None ) : msg = "'%s.project': ADW 2018-05-05" % self . __class__ . __name__ DeprecationWarning ( msg ) if projector is None : try : self . projector = ugali . utils . projector . Projector ( self . config [ 'coords' ] [ 'reference' ] [ 0 ] , self . config [ 'coords' ] [ 'reference' ] [ 1 ] ) except KeyError : logger . warning ( 'Projection reference point is median (lon, lat) of catalog objects' ) self . projector = ugali . utils . projector . Projector ( np . median ( self . lon ) , np . median ( self . lat ) ) else : self . projector = projector self . x , self . y = self . projector . sphereToImage ( self . lon , self . lat ) | 5,290 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/catalog.py#L77-L93 | [
"def",
"as_data_frame",
"(",
"self",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"header_gene",
"=",
"{",
"}",
"header_multiplex",
"=",
"{",
"}",
"headr_transitions",
"=",
"{",
"}",
"for",
"gene",
"in",
"self",
".",
"influence_graph",
".",
"genes",
":",
"header_gene",
"[",
"gene",
"]",
"=",
"repr",
"(",
"gene",
")",
"header_multiplex",
"[",
"gene",
"]",
"=",
"f\"active multiplex on {gene!r}\"",
"headr_transitions",
"[",
"gene",
"]",
"=",
"f\"K_{gene!r}\"",
"columns",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"state",
"in",
"self",
".",
"table",
".",
"keys",
"(",
")",
":",
"for",
"gene",
"in",
"self",
".",
"influence_graph",
".",
"genes",
":",
"columns",
"[",
"header_gene",
"[",
"gene",
"]",
"]",
".",
"append",
"(",
"state",
"[",
"gene",
"]",
")",
"columns",
"[",
"header_multiplex",
"[",
"gene",
"]",
"]",
".",
"append",
"(",
"self",
".",
"_repr_multiplexes",
"(",
"gene",
",",
"state",
")",
")",
"columns",
"[",
"headr_transitions",
"[",
"gene",
"]",
"]",
".",
"append",
"(",
"self",
".",
"_repr_transition",
"(",
"gene",
",",
"state",
")",
")",
"header",
"=",
"list",
"(",
"header_gene",
".",
"values",
"(",
")",
")",
"+",
"list",
"(",
"header_multiplex",
".",
"values",
"(",
")",
")",
"+",
"list",
"(",
"headr_transitions",
".",
"values",
"(",
")",
")",
"return",
"pandas",
".",
"DataFrame",
"(",
"columns",
",",
"columns",
"=",
"header",
")"
] |
Calculate indices of ROI pixels corresponding to object locations . | def spatialBin ( self , roi ) : if hasattr ( self , 'pixel_roi_index' ) and hasattr ( self , 'pixel' ) : logger . warning ( 'Catalog alread spatially binned' ) return # ADW: Not safe to set index = -1 (since it will access last entry); # np.inf would be better... self . pixel = ang2pix ( self . config [ 'coords' ] [ 'nside_pixel' ] , self . lon , self . lat ) self . pixel_roi_index = roi . indexROI ( self . lon , self . lat ) logger . info ( "Found %i objects outside ROI" % ( self . pixel_roi_index < 0 ) . sum ( ) ) | 5,291 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/catalog.py#L95-L108 | [
"def",
"execute_partitioned_dml",
"(",
"self",
",",
"dml",
",",
"params",
"=",
"None",
",",
"param_types",
"=",
"None",
")",
":",
"if",
"params",
"is",
"not",
"None",
":",
"if",
"param_types",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Specify 'param_types' when passing 'params'.\"",
")",
"params_pb",
"=",
"Struct",
"(",
"fields",
"=",
"{",
"key",
":",
"_make_value_pb",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"params",
".",
"items",
"(",
")",
"}",
")",
"else",
":",
"params_pb",
"=",
"None",
"api",
"=",
"self",
".",
"spanner_api",
"txn_options",
"=",
"TransactionOptions",
"(",
"partitioned_dml",
"=",
"TransactionOptions",
".",
"PartitionedDml",
"(",
")",
")",
"metadata",
"=",
"_metadata_with_prefix",
"(",
"self",
".",
"name",
")",
"with",
"SessionCheckout",
"(",
"self",
".",
"_pool",
")",
"as",
"session",
":",
"txn",
"=",
"api",
".",
"begin_transaction",
"(",
"session",
".",
"name",
",",
"txn_options",
",",
"metadata",
"=",
"metadata",
")",
"txn_selector",
"=",
"TransactionSelector",
"(",
"id",
"=",
"txn",
".",
"id",
")",
"restart",
"=",
"functools",
".",
"partial",
"(",
"api",
".",
"execute_streaming_sql",
",",
"session",
".",
"name",
",",
"dml",
",",
"transaction",
"=",
"txn_selector",
",",
"params",
"=",
"params_pb",
",",
"param_types",
"=",
"param_types",
",",
"metadata",
"=",
"metadata",
",",
")",
"iterator",
"=",
"_restart_on_unavailable",
"(",
"restart",
")",
"result_set",
"=",
"StreamedResultSet",
"(",
"iterator",
")",
"list",
"(",
"result_set",
")",
"# consume all partials",
"return",
"result_set",
".",
"stats",
".",
"row_count_lower_bound"
] |
Write the current object catalog to FITS file . | def write ( self , outfile , clobber = True , * * kwargs ) : fitsio . write ( outfile , self . data , clobber = True , * * kwargs ) | 5,292 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/catalog.py#L110-L124 | [
"def",
"delete_network_acl",
"(",
"network_acl_id",
"=",
"None",
",",
"network_acl_name",
"=",
"None",
",",
"disassociate",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"disassociate",
":",
"network_acl",
"=",
"_get_resource",
"(",
"'network_acl'",
",",
"name",
"=",
"network_acl_name",
",",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"if",
"network_acl",
"and",
"network_acl",
".",
"associations",
":",
"subnet_id",
"=",
"network_acl",
".",
"associations",
"[",
"0",
"]",
".",
"subnet_id",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"conn",
".",
"disassociate_network_acl",
"(",
"subnet_id",
")",
"except",
"BotoServerError",
":",
"pass",
"return",
"_delete_resource",
"(",
"resource",
"=",
"'network_acl'",
",",
"name",
"=",
"network_acl_name",
",",
"resource_id",
"=",
"network_acl_id",
",",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")"
] |
Parse catalog FITS files into recarray . | def _parse ( self , roi = None , filenames = None ) : if ( roi is not None ) and ( filenames is not None ) : msg = "Cannot take both roi and filenames" raise Exception ( msg ) if roi is not None : pixels = roi . getCatalogPixels ( ) filenames = self . config . getFilenames ( ) [ 'catalog' ] [ pixels ] elif filenames is None : filenames = self . config . getFilenames ( ) [ 'catalog' ] . compressed ( ) else : filenames = np . atleast_1d ( filenames ) if len ( filenames ) == 0 : msg = "No catalog files found." raise Exception ( msg ) # Load the data self . data = load_infiles ( filenames ) # Apply a selection cut self . _applySelection ( ) # Cast data to recarray (historical reasons) self . data = self . data . view ( np . recarray ) | 5,293 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/catalog.py#L126-L161 | [
"async",
"def",
"_wait",
"(",
"self",
",",
"entity_type",
",",
"entity_id",
",",
"action",
",",
"predicate",
"=",
"None",
")",
":",
"q",
"=",
"asyncio",
".",
"Queue",
"(",
"loop",
"=",
"self",
".",
"_connector",
".",
"loop",
")",
"async",
"def",
"callback",
"(",
"delta",
",",
"old",
",",
"new",
",",
"model",
")",
":",
"await",
"q",
".",
"put",
"(",
"delta",
".",
"get_id",
"(",
")",
")",
"self",
".",
"add_observer",
"(",
"callback",
",",
"entity_type",
",",
"action",
",",
"entity_id",
",",
"predicate",
")",
"entity_id",
"=",
"await",
"q",
".",
"get",
"(",
")",
"# object might not be in the entity_map if we were waiting for a",
"# 'remove' action",
"return",
"self",
".",
"state",
".",
"_live_entity_map",
"(",
"entity_type",
")",
".",
"get",
"(",
"entity_id",
")"
] |
Helper funtion to define pertinent variables from catalog data . | def _defineVariables ( self ) : logger . info ( 'Catalog contains %i objects' % ( len ( self . data ) ) ) mc_source_id_field = self . config [ 'catalog' ] [ 'mc_source_id_field' ] if mc_source_id_field is not None : if mc_source_id_field not in self . data . dtype . names : array = np . zeros ( len ( self . data ) , dtype = '>i8' ) # FITS byte-order convention self . data = mlab . rec_append_fields ( self . data , names = mc_source_id_field , arrs = array ) logger . info ( 'Found %i simulated objects' % ( np . sum ( self . mc_source_id > 0 ) ) ) | 5,294 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/catalog.py#L178-L193 | [
"def",
"from_rep",
"(",
"u",
")",
":",
"if",
"isinstance",
"(",
"u",
",",
"pyversion",
".",
"string_types",
")",
":",
"return",
"uuid",
".",
"UUID",
"(",
"u",
")",
"# hack to remove signs",
"a",
"=",
"ctypes",
".",
"c_ulong",
"(",
"u",
"[",
"0",
"]",
")",
"b",
"=",
"ctypes",
".",
"c_ulong",
"(",
"u",
"[",
"1",
"]",
")",
"combined",
"=",
"a",
".",
"value",
"<<",
"64",
"|",
"b",
".",
"value",
"return",
"uuid",
".",
"UUID",
"(",
"int",
"=",
"combined",
")"
] |
Adds a node to the workflow . | def add_node ( self , node_id , task , inputs ) : if node_id in self . nodes_by_id : raise ValueError ( 'The node {0} already exists in this workflow.' . format ( node_id ) ) node = WorkflowNode ( node_id , task , inputs ) self . nodes_by_id [ node_id ] = node for source , value in six . itervalues ( inputs ) : if source == 'dependency' : dependents = self . dependents_by_node_id . get ( value [ 0 ] , set ( ) ) dependents . add ( node_id ) self . dependents_by_node_id [ value [ 0 ] ] = dependents | 5,295 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/workflow.py#L179-L201 | [
"def",
"vapour_pressure",
"(",
"Temperature",
",",
"element",
")",
":",
"if",
"element",
"==",
"\"Rb\"",
":",
"Tmelt",
"=",
"39.30",
"+",
"273.15",
"# K.",
"if",
"Temperature",
"<",
"Tmelt",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.857",
"-",
"4215.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.312",
"-",
"4040.0",
"/",
"Temperature",
")",
"# Torr.",
"elif",
"element",
"==",
"\"Cs\"",
":",
"Tmelt",
"=",
"28.5",
"+",
"273.15",
"# K.",
"if",
"Temperature",
"<",
"Tmelt",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.711",
"-",
"3999.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.165",
"-",
"3830.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"s",
"=",
"str",
"(",
"element",
")",
"s",
"+=",
"\" is not an element in the database for this function.\"",
"raise",
"ValueError",
"(",
"s",
")",
"P",
"=",
"P",
"*",
"101325.0",
"/",
"760.0",
"# Pascals.",
"return",
"P"
] |
Maps the output from a node to a workflow output . | def map_output ( self , node_id , node_output_name , parameter_name ) : self . output_mapping [ parameter_name ] = ( node_id , node_output_name ) dependents = self . dependents_by_node_id . get ( node_id , set ( ) ) dependents . add ( 'output_{}' . format ( parameter_name ) ) self . dependents_by_node_id [ node_id ] = dependents | 5,296 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/workflow.py#L203-L216 | [
"def",
"vapour_pressure",
"(",
"Temperature",
",",
"element",
")",
":",
"if",
"element",
"==",
"\"Rb\"",
":",
"Tmelt",
"=",
"39.30",
"+",
"273.15",
"# K.",
"if",
"Temperature",
"<",
"Tmelt",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.857",
"-",
"4215.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.312",
"-",
"4040.0",
"/",
"Temperature",
")",
"# Torr.",
"elif",
"element",
"==",
"\"Cs\"",
":",
"Tmelt",
"=",
"28.5",
"+",
"273.15",
"# K.",
"if",
"Temperature",
"<",
"Tmelt",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.711",
"-",
"3999.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.165",
"-",
"3830.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"s",
"=",
"str",
"(",
"element",
")",
"s",
"+=",
"\" is not an element in the database for this function.\"",
"raise",
"ValueError",
"(",
"s",
")",
"P",
"=",
"P",
"*",
"101325.0",
"/",
"760.0",
"# Pascals.",
"return",
"P"
] |
Serialize this workflow to JSON | def to_json ( self , indent = None ) : inputs = ParameterCollection ( self . inputs ) d = { 'meta' : { 'name' : self . name , 'description' : self . description } , 'inputs' : [ ] , 'workflow' : [ ] , 'outputs' : [ { 'name' : k , 'node' : v } for k , v in six . iteritems ( self . output_mapping ) ] } for parameter in self . inputs : input_info = { 'name' : parameter . name , 'type' : parameter . id } args , kwargs = parameter . serialize_args ( ) args = list ( args ) args . pop ( 0 ) # 'name' is already taken care of kwargs . pop ( 'required' , None ) # 'required' is assumed True for workflow inputs if args or kwargs : input_info [ 'args' ] = [ args , kwargs ] d [ 'inputs' ] . append ( input_info ) for node in sorted ( six . itervalues ( self . nodes_by_id ) , key = lambda x : x . id ) : task_name = node . task . name if not task_name : raise ValueError ( 'The task {0} does not have a name and therefore cannot be serialized.' . format ( node . task . __class__ . __name__ ) ) node_inputs = { } for input_name , ( source , value ) in six . iteritems ( node . inputs ) : input_info = { 'source' : source } if source == 'input' : input_info [ 'input' ] = inputs . by_name [ value ] . name else : input_info [ 'node' ] = value node_inputs [ input_name ] = input_info d [ 'workflow' ] . append ( { 'id' : node . id , 'task' : task_name , 'inputs' : node_inputs } ) return json . dumps ( d , indent = indent ) | 5,297 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/workflow.py#L218-L272 | [
"def",
"vapour_pressure",
"(",
"Temperature",
",",
"element",
")",
":",
"if",
"element",
"==",
"\"Rb\"",
":",
"Tmelt",
"=",
"39.30",
"+",
"273.15",
"# K.",
"if",
"Temperature",
"<",
"Tmelt",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.857",
"-",
"4215.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.312",
"-",
"4040.0",
"/",
"Temperature",
")",
"# Torr.",
"elif",
"element",
"==",
"\"Cs\"",
":",
"Tmelt",
"=",
"28.5",
"+",
"273.15",
"# K.",
"if",
"Temperature",
"<",
"Tmelt",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.711",
"-",
"3999.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"P",
"=",
"10",
"**",
"(",
"2.881",
"+",
"4.165",
"-",
"3830.0",
"/",
"Temperature",
")",
"# Torr.",
"else",
":",
"s",
"=",
"str",
"(",
"element",
")",
"s",
"+=",
"\" is not an element in the database for this function.\"",
"raise",
"ValueError",
"(",
"s",
")",
"P",
"=",
"P",
"*",
"101325.0",
"/",
"760.0",
"# Pascals.",
"return",
"P"
] |
Return a new workflow deserialized from a JSON string | def from_json ( cls , text ) : d = json . loads ( text ) meta = d . get ( 'meta' , { } ) workflow = cls ( name = meta . get ( 'name' ) , description = meta . get ( 'description' ) ) for workflow_input in d . get ( 'inputs' , [ ] ) : parameter_cls = Parameter . by_id ( workflow_input [ 'type' ] ) args = [ workflow_input [ 'name' ] ] kwargs = { 'required' : True } if workflow_input . get ( 'args' ) : args = workflow_input [ 'args' ] [ 0 ] + args kwargs . update ( workflow_input [ 'args' ] [ 1 ] ) args , kwargs = parameter_cls . deserialize_args ( args , kwargs ) workflow . inputs . append ( parameter_cls ( * args , * * kwargs ) ) for node in d . get ( 'workflow' , [ ] ) : node_inputs = { } for k , v in six . iteritems ( node . get ( 'inputs' , { } ) ) : node_inputs [ k ] = ( v [ 'source' ] , v . get ( 'input' ) or v . get ( 'node' ) ) workflow . add_node ( node [ 'id' ] , Task . by_name ( node [ 'task' ] ) ( ) , node_inputs ) for output in d . get ( 'outputs' , [ ] ) : node = output [ 'node' ] node_parameters = ParameterCollection ( workflow . nodes_by_id [ node [ 0 ] ] . task . outputs ) # Add parameter to workflow output output_param = copy . copy ( node_parameters . by_name [ node [ 1 ] ] ) output_param . name = output [ 'name' ] workflow . outputs . append ( output_param ) workflow . map_output ( node [ 0 ] , node [ 1 ] , output [ 'name' ] ) return workflow | 5,298 | https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/workflow.py#L275-L313 | [
"def",
"_check_curtailment_target",
"(",
"curtailment",
",",
"curtailment_target",
",",
"curtailment_key",
")",
":",
"if",
"not",
"(",
"abs",
"(",
"curtailment",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"-",
"curtailment_target",
")",
"<",
"1e-1",
")",
".",
"all",
"(",
")",
":",
"message",
"=",
"'Curtailment target not met for {}.'",
".",
"format",
"(",
"curtailment_key",
")",
"logging",
".",
"error",
"(",
"message",
")",
"raise",
"TypeError",
"(",
"message",
")"
] |
Return the static files serving handler wrapping the default handler if static files should be served . Otherwise return the default handler . | def get_handler ( self , * args , * * options ) : handler = super ( ) . get_handler ( * args , * * options ) use_static_handler = options [ 'use_static_handler' ] insecure_serving = options [ 'insecure_serving' ] if use_static_handler and ( settings . DEBUG or insecure_serving ) : return CRAStaticFilesHandler ( handler ) return handler | 5,299 | https://github.com/MasterKale/django-cra-helper/blob/ba50c643c181a18b80ee9bbdbea74b58abd6daad/cra_helper/management/commands/runserver.py#L11-L21 | [
"def",
"main",
"(",
")",
":",
"from",
"IPython",
"import",
"embed",
"\"\"\" Python 3.5.3 (pypy3)\n libttl 2.387338638305664\n ttl 1.3430471420288086\n diff lt - ttl 1.0442914962768555\n librdfxml 24.70371127128601\n rdfxml 17.85916304588318\n diff lr - rl 6.844548225402832\n simple time 18.32300615310669\n \"\"\"",
"# well I guess that answers that question ...",
"# librdf much faster for cpython, not for pypy3",
"from",
"time",
"import",
"time",
"rdflib",
".",
"plugin",
".",
"register",
"(",
"'librdfxml'",
",",
"rdflib",
".",
"parser",
".",
"Parser",
",",
"'librdflib'",
",",
"'libRdfxmlParser'",
")",
"rdflib",
".",
"plugin",
".",
"register",
"(",
"'libttl'",
",",
"rdflib",
".",
"parser",
".",
"Parser",
",",
"'librdflib'",
",",
"'libTurtleParser'",
")",
"p1",
"=",
"Path",
"(",
"'~/git/NIF-Ontology/ttl/NIF-Molecule.ttl'",
")",
".",
"expanduser",
"(",
")",
"start",
"=",
"time",
"(",
")",
"graph",
"=",
"rdflib",
".",
"Graph",
"(",
")",
".",
"parse",
"(",
"p1",
".",
"as_posix",
"(",
")",
",",
"format",
"=",
"'libttl'",
")",
"stop",
"=",
"time",
"(",
")",
"lttime",
"=",
"stop",
"-",
"start",
"print",
"(",
"'libttl'",
",",
"lttime",
")",
"#serialize(graph)",
"start",
"=",
"time",
"(",
")",
"graph",
"=",
"rdflib",
".",
"Graph",
"(",
")",
".",
"parse",
"(",
"p1",
".",
"as_posix",
"(",
")",
",",
"format",
"=",
"'turtle'",
")",
"stop",
"=",
"time",
"(",
")",
"ttltime",
"=",
"stop",
"-",
"start",
"print",
"(",
"'ttl'",
",",
"ttltime",
")",
"print",
"(",
"'diff lt - ttl'",
",",
"lttime",
"-",
"ttltime",
")",
"p2",
"=",
"Path",
"(",
"'~/git/NIF-Ontology/ttl/external/uberon.owl'",
")",
".",
"expanduser",
"(",
")",
"start",
"=",
"time",
"(",
")",
"graph2",
"=",
"rdflib",
".",
"Graph",
"(",
")",
".",
"parse",
"(",
"p2",
".",
"as_posix",
"(",
")",
",",
"format",
"=",
"'librdfxml'",
")",
"stop",
"=",
"time",
"(",
")",
"lrtime",
"=",
"stop",
"-",
"start",
"print",
"(",
"'librdfxml'",
",",
"lrtime",
")",
"if",
"True",
":",
"start",
"=",
"time",
"(",
")",
"graph2",
"=",
"rdflib",
".",
"Graph",
"(",
")",
".",
"parse",
"(",
"p2",
".",
"as_posix",
"(",
")",
",",
"format",
"=",
"'xml'",
")",
"stop",
"=",
"time",
"(",
")",
"rltime",
"=",
"stop",
"-",
"start",
"print",
"(",
"'rdfxml'",
",",
"rltime",
")",
"print",
"(",
"'diff lr - rl'",
",",
"lrtime",
"-",
"rltime",
")",
"if",
"True",
":",
"file_uri",
"=",
"p2",
".",
"as_uri",
"(",
")",
"parser",
"=",
"RDF",
".",
"Parser",
"(",
"name",
"=",
"'rdfxml'",
")",
"stream",
"=",
"parser",
".",
"parse_as_stream",
"(",
"file_uri",
")",
"start",
"=",
"time",
"(",
")",
"# t = list(stream)",
"t",
"=",
"tuple",
"(",
"statement_to_tuple",
"(",
"statement",
")",
"for",
"statement",
"in",
"stream",
")",
"stop",
"=",
"time",
"(",
")",
"stime",
"=",
"stop",
"-",
"start",
"print",
"(",
"'simple time'",
",",
"stime",
")",
"embed",
"(",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.