query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
The package build options . | def build_options ( self ) : if self . version . build_metadata : return set ( self . version . build_metadata . split ( '.' ) ) else : return set ( ) | 11,500 | https://github.com/pmuller/versions/blob/951bc3fd99b6a675190f11ee0752af1d7ff5b440/versions/packages.py#L84-L93 | [
"def",
"smooth_angle_channels",
"(",
"self",
",",
"channels",
")",
":",
"for",
"vertex",
"in",
"self",
".",
"vertices",
":",
"for",
"col",
"in",
"vertex",
".",
"meta",
"[",
"'rot_ind'",
"]",
":",
"if",
"col",
":",
"for",
"k",
"in",
"range",
"(",
"1",
",",
"channels",
".",
"shape",
"[",
"0",
"]",
")",
":",
"diff",
"=",
"channels",
"[",
"k",
",",
"col",
"]",
"-",
"channels",
"[",
"k",
"-",
"1",
",",
"col",
"]",
"if",
"abs",
"(",
"diff",
"+",
"360.",
")",
"<",
"abs",
"(",
"diff",
")",
":",
"channels",
"[",
"k",
":",
",",
"col",
"]",
"=",
"channels",
"[",
"k",
":",
",",
"col",
"]",
"+",
"360.",
"elif",
"abs",
"(",
"diff",
"-",
"360.",
")",
"<",
"abs",
"(",
"diff",
")",
":",
"channels",
"[",
"k",
":",
",",
"col",
"]",
"=",
"channels",
"[",
"k",
":",
",",
"col",
"]",
"-",
"360."
] |
Clears the selected text for this edit . | def clearSelection ( self ) : first = None editors = self . editors ( ) for editor in editors : if not editor . selectedText ( ) : continue first = first or editor editor . backspace ( ) for editor in editors : editor . setFocus ( ) if first : first . setFocus ( ) | 11,501 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xserialedit.py#L48-L65 | [
"def",
"calibrate_data",
"(",
"params",
",",
"raw_data",
",",
"calib_data",
")",
":",
"start",
"=",
"calib_data",
".",
"before",
"(",
"datetime",
".",
"max",
")",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"datetime",
".",
"min",
"start",
"=",
"raw_data",
".",
"after",
"(",
"start",
"+",
"SECOND",
")",
"if",
"start",
"is",
"None",
":",
"return",
"start",
"del",
"calib_data",
"[",
"start",
":",
"]",
"calibrator",
"=",
"Calib",
"(",
"params",
",",
"raw_data",
")",
"def",
"calibgen",
"(",
"inputdata",
")",
":",
"\"\"\"Internal generator function\"\"\"",
"count",
"=",
"0",
"for",
"data",
"in",
"inputdata",
":",
"idx",
"=",
"data",
"[",
"'idx'",
"]",
"count",
"+=",
"1",
"if",
"count",
"%",
"10000",
"==",
"0",
":",
"logger",
".",
"info",
"(",
"\"calib: %s\"",
",",
"idx",
".",
"isoformat",
"(",
"' '",
")",
")",
"elif",
"count",
"%",
"500",
"==",
"0",
":",
"logger",
".",
"debug",
"(",
"\"calib: %s\"",
",",
"idx",
".",
"isoformat",
"(",
"' '",
")",
")",
"for",
"key",
"in",
"(",
"'rain'",
",",
"'abs_pressure'",
",",
"'temp_in'",
")",
":",
"if",
"data",
"[",
"key",
"]",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"'Ignoring invalid data at %s'",
",",
"idx",
".",
"isoformat",
"(",
"' '",
")",
")",
"break",
"else",
":",
"yield",
"calibrator",
".",
"calib",
"(",
"data",
")",
"calib_data",
".",
"update",
"(",
"calibgen",
"(",
"raw_data",
"[",
"start",
":",
"]",
")",
")",
"return",
"start"
] |
Cuts the text from the serial to the clipboard . | def cut ( self ) : text = self . selectedText ( ) for editor in self . editors ( ) : editor . cut ( ) QtGui . QApplication . clipboard ( ) . setText ( text ) | 11,502 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xserialedit.py#L82-L90 | [
"def",
"complex_require_condition",
"(",
")",
":",
"print",
"(",
"\"Demonstrating complex require_condition example\"",
")",
"val",
"=",
"64",
"Buzz",
".",
"require_condition",
"(",
"is_even",
"(",
"val",
")",
",",
"'This condition should pass'",
")",
"val",
"=",
"81",
"Buzz",
".",
"require_condition",
"(",
"is_even",
"(",
"val",
")",
",",
"'Value {val} is not even'",
",",
"val",
"=",
"val",
")"
] |
Moves the cursor to the end of the previous editor | def goBack ( self ) : index = self . indexOf ( self . currentEditor ( ) ) if index == - 1 : return previous = self . editorAt ( index - 1 ) if previous : previous . setFocus ( ) previous . setCursorPosition ( self . sectionLength ( ) ) | 11,503 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xserialedit.py#L206-L217 | [
"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",
")"
] |
Moves the cursor to the beginning of the next editor . | def goForward ( self ) : index = self . indexOf ( self . currentEditor ( ) ) if index == - 1 : return next = self . editorAt ( index + 1 ) if next : next . setFocus ( ) next . setCursorPosition ( 0 ) | 11,504 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xserialedit.py#L219-L230 | [
"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",
")"
] |
Selects the text within all the editors . | def selectAll ( self ) : self . blockEditorHandling ( True ) for editor in self . editors ( ) : editor . selectAll ( ) self . blockEditorHandling ( False ) | 11,505 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xserialedit.py#L315-L322 | [
"def",
"_handle_order_args",
"(",
"self",
",",
"rison_args",
")",
":",
"order_column",
"=",
"rison_args",
".",
"get",
"(",
"API_ORDER_COLUMN_RIS_KEY",
",",
"\"\"",
")",
"order_direction",
"=",
"rison_args",
".",
"get",
"(",
"API_ORDER_DIRECTION_RIS_KEY",
",",
"\"\"",
")",
"if",
"not",
"order_column",
"and",
"self",
".",
"base_order",
":",
"order_column",
",",
"order_direction",
"=",
"self",
".",
"base_order",
"if",
"order_column",
"not",
"in",
"self",
".",
"order_columns",
":",
"return",
"\"\"",
",",
"\"\"",
"return",
"order_column",
",",
"order_direction"
] |
Enters maintenance mode | async def disable ( self , reason = None ) : params = { "enable" : True , "reason" : reason } response = await self . _api . put ( "/v1/agent/maintenance" , params = params ) return response . status == 200 | 11,506 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/agent_endpoint.py#L86-L96 | [
"def",
"tag_arxiv",
"(",
"line",
")",
":",
"def",
"tagger",
"(",
"match",
")",
":",
"groups",
"=",
"match",
".",
"groupdict",
"(",
")",
"if",
"match",
".",
"group",
"(",
"'suffix'",
")",
":",
"groups",
"[",
"'suffix'",
"]",
"=",
"' '",
"+",
"groups",
"[",
"'suffix'",
"]",
"else",
":",
"groups",
"[",
"'suffix'",
"]",
"=",
"''",
"return",
"u'<cds.REPORTNUMBER>arXiv:%(year)s'",
"u'%(month)s.%(num)s%(suffix)s'",
"u'</cds.REPORTNUMBER>'",
"%",
"groups",
"line",
"=",
"re_arxiv_5digits",
".",
"sub",
"(",
"tagger",
",",
"line",
")",
"line",
"=",
"re_arxiv",
".",
"sub",
"(",
"tagger",
",",
"line",
")",
"line",
"=",
"re_new_arxiv_5digits",
".",
"sub",
"(",
"tagger",
",",
"line",
")",
"line",
"=",
"re_new_arxiv",
".",
"sub",
"(",
"tagger",
",",
"line",
")",
"return",
"line"
] |
Resumes normal operation | async def enable ( self , reason = None ) : params = { "enable" : False , "reason" : reason } response = await self . _api . put ( "/v1/agent/maintenance" , params = params ) return response . status == 200 | 11,507 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/agent_endpoint.py#L98-L108 | [
"def",
"main",
"(",
")",
":",
"fmt",
"=",
"'svg'",
"title",
"=",
"\"\"",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"'-f'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-f'",
")",
"file",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"X",
"=",
"numpy",
".",
"loadtxt",
"(",
"file",
")",
"file",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"2",
"]",
"X2",
"=",
"numpy",
".",
"loadtxt",
"(",
"file",
")",
"# else:",
"# X=numpy.loadtxt(sys.stdin,dtype=numpy.float)",
"else",
":",
"print",
"(",
"'-f option required'",
")",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"'-fmt'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-fmt'",
")",
"fmt",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"if",
"'-t'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-t'",
")",
"title",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"CDF",
"=",
"{",
"'X'",
":",
"1",
"}",
"pmagplotlib",
".",
"plot_init",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"5",
",",
"5",
")",
"pmagplotlib",
".",
"plot_cdf",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"X",
",",
"''",
",",
"'r'",
",",
"''",
")",
"pmagplotlib",
".",
"plot_cdf",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"X2",
",",
"title",
",",
"'b'",
",",
"''",
")",
"D",
",",
"p",
"=",
"scipy",
".",
"stats",
".",
"ks_2samp",
"(",
"X",
",",
"X2",
")",
"if",
"p",
">=",
".05",
":",
"print",
"(",
"D",
",",
"p",
",",
"' not rejected at 95%'",
")",
"else",
":",
"print",
"(",
"D",
",",
"p",
",",
"' rejected at 95%'",
")",
"pmagplotlib",
".",
"draw_figs",
"(",
"CDF",
")",
"ans",
"=",
"input",
"(",
"'S[a]ve plot, <Return> to quit '",
")",
"if",
"ans",
"==",
"'a'",
":",
"files",
"=",
"{",
"'X'",
":",
"'CDF_.'",
"+",
"fmt",
"}",
"pmagplotlib",
".",
"save_plots",
"(",
"CDF",
",",
"files",
")"
] |
Parse an ISO datetime which Python does buggily . | def parse_datetime ( dt ) : d = datetime . strptime ( dt [ : - 1 ] , ISOFORMAT ) if dt [ - 1 : ] == 'Z' : return timezone ( 'utc' ) . localize ( d ) else : return d | 11,508 | https://github.com/fitnr/buoyant/blob/ef7a74f9ebd4774629508ccf2c9abb43aa0235c9/buoyant/timezone.py#L21-L28 | [
"def",
"_get_partition_info",
"(",
"storage_system",
",",
"device_path",
")",
":",
"try",
":",
"partition_infos",
"=",
"storage_system",
".",
"RetrieveDiskPartitionInfo",
"(",
"devicePath",
"=",
"[",
"device_path",
"]",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"log",
".",
"trace",
"(",
"'partition_info = %s'",
",",
"partition_infos",
"[",
"0",
"]",
")",
"return",
"partition_infos",
"[",
"0",
"]"
] |
Refreshes the records being loaded by this browser . | def refreshRecords ( self ) : table_type = self . tableType ( ) if ( not table_type ) : self . _records = RecordSet ( ) return False search = nativestring ( self . uiSearchTXT . text ( ) ) query = self . query ( ) . copy ( ) terms , search_query = Q . fromSearch ( search ) if ( search_query ) : query &= search_query self . _records = table_type . select ( where = query ) . search ( terms ) return True | 11,509 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbbrowserwidget.py#L476-L494 | [
"def",
"flow_orifice_vert",
"(",
"Diam",
",",
"Height",
",",
"RatioVCOrifice",
")",
":",
"#Checking input validity",
"ut",
".",
"check_range",
"(",
"[",
"RatioVCOrifice",
",",
"\"0-1\"",
",",
"\"VC orifice ratio\"",
"]",
")",
"if",
"Height",
">",
"-",
"Diam",
"/",
"2",
":",
"flow_vert",
"=",
"integrate",
".",
"quad",
"(",
"lambda",
"z",
":",
"(",
"Diam",
"*",
"np",
".",
"sin",
"(",
"np",
".",
"arccos",
"(",
"z",
"/",
"(",
"Diam",
"/",
"2",
")",
")",
")",
"*",
"np",
".",
"sqrt",
"(",
"Height",
"-",
"z",
")",
")",
",",
"-",
"Diam",
"/",
"2",
",",
"min",
"(",
"Diam",
"/",
"2",
",",
"Height",
")",
")",
"return",
"flow_vert",
"[",
"0",
"]",
"*",
"RatioVCOrifice",
"*",
"np",
".",
"sqrt",
"(",
"2",
"*",
"gravity",
".",
"magnitude",
")",
"else",
":",
"return",
"0"
] |
Joins together the queries from the fixed system the search and the query builder to generate a query for the browser to display . | def refreshResults ( self ) : if ( self . currentMode ( ) == XOrbBrowserWidget . Mode . Detail ) : self . refreshDetails ( ) elif ( self . currentMode ( ) == XOrbBrowserWidget . Mode . Card ) : self . refreshCards ( ) else : self . refreshThumbnails ( ) | 11,510 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbbrowserwidget.py#L496-L506 | [
"def",
"ack",
"(",
"self",
",",
"msg",
")",
":",
"message_id",
"=",
"msg",
"[",
"'headers'",
"]",
"[",
"'message-id'",
"]",
"subscription",
"=",
"msg",
"[",
"'headers'",
"]",
"[",
"'subscription'",
"]",
"transaction_id",
"=",
"None",
"if",
"'transaction-id'",
"in",
"msg",
"[",
"'headers'",
"]",
":",
"transaction_id",
"=",
"msg",
"[",
"'headers'",
"]",
"[",
"'transaction-id'",
"]",
"# print \"acknowledging message id <%s>.\" % message_id",
"return",
"ack",
"(",
"message_id",
",",
"subscription",
",",
"transaction_id",
")"
] |
Refreshes the results for the cards view of the browser . | def refreshCards ( self ) : cards = self . cardWidget ( ) factory = self . factory ( ) self . setUpdatesEnabled ( False ) self . blockSignals ( True ) cards . setUpdatesEnabled ( False ) cards . blockSignals ( True ) cards . clear ( ) QApplication . instance ( ) . processEvents ( ) if ( self . isGroupingActive ( ) ) : grouping = self . records ( ) . grouped ( ) for groupName , records in sorted ( grouping . items ( ) ) : self . _loadCardGroup ( groupName , records , cards ) else : for record in self . records ( ) : widget = factory . createCard ( cards , record ) if ( not widget ) : continue widget . adjustSize ( ) # create the card item
item = QTreeWidgetItem ( cards ) item . setSizeHint ( 0 , QSize ( 0 , widget . height ( ) ) ) cards . setItemWidget ( item , 0 , widget ) cards . setUpdatesEnabled ( True ) cards . blockSignals ( False ) self . setUpdatesEnabled ( True ) self . blockSignals ( False ) | 11,511 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbbrowserwidget.py#L508-L546 | [
"def",
"enable_logging",
"(",
"self",
",",
"bucket_name",
",",
"object_prefix",
"=",
"\"\"",
")",
":",
"info",
"=",
"{",
"\"logBucket\"",
":",
"bucket_name",
",",
"\"logObjectPrefix\"",
":",
"object_prefix",
"}",
"self",
".",
"_patch_property",
"(",
"\"logging\"",
",",
"info",
")"
] |
Refreshes the results for the details view of the browser . | def refreshDetails ( self ) : # start off by filtering based on the group selection
tree = self . uiRecordsTREE tree . blockSignals ( True ) tree . setRecordSet ( self . records ( ) ) tree . blockSignals ( False ) | 11,512 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbbrowserwidget.py#L548-L556 | [
"def",
"publish",
"(",
"self",
",",
"cat",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"request",
".",
"publish_cat1",
"(",
"\"POST\"",
",",
"self",
".",
"con",
",",
"self",
".",
"token",
",",
"cat",
",",
"kwargs",
")",
"return",
"res"
] |
Refreshes the thumbnails view of the browser . | def refreshThumbnails ( self ) : # clear existing items
widget = self . thumbnailWidget ( ) widget . setUpdatesEnabled ( False ) widget . blockSignals ( True ) widget . clear ( ) widget . setIconSize ( self . thumbnailSize ( ) ) factory = self . factory ( ) # load grouped thumbnails (only allow 1 level of grouping)
if ( self . isGroupingActive ( ) ) : grouping = self . records ( ) . grouped ( ) for groupName , records in sorted ( grouping . items ( ) ) : self . _loadThumbnailGroup ( groupName , records ) # load ungrouped thumbnails
else : # load the records into the thumbnail
for record in self . records ( ) : thumbnail = factory . thumbnail ( record ) text = factory . thumbnailText ( record ) RecordListWidgetItem ( thumbnail , text , record , widget ) widget . setUpdatesEnabled ( True ) widget . blockSignals ( False ) | 11,513 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbbrowserwidget.py#L558-L587 | [
"def",
"_bind_topics",
"(",
"self",
",",
"topics",
")",
":",
"# FIXME: Allow for these subscriptions to fail and clean up the previous ones",
"# so that this function is atomic",
"self",
".",
"client",
".",
"subscribe",
"(",
"topics",
".",
"status",
",",
"self",
".",
"_on_status_message",
")",
"self",
".",
"client",
".",
"subscribe",
"(",
"topics",
".",
"tracing",
",",
"self",
".",
"_on_trace",
")",
"self",
".",
"client",
".",
"subscribe",
"(",
"topics",
".",
"streaming",
",",
"self",
".",
"_on_report",
")",
"self",
".",
"client",
".",
"subscribe",
"(",
"topics",
".",
"response",
",",
"self",
".",
"_on_response_message",
")"
] |
Displays the group menu to the user for modification . | def showGroupMenu ( self ) : group_active = self . isGroupingActive ( ) group_by = self . groupBy ( ) menu = XMenu ( self ) menu . setTitle ( 'Grouping Options' ) menu . setShowTitle ( True ) menu . addAction ( 'Edit Advanced Grouping' ) menu . addSeparator ( ) action = menu . addAction ( 'No Grouping' ) action . setCheckable ( True ) action . setChecked ( not group_active ) action = menu . addAction ( 'Advanced' ) action . setCheckable ( True ) action . setChecked ( group_by == self . GroupByAdvancedKey and group_active ) if ( group_by == self . GroupByAdvancedKey ) : font = action . font ( ) font . setBold ( True ) action . setFont ( font ) menu . addSeparator ( ) # add dynamic options from the table schema
tableType = self . tableType ( ) if ( tableType ) : columns = tableType . schema ( ) . columns ( ) columns . sort ( key = lambda x : x . displayName ( ) ) for column in columns : action = menu . addAction ( column . displayName ( ) ) action . setCheckable ( True ) action . setChecked ( group_by == column . displayName ( ) and group_active ) if ( column . displayName ( ) == group_by ) : font = action . font ( ) font . setBold ( True ) action . setFont ( font ) point = QPoint ( 0 , self . uiGroupOptionsBTN . height ( ) ) action = menu . exec_ ( self . uiGroupOptionsBTN . mapToGlobal ( point ) ) if ( not action ) : return elif ( action . text ( ) == 'Edit Advanced Grouping' ) : print 'edit advanced grouping options' elif ( action . text ( ) == 'No Grouping' ) : self . setGroupingActive ( False ) elif ( action . text ( ) == 'Advanced' ) : self . uiGroupBTN . blockSignals ( True ) self . setGroupBy ( self . GroupByAdvancedKey ) self . setGroupingActive ( True ) self . uiGroupBTN . blockSignals ( False ) self . refreshResults ( ) else : self . uiGroupBTN . blockSignals ( True ) self . setGroupBy ( nativestring ( action . text ( ) ) ) self . setGroupingActive ( True ) self . uiGroupBTN . blockSignals ( False ) self . refreshResults ( ) | 11,514 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbbrowserwidget/xorbbrowserwidget.py#L743-L811 | [
"async",
"def",
"dump_blob",
"(",
"writer",
",",
"elem",
",",
"elem_type",
",",
"params",
"=",
"None",
")",
":",
"elem_is_blob",
"=",
"isinstance",
"(",
"elem",
",",
"x",
".",
"BlobType",
")",
"data",
"=",
"bytes",
"(",
"getattr",
"(",
"elem",
",",
"x",
".",
"BlobType",
".",
"DATA_ATTR",
")",
"if",
"elem_is_blob",
"else",
"elem",
")",
"await",
"dump_varint",
"(",
"writer",
",",
"len",
"(",
"elem",
")",
")",
"await",
"writer",
".",
"awrite",
"(",
"data",
")"
] |
This function returns a dict containing default settings | def get_settings ( ) : s = getattr ( settings , 'CLAMAV_UPLOAD' , { } ) s = { 'CONTENT_TYPE_CHECK_ENABLED' : s . get ( 'CONTENT_TYPE_CHECK_ENABLED' , False ) , # LAST_HANDLER is not a user configurable option; we return # it with the settings dict simply because it's convenient. 'LAST_HANDLER' : getattr ( settings , 'FILE_UPLOAD_HANDLERS' ) [ - 1 ] } return s | 11,515 | https://github.com/musashiXXX/django-clamav-upload/blob/00ea8baaa127d98ffb0919aaa2c3aeec9bb58fd5/clamav_upload/__init__.py#L21-L32 | [
"def",
"center_cell_text",
"(",
"cell",
")",
":",
"lines",
"=",
"cell",
".",
"text",
".",
"split",
"(",
"'\\n'",
")",
"cell_width",
"=",
"len",
"(",
"lines",
"[",
"0",
"]",
")",
"-",
"2",
"truncated_lines",
"=",
"[",
"''",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"lines",
")",
"-",
"1",
")",
":",
"truncated",
"=",
"lines",
"[",
"i",
"]",
"[",
"2",
":",
"len",
"(",
"lines",
"[",
"i",
"]",
")",
"-",
"2",
"]",
".",
"rstrip",
"(",
")",
"truncated_lines",
".",
"append",
"(",
"truncated",
")",
"truncated_lines",
".",
"append",
"(",
"''",
")",
"max_line_length",
"=",
"get_longest_line_length",
"(",
"'\\n'",
".",
"join",
"(",
"truncated_lines",
")",
")",
"remainder",
"=",
"cell_width",
"-",
"max_line_length",
"left_width",
"=",
"math",
".",
"floor",
"(",
"remainder",
"/",
"2",
")",
"left_space",
"=",
"left_width",
"*",
"' '",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"truncated_lines",
")",
")",
":",
"truncated_lines",
"[",
"i",
"]",
"=",
"left_space",
"+",
"truncated_lines",
"[",
"i",
"]",
"right_width",
"=",
"cell_width",
"-",
"len",
"(",
"truncated_lines",
"[",
"i",
"]",
")",
"truncated_lines",
"[",
"i",
"]",
"+=",
"right_width",
"*",
"' '",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"lines",
")",
"-",
"1",
")",
":",
"lines",
"[",
"i",
"]",
"=",
"''",
".",
"join",
"(",
"[",
"lines",
"[",
"i",
"]",
"[",
"0",
"]",
",",
"truncated_lines",
"[",
"i",
"]",
",",
"lines",
"[",
"i",
"]",
"[",
"-",
"1",
"]",
"]",
")",
"cell",
".",
"text",
"=",
"'\\n'",
".",
"join",
"(",
"lines",
")",
"return",
"cell"
] |
Clears the settings for this XML format . | def clear ( self ) : self . _xroot = ElementTree . Element ( 'settings' ) self . _xroot . set ( 'version' , '1.0' ) self . _xstack = [ self . _xroot ] | 11,516 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xsettings.py#L119-L125 | [
"def",
"seed",
"(",
"vault_client",
",",
"opt",
")",
":",
"if",
"opt",
".",
"thaw_from",
":",
"opt",
".",
"secrets",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"'aomi-thaw'",
")",
"auto_thaw",
"(",
"vault_client",
",",
"opt",
")",
"Context",
".",
"load",
"(",
"get_secretfile",
"(",
"opt",
")",
",",
"opt",
")",
".",
"fetch",
"(",
"vault_client",
")",
".",
"sync",
"(",
"vault_client",
",",
"opt",
")",
"if",
"opt",
".",
"thaw_from",
":",
"rmtree",
"(",
"opt",
".",
"secrets",
")"
] |
Clears out all the settings for this instance . | def clear ( self ) : if self . _customFormat : self . _customFormat . clear ( ) else : super ( XSettings , self ) . clear ( ) | 11,517 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xsettings.py#L519-L526 | [
"def",
"loadIntoTextureD3D11_Async",
"(",
"self",
",",
"textureId",
",",
"pDstTexture",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"loadIntoTextureD3D11_Async",
"result",
"=",
"fn",
"(",
"textureId",
",",
"pDstTexture",
")",
"return",
"result"
] |
Ends the current group of xml data . | def endGroup ( self ) : if self . _customFormat : self . _customFormat . endGroup ( ) else : super ( XSettings , self ) . endGroup ( ) | 11,518 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xsettings.py#L548-L555 | [
"def",
"send_email_sns",
"(",
"sender",
",",
"subject",
",",
"message",
",",
"topic_ARN",
",",
"image_png",
")",
":",
"from",
"boto3",
"import",
"resource",
"as",
"boto3_resource",
"sns",
"=",
"boto3_resource",
"(",
"'sns'",
")",
"topic",
"=",
"sns",
".",
"Topic",
"(",
"topic_ARN",
"[",
"0",
"]",
")",
"# Subject is max 100 chars",
"if",
"len",
"(",
"subject",
")",
">",
"100",
":",
"subject",
"=",
"subject",
"[",
"0",
":",
"48",
"]",
"+",
"'...'",
"+",
"subject",
"[",
"-",
"49",
":",
"]",
"response",
"=",
"topic",
".",
"publish",
"(",
"Subject",
"=",
"subject",
",",
"Message",
"=",
"message",
")",
"logger",
".",
"debug",
"(",
"(",
"\"Message sent to SNS.\\nMessageId: {},\\nRequestId: {},\\n\"",
"\"HTTPSStatusCode: {}\"",
")",
".",
"format",
"(",
"response",
"[",
"'MessageId'",
"]",
",",
"response",
"[",
"'ResponseMetadata'",
"]",
"[",
"'RequestId'",
"]",
",",
"response",
"[",
"'ResponseMetadata'",
"]",
"[",
"'HTTPStatusCode'",
"]",
")",
")"
] |
Loads the settings from disk for this XSettings object if it is a custom format . | def load ( self ) : # load the custom format
if self . _customFormat and os . path . exists ( self . fileName ( ) ) : self . _customFormat . load ( self . fileName ( ) ) | 11,519 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xsettings.py#L557-L563 | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"self",
".",
"_timeout",
"with",
"self",
".",
"_cond",
":",
"self",
".",
"_enter",
"(",
")",
"# Block while the barrier drains.",
"index",
"=",
"self",
".",
"_count",
"self",
".",
"_count",
"+=",
"1",
"try",
":",
"if",
"index",
"+",
"1",
"==",
"self",
".",
"_parties",
":",
"# We release the barrier",
"self",
".",
"_release",
"(",
")",
"else",
":",
"# We wait until someone releases us",
"self",
".",
"_wait",
"(",
"timeout",
")",
"return",
"index",
"finally",
":",
"self",
".",
"_count",
"-=",
"1",
"# Wake up any threads waiting for barrier to drain.",
"self",
".",
"_exit",
"(",
")"
] |
Syncs the information for this settings out to the file system . | def sync ( self ) : if self . _customFormat : self . _customFormat . save ( self . fileName ( ) ) else : super ( XSettings , self ) . sync ( ) | 11,520 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xsettings.py#L608-L615 | [
"def",
"_get_block_result",
"(",
"chars_a",
",",
"chars_b",
")",
":",
"logger",
".",
"debug",
"(",
"'_get_block_result(%s, %s)'",
",",
"chars_a",
",",
"chars_b",
")",
"first_is_digit",
"=",
"chars_a",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"pop_func",
"=",
"_pop_digits",
"if",
"first_is_digit",
"else",
"_pop_letters",
"return_if_no_b",
"=",
"a_newer",
"if",
"first_is_digit",
"else",
"b_newer",
"block_a",
",",
"block_b",
"=",
"pop_func",
"(",
"chars_a",
")",
",",
"pop_func",
"(",
"chars_b",
")",
"if",
"len",
"(",
"block_b",
")",
"==",
"0",
":",
"logger",
".",
"debug",
"(",
"'blocks are equal'",
")",
"return",
"return_if_no_b",
"return",
"_compare_blocks",
"(",
"block_a",
",",
"block_b",
")"
] |
Clears out the widgets for this query builder . | def clear ( self ) : layout = self . _entryWidget . layout ( ) for i in range ( layout . count ( ) - 1 ) : widget = layout . itemAt ( i ) . widget ( ) widget . close ( ) | 11,521 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquerycontainer.py#L83-L90 | [
"def",
"_ApplySudsJurkoSendPatch",
"(",
"self",
")",
":",
"def",
"GetInflateStream",
"(",
"msg",
")",
":",
"stream",
"=",
"io",
".",
"BytesIO",
"(",
")",
"stream",
".",
"write",
"(",
"msg",
")",
"stream",
".",
"flush",
"(",
")",
"stream",
".",
"seek",
"(",
"0",
")",
"return",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"stream",
",",
"mode",
"=",
"'rb'",
")",
"def",
"PatchedHttpTransportSend",
"(",
"self",
",",
"request",
")",
":",
"\"\"\"Patch for HttpTransport.send to enable gzip compression.\"\"\"",
"msg",
"=",
"request",
".",
"message",
"http_transport",
"=",
"suds",
".",
"transport",
".",
"http",
".",
"HttpTransport",
"url",
"=",
"http_transport",
".",
"_HttpTransport__get_request_url",
"(",
"request",
")",
"headers",
"=",
"request",
".",
"headers",
"u2request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
",",
"msg",
",",
"headers",
")",
"self",
".",
"addcookies",
"(",
"u2request",
")",
"self",
".",
"proxy",
"=",
"self",
".",
"options",
".",
"proxy",
"request",
".",
"headers",
".",
"update",
"(",
"u2request",
".",
"headers",
")",
"suds",
".",
"transport",
".",
"http",
".",
"log",
".",
"debug",
"(",
"'sending:\\n%s'",
",",
"request",
")",
"try",
":",
"fp",
"=",
"self",
".",
"u2open",
"(",
"u2request",
")",
"except",
"urllib2",
".",
"HTTPError",
",",
"e",
":",
"if",
"e",
".",
"code",
"in",
"(",
"202",
",",
"204",
")",
":",
"return",
"None",
"else",
":",
"if",
"e",
".",
"headers",
".",
"get",
"(",
"'content-encoding'",
")",
"==",
"'gzip'",
":",
"# If gzip encoding is used, decompress here.",
"# Need to read and recreate a stream because urllib result objects",
"# don't fully implement the file-like API",
"e",
".",
"fp",
"=",
"GetInflateStream",
"(",
"e",
".",
"fp",
".",
"read",
"(",
")",
")",
"raise",
"suds",
".",
"transport",
".",
"TransportError",
"(",
"e",
".",
"msg",
",",
"e",
".",
"code",
",",
"e",
".",
"fp",
")",
"self",
".",
"getcookies",
"(",
"fp",
",",
"u2request",
")",
"# Note: Python 2 returns httplib.HTTPMessage, and Python 3 returns",
"# http.client.HTTPMessage, which differ slightly.",
"headers",
"=",
"(",
"fp",
".",
"headers",
".",
"dict",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
"else",
"fp",
".",
"headers",
")",
"result",
"=",
"suds",
".",
"transport",
".",
"Reply",
"(",
"200",
",",
"headers",
",",
"fp",
".",
"read",
"(",
")",
")",
"if",
"result",
".",
"headers",
".",
"get",
"(",
"'content-encoding'",
")",
"==",
"'gzip'",
":",
"# If gzip encoding is used, decompress here.",
"result",
".",
"message",
"=",
"GetInflateStream",
"(",
"result",
".",
"message",
")",
".",
"read",
"(",
")",
"suds",
".",
"transport",
".",
"http",
".",
"log",
".",
"debug",
"(",
"'received:\\n%s'",
",",
"result",
")",
"return",
"result",
"suds",
".",
"transport",
".",
"http",
".",
"HttpTransport",
".",
"send",
"=",
"PatchedHttpTransportSend"
] |
Moves the current query down one entry . | def moveDown ( self , entry ) : if not entry : return entries = self . entries ( ) next = entries [ entries . index ( entry ) + 1 ] entry_q = entry . query ( ) next_q = next . query ( ) next . setQuery ( entry_q ) entry . setQuery ( next_q ) | 11,522 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbquerywidget/xorbquerycontainer.py#L168-L182 | [
"def",
"create_api_call",
"(",
"func",
",",
"settings",
")",
":",
"def",
"base_caller",
"(",
"api_call",
",",
"_",
",",
"*",
"args",
")",
":",
"\"\"\"Simply call api_call and ignore settings.\"\"\"",
"return",
"api_call",
"(",
"*",
"args",
")",
"def",
"inner",
"(",
"request",
",",
"options",
"=",
"None",
")",
":",
"\"\"\"Invoke with the actual settings.\"\"\"",
"this_options",
"=",
"_merge_options_metadata",
"(",
"options",
",",
"settings",
")",
"this_settings",
"=",
"settings",
".",
"merge",
"(",
"this_options",
")",
"if",
"this_settings",
".",
"retry",
"and",
"this_settings",
".",
"retry",
".",
"retry_codes",
":",
"api_call",
"=",
"gax",
".",
"retry",
".",
"retryable",
"(",
"func",
",",
"this_settings",
".",
"retry",
",",
"*",
"*",
"this_settings",
".",
"kwargs",
")",
"else",
":",
"api_call",
"=",
"gax",
".",
"retry",
".",
"add_timeout_arg",
"(",
"func",
",",
"this_settings",
".",
"timeout",
",",
"*",
"*",
"this_settings",
".",
"kwargs",
")",
"api_call",
"=",
"_catch_errors",
"(",
"api_call",
",",
"gax",
".",
"config",
".",
"API_ERRORS",
")",
"return",
"api_caller",
"(",
"api_call",
",",
"this_settings",
",",
"request",
")",
"if",
"settings",
".",
"page_descriptor",
":",
"if",
"settings",
".",
"bundler",
"and",
"settings",
".",
"bundle_descriptor",
":",
"raise",
"ValueError",
"(",
"'The API call has incompatible settings: '",
"'bundling and page streaming'",
")",
"api_caller",
"=",
"_page_streamable",
"(",
"settings",
".",
"page_descriptor",
")",
"elif",
"settings",
".",
"bundler",
"and",
"settings",
".",
"bundle_descriptor",
":",
"api_caller",
"=",
"_bundleable",
"(",
"settings",
".",
"bundle_descriptor",
")",
"else",
":",
"api_caller",
"=",
"base_caller",
"return",
"inner"
] |
Matches the tree selection to the views selection . | def _selectTree ( self ) : self . uiGanttTREE . blockSignals ( True ) self . uiGanttTREE . clearSelection ( ) for item in self . uiGanttVIEW . scene ( ) . selectedItems ( ) : item . treeItem ( ) . setSelected ( True ) self . uiGanttTREE . blockSignals ( False ) | 11,523 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidget.py#L158-L166 | [
"def",
"private_messenger",
"(",
")",
":",
"while",
"__websocket_server_running__",
":",
"pipein",
"=",
"open",
"(",
"PRIVATE_PIPE",
",",
"'r'",
")",
"line",
"=",
"pipein",
".",
"readline",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"if",
"line",
"!=",
"''",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"line",
")",
"WebSocketHandler",
".",
"send_private_message",
"(",
"user_id",
"=",
"message",
"[",
"'user_id'",
"]",
",",
"message",
"=",
"message",
")",
"print",
"line",
"remaining_lines",
"=",
"pipein",
".",
"read",
"(",
")",
"pipein",
".",
"close",
"(",
")",
"pipeout",
"=",
"open",
"(",
"PRIVATE_PIPE",
",",
"'w'",
")",
"pipeout",
".",
"write",
"(",
"remaining_lines",
")",
"pipeout",
".",
"close",
"(",
")",
"else",
":",
"pipein",
".",
"close",
"(",
")",
"time",
".",
"sleep",
"(",
"0.05",
")"
] |
Matches the view selection to the trees selection . | def _selectView ( self ) : scene = self . uiGanttVIEW . scene ( ) scene . blockSignals ( True ) scene . clearSelection ( ) for item in self . uiGanttTREE . selectedItems ( ) : item . viewItem ( ) . setSelected ( True ) scene . blockSignals ( False ) curr_item = self . uiGanttTREE . currentItem ( ) vitem = curr_item . viewItem ( ) if vitem : self . uiGanttVIEW . centerOn ( vitem ) | 11,524 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidget.py#L168-L183 | [
"def",
"get_community_badge_progress",
"(",
"self",
",",
"steamID",
",",
"badgeID",
",",
"format",
"=",
"None",
")",
":",
"parameters",
"=",
"{",
"'steamid'",
":",
"steamID",
",",
"'badgeid'",
":",
"badgeID",
"}",
"if",
"format",
"is",
"not",
"None",
":",
"parameters",
"[",
"'format'",
"]",
"=",
"format",
"url",
"=",
"self",
".",
"create_request_url",
"(",
"self",
".",
"interface",
",",
"'GetCommunityBadgeProgress'",
",",
"1",
",",
"parameters",
")",
"data",
"=",
"self",
".",
"retrieve_request",
"(",
"url",
")",
"return",
"self",
".",
"return_data",
"(",
"data",
",",
"format",
"=",
"format",
")"
] |
Updates the view rect to match the current tree value . | def _updateViewRect ( self ) : if not self . updatesEnabled ( ) : return header_h = self . _cellHeight * 2 rect = self . uiGanttVIEW . scene ( ) . sceneRect ( ) sbar_max = self . uiGanttTREE . verticalScrollBar ( ) . maximum ( ) sbar_max += self . uiGanttTREE . viewport ( ) . height ( ) + header_h widget_max = self . uiGanttVIEW . height ( ) widget_max -= ( self . uiGanttVIEW . horizontalScrollBar ( ) . height ( ) + 10 ) rect . setHeight ( max ( widget_max , sbar_max ) ) self . uiGanttVIEW . scene ( ) . setSceneRect ( rect ) | 11,525 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidget.py#L185-L200 | [
"def",
"disassociate_address",
"(",
"self",
",",
"public_ip",
"=",
"None",
",",
"association_id",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"public_ip",
"is",
"not",
"None",
":",
"params",
"[",
"'PublicIp'",
"]",
"=",
"public_ip",
"elif",
"association_id",
"is",
"not",
"None",
":",
"params",
"[",
"'AssociationId'",
"]",
"=",
"association_id",
"return",
"self",
".",
"get_status",
"(",
"'DisassociateAddress'",
",",
"params",
",",
"verb",
"=",
"'POST'",
")"
] |
Syncs all the items to the view . | def syncView ( self ) : if not self . updatesEnabled ( ) : return for item in self . topLevelItems ( ) : try : item . syncView ( recursive = True ) except AttributeError : continue | 11,526 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xganttwidget/xganttwidget.py#L627-L638 | [
"def",
"insert_recording",
"(",
"hw",
")",
":",
"mysql",
"=",
"utils",
".",
"get_mysql_cfg",
"(",
")",
"connection",
"=",
"pymysql",
".",
"connect",
"(",
"host",
"=",
"mysql",
"[",
"'host'",
"]",
",",
"user",
"=",
"mysql",
"[",
"'user'",
"]",
",",
"passwd",
"=",
"mysql",
"[",
"'passwd'",
"]",
",",
"db",
"=",
"mysql",
"[",
"'db'",
"]",
",",
"charset",
"=",
"'utf8mb4'",
",",
"cursorclass",
"=",
"pymysql",
".",
"cursors",
".",
"DictCursor",
")",
"try",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"sql",
"=",
"(",
"\"INSERT INTO `wm_raw_draw_data` (\"",
"\"`user_id`, \"",
"\"`data`, \"",
"\"`md5data`, \"",
"\"`creation_date`, \"",
"\"`device_type`, \"",
"\"`accepted_formula_id`, \"",
"\"`secret`, \"",
"\"`ip`, \"",
"\"`segmentation`, \"",
"\"`internal_id`, \"",
"\"`description` \"",
"\") VALUES (%s, %s, MD5(data), \"",
"\"%s, %s, %s, %s, %s, %s, %s, %s);\"",
")",
"data",
"=",
"(",
"hw",
".",
"user_id",
",",
"hw",
".",
"raw_data_json",
",",
"getattr",
"(",
"hw",
",",
"'creation_date'",
",",
"None",
")",
",",
"getattr",
"(",
"hw",
",",
"'device_type'",
",",
"''",
")",
",",
"getattr",
"(",
"hw",
",",
"'formula_id'",
",",
"None",
")",
",",
"getattr",
"(",
"hw",
",",
"'secret'",
",",
"''",
")",
",",
"getattr",
"(",
"hw",
",",
"'ip'",
",",
"None",
")",
",",
"str",
"(",
"getattr",
"(",
"hw",
",",
"'segmentation'",
",",
"''",
")",
")",
",",
"getattr",
"(",
"hw",
",",
"'internal_id'",
",",
"''",
")",
",",
"getattr",
"(",
"hw",
",",
"'description'",
",",
"''",
")",
")",
"cursor",
".",
"execute",
"(",
"sql",
",",
"data",
")",
"connection",
".",
"commit",
"(",
")",
"for",
"symbol_id",
",",
"strokes",
"in",
"zip",
"(",
"hw",
".",
"symbol_stream",
",",
"hw",
".",
"segmentation",
")",
":",
"insert_symbol_mapping",
"(",
"cursor",
".",
"lastrowid",
",",
"symbol_id",
",",
"hw",
".",
"user_id",
",",
"strokes",
")",
"logging",
".",
"info",
"(",
"\"Insert raw data.\"",
")",
"except",
"pymysql",
".",
"err",
".",
"IntegrityError",
"as",
"e",
":",
"print",
"(",
"\"Error: {} (can probably be ignored)\"",
".",
"format",
"(",
"e",
")",
")"
] |
Return the full file path of a resource of a package . | def get_data_path ( package , resource ) : # type: (str, str) -> str loader = pkgutil . get_loader ( package ) if loader is None or not hasattr ( loader , 'get_data' ) : raise PackageResourceError ( "Failed to load package: '{0}'" . format ( package ) ) mod = sys . modules . get ( package ) or loader . load_module ( package ) if mod is None or not hasattr ( mod , '__file__' ) : raise PackageResourceError ( "Failed to load module: '{0}'" . format ( package ) ) parts = resource . split ( '/' ) parts . insert ( 0 , os . path . dirname ( mod . __file__ ) ) resource_name = os . path . join ( * parts ) return resource_name | 11,527 | https://github.com/tueda/python-form/blob/1e5a8464f7a7a6cbbb32411fc2ea3615fd48334b/form/datapath.py#L11-L25 | [
"def",
"hide",
"(",
"self",
",",
"selections",
")",
":",
"if",
"'atoms'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'atoms'",
"]",
"=",
"selections",
"[",
"'atoms'",
"]",
"self",
".",
"on_atom_hidden_changed",
"(",
")",
"if",
"'bonds'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'bonds'",
"]",
"=",
"selections",
"[",
"'bonds'",
"]",
"self",
".",
"on_bond_hidden_changed",
"(",
")",
"if",
"'box'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'box'",
"]",
"=",
"box_s",
"=",
"selections",
"[",
"'box'",
"]",
"if",
"box_s",
".",
"mask",
"[",
"0",
"]",
":",
"if",
"self",
".",
"viewer",
".",
"has_renderer",
"(",
"self",
".",
"box_renderer",
")",
":",
"self",
".",
"viewer",
".",
"remove_renderer",
"(",
"self",
".",
"box_renderer",
")",
"else",
":",
"if",
"not",
"self",
".",
"viewer",
".",
"has_renderer",
"(",
"self",
".",
"box_renderer",
")",
":",
"self",
".",
"viewer",
".",
"add_renderer",
"(",
"self",
".",
"box_renderer",
")",
"return",
"self",
".",
"hidden_state"
] |
Scrolls to the end for this console edit . | def scrollToEnd ( self ) : vsbar = self . verticalScrollBar ( ) vsbar . setValue ( vsbar . maximum ( ) ) hbar = self . horizontalScrollBar ( ) hbar . setValue ( 0 ) | 11,528 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xloggerwidget/xloggerwidget.py#L423-L431 | [
"def",
"find_partition_multiplex",
"(",
"graphs",
",",
"partition_type",
",",
"*",
"*",
"kwargs",
")",
":",
"n_layers",
"=",
"len",
"(",
"graphs",
")",
"partitions",
"=",
"[",
"]",
"layer_weights",
"=",
"[",
"1",
"]",
"*",
"n_layers",
"for",
"graph",
"in",
"graphs",
":",
"partitions",
".",
"append",
"(",
"partition_type",
"(",
"graph",
",",
"*",
"*",
"kwargs",
")",
")",
"optimiser",
"=",
"Optimiser",
"(",
")",
"improvement",
"=",
"optimiser",
".",
"optimise_partition_multiplex",
"(",
"partitions",
",",
"layer_weights",
")",
"return",
"partitions",
"[",
"0",
"]",
".",
"membership",
",",
"improvement"
] |
Assigns the query from the query widget to the edit . | def assignQuery ( self ) : self . uiRecordTREE . setQuery ( self . _queryWidget . query ( ) , autoRefresh = True ) | 11,529 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbgridedit/xorbgridedit.py#L115-L119 | [
"def",
"fingerprint",
"(",
"self",
",",
"option_type",
",",
"option_val",
")",
":",
"if",
"option_val",
"is",
"None",
":",
"return",
"None",
"# Wrapping all other values in a list here allows us to easily handle single-valued and",
"# list-valued options uniformly. For non-list-valued options, this will be a singleton list",
"# (with the exception of dict, which is not modified). This dict exception works because we do",
"# not currently have any \"list of dict\" type, so there is no ambiguity.",
"if",
"not",
"isinstance",
"(",
"option_val",
",",
"(",
"list",
",",
"tuple",
",",
"dict",
")",
")",
":",
"option_val",
"=",
"[",
"option_val",
"]",
"if",
"option_type",
"==",
"target_option",
":",
"return",
"self",
".",
"_fingerprint_target_specs",
"(",
"option_val",
")",
"elif",
"option_type",
"==",
"dir_option",
":",
"return",
"self",
".",
"_fingerprint_dirs",
"(",
"option_val",
")",
"elif",
"option_type",
"==",
"file_option",
":",
"return",
"self",
".",
"_fingerprint_files",
"(",
"option_val",
")",
"elif",
"option_type",
"==",
"dict_with_files_option",
":",
"return",
"self",
".",
"_fingerprint_dict_with_files",
"(",
"option_val",
")",
"else",
":",
"return",
"self",
".",
"_fingerprint_primitives",
"(",
"option_val",
")"
] |
Commits changes stored in the interface to the database . | def refresh ( self ) : table = self . tableType ( ) if table : table . markTableCacheExpired ( ) self . uiRecordTREE . searchRecords ( self . uiSearchTXT . text ( ) ) | 11,530 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbgridedit/xorbgridedit.py#L186-L194 | [
"def",
"permission_denied",
"(",
"request",
",",
"template_name",
"=",
"None",
",",
"extra_context",
"=",
"None",
")",
":",
"if",
"template_name",
"is",
"None",
":",
"template_name",
"=",
"(",
"'403.html'",
",",
"'authority/403.html'",
")",
"context",
"=",
"{",
"'request_path'",
":",
"request",
".",
"path",
",",
"}",
"if",
"extra_context",
":",
"context",
".",
"update",
"(",
"extra_context",
")",
"return",
"HttpResponseForbidden",
"(",
"loader",
".",
"render_to_string",
"(",
"template_name",
"=",
"template_name",
",",
"context",
"=",
"context",
",",
"request",
"=",
"request",
",",
")",
")"
] |
Return a configuration dict from a URL | def parse ( self , url ) : parsed_url = urlparse . urlparse ( url ) try : default_config = self . CONFIG [ parsed_url . scheme ] except KeyError : raise ValueError ( 'unrecognised URL scheme for {}: {}' . format ( self . __class__ . __name__ , url ) ) handler = self . get_handler_for_scheme ( parsed_url . scheme ) config = copy . deepcopy ( default_config ) return handler ( parsed_url , config ) | 11,531 | https://github.com/evansd/django-envsettings/blob/541932af261d5369f211f836a238dc020ee316e8/envsettings/base.py#L91-L104 | [
"def",
"chunks",
"(",
"self",
")",
":",
"chunks",
"=",
"{",
"}",
"for",
"v",
"in",
"self",
".",
"variables",
".",
"values",
"(",
")",
":",
"if",
"v",
".",
"chunks",
"is",
"not",
"None",
":",
"for",
"dim",
",",
"c",
"in",
"zip",
"(",
"v",
".",
"dims",
",",
"v",
".",
"chunks",
")",
":",
"if",
"dim",
"in",
"chunks",
"and",
"c",
"!=",
"chunks",
"[",
"dim",
"]",
":",
"raise",
"ValueError",
"(",
"'inconsistent chunks'",
")",
"chunks",
"[",
"dim",
"]",
"=",
"c",
"return",
"Frozen",
"(",
"SortedKeysDict",
"(",
"chunks",
")",
")"
] |
Walk over all available auto_config methods passing them the current environment and seeing if they return a configuration URL | def get_auto_config ( self ) : methods = [ m for m in dir ( self ) if m . startswith ( 'auto_config_' ) ] for method_name in sorted ( methods ) : auto_config_method = getattr ( self , method_name ) url = auto_config_method ( self . env ) if url : return url | 11,532 | https://github.com/evansd/django-envsettings/blob/541932af261d5369f211f836a238dc020ee316e8/envsettings/base.py#L114-L124 | [
"def",
"unShare",
"(",
"sharedItem",
")",
":",
"sharedItem",
".",
"store",
".",
"query",
"(",
"Share",
",",
"Share",
".",
"sharedItem",
"==",
"sharedItem",
")",
".",
"deleteFromStore",
"(",
")"
] |
Dispatches the request to the plugins process method | def Process ( self , request , context ) : LOG . debug ( "Process called" ) try : metrics = self . plugin . process ( [ Metric ( pb = m ) for m in request . Metrics ] , ConfigMap ( pb = request . Config ) ) return MetricsReply ( metrics = [ m . pb for m in metrics ] ) except Exception as err : msg = "message: {}\n\nstack trace: {}" . format ( err , traceback . format_exc ( ) ) return MetricsReply ( metrics = [ ] , error = msg ) | 11,533 | https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/processor_proxy.py#L36-L48 | [
"def",
"write_object_array",
"(",
"f",
",",
"data",
",",
"options",
")",
":",
"# We need to grab the special reference dtype and make an empty",
"# array to store all the references in.",
"ref_dtype",
"=",
"h5py",
".",
"special_dtype",
"(",
"ref",
"=",
"h5py",
".",
"Reference",
")",
"data_refs",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"data",
".",
"shape",
",",
"dtype",
"=",
"'object'",
")",
"# We need to make sure that the group to hold references is present,",
"# and create it if it isn't.",
"if",
"options",
".",
"group_for_references",
"not",
"in",
"f",
":",
"f",
".",
"create_group",
"(",
"options",
".",
"group_for_references",
")",
"grp2",
"=",
"f",
"[",
"options",
".",
"group_for_references",
"]",
"if",
"not",
"isinstance",
"(",
"grp2",
",",
"h5py",
".",
"Group",
")",
":",
"del",
"f",
"[",
"options",
".",
"group_for_references",
"]",
"f",
".",
"create_group",
"(",
"options",
".",
"group_for_references",
")",
"grp2",
"=",
"f",
"[",
"options",
".",
"group_for_references",
"]",
"# The Dataset 'a' needs to be present as the canonical empty. It is",
"# just and np.uint32/64([0, 0]) with its a MATLAB_class of",
"# 'canonical empty' and the 'MATLAB_empty' attribute set. If it",
"# isn't present or is incorrectly formatted, it is created",
"# truncating anything previously there.",
"try",
":",
"dset_a",
"=",
"grp2",
"[",
"'a'",
"]",
"if",
"dset_a",
".",
"shape",
"!=",
"(",
"2",
",",
")",
"or",
"not",
"dset_a",
".",
"dtype",
".",
"name",
".",
"startswith",
"(",
"'uint'",
")",
"or",
"np",
".",
"any",
"(",
"dset_a",
"[",
"...",
"]",
"!=",
"np",
".",
"uint64",
"(",
"[",
"0",
",",
"0",
"]",
")",
")",
"or",
"get_attribute_string",
"(",
"dset_a",
",",
"'MATLAB_class'",
")",
"!=",
"'canonical empty'",
"or",
"get_attribute",
"(",
"dset_a",
",",
"'MATLAB_empty'",
")",
"!=",
"1",
":",
"del",
"grp2",
"[",
"'a'",
"]",
"dset_a",
"=",
"grp2",
".",
"create_dataset",
"(",
"'a'",
",",
"data",
"=",
"np",
".",
"uint64",
"(",
"[",
"0",
",",
"0",
"]",
")",
")",
"set_attribute_string",
"(",
"dset_a",
",",
"'MATLAB_class'",
",",
"'canonical empty'",
")",
"set_attribute",
"(",
"dset_a",
",",
"'MATLAB_empty'",
",",
"np",
".",
"uint8",
"(",
"1",
")",
")",
"except",
":",
"dset_a",
"=",
"grp2",
".",
"create_dataset",
"(",
"'a'",
",",
"data",
"=",
"np",
".",
"uint64",
"(",
"[",
"0",
",",
"0",
"]",
")",
")",
"set_attribute_string",
"(",
"dset_a",
",",
"'MATLAB_class'",
",",
"'canonical empty'",
")",
"set_attribute",
"(",
"dset_a",
",",
"'MATLAB_empty'",
",",
"np",
".",
"uint8",
"(",
"1",
")",
")",
"# Go through all the elements of data and write them, gabbing their",
"# references and putting them in data_refs. They will be put in",
"# group_for_references, which is also what the H5PATH needs to be",
"# set to if we are doing MATLAB compatibility (otherwise, the",
"# attribute needs to be deleted). If an element can't be written",
"# (doing matlab compatibility, but it isn't compatible with matlab",
"# and action_for_matlab_incompatible option is True), the reference",
"# to the canonical empty will be used for the reference array to",
"# point to.",
"grp2name",
"=",
"grp2",
".",
"name",
"for",
"index",
",",
"x",
"in",
"np",
".",
"ndenumerate",
"(",
"data",
")",
":",
"name_for_ref",
"=",
"next_unused_name_in_group",
"(",
"grp2",
",",
"16",
")",
"write_data",
"(",
"f",
",",
"grp2",
",",
"name_for_ref",
",",
"x",
",",
"None",
",",
"options",
")",
"try",
":",
"dset",
"=",
"grp2",
"[",
"name_for_ref",
"]",
"data_refs",
"[",
"index",
"]",
"=",
"dset",
".",
"ref",
"if",
"options",
".",
"matlab_compatible",
":",
"set_attribute_string",
"(",
"dset",
",",
"'H5PATH'",
",",
"grp2name",
")",
"else",
":",
"del_attribute",
"(",
"dset",
",",
"'H5PATH'",
")",
"except",
":",
"data_refs",
"[",
"index",
"]",
"=",
"dset_a",
".",
"ref",
"# Now, the dtype needs to be changed to the reference type and the",
"# whole thing copied over to data_to_store.",
"return",
"data_refs",
".",
"astype",
"(",
"ref_dtype",
")",
".",
"copy",
"(",
")"
] |
Triggers the local agent to join a node | async def join ( self , address , * , wan = None ) : response = await self . _api . get ( "/v1/agent/join" , address , params = { "wan" : wan } ) return response . status == 200 | 11,534 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/members_endpoint.py#L44-L59 | [
"def",
"get_gradebook_columns_by_query",
"(",
"self",
",",
"gradebook_column_query",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceQuerySession.get_resources_by_query",
"and_list",
"=",
"list",
"(",
")",
"or_list",
"=",
"list",
"(",
")",
"for",
"term",
"in",
"gradebook_column_query",
".",
"_query_terms",
":",
"if",
"'$in'",
"in",
"gradebook_column_query",
".",
"_query_terms",
"[",
"term",
"]",
"and",
"'$nin'",
"in",
"gradebook_column_query",
".",
"_query_terms",
"[",
"term",
"]",
":",
"and_list",
".",
"append",
"(",
"{",
"'$or'",
":",
"[",
"{",
"term",
":",
"{",
"'$in'",
":",
"gradebook_column_query",
".",
"_query_terms",
"[",
"term",
"]",
"[",
"'$in'",
"]",
"}",
"}",
",",
"{",
"term",
":",
"{",
"'$nin'",
":",
"gradebook_column_query",
".",
"_query_terms",
"[",
"term",
"]",
"[",
"'$nin'",
"]",
"}",
"}",
"]",
"}",
")",
"else",
":",
"and_list",
".",
"append",
"(",
"{",
"term",
":",
"gradebook_column_query",
".",
"_query_terms",
"[",
"term",
"]",
"}",
")",
"for",
"term",
"in",
"gradebook_column_query",
".",
"_keyword_terms",
":",
"or_list",
".",
"append",
"(",
"{",
"term",
":",
"gradebook_column_query",
".",
"_keyword_terms",
"[",
"term",
"]",
"}",
")",
"if",
"or_list",
":",
"and_list",
".",
"append",
"(",
"{",
"'$or'",
":",
"or_list",
"}",
")",
"view_filter",
"=",
"self",
".",
"_view_filter",
"(",
")",
"if",
"view_filter",
":",
"and_list",
".",
"append",
"(",
"view_filter",
")",
"if",
"and_list",
":",
"query_terms",
"=",
"{",
"'$and'",
":",
"and_list",
"}",
"collection",
"=",
"JSONClientValidated",
"(",
"'grading'",
",",
"collection",
"=",
"'GradebookColumn'",
",",
"runtime",
"=",
"self",
".",
"_runtime",
")",
"result",
"=",
"collection",
".",
"find",
"(",
"query_terms",
")",
".",
"sort",
"(",
"'_id'",
",",
"DESCENDING",
")",
"else",
":",
"result",
"=",
"[",
"]",
"return",
"objects",
".",
"GradebookColumnList",
"(",
"result",
",",
"runtime",
"=",
"self",
".",
"_runtime",
",",
"proxy",
"=",
"self",
".",
"_proxy",
")"
] |
Forces removal of a node | async def force_leave ( self , node ) : node_id = extract_attr ( node , keys = [ "Node" , "ID" ] ) response = await self . _get ( "/v1/agent/force-leave" , node_id ) return response . status == 200 | 11,535 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/members_endpoint.py#L61-L78 | [
"def",
"get_pwiz_tables",
"(",
"self",
",",
"engine",
",",
"database",
")",
":",
"introspector",
"=",
"pwiz",
".",
"make_introspector",
"(",
"engine",
",",
"database",
".",
"database",
",",
"*",
"*",
"database",
".",
"connect_kwargs",
")",
"out_file",
"=",
"'/tmp/db_models.py'",
"with",
"Capturing",
"(",
")",
"as",
"code",
":",
"pwiz",
".",
"print_models",
"(",
"introspector",
")",
"code",
"=",
"'\\n'",
".",
"join",
"(",
"code",
")",
"# Unfortunately, introspect.getsource doesn't seem to work",
"# with dynamically created classes unless it is written out",
"# to a file. So write it out to a temporary file",
"with",
"open",
"(",
"out_file",
",",
"'w'",
")",
"as",
"file_",
":",
"file_",
".",
"write",
"(",
"code",
")",
"# Load up the DB models as a new module so that we can",
"# compare them with those in the model definition",
"return",
"imp",
".",
"load_source",
"(",
"'db_models'",
",",
"out_file",
")"
] |
Goes to the next panel tab . | def gotoNext ( self ) : index = self . _currentPanel . currentIndex ( ) + 1 if ( self . _currentPanel . count ( ) == index ) : index = 0 self . _currentPanel . setCurrentIndex ( index ) | 11,536 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanelmenu.py#L136-L144 | [
"def",
"verify",
"(",
"self",
",",
"assoc_handle",
",",
"message",
")",
":",
"assoc",
"=",
"self",
".",
"getAssociation",
"(",
"assoc_handle",
",",
"dumb",
"=",
"True",
")",
"if",
"not",
"assoc",
":",
"logging",
".",
"error",
"(",
"\"failed to get assoc with handle %r to verify \"",
"\"message %r\"",
"%",
"(",
"assoc_handle",
",",
"message",
")",
")",
"return",
"False",
"try",
":",
"valid",
"=",
"assoc",
".",
"checkMessageSignature",
"(",
"message",
")",
"except",
"ValueError",
",",
"ex",
":",
"logging",
".",
"exception",
"(",
"\"Error in verifying %s with %s: %s\"",
"%",
"(",
"message",
",",
"assoc",
",",
"ex",
")",
")",
"return",
"False",
"return",
"valid"
] |
Goes to the previous panel tab . | def gotoPrevious ( self ) : index = self . _currentPanel . currentIndex ( ) - 1 if index < 0 : index = self . _currentPanel . count ( ) - 1 self . _currentPanel . setCurrentIndex ( index ) | 11,537 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanelmenu.py#L146-L154 | [
"def",
"_post_parse_request",
"(",
"self",
",",
"request",
",",
"client_id",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"RefreshAccessTokenRequest",
"(",
"*",
"*",
"request",
".",
"to_dict",
"(",
")",
")",
"try",
":",
"keyjar",
"=",
"self",
".",
"endpoint_context",
".",
"keyjar",
"except",
"AttributeError",
":",
"keyjar",
"=",
"\"\"",
"request",
".",
"verify",
"(",
"keyjar",
"=",
"keyjar",
",",
"opponent_id",
"=",
"client_id",
")",
"if",
"\"client_id\"",
"not",
"in",
"request",
":",
"# Optional for refresh access token request",
"request",
"[",
"\"client_id\"",
"]",
"=",
"client_id",
"logger",
".",
"debug",
"(",
"\"%s: %s\"",
"%",
"(",
"request",
".",
"__class__",
".",
"__name__",
",",
"sanitize",
"(",
"request",
")",
")",
")",
"return",
"request"
] |
Creates a new panel with a copy of the current widget . | def newPanelTab ( self ) : view = self . _currentPanel . currentView ( ) # duplicate the current view if view : new_view = view . duplicate ( self . _currentPanel ) self . _currentPanel . addTab ( new_view , new_view . windowTitle ( ) ) | 11,538 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanelmenu.py#L156-L165 | [
"def",
"stop_experiment",
"(",
"args",
")",
":",
"experiment_id_list",
"=",
"parse_ids",
"(",
"args",
")",
"if",
"experiment_id_list",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"for",
"experiment_id",
"in",
"experiment_id_list",
":",
"print_normal",
"(",
"'Stoping experiment %s'",
"%",
"experiment_id",
")",
"nni_config",
"=",
"Config",
"(",
"experiment_dict",
"[",
"experiment_id",
"]",
"[",
"'fileName'",
"]",
")",
"rest_port",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPort'",
")",
"rest_pid",
"=",
"nni_config",
".",
"get_config",
"(",
"'restServerPid'",
")",
"if",
"rest_pid",
":",
"kill_command",
"(",
"rest_pid",
")",
"tensorboard_pid_list",
"=",
"nni_config",
".",
"get_config",
"(",
"'tensorboardPidList'",
")",
"if",
"tensorboard_pid_list",
":",
"for",
"tensorboard_pid",
"in",
"tensorboard_pid_list",
":",
"try",
":",
"kill_command",
"(",
"tensorboard_pid",
")",
"except",
"Exception",
"as",
"exception",
":",
"print_error",
"(",
"exception",
")",
"nni_config",
".",
"set_config",
"(",
"'tensorboardPidList'",
",",
"[",
"]",
")",
"print_normal",
"(",
"'Stop experiment success!'",
")",
"experiment_config",
".",
"update_experiment",
"(",
"experiment_id",
",",
"'status'",
",",
"'STOPPED'",
")",
"time_now",
"=",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
",",
"time",
".",
"localtime",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"experiment_config",
".",
"update_experiment",
"(",
"experiment_id",
",",
"'endTime'",
",",
"str",
"(",
"time_now",
")",
")"
] |
Prompts the user for a custom name for the current panel tab . | def renamePanel ( self ) : index = self . _currentPanel . currentIndex ( ) title = self . _currentPanel . tabText ( index ) new_title , accepted = QInputDialog . getText ( self , 'Rename Tab' , 'Name:' , QLineEdit . Normal , title ) if accepted : widget = self . _currentPanel . currentView ( ) widget . setWindowTitle ( new_title ) self . _currentPanel . setTabText ( index , new_title ) | 11,539 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewpanelmenu.py#L167-L183 | [
"def",
"remove_range",
"(",
"cls",
",",
"elem",
",",
"end_elem",
",",
"delete_end",
"=",
"True",
")",
":",
"while",
"elem",
"is",
"not",
"None",
"and",
"elem",
"!=",
"end_elem",
"and",
"end_elem",
"not",
"in",
"elem",
".",
"xpath",
"(",
"\"descendant::*\"",
")",
":",
"parent",
"=",
"elem",
".",
"getparent",
"(",
")",
"nxt",
"=",
"elem",
".",
"getnext",
"(",
")",
"parent",
".",
"remove",
"(",
"elem",
")",
"if",
"DEBUG",
"==",
"True",
":",
"print",
"(",
"etree",
".",
"tounicode",
"(",
"elem",
")",
")",
"elem",
"=",
"nxt",
"if",
"elem",
"==",
"end_elem",
":",
"if",
"delete_end",
"==",
"True",
":",
"cls",
".",
"remove",
"(",
"end_elem",
",",
"leave_tail",
"=",
"True",
")",
"elif",
"elem",
"is",
"None",
":",
"if",
"parent",
".",
"tail",
"not",
"in",
"[",
"None",
",",
"''",
"]",
":",
"parent",
".",
"tail",
"=",
"''",
"cls",
".",
"remove_range",
"(",
"parent",
".",
"getnext",
"(",
")",
",",
"end_elem",
")",
"XML",
".",
"remove_if_empty",
"(",
"parent",
")",
"elif",
"end_elem",
"in",
"elem",
".",
"xpath",
"(",
"\"descendant::*\"",
")",
":",
"if",
"DEBUG",
"==",
"True",
":",
"print",
"(",
"elem",
".",
"text",
")",
"elem",
".",
"text",
"=",
"''",
"cls",
".",
"remove_range",
"(",
"elem",
".",
"getchildren",
"(",
")",
"[",
"0",
"]",
",",
"end_elem",
")",
"XML",
".",
"remove_if_empty",
"(",
"elem",
")",
"else",
":",
"print",
"(",
"\"LOGIC ERROR\"",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] |
Reloads the contents for this box . | def reload ( self ) : enum = self . _enum if not enum : return self . clear ( ) if not self . isRequired ( ) : self . addItem ( '' ) if self . sortByKey ( ) : self . addItems ( sorted ( enum . keys ( ) ) ) else : items = enum . items ( ) items . sort ( key = lambda x : x [ 1 ] ) self . addItems ( map ( lambda x : x [ 0 ] , items ) ) | 11,540 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xenumbox.py#L124-L143 | [
"def",
"queueStream",
"(",
"self",
",",
"rdds",
",",
"oneAtATime",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"and",
"not",
"isinstance",
"(",
"default",
",",
"RDD",
")",
":",
"default",
"=",
"self",
".",
"_sc",
".",
"parallelize",
"(",
"default",
")",
"if",
"not",
"rdds",
"and",
"default",
":",
"rdds",
"=",
"[",
"rdds",
"]",
"if",
"rdds",
"and",
"not",
"isinstance",
"(",
"rdds",
"[",
"0",
"]",
",",
"RDD",
")",
":",
"rdds",
"=",
"[",
"self",
".",
"_sc",
".",
"parallelize",
"(",
"input",
")",
"for",
"input",
"in",
"rdds",
"]",
"self",
".",
"_check_serializers",
"(",
"rdds",
")",
"queue",
"=",
"self",
".",
"_jvm",
".",
"PythonDStream",
".",
"toRDDQueue",
"(",
"[",
"r",
".",
"_jrdd",
"for",
"r",
"in",
"rdds",
"]",
")",
"if",
"default",
":",
"default",
"=",
"default",
".",
"_reserialize",
"(",
"rdds",
"[",
"0",
"]",
".",
"_jrdd_deserializer",
")",
"jdstream",
"=",
"self",
".",
"_jssc",
".",
"queueStream",
"(",
"queue",
",",
"oneAtATime",
",",
"default",
".",
"_jrdd",
")",
"else",
":",
"jdstream",
"=",
"self",
".",
"_jssc",
".",
"queueStream",
"(",
"queue",
",",
"oneAtATime",
")",
"return",
"DStream",
"(",
"jdstream",
",",
"self",
",",
"rdds",
"[",
"0",
"]",
".",
"_jrdd_deserializer",
")"
] |
Recalcualtes the slider scene for this widget . | def recalculate ( self ) : # recalculate the scene geometry
scene = self . scene ( ) w = self . calculateSceneWidth ( ) scene . setSceneRect ( 0 , 0 , w , self . height ( ) ) # recalculate the item layout
spacing = self . spacing ( ) x = self . width ( ) / 4.0 y = self . height ( ) / 2.0 for item in self . items ( ) : pmap = item . pixmap ( ) item . setPos ( x , y - pmap . height ( ) / 1.5 ) x += pmap . size ( ) . width ( ) + spacing | 11,541 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/ximageslider/ximageslider.py#L106-L122 | [
"def",
"memmap",
"(",
"filename",
",",
"shape",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"page",
"=",
"None",
",",
"series",
"=",
"0",
",",
"mode",
"=",
"'r+'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"shape",
"is",
"not",
"None",
"and",
"dtype",
"is",
"not",
"None",
":",
"# create a new, empty array",
"kwargs",
".",
"update",
"(",
"data",
"=",
"None",
",",
"shape",
"=",
"shape",
",",
"dtype",
"=",
"dtype",
",",
"returnoffset",
"=",
"True",
",",
"align",
"=",
"TIFF",
".",
"ALLOCATIONGRANULARITY",
")",
"result",
"=",
"imwrite",
"(",
"filename",
",",
"*",
"*",
"kwargs",
")",
"if",
"result",
"is",
"None",
":",
"# TODO: fail before creating file or writing data",
"raise",
"ValueError",
"(",
"'image data are not memory-mappable'",
")",
"offset",
"=",
"result",
"[",
"0",
"]",
"else",
":",
"# use existing file",
"with",
"TiffFile",
"(",
"filename",
",",
"*",
"*",
"kwargs",
")",
"as",
"tif",
":",
"if",
"page",
"is",
"not",
"None",
":",
"page",
"=",
"tif",
".",
"pages",
"[",
"page",
"]",
"if",
"not",
"page",
".",
"is_memmappable",
":",
"raise",
"ValueError",
"(",
"'image data are not memory-mappable'",
")",
"offset",
",",
"_",
"=",
"page",
".",
"is_contiguous",
"shape",
"=",
"page",
".",
"shape",
"dtype",
"=",
"page",
".",
"dtype",
"else",
":",
"series",
"=",
"tif",
".",
"series",
"[",
"series",
"]",
"if",
"series",
".",
"offset",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'image data are not memory-mappable'",
")",
"shape",
"=",
"series",
".",
"shape",
"dtype",
"=",
"series",
".",
"dtype",
"offset",
"=",
"series",
".",
"offset",
"dtype",
"=",
"tif",
".",
"byteorder",
"+",
"dtype",
".",
"char",
"return",
"numpy",
".",
"memmap",
"(",
"filename",
",",
"dtype",
",",
"mode",
",",
"offset",
",",
"shape",
",",
"'C'",
")"
] |
Simple Mercedes me API . | def _check_token ( self ) : need_token = ( self . _token_info is None or self . auth_handler . is_token_expired ( self . _token_info ) ) if need_token : new_token = self . auth_handler . refresh_access_token ( self . _token_info [ 'refresh_token' ] ) # skip when refresh failed if new_token is None : return self . _token_info = new_token self . _auth_header = { "content-type" : "application/json" , "Authorization" : "Bearer {}" . format ( self . _token_info . get ( 'access_token' ) ) } | 11,542 | https://github.com/ReneNulschDE/mercedesmejsonpy/blob/0618a0b49d6bb46599d11a8f66dc8d08d112ceec/mercedesmejsonpy/controller.py#L159-L176 | [
"def",
"strings",
"(",
"self",
")",
":",
"sheet",
"=",
"self",
".",
"result",
".",
"add_sheet",
"(",
"\"strings\"",
")",
"self",
".",
"header",
"(",
"sheet",
",",
"\"strings\"",
")",
"n_row",
"=",
"1",
"# row number",
"for",
"entry",
"in",
"self",
".",
"po",
":",
"row",
"=",
"sheet",
".",
"row",
"(",
"n_row",
")",
"row",
".",
"write",
"(",
"0",
",",
"entry",
".",
"msgid",
")",
"row",
".",
"write",
"(",
"1",
",",
"entry",
".",
"msgstr",
")",
"n_row",
"+=",
"1",
"sheet",
".",
"flush_row_data",
"(",
")"
] |
get refreshed location information . | def get_location ( self , car_id ) : _LOGGER . debug ( "get_location for %s called" , car_id ) api_result = self . _retrieve_api_result ( car_id , API_LOCATION ) _LOGGER . debug ( "get_location result: %s" , api_result ) location = Location ( ) for loc_option in LOCATION_OPTIONS : curr_loc_option = api_result . get ( loc_option ) value = CarAttribute ( curr_loc_option . get ( "value" ) , curr_loc_option . get ( "retrievalstatus" ) , curr_loc_option . get ( "timestamp" ) ) setattr ( location , loc_option , value ) return location | 11,543 | https://github.com/ReneNulschDE/mercedesmejsonpy/blob/0618a0b49d6bb46599d11a8f66dc8d08d112ceec/mercedesmejsonpy/controller.py#L233-L254 | [
"def",
"is_swapped",
"(",
"app_label",
",",
"model",
")",
":",
"default_model",
"=",
"join",
"(",
"app_label",
",",
"model",
")",
"setting",
"=",
"swappable_setting",
"(",
"app_label",
",",
"model",
")",
"value",
"=",
"getattr",
"(",
"settings",
",",
"setting",
",",
"default_model",
")",
"if",
"value",
"!=",
"default_model",
":",
"return",
"value",
"else",
":",
"return",
"False"
] |
Creates a new token with a given policy | async def create ( self , token ) : token = encode_token ( token ) response = await self . _api . put ( "/v1/acl/create" , data = token ) return response . body | 11,544 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/acl_endpoint.py#L15-L59 | [
"def",
"normalize",
"(",
"value",
",",
"unit",
")",
":",
"if",
"value",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Negative value: %s %s.'",
"%",
"(",
"value",
",",
"unit",
")",
")",
"if",
"unit",
"in",
"functions",
".",
"get_keys",
"(",
"INFORMATION_UNITS",
")",
":",
"return",
"_normalize_information",
"(",
"value",
",",
"unit",
")",
"elif",
"unit",
"in",
"TIME_UNITS",
":",
"return",
"_normalize_time",
"(",
"value",
",",
"unit",
")",
"else",
":",
"# Unknown unit, just return it",
"return",
"functions",
".",
"format_value",
"(",
"value",
")",
",",
"unit"
] |
Destroys a given token . | async def destroy ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/acl/destroy" , token_id ) return response . body | 11,545 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/acl_endpoint.py#L93-L103 | [
"def",
"volumes_delete",
"(",
"storage_pool",
",",
"logger",
")",
":",
"try",
":",
"for",
"vol_name",
"in",
"storage_pool",
".",
"listVolumes",
"(",
")",
":",
"try",
":",
"vol",
"=",
"storage_pool",
".",
"storageVolLookupByName",
"(",
"vol_name",
")",
"vol",
".",
"delete",
"(",
"0",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volume %s.\"",
",",
"vol_name",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volumes.\"",
")"
] |
Queries the policy of a given token . | async def info ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . get ( "/v1/acl/info" , token_id ) meta = extract_meta ( response . headers ) try : result = decode_token ( response . body [ 0 ] ) except IndexError : raise NotFound ( response . body , meta = meta ) return consul ( result , meta = meta ) | 11,546 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/acl_endpoint.py#L107-L144 | [
"def",
"decompress",
"(",
"ctype",
",",
"unc_len",
",",
"data",
")",
":",
"if",
"ctype",
"==",
"UBIFS_COMPR_LZO",
":",
"try",
":",
"return",
"lzo",
".",
"decompress",
"(",
"b''",
".",
"join",
"(",
"(",
"b'\\xf0'",
",",
"struct",
".",
"pack",
"(",
"'>I'",
",",
"unc_len",
")",
",",
"data",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"error",
"(",
"decompress",
",",
"'Warn'",
",",
"'LZO Error: %s'",
"%",
"e",
")",
"elif",
"ctype",
"==",
"UBIFS_COMPR_ZLIB",
":",
"try",
":",
"return",
"zlib",
".",
"decompress",
"(",
"data",
",",
"-",
"11",
")",
"except",
"Exception",
"as",
"e",
":",
"error",
"(",
"decompress",
",",
"'Warn'",
",",
"'ZLib Error: %s'",
"%",
"e",
")",
"else",
":",
"return",
"data"
] |
Creates a new token by cloning an existing token | async def clone ( self , token ) : token_id = extract_attr ( token , keys = [ "ID" ] ) response = await self . _api . put ( "/v1/acl/clone" , token_id ) return consul ( response ) | 11,547 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/acl_endpoint.py#L146-L166 | [
"def",
"get_log_format_types",
"(",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"prefix",
"=",
"'logging/'",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"try",
":",
"connection",
"=",
"wmi",
".",
"WMI",
"(",
"namespace",
"=",
"_WMI_NAMESPACE",
")",
"objs",
"=",
"connection",
".",
"IISLogModuleSetting",
"(",
")",
"# Remove the prefix from the name.",
"for",
"obj",
"in",
"objs",
":",
"name",
"=",
"six",
".",
"text_type",
"(",
"obj",
".",
"Name",
")",
".",
"replace",
"(",
"prefix",
",",
"''",
",",
"1",
")",
"ret",
"[",
"name",
"]",
"=",
"six",
".",
"text_type",
"(",
"obj",
".",
"LogModuleId",
")",
"except",
"wmi",
".",
"x_wmi",
"as",
"error",
":",
"_LOG",
".",
"error",
"(",
"'Encountered WMI error: %s'",
",",
"error",
".",
"com_error",
")",
"except",
"(",
"AttributeError",
",",
"IndexError",
")",
"as",
"error",
":",
"_LOG",
".",
"error",
"(",
"'Error getting IISLogModuleSetting: %s'",
",",
"error",
")",
"if",
"not",
"ret",
":",
"_LOG",
".",
"error",
"(",
"'Unable to get log format types.'",
")",
"return",
"ret"
] |
Lists all the active tokens | async def items ( self ) : response = await self . _api . get ( "/v1/acl/list" ) results = [ decode_token ( r ) for r in response . body ] return consul ( results , meta = extract_meta ( response . headers ) ) | 11,548 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/acl_endpoint.py#L168-L194 | [
"def",
"arcball_constrain_to_axis",
"(",
"point",
",",
"axis",
")",
":",
"v",
"=",
"np",
".",
"array",
"(",
"point",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"a",
"=",
"np",
".",
"array",
"(",
"axis",
",",
"dtype",
"=",
"np",
".",
"float64",
",",
"copy",
"=",
"True",
")",
"v",
"-=",
"a",
"*",
"np",
".",
"dot",
"(",
"a",
",",
"v",
")",
"# on plane",
"n",
"=",
"vector_norm",
"(",
"v",
")",
"if",
"n",
">",
"_EPS",
":",
"if",
"v",
"[",
"2",
"]",
"<",
"0.0",
":",
"np",
".",
"negative",
"(",
"v",
",",
"v",
")",
"v",
"/=",
"n",
"return",
"v",
"if",
"a",
"[",
"2",
"]",
"==",
"1.0",
":",
"return",
"np",
".",
"array",
"(",
"[",
"1.0",
",",
"0.0",
",",
"0.0",
"]",
")",
"return",
"unit_vector",
"(",
"[",
"-",
"a",
"[",
"1",
"]",
",",
"a",
"[",
"0",
"]",
",",
"0.0",
"]",
")"
] |
Checks status of ACL replication | async def replication ( self , * , dc = None ) : params = { "dc" : dc } response = await self . _api . get ( "/v1/acl/replication" , params = params ) return response . body | 11,549 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/acl_endpoint.py#L196-L257 | [
"def",
"__make_request",
"(",
"self",
",",
"requests_session",
",",
"method",
",",
"url",
",",
"params",
",",
"data",
",",
"headers",
",",
"certificate",
")",
":",
"verify",
"=",
"False",
"timeout",
"=",
"self",
".",
"timeout",
"try",
":",
"# TODO : Remove this ugly try/except after fixing Java issue: http://mvjira.mv.usa.alcatel.com/browse/VSD-546",
"response",
"=",
"requests_session",
".",
"request",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"verify",
"=",
"verify",
",",
"timeout",
"=",
"timeout",
",",
"params",
"=",
"params",
",",
"cert",
"=",
"certificate",
")",
"except",
"requests",
".",
"exceptions",
".",
"SSLError",
":",
"try",
":",
"response",
"=",
"requests_session",
".",
"request",
"(",
"method",
"=",
"method",
",",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
",",
"verify",
"=",
"verify",
",",
"timeout",
"=",
"timeout",
",",
"params",
"=",
"params",
",",
"cert",
"=",
"certificate",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"return",
"self",
".",
"_did_timeout",
"(",
")",
"except",
"requests",
".",
"exceptions",
".",
"Timeout",
":",
"return",
"self",
".",
"_did_timeout",
"(",
")",
"return",
"response"
] |
Make each string in the collection end with a unique character . Essential for correct builiding of a generalized annotated suffix tree . Returns the updated strings collection encoded in Unicode . | def make_unique_endings ( strings_collection ) : res = [ ] for i in range ( len ( strings_collection ) ) : # NOTE(msdubov): a trick to handle 'narrow' python installation issues. hex_code = hex ( consts . String . UNICODE_SPECIAL_SYMBOLS_START + i ) hex_code = r"\U" + "0" * ( 8 - len ( hex_code ) + 2 ) + hex_code [ 2 : ] res . append ( strings_collection [ i ] + hex_code . decode ( "unicode-escape" ) ) return res | 11,550 | https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/asts/utils.py#L25-L40 | [
"def",
"_parseDelayImportDirectory",
"(",
"self",
",",
"rva",
",",
"size",
",",
"magic",
"=",
"consts",
".",
"PE32",
")",
":",
"return",
"self",
".",
"getDataAtRva",
"(",
"rva",
",",
"size",
")"
] |
Queries for WAN coordinates of Consul servers | async def datacenters ( self ) : response = await self . _api . get ( "/v1/coordinate/datacenters" ) return { data [ "Datacenter" ] : data for data in response . body } | 11,551 | https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/coordinate_endpoint.py#L15-L48 | [
"def",
"parse_flash_log",
"(",
"self",
",",
"logf",
")",
":",
"data",
"=",
"OrderedDict",
"(",
")",
"samplelogs",
"=",
"self",
".",
"split_log",
"(",
"logf",
"[",
"'f'",
"]",
")",
"for",
"slog",
"in",
"samplelogs",
":",
"try",
":",
"sample",
"=",
"dict",
"(",
")",
"## Sample name ##",
"s_name",
"=",
"self",
".",
"clean_pe_name",
"(",
"slog",
",",
"logf",
"[",
"'root'",
"]",
")",
"if",
"s_name",
"is",
"None",
":",
"continue",
"sample",
"[",
"'s_name'",
"]",
"=",
"s_name",
"## Log attributes ##",
"sample",
"[",
"'totalpairs'",
"]",
"=",
"self",
".",
"get_field",
"(",
"'Total pairs'",
",",
"slog",
")",
"sample",
"[",
"'discardpairs'",
"]",
"=",
"self",
".",
"get_field",
"(",
"'Discarded pairs'",
",",
"slog",
")",
"sample",
"[",
"'percdiscard'",
"]",
"=",
"self",
".",
"get_field",
"(",
"'Percent Discarded'",
",",
"slog",
",",
"fl",
"=",
"True",
")",
"sample",
"[",
"'combopairs'",
"]",
"=",
"self",
".",
"get_field",
"(",
"'Combined pairs'",
",",
"slog",
")",
"sample",
"[",
"'inniepairs'",
"]",
"=",
"self",
".",
"get_field",
"(",
"'Innie pairs'",
",",
"slog",
")",
"sample",
"[",
"'outiepairs'",
"]",
"=",
"self",
".",
"get_field",
"(",
"'Outie pairs'",
",",
"slog",
")",
"sample",
"[",
"'uncombopairs'",
"]",
"=",
"self",
".",
"get_field",
"(",
"'Uncombined pairs'",
",",
"slog",
")",
"sample",
"[",
"'perccombo'",
"]",
"=",
"self",
".",
"get_field",
"(",
"'Percent combined'",
",",
"slog",
",",
"fl",
"=",
"True",
")",
"data",
"[",
"s_name",
"]",
"=",
"sample",
"except",
"Exception",
"as",
"err",
":",
"log",
".",
"warning",
"(",
"\"Error parsing record in {}. {}\"",
".",
"format",
"(",
"logf",
"[",
"'fn'",
"]",
",",
"err",
")",
")",
"log",
".",
"debug",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"continue",
"return",
"data"
] |
Resizes the list widget to fit its contents vertically . | def resizeToContents ( self ) : if self . count ( ) : item = self . item ( self . count ( ) - 1 ) rect = self . visualItemRect ( item ) height = rect . bottom ( ) + 8 height = max ( 28 , height ) self . setFixedHeight ( height ) else : self . setFixedHeight ( self . minimumHeight ( ) ) | 11,552 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlistwidget.py#L535-L546 | [
"def",
"render_unregistered",
"(",
"error",
"=",
"None",
")",
":",
"return",
"template",
"(",
"read_index_template",
"(",
")",
",",
"registered",
"=",
"False",
",",
"error",
"=",
"error",
",",
"seeder_data",
"=",
"None",
",",
"url_id",
"=",
"None",
",",
")"
] |
parse openvpn status log | def parse_status_file ( status_file , nas_addr ) : session_users = { } flag1 = False flag2 = False with open ( status_file ) as stlines : for line in stlines : if line . startswith ( "Common Name" ) : flag1 = True continue if line . startswith ( "ROUTING TABLE" ) : flag1 = False continue if line . startswith ( "Virtual Address" ) : flag2 = True continue if line . startswith ( "GLOBAL STATS" ) : flag2 = False continue if flag1 : try : username , realaddr , inbytes , outbytes , _ = line . split ( ',' ) realip , realport = realaddr . split ( ':' ) session_id = md5 ( nas_addr + realip + realport ) . hexdigest ( ) session_users . setdefault ( session_id , { } ) . update ( dict ( session_id = session_id , username = username , realip = realip , realport = realport , inbytes = inbytes , outbytes = outbytes ) ) except : traceback . print_exc ( ) if flag2 : try : userip , username , realaddr , _ = line . split ( ',' ) realip , realport = realaddr . split ( ':' ) session_id = md5 ( nas_addr + realip + realport ) . hexdigest ( ) session_users . setdefault ( session_id , { } ) . update ( dict ( session_id = session_id , username = username , realip = realip , realport = realport , userip = userip , ) ) except : traceback . print_exc ( ) return session_users | 11,553 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/daemon.py#L21-L77 | [
"def",
"_make_model_class",
"(",
"message_type",
",",
"indexed_fields",
",",
"*",
"*",
"props",
")",
":",
"analyzed",
"=",
"_analyze_indexed_fields",
"(",
"indexed_fields",
")",
"for",
"field_name",
",",
"sub_fields",
"in",
"analyzed",
".",
"iteritems",
"(",
")",
":",
"if",
"field_name",
"in",
"props",
":",
"raise",
"ValueError",
"(",
"'field name %s is reserved'",
"%",
"field_name",
")",
"try",
":",
"field",
"=",
"message_type",
".",
"field_by_name",
"(",
"field_name",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"'Message type %s has no field named %s'",
"%",
"(",
"message_type",
".",
"__name__",
",",
"field_name",
")",
")",
"if",
"isinstance",
"(",
"field",
",",
"messages",
".",
"MessageField",
")",
":",
"if",
"not",
"sub_fields",
":",
"raise",
"ValueError",
"(",
"'MessageField %s cannot be indexed, only sub-fields'",
"%",
"field_name",
")",
"sub_model_class",
"=",
"_make_model_class",
"(",
"field",
".",
"type",
",",
"sub_fields",
")",
"prop",
"=",
"model",
".",
"StructuredProperty",
"(",
"sub_model_class",
",",
"field_name",
",",
"repeated",
"=",
"field",
".",
"repeated",
")",
"else",
":",
"if",
"sub_fields",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Unstructured field %s cannot have indexed sub-fields'",
"%",
"field_name",
")",
"if",
"isinstance",
"(",
"field",
",",
"messages",
".",
"EnumField",
")",
":",
"prop",
"=",
"EnumProperty",
"(",
"field",
".",
"type",
",",
"field_name",
",",
"repeated",
"=",
"field",
".",
"repeated",
")",
"elif",
"isinstance",
"(",
"field",
",",
"messages",
".",
"BytesField",
")",
":",
"prop",
"=",
"model",
".",
"BlobProperty",
"(",
"field_name",
",",
"repeated",
"=",
"field",
".",
"repeated",
",",
"indexed",
"=",
"True",
")",
"else",
":",
"# IntegerField, FloatField, BooleanField, StringField.",
"prop",
"=",
"model",
".",
"GenericProperty",
"(",
"field_name",
",",
"repeated",
"=",
"field",
".",
"repeated",
")",
"props",
"[",
"field_name",
"]",
"=",
"prop",
"return",
"model",
".",
"MetaModel",
"(",
"'_%s__Model'",
"%",
"message_type",
".",
"__name__",
",",
"(",
"model",
".",
"Model",
",",
")",
",",
"props",
")"
] |
update status db | def update_status ( dbfile , status_file , nas_addr ) : try : total = 0 params = [ ] for sid , su in parse_status_file ( status_file , nas_addr ) . items ( ) : if 'session_id' in su and 'inbytes' in su and 'outbytes' in su : params . append ( ( su [ 'inbytes' ] , su [ 'outbytes' ] , su [ 'session_id' ] ) ) total += 1 statusdb . batch_update_client ( dbfile , params ) log . msg ( 'update_status total = %s' % total ) except Exception , e : log . err ( 'batch update status error' ) log . err ( e ) | 11,554 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/daemon.py#L79-L93 | [
"def",
"_check_missing_manifests",
"(",
"self",
",",
"segids",
")",
":",
"manifest_paths",
"=",
"[",
"self",
".",
"_manifest_path",
"(",
"segid",
")",
"for",
"segid",
"in",
"segids",
"]",
"with",
"Storage",
"(",
"self",
".",
"vol",
".",
"layer_cloudpath",
",",
"progress",
"=",
"self",
".",
"vol",
".",
"progress",
")",
"as",
"stor",
":",
"exists",
"=",
"stor",
".",
"files_exist",
"(",
"manifest_paths",
")",
"dne",
"=",
"[",
"]",
"for",
"path",
",",
"there",
"in",
"exists",
".",
"items",
"(",
")",
":",
"if",
"not",
"there",
":",
"(",
"segid",
",",
")",
"=",
"re",
".",
"search",
"(",
"r'(\\d+):0$'",
",",
"path",
")",
".",
"groups",
"(",
")",
"dne",
".",
"append",
"(",
"segid",
")",
"return",
"dne"
] |
update radius accounting | def accounting ( dbfile , config ) : try : nas_id = config . get ( 'DEFAULT' , 'nas_id' ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) secret = config . get ( 'DEFAULT' , 'radius_secret' ) radius_addr = config . get ( 'DEFAULT' , 'radius_addr' ) radius_acct_port = config . getint ( 'DEFAULT' , 'radius_acct_port' ) radius_timeout = config . getint ( 'DEFAULT' , 'radius_timeout' ) status_dbfile = config . get ( 'DEFAULT' , 'statusdb' ) clients = statusdb . query_client ( status_dbfile ) ctime = int ( time . time ( ) ) for cli in clients : if ( ctime - int ( cli [ 'uptime' ] ) ) < int ( cli [ 'acct_interval' ] ) : continue session_id = cli [ 'session_id' ] req = { 'User-Name' : cli [ 'username' ] } req [ 'Acct-Status-Type' ] = ACCT_UPDATE req [ 'Acct-Session-Id' ] = session_id req [ "Acct-Output-Octets" ] = int ( cli [ 'outbytes' ] ) req [ "Acct-Input-Octets" ] = int ( cli [ 'inbytes' ] ) req [ 'Acct-Session-Time' ] = ( ctime - int ( cli [ 'ctime' ] ) ) req [ "NAS-IP-Address" ] = nas_addr req [ "NAS-Port-Id" ] = '0/0/0:0.0' req [ "NAS-Port" ] = 0 req [ "Service-Type" ] = "Login-User" req [ "NAS-Identifier" ] = nas_id req [ "Called-Station-Id" ] = '00:00:00:00:00:00' req [ "Calling-Station-Id" ] = '00:00:00:00:00:00' req [ "Framed-IP-Address" ] = cli [ 'userip' ] def update_uptime ( radresp ) : statusdb . update_client_uptime ( status_dbfile , session_id ) log . msg ( 'online<%s> client accounting update' % session_id ) def onresp ( r ) : try : update_uptime ( r ) except Exception as e : log . err ( 'online update uptime error' ) log . err ( e ) d = client . send_acct ( str ( secret ) , get_dictionary ( ) , radius_addr , acctport = radius_acct_port , debug = True , * * req ) d . addCallbacks ( onresp , log . err ) except Exception , e : log . err ( 'accounting error' ) log . err ( e ) | 11,555 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/daemon.py#L95-L147 | [
"def",
"run",
"(",
"self",
")",
":",
"# Create the thread pool.",
"executor",
"=",
"concurrent",
".",
"futures",
".",
"ThreadPoolExecutor",
"(",
"max_workers",
"=",
"self",
".",
"_config",
"[",
"'num_workers'",
"]",
")",
"# Wait to ensure multiple senders can be synchronised.",
"now",
"=",
"int",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timestamp",
"(",
")",
")",
"start_time",
"=",
"(",
"(",
"now",
"+",
"29",
")",
"//",
"30",
")",
"*",
"30",
"self",
".",
"_log",
".",
"info",
"(",
"'Waiting until {}'",
".",
"format",
"(",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"start_time",
")",
")",
")",
"while",
"int",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timestamp",
"(",
")",
")",
"<",
"start_time",
":",
"time",
".",
"sleep",
"(",
"0.1",
")",
"# Run the event loop.",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"try",
":",
"loop",
".",
"run_until_complete",
"(",
"self",
".",
"_run_loop",
"(",
"executor",
")",
")",
"except",
"KeyboardInterrupt",
":",
"pass",
"finally",
":",
"# Send the end of stream message to each stream.",
"self",
".",
"_log",
".",
"info",
"(",
"'Shutting down, closing streams...'",
")",
"tasks",
"=",
"[",
"]",
"for",
"stream",
",",
"item_group",
"in",
"self",
".",
"_streams",
":",
"tasks",
".",
"append",
"(",
"stream",
".",
"async_send_heap",
"(",
"item_group",
".",
"get_end",
"(",
")",
")",
")",
"loop",
".",
"run_until_complete",
"(",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
")",
")",
"self",
".",
"_log",
".",
"info",
"(",
"'... finished.'",
")",
"executor",
".",
"shutdown",
"(",
")"
] |
OpenVPN status daemon | def main ( conf ) : config = init_config ( conf ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) status_file = config . get ( 'DEFAULT' , 'statusfile' ) status_dbfile = config . get ( 'DEFAULT' , 'statusdb' ) nas_coa_port = config . get ( 'DEFAULT' , 'nas_coa_port' ) def do_update_status_task ( ) : d = deferToThread ( update_status , status_dbfile , status_file , nas_addr ) d . addCallback ( log . msg , 'do_update_status_task done!' ) d . addErrback ( log . err ) reactor . callLater ( 60.0 , do_update_status_task ) def do_accounting_task ( ) : d = deferToThread ( accounting , status_dbfile , config ) d . addCallback ( log . msg , 'do_accounting_task done!' ) d . addErrback ( log . err ) reactor . callLater ( 60.0 , do_accounting_task ) do_update_status_task ( ) do_accounting_task ( ) coa_protocol = Authorized ( config ) reactor . listenUDP ( int ( nas_coa_port ) , coa_protocol , interface = '0.0.0.0' ) reactor . run ( ) | 11,556 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/daemon.py#L202-L228 | [
"def",
"create",
"(",
"self",
",",
"image",
",",
"geometry",
",",
"options",
")",
":",
"image",
"=",
"self",
".",
"cropbox",
"(",
"image",
",",
"geometry",
",",
"options",
")",
"image",
"=",
"self",
".",
"orientation",
"(",
"image",
",",
"geometry",
",",
"options",
")",
"image",
"=",
"self",
".",
"colorspace",
"(",
"image",
",",
"geometry",
",",
"options",
")",
"image",
"=",
"self",
".",
"remove_border",
"(",
"image",
",",
"options",
")",
"image",
"=",
"self",
".",
"scale",
"(",
"image",
",",
"geometry",
",",
"options",
")",
"image",
"=",
"self",
".",
"crop",
"(",
"image",
",",
"geometry",
",",
"options",
")",
"image",
"=",
"self",
".",
"rounded",
"(",
"image",
",",
"geometry",
",",
"options",
")",
"image",
"=",
"self",
".",
"blur",
"(",
"image",
",",
"geometry",
",",
"options",
")",
"image",
"=",
"self",
".",
"padding",
"(",
"image",
",",
"geometry",
",",
"options",
")",
"return",
"image"
] |
Filters given entity queryset by an attribute which is linked to given schema and has given value in the field for schema s datatype . | def _filter_by_simple_schema ( self , qs , lookup , sublookup , value , schema ) : value_lookup = 'attrs__value_%s' % schema . datatype if sublookup : value_lookup = '%s__%s' % ( value_lookup , sublookup ) return { 'attrs__schema' : schema , str ( value_lookup ) : value } | 11,557 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/managers.py#L121-L132 | [
"def",
"ListClients",
"(",
"self",
",",
"request",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_RetryLoop",
"(",
"lambda",
"t",
":",
"self",
".",
"_stub",
".",
"ListClients",
"(",
"request",
",",
"timeout",
"=",
"t",
")",
")"
] |
Filters given entity queryset by an attribute which is linked to given many - to - many schema . | def _filter_by_m2m_schema ( self , qs , lookup , sublookup , value , schema , model = None ) : model = model or self . model schemata = dict ( ( s . name , s ) for s in model . get_schemata_for_model ( ) ) # TODO cache this dict, see above too try : schema = schemata [ lookup ] except KeyError : # TODO: smarter error message, i.e. how could this happen and what to do raise ValueError ( u'Could not find schema for lookup "%s"' % lookup ) sublookup = '__%s' % sublookup if sublookup else '' return { 'attrs__schema' : schema , 'attrs__choice%s' % sublookup : value , # TODO: can we filter by id, not name? } | 11,558 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/managers.py#L173-L189 | [
"def",
"resume_experiment",
"(",
"args",
")",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(",
")",
"experiment_id",
"=",
"None",
"experiment_endTime",
"=",
"None",
"#find the latest stopped experiment",
"if",
"not",
"args",
".",
"id",
":",
"print_error",
"(",
"'Please set experiment id! \\nYou could use \\'nnictl resume {id}\\' to resume a stopped experiment!\\n'",
"'You could use \\'nnictl experiment list all\\' to show all of stopped experiments!'",
")",
"exit",
"(",
"1",
")",
"else",
":",
"if",
"experiment_dict",
".",
"get",
"(",
"args",
".",
"id",
")",
"is",
"None",
":",
"print_error",
"(",
"'Id %s not exist!'",
"%",
"args",
".",
"id",
")",
"exit",
"(",
"1",
")",
"if",
"experiment_dict",
"[",
"args",
".",
"id",
"]",
"[",
"'status'",
"]",
"!=",
"'STOPPED'",
":",
"print_error",
"(",
"'Experiment %s is running!'",
"%",
"args",
".",
"id",
")",
"exit",
"(",
"1",
")",
"experiment_id",
"=",
"args",
".",
"id",
"print_normal",
"(",
"'Resuming experiment %s...'",
"%",
"experiment_id",
")",
"nni_config",
"=",
"Config",
"(",
"experiment_dict",
"[",
"experiment_id",
"]",
"[",
"'fileName'",
"]",
")",
"experiment_config",
"=",
"nni_config",
".",
"get_config",
"(",
"'experimentConfig'",
")",
"experiment_id",
"=",
"nni_config",
".",
"get_config",
"(",
"'experimentId'",
")",
"new_config_file_name",
"=",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
",",
"8",
")",
")",
"new_nni_config",
"=",
"Config",
"(",
"new_config_file_name",
")",
"new_nni_config",
".",
"set_config",
"(",
"'experimentConfig'",
",",
"experiment_config",
")",
"launch_experiment",
"(",
"args",
",",
"experiment_config",
",",
"'resume'",
",",
"new_config_file_name",
",",
"experiment_id",
")",
"new_nni_config",
".",
"set_config",
"(",
"'restServerPort'",
",",
"args",
".",
"port",
")"
] |
Creates entity instance and related Attr instances . | def create ( self , * * kwargs ) : fields = self . model . _meta . get_all_field_names ( ) schemata = dict ( ( s . name , s ) for s in self . model . get_schemata_for_model ( ) ) # check if all attributes are known possible_names = set ( fields ) | set ( schemata . keys ( ) ) wrong_names = set ( kwargs . keys ( ) ) - possible_names if wrong_names : raise NameError ( 'Cannot create %s: unknown attribute(s) "%s". ' 'Available fields: (%s). Available schemata: (%s).' % ( self . model . _meta . object_name , '", "' . join ( wrong_names ) , ', ' . join ( fields ) , ', ' . join ( schemata ) ) ) # init entity with fields instance = self . model ( * * dict ( ( k , v ) for k , v in kwargs . items ( ) if k in fields ) ) # set attributes; instance will check schemata on save for name , value in kwargs . items ( ) : setattr ( instance , name , value ) # save instance and EAV attributes instance . save ( force_insert = True ) return instance | 11,559 | https://github.com/neithere/eav-django/blob/7f2e9fe17bbe740622cfb38f6ce0e8413b7da3d7/eav/managers.py#L191-L225 | [
"def",
"get_channel",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"compatibility_mode",
":",
"# For pre-sushibar scritps that do not implement `get_channel`,",
"# we must check it this function exists before calling it...",
"if",
"hasattr",
"(",
"self",
".",
"chef_module",
",",
"'get_channel'",
")",
":",
"config",
".",
"LOGGER",
".",
"info",
"(",
"\"Calling get_channel... \"",
")",
"# Create channel (using the function in the chef script)",
"channel",
"=",
"self",
".",
"chef_module",
".",
"get_channel",
"(",
"*",
"*",
"kwargs",
")",
"# For chefs with a `create_channel` method instead of `get_channel`",
"if",
"hasattr",
"(",
"self",
".",
"chef_module",
",",
"'create_channel'",
")",
":",
"config",
".",
"LOGGER",
".",
"info",
"(",
"\"Calling create_channel... \"",
")",
"# Create channel (using the function in the chef script)",
"channel",
"=",
"self",
".",
"chef_module",
".",
"create_channel",
"(",
"*",
"*",
"kwargs",
")",
"else",
":",
"channel",
"=",
"None",
"# since no channel info, SushiBar functionality will be disabled...",
"return",
"channel",
"elif",
"hasattr",
"(",
"self",
",",
"'channel_info'",
")",
":",
"# If a sublass has an `channel_info` attribute (a dict) it doesn't need",
"# to define a `get_channel` method and instead rely on this code:",
"channel",
"=",
"ChannelNode",
"(",
"source_domain",
"=",
"self",
".",
"channel_info",
"[",
"'CHANNEL_SOURCE_DOMAIN'",
"]",
",",
"source_id",
"=",
"self",
".",
"channel_info",
"[",
"'CHANNEL_SOURCE_ID'",
"]",
",",
"title",
"=",
"self",
".",
"channel_info",
"[",
"'CHANNEL_TITLE'",
"]",
",",
"thumbnail",
"=",
"self",
".",
"channel_info",
".",
"get",
"(",
"'CHANNEL_THUMBNAIL'",
")",
",",
"language",
"=",
"self",
".",
"channel_info",
".",
"get",
"(",
"'CHANNEL_LANGUAGE'",
")",
",",
"description",
"=",
"self",
".",
"channel_info",
".",
"get",
"(",
"'CHANNEL_DESCRIPTION'",
")",
",",
")",
"return",
"channel",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'BaseChef must overrride the get_channel method'",
")"
] |
Removes the current profile from the system . | def removeProfile ( self ) : manager = self . parent ( ) prof = manager . currentProfile ( ) opts = QMessageBox . Yes | QMessageBox . No question = 'Are you sure you want to remove "%s"?' % prof . name ( ) answer = QMessageBox . question ( self , 'Remove Profile' , question , opts ) if ( answer == QMessageBox . Yes ) : manager . removeProfile ( prof ) | 11,560 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofilemanagermenu.py#L44-L55 | [
"def",
"delete_attachments",
"(",
"self",
",",
"volumeID",
",",
"attachmentsID",
")",
":",
"log",
".",
"debug",
"(",
"\"deleting attachments from volume '{}': {}\"",
".",
"format",
"(",
"volumeID",
",",
"attachmentsID",
")",
")",
"rawVolume",
"=",
"self",
".",
"_req_raw_volume",
"(",
"volumeID",
")",
"insID",
"=",
"[",
"a",
"[",
"'id'",
"]",
"for",
"a",
"in",
"rawVolume",
"[",
"'_source'",
"]",
"[",
"'_attachments'",
"]",
"]",
"# check that all requested file are present",
"for",
"id",
"in",
"attachmentsID",
":",
"if",
"id",
"not",
"in",
"insID",
":",
"raise",
"NotFoundException",
"(",
"\"could not found attachment '{}' of the volume '{}'\"",
".",
"format",
"(",
"id",
",",
"volumeID",
")",
")",
"for",
"index",
",",
"id",
"in",
"enumerate",
"(",
"attachmentsID",
")",
":",
"rawVolume",
"[",
"'_source'",
"]",
"[",
"'_attachments'",
"]",
".",
"pop",
"(",
"insID",
".",
"index",
"(",
"id",
")",
")",
"self",
".",
"_db",
".",
"modify_book",
"(",
"volumeID",
",",
"rawVolume",
"[",
"'_source'",
"]",
",",
"version",
"=",
"rawVolume",
"[",
"'_version'",
"]",
")"
] |
Saves the current profile to the current settings from the view widget . | def saveProfile ( self ) : manager = self . parent ( ) prof = manager . currentProfile ( ) # save the current profile save_prof = manager . viewWidget ( ) . saveProfile ( ) prof . setXmlElement ( save_prof . xmlElement ( ) ) | 11,561 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofilemanagermenu.py#L57-L66 | [
"def",
"is_citeable",
"(",
"publication_info",
")",
":",
"def",
"_item_has_pub_info",
"(",
"item",
")",
":",
"return",
"all",
"(",
"key",
"in",
"item",
"for",
"key",
"in",
"(",
"'journal_title'",
",",
"'journal_volume'",
")",
")",
"def",
"_item_has_page_or_artid",
"(",
"item",
")",
":",
"return",
"any",
"(",
"key",
"in",
"item",
"for",
"key",
"in",
"(",
"'page_start'",
",",
"'artid'",
")",
")",
"has_pub_info",
"=",
"any",
"(",
"_item_has_pub_info",
"(",
"item",
")",
"for",
"item",
"in",
"publication_info",
")",
"has_page_or_artid",
"=",
"any",
"(",
"_item_has_page_or_artid",
"(",
"item",
")",
"for",
"item",
"in",
"publication_info",
")",
"return",
"has_pub_info",
"and",
"has_page_or_artid"
] |
Saves the current profile as a new profile to the manager . | def saveProfileAs ( self ) : name , ok = QInputDialog . getText ( self , 'Create Profile' , 'Name:' ) if ( not name ) : return manager = self . parent ( ) prof = manager . viewWidget ( ) . saveProfile ( ) prof . setName ( nativestring ( name ) ) self . parent ( ) . addProfile ( prof ) | 11,562 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofilemanagermenu.py#L68-L79 | [
"def",
"delete_attachments",
"(",
"self",
",",
"volumeID",
",",
"attachmentsID",
")",
":",
"log",
".",
"debug",
"(",
"\"deleting attachments from volume '{}': {}\"",
".",
"format",
"(",
"volumeID",
",",
"attachmentsID",
")",
")",
"rawVolume",
"=",
"self",
".",
"_req_raw_volume",
"(",
"volumeID",
")",
"insID",
"=",
"[",
"a",
"[",
"'id'",
"]",
"for",
"a",
"in",
"rawVolume",
"[",
"'_source'",
"]",
"[",
"'_attachments'",
"]",
"]",
"# check that all requested file are present",
"for",
"id",
"in",
"attachmentsID",
":",
"if",
"id",
"not",
"in",
"insID",
":",
"raise",
"NotFoundException",
"(",
"\"could not found attachment '{}' of the volume '{}'\"",
".",
"format",
"(",
"id",
",",
"volumeID",
")",
")",
"for",
"index",
",",
"id",
"in",
"enumerate",
"(",
"attachmentsID",
")",
":",
"rawVolume",
"[",
"'_source'",
"]",
"[",
"'_attachments'",
"]",
".",
"pop",
"(",
"insID",
".",
"index",
"(",
"id",
")",
")",
"self",
".",
"_db",
".",
"modify_book",
"(",
"volumeID",
",",
"rawVolume",
"[",
"'_source'",
"]",
",",
"version",
"=",
"rawVolume",
"[",
"'_version'",
"]",
")"
] |
r Return a hexdump - dump of a string . | def hexdump ( logger , s , width = 16 , skip = True , hexii = False , begin = 0 , highlight = None ) : s = _flat ( s ) return '\n' . join ( hexdump_iter ( logger , StringIO ( s ) , width , skip , hexii , begin , highlight ) ) | 11,563 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/hexdump.py#L183-L314 | [
"def",
"updateSeriesRegistrationStatus",
"(",
")",
":",
"from",
".",
"models",
"import",
"Series",
"if",
"not",
"getConstant",
"(",
"'general__enableCronTasks'",
")",
":",
"return",
"logger",
".",
"info",
"(",
"'Checking status of Series that are open for registration.'",
")",
"open_series",
"=",
"Series",
".",
"objects",
".",
"filter",
"(",
")",
".",
"filter",
"(",
"*",
"*",
"{",
"'registrationOpen'",
":",
"True",
"}",
")",
"for",
"series",
"in",
"open_series",
":",
"series",
".",
"updateRegistrationStatus",
"(",
")"
] |
Updates the text based on the current format options . | def adjustText ( self ) : pos = self . cursorPosition ( ) self . blockSignals ( True ) super ( XLineEdit , self ) . setText ( self . formatText ( self . text ( ) ) ) self . setCursorPosition ( pos ) self . blockSignals ( False ) | 11,564 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlineedit.py#L110-L118 | [
"def",
"unregister_signal_handlers",
"(",
")",
":",
"signal",
".",
"signal",
"(",
"SIGNAL_STACKTRACE",
",",
"signal",
".",
"SIG_IGN",
")",
"signal",
".",
"signal",
"(",
"SIGNAL_PDB",
",",
"signal",
".",
"SIG_IGN",
")"
] |
Adjusts the placement of the buttons for this line edit . | def adjustButtons ( self ) : y = 1 for btn in self . buttons ( ) : btn . setIconSize ( self . iconSize ( ) ) btn . setFixedSize ( QSize ( self . height ( ) - 2 , self . height ( ) - 2 ) ) # adjust the location for the left buttons left_buttons = self . _buttons . get ( Qt . AlignLeft , [ ] ) x = ( self . cornerRadius ( ) / 2.0 ) + 2 for btn in left_buttons : btn . move ( x , y ) x += btn . width ( ) # adjust the location for the right buttons right_buttons = self . _buttons . get ( Qt . AlignRight , [ ] ) w = self . width ( ) bwidth = sum ( [ btn . width ( ) for btn in right_buttons ] ) bwidth += ( self . cornerRadius ( ) / 2.0 ) + 1 for btn in right_buttons : btn . move ( w - bwidth , y ) bwidth -= btn . width ( ) self . _buttonWidth = sum ( [ btn . width ( ) for btn in self . buttons ( ) ] ) self . adjustTextMargins ( ) | 11,565 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlineedit.py#L152-L182 | [
"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",
")"
] |
Adjusts the margins for the text based on the contents to be displayed . | def adjustTextMargins ( self ) : left_buttons = self . _buttons . get ( Qt . AlignLeft , [ ] ) if left_buttons : bwidth = left_buttons [ - 1 ] . pos ( ) . x ( ) + left_buttons [ - 1 ] . width ( ) - 4 else : bwidth = 0 + ( max ( 8 , self . cornerRadius ( ) ) - 8 ) ico = self . icon ( ) if ico and not ico . isNull ( ) : bwidth += self . iconSize ( ) . width ( ) self . setTextMargins ( bwidth , 0 , 0 , 0 ) | 11,566 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlineedit.py#L184-L199 | [
"def",
"import_data",
"(",
"args",
")",
":",
"validate_file",
"(",
"args",
".",
"filename",
")",
"validate_dispatcher",
"(",
"args",
")",
"content",
"=",
"load_search_space",
"(",
"args",
".",
"filename",
")",
"args",
".",
"port",
"=",
"get_experiment_port",
"(",
"args",
")",
"if",
"args",
".",
"port",
"is",
"not",
"None",
":",
"if",
"import_data_to_restful_server",
"(",
"args",
",",
"content",
")",
":",
"pass",
"else",
":",
"print_error",
"(",
"'Import data failed!'",
")"
] |
Clears the text from the edit . | def clear ( self ) : super ( XLineEdit , self ) . clear ( ) self . textEntered . emit ( '' ) self . textChanged . emit ( '' ) self . textEdited . emit ( '' ) | 11,567 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlineedit.py#L237-L245 | [
"def",
"define_Precip",
"(",
"self",
",",
"diameter",
",",
"density",
",",
"molecweight",
",",
"alumMPM",
")",
":",
"self",
".",
"PrecipDiameter",
"=",
"diameter",
"self",
".",
"PrecipDensity",
"=",
"density",
"self",
".",
"PrecipMolecWeight",
"=",
"molecweight",
"self",
".",
"PrecipAluminumMPM",
"=",
"alumMPM"
] |
Get a terminal capability exposes through the curses module . | def get ( cap , * args , * * kwargs ) : # Hack for readthedocs.org if 'READTHEDOCS' in os . environ : return '' if kwargs != { } : raise TypeError ( "get(): No such argument %r" % kwargs . popitem ( ) [ 0 ] ) if _cache == { } : # Fix for BPython try : curses . setupterm ( ) except : pass s = _cache . get ( cap ) if not s : s = curses . tigetstr ( cap ) if s == None : s = curses . tigetnum ( cap ) if s == - 2 : s = curses . tigetflag ( cap ) if s == - 1 : # default to empty string so tparm doesn't fail s = '' else : s = bool ( s ) _cache [ cap ] = s # if 's' is not set 'curses.tparm' will throw an error if given arguments if args and s : r = curses . tparm ( s , * args ) return r . decode ( 'utf-8' ) else : if isinstance ( s , bytes ) : return s . decode ( 'utf-8' ) else : return s | 11,568 | https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/termcap.py#L9-L49 | [
"def",
"combine_slices",
"(",
"slice_datasets",
",",
"rescale",
"=",
"None",
")",
":",
"if",
"len",
"(",
"slice_datasets",
")",
"==",
"0",
":",
"raise",
"DicomImportException",
"(",
"\"Must provide at least one DICOM dataset\"",
")",
"_validate_slices_form_uniform_grid",
"(",
"slice_datasets",
")",
"voxels",
"=",
"_merge_slice_pixel_arrays",
"(",
"slice_datasets",
",",
"rescale",
")",
"transform",
"=",
"_ijk_to_patient_xyz_transform_matrix",
"(",
"slice_datasets",
")",
"return",
"voxels",
",",
"transform"
] |
Registers a thermostat with the UH1 | def registerThermostat ( self , thermostat ) : try : type ( thermostat ) == heatmiser . HeatmiserThermostat if thermostat . address in self . thermostats . keys ( ) : raise ValueError ( "Key already present" ) else : self . thermostats [ thermostat . address ] = thermostat except ValueError : pass except Exception as e : logging . info ( "You're not adding a HeatmiiserThermostat Object" ) logging . info ( e . message ) return self . _serport | 11,569 | https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/connection.py#L49-L62 | [
"def",
"delete_marker",
"(",
"self",
",",
"iid",
")",
":",
"if",
"iid",
"==",
"tk",
".",
"ALL",
":",
"for",
"iid",
"in",
"self",
".",
"markers",
".",
"keys",
"(",
")",
":",
"self",
".",
"delete_marker",
"(",
"iid",
")",
"return",
"options",
"=",
"self",
".",
"_markers",
"[",
"iid",
"]",
"rectangle_id",
",",
"text_id",
"=",
"options",
"[",
"\"rectangle_id\"",
"]",
",",
"options",
"[",
"\"text_id\"",
"]",
"del",
"self",
".",
"_canvas_markers",
"[",
"rectangle_id",
"]",
"del",
"self",
".",
"_canvas_markers",
"[",
"text_id",
"]",
"del",
"self",
".",
"_markers",
"[",
"iid",
"]",
"self",
".",
"_timeline",
".",
"delete",
"(",
"rectangle_id",
",",
"text_id",
")"
] |
Clears out the actions for this menu and then loads the files . | def refresh ( self ) : self . clear ( ) for i , filename in enumerate ( self . filenames ( ) ) : name = '%i. %s' % ( i + 1 , os . path . basename ( filename ) ) action = self . addAction ( name ) action . setData ( wrapVariant ( filename ) ) | 11,570 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/menus/xrecentfilesmenu.py#L84-L93 | [
"def",
"_set_max_value",
"(",
"self",
",",
"max_value",
")",
":",
"self",
".",
"_external_max_value",
"=",
"max_value",
"# Check that the current value of the parameter is still within the boundaries. If not, issue a warning",
"if",
"self",
".",
"_external_max_value",
"is",
"not",
"None",
"and",
"self",
".",
"value",
">",
"self",
".",
"_external_max_value",
":",
"warnings",
".",
"warn",
"(",
"\"The current value of the parameter %s (%s) \"",
"\"was above the new maximum %s.\"",
"%",
"(",
"self",
".",
"name",
",",
"self",
".",
"value",
",",
"self",
".",
"_external_max_value",
")",
",",
"exceptions",
".",
"RuntimeWarning",
")",
"self",
".",
"value",
"=",
"self",
".",
"_external_max_value"
] |
The values for insert it can be a dict row or list tuple row . | def values ( self , values ) : if isinstance ( values , dict ) : l = [ ] for column in self . _columns : l . append ( values [ column ] ) self . _values . append ( tuple ( l ) ) else : self . _values . append ( values ) return self | 11,571 | https://github.com/whiteclover/dbpy/blob/3d9ce85f55cfb39cced22081e525f79581b26b3a/db/query/insert.py#L36-L47 | [
"def",
"file_is_seekable",
"(",
"f",
")",
":",
"try",
":",
"f",
".",
"tell",
"(",
")",
"logger",
".",
"info",
"(",
"\"File is seekable!\"",
")",
"except",
"IOError",
",",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ESPIPE",
":",
"return",
"False",
"else",
":",
"raise",
"return",
"True"
] |
Modifies the minimum width to factor in the size of the pixmaps and the number for the maximum . | def adjustMinimumWidth ( self ) : pw = self . pixmapSize ( ) . width ( ) # allow 1 pixel space between the icons
self . setMinimumWidth ( pw * self . maximum ( ) + 3 * self . maximum ( ) ) | 11,572 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xratingslider.py#L44-L52 | [
"def",
"end_prov_graph",
"(",
"self",
")",
":",
"endTime",
"=",
"Literal",
"(",
"datetime",
".",
"now",
"(",
")",
")",
"self",
".",
"prov_g",
".",
"add",
"(",
"(",
"self",
".",
"entity_d",
",",
"self",
".",
"prov",
".",
"generatedAtTime",
",",
"endTime",
")",
")",
"self",
".",
"prov_g",
".",
"add",
"(",
"(",
"self",
".",
"activity",
",",
"self",
".",
"prov",
".",
"endedAtTime",
",",
"endTime",
")",
")"
] |
OpenVPN client_disconnect method | def cli ( conf ) : config = init_config ( conf ) nas_id = config . get ( 'DEFAULT' , 'nas_id' ) secret = config . get ( 'DEFAULT' , 'radius_secret' ) nas_addr = config . get ( 'DEFAULT' , 'nas_addr' ) radius_addr = config . get ( 'DEFAULT' , 'radius_addr' ) radius_acct_port = config . getint ( 'DEFAULT' , 'radius_acct_port' ) radius_timeout = config . getint ( 'DEFAULT' , 'radius_timeout' ) status_dbfile = config . get ( 'DEFAULT' , 'statusdb' ) username = os . environ . get ( 'username' ) userip = os . environ . get ( 'ifconfig_pool_remote_ip' ) realip = os . environ . get ( 'trusted_ip' ) realport = os . environ . get ( 'trusted_port' ) session_id = md5 ( nas_addr + realip + realport ) . hexdigest ( ) req = { 'User-Name' : username } req [ 'Acct-Status-Type' ] = ACCT_STOP req [ 'Acct-Session-Id' ] = session_id req [ "Acct-Output-Octets" ] = 0 req [ "Acct-Input-Octets" ] = 0 req [ 'Acct-Session-Time' ] = 0 req [ "NAS-IP-Address" ] = nas_addr req [ "NAS-Port-Id" ] = '0/0/0:0.0' req [ "NAS-Port" ] = 0 req [ "Service-Type" ] = "Login-User" req [ "NAS-Identifier" ] = nas_id req [ "Called-Station-Id" ] = '00:00:00:00:00:00' req [ "Calling-Station-Id" ] = '00:00:00:00:00:00' req [ "Framed-IP-Address" ] = userip def shutdown ( exitcode = 0 ) : reactor . addSystemEventTrigger ( 'after' , 'shutdown' , os . _exit , exitcode ) reactor . stop ( ) def onresp ( r ) : try : statusdb . del_client ( status_dbfile , session_id ) log . msg ( 'delete online<%s> client from db' % session_id ) except Exception as e : log . err ( 'del client online error' ) log . err ( e ) shutdown ( 0 ) def onerr ( e ) : log . err ( e ) shutdown ( 1 ) d = client . send_acct ( str ( secret ) , get_dictionary ( ) , radius_addr , acctport = radius_acct_port , debug = True , * * req ) d . addCallbacks ( onresp , onerr ) reactor . callLater ( radius_timeout , shutdown , 1 ) reactor . run ( ) | 11,573 | https://github.com/talkincode/txradius/blob/b86fdbc9be41183680b82b07d3a8e8ea10926e01/txradius/openvpn/client_disconnect.py#L19-L73 | [
"def",
"to_pint",
"(",
"self",
",",
"unit_registry",
"=",
"None",
")",
":",
"if",
"unit_registry",
"is",
"None",
":",
"unit_registry",
"=",
"_pint",
".",
"UnitRegistry",
"(",
")",
"powers_dict",
"=",
"self",
".",
"units",
".",
"expr",
".",
"as_powers_dict",
"(",
")",
"units",
"=",
"[",
"]",
"for",
"unit",
",",
"pow",
"in",
"powers_dict",
".",
"items",
"(",
")",
":",
"# we have to do this because Pint doesn't recognize",
"# \"yr\" as \"year\"",
"if",
"str",
"(",
"unit",
")",
".",
"endswith",
"(",
"\"yr\"",
")",
"and",
"len",
"(",
"str",
"(",
"unit",
")",
")",
"in",
"[",
"2",
",",
"3",
"]",
":",
"unit",
"=",
"str",
"(",
"unit",
")",
".",
"replace",
"(",
"\"yr\"",
",",
"\"year\"",
")",
"units",
".",
"append",
"(",
"\"%s**(%s)\"",
"%",
"(",
"unit",
",",
"Rational",
"(",
"pow",
")",
")",
")",
"units",
"=",
"\"*\"",
".",
"join",
"(",
"units",
")",
"return",
"unit_registry",
".",
"Quantity",
"(",
"self",
".",
"value",
",",
"units",
")"
] |
Looks up the view at the inputed point . | def viewAt ( self , point ) : widget = self . childAt ( point ) if widget : return projexui . ancestor ( widget , XView ) else : return None | 11,574 | https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewwidget.py#L578-L590 | [
"def",
"DumpAsCSV",
"(",
"self",
",",
"separator",
"=",
"\",\"",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"for",
"row",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxRow",
"+",
"1",
")",
":",
"sep",
"=",
"\"\"",
"for",
"column",
"in",
"range",
"(",
"1",
",",
"self",
".",
"maxColumn",
"+",
"1",
")",
":",
"file",
".",
"write",
"(",
"\"%s\\\"%s\\\"\"",
"%",
"(",
"sep",
",",
"self",
".",
"GetCellValue",
"(",
"column",
",",
"row",
",",
"\"\"",
")",
")",
")",
"sep",
"=",
"separator",
"file",
".",
"write",
"(",
"\"\\n\"",
")"
] |
Draw molecule structure image . | def draw ( canvas , mol ) : mol . require ( "ScaleAndCenter" ) mlb = mol . size2d [ 2 ] if not mol . atom_count ( ) : return bond_type_fn = { 1 : { 0 : single_bond , 1 : wedged_single , 2 : dashed_wedged_single , 3 : wave_single , } , 2 : { 0 : cw_double , 1 : counter_cw_double , 2 : double_bond , 3 : cross_double } , 3 : { 0 : triple_bond } } # Draw bonds for u , v , bond in mol . bonds_iter ( ) : if not bond . visible : continue if ( u < v ) == bond . is_lower_first : f , s = ( u , v ) else : s , f = ( u , v ) p1 = mol . atom ( f ) . coords p2 = mol . atom ( s ) . coords if p1 == p2 : continue # avoid zero division if mol . atom ( f ) . visible : p1 = gm . t_seg ( p1 , p2 , F_AOVL , 2 ) [ 0 ] if mol . atom ( s ) . visible : p2 = gm . t_seg ( p1 , p2 , F_AOVL , 1 ) [ 1 ] color1 = mol . atom ( f ) . color color2 = mol . atom ( s ) . color bond_type_fn [ bond . order ] [ bond . type ] ( canvas , p1 , p2 , color1 , color2 , mlb ) # Draw atoms for n , atom in mol . atoms_iter ( ) : if not atom . visible : continue p = atom . coords color = atom . color # Determine text direction if atom . H_count : cosnbrs = [ ] hrzn = ( p [ 0 ] + 1 , p [ 1 ] ) for nbr in mol . graph . neighbors ( n ) : pnbr = mol . atom ( nbr ) . coords try : cosnbrs . append ( gm . dot_product ( hrzn , pnbr , p ) / gm . distance ( p , pnbr ) ) except ZeroDivisionError : pass if not cosnbrs or min ( cosnbrs ) > 0 : # [atom]< or isolated node(ex. H2O, HCl) text = atom . formula_html ( True ) canvas . draw_text ( p , text , color , "right" ) continue elif max ( cosnbrs ) < 0 : # >[atom] text = atom . formula_html ( ) canvas . draw_text ( p , text , color , "left" ) continue # -[atom]- or no hydrogens text = atom . formula_html ( ) canvas . draw_text ( p , text , color , "center" ) | 11,575 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/draw/drawer2d.py#L17-L93 | [
"def",
"busday_count_mask_NaT",
"(",
"begindates",
",",
"enddates",
",",
"out",
"=",
"None",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"empty",
"(",
"broadcast",
"(",
"begindates",
",",
"enddates",
")",
".",
"shape",
",",
"dtype",
"=",
"float",
")",
"beginmask",
"=",
"isnat",
"(",
"begindates",
")",
"endmask",
"=",
"isnat",
"(",
"enddates",
")",
"out",
"=",
"busday_count",
"(",
"# Temporarily fill in non-NaT values.",
"where",
"(",
"beginmask",
",",
"_notNaT",
",",
"begindates",
")",
",",
"where",
"(",
"endmask",
",",
"_notNaT",
",",
"enddates",
")",
",",
"out",
"=",
"out",
",",
")",
"# Fill in entries where either comparison was NaT with nan in the output.",
"out",
"[",
"beginmask",
"|",
"endmask",
"]",
"=",
"nan",
"return",
"out"
] |
Convert SMILES text to compound object | def smiles_to_compound ( smiles , assign_descriptors = True ) : it = iter ( smiles ) mol = molecule ( ) try : for token in it : mol ( token ) result , _ = mol ( None ) except KeyError as err : raise ValueError ( "Unsupported Symbol: {}" . format ( err ) ) result . graph . remove_node ( 0 ) logger . debug ( result ) if assign_descriptors : molutil . assign_descriptors ( result ) return result | 11,576 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/smilessupplier.py#L316-L334 | [
"async",
"def",
"_wrap_ws",
"(",
"self",
",",
"handler",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"method",
"=",
"self",
".",
"request_method",
"(",
")",
"# call the wrapped handler",
"data",
"=",
"await",
"handler",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"status",
"=",
"self",
".",
"responses",
".",
"get",
"(",
"method",
",",
"OK",
")",
"response",
"=",
"{",
"'type'",
":",
"'response'",
",",
"'key'",
":",
"getattr",
"(",
"self",
".",
"request",
",",
"'key'",
",",
"None",
")",
",",
"'status'",
":",
"status",
",",
"'payload'",
":",
"data",
"}",
"except",
"Exception",
"as",
"ex",
":",
"response",
"=",
"{",
"'type'",
":",
"'response'",
",",
"'key'",
":",
"getattr",
"(",
"self",
".",
"request",
",",
"'key'",
",",
"None",
")",
",",
"'status'",
":",
"getattr",
"(",
"ex",
",",
"'status'",
",",
"500",
")",
",",
"'payload'",
":",
"getattr",
"(",
"ex",
",",
"'msg'",
",",
"'general error'",
")",
"}",
"# return a formatted response object",
"return",
"self",
".",
"format",
"(",
"method",
",",
"response",
")"
] |
Convert mode weights of spin - weighted function to values on a grid | def salm2map ( salm , s , lmax , Ntheta , Nphi ) : if Ntheta < 2 or Nphi < 1 : raise ValueError ( "Input values of Ntheta={0} and Nphi={1} " . format ( Ntheta , Nphi ) + "are not allowed; they must be greater than 1 and 0, respectively." ) if lmax < 1 : raise ValueError ( "Input value of lmax={0} " . format ( lmax ) + "is not allowed; it must be greater than 0 and should be greater " + "than |s|={0}." . format ( abs ( s ) ) ) import numpy as np salm = np . ascontiguousarray ( salm , dtype = np . complex128 ) if salm . shape [ - 1 ] < N_lm ( lmax ) : raise ValueError ( "The input `salm` array of shape {0} is too small for the stated `lmax` of {1}. " . format ( salm . shape , lmax ) + "Perhaps you forgot to include the (zero) modes with ell<|s|." ) map = np . empty ( salm . shape [ : - 1 ] + ( Ntheta , Nphi ) , dtype = np . complex128 ) if salm . ndim > 1 : s = np . ascontiguousarray ( s , dtype = np . intc ) if s . ndim != salm . ndim - 1 or np . product ( s . shape ) != np . product ( salm . shape [ : - 1 ] ) : s = s * np . ones ( salm . shape [ : - 1 ] , dtype = np . intc ) _multi_salm2map ( salm , map , s , lmax , Ntheta , Nphi ) else : _salm2map ( salm , map , s , lmax , Ntheta , Nphi ) return map | 11,577 | https://github.com/moble/spinsfast/blob/02480a3f712eb88eff5faa1d4afcbdfb0c25b865/python/__init__.py#L40-L133 | [
"def",
"GetMetricMetadata",
"(",
")",
":",
"return",
"[",
"stats_utils",
".",
"CreateCounterMetadata",
"(",
"\"grr_client_unknown\"",
")",
",",
"stats_utils",
".",
"CreateCounterMetadata",
"(",
"\"grr_decoding_error\"",
")",
",",
"stats_utils",
".",
"CreateCounterMetadata",
"(",
"\"grr_decryption_error\"",
")",
",",
"stats_utils",
".",
"CreateCounterMetadata",
"(",
"\"grr_authenticated_messages\"",
")",
",",
"stats_utils",
".",
"CreateCounterMetadata",
"(",
"\"grr_unauthenticated_messages\"",
")",
",",
"stats_utils",
".",
"CreateCounterMetadata",
"(",
"\"grr_rsa_operations\"",
")",
",",
"stats_utils",
".",
"CreateCounterMetadata",
"(",
"\"grr_encrypted_cipher_cache\"",
",",
"fields",
"=",
"[",
"(",
"\"type\"",
",",
"str",
")",
"]",
")",
",",
"]"
] |
Convert values of spin - weighted function on a grid to mode weights | def map2salm ( map , s , lmax ) : import numpy as np map = np . ascontiguousarray ( map , dtype = np . complex128 ) salm = np . empty ( map . shape [ : - 2 ] + ( N_lm ( lmax ) , ) , dtype = np . complex128 ) if map . ndim > 2 : s = np . ascontiguousarray ( s , dtype = np . intc ) if s . ndim != map . ndim - 2 or np . product ( s . shape ) != np . product ( map . shape [ : - 2 ] ) : s = s * np . ones ( map . shape [ : - 2 ] , dtype = np . intc ) _multi_map2salm ( map , salm , s , lmax ) else : _map2salm ( map , salm , s , lmax ) return salm | 11,578 | https://github.com/moble/spinsfast/blob/02480a3f712eb88eff5faa1d4afcbdfb0c25b865/python/__init__.py#L136-L216 | [
"def",
"_ParseWtmp",
"(",
")",
":",
"users",
"=",
"{",
"}",
"wtmp_struct_size",
"=",
"UtmpStruct",
".",
"GetSize",
"(",
")",
"filenames",
"=",
"glob",
".",
"glob",
"(",
"\"/var/log/wtmp*\"",
")",
"+",
"[",
"\"/var/run/utmp\"",
"]",
"for",
"filename",
"in",
"filenames",
":",
"try",
":",
"wtmp",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
".",
"read",
"(",
")",
"except",
"IOError",
":",
"continue",
"for",
"offset",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"wtmp",
")",
",",
"wtmp_struct_size",
")",
":",
"try",
":",
"record",
"=",
"UtmpStruct",
"(",
"wtmp",
"[",
"offset",
":",
"offset",
"+",
"wtmp_struct_size",
"]",
")",
"except",
"utils",
".",
"ParsingError",
":",
"break",
"# Users only appear for USER_PROCESS events, others are system.",
"if",
"record",
".",
"ut_type",
"!=",
"7",
":",
"continue",
"try",
":",
"if",
"users",
"[",
"record",
".",
"ut_user",
"]",
"<",
"record",
".",
"tv_sec",
":",
"users",
"[",
"record",
".",
"ut_user",
"]",
"=",
"record",
".",
"tv_sec",
"except",
"KeyError",
":",
"users",
"[",
"record",
".",
"ut_user",
"]",
"=",
"record",
".",
"tv_sec",
"return",
"users"
] |
Take the fft of the theta extended map then zero pad and reorganize it | def Imm ( extended_map , s , lmax ) : import numpy as np extended_map = np . ascontiguousarray ( extended_map , dtype = np . complex128 ) NImm = ( 2 * lmax + 1 ) ** 2 imm = np . empty ( NImm , dtype = np . complex128 ) _Imm ( extended_map , imm , s , lmax ) return imm | 11,579 | https://github.com/moble/spinsfast/blob/02480a3f712eb88eff5faa1d4afcbdfb0c25b865/python/__init__.py#L252-L264 | [
"def",
"register_on_machine_data_changed",
"(",
"self",
",",
"callback",
")",
":",
"event_type",
"=",
"library",
".",
"VBoxEventType",
".",
"on_machine_data_changed",
"return",
"self",
".",
"event_source",
".",
"register_callback",
"(",
"callback",
",",
"event_type",
")"
] |
Base query for an url and xpath | def _query ( self , url , xpath ) : return self . session . query ( CachedRequest ) . filter ( CachedRequest . url == url ) . filter ( CachedRequest . xpath == xpath ) | 11,580 | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/cache.py#L106-L113 | [
"def",
"get_row_headers",
"(",
"rows",
",",
"row_headers_count_value",
"=",
"0",
",",
"column_headers_count",
"=",
"1",
")",
":",
"# TODO: REFACTOR ALGORITHM NEEDED",
"partial_headers",
"=",
"[",
"]",
"if",
"row_headers_count_value",
":",
"# Take partial data",
"for",
"k_index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"rows",
")",
"-",
"column_headers_count",
")",
":",
"header",
"=",
"rows",
"[",
"k_index",
"+",
"column_headers_count",
"]",
"[",
":",
"row_headers_count_value",
"]",
"partial_headers",
".",
"append",
"(",
"remove_list_duplicates",
"(",
"force_list",
"(",
"header",
")",
")",
")",
"# Populate headers",
"populated_headers",
"=",
"populate_csv_headers",
"(",
"rows",
",",
"partial_headers",
",",
"column_headers_count",
")",
"return",
"populated_headers"
] |
Get a URL via the cache . | def get ( self , url , store_on_error = False , xpath = None , rate_limit = None , log_hits = True , log_misses = True ) : try : # get cached request - if none is found, this throws a NoResultFound exception cached = self . _query ( url , xpath ) . one ( ) if log_hits : config . logger . info ( "Request cache hit: " + url ) # if the cached value is from a request that resulted in an error, throw an exception if cached . status_code != requests . codes . ok : raise RuntimeError ( "Cached request returned an error, code " + str ( cached . status_code ) ) except NoResultFound : if log_misses : config . logger . info ( "Request cache miss: " + url ) # perform the request try : # rate limit if rate_limit is not None and self . last_query is not None : to_sleep = rate_limit - ( datetime . datetime . now ( ) - self . last_query ) . total_seconds ( ) if to_sleep > 0 : time . sleep ( to_sleep ) self . last_query = datetime . datetime . now ( ) response = requests . get ( url ) status_code = response . status_code # get 'text', not 'content', because then we are sure to get unicode content = response . text response . close ( ) if xpath is not None : doc = html . fromstring ( content ) nodes = doc . xpath ( xpath ) if len ( nodes ) == 0 : # xpath not found; set content and status code, exception is raised below content = "xpath not found: " + xpath status_code = ERROR_XPATH_NOT_FOUND else : # extract desired node only content = html . tostring ( nodes [ 0 ] , encoding = 'unicode' ) except requests . ConnectionError as e : # on a connection error, write exception information to a response object status_code = ERROR_CONNECTION_ERROR content = str ( e ) # a new request cache object cached = CachedRequest ( url = str ( url ) , content = content , status_code = status_code , xpath = xpath , queried_on = datetime . datetime . now ( ) ) # if desired, store the response even if an error occurred if status_code == requests . codes . ok or store_on_error : self . session . add ( cached ) self . session . commit ( ) if status_code != requests . codes . ok : raise RuntimeError ( "Error processing the request, " + str ( status_code ) + ": " + content ) return cached . content | 11,581 | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/cache.py#L115-L202 | [
"def",
"read",
"(",
"self",
",",
"filename",
",",
"rowprefix",
"=",
"None",
",",
"colprefix",
"=",
"None",
",",
"delim",
"=",
"\":\"",
")",
":",
"self",
".",
"matrix",
"=",
"scipy",
".",
"io",
".",
"mmread",
"(",
"filename",
")",
"with",
"open",
"(",
"filename",
"+",
"\".rownames\"",
")",
"as",
"in_handle",
":",
"self",
".",
"rownames",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"in_handle",
"]",
"if",
"rowprefix",
":",
"self",
".",
"rownames",
"=",
"[",
"rowprefix",
"+",
"delim",
"+",
"x",
"for",
"x",
"in",
"self",
".",
"rownames",
"]",
"with",
"open",
"(",
"filename",
"+",
"\".colnames\"",
")",
"as",
"in_handle",
":",
"self",
".",
"colnames",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"in_handle",
"]",
"if",
"colprefix",
":",
"self",
".",
"colnames",
"=",
"[",
"colprefix",
"+",
"delim",
"+",
"x",
"for",
"x",
"in",
"self",
".",
"colnames",
"]"
] |
Get time stamp of cached query result . | def get_timestamp ( self , url , xpath = None ) : if not path . exists ( self . db_path ) : return None if self . _query ( url , xpath ) . count ( ) > 0 : return self . _query ( url , xpath ) . one ( ) . queried_on | 11,582 | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/ozelot/cache.py#L241-L257 | [
"def",
"communityvisibilitystate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_communityvisibilitystate",
"==",
"None",
":",
"return",
"None",
"elif",
"self",
".",
"_communityvisibilitystate",
"in",
"self",
".",
"VisibilityState",
":",
"return",
"self",
".",
"VisibilityState",
"[",
"self",
".",
"_communityvisibilitystate",
"]",
"else",
":",
"#Invalid State",
"return",
"None"
] |
Method to build the base logging system . By default logging level is set to INFO . | def set_logger ( self ) : logger = logging . getLogger ( __name__ ) logger . setLevel ( level = logging . INFO ) logger_file = os . path . join ( self . logs_path , 'dingtalk_sdk.logs' ) logger_handler = logging . FileHandler ( logger_file ) logger_handler . setLevel ( logging . INFO ) logger_formatter = logging . Formatter ( '[%(asctime)s | %(name)s | %(levelname)s] %(message)s' ) logger_handler . setFormatter ( logger_formatter ) logger . addHandler ( logger_handler ) return logger | 11,583 | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/base_request.py#L22-L35 | [
"def",
"retry",
"(",
"*",
"excepts",
")",
":",
"@",
"decorator",
".",
"decorator",
"def",
"new_func",
"(",
"func",
",",
"job",
")",
":",
"'''No docstring'''",
"try",
":",
"func",
"(",
"job",
")",
"except",
"tuple",
"(",
"excepts",
")",
":",
"job",
".",
"retry",
"(",
")",
"return",
"new_func"
] |
Get the original response of requests | def get_response ( self ) : request = getattr ( requests , self . request_method , None ) if request is None and self . _request_method is None : raise ValueError ( "A effective http request method must be set" ) if self . request_url is None : raise ValueError ( "Fatal error occurred, the class property \"request_url\" is" "set to None, reset it with an effective url of dingtalk api." ) response = request ( self . request_url , * * self . kwargs ) self . response = response return response | 11,584 | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/base_request.py#L55-L67 | [
"def",
"_get_port_speed_price_id",
"(",
"items",
",",
"port_speed",
",",
"no_public",
",",
"location",
")",
":",
"for",
"item",
"in",
"items",
":",
"if",
"utils",
".",
"lookup",
"(",
"item",
",",
"'itemCategory'",
",",
"'categoryCode'",
")",
"!=",
"'port_speed'",
":",
"continue",
"# Check for correct capacity and if the item matches private only",
"if",
"any",
"(",
"[",
"int",
"(",
"utils",
".",
"lookup",
"(",
"item",
",",
"'capacity'",
")",
")",
"!=",
"port_speed",
",",
"_is_private_port_speed_item",
"(",
"item",
")",
"!=",
"no_public",
",",
"not",
"_is_bonded",
"(",
"item",
")",
"]",
")",
":",
"continue",
"for",
"price",
"in",
"item",
"[",
"'prices'",
"]",
":",
"if",
"not",
"_matches_location",
"(",
"price",
",",
"location",
")",
":",
"continue",
"return",
"price",
"[",
"'id'",
"]",
"raise",
"SoftLayer",
".",
"SoftLayerError",
"(",
"\"Could not find valid price for port speed: '%s'\"",
"%",
"port_speed",
")"
] |
Sends a raw command to the Slack server generating a message ID automatically . | def sendCommand ( self , * * msg ) : assert 'type' in msg , 'Message type is required.' msg [ 'id' ] = self . next_message_id self . next_message_id += 1 if self . next_message_id >= maxint : self . next_message_id = 1 self . sendMessage ( json . dumps ( msg ) ) return msg [ 'id' ] | 11,585 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/protocol.py#L70-L83 | [
"def",
"infer_freq",
"(",
"index",
",",
"warn",
"=",
"True",
")",
":",
"import",
"pandas",
"as",
"pd",
"if",
"isinstance",
"(",
"index",
",",
"ABCSeries",
")",
":",
"values",
"=",
"index",
".",
"_values",
"if",
"not",
"(",
"is_datetime64_dtype",
"(",
"values",
")",
"or",
"is_timedelta64_dtype",
"(",
"values",
")",
"or",
"values",
".",
"dtype",
"==",
"object",
")",
":",
"raise",
"TypeError",
"(",
"\"cannot infer freq from a non-convertible dtype \"",
"\"on a Series of {dtype}\"",
".",
"format",
"(",
"dtype",
"=",
"index",
".",
"dtype",
")",
")",
"index",
"=",
"values",
"if",
"is_period_arraylike",
"(",
"index",
")",
":",
"raise",
"TypeError",
"(",
"\"PeriodIndex given. Check the `freq` attribute \"",
"\"instead of using infer_freq.\"",
")",
"elif",
"is_timedelta64_dtype",
"(",
"index",
")",
":",
"# Allow TimedeltaIndex and TimedeltaArray",
"inferer",
"=",
"_TimedeltaFrequencyInferer",
"(",
"index",
",",
"warn",
"=",
"warn",
")",
"return",
"inferer",
".",
"get_freq",
"(",
")",
"if",
"isinstance",
"(",
"index",
",",
"pd",
".",
"Index",
")",
"and",
"not",
"isinstance",
"(",
"index",
",",
"pd",
".",
"DatetimeIndex",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"(",
"pd",
".",
"Int64Index",
",",
"pd",
".",
"Float64Index",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"cannot infer freq from a non-convertible index \"",
"\"type {type}\"",
".",
"format",
"(",
"type",
"=",
"type",
"(",
"index",
")",
")",
")",
"index",
"=",
"index",
".",
"values",
"if",
"not",
"isinstance",
"(",
"index",
",",
"pd",
".",
"DatetimeIndex",
")",
":",
"try",
":",
"index",
"=",
"pd",
".",
"DatetimeIndex",
"(",
"index",
")",
"except",
"AmbiguousTimeError",
":",
"index",
"=",
"pd",
".",
"DatetimeIndex",
"(",
"index",
".",
"asi8",
")",
"inferer",
"=",
"_FrequencyInferer",
"(",
"index",
",",
"warn",
"=",
"warn",
")",
"return",
"inferer",
".",
"get_freq",
"(",
")"
] |
Sends a chat message to a given id user group or channel . | def sendChatMessage ( self , text , id = None , user = None , group = None , channel = None , parse = 'none' , link_names = True , unfurl_links = True , unfurl_media = False , send_with_api = False , icon_emoji = None , icon_url = None , username = None , attachments = None , thread_ts = None , reply_broadcast = False ) : if id is not None : assert user is None , 'id and user cannot both be set.' assert group is None , 'id and group cannot both be set.' assert channel is None , 'id and channel cannot both be set.' elif user is not None : assert group is None , 'user and group cannot both be set.' assert channel is None , 'user and channel cannot both be set.' # Private message to user, get the IM name id = self . meta . find_im_by_user_name ( user , auto_create = True ) [ 0 ] elif group is not None : assert channel is None , 'group and channel cannot both be set.' # Message to private group, get the group name. id = self . meta . find_group_by_name ( group ) [ 0 ] elif channel is not None : # Message sent to a channel id = self . meta . find_channel_by_name ( channel ) [ 0 ] else : raise Exception , 'Should not reach here.' if send_with_api : return self . meta . api . chat . postMessage ( token = self . meta . token , channel = id , text = text , parse = parse , link_names = link_names , unfurl_links = unfurl_links , unfurl_media = unfurl_media , icon_url = icon_url , icon_emoji = icon_emoji , username = username , attachments = attachments , thread_ts = thread_ts , reply_broadcast = reply_broadcast , ) else : assert icon_url is None , 'icon_url can only be set if send_with_api is True' assert icon_emoji is None , 'icon_emoji can only be set if send_with_api is True' assert username is None , 'username can only be set if send_with_api is True' return self . sendCommand ( type = 'message' , channel = id , text = text , parse = parse , link_names = link_names , unfurl_links = unfurl_links , unfurl_media = unfurl_media , thread_ts = thread_ts , reply_broadcast = reply_broadcast , ) | 11,586 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/protocol.py#L86-L155 | [
"def",
"fetch",
"(",
"self",
",",
"vault_client",
")",
":",
"backends",
"=",
"[",
"(",
"self",
".",
"mounts",
",",
"SecretBackend",
")",
",",
"(",
"self",
".",
"auths",
",",
"AuthBackend",
")",
",",
"(",
"self",
".",
"logs",
",",
"LogBackend",
")",
"]",
"for",
"b_list",
",",
"b_class",
"in",
"backends",
":",
"backend_list",
"=",
"b_list",
"(",
")",
"if",
"backend_list",
":",
"existing",
"=",
"getattr",
"(",
"vault_client",
",",
"b_class",
".",
"list_fun",
")",
"(",
")",
"for",
"backend",
"in",
"backend_list",
":",
"backend",
".",
"fetch",
"(",
"vault_client",
",",
"existing",
")",
"for",
"rsc",
"in",
"self",
".",
"resources",
"(",
")",
":",
"if",
"issubclass",
"(",
"type",
"(",
"rsc",
")",
",",
"Secret",
")",
":",
"nc_exists",
"=",
"(",
"rsc",
".",
"mount",
"!=",
"'cubbyhole'",
"and",
"find_backend",
"(",
"rsc",
".",
"mount",
",",
"self",
".",
"_mounts",
")",
".",
"existing",
")",
"if",
"nc_exists",
"or",
"rsc",
".",
"mount",
"==",
"'cubbyhole'",
":",
"rsc",
".",
"fetch",
"(",
"vault_client",
")",
"elif",
"issubclass",
"(",
"type",
"(",
"rsc",
")",
",",
"Auth",
")",
":",
"if",
"find_backend",
"(",
"rsc",
".",
"mount",
",",
"self",
".",
"_auths",
")",
".",
"existing",
":",
"rsc",
".",
"fetch",
"(",
"vault_client",
")",
"elif",
"issubclass",
"(",
"type",
"(",
"rsc",
")",
",",
"Mount",
")",
":",
"rsc",
".",
"existing",
"=",
"find_backend",
"(",
"rsc",
".",
"mount",
",",
"self",
".",
"_mounts",
")",
".",
"existing",
"else",
":",
"rsc",
".",
"fetch",
"(",
"vault_client",
")",
"return",
"self"
] |
Entry point for the bolt executable . | def run ( ) : options = btoptions . Options ( ) btlog . initialize_logging ( options . log_level , options . log_file ) app = btapp . get_application ( ) app . run ( ) | 11,587 | https://github.com/abantos/bolt/blob/8b6a911d4a7b1a6e870748a523c9b2b91997c773/bolt/__init__.py#L31-L38 | [
"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",
")"
] |
Save molecules to the SDFile format file | def mols_to_file ( mols , path ) : with open ( path , 'w' ) as f : f . write ( mols_to_text ( mols ) ) | 11,588 | https://github.com/mojaie/chorus/blob/fc7fe23a0272554c67671645ab07830b315eeb1b/chorus/v2000writer.py#L130-L138 | [
"def",
"set_source",
"(",
"self",
",",
"propname",
",",
"pores",
")",
":",
"locs",
"=",
"self",
".",
"tomask",
"(",
"pores",
"=",
"pores",
")",
"if",
"(",
"not",
"np",
".",
"all",
"(",
"np",
".",
"isnan",
"(",
"self",
"[",
"'pore.bc_value'",
"]",
"[",
"locs",
"]",
")",
")",
")",
"or",
"(",
"not",
"np",
".",
"all",
"(",
"np",
".",
"isnan",
"(",
"self",
"[",
"'pore.bc_rate'",
"]",
"[",
"locs",
"]",
")",
")",
")",
":",
"raise",
"Exception",
"(",
"'Boundary conditions already present in given '",
"+",
"'pores, cannot also assign source terms'",
")",
"self",
"[",
"propname",
"]",
"=",
"locs",
"self",
".",
"settings",
"[",
"'sources'",
"]",
".",
"append",
"(",
"propname",
")"
] |
Starts the client listener to listen for server responses . | def listen ( self ) : logger . info ( "Listening on port " + str ( self . listener . listen_port ) ) self . listener . listen ( ) | 11,589 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/client.py#L158-L170 | [
"def",
"wbmax",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float '",
"'for field `wbmax`'",
".",
"format",
"(",
"value",
")",
")",
"self",
".",
"_wbmax",
"=",
"value"
] |
Processes messages that have been delivered from the transport protocol . | def retransmit ( self , data ) : # Handle retransmitting REGISTER requests if we don't hear back from # the server. if data [ "method" ] == "REGISTER" : if not self . registered and self . register_retries < self . max_retries : logger . debug ( "<%s> Timeout exceeded. " % str ( self . cuuid ) + "Retransmitting REGISTER request." ) self . register_retries += 1 self . register ( data [ "address" ] , retry = False ) else : logger . debug ( "<%s> No need to retransmit." % str ( self . cuuid ) ) if data [ "method" ] == "EVENT" : if data [ "euuid" ] in self . event_uuids : # Increment the current retry count of the euuid self . event_uuids [ data [ "euuid" ] ] [ "retry" ] += 1 if self . event_uuids [ data [ "euuid" ] ] [ "retry" ] > self . max_retries : logger . debug ( "<%s> Max retries exceeded. Timed out waiting " "for server for event: %s" % ( data [ "cuuid" ] , data [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Deleting event from currently " "processing event uuids" % ( data [ "cuuid" ] , str ( data [ "euuid" ] ) ) ) del self . event_uuids [ data [ "euuid" ] ] else : # Retransmit that shit self . listener . send_datagram ( serialize_data ( data , self . compression , self . encryption , self . server_key ) , self . server ) # Then we set another schedule to check again logger . debug ( "<%s> <euuid:%s> Scheduling to retry in %s " "seconds" % ( data [ "cuuid" ] , str ( data [ "euuid" ] ) , str ( self . timeout ) ) ) self . listener . call_later ( self . timeout , self . retransmit , data ) else : logger . debug ( "<%s> <euuid:%s> No need to " "retransmit." % ( str ( self . cuuid ) , str ( data [ "euuid" ] ) ) ) | 11,590 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/client.py#L173-L230 | [
"def",
"minion_config",
"(",
"path",
",",
"env_var",
"=",
"'SALT_MINION_CONFIG'",
",",
"defaults",
"=",
"None",
",",
"cache_minion_id",
"=",
"False",
",",
"ignore_config_errors",
"=",
"True",
",",
"minion_id",
"=",
"None",
",",
"role",
"=",
"'minion'",
")",
":",
"if",
"defaults",
"is",
"None",
":",
"defaults",
"=",
"DEFAULT_MINION_OPTS",
".",
"copy",
"(",
")",
"if",
"not",
"os",
".",
"environ",
".",
"get",
"(",
"env_var",
",",
"None",
")",
":",
"# No valid setting was given using the configuration variable.",
"# Lets see is SALT_CONFIG_DIR is of any use",
"salt_config_dir",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SALT_CONFIG_DIR'",
",",
"None",
")",
"if",
"salt_config_dir",
":",
"env_config_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"salt_config_dir",
",",
"'minion'",
")",
"if",
"salt_config_dir",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"env_config_file_path",
")",
":",
"# We can get a configuration file using SALT_CONFIG_DIR, let's",
"# update the environment with this information",
"os",
".",
"environ",
"[",
"env_var",
"]",
"=",
"env_config_file_path",
"overrides",
"=",
"load_config",
"(",
"path",
",",
"env_var",
",",
"DEFAULT_MINION_OPTS",
"[",
"'conf_file'",
"]",
")",
"default_include",
"=",
"overrides",
".",
"get",
"(",
"'default_include'",
",",
"defaults",
"[",
"'default_include'",
"]",
")",
"include",
"=",
"overrides",
".",
"get",
"(",
"'include'",
",",
"[",
"]",
")",
"overrides",
".",
"update",
"(",
"include_config",
"(",
"default_include",
",",
"path",
",",
"verbose",
"=",
"False",
",",
"exit_on_config_errors",
"=",
"not",
"ignore_config_errors",
")",
")",
"overrides",
".",
"update",
"(",
"include_config",
"(",
"include",
",",
"path",
",",
"verbose",
"=",
"True",
",",
"exit_on_config_errors",
"=",
"not",
"ignore_config_errors",
")",
")",
"opts",
"=",
"apply_minion_config",
"(",
"overrides",
",",
"defaults",
",",
"cache_minion_id",
"=",
"cache_minion_id",
",",
"minion_id",
"=",
"minion_id",
")",
"opts",
"[",
"'__role'",
"]",
"=",
"role",
"apply_sdb",
"(",
"opts",
")",
"_validate_opts",
"(",
"opts",
")",
"return",
"opts"
] |
Processes messages that have been delivered from the transport protocol | def handle_message ( self , msg , host ) : logger . debug ( "Executing handle_message method." ) response = None # Unserialize the data packet # If encryption is enabled, and we've receive the server's public key # already, try to decrypt if self . encryption and self . server_key : msg_data = unserialize_data ( msg , self . compression , self . encryption ) else : msg_data = unserialize_data ( msg , self . compression ) # Log the packet logger . debug ( "Packet received: " + pformat ( msg_data ) ) # If the message data is blank, return none if not msg_data : return response if "method" in msg_data : if msg_data [ "method" ] == "OHAI Client" : logger . debug ( "<%s> Autodiscover response from server received " "from: %s" % ( self . cuuid , host [ 0 ] ) ) self . discovered_servers [ host ] = [ msg_data [ "version" ] , msg_data [ "server_name" ] ] # Try to register with the discovered server if self . autoregistering : self . register ( host ) self . autoregistering = False elif msg_data [ "method" ] == "NOTIFY" : self . event_notifies [ msg_data [ "euuid" ] ] = msg_data [ "event_data" ] logger . debug ( "<%s> Notify received" % self . cuuid ) logger . debug ( "<%s> Notify event buffer: %s" % ( self . cuuid , pformat ( self . event_notifies ) ) ) # Send an OK NOTIFY to the server confirming we got the message response = serialize_data ( { "cuuid" : str ( self . cuuid ) , "method" : "OK NOTIFY" , "euuid" : msg_data [ "euuid" ] } , self . compression , self . encryption , self . server_key ) elif msg_data [ "method" ] == "OK REGISTER" : logger . debug ( "<%s> Ok register received" % self . cuuid ) self . registered = True self . server = host # If the server sent us their public key, store it if "encryption" in msg_data and self . encryption : self . server_key = PublicKey ( msg_data [ "encryption" ] [ 0 ] , msg_data [ "encryption" ] [ 1 ] ) elif ( msg_data [ "method" ] == "LEGAL" or msg_data [ "method" ] == "ILLEGAL" ) : logger . debug ( "<%s> Legality message received" % str ( self . cuuid ) ) self . legal_check ( msg_data ) # Send an OK EVENT response to the server confirming we # received the message response = serialize_data ( { "cuuid" : str ( self . cuuid ) , "method" : "OK EVENT" , "euuid" : msg_data [ "euuid" ] } , self . compression , self . encryption , self . server_key ) logger . debug ( "Packet processing completed" ) return response | 11,591 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/client.py#L233-L321 | [
"def",
"weld_variance",
"(",
"array",
",",
"weld_type",
")",
":",
"weld_obj_mean",
"=",
"weld_mean",
"(",
"array",
",",
"weld_type",
")",
"obj_id",
",",
"weld_obj",
"=",
"create_weld_object",
"(",
"array",
")",
"weld_obj_mean_id",
"=",
"get_weld_obj_id",
"(",
"weld_obj",
",",
"weld_obj_mean",
")",
"weld_template",
"=",
"_weld_variance_code",
"weld_obj",
".",
"weld_code",
"=",
"weld_template",
".",
"format",
"(",
"array",
"=",
"obj_id",
",",
"type",
"=",
"weld_type",
",",
"mean",
"=",
"weld_obj_mean_id",
")",
"return",
"weld_obj"
] |
This function will send out an autodiscover broadcast to find a Neteria server . Any servers that respond with an OHAI CLIENT packet are servers that we can connect to . Servers that respond are stored in the discovered_servers list . | def autodiscover ( self , autoregister = True ) : logger . debug ( "<%s> Sending autodiscover message to broadcast " "address" % str ( self . cuuid ) ) if not self . listener . listening : logger . warning ( "Neteria client is not listening. The client " "will not be able to process responses from the server" ) message = serialize_data ( { "method" : "OHAI" , "version" : self . version , "cuuid" : str ( self . cuuid ) } , self . compression , encryption = False ) if autoregister : self . autoregistering = True self . listener . send_datagram ( message , ( "<broadcast>" , self . server_port ) , message_type = "broadcast" ) | 11,592 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/client.py#L324-L360 | [
"def",
"flush",
"(",
"self",
")",
":",
"Queue",
".",
"flush",
"(",
"self",
")",
"Event",
".",
"delete",
"(",
"self",
")",
"Crawl",
".",
"flush",
"(",
"self",
")"
] |
This function will send a register packet to the discovered Neteria server . | def register ( self , address , retry = True ) : logger . debug ( "<%s> Sending REGISTER request to: %s" % ( str ( self . cuuid ) , str ( address ) ) ) if not self . listener . listening : logger . warning ( "Neteria client is not listening." ) # Construct the message to send message = { "method" : "REGISTER" , "cuuid" : str ( self . cuuid ) } # If we have encryption enabled, send our public key with our REGISTER # request if self . encryption : message [ "encryption" ] = [ self . encryption . n , self . encryption . e ] # Send a REGISTER to the server self . listener . send_datagram ( serialize_data ( message , self . compression , encryption = False ) , address ) if retry : # Reset the current number of REGISTER retries self . register_retries = 0 # Schedule a task to run in x seconds to check to see if we've timed # out in receiving a response from the server self . listener . call_later ( self . timeout , self . retransmit , { "method" : "REGISTER" , "address" : address } ) | 11,593 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/client.py#L363-L408 | [
"def",
"retention_period",
"(",
"self",
",",
"value",
")",
":",
"policy",
"=",
"self",
".",
"_properties",
".",
"setdefault",
"(",
"\"retentionPolicy\"",
",",
"{",
"}",
")",
"if",
"value",
"is",
"not",
"None",
":",
"policy",
"[",
"\"retentionPeriod\"",
"]",
"=",
"str",
"(",
"value",
")",
"else",
":",
"policy",
"=",
"None",
"self",
".",
"_patch_property",
"(",
"\"retentionPolicy\"",
",",
"policy",
")"
] |
This function will send event packets to the server . This is the main method you would use to send data from your application to the server . | def event ( self , event_data , priority = "normal" , event_method = "EVENT" ) : logger . debug ( "event: " + str ( event_data ) ) # Generate an event UUID for this event euuid = uuid . uuid1 ( ) logger . debug ( "<%s> <euuid:%s> Sending event data to server: " "%s" % ( str ( self . cuuid ) , str ( euuid ) , str ( self . server ) ) ) if not self . listener . listening : logger . warning ( "Neteria client is not listening." ) # If we're not even registered, don't even bother. if not self . registered : logger . warning ( "<%s> <euuid:%s> Client is currently not registered. " "Event not sent." % ( str ( self . cuuid ) , str ( euuid ) ) ) return False # Send the event data to the server packet = { "method" : event_method , "cuuid" : str ( self . cuuid ) , "euuid" : str ( euuid ) , "event_data" : event_data , "timestamp" : str ( datetime . now ( ) ) , "retry" : 0 , "priority" : priority } self . listener . send_datagram ( serialize_data ( packet , self . compression , self . encryption , self . server_key ) , self . server ) logger . debug ( "<%s> Sending EVENT Packet: %s" % ( str ( self . cuuid ) , pformat ( packet ) ) ) # Set the sent event to our event buffer to see if we need to roll back # or anything self . event_uuids [ str ( euuid ) ] = packet # Now we need to reschedule a timeout/retransmit check logger . debug ( "<%s> Scheduling retry in %s seconds" % ( str ( self . cuuid ) , str ( self . timeout ) ) ) self . listener . call_later ( self . timeout , self . retransmit , packet ) return euuid | 11,594 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/client.py#L411-L487 | [
"def",
"create",
"(",
"self",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"path",
"=",
"'/creditor_bank_accounts'",
"if",
"params",
"is",
"not",
"None",
":",
"params",
"=",
"{",
"self",
".",
"_envelope_key",
"(",
")",
":",
"params",
"}",
"try",
":",
"response",
"=",
"self",
".",
"_perform_request",
"(",
"'POST'",
",",
"path",
",",
"params",
",",
"headers",
",",
"retry_failures",
"=",
"True",
")",
"except",
"errors",
".",
"IdempotentCreationConflictError",
"as",
"err",
":",
"return",
"self",
".",
"get",
"(",
"identity",
"=",
"err",
".",
"conflicting_resource_id",
",",
"params",
"=",
"params",
",",
"headers",
"=",
"headers",
")",
"return",
"self",
".",
"_resource_for",
"(",
"response",
")"
] |
This method handles event legality check messages from the server . | def legal_check ( self , message ) : # If the event was legal, remove it from our event buffer if message [ "method" ] == "LEGAL" : logger . debug ( "<%s> <euuid:%s> Event LEGAL" % ( str ( self . cuuid ) , message [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Removing event from event " "buffer." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) # If the message was a high priority, then we keep track of legal # events too if message [ "priority" ] == "high" : self . event_confirmations [ message [ "euuid" ] ] = self . event_uuids [ message [ "euuid" ] ] logger . debug ( "<%s> <euuid:%s> Event was high priority. Adding " "to confirmations buffer." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Current event confirmation " "buffer: %s" % ( str ( self . cuuid ) , message [ "euuid" ] , pformat ( self . event_confirmations ) ) ) # Try and remove the event from the currently processing events try : del self . event_uuids [ message [ "euuid" ] ] except KeyError : logger . warning ( "<%s> <euuid:%s> Euuid does not exist in event " "buffer. Key was removed before we could process " "it." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) # If the event was illegal, remove it from our event buffer and add it # to our rollback list elif message [ "method" ] == "ILLEGAL" : logger . debug ( "<%s> <euuid:%s> Event ILLEGAL" % ( str ( self . cuuid ) , message [ "euuid" ] ) ) logger . debug ( "<%s> <euuid:%s> Removing event from event buffer and " "adding to rollback buffer." % ( str ( self . cuuid ) , message [ "euuid" ] ) ) self . event_rollbacks [ message [ "euuid" ] ] = self . event_uuids [ message [ "euuid" ] ] del self . event_uuids [ message [ "euuid" ] ] | 11,595 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/client.py#L490-L543 | [
"def",
"to_xlsx",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"xlsxwriter",
".",
"workbook",
"import",
"Workbook",
"as",
"_Workbook",
"self",
".",
"workbook_obj",
"=",
"_Workbook",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"workbook_obj",
".",
"set_calc_mode",
"(",
"self",
".",
"calc_mode",
")",
"for",
"worksheet",
"in",
"self",
".",
"itersheets",
"(",
")",
":",
"worksheet",
".",
"to_xlsx",
"(",
"workbook",
"=",
"self",
")",
"self",
".",
"workbook_obj",
".",
"filename",
"=",
"self",
".",
"filename",
"if",
"self",
".",
"filename",
":",
"self",
".",
"workbook_obj",
".",
"close",
"(",
")",
"return",
"self",
".",
"workbook_obj"
] |
Locu Venue Search API Call Wrapper | def search ( self , category = None , cuisine = None , location = ( None , None ) , radius = None , tl_coord = ( None , None ) , br_coord = ( None , None ) , name = None , country = None , locality = None , region = None , postal_code = None , street_address = None , website_url = None , has_menu = None , open_at = None ) : params = self . _get_params ( category = category , cuisine = cuisine , location = location , radius = radius , tl_coord = tl_coord , br_coord = br_coord , name = name , country = country , locality = locality , region = region , postal_code = postal_code , street_address = street_address , website_url = website_url , has_menu = has_menu , open_at = open_at ) return self . _create_query ( 'search' , params ) | 11,596 | https://github.com/Locu-Unofficial/locu-python/blob/fcdf136b68333ab7055e623591801dd35df3bc45/locu/api.py#L147-L199 | [
"def",
"decompress_messages",
"(",
"self",
",",
"partitions_offmsgs",
")",
":",
"for",
"pomsg",
"in",
"partitions_offmsgs",
":",
"if",
"pomsg",
"[",
"'message'",
"]",
":",
"pomsg",
"[",
"'message'",
"]",
"=",
"self",
".",
"decompress_fun",
"(",
"pomsg",
"[",
"'message'",
"]",
")",
"yield",
"pomsg"
] |
Takes the dictionary that is returned by search or search_next function and gets the next batch of results | def search_next ( self , obj ) : if 'meta' in obj and 'next' in obj [ 'meta' ] and obj [ 'meta' ] [ 'next' ] != None : uri = self . api_url % obj [ 'meta' ] [ 'next' ] header , content = self . _http_uri_request ( uri ) resp = json . loads ( content ) if not self . _is_http_response_ok ( header ) : error = resp . get ( 'error_message' , 'Unknown Error' ) raise HttpException ( header . status , header . reason , error ) return resp return { } | 11,597 | https://github.com/Locu-Unofficial/locu-python/blob/fcdf136b68333ab7055e623591801dd35df3bc45/locu/api.py#L201-L222 | [
"def",
"update_required",
"(",
"srcpth",
",",
"dstpth",
")",
":",
"return",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dstpth",
")",
"or",
"os",
".",
"stat",
"(",
"srcpth",
")",
".",
"st_mtime",
">",
"os",
".",
"stat",
"(",
"dstpth",
")",
".",
"st_mtime"
] |
Locu Venue Details API Call Wrapper | def get_details ( self , ids ) : if isinstance ( ids , list ) : if len ( ids ) > 5 : ids = ids [ : 5 ] id_param = ';' . join ( ids ) + '/' else : ids = str ( ids ) id_param = ids + '/' header , content = self . _http_request ( id_param ) resp = json . loads ( content ) if not self . _is_http_response_ok ( header ) : error = resp . get ( 'error_message' , 'Unknown Error' ) raise HttpException ( header . status , header . reason , error ) return resp | 11,598 | https://github.com/Locu-Unofficial/locu-python/blob/fcdf136b68333ab7055e623591801dd35df3bc45/locu/api.py#L280-L302 | [
"def",
"grep_log",
"(",
"self",
",",
"expr",
",",
"filename",
"=",
"'system.log'",
",",
"from_mark",
"=",
"None",
")",
":",
"matchings",
"=",
"[",
"]",
"pattern",
"=",
"re",
".",
"compile",
"(",
"expr",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"get_path",
"(",
")",
",",
"'logs'",
",",
"filename",
")",
")",
"as",
"f",
":",
"if",
"from_mark",
":",
"f",
".",
"seek",
"(",
"from_mark",
")",
"for",
"line",
"in",
"f",
":",
"m",
"=",
"pattern",
".",
"search",
"(",
"line",
")",
"if",
"m",
":",
"matchings",
".",
"append",
"(",
"(",
"line",
",",
"m",
")",
")",
"return",
"matchings"
] |
Given a venue id returns a list of menus associated with a venue | def get_menus ( self , id ) : resp = self . get_details ( [ id ] ) menus = [ ] for obj in resp [ 'objects' ] : if obj [ 'has_menu' ] : menus += obj [ 'menus' ] return menus | 11,599 | https://github.com/Locu-Unofficial/locu-python/blob/fcdf136b68333ab7055e623591801dd35df3bc45/locu/api.py#L304-L314 | [
"async",
"def",
"write",
"(",
"self",
",",
"writer",
":",
"Any",
",",
"close_boundary",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_parts",
":",
"return",
"for",
"part",
",",
"encoding",
",",
"te_encoding",
"in",
"self",
".",
"_parts",
":",
"await",
"writer",
".",
"write",
"(",
"b'--'",
"+",
"self",
".",
"_boundary",
"+",
"b'\\r\\n'",
")",
"await",
"writer",
".",
"write",
"(",
"part",
".",
"_binary_headers",
")",
"if",
"encoding",
"or",
"te_encoding",
":",
"w",
"=",
"MultipartPayloadWriter",
"(",
"writer",
")",
"if",
"encoding",
":",
"w",
".",
"enable_compression",
"(",
"encoding",
")",
"if",
"te_encoding",
":",
"w",
".",
"enable_encoding",
"(",
"te_encoding",
")",
"await",
"part",
".",
"write",
"(",
"w",
")",
"# type: ignore",
"await",
"w",
".",
"write_eof",
"(",
")",
"else",
":",
"await",
"part",
".",
"write",
"(",
"writer",
")",
"await",
"writer",
".",
"write",
"(",
"b'\\r\\n'",
")",
"if",
"close_boundary",
":",
"await",
"writer",
".",
"write",
"(",
"b'--'",
"+",
"self",
".",
"_boundary",
"+",
"b'--\\r\\n'",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.