query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
use before any custom printing when using the progress iter to ensure your print statement starts on a new line instead of at the end of a progress line | def ensure_newline ( self ) : DECTCEM_SHOW = '\033[?25h' # show cursor AT_END = DECTCEM_SHOW + '\n' if not self . _cursor_at_newline : self . write ( AT_END ) self . _cursor_at_newline = True | 9,600 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_progress.py#L796-L806 | [
"def",
"author_info",
"(",
"name",
",",
"contact",
"=",
"None",
",",
"public_key",
"=",
"None",
")",
":",
"return",
"Storage",
"(",
"name",
"=",
"name",
",",
"contact",
"=",
"contact",
",",
"public_key",
"=",
"public_key",
")"
] |
resonably decent hueristics for how much time to wait before updating progress . | def _get_timethresh_heuristics ( self ) : if self . length > 1E5 : time_thresh = 2.5 elif self . length > 1E4 : time_thresh = 2.0 elif self . length > 1E3 : time_thresh = 1.0 else : time_thresh = 0.5 return time_thresh | 9,601 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_progress.py#L808-L821 | [
"def",
"register_for_app",
"(",
"self",
",",
"app_label",
"=",
"None",
",",
"exclude_models",
"=",
"None",
",",
"exclude_model_classes",
"=",
"None",
")",
":",
"models",
"=",
"[",
"]",
"exclude_models",
"=",
"exclude_models",
"or",
"[",
"]",
"app_config",
"=",
"django_apps",
".",
"get_app_config",
"(",
"app_label",
")",
"for",
"model",
"in",
"app_config",
".",
"get_models",
"(",
")",
":",
"if",
"model",
".",
"_meta",
".",
"label_lower",
"in",
"exclude_models",
":",
"pass",
"elif",
"exclude_model_classes",
"and",
"issubclass",
"(",
"model",
",",
"exclude_model_classes",
")",
":",
"pass",
"else",
":",
"models",
".",
"append",
"(",
"model",
".",
"_meta",
".",
"label_lower",
")",
"self",
".",
"register",
"(",
"models",
")"
] |
Load executable code from a URL or a path | def load_code ( name , base_path = None , recurse = False ) : if '/' in name : return load_location ( name , base_path , module = False ) return importer . import_code ( name , base_path , recurse = recurse ) | 9,602 | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/code.py#L64-L69 | [
"def",
"group_experiments_greedy",
"(",
"tomo_expt",
":",
"TomographyExperiment",
")",
":",
"diag_sets",
"=",
"_max_tpb_overlap",
"(",
"tomo_expt",
")",
"grouped_expt_settings_list",
"=",
"list",
"(",
"diag_sets",
".",
"values",
"(",
")",
")",
"grouped_tomo_expt",
"=",
"TomographyExperiment",
"(",
"grouped_expt_settings_list",
",",
"program",
"=",
"tomo_expt",
".",
"program",
")",
"return",
"grouped_tomo_expt"
] |
Load a module from a URL or a path | def load ( name , base_path = None ) : if '/' in name : return load_location ( name , base_path , module = True ) return importer . import_symbol ( name , base_path ) | 9,603 | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/code.py#L73-L78 | [
"def",
"group_experiments_greedy",
"(",
"tomo_expt",
":",
"TomographyExperiment",
")",
":",
"diag_sets",
"=",
"_max_tpb_overlap",
"(",
"tomo_expt",
")",
"grouped_expt_settings_list",
"=",
"list",
"(",
"diag_sets",
".",
"values",
"(",
")",
")",
"grouped_tomo_expt",
"=",
"TomographyExperiment",
"(",
"grouped_expt_settings_list",
",",
"program",
"=",
"tomo_expt",
".",
"program",
")",
"return",
"grouped_tomo_expt"
] |
Extend sys . path by a list of git paths . | def extend ( path = None , cache = None ) : if path is None : path = config . PATH try : path = path . split ( ':' ) except : pass sys . path . extend ( [ library . to_path ( p , cache ) for p in path ] ) | 9,604 | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/sys_path.py#L5-L14 | [
"def",
"_CreateDynamicDisplayAdSettings",
"(",
"media_service",
",",
"opener",
")",
":",
"image",
"=",
"_CreateImage",
"(",
"media_service",
",",
"opener",
",",
"'https://goo.gl/dEvQeF'",
")",
"logo",
"=",
"{",
"'type'",
":",
"'IMAGE'",
",",
"'mediaId'",
":",
"image",
"[",
"'mediaId'",
"]",
",",
"'xsi_type'",
":",
"'Image'",
"}",
"dynamic_settings",
"=",
"{",
"'landscapeLogoImage'",
":",
"logo",
",",
"'pricePrefix'",
":",
"'as low as'",
",",
"'promoText'",
":",
"'Free shipping!'",
",",
"'xsi_type'",
":",
"'DynamicSettings'",
",",
"}",
"return",
"dynamic_settings"
] |
A context that temporarily extends sys . path and reverts it after the context is complete . | def extender ( path = None , cache = None ) : old_path = sys . path [ : ] extend ( path , cache = None ) try : yield finally : sys . path = old_path | 9,605 | https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/sys_path.py#L18-L27 | [
"def",
"_is_duplicate_record",
"(",
"self",
",",
"rtype",
",",
"name",
",",
"content",
")",
":",
"records",
"=",
"self",
".",
"_list_records",
"(",
"rtype",
",",
"name",
",",
"content",
")",
"is_duplicate",
"=",
"len",
"(",
"records",
")",
">=",
"1",
"if",
"is_duplicate",
":",
"LOGGER",
".",
"info",
"(",
"'Duplicate record %s %s %s, NOOP'",
",",
"rtype",
",",
"name",
",",
"content",
")",
"return",
"is_duplicate"
] |
Adds a typed child object to the conditional derived variable . | def add ( self , child ) : if isinstance ( child , Case ) : self . add_case ( child ) else : raise ModelError ( 'Unsupported child element' ) | 9,606 | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/dynamics.py#L203-L213 | [
"def",
"find_apikey",
"(",
")",
":",
"env_keys",
"=",
"[",
"'TINYPNG_APIKEY'",
",",
"'TINYPNG_API_KEY'",
"]",
"paths",
"=",
"[",
"]",
"paths",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"\".\"",
")",
",",
"\"tinypng.key\"",
")",
")",
"# local directory",
"paths",
".",
"append",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.tinypng.key\"",
")",
")",
"# home directory",
"for",
"env_key",
"in",
"env_keys",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"env_key",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"env_key",
")",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"open",
"(",
"path",
",",
"'rt'",
")",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"return",
"None"
] |
Adds a typed child object to the event handler . | def add ( self , child ) : if isinstance ( child , Action ) : self . add_action ( child ) else : raise ModelError ( 'Unsupported child element' ) | 9,607 | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/dynamics.py#L402-L412 | [
"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",
")"
] |
Adds a typed child object to the behavioral object . | def add ( self , child ) : if isinstance ( child , StateVariable ) : self . add_state_variable ( child ) elif isinstance ( child , DerivedVariable ) : self . add_derived_variable ( child ) elif isinstance ( child , ConditionalDerivedVariable ) : self . add_conditional_derived_variable ( child ) elif isinstance ( child , TimeDerivative ) : self . add_time_derivative ( child ) elif isinstance ( child , EventHandler ) : self . add_event_handler ( child ) elif isinstance ( child , KineticScheme ) : self . add_kinetic_scheme ( child ) else : raise ModelError ( 'Unsupported child element' ) | 9,608 | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/dynamics.py#L757-L777 | [
"def",
"get_or_generate_vocabulary",
"(",
"data_dir",
",",
"tmp_dir",
",",
"data_prefix",
",",
"max_page_size_exp",
",",
"approx_vocab_size",
"=",
"32768",
",",
"strip",
"=",
"True",
")",
":",
"num_pages_for_vocab_generation",
"=",
"approx_vocab_size",
"//",
"3",
"vocab_file",
"=",
"vocab_filename",
"(",
"approx_vocab_size",
",",
"strip",
")",
"def",
"my_generator",
"(",
"data_prefix",
")",
":",
"\"\"\"Line generator for vocab.\"\"\"",
"count",
"=",
"0",
"for",
"page",
"in",
"corpus_page_generator",
"(",
"all_corpus_files",
"(",
"data_prefix",
")",
"[",
":",
":",
"-",
"1",
"]",
",",
"tmp_dir",
",",
"max_page_size_exp",
")",
":",
"revisions",
"=",
"page",
"[",
"\"revisions\"",
"]",
"if",
"revisions",
":",
"text",
"=",
"get_text",
"(",
"revisions",
"[",
"-",
"1",
"]",
",",
"strip",
"=",
"strip",
")",
"yield",
"text",
"count",
"+=",
"1",
"if",
"count",
"%",
"100",
"==",
"0",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"reading pages for vocab %d\"",
"%",
"count",
")",
"if",
"count",
">",
"num_pages_for_vocab_generation",
":",
"break",
"return",
"generator_utils",
".",
"get_or_generate_vocab_inner",
"(",
"data_dir",
",",
"vocab_file",
",",
"approx_vocab_size",
",",
"my_generator",
"(",
"data_prefix",
")",
")"
] |
Adds a typed child object to the dynamics object . | def add ( self , child ) : if isinstance ( child , Regime ) : self . add_regime ( child ) else : Behavioral . add ( self , child ) | 9,609 | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/dynamics.py#L876-L886 | [
"def",
"verify_subscription",
"(",
"request",
",",
"ident",
")",
":",
"try",
":",
"unverified",
"=",
"UnverifiedSubscription",
".",
"objects",
".",
"get",
"(",
"ident",
"=",
"ident",
")",
"except",
"UnverifiedSubscription",
".",
"DoesNotExist",
":",
"return",
"respond",
"(",
"'overseer/invalid_subscription_token.html'",
",",
"{",
"}",
",",
"request",
")",
"subscription",
"=",
"Subscription",
".",
"objects",
".",
"get_or_create",
"(",
"email",
"=",
"unverified",
".",
"email",
",",
"defaults",
"=",
"{",
"'ident'",
":",
"unverified",
".",
"ident",
",",
"}",
")",
"[",
"0",
"]",
"subscription",
".",
"services",
"=",
"unverified",
".",
"services",
".",
"all",
"(",
")",
"unverified",
".",
"delete",
"(",
")",
"return",
"respond",
"(",
"'overseer/subscription_confirmed.html'",
",",
"{",
"'subscription'",
":",
"subscription",
",",
"}",
",",
"request",
")"
] |
Fills lookup database with biological set names | def create_bioset_lookup ( lookupdb , spectrafns , set_names ) : unique_setnames = set ( set_names ) lookupdb . store_biosets ( ( ( x , ) for x in unique_setnames ) ) set_id_map = lookupdb . get_setnames ( ) mzmlfiles = ( ( os . path . basename ( fn ) , set_id_map [ setname ] ) for fn , setname in zip ( spectrafns , set_names ) ) lookupdb . store_mzmlfiles ( mzmlfiles ) lookupdb . index_biosets ( ) | 9,610 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/biosets.py#L4-L12 | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"try",
":",
"if",
"_message_test_port",
"is",
"not",
"None",
":",
"_message_test_port",
".",
"sent",
".",
"append",
"(",
"message",
")",
"yield",
"message",
".",
"send",
"(",
"self",
")",
"except",
"(",
"WebSocketClosedError",
",",
"StreamClosedError",
")",
":",
"# Tornado 4.x may raise StreamClosedError",
"# on_close() is / will be called anyway",
"log",
".",
"warning",
"(",
"\"Failed sending message as connection was closed\"",
")",
"raise",
"gen",
".",
"Return",
"(",
"None",
")"
] |
Same as get_modpath but doesnt import directly | def get_modpath_from_modname ( modname , prefer_pkg = False , prefer_main = False ) : from os . path import dirname , basename , join , exists initname = '__init__.py' mainname = '__main__.py' if modname in sys . modules : modpath = sys . modules [ modname ] . __file__ . replace ( '.pyc' , '.py' ) else : import pkgutil loader = pkgutil . find_loader ( modname ) modpath = loader . filename . replace ( '.pyc' , '.py' ) if '.' not in basename ( modpath ) : modpath = join ( modpath , initname ) if prefer_pkg : if modpath . endswith ( initname ) or modpath . endswith ( mainname ) : modpath = dirname ( modpath ) if prefer_main : if modpath . endswith ( initname ) : main_modpath = modpath [ : - len ( initname ) ] + mainname if exists ( main_modpath ) : modpath = main_modpath return modpath | 9,611 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_import.py#L243-L269 | [
"def",
"validate",
"(",
"ref_time",
",",
"ref_freqs",
",",
"est_time",
",",
"est_freqs",
")",
":",
"util",
".",
"validate_events",
"(",
"ref_time",
",",
"max_time",
"=",
"MAX_TIME",
")",
"util",
".",
"validate_events",
"(",
"est_time",
",",
"max_time",
"=",
"MAX_TIME",
")",
"if",
"ref_time",
".",
"size",
"==",
"0",
":",
"warnings",
".",
"warn",
"(",
"\"Reference times are empty.\"",
")",
"if",
"ref_time",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Reference times have invalid dimension\"",
")",
"if",
"len",
"(",
"ref_freqs",
")",
"==",
"0",
":",
"warnings",
".",
"warn",
"(",
"\"Reference frequencies are empty.\"",
")",
"if",
"est_time",
".",
"size",
"==",
"0",
":",
"warnings",
".",
"warn",
"(",
"\"Estimated times are empty.\"",
")",
"if",
"est_time",
".",
"ndim",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"Estimated times have invalid dimension\"",
")",
"if",
"len",
"(",
"est_freqs",
")",
"==",
"0",
":",
"warnings",
".",
"warn",
"(",
"\"Estimated frequencies are empty.\"",
")",
"if",
"ref_time",
".",
"size",
"!=",
"len",
"(",
"ref_freqs",
")",
":",
"raise",
"ValueError",
"(",
"'Reference times and frequencies have unequal '",
"'lengths.'",
")",
"if",
"est_time",
".",
"size",
"!=",
"len",
"(",
"est_freqs",
")",
":",
"raise",
"ValueError",
"(",
"'Estimate times and frequencies have unequal '",
"'lengths.'",
")",
"for",
"freq",
"in",
"ref_freqs",
":",
"util",
".",
"validate_frequencies",
"(",
"freq",
",",
"max_freq",
"=",
"MAX_FREQ",
",",
"min_freq",
"=",
"MIN_FREQ",
",",
"allow_negatives",
"=",
"False",
")",
"for",
"freq",
"in",
"est_freqs",
":",
"util",
".",
"validate_frequencies",
"(",
"freq",
",",
"max_freq",
"=",
"MAX_FREQ",
",",
"min_freq",
"=",
"MIN_FREQ",
",",
"allow_negatives",
"=",
"False",
")"
] |
Check if a python module is installed without attempting to import it . Note that if modname indicates a child module the parent module is always loaded . | def check_module_installed ( modname ) : import pkgutil if '.' in modname : # Prevent explicit import if possible parts = modname . split ( '.' ) base = parts [ 0 ] submods = parts [ 1 : ] loader = pkgutil . find_loader ( base ) if loader is not None : # TODO: check to see if path to the submod exists submods return True loader = pkgutil . find_loader ( modname ) is_installed = loader is not None return is_installed | 9,612 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_import.py#L272-L317 | [
"def",
"is_registration_possible",
"(",
"self",
",",
"user_info",
")",
":",
"return",
"self",
".",
"get_accessibility",
"(",
")",
".",
"is_open",
"(",
")",
"and",
"self",
".",
"_registration",
".",
"is_open",
"(",
")",
"and",
"self",
".",
"is_user_accepted_by_access_control",
"(",
"user_info",
")"
] |
r imports module from a file path | def import_module_from_fpath ( module_fpath ) : from os . path import basename , splitext , isdir , join , exists , dirname , split import platform if isdir ( module_fpath ) : module_fpath = join ( module_fpath , '__init__.py' ) print ( 'module_fpath = {!r}' . format ( module_fpath ) ) if not exists ( module_fpath ) : raise ImportError ( 'module_fpath={!r} does not exist' . format ( module_fpath ) ) python_version = platform . python_version ( ) modname = splitext ( basename ( module_fpath ) ) [ 0 ] if modname == '__init__' : modname = split ( dirname ( module_fpath ) ) [ 1 ] if util_inject . PRINT_INJECT_ORDER : if modname not in sys . argv : util_inject . noinject ( modname , N = 2 , via = 'ut.import_module_from_fpath' ) if python_version . startswith ( '2.7' ) : import imp module = imp . load_source ( modname , module_fpath ) elif python_version . startswith ( '3' ) : import importlib . machinery loader = importlib . machinery . SourceFileLoader ( modname , module_fpath ) module = loader . load_module ( ) # module = loader.exec_module(modname) else : raise AssertionError ( 'invalid python version={!r}' . format ( python_version ) ) return module | 9,613 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_import.py#L469-L609 | [
"def",
"_ValidateClosedTimeRange",
"(",
"time_range",
")",
":",
"time_range_start",
",",
"time_range_end",
"=",
"time_range",
"_ValidateTimestamp",
"(",
"time_range_start",
")",
"_ValidateTimestamp",
"(",
"time_range_end",
")",
"if",
"time_range_start",
">",
"time_range_end",
":",
"raise",
"ValueError",
"(",
"\"Invalid time-range: %d > %d.\"",
"%",
"(",
"time_range_start",
".",
"AsMicrosecondsSinceEpoch",
"(",
")",
",",
"time_range_end",
".",
"AsMicrosecondsSinceEpoch",
"(",
")",
")",
")"
] |
Prints local variables in function . | def print_locals ( * args , * * kwargs ) : from utool import util_str from utool import util_dbg from utool import util_dict locals_ = util_dbg . get_parent_frame ( ) . f_locals keys = kwargs . get ( 'keys' , None if len ( args ) == 0 else [ ] ) to_print = { } for arg in args : varname = util_dbg . get_varname_from_locals ( arg , locals_ ) to_print [ varname ] = arg if keys is not None : to_print . update ( util_dict . dict_take ( locals_ , keys ) ) if not to_print : to_print = locals_ locals_str = util_str . repr4 ( to_print ) print ( locals_str ) | 9,614 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_print.py#L329-L353 | [
"def",
"get_listing",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'listing'",
")",
":",
"allEvents",
"=",
"self",
".",
"get_allEvents",
"(",
")",
"openEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
"closedEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
"publicEvents",
"=",
"allEvents",
".",
"instance_of",
"(",
"PublicEvent",
")",
"allSeries",
"=",
"allEvents",
".",
"instance_of",
"(",
"Series",
")",
"self",
".",
"listing",
"=",
"{",
"'allEvents'",
":",
"allEvents",
",",
"'openEvents'",
":",
"openEvents",
",",
"'closedEvents'",
":",
"closedEvents",
",",
"'publicEvents'",
":",
"publicEvents",
",",
"'allSeries'",
":",
"allSeries",
",",
"'regOpenEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"publicevent__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'regClosedEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
".",
"filter",
"(",
"Q",
"(",
"publicevent__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'categorySeparateEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"True",
")",
".",
"order_by",
"(",
"'publicevent__category'",
")",
",",
"'regOpenSeries'",
":",
"allSeries",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"series__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"series__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'regClosedSeries'",
":",
"allSeries",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
".",
"filter",
"(",
"Q",
"(",
"series__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"series__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'categorySeparateSeries'",
":",
"allSeries",
".",
"filter",
"(",
"series__category__separateOnRegistrationPage",
"=",
"True",
")",
".",
"order_by",
"(",
"'series__category'",
")",
",",
"}",
"return",
"self",
".",
"listing"
] |
archive_fpath = zip_fpath archive_file = zip_file | def _extract_archive ( archive_fpath , archive_file , archive_namelist , output_dir , force_commonprefix = True , prefix = None , dryrun = False , verbose = not QUIET , overwrite = None ) : # force extracted components into a subdirectory if force_commonprefix is # on return_path = output_diG # FIXMpathE doesn't work right if prefix is not None : output_dir = join ( output_dir , prefix ) util_path . ensurepath ( output_dir ) archive_basename , ext = split_archive_ext ( basename ( archive_fpath ) ) if force_commonprefix and commonprefix ( archive_namelist ) == '' : # use the archivename as the default common prefix output_dir = join ( output_dir , archive_basename ) util_path . ensurepath ( output_dir ) for member in archive_namelist : ( dname , fname ) = split ( member ) dpath = join ( output_dir , dname ) util_path . ensurepath ( dpath ) if verbose : print ( '[utool] Unarchive ' + fname + ' in ' + dpath ) if not dryrun : if overwrite is False : if exists ( join ( output_dir , member ) ) : continue archive_file . extract ( member , path = output_dir ) return output_dir | 9,615 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L164-L196 | [
"def",
"_check_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"self",
".",
"available_types",
":",
"msg",
"=",
"'Unsupported cluster type was given: %s'",
"%",
"self",
".",
"type",
"raise",
"DeviceGroupNotSupported",
"(",
"msg",
")",
"elif",
"self",
".",
"type",
"==",
"'sync-only'",
"and",
"self",
".",
"name",
"!=",
"'device_trust_group'",
":",
"msg",
"=",
"\"Management of sync-only device groups only supported for \"",
"\"built-in device group named 'device_trust_group'\"",
"raise",
"DeviceGroupNotSupported",
"(",
"msg",
")"
] |
r Opens a url in the specified or default browser | def open_url_in_browser ( url , browsername = None , fallback = False ) : import webbrowser print ( '[utool] Opening url=%r in browser' % ( url , ) ) if browsername is None : browser = webbrowser . open ( url ) else : browser = get_prefered_browser ( pref_list = [ browsername ] , fallback = fallback ) return browser . open ( url ) | 9,616 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L199-L222 | [
"def",
"CopyToStatTimeTuple",
"(",
"self",
")",
":",
"normalized_timestamp",
"=",
"self",
".",
"_GetNormalizedTimestamp",
"(",
")",
"if",
"normalized_timestamp",
"is",
"None",
":",
"return",
"None",
",",
"None",
"if",
"self",
".",
"_precision",
"in",
"(",
"definitions",
".",
"PRECISION_1_NANOSECOND",
",",
"definitions",
".",
"PRECISION_100_NANOSECONDS",
",",
"definitions",
".",
"PRECISION_1_MICROSECOND",
",",
"definitions",
".",
"PRECISION_1_MILLISECOND",
",",
"definitions",
".",
"PRECISION_100_MILLISECONDS",
")",
":",
"remainder",
"=",
"int",
"(",
"(",
"normalized_timestamp",
"%",
"1",
")",
"*",
"self",
".",
"_100NS_PER_SECOND",
")",
"return",
"int",
"(",
"normalized_timestamp",
")",
",",
"remainder",
"return",
"int",
"(",
"normalized_timestamp",
")",
",",
"None"
] |
r Directly reads data from url | def url_read ( url , verbose = True ) : if url . find ( '://' ) == - 1 : url = 'http://' + url if verbose : print ( 'Reading data from url=%r' % ( url , ) ) try : file_ = _urllib . request . urlopen ( url ) #file_ = _urllib.urlopen(url) except IOError : raise data = file_ . read ( ) file_ . close ( ) return data | 9,617 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L402-L417 | [
"async",
"def",
"open_search",
"(",
"type_",
":",
"str",
",",
"query",
":",
"dict",
",",
"options",
":",
"dict",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"if",
"not",
"hasattr",
"(",
"Wallet",
".",
"open_search",
",",
"\"cb\"",
")",
":",
"logger",
".",
"debug",
"(",
"\"vcx_wallet_open_search: Creating callback\"",
")",
"Wallet",
".",
"open_search",
".",
"cb",
"=",
"create_cb",
"(",
"CFUNCTYPE",
"(",
"None",
",",
"c_uint32",
",",
"c_uint32",
",",
"c_uint32",
")",
")",
"c_type_",
"=",
"c_char_p",
"(",
"type_",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"c_query",
"=",
"c_char_p",
"(",
"json",
".",
"dumps",
"(",
"query",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"c_options",
"=",
"c_char_p",
"(",
"json",
".",
"dumps",
"(",
"options",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"options",
"else",
"None",
"data",
"=",
"await",
"do_call",
"(",
"'vcx_wallet_open_search'",
",",
"c_type_",
",",
"c_query",
",",
"c_options",
",",
"Wallet",
".",
"open_search",
".",
"cb",
")",
"logger",
".",
"debug",
"(",
"\"vcx_wallet_open_search completed\"",
")",
"return",
"data"
] |
r Directly reads text data from url | def url_read_text ( url , verbose = True ) : data = url_read ( url , verbose ) text = data . decode ( 'utf8' ) return text | 9,618 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L420-L426 | [
"def",
"singleton_init_by",
"(",
"init_fn",
"=",
"None",
")",
":",
"if",
"not",
"init_fn",
":",
"def",
"wrap_init",
"(",
"origin_init",
")",
":",
"return",
"origin_init",
"else",
":",
"def",
"wrap_init",
"(",
"origin_init",
")",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"origin_init",
"(",
"self",
")",
"init_fn",
"(",
"self",
")",
"return",
"__init__",
"def",
"inner",
"(",
"cls_def",
":",
"type",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls_def",
",",
"'__instancecheck__'",
")",
"or",
"isinstance",
"(",
"cls_def",
".",
"__instancecheck__",
",",
"(",
"types",
".",
"BuiltinMethodType",
",",
"_slot_wrapper",
")",
")",
":",
"def",
"__instancecheck__",
"(",
"self",
",",
"instance",
")",
":",
"return",
"instance",
"is",
"self",
"cls_def",
".",
"__instancecheck__",
"=",
"__instancecheck__",
"_origin_init",
"=",
"cls_def",
".",
"__init__",
"cls_def",
".",
"__init__",
"=",
"wrap_init",
"(",
"_origin_init",
")",
"return",
"cls_def",
"(",
")",
"return",
"inner"
] |
Dropbox links should be en - mass downloaed from dl . dropbox | def clean_dropbox_link ( dropbox_url ) : cleaned_url = dropbox_url . replace ( 'www.dropbox' , 'dl.dropbox' ) postfix_list = [ '?dl=0' ] for postfix in postfix_list : if cleaned_url . endswith ( postfix ) : cleaned_url = cleaned_url [ : - 1 * len ( postfix ) ] # cleaned_url = cleaned_url.rstrip('?dl=0') return cleaned_url | 9,619 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L503-L526 | [
"def",
"create_alarm_subscription",
"(",
"self",
",",
"on_data",
"=",
"None",
",",
"timeout",
"=",
"60",
")",
":",
"manager",
"=",
"WebSocketSubscriptionManager",
"(",
"self",
".",
"_client",
",",
"resource",
"=",
"'alarms'",
")",
"# Represent subscription as a future",
"subscription",
"=",
"AlarmSubscription",
"(",
"manager",
")",
"wrapped_callback",
"=",
"functools",
".",
"partial",
"(",
"_wrap_callback_parse_alarm_data",
",",
"subscription",
",",
"on_data",
")",
"manager",
".",
"open",
"(",
"wrapped_callback",
",",
"instance",
"=",
"self",
".",
"_instance",
",",
"processor",
"=",
"self",
".",
"_processor",
")",
"# Wait until a reply or exception is received",
"subscription",
".",
"reply",
"(",
"timeout",
"=",
"timeout",
")",
"return",
"subscription"
] |
r Automatically download selenium chrome driver if needed | def grab_selenium_chromedriver ( redownload = False ) : import utool as ut import os import stat # TODO: use a better download dir (but it must be in the PATh or selenium freaks out) chromedriver_dpath = ut . ensuredir ( ut . truepath ( '~/bin' ) ) chromedriver_fpath = join ( chromedriver_dpath , 'chromedriver' ) if not ut . checkpath ( chromedriver_fpath ) or redownload : assert chromedriver_dpath in os . environ [ 'PATH' ] . split ( os . pathsep ) # TODO: make this work for windows as well if ut . LINUX and ut . util_cplat . is64bit_python ( ) : import requests rsp = requests . get ( 'http://chromedriver.storage.googleapis.com/LATEST_RELEASE' , timeout = TIMEOUT ) assert rsp . status_code == 200 url = 'http://chromedriver.storage.googleapis.com/' + rsp . text . strip ( ) + '/chromedriver_linux64.zip' ut . grab_zipped_url ( url , download_dir = chromedriver_dpath , redownload = True ) else : raise AssertionError ( 'unsupported chrome driver getter script' ) if not ut . WIN32 : st = os . stat ( chromedriver_fpath ) os . chmod ( chromedriver_fpath , st . st_mode | stat . S_IEXEC ) ut . assert_exists ( chromedriver_fpath ) os . environ [ 'webdriver.chrome.driver' ] = chromedriver_fpath return chromedriver_fpath | 9,620 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L627-L675 | [
"def",
"cfg",
"(",
"self",
")",
":",
"config",
"=",
"LStruct",
"(",
"self",
".",
"defaults",
")",
"module",
"=",
"config",
"[",
"'CONFIG'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"CONFIGURATION_ENVIRON_VARIABLE",
",",
"config",
"[",
"'CONFIG'",
"]",
")",
"if",
"module",
":",
"try",
":",
"module",
"=",
"import_module",
"(",
"module",
")",
"config",
".",
"update",
"(",
"{",
"name",
":",
"getattr",
"(",
"module",
",",
"name",
")",
"for",
"name",
"in",
"dir",
"(",
"module",
")",
"if",
"name",
"==",
"name",
".",
"upper",
"(",
")",
"and",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
"}",
")",
"except",
"ImportError",
"as",
"exc",
":",
"config",
".",
"CONFIG",
"=",
"None",
"self",
".",
"logger",
".",
"error",
"(",
"\"Error importing %s: %s\"",
",",
"module",
",",
"exc",
")",
"# Patch configuration from ENV",
"for",
"name",
"in",
"config",
":",
"if",
"name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"name",
"!=",
"name",
".",
"upper",
"(",
")",
"or",
"name",
"not",
"in",
"os",
".",
"environ",
":",
"continue",
"try",
":",
"config",
"[",
"name",
"]",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
"[",
"name",
"]",
")",
"except",
"ValueError",
":",
"pass",
"return",
"config"
] |
pip install selenium - U | def grab_selenium_driver ( driver_name = None ) : from selenium import webdriver if driver_name is None : driver_name = 'firefox' if driver_name . lower ( ) == 'chrome' : grab_selenium_chromedriver ( ) return webdriver . Chrome ( ) elif driver_name . lower ( ) == 'firefox' : # grab_selenium_chromedriver() return webdriver . Firefox ( ) else : raise AssertionError ( 'unknown name = %r' % ( driver_name , ) ) | 9,621 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L678-L692 | [
"def",
"_GetDelayImportTimestamps",
"(",
"self",
",",
"pefile_object",
")",
":",
"delay_import_timestamps",
"=",
"[",
"]",
"if",
"not",
"hasattr",
"(",
"pefile_object",
",",
"'DIRECTORY_ENTRY_DELAY_IMPORT'",
")",
":",
"return",
"delay_import_timestamps",
"for",
"importdata",
"in",
"pefile_object",
".",
"DIRECTORY_ENTRY_DELAY_IMPORT",
":",
"dll_name",
"=",
"importdata",
".",
"dll",
"try",
":",
"dll_name",
"=",
"dll_name",
".",
"decode",
"(",
"'ascii'",
")",
"except",
"UnicodeDecodeError",
":",
"dll_name",
"=",
"dll_name",
".",
"decode",
"(",
"'ascii'",
",",
"errors",
"=",
"'replace'",
")",
"timestamp",
"=",
"getattr",
"(",
"importdata",
".",
"struct",
",",
"'dwTimeStamp'",
",",
"0",
")",
"delay_import_timestamps",
".",
"append",
"(",
"[",
"dll_name",
",",
"timestamp",
"]",
")",
"return",
"delay_import_timestamps"
] |
r Downloads a file and returns the local path of the file . | def grab_file_url ( file_url , appname = 'utool' , download_dir = None , delay = None , spoof = False , fname = None , verbose = True , redownload = False , check_hash = False ) : file_url = clean_dropbox_link ( file_url ) if fname is None : fname = basename ( file_url ) # Download zipfile to if download_dir is None : download_dir = util_cplat . get_app_cache_dir ( appname ) # Zipfile should unzip to: fpath = join ( download_dir , fname ) # If check hash, get remote hash and assert local copy is the same if check_hash : if isinstance ( check_hash , ( list , tuple ) ) : hash_list = check_hash else : hash_list = [ 'md5' ] # hash_list = ['sha1.custom', 'md5', 'sha1', 'sha256'] # Get expected remote file hash_remote , hash_tag_remote = grab_file_remote_hash ( file_url , hash_list , verbose = verbose ) hash_list = [ hash_tag_remote ] # We have a valid candidate hash from remote, check for same hash locally hash_local , hash_tag_local = get_file_local_hash ( fpath , hash_list , verbose = verbose ) if verbose : print ( '[utool] Pre Local Hash: %r' % ( hash_local , ) ) print ( '[utool] Pre Remote Hash: %r' % ( hash_remote , ) ) # Check all 4 hash conditions if hash_remote is None : # No remote hash provided, turn off post-download hash check check_hash = False elif hash_local is None : if verbose : print ( '[utool] Remote hash provided but local hash missing, redownloading.' ) redownload = True elif hash_local == hash_remote : assert hash_tag_local == hash_tag_remote , ( 'hash tag disagreement' ) else : if verbose : print ( '[utool] Both hashes provided, but they disagree, redownloading.' ) redownload = True # Download util_path . ensurepath ( download_dir ) if redownload or not exists ( fpath ) : # Download testdata if verbose : print ( '[utool] Downloading file %s' % fpath ) if delay is not None : print ( '[utool] delay download by %r seconds' % ( delay , ) ) time . sleep ( delay ) download_url ( file_url , fpath , spoof = spoof ) else : if verbose : print ( '[utool] Already have file %s' % fpath ) util_path . assert_exists ( fpath ) # Post-download local hash verification if check_hash : # File has been successfuly downloaded, write remote hash to local hash file hash_fpath = '%s.%s' % ( fpath , hash_tag_remote , ) with open ( hash_fpath , 'w' ) as hash_file : hash_file . write ( hash_remote ) # For sanity check (custom) and file verification (hashing), get local hash again hash_local , hash_tag_local = get_file_local_hash ( fpath , hash_list , verbose = verbose ) if verbose : print ( '[utool] Post Local Hash: %r' % ( hash_local , ) ) assert hash_local == hash_remote , 'Post-download hash disagreement' assert hash_tag_local == hash_tag_remote , 'Post-download hash tag disagreement' return fpath | 9,622 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L782-L905 | [
"def",
"get_form_kwargs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"super",
"(",
"ClassRegistrationView",
",",
"self",
")",
".",
"get_form_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"kwargs",
"[",
"'user'",
"]",
"=",
"self",
".",
"request",
".",
"user",
"if",
"hasattr",
"(",
"self",
".",
"request",
",",
"'user'",
")",
"else",
"None",
"listing",
"=",
"self",
".",
"get_listing",
"(",
")",
"kwargs",
".",
"update",
"(",
"{",
"'openEvents'",
":",
"listing",
"[",
"'openEvents'",
"]",
",",
"'closedEvents'",
":",
"listing",
"[",
"'closedEvents'",
"]",
",",
"}",
")",
"return",
"kwargs"
] |
r downloads and unzips the url | def grab_zipped_url ( zipped_url , ensure = True , appname = 'utool' , download_dir = None , force_commonprefix = True , cleanup = False , redownload = False , spoof = False ) : zipped_url = clean_dropbox_link ( zipped_url ) zip_fname = split ( zipped_url ) [ 1 ] data_name = split_archive_ext ( zip_fname ) [ 0 ] # Download zipfile to if download_dir is None : download_dir = util_cplat . get_app_cache_dir ( appname ) # Zipfile should unzip to: data_dir = join ( download_dir , data_name ) if ensure or redownload : if redownload : util_path . remove_dirs ( data_dir ) util_path . ensurepath ( download_dir ) if not exists ( data_dir ) or redownload : # Download and unzip testdata zip_fpath = realpath ( join ( download_dir , zip_fname ) ) #print('[utool] Downloading archive %s' % zip_fpath) if not exists ( zip_fpath ) or redownload : download_url ( zipped_url , zip_fpath , spoof = spoof ) unarchive_file ( zip_fpath , force_commonprefix ) if cleanup : util_path . delete ( zip_fpath ) # Cleanup if cleanup : util_path . assert_exists ( data_dir ) return util_path . unixpath ( data_dir ) | 9,623 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L908-L974 | [
"def",
"audit_customer_subscription",
"(",
"customer",
",",
"unknown",
"=",
"True",
")",
":",
"if",
"(",
"hasattr",
"(",
"customer",
",",
"'suspended'",
")",
"and",
"customer",
".",
"suspended",
")",
":",
"result",
"=",
"AUDIT_RESULTS",
"[",
"'suspended'",
"]",
"else",
":",
"if",
"hasattr",
"(",
"customer",
",",
"'subscription'",
")",
":",
"try",
":",
"result",
"=",
"AUDIT_RESULTS",
"[",
"customer",
".",
"subscription",
".",
"status",
"]",
"except",
"KeyError",
",",
"err",
":",
"# TODO should this be a more specific exception class?",
"raise",
"Exception",
"(",
"\"Unable to locate a result set for \\\nsubscription status %s in ZEBRA_AUDIT_RESULTS\"",
")",
"%",
"str",
"(",
"err",
")",
"else",
":",
"result",
"=",
"AUDIT_RESULTS",
"[",
"'no_subscription'",
"]",
"return",
"result"
] |
r wrapper for scp | def scp_pull ( remote_path , local_path = '.' , remote = 'localhost' , user = None ) : import utool as ut if user is not None : remote_uri = user + '@' + remote + ':' + remote_path else : remote_uri = remote + ':' + remote_path scp_exe = 'scp' scp_args = ( scp_exe , '-r' , remote_uri , local_path ) ut . cmd ( scp_args ) | 9,624 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L1123-L1132 | [
"def",
"permutation_entropy",
"(",
"x",
",",
"n",
",",
"tau",
")",
":",
"PeSeq",
"=",
"[",
"]",
"Em",
"=",
"embed_seq",
"(",
"x",
",",
"tau",
",",
"n",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"Em",
")",
")",
":",
"r",
"=",
"[",
"]",
"z",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"Em",
"[",
"i",
"]",
")",
")",
":",
"z",
".",
"append",
"(",
"Em",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"Em",
"[",
"i",
"]",
")",
")",
":",
"z",
".",
"sort",
"(",
")",
"r",
".",
"append",
"(",
"z",
".",
"index",
"(",
"Em",
"[",
"i",
"]",
"[",
"j",
"]",
")",
")",
"z",
"[",
"z",
".",
"index",
"(",
"Em",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"]",
"=",
"-",
"1",
"PeSeq",
".",
"append",
"(",
"r",
")",
"RankMat",
"=",
"[",
"]",
"while",
"len",
"(",
"PeSeq",
")",
">",
"0",
":",
"RankMat",
".",
"append",
"(",
"PeSeq",
".",
"count",
"(",
"PeSeq",
"[",
"0",
"]",
")",
")",
"x",
"=",
"PeSeq",
"[",
"0",
"]",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"PeSeq",
".",
"count",
"(",
"PeSeq",
"[",
"0",
"]",
")",
")",
":",
"PeSeq",
".",
"pop",
"(",
"PeSeq",
".",
"index",
"(",
"x",
")",
")",
"RankMat",
"=",
"numpy",
".",
"array",
"(",
"RankMat",
")",
"RankMat",
"=",
"numpy",
".",
"true_divide",
"(",
"RankMat",
",",
"RankMat",
".",
"sum",
"(",
")",
")",
"EntropyMat",
"=",
"numpy",
".",
"multiply",
"(",
"numpy",
".",
"log2",
"(",
"RankMat",
")",
",",
"RankMat",
")",
"PE",
"=",
"-",
"1",
"*",
"EntropyMat",
".",
"sum",
"(",
")",
"return",
"PE"
] |
remote_uri = user | def list_remote ( remote_uri , verbose = False ) : remote_uri1 , remote_dpath = remote_uri . split ( ':' ) if not remote_dpath : remote_dpath = '.' import utool as ut out = ut . cmd ( 'ssh' , remote_uri1 , 'ls -l %s' % ( remote_dpath , ) , verbose = verbose ) import re # Find lines that look like ls output split_lines = [ re . split ( r'\s+' , t ) for t in out [ 0 ] . split ( '\n' ) ] paths = [ ' ' . join ( t2 [ 8 : ] ) for t2 in split_lines if len ( t2 ) > 8 ] return paths | 9,625 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L1135-L1148 | [
"def",
"cli",
"(",
"ctx",
",",
"ftdi_enable",
",",
"ftdi_disable",
",",
"serial_enable",
",",
"serial_disable",
")",
":",
"exit_code",
"=",
"0",
"if",
"ftdi_enable",
":",
"# pragma: no cover",
"exit_code",
"=",
"Drivers",
"(",
")",
".",
"ftdi_enable",
"(",
")",
"elif",
"ftdi_disable",
":",
"# pragma: no cover",
"exit_code",
"=",
"Drivers",
"(",
")",
".",
"ftdi_disable",
"(",
")",
"elif",
"serial_enable",
":",
"# pragma: no cover",
"exit_code",
"=",
"Drivers",
"(",
")",
".",
"serial_enable",
"(",
")",
"elif",
"serial_disable",
":",
"# pragma: no cover",
"exit_code",
"=",
"Drivers",
"(",
")",
".",
"serial_disable",
"(",
")",
"else",
":",
"click",
".",
"secho",
"(",
"ctx",
".",
"get_help",
"(",
")",
")",
"ctx",
".",
"exit",
"(",
"exit_code",
")"
] |
r Wrapper for rsync | def rsync ( src_uri , dst_uri , exclude_dirs = [ ] , port = 22 , dryrun = False ) : from utool import util_cplat rsync_exe = 'rsync' rsync_options = '-avhzP' #rsync_options += ' --port=%d' % (port,) rsync_options += ' -e "ssh -p %d"' % ( port , ) if len ( exclude_dirs ) > 0 : exclude_tup = [ '--exclude ' + dir_ for dir_ in exclude_dirs ] exclude_opts = ' ' . join ( exclude_tup ) rsync_options += ' ' + exclude_opts cmdtuple = ( rsync_exe , rsync_options , src_uri , dst_uri ) cmdstr = ' ' . join ( cmdtuple ) print ( '[rsync] src_uri = %r ' % ( src_uri , ) ) print ( '[rsync] dst_uri = %r ' % ( dst_uri , ) ) print ( '[rsync] cmdstr = %r' % cmdstr ) print ( cmdstr ) #if not dryrun: util_cplat . cmd ( cmdstr , dryrun = dryrun ) | 9,626 | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_grabdata.py#L1151-L1214 | [
"def",
"_create_download_failed_message",
"(",
"exception",
",",
"url",
")",
":",
"message",
"=",
"'Failed to download from:\\n{}\\nwith {}:\\n{}'",
".",
"format",
"(",
"url",
",",
"exception",
".",
"__class__",
".",
"__name__",
",",
"exception",
")",
"if",
"_is_temporal_problem",
"(",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"requests",
".",
"ConnectionError",
")",
":",
"message",
"+=",
"'\\nPlease check your internet connection and try again.'",
"else",
":",
"message",
"+=",
"'\\nThere might be a problem in connection or the server failed to process '",
"'your request. Please try again.'",
"elif",
"isinstance",
"(",
"exception",
",",
"requests",
".",
"HTTPError",
")",
":",
"try",
":",
"server_message",
"=",
"''",
"for",
"elem",
"in",
"decode_data",
"(",
"exception",
".",
"response",
".",
"content",
",",
"MimeType",
".",
"XML",
")",
":",
"if",
"'ServiceException'",
"in",
"elem",
".",
"tag",
"or",
"'Message'",
"in",
"elem",
".",
"tag",
":",
"server_message",
"+=",
"elem",
".",
"text",
".",
"strip",
"(",
"'\\n\\t '",
")",
"except",
"ElementTree",
".",
"ParseError",
":",
"server_message",
"=",
"exception",
".",
"response",
".",
"text",
"message",
"+=",
"'\\nServer response: \"{}\"'",
".",
"format",
"(",
"server_message",
")",
"return",
"message"
] |
Get a cached value for the specified date range and query | def get_cache ( self , namespace , query_hash , length , start , end ) : query = 'SELECT start, value FROM gauged_cache WHERE namespace = ? ' 'AND hash = ? AND length = ? AND start BETWEEN ? AND ?' cursor = self . cursor cursor . execute ( query , ( namespace , query_hash , length , start , end ) ) return tuple ( cursor . fetchall ( ) ) | 9,627 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/drivers/sqlite.py#L237-L243 | [
"def",
"fixpairs",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fixpairs",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"3",
":",
"sys",
".",
"exit",
"(",
"not",
"p",
".",
"print_help",
"(",
")",
")",
"pairsfile",
",",
"sep",
",",
"sd",
"=",
"args",
"newpairsfile",
"=",
"pairsfile",
".",
"rsplit",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"+",
"\".new.pairs\"",
"sep",
"=",
"int",
"(",
"sep",
")",
"sd",
"=",
"int",
"(",
"sd",
")",
"p",
"=",
"PairsFile",
"(",
"pairsfile",
")",
"p",
".",
"fixLibraryStats",
"(",
"sep",
",",
"sd",
")",
"p",
".",
"write",
"(",
"newpairsfile",
")"
] |
Reviews the final bug report . | def review ( cls , content , log , parent , window_icon ) : # pragma: no cover dlg = DlgReview ( content , log , parent , window_icon ) if dlg . exec_ ( ) : return dlg . ui . edit_main . toPlainText ( ) , dlg . ui . edit_log . toPlainText ( ) return None , None | 9,628 | https://github.com/ColinDuquesnoy/QCrash/blob/775e1b15764e2041a8f9a08bea938e4d6ce817c7/qcrash/_dialogs/review.py#L44-L58 | [
"def",
"ttl",
"(",
"self",
",",
"value",
")",
":",
"# get timer",
"timer",
"=",
"getattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"None",
")",
"# if timer is running, stop the timer",
"if",
"timer",
"is",
"not",
"None",
":",
"timer",
".",
"cancel",
"(",
")",
"# initialize timestamp",
"timestamp",
"=",
"None",
"# if value is None",
"if",
"value",
"is",
"None",
":",
"# nonify timer",
"timer",
"=",
"None",
"else",
":",
"# else, renew a timer",
"# get timestamp",
"timestamp",
"=",
"time",
"(",
")",
"+",
"value",
"# start a new timer",
"timer",
"=",
"Timer",
"(",
"value",
",",
"self",
".",
"__del__",
")",
"timer",
".",
"start",
"(",
")",
"# set/update attributes",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"timer",
")",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TS",
",",
"timestamp",
")"
] |
Return version from setup . py | def get_version ( ) : version_desc = open ( os . path . join ( os . path . abspath ( APISettings . VERSION_FILE ) ) ) version_file = version_desc . read ( ) try : version = re . search ( r"version=['\"]([^'\"]+)['\"]" , version_file ) . group ( 1 ) return version except FileNotFoundError : Shell . fail ( 'File not found!' ) raise FileNotFoundError except ValueError : Shell . fail ( 'Version not found in file ' + version_file + '!' ) raise ValueError finally : version_desc . close ( ) | 9,629 | https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L13-L30 | [
"def",
"get_thumbnails",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# First, delete any related thumbnails.",
"source_cache",
"=",
"self",
".",
"get_source_cache",
"(",
")",
"if",
"source_cache",
":",
"thumbnail_storage_hash",
"=",
"utils",
".",
"get_storage_hash",
"(",
"self",
".",
"thumbnail_storage",
")",
"for",
"thumbnail_cache",
"in",
"source_cache",
".",
"thumbnails",
".",
"all",
"(",
")",
":",
"# Only iterate files which are stored using the current",
"# thumbnail storage.",
"if",
"thumbnail_cache",
".",
"storage_hash",
"==",
"thumbnail_storage_hash",
":",
"yield",
"ThumbnailFile",
"(",
"name",
"=",
"thumbnail_cache",
".",
"name",
",",
"storage",
"=",
"self",
".",
"thumbnail_storage",
")"
] |
Write new version into VERSION_FILE | def set_version ( old_version , new_version ) : try : if APISettings . DEBUG : Shell . debug ( '* ' + old_version + ' --> ' + new_version ) return True for line in fileinput . input ( os . path . abspath ( APISettings . VERSION_FILE ) , inplace = True ) : print ( line . replace ( old_version , new_version ) , end = '' ) Shell . success ( '* ' + old_version + ' --> ' + new_version ) except FileNotFoundError : Shell . warn ( 'File not found!' ) | 9,630 | https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L33-L46 | [
"def",
"remove_all_callbacks",
"(",
"self",
")",
":",
"for",
"cb_id",
"in",
"list",
"(",
"self",
".",
"_next_tick_callback_removers",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_next_tick_callback",
"(",
"cb_id",
")",
"for",
"cb_id",
"in",
"list",
"(",
"self",
".",
"_timeout_callback_removers",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_timeout_callback",
"(",
"cb_id",
")",
"for",
"cb_id",
"in",
"list",
"(",
"self",
".",
"_periodic_callback_removers",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_periodic_callback",
"(",
"cb_id",
")"
] |
Increment the major number of project | def set_major ( self ) : old_version = self . get_version ( ) new_version = str ( int ( old_version . split ( '.' , 5 ) [ 0 ] ) + 1 ) + '.0.0' self . set_version ( old_version , new_version ) | 9,631 | https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L71-L77 | [
"def",
"expire_queues",
"(",
"self",
")",
":",
"curr_time",
"=",
"time",
".",
"time",
"(",
")",
"for",
"key",
"in",
"list",
"(",
"self",
".",
"queue_dict",
")",
":",
"diff",
"=",
"curr_time",
"-",
"self",
".",
"queue_dict",
"[",
"key",
"]",
"[",
"1",
"]",
"if",
"diff",
">",
"self",
".",
"queue_timeout",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Expiring domain queue key \"",
"+",
"key",
")",
"del",
"self",
".",
"queue_dict",
"[",
"key",
"]",
"if",
"key",
"in",
"self",
".",
"queue_keys",
":",
"self",
".",
"queue_keys",
".",
"remove",
"(",
"key",
")"
] |
Increment the minor number of project | def set_minor ( self ) : old_version = self . get_version ( ) new_version = str ( int ( old_version . split ( '.' , 5 ) [ 0 ] ) ) + '.' + str ( int ( old_version . split ( '.' , 5 ) [ 1 ] ) + 1 ) + '.0' self . set_version ( old_version , new_version ) | 9,632 | https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L79-L86 | [
"def",
"_get_keycodes",
"(",
")",
":",
"try",
":",
"return",
"_key_cache",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"pass",
"result",
"=",
"[",
"]",
"terminators",
"=",
"'ABCDFHPQRS~'",
"with",
"TerminalContext",
"(",
")",
":",
"code",
"=",
"get_ord",
"(",
")",
"result",
".",
"append",
"(",
"code",
")",
"if",
"code",
"==",
"27",
":",
"with",
"TimerContext",
"(",
"0.1",
")",
"as",
"timer",
":",
"code",
"=",
"get_ord",
"(",
")",
"if",
"not",
"timer",
".",
"timed_out",
":",
"result",
".",
"append",
"(",
"code",
")",
"result",
".",
"append",
"(",
"get_ord",
"(",
")",
")",
"if",
"64",
"<",
"result",
"[",
"-",
"1",
"]",
"<",
"69",
":",
"pass",
"elif",
"result",
"[",
"1",
"]",
"==",
"91",
":",
"while",
"True",
":",
"code",
"=",
"get_ord",
"(",
")",
"result",
".",
"append",
"(",
"code",
")",
"if",
"chr",
"(",
"code",
")",
"in",
"terminators",
":",
"break",
"return",
"tuple",
"(",
"result",
")"
] |
Increment the patch number of project | def set_patch ( self , pre_release_tag = '' ) : current_version = self . get_version ( ) current_patch = self . get_patch_version ( current_version ) current_pre_release_tag = self . get_current_pre_release_tag ( current_patch ) current_RELEASE_SEPARATOR = self . get_current_RELEASE_SEPARATOR ( current_patch ) new_patch = '' # The new patch should get a release tag if pre_release_tag : # Check, if the current patch already contains a pre_release_tag. if current_pre_release_tag : new_patch = str ( current_patch . split ( current_pre_release_tag , 2 ) [ 0 ] ) + pre_release_tag if pre_release_tag == current_pre_release_tag : new_patch += str ( int ( current_patch . split ( current_pre_release_tag , 2 ) [ 1 ] ) + 1 ) else : new_patch += '0' # The current patch does not contains a pre_release_tag. else : new_patch = str ( int ( current_patch ) + 1 ) + APISettings . RELEASE_SEPARATOR + pre_release_tag + '0' # The new patch should not contain any tag. So just increase it. else : if current_RELEASE_SEPARATOR : new_patch = str ( int ( current_patch . split ( current_RELEASE_SEPARATOR , 2 ) [ 0 ] ) + 1 ) elif current_pre_release_tag : new_patch = str ( int ( current_patch . split ( current_pre_release_tag , 2 ) [ 0 ] ) + 1 ) else : new_patch = str ( int ( current_patch ) + 1 ) new_version = str ( int ( current_version . split ( '.' , 5 ) [ 0 ] ) ) + '.' + str ( int ( current_version . split ( '.' , 5 ) [ 1 ] ) ) + '.' + str ( new_patch ) self . set_version ( current_version , new_version ) | 9,633 | https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/version/version.py#L88-L134 | [
"def",
"clear_results_db",
"(",
"session",
")",
":",
"from",
"egoio",
".",
"db_tables",
".",
"model_draft",
"import",
"EgoGridPfHvResultBus",
"as",
"BusResult",
",",
"EgoGridPfHvResultBusT",
"as",
"BusTResult",
",",
"EgoGridPfHvResultStorage",
"as",
"StorageResult",
",",
"EgoGridPfHvResultStorageT",
"as",
"StorageTResult",
",",
"EgoGridPfHvResultGenerator",
"as",
"GeneratorResult",
",",
"EgoGridPfHvResultGeneratorT",
"as",
"GeneratorTResult",
",",
"EgoGridPfHvResultLine",
"as",
"LineResult",
",",
"EgoGridPfHvResultLineT",
"as",
"LineTResult",
",",
"EgoGridPfHvResultLoad",
"as",
"LoadResult",
",",
"EgoGridPfHvResultLoadT",
"as",
"LoadTResult",
",",
"EgoGridPfHvResultTransformer",
"as",
"TransformerResult",
",",
"EgoGridPfHvResultTransformerT",
"as",
"TransformerTResult",
",",
"EgoGridPfHvResultMeta",
"as",
"ResultMeta",
"print",
"(",
"'Are you sure that you want to clear all results in the OEDB?'",
")",
"choice",
"=",
"''",
"while",
"choice",
"not",
"in",
"[",
"'y'",
",",
"'n'",
"]",
":",
"choice",
"=",
"input",
"(",
"'(y/n): '",
")",
"if",
"choice",
"==",
"'y'",
":",
"print",
"(",
"'Are you sure?'",
")",
"choice2",
"=",
"''",
"while",
"choice2",
"not",
"in",
"[",
"'y'",
",",
"'n'",
"]",
":",
"choice2",
"=",
"input",
"(",
"'(y/n): '",
")",
"if",
"choice2",
"==",
"'y'",
":",
"print",
"(",
"'Deleting all results...'",
")",
"session",
".",
"query",
"(",
"BusResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"BusTResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"StorageResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"StorageTResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"GeneratorResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"GeneratorTResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"LoadResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"LoadTResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"LineResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"LineTResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"TransformerResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"TransformerTResult",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"ResultMeta",
")",
".",
"delete",
"(",
")",
"session",
".",
"commit",
"(",
")",
"else",
":",
"print",
"(",
"'Deleting aborted!'",
")",
"else",
":",
"print",
"(",
"'Deleting aborted!'",
")"
] |
Return all buffered data and clear the stack . | def flush ( self ) : ( slice_ , self . __buffer ) = ( self . __buffer , '' ) self . __size = 0 return slice_ | 9,634 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L78-L84 | [
"def",
"calculate_pore_diameter",
"(",
"self",
")",
":",
"self",
".",
"pore_diameter",
",",
"self",
".",
"pore_closest_atom",
"=",
"pore_diameter",
"(",
"self",
".",
"elements",
",",
"self",
".",
"coordinates",
")",
"self",
".",
"properties",
"[",
"'pore_diameter'",
"]",
"=",
"{",
"'diameter'",
":",
"self",
".",
"pore_diameter",
",",
"'atom'",
":",
"int",
"(",
"self",
".",
"pore_closest_atom",
")",
",",
"}",
"return",
"self",
".",
"pore_diameter"
] |
Initiate the handshake . | def __send_hello ( self ) : _logger . debug ( "Saying hello: [%s]" , self ) self . __c . send ( nsq . config . protocol . MAGIC_IDENTIFIER ) | 9,635 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L137-L142 | [
"def",
"delete_blob",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"if",
"'container'",
"not",
"in",
"kwargs",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'A container must be specified'",
")",
"if",
"'blob'",
"not",
"in",
"kwargs",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'A blob must be specified'",
")",
"storageservice",
"=",
"_get_block_blob_service",
"(",
"kwargs",
")",
"storageservice",
".",
"delete_blob",
"(",
"kwargs",
"[",
"'container'",
"]",
",",
"kwargs",
"[",
"'blob'",
"]",
")",
"return",
"True"
] |
Send - loop . | def __sender ( self ) : # If we're ignoring the quit, the connections will have to be closed # by the server. while ( self . __ignore_quit is True or self . __nice_quit_ev . is_set ( ) is False ) and self . __force_quit_ev . is_set ( ) is False : # TODO(dustin): The quit-signals aren't being properly set after a producer # stop. # TODO(dustin): Consider breaking the loop if we haven't yet retried to # reconnect a couple of times. A connection will automatically be # reattempted. try : ( command , parts ) = self . __outgoing_q . get ( block = False ) except gevent . queue . Empty : gevent . sleep ( nsq . config . client . WRITE_THROTTLE_S ) else : _logger . debug ( "Dequeued outgoing command ((%d) remaining): " "[%s]" , self . __outgoing_q . qsize ( ) , self . __distill_command_name ( command ) ) self . __send_command_primitive ( command , parts ) self . __send_thread_ev . set ( ) | 9,636 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L479-L506 | [
"def",
"price_and_currency",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.Amount'",
")",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.CurrencyCode'",
")",
"if",
"price",
":",
"dprice",
"=",
"Decimal",
"(",
"price",
")",
"/",
"100",
"if",
"'JP'",
"not",
"in",
"self",
".",
"region",
"else",
"Decimal",
"(",
"price",
")",
"return",
"dprice",
",",
"currency",
"else",
":",
"return",
"None",
",",
"None"
] |
Receive - loop . | def __receiver ( self ) : # If we're ignoring the quit, the connections will have to be closed # by the server. while ( self . __ignore_quit is True or self . __nice_quit_ev . is_set ( ) is False ) and self . __force_quit_ev . is_set ( ) is False : # TODO(dustin): The quit-signals aren't being properly set after a producer # stop. # TODO(dustin): Consider breaking the loop if we haven't yet retried to # reconnect a couple of times. A connection will automatically be # reattempted. try : self . __read_frame ( ) except errno . EAGAIN : gevent . sleep ( nsq . config . client . READ_THROTTLE_S ) self . __receive_thread_ev . set ( ) | 9,637 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L508-L529 | [
"def",
"price_and_currency",
"(",
"self",
")",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.SalePrice.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.Amount'",
")",
"if",
"price",
":",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'Offers.Offer.OfferListing.Price.CurrencyCode'",
")",
"else",
":",
"price",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.Amount'",
")",
"currency",
"=",
"self",
".",
"_safe_get_element_text",
"(",
"'OfferSummary.LowestNewPrice.CurrencyCode'",
")",
"if",
"price",
":",
"dprice",
"=",
"Decimal",
"(",
"price",
")",
"/",
"100",
"if",
"'JP'",
"not",
"in",
"self",
".",
"region",
"else",
"Decimal",
"(",
"price",
")",
"return",
"dprice",
",",
"currency",
"else",
":",
"return",
"None",
",",
"None"
] |
Connect the server and maintain the connection . This shall not return until a connection has been determined to absolutely not be available . | def run ( self ) : while self . __nice_quit_ev . is_set ( ) is False : self . __connect ( ) _logger . info ( "Connection re-connect loop has terminated: %s" , self . __mc ) | 9,638 | https://github.com/dsoprea/NsqSpinner/blob/972237b8ddce737983bfed001fde52e5236be695/nsq/connection.py#L598-L607 | [
"def",
"IOR",
"(",
"classical_reg1",
",",
"classical_reg2",
")",
":",
"left",
",",
"right",
"=",
"unpack_reg_val_pair",
"(",
"classical_reg1",
",",
"classical_reg2",
")",
"return",
"ClassicalInclusiveOr",
"(",
"left",
",",
"right",
")"
] |
Serialize an object to disk using pickle protocol . | def save ( obj , filename , protocol = 4 ) : with open ( filename , 'wb' ) as f : pickle . dump ( obj , f , protocol = protocol ) | 9,639 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L20-L31 | [
"def",
"jtag_configure",
"(",
"self",
",",
"instr_regs",
"=",
"0",
",",
"data_bits",
"=",
"0",
")",
":",
"if",
"not",
"util",
".",
"is_natural",
"(",
"instr_regs",
")",
":",
"raise",
"ValueError",
"(",
"'IR value is not a natural number.'",
")",
"if",
"not",
"util",
".",
"is_natural",
"(",
"data_bits",
")",
":",
"raise",
"ValueError",
"(",
"'Data bits is not a natural number.'",
")",
"self",
".",
"_dll",
".",
"JLINKARM_ConfigJTAG",
"(",
"instr_regs",
",",
"data_bits",
")",
"return",
"None"
] |
Load a JSON object from the specified file . | def load_json ( filename , * * kwargs ) : with open ( filename , 'r' , encoding = 'utf-8' ) as f : return json . load ( f , * * kwargs ) | 9,640 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L34-L47 | [
"def",
"remover",
"(",
"self",
",",
"id_brand",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_brand",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Brand is invalid or was not informed.'",
")",
"url",
"=",
"'brand/'",
"+",
"str",
"(",
"id_brand",
")",
"+",
"'/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'DELETE'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] |
Save an object as a JSON file . | def save_json ( obj , filename , * * kwargs ) : with open ( filename , 'w' , encoding = 'utf-8' ) as f : json . dump ( obj , f , * * kwargs ) | 9,641 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L50-L61 | [
"def",
"remover",
"(",
"self",
",",
"id_brand",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_brand",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Brand is invalid or was not informed.'",
")",
"url",
"=",
"'brand/'",
"+",
"str",
"(",
"id_brand",
")",
"+",
"'/'",
"code",
",",
"xml",
"=",
"self",
".",
"submit",
"(",
"None",
",",
"'DELETE'",
",",
"url",
")",
"return",
"self",
".",
"response",
"(",
"code",
",",
"xml",
")"
] |
Load a text file as an array of lines . | def load_lines ( filename ) : with open ( filename , 'r' , encoding = 'utf-8' ) as f : return [ line . rstrip ( '\n' ) for line in f . readlines ( ) ] | 9,642 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L64-L76 | [
"def",
"set_USRdict",
"(",
"self",
",",
"USRdict",
"=",
"{",
"}",
")",
":",
"self",
".",
"_check_inputs",
"(",
"USRdict",
"=",
"USRdict",
")",
"self",
".",
"_USRdict",
"=",
"USRdict"
] |
Save an array of lines to a file . | def save_lines ( lines , filename ) : with open ( filename , 'w' , encoding = 'utf-8' ) as f : f . write ( '\n' . join ( lines ) ) | 9,643 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/io.py#L79-L89 | [
"def",
"message",
"(",
"self",
")",
":",
"return",
"{",
"'timestamp'",
":",
"time",
".",
"mktime",
"(",
"self",
".",
"timestamp",
".",
"timetuple",
"(",
")",
")",
"*",
"1e3",
"+",
"self",
".",
"timestamp",
".",
"microsecond",
"/",
"1e3",
",",
"'group'",
":",
"self",
".",
"group_pk",
",",
"'participant'",
":",
"None",
"if",
"not",
"self",
".",
"participant",
"else",
"self",
".",
"participant",
".",
"code",
",",
"'channel'",
":",
"self",
".",
"channel",
",",
"'value'",
":",
"self",
".",
"value",
"}"
] |
Adds a typed child object to the component . | def add ( self , child ) : if isinstance ( child , Component ) : self . add_child ( child ) else : raise ModelError ( 'Unsupported child element' ) | 9,644 | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/component.py#L1122-L1132 | [
"def",
"get_samples",
"(",
"self",
",",
"n",
")",
":",
"normalized_w",
"=",
"self",
".",
"weights",
"/",
"np",
".",
"sum",
"(",
"self",
".",
"weights",
")",
"get_rand_index",
"=",
"st",
".",
"rv_discrete",
"(",
"values",
"=",
"(",
"range",
"(",
"self",
".",
"N",
")",
",",
"normalized_w",
")",
")",
".",
"rvs",
"(",
"size",
"=",
"n",
")",
"samples",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"k",
"=",
"0",
"j",
"=",
"0",
"while",
"(",
"k",
"<",
"n",
")",
":",
"i",
"=",
"get_rand_index",
"[",
"j",
"]",
"j",
"=",
"j",
"+",
"1",
"if",
"(",
"j",
"==",
"n",
")",
":",
"get_rand_index",
"=",
"st",
".",
"rv_discrete",
"(",
"values",
"=",
"(",
"range",
"(",
"self",
".",
"N",
")",
",",
"normalized_w",
")",
")",
".",
"rvs",
"(",
"size",
"=",
"n",
")",
"j",
"=",
"0",
"v",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"loc",
"=",
"self",
".",
"points",
"[",
"i",
"]",
",",
"scale",
"=",
"self",
".",
"sigma",
"[",
"i",
"]",
")",
"if",
"(",
"v",
">",
"self",
".",
"max_limit",
"or",
"v",
"<",
"self",
".",
"min_limit",
")",
":",
"continue",
"else",
":",
"samples",
"[",
"k",
"]",
"=",
"v",
"k",
"=",
"k",
"+",
"1",
"if",
"(",
"k",
"==",
"n",
")",
":",
"break",
"return",
"samples"
] |
Writes peps to db . We can reverse to be able to look up peptides that have some amino acids missing at the N - terminal . This way we can still use the index . | def write_peps ( self , peps , reverse_seqs ) : if reverse_seqs : peps = [ ( x [ 0 ] [ : : - 1 ] , ) for x in peps ] cursor = self . get_cursor ( ) cursor . executemany ( 'INSERT INTO known_searchspace(seqs) VALUES (?)' , peps ) self . conn . commit ( ) | 9,645 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/lookups/sqlite/searchspace.py#L9-L19 | [
"def",
"folder_shared_message",
"(",
"self",
",",
"request",
",",
"user",
",",
"folder",
")",
":",
"messages",
".",
"success",
"(",
"request",
",",
"_",
"(",
"\"Folder {} is now shared with {}\"",
".",
"format",
"(",
"folder",
",",
"user",
")",
")",
")"
] |
A convenience method that allows you to send a well formatted http request to another service | def send_http_request ( self , app : str , service : str , version : str , method : str , entity : str , params : dict ) : host , port , node_id , service_type = self . _registry_client . resolve ( service , version , entity , HTTP ) url = 'http://{}:{}{}' . format ( host , port , params . pop ( 'path' ) ) http_keys = [ 'data' , 'headers' , 'cookies' , 'auth' , 'allow_redirects' , 'compress' , 'chunked' ] kwargs = { k : params [ k ] for k in http_keys if k in params } query_params = params . pop ( 'params' , { } ) if app is not None : query_params [ 'app' ] = app query_params [ 'version' ] = version query_params [ 'service' ] = service response = yield from aiohttp . request ( method , url , params = query_params , * * kwargs ) return response | 9,646 | https://github.com/quikmile/trellio/blob/e8b050077562acf32805fcbb9c0c162248a23c62/trellio/bus.py#L31-L51 | [
"def",
"_is_cow",
"(",
"path",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"return",
"'C'",
"not",
"in",
"__salt__",
"[",
"'file.lsattr'",
"]",
"(",
"dirname",
")",
"[",
"path",
"]"
] |
Install an except hook that will show the crash report dialog when an unhandled exception has occured . | def install_except_hook ( except_hook = _hooks . except_hook ) : if not _backends : raise ValueError ( 'no backends found, you must at least install one ' 'backend before calling this function' ) global _except_hook _except_hook = _hooks . QtExceptHook ( except_hook ) | 9,647 | https://github.com/ColinDuquesnoy/QCrash/blob/775e1b15764e2041a8f9a08bea938e4d6ce817c7/qcrash/api.py#L36-L49 | [
"def",
"generate_http_manifest",
"(",
"self",
")",
":",
"base_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"translate_path",
"(",
"self",
".",
"path",
")",
")",
"self",
".",
"dataset",
"=",
"dtoolcore",
".",
"DataSet",
".",
"from_uri",
"(",
"base_path",
")",
"admin_metadata_fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base_path",
",",
"\".dtool\"",
",",
"\"dtool\"",
")",
"with",
"open",
"(",
"admin_metadata_fpath",
")",
"as",
"fh",
":",
"admin_metadata",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"http_manifest",
"=",
"{",
"\"admin_metadata\"",
":",
"admin_metadata",
",",
"\"manifest_url\"",
":",
"self",
".",
"generate_url",
"(",
"\".dtool/manifest.json\"",
")",
",",
"\"readme_url\"",
":",
"self",
".",
"generate_url",
"(",
"\"README.yml\"",
")",
",",
"\"overlays\"",
":",
"self",
".",
"generate_overlay_urls",
"(",
")",
",",
"\"item_urls\"",
":",
"self",
".",
"generate_item_urls",
"(",
")",
"}",
"return",
"bytes",
"(",
"json",
".",
"dumps",
"(",
"http_manifest",
")",
",",
"\"utf-8\"",
")"
] |
Show the issue report dialog manually . | def show_report_dialog ( window_title = 'Report an issue...' , window_icon = None , traceback = None , issue_title = '' , issue_description = '' , parent = None , modal = None , include_log = True , include_sys_info = True ) : if not _backends : raise ValueError ( 'no backends found, you must at least install one ' 'backend before calling this function' ) from . _dialogs . report import DlgReport dlg = DlgReport ( _backends , window_title = window_title , window_icon = window_icon , traceback = traceback , issue_title = issue_title , issue_description = issue_description , parent = parent , include_log = include_log , include_sys_info = include_sys_info ) if modal : dlg . show ( ) return dlg else : dlg . exec_ ( ) | 9,648 | https://github.com/ColinDuquesnoy/QCrash/blob/775e1b15764e2041a8f9a08bea938e4d6ce817c7/qcrash/api.py#L64-L93 | [
"def",
"reconnect_redis",
"(",
"self",
")",
":",
"if",
"self",
".",
"shared_client",
"and",
"Storage",
".",
"storage",
":",
"return",
"Storage",
".",
"storage",
"storage",
"=",
"Redis",
"(",
"port",
"=",
"self",
".",
"context",
".",
"config",
".",
"REDIS_RESULT_STORAGE_SERVER_PORT",
",",
"host",
"=",
"self",
".",
"context",
".",
"config",
".",
"REDIS_RESULT_STORAGE_SERVER_HOST",
",",
"db",
"=",
"self",
".",
"context",
".",
"config",
".",
"REDIS_RESULT_STORAGE_SERVER_DB",
",",
"password",
"=",
"self",
".",
"context",
".",
"config",
".",
"REDIS_RESULT_STORAGE_SERVER_PASSWORD",
")",
"if",
"self",
".",
"shared_client",
":",
"Storage",
".",
"storage",
"=",
"storage",
"return",
"storage"
] |
Appends a Middleware to the route which is to be executed before the route runs | def middleware ( self , args ) : if self . url [ ( len ( self . url ) - 1 ) ] == ( self . url_ , self . controller , dict ( method = self . method , request_type = self . request_type , middleware = None ) ) : self . url . pop ( ) self . url . append ( ( self . url_ , self . controller , dict ( method = self . method , request_type = self . request_type , middleware = args ) ) ) return self | 9,649 | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/route.py#L27-L34 | [
"def",
"login_with_token",
"(",
"refresh_token",
",",
"team",
"=",
"None",
")",
":",
"# Get an access token and a new refresh token.",
"_check_team_id",
"(",
"team",
")",
"auth",
"=",
"_update_auth",
"(",
"team",
",",
"refresh_token",
")",
"url",
"=",
"get_registry_url",
"(",
"team",
")",
"contents",
"=",
"_load_auth",
"(",
")",
"contents",
"[",
"url",
"]",
"=",
"auth",
"_save_auth",
"(",
"contents",
")",
"_clear_session",
"(",
"team",
")"
] |
Gets the Controller and adds the route controller and method to the url list for GET request | def get ( self , url , controller ) : self . request_type = 'GET' controller_class , controller_method = self . __return_controller__ ( controller ) self . controller = controller_class self . method = controller_method self . url_ = url self . url . append ( ( url , controller_class , dict ( method = controller_method , request_type = self . request_type , middleware = None ) ) ) return self | 9,650 | https://github.com/moluwole/Bast/blob/eecf55ae72e6f24af7c101549be0422cd2c1c95a/bast/route.py#L62-L75 | [
"def",
"save",
"(",
"self",
",",
"ts",
")",
":",
"with",
"open",
"(",
"self",
",",
"'w'",
")",
"as",
"f",
":",
"Timestamp",
".",
"wrap",
"(",
"ts",
")",
".",
"dump",
"(",
"f",
")"
] |
Get a byte array representing the value | def to_bytes ( value ) : if isinstance ( value , unicode ) : return value . encode ( 'utf8' ) elif not isinstance ( value , str ) : return str ( value ) return value | 9,651 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/utilities.py#L14-L20 | [
"def",
"remove_stale_javascripts",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing stale javascripts ...\"",
")",
"for",
"js",
"in",
"JAVASCRIPTS_TO_REMOVE",
":",
"logger",
".",
"info",
"(",
"\"Unregistering JS %s\"",
"%",
"js",
")",
"portal",
".",
"portal_javascripts",
".",
"unregisterResource",
"(",
"js",
")"
] |
Generate a table for cli output | def table_repr ( columns , rows , data , padding = 2 ) : padding = ' ' * padding column_lengths = [ len ( column ) for column in columns ] for row in rows : for i , column in enumerate ( columns ) : item = str ( data [ row ] [ column ] ) column_lengths [ i ] = max ( len ( item ) , column_lengths [ i ] ) max_row_length = max ( len ( row ) for row in rows ) if len ( rows ) else 0 table_row = ' ' * max_row_length for i , column in enumerate ( columns ) : table_row += padding + column . rjust ( column_lengths [ i ] ) table_rows = [ table_row ] for row in rows : table_row = row . rjust ( max_row_length ) for i , column in enumerate ( columns ) : item = str ( data [ row ] [ column ] ) table_row += padding + item . rjust ( column_lengths [ i ] ) table_rows . append ( table_row ) return '\n' . join ( table_rows ) | 9,652 | https://github.com/chriso/gauged/blob/cda3bba2f3e92ce2fb4aa92132dcc0e689bf7976/gauged/utilities.py#L36-L55 | [
"def",
"get_placement_solver",
"(",
"service_instance",
")",
":",
"stub",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_new_service_instance_stub",
"(",
"service_instance",
",",
"ns",
"=",
"'pbm/2.0'",
",",
"path",
"=",
"'/pbm/sdk'",
")",
"pbm_si",
"=",
"pbm",
".",
"ServiceInstance",
"(",
"'ServiceInstance'",
",",
"stub",
")",
"try",
":",
"profile_manager",
"=",
"pbm_si",
".",
"RetrieveContent",
"(",
")",
".",
"placementSolver",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"return",
"profile_manager"
] |
Runs through fasta file and returns proteins accession nrs sequences and evidence levels for storage in lookup DB . Duplicate accessions in fasta are accepted and removed by keeping only the last one . | def get_proteins_for_db ( fastafn ) : objects = { } for record in parse_fasta ( fastafn ) : objects [ parse_protein_identifier ( record ) ] = record return ( ( ( acc , ) for acc in list ( objects ) ) , ( ( acc , str ( record . seq ) ) for acc , record in objects . items ( ) ) , ( ( acc , get_uniprot_evidence_level ( record . description ) ) for acc , record in objects . items ( ) ) ) | 9,653 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/fasta.py#L4-L15 | [
"def",
"max_texture_limit",
"(",
"self",
")",
":",
"max_unit_array",
"=",
"(",
"gl",
".",
"GLint",
"*",
"1",
")",
"(",
")",
"gl",
".",
"glGetIntegerv",
"(",
"gl",
".",
"GL_MAX_TEXTURE_IMAGE_UNITS",
",",
"max_unit_array",
")",
"return",
"max_unit_array",
"[",
"0",
"]"
] |
Returns uniprot protein existence evidence level for a fasta header . Evidence levels are 1 - 5 but we return 5 - x since sorting still demands that higher is better . | def get_uniprot_evidence_level ( header ) : header = header . split ( ) for item in header : item = item . split ( '=' ) try : if item [ 0 ] == 'PE' : return 5 - int ( item [ 1 ] ) except IndexError : continue return - 1 | 9,654 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/fasta.py#L119-L131 | [
"def",
"reset_subscriptions",
"(",
"self",
",",
"accounts",
"=",
"[",
"]",
",",
"markets",
"=",
"[",
"]",
",",
"objects",
"=",
"[",
"]",
")",
":",
"self",
".",
"websocket",
".",
"reset_subscriptions",
"(",
"accounts",
",",
"self",
".",
"get_market_ids",
"(",
"markets",
")",
",",
"objects",
")"
] |
Run our loop and any defined hooks ... | def run ( self ) : self . pre_run ( ) first = True while self . runnable : self . pre_call_message ( ) if first : self . pre_first_call_message ( ) message , payload = self . listener . get ( ) getattr ( self , message ) ( payload ) if first : first = False self . post_first_call_message ( ) self . post_call_message ( ) self . post_run ( ) | 9,655 | https://github.com/jdodds/feather/blob/92a9426e692b33c7fddf758df8dbc99a9a1ba8ef/feather/plugin.py#L70-L90 | [
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
Calculate an array of multiplicities and corresponding coincidence IDs | def count_multiplicities ( times , tmax = 20 ) : n = times . shape [ 0 ] mtp = np . ones ( n , dtype = '<i4' ) # multiplicities cid = np . zeros ( n , '<i4' ) # coincidence id idx0 = 0 _mtp = 1 _cid = 0 t0 = times [ idx0 ] for i in range ( 1 , n ) : dt = times [ i ] - t0 if dt > tmax : mtp [ idx0 : i ] = _mtp cid [ idx0 : i ] = _cid _mtp = 0 _cid += 1 idx0 = i t0 = times [ i ] _mtp += 1 if i == n - 1 : mtp [ idx0 : ] = _mtp cid [ idx0 : ] = _cid break return mtp , cid | 9,656 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/hits.py#L28-L68 | [
"def",
"remove_group",
"(",
"self",
",",
"groupname",
")",
":",
"# implementation based on",
"# https://docs.atlassian.com/jira/REST/ondemand/#d2e5173",
"url",
"=",
"self",
".",
"_options",
"[",
"'server'",
"]",
"+",
"'/rest/api/latest/group'",
"x",
"=",
"{",
"'groupname'",
":",
"groupname",
"}",
"self",
".",
"_session",
".",
"delete",
"(",
"url",
",",
"params",
"=",
"x",
")",
"return",
"True"
] |
Build machine from list of lines . | def build_machine ( lines ) : if lines == [ ] : raise SyntaxError ( 'Empty file' ) else : machine = Machine ( lines [ 0 ] . split ( ) ) for line in lines [ 1 : ] : if line . strip ( ) != '' : machine . add_state ( line ) machine . check ( ) return machine | 9,657 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L175-L185 | [
"def",
"column",
"(",
"self",
",",
"column",
",",
"option",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"config",
"=",
"False",
"if",
"option",
"==",
"'type'",
":",
"return",
"self",
".",
"_column_types",
"[",
"column",
"]",
"elif",
"'type'",
"in",
"kw",
":",
"config",
"=",
"True",
"self",
".",
"_column_types",
"[",
"column",
"]",
"=",
"kw",
".",
"pop",
"(",
"'type'",
")",
"if",
"kw",
":",
"self",
".",
"_visual_drag",
".",
"column",
"(",
"ttk",
".",
"Treeview",
".",
"column",
"(",
"self",
",",
"column",
",",
"'id'",
")",
",",
"option",
",",
"*",
"*",
"kw",
")",
"if",
"kw",
"or",
"option",
":",
"return",
"ttk",
".",
"Treeview",
".",
"column",
"(",
"self",
",",
"column",
",",
"option",
",",
"*",
"*",
"kw",
")",
"elif",
"not",
"config",
":",
"res",
"=",
"ttk",
".",
"Treeview",
".",
"column",
"(",
"self",
",",
"column",
",",
"option",
",",
"*",
"*",
"kw",
")",
"res",
"[",
"'type'",
"]",
"=",
"self",
".",
"_column_types",
"[",
"column",
"]",
"return",
"res"
] |
Add state and rules to machine . | def add_state ( self , string ) : parsed_string = string . split ( ) if len ( parsed_string ) > 0 : state , rules = parsed_string [ 0 ] , parsed_string [ 1 : ] if len ( rules ) != len ( self . alphabet ) : raise SyntaxError ( 'Wrong count of rules ({cur}/{exp}): {string}' . format ( cur = len ( rules ) , exp = len ( self . alphabet ) , string = string ) ) if state in self . states or state == self . TERM_STATE : raise SyntaxError ( 'Double definition of state: ' + state ) else : self . states [ state ] = [ ] for rule in rules : try : self . _add_rule ( state , rule ) except SyntaxError as err : self . states . pop ( state ) raise err | 9,658 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L60-L81 | [
"def",
"_log_effective_mass_data",
"(",
"data",
",",
"is_spin_polarized",
",",
"mass_type",
"=",
"'m_e'",
")",
":",
"s",
"=",
"' ({})'",
".",
"format",
"(",
"data",
"[",
"'spin'",
"]",
".",
"name",
")",
"if",
"is_spin_polarized",
"else",
"''",
"# add 1 to band id to be consistent with VASP",
"band_str",
"=",
"'band {}{}'",
".",
"format",
"(",
"data",
"[",
"'band_id'",
"]",
"+",
"1",
",",
"s",
")",
"start_kpoint",
"=",
"data",
"[",
"'start_kpoint'",
"]",
"end_kpoint",
"=",
"data",
"[",
"'end_kpoint'",
"]",
"eff_mass",
"=",
"data",
"[",
"'effective_mass'",
"]",
"kpoint_str",
"=",
"kpt_str",
".",
"format",
"(",
"k",
"=",
"start_kpoint",
".",
"frac_coords",
")",
"if",
"start_kpoint",
".",
"label",
":",
"kpoint_str",
"+=",
"' ({})'",
".",
"format",
"(",
"start_kpoint",
".",
"label",
")",
"kpoint_str",
"+=",
"' -> '",
"kpoint_str",
"+=",
"kpt_str",
".",
"format",
"(",
"k",
"=",
"end_kpoint",
".",
"frac_coords",
")",
"if",
"end_kpoint",
".",
"label",
":",
"kpoint_str",
"+=",
"' ({})'",
".",
"format",
"(",
"end_kpoint",
".",
"label",
")",
"logging",
".",
"info",
"(",
"' {}: {:.3f} | {} | {}'",
".",
"format",
"(",
"mass_type",
",",
"eff_mass",
",",
"band_str",
",",
"kpoint_str",
")",
")"
] |
Check semantic rules . | def check ( self ) : has_term = False if self . START_STATE not in self . states : raise SyntaxError ( 'Undefined start rule' ) for state in self . states : for rule in self . states [ state ] : if rule is not None : if rule [ 2 ] == self . TERM_STATE : has_term = True elif rule [ 2 ] not in self . states : raise SyntaxError ( 'Unexpected state: ' + rule [ 2 ] ) if not has_term : raise SyntaxError ( 'Missed terminate state' ) | 9,659 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L83-L99 | [
"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"
] |
Init system values . | def init_tape ( self , string ) : for char in string : if char not in self . alphabet and not char . isspace ( ) and char != self . EMPTY_SYMBOL : raise RuntimeError ( 'Invalid symbol: "' + char + '"' ) self . check ( ) self . state = self . START_STATE self . head = 0 self . tape = { } for i in range ( len ( string ) ) : symbol = string [ i ] if not string [ i ] . isspace ( ) else self . EMPTY_SYMBOL self . tape [ i ] = symbol | 9,660 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L101-L114 | [
"def",
"requires_open_handle",
"(",
"method",
")",
":",
"# pylint: disable=invalid-name",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"wrapper_requiring_open_handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"The wrapper to be returned.\"\"\"",
"if",
"self",
".",
"is_closed",
"(",
")",
":",
"raise",
"usb_exceptions",
".",
"HandleClosedError",
"(",
")",
"return",
"method",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper_requiring_open_handle"
] |
Get content of tape . | def get_tape ( self ) : result = '' for i in range ( min ( self . tape ) , max ( self . tape ) + 1 ) : symbol = self . tape [ i ] if self . tape [ i ] != self . EMPTY_SYMBOL else ' ' result += symbol # Remove unnecessary empty symbols on tape return result . strip ( ) | 9,661 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L116-L123 | [
"def",
"select_models",
"(",
"clas",
",",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'columns'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"don't pass 'columns' to select_models\"",
")",
"return",
"(",
"set_options",
"(",
"pool_or_cursor",
",",
"clas",
"(",
"*",
"row",
")",
")",
"for",
"row",
"in",
"clas",
".",
"select",
"(",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
")"
] |
One step of execution . | def execute_once ( self ) : symbol = self . tape . get ( self . head , self . EMPTY_SYMBOL ) index = self . alphabet . index ( symbol ) rule = self . states [ self . state ] [ index ] if rule is None : raise RuntimeError ( 'Unexpected symbol: ' + symbol ) self . tape [ self . head ] = rule [ 0 ] if rule [ 1 ] == 'L' : self . head -= 1 elif rule [ 1 ] == 'R' : self . head += 1 self . state = rule [ 2 ] | 9,662 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L125-L142 | [
"def",
"sync",
"(",
"self",
",",
"vault_client",
")",
":",
"if",
"self",
".",
"present",
":",
"if",
"not",
"self",
".",
"existing",
":",
"LOG",
".",
"info",
"(",
"\"Mounting %s backend on %s\"",
",",
"self",
".",
"backend",
",",
"self",
".",
"path",
")",
"self",
".",
"actually_mount",
"(",
"vault_client",
")",
"else",
":",
"LOG",
".",
"info",
"(",
"\"%s backend already mounted on %s\"",
",",
"self",
".",
"backend",
",",
"self",
".",
"path",
")",
"else",
":",
"if",
"self",
".",
"existing",
":",
"LOG",
".",
"info",
"(",
"\"Unmounting %s backend on %s\"",
",",
"self",
".",
"backend",
",",
"self",
".",
"path",
")",
"self",
".",
"unmount",
"(",
"vault_client",
")",
"else",
":",
"LOG",
".",
"info",
"(",
"\"%s backend already unmounted on %s\"",
",",
"self",
".",
"backend",
",",
"self",
".",
"path",
")",
"if",
"self",
".",
"present",
"and",
"vault_client",
".",
"version",
":",
"self",
".",
"sync_tunables",
"(",
"vault_client",
")"
] |
Return python code for create and execute machine . | def compile ( self ) : result = TEMPLATE result += 'machine = Machine(' + repr ( self . alphabet ) + ')\n' for state in self . states : repr_state = state [ 0 ] for rule in self . states [ state ] : repr_state += ' ' + ( ',' . join ( rule ) if rule is not None else '-' ) result += ( "machine.add_state({repr_state})\n" . format ( repr_state = repr ( repr_state ) ) ) result += "for line in stdin:\n" result += " print(machine.execute(line))" return result | 9,663 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/turing.py#L159-L173 | [
"def",
"ticker",
"(",
"self",
",",
"currency",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"}",
"params",
".",
"update",
"(",
"kwargs",
")",
"# see https://github.com/barnumbirr/coinmarketcap/pull/28",
"if",
"currency",
":",
"currency",
"=",
"str",
"(",
"currency",
")",
"+",
"'/'",
"response",
"=",
"self",
".",
"__request",
"(",
"'ticker/'",
"+",
"currency",
",",
"params",
")",
"return",
"response"
] |
Check if all required services are provided | def get_missing_services ( self , services ) : required_services = set ( services ) provided_services = set ( self . _services . keys ( ) ) missing_services = required_services . difference ( provided_services ) return sorted ( missing_services ) | 9,664 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L72-L85 | [
"def",
"value_from_object",
"(",
"self",
",",
"obj",
")",
":",
"try",
":",
"# not using self.attname, access the descriptor instead.",
"placeholder",
"=",
"getattr",
"(",
"obj",
",",
"self",
".",
"name",
")",
"except",
"Placeholder",
".",
"DoesNotExist",
":",
"return",
"None",
"# Still allow ModelForm / admin to open and create a new Placeholder if the table was truncated.",
"return",
"placeholder",
".",
"id",
"if",
"placeholder",
"else",
"None"
] |
Activate the pump and let the flow go . | def _drain ( self , cycles = None ) : log . info ( "Now draining..." ) if not cycles : log . info ( "No cycle count, the pipeline may be drained forever." ) if self . calibration : log . info ( "Setting up the detector calibration." ) for module in self . modules : module . detector = self . calibration . get_detector ( ) try : while not self . _stop : cycle_start = timer ( ) cycle_start_cpu = process_time ( ) log . debug ( "Pumping blob #{0}" . format ( self . _cycle_count ) ) self . blob = Blob ( ) for module in self . modules : if self . blob is None : log . debug ( "Skipping {0}, due to empty blob." . format ( module . name ) ) continue if module . only_if and not module . only_if . issubset ( set ( self . blob . keys ( ) ) ) : log . debug ( "Skipping {0}, due to missing required key" "'{1}'." . format ( module . name , module . only_if ) ) continue if ( self . _cycle_count + 1 ) % module . every != 0 : log . debug ( "Skipping {0} (every {1} iterations)." . format ( module . name , module . every ) ) continue if module . blob_keys is not None : blob_to_send = Blob ( { k : self . blob [ k ] for k in module . blob_keys if k in self . blob } ) else : blob_to_send = self . blob log . debug ( "Processing {0} " . format ( module . name ) ) start = timer ( ) start_cpu = process_time ( ) new_blob = module ( blob_to_send ) if self . timeit or module . timeit : self . _timeit [ module ] [ 'process' ] . append ( timer ( ) - start ) self . _timeit [ module ] [ 'process_cpu' ] . append ( process_time ( ) - start_cpu ) if module . blob_keys is not None : if new_blob is not None : for key in new_blob . keys ( ) : self . blob [ key ] = new_blob [ key ] else : self . blob = new_blob self . _timeit [ 'cycles' ] . append ( timer ( ) - cycle_start ) self . _timeit [ 'cycles_cpu' ] . append ( process_time ( ) - cycle_start_cpu ) self . _cycle_count += 1 if cycles and self . _cycle_count >= cycles : raise StopIteration except StopIteration : log . info ( "Nothing left to pump through." ) return self . finish ( ) | 9,665 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L258-L344 | [
"def",
"is_after",
"(",
"self",
",",
"other",
")",
":",
"any_timestamp_greater",
"=",
"False",
"for",
"replica_id",
",",
"other_timestamp",
"in",
"other",
".",
"entry_set",
"(",
")",
":",
"local_timestamp",
"=",
"self",
".",
"_replica_timestamps",
".",
"get",
"(",
"replica_id",
")",
"if",
"local_timestamp",
"is",
"None",
"or",
"local_timestamp",
"<",
"other_timestamp",
":",
"return",
"False",
"elif",
"local_timestamp",
">",
"other_timestamp",
":",
"any_timestamp_greater",
"=",
"True",
"# there is at least one local timestamp greater or local vector clock has additional timestamps",
"return",
"any_timestamp_greater",
"or",
"other",
".",
"size",
"(",
")",
"<",
"self",
".",
"size",
"(",
")"
] |
Final comparison of provided and required modules | def _check_service_requirements ( self ) : missing = self . services . get_missing_services ( self . required_services . keys ( ) ) if missing : self . log . critical ( "Following services are required and missing: {}" . format ( ', ' . join ( missing ) ) ) return False return True | 9,666 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L346-L358 | [
"def",
"normalize_filename",
"(",
"filename",
")",
":",
"# if the url pointed to a directory then just replace all the special chars",
"filename",
"=",
"re",
".",
"sub",
"(",
"\"/|\\\\|;|:|\\?|=\"",
",",
"\"_\"",
",",
"filename",
")",
"if",
"len",
"(",
"filename",
")",
">",
"150",
":",
"prefix",
"=",
"hashlib",
".",
"md5",
"(",
"filename",
")",
".",
"hexdigest",
"(",
")",
"filename",
"=",
"prefix",
"+",
"filename",
"[",
"-",
"140",
":",
"]",
"return",
"filename"
] |
Execute _drain while trapping KeyboardInterrupt | def drain ( self , cycles = None ) : if not self . _check_service_requirements ( ) : self . init_timer . stop ( ) return self . finish ( ) if self . anybar : self . anybar . change ( "orange" ) self . init_timer . stop ( ) log . info ( "Trapping CTRL+C and starting to drain." ) signal . signal ( signal . SIGINT , self . _handle_ctrl_c ) with ignored ( KeyboardInterrupt ) : return self . _drain ( cycles ) | 9,667 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L360-L371 | [
"def",
"AddFile",
"(",
"self",
",",
"fd",
")",
":",
"hashes",
"=",
"self",
".",
"_HashFile",
"(",
"fd",
")",
"# The empty file is very common, we don't keep the back references for it",
"# in the DB since it just takes up too much space.",
"empty_hash",
"=",
"(",
"\"e3b0c44298fc1c149afbf4c8996fb924\"",
"\"27ae41e4649b934ca495991b7852b855\"",
")",
"if",
"hashes",
".",
"sha256",
"==",
"empty_hash",
":",
"return",
"# Update the hashes field now that we have calculated them all.",
"fd",
".",
"Set",
"(",
"fd",
".",
"Schema",
".",
"HASH",
",",
"hashes",
")",
"fd",
".",
"Flush",
"(",
")",
"# sha256 is the canonical location.",
"canonical_urn",
"=",
"self",
".",
"PATH",
".",
"Add",
"(",
"\"generic/sha256\"",
")",
".",
"Add",
"(",
"str",
"(",
"hashes",
".",
"sha256",
")",
")",
"if",
"not",
"list",
"(",
"aff4",
".",
"FACTORY",
".",
"Stat",
"(",
"[",
"canonical_urn",
"]",
")",
")",
":",
"aff4",
".",
"FACTORY",
".",
"Copy",
"(",
"fd",
".",
"urn",
",",
"canonical_urn",
")",
"# Remove the STAT entry, it makes no sense to copy it between clients.",
"with",
"aff4",
".",
"FACTORY",
".",
"Open",
"(",
"canonical_urn",
",",
"mode",
"=",
"\"rw\"",
",",
"token",
"=",
"self",
".",
"token",
")",
"as",
"new_fd",
":",
"new_fd",
".",
"Set",
"(",
"new_fd",
".",
"Schema",
".",
"STAT",
"(",
"None",
")",
")",
"self",
".",
"_AddToIndex",
"(",
"canonical_urn",
",",
"fd",
".",
"urn",
")",
"for",
"hash_type",
",",
"hash_digest",
"in",
"hashes",
".",
"ListSetFields",
"(",
")",
":",
"# Determine fingerprint type.",
"hash_type",
"=",
"hash_type",
".",
"name",
"# No need to create a symlink for sha256, it's the canonical location.",
"if",
"hash_type",
"==",
"\"sha256\"",
":",
"continue",
"hash_digest",
"=",
"str",
"(",
"hash_digest",
")",
"fingerprint_type",
"=",
"\"generic\"",
"if",
"hash_type",
".",
"startswith",
"(",
"\"pecoff_\"",
")",
":",
"fingerprint_type",
"=",
"\"pecoff\"",
"hash_type",
"=",
"hash_type",
"[",
"len",
"(",
"\"pecoff_\"",
")",
":",
"]",
"if",
"hash_type",
"not",
"in",
"self",
".",
"HASH_TYPES",
"[",
"fingerprint_type",
"]",
":",
"continue",
"file_store_urn",
"=",
"self",
".",
"PATH",
".",
"Add",
"(",
"fingerprint_type",
")",
".",
"Add",
"(",
"hash_type",
")",
".",
"Add",
"(",
"hash_digest",
")",
"with",
"aff4",
".",
"FACTORY",
".",
"Create",
"(",
"file_store_urn",
",",
"aff4",
".",
"AFF4Symlink",
",",
"token",
"=",
"self",
".",
"token",
")",
"as",
"symlink",
":",
"symlink",
".",
"Set",
"(",
"symlink",
".",
"Schema",
".",
"SYMLINK_TARGET",
",",
"canonical_urn",
")",
"# We do not want to be externally written here.",
"return",
"None"
] |
Handle the keyboard interrupts . | def _handle_ctrl_c ( self , * args ) : if self . anybar : self . anybar . change ( "exclamation" ) if self . _stop : print ( "\nForced shutdown..." ) raise SystemExit if not self . _stop : hline = 42 * '=' print ( '\n' + hline + "\nGot CTRL+C, waiting for current cycle...\n" "Press CTRL+C again if you're in hurry!\n" + hline ) self . _stop = True | 9,668 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L397-L410 | [
"def",
"rowcol_to_a1",
"(",
"row",
",",
"col",
")",
":",
"row",
"=",
"int",
"(",
"row",
")",
"col",
"=",
"int",
"(",
"col",
")",
"if",
"row",
"<",
"1",
"or",
"col",
"<",
"1",
":",
"raise",
"IncorrectCellLabel",
"(",
"'(%s, %s)'",
"%",
"(",
"row",
",",
"col",
")",
")",
"div",
"=",
"col",
"column_label",
"=",
"''",
"while",
"div",
":",
"(",
"div",
",",
"mod",
")",
"=",
"divmod",
"(",
"div",
",",
"26",
")",
"if",
"mod",
"==",
"0",
":",
"mod",
"=",
"26",
"div",
"-=",
"1",
"column_label",
"=",
"chr",
"(",
"mod",
"+",
"MAGIC_NUMBER",
")",
"+",
"column_label",
"label",
"=",
"'%s%s'",
"%",
"(",
"column_label",
",",
"row",
")",
"return",
"label"
] |
Return the value of the requested parameter or default if None . | def get ( self , name , default = None ) : value = self . parameters . get ( name ) self . _processed_parameters . append ( name ) if value is None : return default return value | 9,669 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L531-L537 | [
"def",
"cublasZgemm",
"(",
"handle",
",",
"transa",
",",
"transb",
",",
"m",
",",
"n",
",",
"k",
",",
"alpha",
",",
"A",
",",
"lda",
",",
"B",
",",
"ldb",
",",
"beta",
",",
"C",
",",
"ldc",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasZgemm_v2",
"(",
"handle",
",",
"_CUBLAS_OP",
"[",
"transa",
"]",
",",
"_CUBLAS_OP",
"[",
"transb",
"]",
",",
"m",
",",
"n",
",",
"k",
",",
"ctypes",
".",
"byref",
"(",
"cuda",
".",
"cuDoubleComplex",
"(",
"alpha",
".",
"real",
",",
"alpha",
".",
"imag",
")",
")",
",",
"int",
"(",
"A",
")",
",",
"lda",
",",
"int",
"(",
"B",
")",
",",
"ldb",
",",
"ctypes",
".",
"byref",
"(",
"cuda",
".",
"cuDoubleComplex",
"(",
"beta",
".",
"real",
",",
"beta",
".",
"imag",
")",
")",
",",
"int",
"(",
"C",
")",
",",
"ldc",
")",
"cublasCheckStatus",
"(",
"status",
")"
] |
Return the value of the requested parameter or raise an error . | def require ( self , name ) : value = self . get ( name ) if value is None : raise TypeError ( "{0} requires the parameter '{1}'." . format ( self . __class__ , name ) ) return value | 9,670 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L539-L548 | [
"def",
"read_ndk_event",
"(",
"self",
",",
"raw_data",
",",
"id0",
")",
":",
"gcmt",
"=",
"GCMTEvent",
"(",
")",
"# Get hypocentre",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
".",
"hypocentre",
"=",
"self",
".",
"_read_hypocentre_from_ndk_string",
"(",
"ndkstring",
")",
"# GCMT metadata",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"+",
"1",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
"=",
"self",
".",
"_get_metadata_from_ndk_string",
"(",
"gcmt",
",",
"ndkstring",
")",
"# Get Centroid",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"+",
"2",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
".",
"centroid",
"=",
"self",
".",
"_read_centroid_from_ndk_string",
"(",
"ndkstring",
",",
"gcmt",
".",
"hypocentre",
")",
"# Get Moment Tensor",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"+",
"3",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
".",
"moment_tensor",
"=",
"self",
".",
"_get_moment_tensor_from_ndk_string",
"(",
"ndkstring",
")",
"# Get principal axes",
"ndkstring",
"=",
"raw_data",
"[",
"id0",
"+",
"4",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
"gcmt",
".",
"principal_axes",
"=",
"self",
".",
"_get_principal_axes_from_ndk_string",
"(",
"ndkstring",
"[",
"3",
":",
"48",
"]",
",",
"exponent",
"=",
"gcmt",
".",
"moment_tensor",
".",
"exponent",
")",
"# Get Nodal Planes",
"gcmt",
".",
"nodal_planes",
"=",
"self",
".",
"_get_nodal_planes_from_ndk_string",
"(",
"ndkstring",
"[",
"57",
":",
"]",
")",
"# Get Moment and Magnitude",
"gcmt",
".",
"moment",
",",
"gcmt",
".",
"version",
",",
"gcmt",
".",
"magnitude",
"=",
"self",
".",
"_get_moment_from_ndk_string",
"(",
"ndkstring",
",",
"gcmt",
".",
"moment_tensor",
".",
"exponent",
")",
"return",
"gcmt"
] |
Check if any of the parameters passed in are ignored | def _check_unused_parameters ( self ) : all_params = set ( self . parameters . keys ( ) ) processed_params = set ( self . _processed_parameters ) unused_params = all_params - processed_params - RESERVED_ARGS if unused_params : self . log . warning ( "The following parameters were ignored: {}" . format ( ', ' . join ( sorted ( unused_params ) ) ) ) | 9,671 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L565-L576 | [
"def",
"trace_max_buffer_capacity",
"(",
"self",
")",
":",
"cmd",
"=",
"enums",
".",
"JLinkTraceCommand",
".",
"GET_MAX_CAPACITY",
"data",
"=",
"ctypes",
".",
"c_uint32",
"(",
"0",
")",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_TRACE_Control",
"(",
"cmd",
",",
"ctypes",
".",
"byref",
"(",
"data",
")",
")",
"if",
"(",
"res",
"==",
"1",
")",
":",
"raise",
"errors",
".",
"JLinkException",
"(",
"'Failed to get max trace buffer size.'",
")",
"return",
"data",
".",
"value"
] |
Open the file with filename | def open_file ( self , filename ) : try : if filename . endswith ( '.gz' ) : self . blob_file = gzip . open ( filename , 'rb' ) else : self . blob_file = open ( filename , 'rb' ) except TypeError : log . error ( "Please specify a valid filename." ) raise SystemExit except IOError as error_message : log . error ( error_message ) raise SystemExit | 9,672 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/core.py#L599-L611 | [
"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"
] |
Parse any time string . Use a custom timezone matching if the original matching does not pull one out . | def parse ( cls , date_string ) : try : date = dateparser . parse ( date_string ) if date . tzinfo is None : date = dateparser . parse ( date_string , tzinfos = cls . tzd ) return date except Exception : raise ValueError ( "Could not parse date string!" ) | 9,673 | https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/utils/asatime.py#L54-L65 | [
"def",
"unfreeze",
"(",
"name",
")",
":",
"if",
"not",
"exists",
"(",
"name",
")",
":",
"raise",
"ContainerNotExists",
"(",
"\"The container (%s) does not exist!\"",
"%",
"name",
")",
"cmd",
"=",
"[",
"'lxc-unfreeze'",
",",
"'-n'",
",",
"name",
"]",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] |
get the espg code from the crs system | def epsg_code ( geojson ) : if isinstance ( geojson , dict ) : if 'crs' in geojson : urn = geojson [ 'crs' ] [ 'properties' ] [ 'name' ] . split ( ':' ) if 'EPSG' in urn : try : return int ( urn [ - 1 ] ) except ( TypeError , ValueError ) : return None return None | 9,674 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L24-L36 | [
"def",
"get_form_kwargs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"super",
"(",
"ClassRegistrationView",
",",
"self",
")",
".",
"get_form_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"kwargs",
"[",
"'user'",
"]",
"=",
"self",
".",
"request",
".",
"user",
"if",
"hasattr",
"(",
"self",
".",
"request",
",",
"'user'",
")",
"else",
"None",
"listing",
"=",
"self",
".",
"get_listing",
"(",
")",
"kwargs",
".",
"update",
"(",
"{",
"'openEvents'",
":",
"listing",
"[",
"'openEvents'",
"]",
",",
"'closedEvents'",
":",
"listing",
"[",
"'closedEvents'",
"]",
",",
"}",
")",
"return",
"kwargs"
] |
Convert coordinates from one crs to another | def convert_coordinates ( coords , origin , wgs84 , wrapped ) : if isinstance ( coords , list ) or isinstance ( coords , tuple ) : try : if isinstance ( coords [ 0 ] , list ) or isinstance ( coords [ 0 ] , tuple ) : return [ convert_coordinates ( list ( c ) , origin , wgs84 , wrapped ) for c in coords ] elif isinstance ( coords [ 0 ] , float ) : c = list ( transform ( origin , wgs84 , * coords ) ) if wrapped and c [ 0 ] < - 170 : c [ 0 ] = c [ 0 ] + 360 return c except IndexError : pass return None | 9,675 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L56-L71 | [
"def",
"set_context",
"(",
"self",
",",
"context",
",",
"bSuspend",
"=",
"False",
")",
":",
"# Get the thread handle.",
"dwAccess",
"=",
"win32",
".",
"THREAD_SET_CONTEXT",
"if",
"bSuspend",
":",
"dwAccess",
"=",
"dwAccess",
"|",
"win32",
".",
"THREAD_SUSPEND_RESUME",
"hThread",
"=",
"self",
".",
"get_handle",
"(",
"dwAccess",
")",
"# Suspend the thread if requested.",
"if",
"bSuspend",
":",
"self",
".",
"suspend",
"(",
")",
"# No fix for the exit process event bug.",
"# Setting the context of a dead thread is pointless anyway.",
"# Set the thread context.",
"try",
":",
"if",
"win32",
".",
"bits",
"==",
"64",
"and",
"self",
".",
"is_wow64",
"(",
")",
":",
"win32",
".",
"Wow64SetThreadContext",
"(",
"hThread",
",",
"context",
")",
"else",
":",
"win32",
".",
"SetThreadContext",
"(",
"hThread",
",",
"context",
")",
"# Resume the thread if we suspended it.",
"finally",
":",
"if",
"bSuspend",
":",
"self",
".",
"resume",
"(",
")"
] |
Convert a given geojson to wgs84 . The original epsg must be included insde the crs tag of geojson | def to_latlon ( geojson , origin_espg = None ) : if isinstance ( geojson , dict ) : # get epsg code: if origin_espg : code = origin_espg else : code = epsg_code ( geojson ) if code : origin = Proj ( init = 'epsg:%s' % code ) wgs84 = Proj ( init = 'epsg:4326' ) wrapped = test_wrap_coordinates ( geojson [ 'coordinates' ] , origin , wgs84 ) new_coords = convert_coordinates ( geojson [ 'coordinates' ] , origin , wgs84 , wrapped ) if new_coords : geojson [ 'coordinates' ] = new_coords try : del geojson [ 'crs' ] except KeyError : pass return geojson | 9,676 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L74-L99 | [
"def",
"convert_machine_list_value",
"(",
"name",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"Union",
"[",
"datetime",
".",
"datetime",
",",
"str",
",",
"int",
"]",
":",
"if",
"name",
"==",
"'modify'",
":",
"return",
"convert_machine_list_time_val",
"(",
"value",
")",
"elif",
"name",
"==",
"'size'",
":",
"return",
"int",
"(",
"value",
")",
"else",
":",
"return",
"value"
] |
Convert camelcase names to underscore | def camelcase_underscore ( name ) : s1 = re . sub ( '(.)([A-Z][a-z]+)' , r'\1_\2' , name ) return re . sub ( '([a-z0-9])([A-Z])' , r'\1_\2' , s1 ) . lower ( ) | 9,677 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L102-L105 | [
"def",
"metadata",
"(",
"self",
",",
"delete",
"=",
"False",
")",
":",
"if",
"delete",
":",
"return",
"self",
".",
"_session",
".",
"delete",
"(",
"self",
".",
"__v1",
"(",
")",
"+",
"\"/metadata\"",
")",
".",
"json",
"(",
")",
"else",
":",
"return",
"self",
".",
"_session",
".",
"get",
"(",
"self",
".",
"__v1",
"(",
")",
"+",
"\"/metadata\"",
")",
".",
"json",
"(",
")"
] |
Returns the list of all tile names from Product_Organisation element in metadata . xml | def get_tiles_list ( element ) : tiles = { } for el in element : g = ( el . findall ( './/Granules' ) or el . findall ( './/Granule' ) ) [ 0 ] name = g . attrib [ 'granuleIdentifier' ] name_parts = name . split ( '_' ) mgs = name_parts [ - 2 ] tiles [ mgs ] = name return tiles | 9,678 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L108-L124 | [
"def",
"set_connection_type",
"(",
"self",
",",
"connection_type",
")",
":",
"result",
"=",
"self",
".",
"library",
".",
"Cli_SetConnectionType",
"(",
"self",
".",
"pointer",
",",
"c_uint16",
"(",
"connection_type",
")",
")",
"if",
"result",
"!=",
"0",
":",
"raise",
"Snap7Exception",
"(",
"\"The parameter was invalid\"",
")"
] |
Looks at metadata . xml file of sentinel product and extract useful keys Returns a python dict | def metadata_to_dict ( metadata ) : tree = etree . parse ( metadata ) root = tree . getroot ( ) meta = OrderedDict ( ) keys = [ 'SPACECRAFT_NAME' , 'PRODUCT_STOP_TIME' , 'Cloud_Coverage_Assessment' , 'PROCESSING_LEVEL' , 'PRODUCT_TYPE' , 'PROCESSING_BASELINE' , 'SENSING_ORBIT_NUMBER' , 'SENSING_ORBIT_DIRECTION' , 'PRODUCT_FORMAT' , ] # grab important keys from the file for key in keys : try : meta [ key . lower ( ) ] = root . findall ( './/' + key ) [ 0 ] . text except IndexError : meta [ key . lower ( ) ] = None meta [ 'product_cloud_coverage_assessment' ] = float ( meta . pop ( 'cloud_coverage_assessment' ) ) meta [ 'sensing_orbit_number' ] = int ( meta [ 'sensing_orbit_number' ] ) # get tile list meta [ 'tiles' ] = get_tiles_list ( root . findall ( './/Product_Organisation' ) [ 0 ] ) # get available bands if root . findall ( './/Band_List' ) : bands = root . findall ( './/Band_List' ) [ 0 ] meta [ 'band_list' ] = [ ] for b in bands : band = b . text . replace ( 'B' , '' ) if len ( band ) == 1 : band = 'B' + pad ( band , 2 ) else : band = b . text meta [ 'band_list' ] . append ( band ) else : bands = root . findall ( './/Spectral_Information_List' ) [ 0 ] meta [ 'band_list' ] = [ ] for b in bands : band = b . attrib [ 'physicalBand' ] . replace ( 'B' , '' ) if len ( band ) == 1 : band = 'B' + pad ( band , 2 ) else : band = b . attrib [ 'physicalBand' ] meta [ 'band_list' ] . append ( band ) return meta | 9,679 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L127-L184 | [
"def",
"get_booking",
"(",
"request",
")",
":",
"booking",
"=",
"None",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"try",
":",
"booking",
"=",
"Booking",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
",",
"booking_status__slug",
"=",
"'inprogress'",
")",
"except",
"Booking",
".",
"DoesNotExist",
":",
"# The user does not have any open bookings",
"pass",
"else",
":",
"session",
"=",
"Session",
".",
"objects",
".",
"get",
"(",
"session_key",
"=",
"request",
".",
"session",
".",
"session_key",
")",
"try",
":",
"booking",
"=",
"Booking",
".",
"objects",
".",
"get",
"(",
"session",
"=",
"session",
")",
"except",
"Booking",
".",
"DoesNotExist",
":",
"# The user does not have any bookings in his session",
"pass",
"return",
"booking"
] |
Calculate the data and tile geometry for sentinel - 2 tiles | def get_tile_geometry ( path , origin_espg , tolerance = 500 ) : with rasterio . open ( path ) as src : # Get tile geometry b = src . bounds tile_shape = Polygon ( [ ( b [ 0 ] , b [ 1 ] ) , ( b [ 2 ] , b [ 1 ] ) , ( b [ 2 ] , b [ 3 ] ) , ( b [ 0 ] , b [ 3 ] ) , ( b [ 0 ] , b [ 1 ] ) ] ) tile_geojson = mapping ( tile_shape ) # read first band of the image image = src . read ( 1 ) # create a mask of zero values mask = image == 0. # generate shapes of the mask novalue_shape = shapes ( image , mask = mask , transform = src . affine ) # generate polygons using shapely novalue_shape = [ Polygon ( s [ 'coordinates' ] [ 0 ] ) for ( s , v ) in novalue_shape ] if novalue_shape : # Make sure polygons are united # also simplify the resulting polygon union = cascaded_union ( novalue_shape ) # generates a geojson data_shape = tile_shape . difference ( union ) # If there are multipolygons, select the largest one if data_shape . geom_type == 'MultiPolygon' : areas = { p . area : i for i , p in enumerate ( data_shape ) } largest = max ( areas . keys ( ) ) data_shape = data_shape [ areas [ largest ] ] # if the polygon has interior rings, remove them if list ( data_shape . interiors ) : data_shape = Polygon ( data_shape . exterior . coords ) data_shape = data_shape . simplify ( tolerance , preserve_topology = False ) data_geojson = mapping ( data_shape ) else : data_geojson = tile_geojson # convert cooridnates to degrees return ( to_latlon ( tile_geojson , origin_espg ) , to_latlon ( data_geojson , origin_espg ) ) | 9,680 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L187-L235 | [
"def",
"url_to_resource",
"(",
"url",
",",
"request",
"=",
"None",
")",
":",
"if",
"request",
"is",
"None",
":",
"request",
"=",
"get_current_request",
"(",
")",
"# cnv = request.registry.getAdapter(request, IResourceUrlConverter)",
"reg",
"=",
"get_current_registry",
"(",
")",
"cnv",
"=",
"reg",
".",
"getAdapter",
"(",
"request",
",",
"IResourceUrlConverter",
")",
"return",
"cnv",
".",
"url_to_resource",
"(",
"url",
")"
] |
Generate metadata for a given tile | def tile_metadata ( tile , product , geometry_check = None ) : grid = 'T{0}{1}{2}' . format ( pad ( tile [ 'utmZone' ] , 2 ) , tile [ 'latitudeBand' ] , tile [ 'gridSquare' ] ) meta = OrderedDict ( { 'tile_name' : product [ 'tiles' ] [ grid ] } ) logger . info ( '%s Processing tile %s' % ( threading . current_thread ( ) . name , tile [ 'path' ] ) ) meta [ 'date' ] = tile [ 'timestamp' ] . split ( 'T' ) [ 0 ] meta [ 'thumbnail' ] = '{1}/{0}/preview.jp2' . format ( tile [ 'path' ] , s3_url ) # remove unnecessary keys product . pop ( 'tiles' ) tile . pop ( 'datastrip' ) bands = product . pop ( 'band_list' ) for k , v in iteritems ( tile ) : meta [ camelcase_underscore ( k ) ] = v meta . update ( product ) # construct download links links = [ '{2}/{0}/{1}.jp2' . format ( meta [ 'path' ] , b , s3_url ) for b in bands ] meta [ 'download_links' ] = { 'aws_s3' : links } meta [ 'original_tile_meta' ] = '{0}/{1}/tileInfo.json' . format ( s3_url , meta [ 'path' ] ) def internal_latlon ( meta ) : keys = [ 'tile_origin' , 'tile_geometry' , 'tile_data_geometry' ] for key in keys : if key in meta : meta [ key ] = to_latlon ( meta [ key ] ) return meta # change coordinates to wsg4 degrees if geometry_check : if geometry_check ( meta ) : meta = get_tile_geometry_from_s3 ( meta ) else : meta = internal_latlon ( meta ) else : meta = internal_latlon ( meta ) # rename path key to aws_path meta [ 'aws_path' ] = meta . pop ( 'path' ) return meta | 9,681 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/converter.py#L266-L324 | [
"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",
")"
] |
Load and return markov algorithm . | def load_markov ( argv , stdin ) : if len ( argv ) > 3 : with open ( argv [ 3 ] ) as input_file : return Algorithm ( input_file . readlines ( ) ) else : return Algorithm ( stdin . readlines ( ) ) | 9,682 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/__main__.py#L21-L27 | [
"def",
"win32_refresh_window",
"(",
"cls",
")",
":",
"# Get console handle",
"handle",
"=",
"windll",
".",
"kernel32",
".",
"GetConsoleWindow",
"(",
")",
"RDW_INVALIDATE",
"=",
"0x0001",
"windll",
".",
"user32",
".",
"RedrawWindow",
"(",
"handle",
",",
"None",
",",
"None",
",",
"c_uint",
"(",
"RDW_INVALIDATE",
")",
")"
] |
Load and return turing machine . | def load_turing ( argv , stdin ) : if len ( argv ) > 3 : with open ( argv [ 3 ] ) as input_file : return build_machine ( input_file . readlines ( ) ) else : return build_machine ( stdin . readlines ( ) ) | 9,683 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/__main__.py#L29-L35 | [
"def",
"to_vcf",
"(",
"in_file",
",",
"caller",
",",
"header_fn",
",",
"vcf_fn",
",",
"data",
",",
"sep",
"=",
"\"\\t\"",
")",
":",
"out_file",
"=",
"\"%s.vcf\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"[",
"0",
"]",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
"+",
"\".gz\"",
")",
"and",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",
":",
"with",
"open",
"(",
"tx_out_file",
",",
"\"w\"",
")",
"as",
"out_handle",
":",
"out_handle",
".",
"write",
"(",
"_vcf_header",
".",
"format",
"(",
"caller",
"=",
"caller",
")",
")",
"out_handle",
".",
"write",
"(",
"\"\\t\"",
".",
"join",
"(",
"[",
"\"#CHROM\"",
",",
"\"POS\"",
",",
"\"ID\"",
",",
"\"REF\"",
",",
"\"ALT\"",
",",
"\"QUAL\"",
",",
"\"FILTER\"",
",",
"\"INFO\"",
",",
"\"FORMAT\"",
",",
"dd",
".",
"get_sample_name",
"(",
"data",
")",
"]",
")",
"+",
"\"\\n\"",
")",
"header",
",",
"in_handle",
"=",
"header_fn",
"(",
"in_handle",
")",
"for",
"line",
"in",
"in_handle",
":",
"out",
"=",
"vcf_fn",
"(",
"dict",
"(",
"zip",
"(",
"header",
",",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"sep",
")",
")",
")",
")",
"if",
"out",
":",
"out_handle",
".",
"write",
"(",
"\"\\t\"",
".",
"join",
"(",
"out",
")",
"+",
"\"\\n\"",
")",
"out_file",
"=",
"vcfutils",
".",
"bgzip_and_index",
"(",
"out_file",
",",
"data",
"[",
"\"config\"",
"]",
")",
"effects_vcf",
",",
"_",
"=",
"effects",
".",
"add_to_vcf",
"(",
"out_file",
",",
"data",
",",
"\"snpeff\"",
")",
"return",
"effects_vcf",
"or",
"out_file"
] |
Execute when user call turingmarkov . | def main ( argv , stdin , stdout ) : if len ( argv ) > 1 and argv [ 1 : 3 ] == [ "compile" , "markov" ] : algo = load_markov ( argv , stdin ) print ( algo . compile ( ) , file = stdout ) elif len ( argv ) == 4 and argv [ 1 : 3 ] == [ "run" , "markov" ] : algo = load_markov ( argv , stdin ) for line in stdin : print ( algo . execute ( '' . join ( line . split ( ) ) ) , file = stdout ) elif len ( argv ) > 1 and argv [ 1 : 3 ] == [ "compile" , "turing" ] : machine = load_turing ( argv , stdin ) print ( machine . compile ( ) , file = stdout ) elif len ( argv ) == 4 and argv [ 1 : 3 ] == [ "run" , "turing" ] : machine = load_turing ( argv , stdin ) for line in stdin : print ( machine . execute ( line ) , file = stdout ) elif len ( argv ) == 2 and argv [ 1 ] == "test" : path = os . path . abspath ( os . path . dirname ( __file__ ) ) argv [ 1 ] = path pytest . main ( ) elif len ( argv ) == 2 and argv [ 1 ] == "version" : print ( "TuringMarkov" , VERSION , file = stdout ) else : print ( USAGE , file = stdout ) if not ( len ( argv ) == 2 and argv [ 1 ] == "help" ) : exit ( 1 ) | 9,684 | https://github.com/vslutov/turingmarkov/blob/63e2ba255d7d0d868cbc4bf3e568b1c1bbcf38ce/turingmarkov/__main__.py#L37-L65 | [
"def",
"CleanAff4Clients",
"(",
"self",
")",
":",
"inactive_client_ttl",
"=",
"config",
".",
"CONFIG",
"[",
"\"DataRetention.inactive_client_ttl\"",
"]",
"if",
"not",
"inactive_client_ttl",
":",
"self",
".",
"Log",
"(",
"\"TTL not set - nothing to do...\"",
")",
"return",
"exception_label",
"=",
"config",
".",
"CONFIG",
"[",
"\"DataRetention.inactive_client_ttl_exception_label\"",
"]",
"index",
"=",
"client_index",
".",
"CreateClientIndex",
"(",
"token",
"=",
"self",
".",
"token",
")",
"client_urns",
"=",
"index",
".",
"LookupClients",
"(",
"[",
"\".\"",
"]",
")",
"deadline",
"=",
"rdfvalue",
".",
"RDFDatetime",
".",
"Now",
"(",
")",
"-",
"inactive_client_ttl",
"deletion_count",
"=",
"0",
"for",
"client_group",
"in",
"collection",
".",
"Batch",
"(",
"client_urns",
",",
"1000",
")",
":",
"inactive_client_urns",
"=",
"[",
"]",
"for",
"client",
"in",
"aff4",
".",
"FACTORY",
".",
"MultiOpen",
"(",
"client_group",
",",
"mode",
"=",
"\"r\"",
",",
"aff4_type",
"=",
"aff4_grr",
".",
"VFSGRRClient",
",",
"token",
"=",
"self",
".",
"token",
")",
":",
"if",
"exception_label",
"in",
"client",
".",
"GetLabelsNames",
"(",
")",
":",
"continue",
"if",
"client",
".",
"Get",
"(",
"client",
".",
"Schema",
".",
"LAST",
")",
"<",
"deadline",
":",
"inactive_client_urns",
".",
"append",
"(",
"client",
".",
"urn",
")",
"aff4",
".",
"FACTORY",
".",
"MultiDelete",
"(",
"inactive_client_urns",
",",
"token",
"=",
"self",
".",
"token",
")",
"deletion_count",
"+=",
"len",
"(",
"inactive_client_urns",
")",
"self",
".",
"HeartBeat",
"(",
")",
"self",
".",
"Log",
"(",
"\"Deleted %d inactive clients.\"",
"%",
"deletion_count",
")"
] |
Print the detectors table | def detectors ( regex = None , sep = '\t' , temporary = False ) : db = DBManager ( temporary = temporary ) dt = db . detectors if regex is not None : try : re . compile ( regex ) except re . error : log . error ( "Invalid regex!" ) return dt = dt [ dt [ 'OID' ] . str . contains ( regex ) | dt [ 'CITY' ] . str . contains ( regex ) ] dt . to_csv ( sys . stdout , sep = sep ) | 9,685 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/cmd.py#L112-L123 | [
"def",
"random_connection",
"(",
"self",
")",
":",
"# While at the moment there's no need for this to be a context manager",
"# per se, I would like to use that interface since I anticipate",
"# adding some wrapping around it at some point.",
"yield",
"random",
".",
"choice",
"(",
"[",
"conn",
"for",
"conn",
"in",
"self",
".",
"connections",
"(",
")",
"if",
"conn",
".",
"alive",
"(",
")",
"]",
")"
] |
gets a single products metadata | def get_product_metadata_path ( product_name ) : string_date = product_name . split ( '_' ) [ - 1 ] date = datetime . datetime . strptime ( string_date , '%Y%m%dT%H%M%S' ) path = 'products/{0}/{1}/{2}/{3}' . format ( date . year , date . month , date . day , product_name ) return { product_name : { 'metadata' : '{0}/{1}' . format ( path , 'metadata.xml' ) , 'tiles' : get_tile_metadata_path ( '{0}/{1}' . format ( path , 'productInfo.json' ) ) } } | 9,686 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/crawler.py#L24-L36 | [
"def",
"dump",
"(",
"self",
")",
":",
"assert",
"self",
".",
"database",
"is",
"not",
"None",
"cmd",
"=",
"\"SELECT count from {} WHERE rowid={}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_INFO_TABLE",
",",
"self",
".",
"STATE_INFO_ROW",
")",
")",
"ret",
"=",
"self",
".",
"_fetchall",
"(",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"1",
"assert",
"len",
"(",
"ret",
"[",
"0",
"]",
")",
"==",
"1",
"count",
"=",
"self",
".",
"_from_sqlite",
"(",
"ret",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"+",
"self",
".",
"inserts",
"if",
"count",
">",
"self",
".",
"row_limit",
":",
"msg",
"=",
"\"cleaning up state, this might take a while.\"",
"logger",
".",
"warning",
"(",
"msg",
")",
"delete",
"=",
"count",
"-",
"self",
".",
"row_limit",
"delete",
"+=",
"int",
"(",
"self",
".",
"row_limit",
"*",
"(",
"self",
".",
"row_cleanup_quota",
"/",
"100.0",
")",
")",
"cmd",
"=",
"(",
"\"DELETE FROM {} WHERE timestamp IN (\"",
"\"SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});\"",
")",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_TABLE",
",",
"self",
".",
"STATE_TABLE",
",",
"delete",
")",
")",
"self",
".",
"_vacuum",
"(",
")",
"cmd",
"=",
"\"SELECT COUNT(*) FROM {}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_TABLE",
")",
")",
"ret",
"=",
"self",
".",
"_fetchall",
"(",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"1",
"assert",
"len",
"(",
"ret",
"[",
"0",
"]",
")",
"==",
"1",
"count",
"=",
"ret",
"[",
"0",
"]",
"[",
"0",
"]",
"cmd",
"=",
"\"UPDATE {} SET count = {} WHERE rowid = {}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_INFO_TABLE",
",",
"self",
".",
"_to_sqlite",
"(",
"count",
")",
",",
"self",
".",
"STATE_INFO_ROW",
",",
")",
")",
"self",
".",
"_update_cache_directory_state",
"(",
")",
"self",
".",
"database",
".",
"commit",
"(",
")",
"self",
".",
"cursor",
".",
"close",
"(",
")",
"self",
".",
"database",
".",
"close",
"(",
")",
"self",
".",
"database",
"=",
"None",
"self",
".",
"cursor",
"=",
"None",
"self",
".",
"inserts",
"=",
"0"
] |
Get paths to multiple products metadata | def get_products_metadata_path ( year , month , day ) : products = { } path = 'products/{0}/{1}/{2}/' . format ( year , month , day ) for key in bucket . objects . filter ( Prefix = path ) : product_path = key . key . replace ( path , '' ) . split ( '/' ) name = product_path [ 0 ] if name not in products : products [ name ] = { } if product_path [ 1 ] == 'metadata.xml' : products [ name ] [ 'metadata' ] = key . key if product_path [ 1 ] == 'productInfo.json' : products [ name ] [ 'tiles' ] = get_tile_metadata_path ( key . key ) return products | 9,687 | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/crawler.py#L39-L56 | [
"def",
"dump",
"(",
"self",
")",
":",
"assert",
"self",
".",
"database",
"is",
"not",
"None",
"cmd",
"=",
"\"SELECT count from {} WHERE rowid={}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_INFO_TABLE",
",",
"self",
".",
"STATE_INFO_ROW",
")",
")",
"ret",
"=",
"self",
".",
"_fetchall",
"(",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"1",
"assert",
"len",
"(",
"ret",
"[",
"0",
"]",
")",
"==",
"1",
"count",
"=",
"self",
".",
"_from_sqlite",
"(",
"ret",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"+",
"self",
".",
"inserts",
"if",
"count",
">",
"self",
".",
"row_limit",
":",
"msg",
"=",
"\"cleaning up state, this might take a while.\"",
"logger",
".",
"warning",
"(",
"msg",
")",
"delete",
"=",
"count",
"-",
"self",
".",
"row_limit",
"delete",
"+=",
"int",
"(",
"self",
".",
"row_limit",
"*",
"(",
"self",
".",
"row_cleanup_quota",
"/",
"100.0",
")",
")",
"cmd",
"=",
"(",
"\"DELETE FROM {} WHERE timestamp IN (\"",
"\"SELECT timestamp FROM {} ORDER BY timestamp ASC LIMIT {});\"",
")",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_TABLE",
",",
"self",
".",
"STATE_TABLE",
",",
"delete",
")",
")",
"self",
".",
"_vacuum",
"(",
")",
"cmd",
"=",
"\"SELECT COUNT(*) FROM {}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_TABLE",
")",
")",
"ret",
"=",
"self",
".",
"_fetchall",
"(",
")",
"assert",
"len",
"(",
"ret",
")",
"==",
"1",
"assert",
"len",
"(",
"ret",
"[",
"0",
"]",
")",
"==",
"1",
"count",
"=",
"ret",
"[",
"0",
"]",
"[",
"0",
"]",
"cmd",
"=",
"\"UPDATE {} SET count = {} WHERE rowid = {}\"",
"self",
".",
"_execute",
"(",
"cmd",
".",
"format",
"(",
"self",
".",
"STATE_INFO_TABLE",
",",
"self",
".",
"_to_sqlite",
"(",
"count",
")",
",",
"self",
".",
"STATE_INFO_ROW",
",",
")",
")",
"self",
".",
"_update_cache_directory_state",
"(",
")",
"self",
".",
"database",
".",
"commit",
"(",
")",
"self",
".",
"cursor",
".",
"close",
"(",
")",
"self",
".",
"database",
".",
"close",
"(",
")",
"self",
".",
"database",
"=",
"None",
"self",
".",
"cursor",
"=",
"None",
"self",
".",
"inserts",
"=",
"0"
] |
Mark the start of timing overwriting the automatic start data written on import or the automatic start at the beginning of a subdivision . | def start ( backdate = None ) : if f . s . cum : raise StartError ( "Already have stamps, can't start again (must reset)." ) if f . t . subdvsn_awaiting or f . t . par_subdvsn_awaiting : raise StartError ( "Already have subdivisions, can't start again (must reset)." ) if f . t . stopped : raise StoppedError ( "Timer already stopped (must open new or reset)." ) t = timer ( ) if backdate is None : t_start = t else : if f . t is f . root : raise BackdateError ( "Cannot backdate start of root timer." ) if not isinstance ( backdate , float ) : raise TypeError ( "Backdate must be type float." ) if backdate > t : raise BackdateError ( "Cannot backdate to future time." ) if backdate < f . tm1 . last_t : raise BackdateError ( "Cannot backdate start to time previous to latest stamp in parent timer." ) t_start = backdate f . t . paused = False f . t . tmp_total = 0. # (In case previously paused.) f . t . start_t = t_start f . t . last_t = t_start return t | 9,688 | https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L40-L85 | [
"def",
"lens_center",
"(",
"self",
",",
"kwargs_lens",
",",
"k",
"=",
"None",
",",
"bool_list",
"=",
"None",
",",
"numPix",
"=",
"200",
",",
"deltaPix",
"=",
"0.01",
",",
"center_x_init",
"=",
"0",
",",
"center_y_init",
"=",
"0",
")",
":",
"x_grid",
",",
"y_grid",
"=",
"util",
".",
"make_grid",
"(",
"numPix",
"=",
"numPix",
",",
"deltapix",
"=",
"deltaPix",
")",
"x_grid",
"+=",
"center_x_init",
"y_grid",
"+=",
"center_y_init",
"if",
"bool_list",
"is",
"None",
":",
"kappa",
"=",
"self",
".",
"_lensModel",
".",
"kappa",
"(",
"x_grid",
",",
"y_grid",
",",
"kwargs_lens",
",",
"k",
"=",
"k",
")",
"else",
":",
"kappa",
"=",
"np",
".",
"zeros_like",
"(",
"x_grid",
")",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"kwargs_lens",
")",
")",
":",
"if",
"bool_list",
"[",
"k",
"]",
"is",
"True",
":",
"kappa",
"+=",
"self",
".",
"_lensModel",
".",
"kappa",
"(",
"x_grid",
",",
"y_grid",
",",
"kwargs_lens",
",",
"k",
"=",
"k",
")",
"center_x",
"=",
"x_grid",
"[",
"kappa",
"==",
"np",
".",
"max",
"(",
"kappa",
")",
"]",
"center_y",
"=",
"y_grid",
"[",
"kappa",
"==",
"np",
".",
"max",
"(",
"kappa",
")",
"]",
"return",
"center_x",
",",
"center_y"
] |
Mark the end of a timing interval . | def stamp ( name , backdate = None , unique = None , keep_subdivisions = None , quick_print = None , un = None , ks = None , qp = None ) : t = timer ( ) if f . t . stopped : raise StoppedError ( "Cannot stamp stopped timer." ) if f . t . paused : raise PausedError ( "Cannot stamp paused timer." ) if backdate is None : t_stamp = t else : if not isinstance ( backdate , float ) : raise TypeError ( "Backdate must be type float." ) if backdate > t : raise BackdateError ( "Cannot backdate to future time." ) if backdate < f . t . last_t : raise BackdateError ( "Cannot backdate to time earlier than last stamp." ) t_stamp = backdate elapsed = t_stamp - f . t . last_t # Logic: default unless either arg used. if both args used, 'or' them. unique = SET [ 'UN' ] if ( unique is None and un is None ) else bool ( unique or un ) # bool(None) becomes False keep_subdivisions = SET [ 'KS' ] if ( keep_subdivisions is None and ks is None ) else bool ( keep_subdivisions or ks ) quick_print = SET [ 'QP' ] if ( quick_print is None and qp is None ) else bool ( quick_print or qp ) _stamp ( name , elapsed , unique , keep_subdivisions , quick_print ) tmp_self = timer ( ) - t f . t . self_cut += tmp_self f . t . last_t = t_stamp + tmp_self return t | 9,689 | https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L88-L155 | [
"def",
"create_cvmfs_storage_class",
"(",
"cvmfs_volume",
")",
":",
"from",
"kubernetes",
".",
"client",
".",
"rest",
"import",
"ApiException",
"from",
"reana_commons",
".",
"k8s",
".",
"api_client",
"import",
"current_k8s_storagev1_api_client",
"try",
":",
"current_k8s_storagev1_api_client",
".",
"create_storage_class",
"(",
"render_cvmfs_sc",
"(",
"cvmfs_volume",
")",
")",
"except",
"ApiException",
"as",
"e",
":",
"if",
"e",
".",
"status",
"!=",
"409",
":",
"raise",
"e"
] |
Mark the end of timing . Optionally performs a stamp hence accepts the same arguments . | def stop ( name = None , backdate = None , unique = None , keep_subdivisions = None , quick_print = None , un = None , ks = None , qp = None ) : t = timer ( ) if f . t . stopped : raise StoppedError ( "Timer already stopped." ) if backdate is None : t_stop = t else : if f . t is f . root : raise BackdateError ( "Cannot backdate stop of root timer." ) if not isinstance ( backdate , float ) : raise TypeError ( "Backdate must be type float." ) if backdate > t : raise BackdateError ( "Cannot backdate to future time." ) if backdate < f . t . last_t : raise BackdateError ( "Cannot backdate to time earlier than last stamp." ) t_stop = backdate unique = SET [ 'UN' ] if ( unique is None and un is None ) else bool ( unique or un ) # bool(None) becomes False keep_subdivisions = SET [ 'KS' ] if ( keep_subdivisions is None and ks is None ) else bool ( keep_subdivisions or ks ) quick_print = SET [ 'QP' ] if ( quick_print is None and qp is None ) else bool ( quick_print or qp ) if name is not None : if f . t . paused : raise PausedError ( "Cannot stamp paused timer." ) elapsed = t_stop - f . t . last_t _stamp ( name , elapsed , unique , keep_subdivisions , quick_print ) else : times_priv . assign_subdivisions ( UNASGN , keep_subdivisions ) for s in f . t . rgstr_stamps : if s not in f . s . cum : f . s . cum [ s ] = 0. f . s . order . append ( s ) if not f . t . paused : f . t . tmp_total += t_stop - f . t . start_t f . t . tmp_total -= f . t . self_cut f . t . self_cut += timer ( ) - t # AFTER subtraction from tmp_total, before dump times_priv . dump_times ( ) f . t . stopped = True if quick_print : print ( "({}) Total: {:.4f}" . format ( f . t . name , f . r . total ) ) return t | 9,690 | https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L158-L231 | [
"def",
"normalize_names",
"(",
"column_names",
")",
":",
"result",
"=",
"[",
"]",
"for",
"column_name",
"in",
"column_names",
":",
"column",
"=",
"Column",
"(",
"column_name",
")",
".",
"normalize",
"(",
"forbidden_column_names",
"=",
"result",
")",
"result",
".",
"append",
"(",
"column",
".",
"name",
")",
"return",
"result"
] |
Pause the timer preventing subsequent time from accumulating in the total . Renders the timer inactive disabling other timing commands . | def pause ( ) : t = timer ( ) if f . t . stopped : raise StoppedError ( "Cannot pause stopped timer." ) if f . t . paused : raise PausedError ( "Timer already paused." ) f . t . paused = True f . t . tmp_total += t - f . t . start_t f . t . start_t = None f . t . last_t = None return t | 9,691 | https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L234-L255 | [
"def",
"cublasGetVersion",
"(",
"handle",
")",
":",
"version",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"status",
"=",
"_libcublas",
".",
"cublasGetVersion_v2",
"(",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"version",
")",
")",
"cublasCheckStatus",
"(",
"status",
")",
"return",
"version",
".",
"value"
] |
Resume a paused timer re - activating it . Subsequent time accumulates in the total . | def resume ( ) : t = timer ( ) if f . t . stopped : raise StoppedError ( "Cannot resume stopped timer." ) if not f . t . paused : raise PausedError ( "Cannot resume timer that is not paused." ) f . t . paused = False f . t . start_t = t f . t . last_t = t return t | 9,692 | https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timer.py#L258-L278 | [
"def",
"delete_project",
"(",
"project_id",
")",
":",
"project",
"=",
"get_data_or_404",
"(",
"'project'",
",",
"project_id",
")",
"if",
"project",
"[",
"'owner_id'",
"]",
"!=",
"get_current_user_id",
"(",
")",
":",
"return",
"jsonify",
"(",
"message",
"=",
"'forbidden'",
")",
",",
"403",
"delete_instance",
"(",
"'project'",
",",
"project_id",
")",
"return",
"jsonify",
"(",
"{",
"}",
")"
] |
Make copies of everything assign to global shortcuts so functions work on them extract the times then restore the running stacks . | def collapse_times ( ) : orig_ts = f . timer_stack orig_ls = f . loop_stack copy_ts = _copy_timer_stack ( ) copy_ls = copy . deepcopy ( f . loop_stack ) f . timer_stack = copy_ts f . loop_stack = copy_ls f . refresh_shortcuts ( ) while ( len ( f . timer_stack ) > 1 ) or f . t . in_loop : _collapse_subdivision ( ) timer_pub . stop ( ) collapsed_times = f . r f . timer_stack = orig_ts # (loops throw error if not same object!) f . loop_stack = orig_ls f . refresh_shortcuts ( ) return collapsed_times | 9,693 | https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/private/collapse.py#L15-L33 | [
"def",
"has_pubmed",
"(",
"edge_data",
":",
"EdgeData",
")",
"->",
"bool",
":",
"return",
"CITATION",
"in",
"edge_data",
"and",
"CITATION_TYPE_PUBMED",
"==",
"edge_data",
"[",
"CITATION",
"]",
"[",
"CITATION_TYPE",
"]"
] |
Create a new plate and commit it to the database | def create_plate ( self , plate_id , description , meta_data_id , values , complement , parent_plate ) : # Make sure the plate id doesn't already exist with switch_db ( PlateDefinitionModel , db_alias = 'hyperstream' ) : try : p = PlateDefinitionModel . objects . get ( plate_id = plate_id ) if p : logging . info ( "Plate with id {} already exists" . format ( plate_id ) ) return self . plates [ plate_id ] except DoesNotExist : pass except MultipleObjectsReturned : raise plate_definition = PlateDefinitionModel ( plate_id = plate_id , description = description , meta_data_id = meta_data_id , values = values , complement = complement , parent_plate = parent_plate ) self . add_plate ( plate_definition ) plate_definition . save ( ) return self . plates [ plate_id ] | 9,694 | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/plate/plate_manager.py#L100-L139 | [
"def",
"fmt_duration",
"(",
"duration",
")",
":",
"try",
":",
"return",
"fmt",
".",
"human_duration",
"(",
"float",
"(",
"duration",
")",
",",
"0",
",",
"2",
",",
"True",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
"\"N/A\"",
".",
"rjust",
"(",
"len",
"(",
"fmt",
".",
"human_duration",
"(",
"0",
",",
"0",
",",
"2",
",",
"True",
")",
")",
")"
] |
Instantiate a TimedLoop object for measuring loop iteration timing data . Can be used with either for or while loops . | def timed_loop ( name = None , rgstr_stamps = None , save_itrs = SET [ 'SI' ] , loop_end_stamp = None , end_stamp_unique = SET [ 'UN' ] , keep_prev_subdivisions = SET [ 'KS' ] , keep_end_subdivisions = SET [ 'KS' ] , quick_print = SET [ 'QP' ] ) : return TimedLoop ( name = name , rgstr_stamps = rgstr_stamps , save_itrs = save_itrs , loop_end_stamp = loop_end_stamp , end_stamp_unique = end_stamp_unique , keep_prev_subdivisions = keep_prev_subdivisions , keep_end_subdivisions = keep_end_subdivisions ) | 9,695 | https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timedloop.py#L13-L69 | [
"def",
"assign_ranks_to_grid",
"(",
"grid",
",",
"ranks",
")",
":",
"assignments",
"=",
"deepcopy",
"(",
"grid",
")",
"ranks",
"[",
"\"0b0\"",
"]",
"=",
"0",
"ranks",
"[",
"\"-0b1\"",
"]",
"=",
"-",
"1",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"grid",
")",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"grid",
"[",
"i",
"]",
")",
")",
":",
"if",
"type",
"(",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"is",
"list",
":",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
")",
")",
":",
"assignments",
"[",
"i",
"]",
"[",
"j",
"]",
"[",
"k",
"]",
"=",
"ranks",
"[",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
"[",
"k",
"]",
"]",
"else",
":",
"assignments",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"ranks",
"[",
"grid",
"[",
"i",
"]",
"[",
"j",
"]",
"]",
"return",
"assignments"
] |
Instantiate a TimedLoop object for measuring for loop iteration timing data . Can be used only on for loops . | def timed_for ( iterable , name = None , rgstr_stamps = None , save_itrs = SET [ 'SI' ] , loop_end_stamp = None , end_stamp_unique = SET [ 'UN' ] , keep_prev_subdivisions = SET [ 'KS' ] , keep_end_subdivisions = SET [ 'KS' ] , quick_print = SET [ 'QP' ] ) : return TimedFor ( iterable , name = name , rgstr_stamps = rgstr_stamps , save_itrs = save_itrs , loop_end_stamp = loop_end_stamp , end_stamp_unique = end_stamp_unique , keep_prev_subdivisions = keep_prev_subdivisions , keep_end_subdivisions = keep_end_subdivisions ) | 9,696 | https://github.com/astooke/gtimer/blob/2146dab459e5d959feb291821733d3d3ba7c523c/gtimer/public/timedloop.py#L72-L131 | [
"def",
"get_partition",
"(",
"url",
",",
"headers",
",",
"source_id",
",",
"container",
",",
"partition",
")",
":",
"accepted_formats",
"=",
"list",
"(",
"serializer",
".",
"format_registry",
".",
"keys",
"(",
")",
")",
"accepted_compression",
"=",
"list",
"(",
"serializer",
".",
"compression_registry",
".",
"keys",
"(",
")",
")",
"payload",
"=",
"dict",
"(",
"action",
"=",
"'read'",
",",
"source_id",
"=",
"source_id",
",",
"accepted_formats",
"=",
"accepted_formats",
",",
"accepted_compression",
"=",
"accepted_compression",
")",
"if",
"partition",
"is",
"not",
"None",
":",
"payload",
"[",
"'partition'",
"]",
"=",
"partition",
"try",
":",
"resp",
"=",
"requests",
".",
"post",
"(",
"urljoin",
"(",
"url",
",",
"'/v1/source'",
")",
",",
"data",
"=",
"msgpack",
".",
"packb",
"(",
"payload",
",",
"use_bin_type",
"=",
"True",
")",
",",
"*",
"*",
"headers",
")",
"if",
"resp",
".",
"status_code",
"!=",
"200",
":",
"raise",
"Exception",
"(",
"'Error reading data'",
")",
"msg",
"=",
"msgpack",
".",
"unpackb",
"(",
"resp",
".",
"content",
",",
"*",
"*",
"unpack_kwargs",
")",
"format",
"=",
"msg",
"[",
"'format'",
"]",
"compression",
"=",
"msg",
"[",
"'compression'",
"]",
"compressor",
"=",
"serializer",
".",
"compression_registry",
"[",
"compression",
"]",
"encoder",
"=",
"serializer",
".",
"format_registry",
"[",
"format",
"]",
"chunk",
"=",
"encoder",
".",
"decode",
"(",
"compressor",
".",
"decompress",
"(",
"msg",
"[",
"'data'",
"]",
")",
",",
"container",
")",
"return",
"chunk",
"finally",
":",
"if",
"resp",
"is",
"not",
"None",
":",
"resp",
".",
"close",
"(",
")"
] |
Write calibration set to file | def write_calibration ( calib , f , loc ) : for i , node in enumerate ( [ p + '_' + s for p in [ 'pos' , 'dir' ] for s in 'xyz' ] ) : h5loc = loc + '/' + node ca = f . get_node ( h5loc ) ca . append ( calib [ : , i ] ) du = f . get_node ( loc + '/du' ) du . append ( calib [ : , 7 ] . astype ( 'u1' ) ) floor = f . get_node ( loc + '/floor' ) floor . append ( calib [ : , 8 ] . astype ( 'u1' ) ) t0 = f . get_node ( loc + '/t0' ) t0 . append ( calib [ : , 6 ] ) if loc == "/hits" : time = f . get_node ( loc + "/time" ) offset = len ( time ) chunk_size = len ( calib ) time [ offset - chunk_size : offset ] += calib [ : , 6 ] | 9,697 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/calibrate.py#L87-L108 | [
"def",
"get_new_connection",
"(",
"self",
",",
"conn_params",
")",
":",
"connection",
"=",
"ldap",
".",
"ldapobject",
".",
"ReconnectLDAPObject",
"(",
"uri",
"=",
"conn_params",
"[",
"'uri'",
"]",
",",
"retry_max",
"=",
"conn_params",
"[",
"'retry_max'",
"]",
",",
"retry_delay",
"=",
"conn_params",
"[",
"'retry_delay'",
"]",
",",
"bytes_mode",
"=",
"False",
")",
"options",
"=",
"conn_params",
"[",
"'options'",
"]",
"for",
"opt",
",",
"value",
"in",
"options",
".",
"items",
"(",
")",
":",
"if",
"opt",
"==",
"'query_timeout'",
":",
"connection",
".",
"timeout",
"=",
"int",
"(",
"value",
")",
"elif",
"opt",
"==",
"'page_size'",
":",
"self",
".",
"page_size",
"=",
"int",
"(",
"value",
")",
"else",
":",
"connection",
".",
"set_option",
"(",
"opt",
",",
"value",
")",
"if",
"conn_params",
"[",
"'tls'",
"]",
":",
"connection",
".",
"start_tls_s",
"(",
")",
"connection",
".",
"simple_bind_s",
"(",
"conn_params",
"[",
"'bind_dn'",
"]",
",",
"conn_params",
"[",
"'bind_pw'",
"]",
",",
")",
"return",
"connection"
] |
Create EArrays for calibrated hits | def initialise_arrays ( group , f ) : for node in [ 'pos_x' , 'pos_y' , 'pos_z' , 'dir_x' , 'dir_y' , 'dir_z' , 'du' , 'floor' , 't0' ] : if node in [ 'floor' , 'du' ] : atom = U1_ATOM else : atom = F4_ATOM f . create_earray ( group , node , atom , ( 0 , ) , filters = FILTERS ) | 9,698 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/calibrate.py#L111-L119 | [
"def",
"unfreeze",
"(",
"name",
",",
"path",
"=",
"None",
",",
"use_vt",
"=",
"None",
")",
":",
"_ensure_exists",
"(",
"name",
",",
"path",
"=",
"path",
")",
"if",
"state",
"(",
"name",
",",
"path",
"=",
"path",
")",
"==",
"'stopped'",
":",
"raise",
"CommandExecutionError",
"(",
"'Container \\'{0}\\' is stopped'",
".",
"format",
"(",
"name",
")",
")",
"cmd",
"=",
"'lxc-unfreeze'",
"if",
"path",
":",
"cmd",
"+=",
"' -P {0}'",
".",
"format",
"(",
"pipes",
".",
"quote",
"(",
"path",
")",
")",
"return",
"_change_state",
"(",
"cmd",
",",
"name",
",",
"'running'",
",",
"path",
"=",
"path",
",",
"use_vt",
"=",
"use_vt",
")"
] |
Create a blob counter . | def blob_counter ( self ) : import aa # pylint: disablF0401 # noqa from ROOT import EventFile # pylint: disable F0401 try : event_file = EventFile ( self . filename ) except Exception : raise SystemExit ( "Could not open file" ) num_blobs = 0 for event in event_file : num_blobs += 1 return num_blobs | 9,699 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/aanet.py#L248-L262 | [
"def",
"add_command_line_options_argparse",
"(",
"cls",
",",
"argparser",
")",
":",
"import",
"argparse",
"class",
"SetParameter",
"(",
"argparse",
".",
"Action",
")",
":",
"\"\"\"callback object for ArgumentParser\"\"\"",
"def",
"__call__",
"(",
"self",
",",
"parser",
",",
"namespace",
",",
"value",
",",
"option_string",
"=",
"None",
")",
":",
"cls",
".",
"config",
"[",
"option_string",
"]",
"=",
"value",
"if",
"option_string",
"==",
"\"--stomp-conf\"",
":",
"cls",
".",
"load_configuration_file",
"(",
"value",
")",
"argparser",
".",
"add_argument",
"(",
"\"--stomp-host\"",
",",
"metavar",
"=",
"\"HOST\"",
",",
"default",
"=",
"cls",
".",
"defaults",
".",
"get",
"(",
"\"--stomp-host\"",
")",
",",
"help",
"=",
"\"Stomp broker address, default '%(default)s'\"",
",",
"type",
"=",
"str",
",",
"action",
"=",
"SetParameter",
",",
")",
"argparser",
".",
"add_argument",
"(",
"\"--stomp-port\"",
",",
"metavar",
"=",
"\"PORT\"",
",",
"default",
"=",
"cls",
".",
"defaults",
".",
"get",
"(",
"\"--stomp-port\"",
")",
",",
"help",
"=",
"\"Stomp broker port, default '%(default)s'\"",
",",
"type",
"=",
"int",
",",
"action",
"=",
"SetParameter",
",",
")",
"argparser",
".",
"add_argument",
"(",
"\"--stomp-user\"",
",",
"metavar",
"=",
"\"USER\"",
",",
"default",
"=",
"cls",
".",
"defaults",
".",
"get",
"(",
"\"--stomp-user\"",
")",
",",
"help",
"=",
"\"Stomp user, default '%(default)s'\"",
",",
"type",
"=",
"str",
",",
"action",
"=",
"SetParameter",
",",
")",
"argparser",
".",
"add_argument",
"(",
"\"--stomp-pass\"",
",",
"metavar",
"=",
"\"PASS\"",
",",
"default",
"=",
"cls",
".",
"defaults",
".",
"get",
"(",
"\"--stomp-pass\"",
")",
",",
"help",
"=",
"\"Stomp password\"",
",",
"type",
"=",
"str",
",",
"action",
"=",
"SetParameter",
",",
")",
"argparser",
".",
"add_argument",
"(",
"\"--stomp-prfx\"",
",",
"metavar",
"=",
"\"PRE\"",
",",
"default",
"=",
"cls",
".",
"defaults",
".",
"get",
"(",
"\"--stomp-prfx\"",
")",
",",
"help",
"=",
"\"Stomp namespace prefix, default '%(default)s'\"",
",",
"type",
"=",
"str",
",",
"action",
"=",
"SetParameter",
",",
")",
"argparser",
".",
"add_argument",
"(",
"\"--stomp-conf\"",
",",
"metavar",
"=",
"\"CNF\"",
",",
"default",
"=",
"cls",
".",
"defaults",
".",
"get",
"(",
"\"--stomp-conf\"",
")",
",",
"help",
"=",
"\"Stomp configuration file containing connection information, disables default values\"",
",",
"type",
"=",
"str",
",",
"action",
"=",
"SetParameter",
",",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.