idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
27,900
def compress ( bytes , target ) : length = len ( bytes ) if target > length : raise ValueError ( "Fewer input bytes than requested output" ) seg_size = length // target segments = [ bytes [ i * seg_size : ( i + 1 ) * seg_size ] for i in range ( target ) ] segments [ - 1 ] . extend ( bytes [ target * seg_size : ] ) chec...
Compress a list of byte values to a fixed target length .
27,901
def uuid ( self , ** params ) : digest = str ( uuidlib . uuid4 ( ) ) . replace ( '-' , '' ) return self . humanize ( digest , ** params ) , digest
Generate a UUID with a human - readable representation .
27,902
def async_task ( func , * args , ** kwargs ) : keywords = kwargs . copy ( ) opt_keys = ( 'hook' , 'group' , 'save' , 'sync' , 'cached' , 'ack_failure' , 'iter_count' , 'iter_cached' , 'chain' , 'broker' ) q_options = keywords . pop ( 'q_options' , { } ) tag = uuid ( ) task = { 'id' : tag [ 1 ] , 'name' : keywords . pop...
Queue a task for the cluster .
27,903
def schedule ( func , * args , ** kwargs ) : name = kwargs . pop ( 'name' , None ) hook = kwargs . pop ( 'hook' , None ) schedule_type = kwargs . pop ( 'schedule_type' , Schedule . ONCE ) minutes = kwargs . pop ( 'minutes' , None ) repeats = kwargs . pop ( 'repeats' , - 1 ) next_run = kwargs . pop ( 'next_run' , timezo...
Create a schedule .
27,904
def result ( task_id , wait = 0 , cached = Conf . CACHED ) : if cached : return result_cached ( task_id , wait ) start = time ( ) while True : r = Task . get_result ( task_id ) if r : return r if ( time ( ) - start ) * 1000 >= wait >= 0 : break sleep ( 0.01 )
Return the result of the named task .
27,905
def result_cached ( task_id , wait = 0 , broker = None ) : if not broker : broker = get_broker ( ) start = time ( ) while True : r = broker . cache . get ( '{}:{}' . format ( broker . list_key , task_id ) ) if r : return SignedPackage . loads ( r ) [ 'result' ] if ( time ( ) - start ) * 1000 >= wait >= 0 : break sleep ...
Return the result from the cache backend
27,906
def result_group ( group_id , failures = False , wait = 0 , count = None , cached = Conf . CACHED ) : if cached : return result_group_cached ( group_id , failures , wait , count ) start = time ( ) if count : while True : if count_group ( group_id ) == count or wait and ( time ( ) - start ) * 1000 >= wait >= 0 : break s...
Return a list of results for a task group .
27,907
def result_group_cached ( group_id , failures = False , wait = 0 , count = None , broker = None ) : if not broker : broker = get_broker ( ) start = time ( ) if count : while True : if count_group_cached ( group_id ) == count or wait and ( time ( ) - start ) * 1000 >= wait > 0 : break sleep ( 0.01 ) while True : group_l...
Return a list of results for a task group from the cache backend
27,908
def fetch ( task_id , wait = 0 , cached = Conf . CACHED ) : if cached : return fetch_cached ( task_id , wait ) start = time ( ) while True : t = Task . get_task ( task_id ) if t : return t if ( time ( ) - start ) * 1000 >= wait >= 0 : break sleep ( 0.01 )
Return the processed task .
27,909
def fetch_cached ( task_id , wait = 0 , broker = None ) : if not broker : broker = get_broker ( ) start = time ( ) while True : r = broker . cache . get ( '{}:{}' . format ( broker . list_key , task_id ) ) if r : task = SignedPackage . loads ( r ) t = Task ( id = task [ 'id' ] , name = task [ 'name' ] , func = task [ '...
Return the processed task from the cache backend
27,910
def fetch_group ( group_id , failures = True , wait = 0 , count = None , cached = Conf . CACHED ) : if cached : return fetch_group_cached ( group_id , failures , wait , count ) start = time ( ) if count : while True : if count_group ( group_id ) == count or wait and ( time ( ) - start ) * 1000 >= wait >= 0 : break slee...
Return a list of Tasks for a task group .
27,911
def fetch_group_cached ( group_id , failures = True , wait = 0 , count = None , broker = None ) : if not broker : broker = get_broker ( ) start = time ( ) if count : while True : if count_group_cached ( group_id ) == count or wait and ( time ( ) - start ) * 1000 >= wait >= 0 : break sleep ( 0.01 ) while True : group_li...
Return a list of Tasks for a task group in the cache backend
27,912
def count_group ( group_id , failures = False , cached = Conf . CACHED ) : if cached : return count_group_cached ( group_id , failures ) return Task . get_group_count ( group_id , failures )
Count the results in a group .
27,913
def count_group_cached ( group_id , failures = False , broker = None ) : if not broker : broker = get_broker ( ) group_list = broker . cache . get ( '{}:{}:keys' . format ( broker . list_key , group_id ) ) if group_list : if not failures : return len ( group_list ) failure_count = 0 for task_key in group_list : task = ...
Count the results in a group in the cache backend
27,914
def delete_group_cached ( group_id , broker = None ) : if not broker : broker = get_broker ( ) group_key = '{}:{}:keys' . format ( broker . list_key , group_id ) group_list = broker . cache . get ( group_key ) broker . cache . delete_many ( group_list ) broker . cache . delete ( group_key )
Delete a group from the cache backend
27,915
def delete_cached ( task_id , broker = None ) : if not broker : broker = get_broker ( ) return broker . cache . delete ( '{}:{}' . format ( broker . list_key , task_id ) )
Delete a task from the cache backend
27,916
def async_iter ( func , args_iter , ** kwargs ) : iter_count = len ( args_iter ) iter_group = uuid ( ) [ 1 ] options = kwargs . get ( 'q_options' , kwargs ) options . pop ( 'hook' , None ) options [ 'broker' ] = options . get ( 'broker' , get_broker ( ) ) options [ 'group' ] = iter_group options [ 'iter_count' ] = iter...
enqueues a function with iterable arguments
27,917
def _sync ( pack ) : task_queue = Queue ( ) result_queue = Queue ( ) task = SignedPackage . loads ( pack ) task_queue . put ( task ) task_queue . put ( 'STOP' ) worker ( task_queue , result_queue , Value ( 'f' , - 1 ) ) result_queue . put ( 'STOP' ) monitor ( result_queue ) task_queue . close ( ) task_queue . join_thre...
Simulate a package travelling through the cluster .
27,918
def append ( self , * args ) : self . args . append ( args ) if self . started : self . started = False return self . length ( )
add arguments to the set
27,919
def retry_failed ( FailAdmin , request , queryset ) : for task in queryset : async_task ( task . func , * task . args or ( ) , hook = task . hook , ** task . kwargs or { } ) task . delete ( )
Submit selected tasks back to the queue .
27,920
def get_queryset ( self , request ) : qs = super ( TaskAdmin , self ) . get_queryset ( request ) return qs . filter ( success = True )
Only show successes .
27,921
def get_readonly_fields ( self , request , obj = None ) : return list ( self . readonly_fields ) + [ field . name for field in obj . _meta . fields ]
Set all fields readonly .
27,922
def save_task ( task , broker ) : if not task . get ( 'save' , Conf . SAVE_LIMIT >= 0 ) and task [ 'success' ] : return if task . get ( 'chain' , None ) : django_q . tasks . async_chain ( task [ 'chain' ] , group = task [ 'group' ] , cached = task [ 'cached' ] , sync = task [ 'sync' ] , broker = broker ) db . close_old...
Saves the task package to Django or the cache
27,923
def scheduler ( broker = None ) : if not broker : broker = get_broker ( ) db . close_old_connections ( ) try : for s in Schedule . objects . exclude ( repeats = 0 ) . filter ( next_run__lt = timezone . now ( ) ) : args = ( ) kwargs = { } if s . kwargs : try : kwargs = eval ( 'dict({})' . format ( s . kwargs ) ) except ...
Creates a task from a schedule at the scheduled time and schedules next run
27,924
def _get_service_connection ( self , service , service_command = None , create = True , timeout_ms = None ) : connection = self . _service_connections . get ( service , None ) if connection : return connection if not connection and not create : return None if service_command : destination_str = b'%s:%s' % ( service , s...
Based on the service get the AdbConnection for that service or create one if it doesnt exist
27,925
def ConnectDevice ( self , port_path = None , serial = None , default_timeout_ms = None , ** kwargs ) : if 'handle' in kwargs : self . _handle = kwargs . pop ( 'handle' ) else : if isinstance ( serial , ( bytes , bytearray ) ) : serial = serial . decode ( 'utf-8' ) if serial and ':' in serial : self . _handle = common ...
Convenience function to setup a transport handle for the adb device from usb path or serial then connect to it .
27,926
def Install ( self , apk_path , destination_dir = '' , replace_existing = True , grant_permissions = False , timeout_ms = None , transfer_progress_callback = None ) : if not destination_dir : destination_dir = '/data/local/tmp/' basename = os . path . basename ( apk_path ) destination_path = posixpath . join ( destinat...
Install an apk to the device .
27,927
def Uninstall ( self , package_name , keep_data = False , timeout_ms = None ) : cmd = [ 'pm uninstall' ] if keep_data : cmd . append ( '-k' ) cmd . append ( '"%s"' % package_name ) return self . Shell ( ' ' . join ( cmd ) , timeout_ms = timeout_ms )
Removes a package from the device .
27,928
def Push ( self , source_file , device_filename , mtime = '0' , timeout_ms = None , progress_callback = None , st_mode = None ) : if isinstance ( source_file , str ) : if os . path . isdir ( source_file ) : self . Shell ( "mkdir " + device_filename ) for f in os . listdir ( source_file ) : self . Push ( os . path . joi...
Push a file or directory to the device .
27,929
def Pull ( self , device_filename , dest_file = None , timeout_ms = None , progress_callback = None ) : if not dest_file : dest_file = io . BytesIO ( ) elif isinstance ( dest_file , str ) : dest_file = open ( dest_file , 'wb' ) elif isinstance ( dest_file , file ) : pass else : raise ValueError ( "destfile is of unknow...
Pull a file from the device .
27,930
def List ( self , device_path ) : connection = self . protocol_handler . Open ( self . _handle , destination = b'sync:' ) listing = self . filesync_handler . List ( connection , device_path ) connection . Close ( ) return listing
Return a directory listing of the given path .
27,931
def Shell ( self , command , timeout_ms = None ) : return self . protocol_handler . Command ( self . _handle , service = b'shell' , command = command , timeout_ms = timeout_ms )
Run command on the device returning the output .
27,932
def StreamingShell ( self , command , timeout_ms = None ) : return self . protocol_handler . StreamingCommand ( self . _handle , service = b'shell' , command = command , timeout_ms = timeout_ms )
Run command on the device yielding each line of output .
27,933
def InteractiveShell ( self , cmd = None , strip_cmd = True , delim = None , strip_delim = True ) : conn = self . _get_service_connection ( b'shell:' ) return self . protocol_handler . InteractiveShellCommand ( conn , cmd = cmd , strip_cmd = strip_cmd , delim = delim , strip_delim = strip_delim )
Get stdout from the currently open interactive shell and optionally run a command on the device returning all output .
27,934
def InterfaceMatcher ( clazz , subclass , protocol ) : interface = ( clazz , subclass , protocol ) def Matcher ( device ) : for setting in device . iterSettings ( ) : if GetInterface ( setting ) == interface : return setting return Matcher
Returns a matcher that returns the setting with the given interface .
27,935
def Open ( self ) : port_path = tuple ( self . port_path ) with self . _HANDLE_CACHE_LOCK : old_handle = self . _HANDLE_CACHE . get ( port_path ) if old_handle is not None : old_handle . Close ( ) self . _read_endpoint = None self . _write_endpoint = None for endpoint in self . _setting . iterEndpoints ( ) : address = ...
Opens the USB device for this setting and claims the interface .
27,936
def PortPathMatcher ( cls , port_path ) : if isinstance ( port_path , str ) : port_path = [ int ( part ) for part in SYSFS_PORT_SPLIT_RE . split ( port_path ) ] return lambda device : device . port_path == port_path
Returns a device matcher for the given port path .
27,937
def Find ( cls , setting_matcher , port_path = None , serial = None , timeout_ms = None ) : if port_path : device_matcher = cls . PortPathMatcher ( port_path ) usb_info = port_path elif serial : device_matcher = cls . SerialMatcher ( serial ) usb_info = serial else : device_matcher = None usb_info = 'first' return cls ...
Gets the first device that matches according to the keyword args .
27,938
def FindFirst ( cls , setting_matcher , device_matcher = None , ** kwargs ) : try : return next ( cls . FindDevices ( setting_matcher , device_matcher = device_matcher , ** kwargs ) ) except StopIteration : raise usb_exceptions . DeviceNotFoundError ( 'No device available, or it is in the wrong configuration.' )
Find and return the first matching device .
27,939
def FindDevices ( cls , setting_matcher , device_matcher = None , usb_info = '' , timeout_ms = None ) : ctx = usb1 . USBContext ( ) for device in ctx . getDeviceList ( skip_on_error = True ) : setting = setting_matcher ( device ) if setting is None : continue handle = cls ( device , setting , usb_info = usb_info , time...
Find and yield the devices that match .
27,940
def Write ( self , data ) : self . _Send ( b'WRTE' , arg0 = self . local_id , arg1 = self . remote_id , data = data ) cmd , okay_data = self . ReadUntil ( b'OKAY' ) if cmd != b'OKAY' : if cmd == b'FAIL' : raise usb_exceptions . AdbCommandFailureException ( 'Command failed.' , okay_data ) raise InvalidCommandError ( 'Ex...
Write a packet and expect an Ack .
27,941
def ReadUntil ( self , * expected_cmds ) : cmd , remote_id , local_id , data = AdbMessage . Read ( self . usb , expected_cmds , self . timeout_ms ) if local_id != 0 and self . local_id != local_id : raise InterleavedDataError ( "We don't support multiple streams..." ) if remote_id != 0 and self . remote_id != remote_id...
Read a packet Ack any write packets .
27,942
def ReadUntilClose ( self ) : while True : cmd , data = self . ReadUntil ( b'CLSE' , b'WRTE' ) if cmd == b'CLSE' : self . _Send ( b'CLSE' , arg0 = self . local_id , arg1 = self . remote_id ) break if cmd != b'WRTE' : if cmd == b'FAIL' : raise usb_exceptions . AdbCommandFailureException ( 'Command failed.' , data ) rais...
Yield packets until a Close packet is received .
27,943
def Pack ( self ) : return struct . pack ( self . format , self . command , self . arg0 , self . arg1 , len ( self . data ) , self . checksum , self . magic )
Returns this message in an over - the - wire format .
27,944
def Send ( self , usb , timeout_ms = None ) : usb . BulkWrite ( self . Pack ( ) , timeout_ms ) usb . BulkWrite ( self . data , timeout_ms )
Send this message over USB .
27,945
def Read ( cls , usb , expected_cmds , timeout_ms = None , total_timeout_ms = None ) : total_timeout_ms = usb . Timeout ( total_timeout_ms ) start = time . time ( ) while True : msg = usb . BulkRead ( 24 , timeout_ms ) cmd , arg0 , arg1 , data_length , data_checksum = cls . Unpack ( msg ) command = cls . constants . ge...
Receive a response from the device .
27,946
def Connect ( cls , usb , banner = b'notadb' , rsa_keys = None , auth_timeout_ms = 100 ) : if isinstance ( banner , str ) : banner = bytearray ( banner , 'utf-8' ) msg = cls ( command = b'CNXN' , arg0 = VERSION , arg1 = MAX_ADB_DATA , data = b'host::%s\0' % banner ) msg . Send ( usb ) cmd , arg0 , arg1 , banner = cls ....
Establish a new connection to the device .
27,947
def Open ( cls , usb , destination , timeout_ms = None ) : local_id = 1 msg = cls ( command = b'OPEN' , arg0 = local_id , arg1 = 0 , data = destination + b'\0' ) msg . Send ( usb , timeout_ms ) cmd , remote_id , their_local_id , _ = cls . Read ( usb , [ b'CLSE' , b'OKAY' ] , timeout_ms = timeout_ms ) if local_id != the...
Opens a new connection to the device via an OPEN message .
27,948
def ConnectDevice ( self , port_path = None , serial = None , default_timeout_ms = None , chunk_kb = 1024 , ** kwargs ) : if 'handle' in kwargs : self . _handle = kwargs [ 'handle' ] else : self . _handle = common . UsbHandle . FindAndOpen ( DeviceIsAvailable , port_path = port_path , serial = serial , timeout_ms = def...
Convenience function to get an adb device from usb path or serial .
27,949
def _DocToArgs ( doc ) : m = None offset = None in_arg = False out = { } for l in doc . splitlines ( ) : if l . strip ( ) == 'Args:' : in_arg = True elif in_arg : if not l . strip ( ) : break if offset is None : offset = len ( l ) - len ( l . lstrip ( ) ) l = l [ offset : ] if l [ 0 ] == ' ' and m : out [ m . group ( 1...
Converts a docstring documenting arguments into a dict .
27,950
def MakeSubparser ( subparsers , parents , method , arguments = None ) : name = ( '-' . join ( re . split ( r'([A-Z][a-z]+)' , method . __name__ ) [ 1 : - 1 : 2 ] ) ) . lower ( ) help = method . __doc__ . splitlines ( ) [ 0 ] subparser = subparsers . add_parser ( name = name , description = help , help = help . rstrip ...
Returns an argparse subparser to create a subcommand to adb .
27,951
def _RunMethod ( dev , args , extra ) : logging . info ( '%s(%s)' , args . method . __name__ , ', ' . join ( args . positional ) ) result = args . method ( dev , * args . positional , ** extra ) if result is not None : if isinstance ( result , io . StringIO ) : sys . stdout . write ( result . getvalue ( ) ) elif isinst...
Runs a method registered via MakeSubparser .
27,952
def StartCli ( args , adb_commands , extra = None , ** device_kwargs ) : try : dev = adb_commands ( ) dev . ConnectDevice ( port_path = args . port_path , serial = args . serial , default_timeout_ms = args . timeout_ms , ** device_kwargs ) except usb_exceptions . DeviceNotFoundError as e : print ( 'No device found: {}'...
Starts a common CLI interface for this usb path and protocol .
27,953
def Pull ( cls , connection , filename , dest_file , progress_callback ) : if progress_callback : total_bytes = cls . Stat ( connection , filename ) [ 1 ] progress = cls . _HandleProgress ( lambda current : progress_callback ( filename , current , total_bytes ) ) next ( progress ) cnxn = FileSyncConnection ( connection...
Pull a file from the device into the file - like dest_file .
27,954
def Read ( self , expected_ids , read_data = True ) : if self . send_idx : self . _Flush ( ) header_data = self . _ReadBuffered ( self . recv_header_len ) header = struct . unpack ( self . recv_header_format , header_data ) command_id = self . wire_to_id [ header [ 0 ] ] if command_id not in expected_ids : if command_i...
Read ADB messages and return FileSync packets .
27,955
def ReadUntil ( self , expected_ids , * finish_ids ) : while True : cmd_id , header , data = self . Read ( expected_ids + finish_ids ) yield cmd_id , header , data if cmd_id in finish_ids : break
Useful wrapper around Read .
27,956
def Devices ( args ) : for d in adb_commands . AdbCommands . Devices ( ) : if args . output_port_path : print ( '%s\tdevice\t%s' % ( d . serial_number , ',' . join ( str ( p ) for p in d . port_path ) ) ) else : print ( '%s\tdevice' % d . serial_number ) return 0
Lists the available devices .
27,957
def List ( device , device_path ) : files = device . List ( device_path ) files . sort ( key = lambda x : x . filename ) maxname = max ( len ( f . filename ) for f in files ) maxsize = max ( len ( str ( f . size ) ) for f in files ) for f in files : mode = ( ( 'd' if stat . S_ISDIR ( f . mode ) else '-' ) + ( 'r' if f ...
Prints a directory listing .
27,958
def Shell ( device , * command ) : if command : return device . StreamingShell ( ' ' . join ( command ) ) else : terminal_prompt = device . InteractiveShell ( ) print ( terminal_prompt . decode ( 'utf-8' ) ) while True : cmd = input ( '> ' ) if not cmd : continue elif cmd == 'exit' : break else : stdout = device . Inte...
Runs a command on the device and prints the stdout .
27,959
def updateActiveMarkupClass ( self ) : previousMarkupClass = self . activeMarkupClass self . activeMarkupClass = find_markup_class_by_name ( globalSettings . defaultMarkup ) if self . _fileName : markupClass = get_markup_for_file_name ( self . _fileName , return_class = True ) if markupClass : self . activeMarkupClass ...
Update the active markup class based on the default class and the current filename . If the active markup class changes the highlighter is rerun on the input text the markup object of this tab is replaced with one of the new class and the activeMarkupChanged signal is emitted .
27,960
def detectFileEncoding ( self , fileName ) : try : import chardet except ImportError : return with open ( fileName , 'rb' ) as inputFile : raw = inputFile . read ( 2048 ) result = chardet . detect ( raw ) if result [ 'confidence' ] > 0.9 : if result [ 'encoding' ] . lower ( ) == 'ascii' : return 'utf-8' return result [...
Detect content encoding of specific file .
27,961
def openSourceFile ( self , fileToOpen ) : if self . fileName : currentExt = splitext ( self . fileName ) [ 1 ] basename , ext = splitext ( fileToOpen ) if ext in ( '.html' , '' ) and exists ( basename + currentExt ) : self . p . openFileWrapper ( basename + currentExt ) return basename + currentExt if exists ( fileToO...
Finds and opens the source file for link target fileToOpen .
27,962
def extendMarkdown ( self , md ) : md . preprocessors . register ( PosMapMarkPreprocessor ( md ) , 'posmap_mark' , 50 ) md . preprocessors . register ( PosMapCleanPreprocessor ( md ) , 'posmap_clean' , 5 ) md . parser . blockprocessors . register ( PosMapBlockProcessor ( md . parser ) , 'posmap' , 150 ) orig_codehilite...
Insert the PosMapExtension blockprocessor before any other extensions to make sure our own markers inserted by the preprocessor are removed before any other extensions get confused by them .
27,963
def tabFileNameChanged ( self , tab ) : if tab == self . currentTab : if tab . fileName : self . setWindowTitle ( "" ) if globalSettings . windowTitleFullPath : self . setWindowTitle ( tab . fileName + '[*]' ) self . setWindowFilePath ( tab . fileName ) self . tabWidget . setTabText ( self . ind , tab . getBaseName ( )...
Perform all UI state changes that need to be done when the filename of the current tab has changed .
27,964
def tabActiveMarkupChanged ( self , tab ) : if tab == self . currentTab : markupClass = tab . getActiveMarkupClass ( ) dtMarkdown = ( markupClass == markups . MarkdownMarkup ) dtMkdOrReST = dtMarkdown or ( markupClass == markups . ReStructuredTextMarkup ) self . formattingBox . setEnabled ( dtMarkdown ) self . symbolBo...
Perform all UI state changes that need to be done when the active markup class of the current tab has changed .
27,965
def tabModificationStateChanged ( self , tab ) : if tab == self . currentTab : changed = tab . editBox . document ( ) . isModified ( ) if self . autoSaveActive ( tab ) : changed = False self . actionSave . setEnabled ( changed ) self . setWindowModified ( changed )
Perform all UI state changes that need to be done when the modification state of the current tab has changed .
27,966
def getPageSizeByName ( self , pageSizeName ) : pageSize = None lowerCaseNames = { pageSize . lower ( ) : pageSize for pageSize in self . availablePageSizes ( ) } if pageSizeName . lower ( ) in lowerCaseNames : pageSize = getattr ( QPagedPaintDevice , lowerCaseNames [ pageSizeName . lower ( ) ] ) return pageSize
Returns a validated PageSize instance corresponding to the given name . Returns None if the name is not a valid PageSize .
27,967
def availablePageSizes ( self ) : sizes = [ x for x in dir ( QPagedPaintDevice ) if type ( getattr ( QPagedPaintDevice , x ) ) == QPagedPaintDevice . PageSize ] return sizes
List available page sizes .
27,968
def data_from_cluster_id ( self , cluster_id , graph , data ) : if cluster_id in graph [ "nodes" ] : cluster_members = graph [ "nodes" ] [ cluster_id ] cluster_members_data = data [ cluster_members ] return cluster_members_data else : return np . array ( [ ] )
Returns the original data of each cluster member for a given cluster ID
27,969
def _colors_to_rgb ( colorscale ) : if colorscale [ 0 ] [ 1 ] [ 0 ] == "#" : plotly_colors = np . array ( colorscale ) [ : , 1 ] . tolist ( ) for k , hexcode in enumerate ( plotly_colors ) : hexcode = hexcode . lstrip ( "#" ) hex_len = len ( hexcode ) step = hex_len // 3 colorscale [ k ] [ 1 ] = "rgb" + str ( tuple ( i...
Ensure that the color scale is formatted in rgb strings . If the colorscale is a hex string then convert to rgb .
27,970
def build_histogram ( data , colorscale = None , nbins = 10 ) : if colorscale is None : colorscale = colorscale_default colorscale = _colors_to_rgb ( colorscale ) h_min , h_max = 0 , 1 hist , bin_edges = np . histogram ( data , range = ( h_min , h_max ) , bins = nbins ) bin_mids = np . mean ( np . array ( list ( zip ( ...
Build histogram of data based on values of color_function
27,971
def draw_matplotlib ( g , ax = None , fig = None ) : import networkx as nx import matplotlib . pyplot as plt fig = fig if fig else plt . figure ( ) ax = ax if ax else plt . gca ( ) if not isinstance ( g , nx . Graph ) : from . adapter import to_networkx g = to_networkx ( g ) bbox = ax . get_window_extent ( ) . transfor...
Draw the graph using NetworkX drawing functionality .
27,972
def get_kmgraph_meta ( mapper_summary ) : d = mapper_summary [ "custom_meta" ] meta = ( "<b>N_cubes:</b> " + str ( d [ "n_cubes" ] ) + " <b>Perc_overlap:</b> " + str ( d [ "perc_overlap" ] ) ) meta += ( "<br><b>Nodes:</b> " + str ( mapper_summary [ "n_nodes" ] ) + " <b>Edges:</b> " + str ( mapper_summary [ "n_edges" ] ...
Extract info from mapper summary to be displayed below the graph plot
27,973
def summary_fig ( mapper_summary , width = 600 , height = 500 , top = 60 , left = 20 , bottom = 60 , right = 20 , bgcolor = "rgb(240,240,240)" , ) : text = _text_mapper_summary ( mapper_summary ) data = [ dict ( type = "scatter" , x = [ 0 , width ] , y = [ height , 0 ] , mode = "text" , text = [ text , "" ] , textposit...
Define a dummy figure that displays info on the algorithms and sklearn class instances or methods used Returns a FigureWidget object representing the figure
27,974
def compute ( self , nodes ) : result = defaultdict ( list ) candidates = itertools . combinations ( nodes . keys ( ) , 2 ) for candidate in candidates : if ( len ( set ( nodes [ candidate [ 0 ] ] ) . intersection ( nodes [ candidate [ 1 ] ] ) ) >= self . min_intersection ) : result [ candidate [ 0 ] ] . append ( candi...
Helper function to find edges of the overlapping clusters .
27,975
def fit ( self , data ) : di = np . array ( range ( 1 , data . shape [ 1 ] ) ) indexless_data = data [ : , di ] n_dims = indexless_data . shape [ 1 ] if isinstance ( self . n_cubes , Iterable ) : n_cubes = np . array ( self . n_cubes ) assert ( len ( n_cubes ) == n_dims ) , "Custom cubes in each dimension must match nu...
Fit a cover on the data . This method constructs centers and radii in each dimension given the perc_overlap and n_cube .
27,976
def transform_single ( self , data , center , i = 0 ) : lowerbounds , upperbounds = center - self . radius_ , center + self . radius_ entries = ( data [ : , self . di_ ] >= lowerbounds ) & ( data [ : , self . di_ ] <= upperbounds ) hypercube = data [ np . invert ( np . any ( entries == False , axis = 1 ) ) ] if self . ...
Compute entries of data in hypercube centered at center
27,977
def transform ( self , data , centers = None ) : centers = centers or self . centers_ hypercubes = [ self . transform_single ( data , cube , i ) for i , cube in enumerate ( centers ) ] hypercubes = [ cube for cube in hypercubes if len ( cube ) ] return hypercubes
Find entries of all hypercubes . If centers = None then use self . centers_ as computed in self . fit . Empty hypercubes are removed from the result
27,978
def to_networkx ( graph ) : import networkx as nx nodes = graph [ "nodes" ] . keys ( ) edges = [ [ start , end ] for start , ends in graph [ "links" ] . items ( ) for end in ends ] g = nx . Graph ( ) g . add_nodes_from ( nodes ) nx . set_node_attributes ( g , dict ( graph [ "nodes" ] ) , "membership" ) g . add_edges_fr...
Convert a Mapper 1 - complex to a networkx graph .
27,979
def get_corpus ( filename : str ) -> frozenset : lines = [ ] with open ( os . path . join ( corpus_path ( ) , filename ) , "r" , encoding = "utf-8-sig" ) as fh : lines = fh . read ( ) . splitlines ( ) return frozenset ( lines )
Read corpus from file and return a frozenset
27,980
def get_corpus_path ( name : str ) -> [ str , None ] : db = TinyDB ( corpus_db_path ( ) ) temp = Query ( ) if len ( db . search ( temp . name == name ) ) > 0 : path = get_full_data_path ( db . search ( temp . name == name ) [ 0 ] [ "file" ] ) db . close ( ) if not os . path . exists ( path ) : download ( name ) return ...
Get corpus path
27,981
def summarize ( text : str , n : int , engine : str = "frequency" , tokenizer : str = "newmm" ) -> List [ str ] : sents = [ ] if engine == "frequency" : sents = FrequencySummarizer ( ) . summarize ( text , n , tokenizer ) else : sents = sent_tokenize ( text ) [ : n ] return sents
Thai text summarization
27,982
def edges ( word : str , lang : str = "th" ) : obj = requests . get ( f"http://api.conceptnet.io/c/{lang}/{word}" ) . json ( ) return obj [ "edges" ]
Get edges from ConceptNet API
27,983
def thaiword_to_num ( word : str ) -> int : if not word : return None tokens = [ ] if isinstance ( word , str ) : tokens = _TOKENIZER . word_tokenize ( word ) elif isinstance ( word , Iterable ) : for w in word : tokens . extend ( _TOKENIZER . word_tokenize ( w ) ) res = [ ] for tok in tokens : if tok in _THAIWORD_NUMS...
Converts a Thai number spellout word to actual number value
27,984
def pos_tag ( words : List [ str ] , engine : str = "perceptron" , corpus : str = "orchid" ) -> List [ Tuple [ str , str ] ] : _corpus = corpus _tag = [ ] if corpus == "orchid_ud" : corpus = "orchid" if not words : return [ ] if engine == "perceptron" : from . perceptron import tag as tag_ elif engine == "artagger" : t...
Part of Speech tagging function .
27,985
def pos_tag_sents ( sentences : List [ List [ str ] ] , engine : str = "perceptron" , corpus : str = "orchid" ) -> List [ List [ Tuple [ str , str ] ] ] : if not sentences : return [ ] return [ pos_tag ( sent , engine = engine , corpus = corpus ) for sent in sentences ]
Part of Speech tagging Sentence function .
27,986
def _keep ( word_freq : int , min_freq : int , min_len : int , max_len : int , dict_filter : Callable [ [ str ] , bool ] , ) : if not word_freq or word_freq [ 1 ] < min_freq : return False word = word_freq [ 0 ] if not word or len ( word ) < min_len or len ( word ) > max_len or word [ 0 ] == "." : return False return d...
Keep only Thai words with at least min_freq frequency and has length between min_len and max_len characters
27,987
def _edits1 ( word : str ) -> Set [ str ] : splits = [ ( word [ : i ] , word [ i : ] ) for i in range ( len ( word ) + 1 ) ] deletes = [ L + R [ 1 : ] for L , R in splits if R ] transposes = [ L + R [ 1 ] + R [ 0 ] + R [ 2 : ] for L , R in splits if len ( R ) > 1 ] replaces = [ L + c + R [ 1 : ] for L , R in splits if ...
Return a set of words with edit distance of 1 from the input word
27,988
def _edits2 ( word : str ) -> Set [ str ] : return set ( e2 for e1 in _edits1 ( word ) for e2 in _edits1 ( e1 ) )
Return a set of words with edit distance of 2 from the input word
27,989
def known ( self , words : List [ str ] ) -> List [ str ] : return list ( w for w in words if w in self . __WORDS )
Return a list of given words that found in the spelling dictionary
27,990
def prob ( self , word : str ) -> float : return self . __WORDS [ word ] / self . __WORDS_TOTAL
Return probability of an input word according to the spelling dictionary
27,991
def spell ( self , word : str ) -> List [ str ] : if not word : return "" candidates = ( self . known ( [ word ] ) or self . known ( _edits1 ( word ) ) or self . known ( _edits2 ( word ) ) or [ word ] ) candidates . sort ( key = self . freq , reverse = True ) return candidates
Return a list of possible words according to edit distance of 1 and 2 sorted by frequency of word occurrance in the spelling dictionary
27,992
def sent_tokenize ( text : str , engine : str = "whitespace+newline" ) -> List [ str ] : if not text or not isinstance ( text , str ) : return [ ] sentences = [ ] if engine == "whitespace" : sentences = re . split ( r" +" , text , re . U ) else : sentences = text . split ( ) return sentences
This function does not yet automatically recognize when a sentence actually ends . Rather it helps split text where white space and a new line is found .
27,993
def tag_provinces ( tokens : List [ str ] ) -> List [ Tuple [ str , str ] ] : province_list = provinces ( ) output = [ ] for token in tokens : if token in province_list : output . append ( ( token , "B-LOCATION" ) ) else : output . append ( ( token , "O" ) ) return output
Recognize Thailand provinces in text
27,994
def get_ner ( self , text : str , pos : bool = True ) -> Union [ List [ Tuple [ str , str ] ] , List [ Tuple [ str , str , str ] ] ] : self . __tokens = word_tokenize ( text , engine = _WORD_TOKENIZER ) self . __pos_tags = pos_tag ( self . __tokens , engine = "perceptron" , corpus = "orchid_ud" ) self . __x_test = self...
Get named - entities in text
27,995
def find_all_segment ( text : str , custom_dict : Trie = None ) -> List [ str ] : if not text or not isinstance ( text , str ) : return [ ] ww = list ( _multicut ( text , custom_dict = custom_dict ) ) return list ( _combine ( ww ) )
Get all possible segment variations
27,996
def reign_year_to_ad ( reign_year : int , reign : int ) -> int : if int ( reign ) == 10 : ad = int ( reign_year ) + 2015 elif int ( reign ) == 9 : ad = int ( reign_year ) + 1945 elif int ( reign ) == 8 : ad = int ( reign_year ) + 1928 elif int ( reign ) == 7 : ad = int ( reign_year ) + 1924 return ad
Reign year of Chakri dynasty Thailand
27,997
def most_similar_cosmul ( positive : List [ str ] , negative : List [ str ] ) : return _MODEL . most_similar_cosmul ( positive = positive , negative = negative )
Word arithmetic operations If a word is not in the vocabulary KeyError will be raised .
27,998
def similarity ( word1 : str , word2 : str ) -> float : return _MODEL . similarity ( word1 , word2 )
Get cosine similarity between two words . If a word is not in the vocabulary KeyError will be raised .
27,999
def sentence_vectorizer ( text : str , use_mean : bool = True ) : words = word_tokenize ( text , engine = "ulmfit" ) vec = np . zeros ( ( 1 , WV_DIM ) ) for word in words : if word == " " : word = "xxspace" elif word == "\n" : word = "xxeol" if word in _MODEL . wv . index2word : vec += _MODEL . wv . word_vec ( word ) e...
Get sentence vector from text If a word is not in the vocabulary KeyError will be raised .