_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q18300
create_supercut
train
def create_supercut(composition, outputfile, padding): """Concatenate video clips together and output finished video file to the output directory. """ print("[+] Creating clips.") demo_supercut(composition, padding) # add padding when necessary for (clip, nextclip) in zip(composition, compo...
python
{ "resource": "" }
q18301
create_supercut_in_batches
train
def create_supercut_in_batches(composition, outputfile, padding): """Create & concatenate video clips in groups of size BATCH_SIZE and output finished video file to output directory. """ total_clips = len(composition) start_index = 0 end_index = BATCH_SIZE batch_comp = [] while start_ind...
python
{ "resource": "" }
q18302
search_line
train
def search_line(line, search, searchtype): """Return True if search term is found in given line, False otherwise.""" if searchtype == 're' or searchtype == 'word': return re.search(search, line) #, re.IGNORECASE) elif searchtype == 'pos': return searcher.search_out(line, search) elif se...
python
{ "resource": "" }
q18303
get_subtitle_files
train
def get_subtitle_files(inputfile): """Return a list of subtitle files.""" srts = [] for f in inputfile: filename = f.split('.') filename[-1] = 'srt' srt = '.'.join(filename) if os.path.isfile(srt): srts.append(srt) if len(srts) == 0: print("[!] No su...
python
{ "resource": "" }
q18304
get_vtt_files
train
def get_vtt_files(inputfile): """Return a list of vtt files.""" vtts = [] for f in inputfile: filename = f.split('.') filename = '.'.join(filename[0:-1]) vtt = glob(filename + '*.vtt') if len(vtt) > 0: vtts.append({'vtt': vtt[0], 'video': f}) if len(vtts) ==...
python
{ "resource": "" }
q18305
videogrep
train
def videogrep(inputfile, outputfile, search, searchtype, maxclips=0, padding=0, test=False, randomize=False, sync=0, use_transcript=False, use_vtt=False, export_clips=False): """Search through and find all instances of the search term in an srt or transcript, create a supercut around that instance, and output a...
python
{ "resource": "" }
q18306
basic_color
train
def basic_color(code): """ 16 colors supported """ def inner(text, rl=False): """ Every raw_input with color sequences should be called with rl=True to avoid readline messed up the length calculation """ c = code if rl: return "\001\033[%sm\002%s\001\0...
python
{ "resource": "" }
q18307
term_color
train
def term_color(code): """ 256 colors supported """ def inner(text, rl=False): """ Every raw_input with color sequences should be called with rl=True to avoid readline messed up the length calculation """ c = code if rl: return "\001\033[38;5;%s...
python
{ "resource": "" }
q18308
color_func
train
def color_func(func_name): """ Call color function base on name """ if str(func_name).isdigit(): return term_color(int(func_name)) return globals()[func_name]
python
{ "resource": "" }
q18309
MPlayer._send_command
train
def _send_command(self, cmd, expect=None): """Send a command to MPlayer. cmd: the command string expect: expect the output starts with a certain string The result, if any, is returned as a string. """ if not self.is_alive: raise NotPlayingError() logg...
python
{ "resource": "" }
q18310
EntitySpec.stream
train
def stream( self, accountID, **kwargs ): """ Get a stream of Transactions for an Account starting from when the request is made. Args: accountID: Account Identifier Returns: v20.response.Response containing the...
python
{ "resource": "" }
q18311
EntitySpec.price
train
def price( self, instrument, **kwargs ): """ Fetch a price for an instrument. Accounts are not associated in any way with this endpoint. Args: instrument: Name of the Instrument time: The time at which t...
python
{ "resource": "" }
q18312
EntitySpec.list
train
def list( self, accountID, **kwargs ): """ Get a list of Orders for an Account Args: accountID: Account Identifier ids: List of Order IDs to retrieve state: The state to filter the re...
python
{ "resource": "" }
q18313
EntitySpec.cancel
train
def cancel( self, accountID, orderSpecifier, **kwargs ): """ Cancel a pending Order in an Account Args: accountID: Account Identifier orderSpecifier: The Order Specifier Returns: v20...
python
{ "resource": "" }
q18314
EntitySpec.market
train
def market(self, accountID, **kwargs): """ Shortcut to create a Market Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a MarketOrderRequest Returns: v20.response.Response containing the results from submit...
python
{ "resource": "" }
q18315
EntitySpec.limit
train
def limit(self, accountID, **kwargs): """ Shortcut to create a Limit Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a LimitOrderRequest Returns: v20.response.Response containing the results from submittin...
python
{ "resource": "" }
q18316
EntitySpec.limit_replace
train
def limit_replace(self, accountID, orderID, **kwargs): """ Shortcut to replace a pending Limit Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Limit Order to replace kwargs : The arguments to create a LimitOrderRequest ...
python
{ "resource": "" }
q18317
EntitySpec.stop
train
def stop(self, accountID, **kwargs): """ Shortcut to create a Stop Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopOrderRequest Returns: v20.response.Response containing the results from submitting ...
python
{ "resource": "" }
q18318
EntitySpec.stop_replace
train
def stop_replace(self, accountID, orderID, **kwargs): """ Shortcut to replace a pending Stop Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Stop Order to replace kwargs : The arguments to create a StopOrderRequest ...
python
{ "resource": "" }
q18319
EntitySpec.market_if_touched
train
def market_if_touched(self, accountID, **kwargs): """ Shortcut to create a MarketIfTouched Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a MarketIfTouchedOrderRequest Returns: v20.response.Response conta...
python
{ "resource": "" }
q18320
EntitySpec.market_if_touched_replace
train
def market_if_touched_replace(self, accountID, orderID, **kwargs): """ Shortcut to replace a pending MarketIfTouched Order in an Account Args: accountID : The ID of the Account orderID : The ID of the MarketIfTouched Order to replace kwargs : The arguments to...
python
{ "resource": "" }
q18321
EntitySpec.take_profit
train
def take_profit(self, accountID, **kwargs): """ Shortcut to create a Take Profit Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a TakeProfitOrderRequest Returns: v20.response.Response containing the resul...
python
{ "resource": "" }
q18322
EntitySpec.take_profit_replace
train
def take_profit_replace(self, accountID, orderID, **kwargs): """ Shortcut to replace a pending Take Profit Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Take Profit Order to replace kwargs : The arguments to create a Take...
python
{ "resource": "" }
q18323
EntitySpec.stop_loss
train
def stop_loss(self, accountID, **kwargs): """ Shortcut to create a Stop Loss Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a StopLossOrderRequest Returns: v20.response.Response containing the results fro...
python
{ "resource": "" }
q18324
EntitySpec.stop_loss_replace
train
def stop_loss_replace(self, accountID, orderID, **kwargs): """ Shortcut to replace a pending Stop Loss Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Stop Loss Order to replace kwargs : The arguments to create a StopLossOr...
python
{ "resource": "" }
q18325
EntitySpec.trailing_stop_loss
train
def trailing_stop_loss(self, accountID, **kwargs): """ Shortcut to create a Trailing Stop Loss Order in an Account Args: accountID : The ID of the Account kwargs : The arguments to create a TrailingStopLossOrderRequest Returns: v20.response.Response ...
python
{ "resource": "" }
q18326
EntitySpec.trailing_stop_loss_replace
train
def trailing_stop_loss_replace(self, accountID, orderID, **kwargs): """ Shortcut to replace a pending Trailing Stop Loss Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Take Profit Order to replace kwargs : The arguments to...
python
{ "resource": "" }
q18327
Context.set_token
train
def set_token(self, token): """ Set the token for the v20 context Args: token: The token used to access the v20 REST api """ self.token = token self.set_header( 'Authorization', "Bearer {}".format(token) )
python
{ "resource": "" }
q18328
Context.set_datetime_format
train
def set_datetime_format(self, format): """ Set the Accept-Datetime-Format header to an acceptable value Args: format: UNIX or RFC3339 """ if not format in ["UNIX", "RFC3339"]: return self.datetime_format = format self.set_header(...
python
{ "resource": "" }
q18329
Context.request
train
def request(self, request): """ Perform an HTTP request through the context Args: request: A v20.request.Request object Returns: A v20.response.Response object """ url = "{}{}".format(self._base_url, request.path) timeout = self.poll_ti...
python
{ "resource": "" }
q18330
EntitySpec.list
train
def list( self, **kwargs ): """ Get a list of all Accounts authorized for the provided token. Args: Returns: v20.response.Response containing the results from submitting the request """ request = Request( 'GET', ...
python
{ "resource": "" }
q18331
EntitySpec.instruments
train
def instruments( self, accountID, **kwargs ): """ Get the list of tradeable instruments for the given Account. The list of tradeable instruments is dependent on the regulatory division that the Account is located in, thus should be the same for all Accounts ...
python
{ "resource": "" }
q18332
EntitySpec.get_info
train
def get_info( self, userSpecifier, **kwargs ): """ Fetch the user information for the specified user. This endpoint is intended to be used by the user themself to obtain their own information. Args: userSpecifier: The User ...
python
{ "resource": "" }
q18333
EntitySpec.get
train
def get( self, accountID, **kwargs ): """ Get pricing information for a specified list of Instruments within an Account. Args: accountID: Account Identifier instruments: List of Instruments to get pricin...
python
{ "resource": "" }
q18334
OutputHandler.output_for_skipping_run_set
train
def output_for_skipping_run_set(self, runSet, reason=None): ''' This function writes a simple message to terminal and logfile, when a run set is skipped. There is no message about skipping a run set in the xml-file. ''' # print to terminal util.printOut("\nSkippi...
python
{ "resource": "" }
q18335
OutputHandler.writeRunSetInfoToLog
train
def writeRunSetInfoToLog(self, runSet): """ This method writes the information about a run set into the txt_file. """ runSetInfo = "\n\n" if runSet.name: runSetInfo += runSet.name + "\n" runSetInfo += "Run set {0} of {1} with options '{2}' and propertyfile '{...
python
{ "resource": "" }
q18336
OutputHandler.runs_to_xml
train
def runs_to_xml(self, runSet, runs, blockname=None): """ This function creates the XML structure for a list of runs """ # copy benchmarkinfo, limits, columntitles, systeminfo from xml_header runsElem = util.copy_of_xml_element(self.xml_header) runsElem.set("options", " "....
python
{ "resource": "" }
q18337
OutputHandler.add_values_to_run_xml
train
def add_values_to_run_xml(self, run): """ This function adds the result values to the XML representation of a run. """ runElem = run.xml for elem in list(runElem): runElem.remove(elem) self.add_column_to_xml(runElem, 'status', run.status) self.add_c...
python
{ "resource": "" }
q18338
OutputHandler.add_values_to_run_set_xml
train
def add_values_to_run_set_xml(self, runSet, cputime, walltime, energy): """ This function adds the result values to the XML representation of a runSet. """ self.add_column_to_xml(runSet.xml, 'cputime', cputime) self.add_column_to_xml(runSet.xml, 'walltime', walltime) ener...
python
{ "resource": "" }
q18339
OutputHandler.format_sourcefile_name
train
def format_sourcefile_name(self, fileName, runSet): ''' Formats the file name of a program for printing on console. ''' if fileName.startswith(runSet.common_prefix): fileName = fileName[len(runSet.common_prefix):] return fileName.ljust(runSet.max_length_of_filename + ...
python
{ "resource": "" }
q18340
OutputHandler._write_pretty_result_xml_to_file
train
def _write_pretty_result_xml_to_file(self, xml, filename): """Writes a nicely formatted XML file with DOCTYPE, and compressed if necessary.""" if self.compress_results: actual_filename = filename + ".bz2" # Use BZ2File directly or our hack for Python 3.2 open_func = b...
python
{ "resource": "" }
q18341
get_extract_value_function
train
def get_extract_value_function(column_identifier): """ returns a function that extracts the value for a column. """ def extract_value(run_result): pos = None for i, column in enumerate(run_result.columns): if column.title == column_identifier: pos = i ...
python
{ "resource": "" }
q18342
check_memory_size
train
def check_memory_size(memLimit, num_of_threads, memoryAssignment, my_cgroups): """Check whether the desired amount of parallel benchmarks fits in the memory. Implemented are checks for memory limits via cgroup controller "memory" and memory bank restrictions via cgroup controller "cpuset", as well as wh...
python
{ "resource": "" }
q18343
_get_memory_bank_size
train
def _get_memory_bank_size(memBank): """Get the size of a memory bank in bytes.""" fileName = '/sys/devices/system/node/node{0}/meminfo'.format(memBank) size = None with open(fileName) as f: for line in f: if 'MemTotal' in line: size = line.split(':')[1].strip() ...
python
{ "resource": "" }
q18344
Tool.determine_result
train
def determine_result(self, returncode, returnsignal, output, isTimeout): """ Returns a BenchExec result status based on the output of SMACK """ splitout = "\n".join(output) if 'SMACK found no errors' in splitout: return result.RESULT_TRUE_PROP errmsg = re.search...
python
{ "resource": "" }
q18345
ContainerExecutor._get_result_files_base
train
def _get_result_files_base(self, temp_dir): """Given the temp directory that is created for each run, return the path to the directory where files created by the tool are stored.""" if not self._use_namespaces: return super(ContainerExecutor, self)._get_result_files_base(temp_dir) ...
python
{ "resource": "" }
q18346
ContainerExecutor.execute_run
train
def execute_run(self, args, workingDir=None, output_dir=None, result_files_patterns=[], rootDir=None, environ=os.environ.copy()): """ This method executes the command line and waits for the termination of it, handling all setup and cleanup. @param args: the command li...
python
{ "resource": "" }
q18347
ContainerExecutor._setup_root_filesystem
train
def _setup_root_filesystem(self, root_dir): """Setup the filesystem layout in the given root directory. Create a copy of the existing proc- and dev-mountpoints in the specified root directory. Afterwards we chroot into it. @param root_dir: The path of the root directory that is used to ...
python
{ "resource": "" }
q18348
ContainerExecutor._transfer_output_files
train
def _transfer_output_files(self, tool_output_dir, working_dir, output_dir, patterns): """Transfer files created by the tool in the container to the output directory. @param tool_output_dir: The directory under which all tool output files are created. @param working_dir: The absolute working dire...
python
{ "resource": "" }
q18349
parse_table_definition_file
train
def parse_table_definition_file(file): ''' Read an parse the XML of a table-definition file. @return: an ElementTree object for the table definition ''' logging.info("Reading table definition from '%s'...", file) if not os.path.isfile(file): logging.error("File '%s' does not exist.", fil...
python
{ "resource": "" }
q18350
load_results_from_table_definition
train
def load_results_from_table_definition(table_definition, table_definition_file, options): """ Load all results in files that are listed in the given table-definition file. @return: a list of RunSetResult objects """ default_columns = extract_columns_from_table_definition_file(table_definition, table...
python
{ "resource": "" }
q18351
load_results_with_table_definition
train
def load_results_with_table_definition(result_files, table_definition, table_definition_file, options): """ Load results from given files with column definitions taken from a table-definition file. @return: a list of RunSetResult objects """ columns = extract_columns_from_table_definition_file(table...
python
{ "resource": "" }
q18352
extract_columns_from_table_definition_file
train
def extract_columns_from_table_definition_file(xmltag, table_definition_file): """ Extract all columns mentioned in the result tag of a table definition file. """ def handle_path(path): """Convert path from a path relative to table-definition file.""" if not path or path.startswith("http...
python
{ "resource": "" }
q18353
_get_columns_relevant_for_diff
train
def _get_columns_relevant_for_diff(columns_to_show): """ Extract columns that are relevant for the diff table. @param columns_to_show: (list) A list of columns that should be shown @return: (set) Set of columns that are relevant for the diff table. If none is marked relevant, the column na...
python
{ "resource": "" }
q18354
get_task_id
train
def get_task_id(task, base_path_or_url): """ Return a unique identifier for a given task. @param task: the XML element that represents a task @return a tuple with filename of task as first element """ name = task.get('name') if base_path_or_url: if Util.is_url(base_path_or_url): ...
python
{ "resource": "" }
q18355
load_tool
train
def load_tool(result): """ Load the module with the tool-specific code. """ def load_tool_module(tool_module): if not tool_module: logging.warning('Cannot extract values from log files for benchmark results %s ' '(missing attribute "toolmodule" on tag "res...
python
{ "resource": "" }
q18356
load_results
train
def load_results(result_files, options, run_set_id=None, columns=None, columns_relevant_for_diff=set()): """Version of load_result for multiple input files that will be loaded concurrently.""" return parallel.map( load_result, result_files, itertools.repeat(options), ...
python
{ "resource": "" }
q18357
load_result
train
def load_result(result_file, options, run_set_id=None, columns=None, columns_relevant_for_diff=set()): """ Completely handle loading a single result file. @param result_file the file to parse @param options additional options @param run_set_id the identifier of the run set @param...
python
{ "resource": "" }
q18358
parse_results_file
train
def parse_results_file(resultFile, run_set_id=None, ignore_errors=False): ''' This function parses an XML file that contains the results of the execution of a run set. It returns the "result" XML tag. @param resultFile: The file name of the XML file that contains the results. @param run_set_id: An o...
python
{ "resource": "" }
q18359
merge_task_lists
train
def merge_task_lists(runset_results, tasks): """ Set the filelists of all RunSetResult elements so that they contain the same files in the same order. For missing files a dummy element is inserted. """ for runset in runset_results: # create mapping from id to RunResult object # Use r...
python
{ "resource": "" }
q18360
get_rows
train
def get_rows(runSetResults): """ Create list of rows with all data. Each row consists of several RunResults. """ rows = [] for task_results in zip(*[runset.results for runset in runSetResults]): rows.append(Row(task_results)) return rows
python
{ "resource": "" }
q18361
filter_rows_with_differences
train
def filter_rows_with_differences(rows): """ Find all rows with differences in the status column. """ if not rows: # empty table return [] if len(rows[0].results) == 1: # table with single column return [] def get_index_of_column(name, cols): for i in ran...
python
{ "resource": "" }
q18362
select_relevant_id_columns
train
def select_relevant_id_columns(rows): """ Find out which of the entries in Row.id are equal for all given rows. @return: A list of True/False values according to whether the i-th part of the id is always equal. """ relevant_id_columns = [True] # first column (file name) is always relevant if row...
python
{ "resource": "" }
q18363
get_regression_count
train
def get_regression_count(rows, ignoreFlappingTimeouts): # for options.dump_counts """Count the number of regressions, i.e., differences in status of the two right-most results where the new one is not "better" than the old one. Any change in status between error, unknown, and wrong result is a regression. ...
python
{ "resource": "" }
q18364
RunSetResult.collect_data
train
def collect_data(self, correct_only): """ Load the actual result values from the XML file and the log files. This may take some time if many log files have to be opened and parsed. """ self.results = [] def get_value_from_logfile(lines, identifier): """ ...
python
{ "resource": "" }
q18365
Row.set_relative_path
train
def set_relative_path(self, common_prefix, base_dir): """ generate output representation of rows """ self.short_filename = self.filename.replace(common_prefix, '', 1)
python
{ "resource": "" }
q18366
Tool._version_newer_than
train
def _version_newer_than(self, vers): """ Determine whether the version is greater than some given version """ v = self.version(self.executable()) vers_num = v[:v.index('-')] if not vers_num[0].isdigit(): # this is the old version which is "older" than any give...
python
{ "resource": "" }
q18367
_get_user_account_info
train
def _get_user_account_info(user): """Get the user account info from the passwd database. Only works on Linux. @param user The name of a user account or a numeric uid prefixed with '#' @return a tuple that corresponds to the members of the passwd structure @raise KeyError: If user account is unknown ...
python
{ "resource": "" }
q18368
_reduce_file_size_if_necessary
train
def _reduce_file_size_if_necessary(fileName, maxSize): """ This function shrinks a file. We remove only the middle part of a file, the file-start and the file-end remain unchanged. """ fileSize = os.path.getsize(fileName) if maxSize is None: logging.debug("Size of logfile '%s' is %s...
python
{ "resource": "" }
q18369
_try_join_cancelled_thread
train
def _try_join_cancelled_thread(thread): """Join a thread, but if the thread doesn't terminate for some time, ignore it instead of waiting infinitely.""" thread.join(10) if thread.is_alive(): logging.warning("Thread %s did not terminate within grace period after cancellation", ...
python
{ "resource": "" }
q18370
RunExecutor._init_cgroups
train
def _init_cgroups(self): """ This function initializes the cgroups for the limitations and measurements. """ self.cgroups = find_my_cgroups() for subsystem in self._cgroup_subsystems: self.cgroups.require_subsystem(subsystem) if subsystem not in self.cgro...
python
{ "resource": "" }
q18371
RunExecutor._build_cmdline
train
def _build_cmdline(self, args, env={}): """ Build the final command line for executing the given command, using sudo if necessary. """ if self._user is None: return super(RunExecutor, self)._build_cmdline(args, env) result = _SUDO_ARGS + [self._user] f...
python
{ "resource": "" }
q18372
RunExecutor._kill_process
train
def _kill_process(self, pid, cgroups=None, sig=signal.SIGKILL): """ Try to send signal to given process, either directly of with sudo. Because we cannot send signals to the sudo process itself, this method checks whether the target is the sudo process and redirects the signal to ...
python
{ "resource": "" }
q18373
RunExecutor._listdir
train
def _listdir(self, path): """Return the list of files in a directory, assuming that our user can read it.""" if self._user is None: return os.listdir(path) else: args = self._build_cmdline(['/bin/ls', '-1A', path]) return subprocess.check_output(args, stderr=D...
python
{ "resource": "" }
q18374
RunExecutor._setup_cgroups
train
def _setup_cgroups(self, my_cpus, memlimit, memory_nodes, cgroup_values): """ This method creates the CGroups for the following execution. @param my_cpus: None or a list of the CPU cores to use @param memlimit: None or memory limit in bytes @param memory_nodes: None or a list of ...
python
{ "resource": "" }
q18375
RunExecutor._create_temp_dir
train
def _create_temp_dir(self): """Create a temporary directory for the run.""" if self._user is None: base_dir = tempfile.mkdtemp(prefix="BenchExec_run_") else: create_temp_dir = self._build_cmdline([ 'python', '-c', 'import tempfile;' ...
python
{ "resource": "" }
q18376
RunExecutor._cleanup_temp_dir
train
def _cleanup_temp_dir(self, base_dir): """Delete given temporary directory and all its contents.""" if self._should_cleanup_temp_dir: logging.debug('Cleaning up temporary directory %s.', base_dir) if self._user is None: util.rmtree(base_dir, onerror=util.log_rmtre...
python
{ "resource": "" }
q18377
RunExecutor._setup_environment
train
def _setup_environment(self, environments): """Return map with desired environment variables for run.""" # If keepEnv is set or sudo is used, start from a fresh environment, # otherwise with the current one. # keepEnv specifies variables to copy from the current environment, # ne...
python
{ "resource": "" }
q18378
RunExecutor._setup_output_file
train
def _setup_output_file(self, output_filename, args, write_header=True): """Open and prepare output file.""" # write command line into outputFile # (without environment variables, they are documented by benchexec) try: output_file = open(output_filename, 'w') # override existi...
python
{ "resource": "" }
q18379
RunExecutor._setup_cgroup_time_limit
train
def _setup_cgroup_time_limit(self, hardtimelimit, softtimelimit, walltimelimit, cgroups, cores, pid_to_kill): """Start time-limit handler. @return None or the time-limit handler for calling cancel() """ # hard time limit with cgroups is optional (addition...
python
{ "resource": "" }
q18380
RunExecutor._setup_cgroup_memory_limit
train
def _setup_cgroup_memory_limit(self, memlimit, cgroups, pid_to_kill): """Start memory-limit handler. @return None or the memory-limit handler for calling cancel() """ if memlimit is not None: try: oomThread = oomhandler.KillProcessOnOomThread( ...
python
{ "resource": "" }
q18381
RunExecutor._setup_ulimit_time_limit
train
def _setup_ulimit_time_limit(self, hardtimelimit, cgroups): """Setup time limit with ulimit for the current process.""" if hardtimelimit is not None: # Also use ulimit for CPU time limit as a fallback if cgroups don't work. if CPUACCT in cgroups: # Use a slightly ...
python
{ "resource": "" }
q18382
RunExecutor._setup_file_hierarchy_limit
train
def _setup_file_hierarchy_limit( self, files_count_limit, files_size_limit, temp_dir, cgroups, pid_to_kill): """Start thread that enforces any file-hiearchy limits.""" if files_count_limit is not None or files_size_limit is not None: file_hierarchy_limit_thread = FileHierarchyLim...
python
{ "resource": "" }
q18383
RunExecutor._get_cgroup_measurements
train
def _get_cgroup_measurements(self, cgroups, ru_child, result): """ This method calculates the exact results for time and memory measurements. It is not important to call this method as soon as possible after the run. """ logging.debug("Getting cgroup measurements.") cput...
python
{ "resource": "" }
q18384
RunExecutor.check_for_new_files_in_home
train
def check_for_new_files_in_home(self): """Check that the user account's home directory now does not contain more files than when this instance was created, and warn otherwise. Does nothing if no user account was given to RunExecutor. @return set of newly created files """ ...
python
{ "resource": "" }
q18385
sethostname
train
def sethostname(name): """Set the host name of the machine.""" # TODO: replace with socket.sethostname, which is available from Python 3.3 name = name.encode() _libc.sethostname(name, len(name))
python
{ "resource": "" }
q18386
check_cgroup_availability
train
def check_cgroup_availability(wait=1): """ Basic utility to check the availability and permissions of cgroups. This will log some warnings for the user if necessary. On some systems, daemons such as cgrulesengd might interfere with the cgroups of a process soon after it was started. Thus this functi...
python
{ "resource": "" }
q18387
Tool.allInText
train
def allInText(self, words, text): """ This function checks, if all the words appear in the given order in the text. """ index = 0 for word in words: index = text[index:].find(word) if index == -1: return False return True
python
{ "resource": "" }
q18388
printOut
train
def printOut(value, end='\n'): """ This function prints the given String immediately and flushes the output. """ sys.stdout.write(value) sys.stdout.write(end) sys.stdout.flush()
python
{ "resource": "" }
q18389
is_code
train
def is_code(filename): """ This function returns True, if a line of the file contains bracket '{'. """ with open(filename, "r") as file: for line in file: # ignore comments and empty lines if not is_comment(line) \ and '{' in line: # <-- simple indica...
python
{ "resource": "" }
q18390
get_list_from_xml
train
def get_list_from_xml(elem, tag="option", attributes=["name"]): ''' This function searches for all "option"-tags and returns a list with all attributes and texts. ''' return flatten(([option.get(attr) for attr in attributes] + [option.text] for option in elem.findall(tag)), exclude=[None])
python
{ "resource": "" }
q18391
parse_int_list
train
def parse_int_list(s): """ Parse a comma-separated list of strings. The list may additionally contain ranges such as "1-5", which will be expanded into "1,2,3,4,5". """ result = [] for item in s.split(','): item = item.strip().split('-') if len(item) == 1: result....
python
{ "resource": "" }
q18392
split_number_and_unit
train
def split_number_and_unit(s): """Parse a string that consists of a integer number and an optional unit. @param s a non-empty string that starts with an int and is followed by some letters @return a triple of the number (as int) and the unit """ if not s: raise ValueError('empty value') s...
python
{ "resource": "" }
q18393
parse_memory_value
train
def parse_memory_value(s): """Parse a string that contains a number of bytes, optionally with a unit like MB. @return the number of bytes encoded by the string """ number, unit = split_number_and_unit(s) if not unit or unit == 'B': return number elif unit == 'kB': return number *...
python
{ "resource": "" }
q18394
parse_timespan_value
train
def parse_timespan_value(s): """Parse a string that contains a time span, optionally with a unit like s. @return the number of seconds encoded by the string """ number, unit = split_number_and_unit(s) if not unit or unit == "s": return number elif unit == "min": return number * 6...
python
{ "resource": "" }
q18395
expand_filename_pattern
train
def expand_filename_pattern(pattern, base_dir): """ Expand a file name pattern containing wildcards, environment variables etc. @param pattern: The pattern string to expand. @param base_dir: The directory where relative paths are based on. @return: A list of file names (possibly empty). """ ...
python
{ "resource": "" }
q18396
substitute_vars
train
def substitute_vars(template, replacements): """Replace certain keys with respective values in a string. @param template: the string in which replacements should be made @param replacements: a dict or a list of pairs of keys and values """ result = template for (key, value) in replacements: ...
python
{ "resource": "" }
q18397
rmtree
train
def rmtree(path, ignore_errors=False, onerror=None): """Same as shutil.rmtree, but supports directories without write or execute permissions.""" if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise for root, dirs, unused_files...
python
{ "resource": "" }
q18398
copy_all_lines_from_to
train
def copy_all_lines_from_to(inputFile, outputFile): """Copy all lines from an input file object to an output file object.""" currentLine = inputFile.readline() while currentLine: outputFile.write(currentLine) currentLine = inputFile.readline()
python
{ "resource": "" }
q18399
write_file
train
def write_file(content, *path): """ Simply write some content to a file, overriding the file if necessary. """ with open(os.path.join(*path), "w") as file: return file.write(content)
python
{ "resource": "" }