text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_cleanup(self, subcmd, opts, *args): """Recursively clean up the working copy, removing locks, resuming unfinished operations, etc. usage: ${cmd_option_lis...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_commit(self, subcmd, opts, *args): """Send changes from your working copy to the repository. usage: A log message must be provided, but it can be empty. I...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_copy(self, subcmd, opts, *args): """Duplicate something in working copy or repository, remembering history. usage: copy SRC DST SRC and DST can each be ei...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_delete(self, subcmd, opts, *args): """Remove files and directories from version control. usage: 1. Each item specified by a PATH is scheduled for deletion...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_diff(self, subcmd, opts, *args): """Display the differences between two paths. usage: 2. diff [-r N[:M]] --old=OLD-TGT[@OLDREV] [--new=NEW-TGT[@NEWREV]] \...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_import(self, subcmd, opts, *args): """Commit an unversioned file or tree into the repository. usage: import [PATH] URL Recursively commit a copy of PATH t...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_info(self, subcmd, opts, *args): """Display information about a file or directory. usage: Print information about each PATH (default: '.'). ${cmd_option_l...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_list(self, subcmd, opts, *args): """List directory entries in the repository. usage: List each TARGET file and the contents of each TARGET directory as th...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_merge(self, subcmd, opts, *args): """Apply the differences between two sources to a working copy path. usage: 1. merge sourceURL1[@N] sourceURL2[@M] [WCPA...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_mkdir(self, subcmd, opts, *args): """Create a new directory under version control. usage: Create version controlled directories. 1. Each directory specifi...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_propdel(self, subcmd, opts, *args): """Remove PROPNAME from files, dirs, or revisions. usage: 2. propdel PROPNAME --revprop -r REV [URL] 1. Removes versio...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_propedit(self, subcmd, opts, *args): """Edit property PROPNAME with an external editor on targets. usage: 2. propedit PROPNAME --revprop -r REV [URL] 1. E...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_propget(self, subcmd, opts, *args): """Print value of PROPNAME on files, dirs, or revisions. usage: 2. propget PROPNAME --revprop -r REV [URL] 1. Prints v...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_proplist(self, subcmd, opts, *args): """List all properties on files, dirs, or revisions. usage: 2. proplist --revprop -r REV [URL] 1. Lists versioned pro...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_propset(self, subcmd, opts, *args): """Set PROPNAME to PROPVAL on files, dirs, or revisions. usage: 2. propset PROPNAME --revprop -r REV [PROPVAL | -F VAL...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_resolved(self, subcmd, opts, *args): """Remove 'conflicted' state on working copy files or directories. usage: Note: this subcommand does not semantically...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_status(self, subcmd, opts, *args): """Print the status of working copy files and directories. usage: With no args, print only locally modified items (no n...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_switch(self, subcmd, opts, *args): """Update the working copy to a different URL. usage: 1. switch URL [PATH] 1. Update the working copy to mirror a new U...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_update(self, subcmd, opts, *args): """Bring changes from the repository into the working copy. usage: If no revision given, bring working copy up-to-date ...
print "'svn %s' opts: %s" % (subcmd, opts) print "'svn %s' args: %s" % (subcmd, args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_redirect(request, fallback_url, **kwargs): """ Evaluates a redirect url by consulting GET, POST and the session. """
redirect_field_name = kwargs.get("redirect_field_name", "next") next = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, '')) if not next: # try the session if available if hasattr(request, "session"): session_key_value = kwar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_error(self, path, error): """Add error message for given field path. Example: :: builder = ValidationErrorBuilder() builder.add_error('foo.bar.baz', 'Som...
self.errors = merge_errors(self.errors, self._make_error(path, error))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_suitable_period(): """ Automatically find a suitable period to use. Factors are best, because they will have 1 left over when dividing SIZE+1. This only...
# The highest acceptable factor will be the square root of the size. highest_acceptable_factor = int(math.sqrt(SIZE)) # Too high a factor (eg SIZE/2) and the interval is too small, too # low (eg 2) and the period is too small. # We would prefer it to be lower than the number of VALID_CHARS, but mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def friendly_number(num): """ Convert a base 10 number to a base X string. Charcters from VALID_CHARS are chosen, to convert the number to eg base 24, if there a...
# Convert to a (shorter) string for human consumption string = "" # The length of the string can be determined by STRING_LENGTH or by how many # characters are necessary to present a base 30 representation of SIZE. while STRING_LENGTH and len(string) <= STRING_LENGTH \ or len(VALID_CHAR...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _login(session): """Login to Fedex Delivery Manager."""
session.get(LOGIN_REFERER) resp = session.post(LOGIN_URL, { 'user': session.auth.username, 'pwd': session.auth.password }, headers={ 'Referer': LOGIN_REFERER, 'X-Requested-With': 'XMLHttpRequest' }) if resp.status_code != 200: raise FedexError('could not logi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_packages(session): """Get packages."""
resp = session.post(TRACKING_URL, { 'data': json.dumps(SHIPMENT_LIST_REQUEST), 'action': SHIPMENT_LIST_ACTION, 'format': SHIPMENT_LIST_FORMAT, 'locale': session.auth.locale, 'version': 1 }) data = resp.json().get('ShipmentListLightResponse') if not data.get('succ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict_value_hint(key, mapper=None): """Returns a function that takes a dictionary and returns value of particular key. The returned value can be optionally pr...
if mapper is None: mapper = identity def hinter(data): return mapper(data.get(key)) return hinter
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validated_type(base_type, name=None, validate=None): """Convenient way to create a new type by adding validation to existing type. Example: :: Ipv4Address = ...
if validate is None: validate = [] if not is_sequence(validate): validate = [validate] class ValidatedSubtype(base_type): if name is not None: __name__ = name def __init__(self, *args, **kwargs): super(ValidatedSubtype, self).__init__(*args, **kwarg...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(self, data, context=None): """Takes serialized data and returns validation errors or None. :param data: Data to validate. :param context: Context da...
try: self.load(data, context) return None except ValidationError as ve: return ve.messages
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_into(self, obj, data, inplace=True, *args, **kwargs): """Load data and update existing object. :param obj: Object to update with deserialized data. :par...
if obj is None: raise ValueError('Load target should not be None') if data is MISSING: return if data is None: self._fail('required') if not is_mapping(data): self._fail('invalid', data=data) errors_builder = ValidationErrorBui...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_for(self, obj, data, *args, **kwargs): """Takes target object and serialized data, tries to update that object with data and validate result. Return...
try: self.load_into(obj, data, inplace=False, *args, **kwargs) return None except ValidationError as ve: return ve.messages
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_country_locations(api_response, is_country=True): """ Filter the response to only include the elements that are countries. This uses the 'api_response...
return [item for item in api_response if item[ISCOUNTRY]==is_country]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_next_number(self): """ Returnes next invoice number - reset yearly. .. warning:: This is only used to prepopulate ``number`` field on saving new invoice...
# Recupere les facture de l annee relative_invoices = Invoice.objects.filter(invoice_date__year=self.invoice_date.year) # on prend le numero le plus eleve du champs number, sinon on met 0 last_number = relative_invoices.aggregate(Max('number'))['number__max'] or 0 return last_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_context_aware(func, numargs): """ Check if given function has no more arguments than given. If so, wrap it into another function that takes extra argume...
try: if inspect.ismethod(func): arg_count = len(inspect.getargspec(func).args) - 1 elif inspect.isfunction(func): arg_count = len(inspect.getargspec(func).args) elif inspect.isclass(func): arg_count = len(inspect.getargspec(func.__init__).args) - 1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call_with_context(func, context, *args): """ Check if given function has more arguments than given. Call it with context as last argument or without it. """
return make_context_aware(func, len(args))(*args + (context,))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_snake_case(s): """Converts camel-case identifiers to snake-case."""
return re.sub('([^_A-Z])([A-Z])', lambda m: m.group(1) + '_' + m.group(2).lower(), s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_settings(settings): """Ensure all user-supplied settings exist, or throw a useful error message. :param obj settings: The Django settings object. ""...
if not (settings.STORMPATH_ID and settings.STORMPATH_SECRET): raise ImproperlyConfigured('Both STORMPATH_ID and STORMPATH_SECRET must be specified in settings.py.') if not settings.STORMPATH_APPLICATION: raise ImproperlyConfigured('STORMPATH_APPLICATION must be specified in settings.py.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_default_is_active(): """ Stormpath user is active by default if e-mail verification is disabled. """
directory = APPLICATION.default_account_store_mapping.account_store verif_email = directory.account_creation_policy.verification_email_status return verif_email == AccountCreationPolicy.EMAIL_STATUS_DISABLED
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stormpath_authenticate(self, username, password): """Check if Stormpath authentication works :param username: Can be actual username or email :param passwor...
APPLICATION = get_application() try: result = APPLICATION.authenticate_account(username, password) return result.account except Error as e: log.debug(e) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_group_difference(self, sp_groups): """Helper method for gettings the groups that are present in the local db but not on stormpath and the other way arou...
db_groups = set(Group.objects.all().values_list('name', flat=True)) missing_from_db = set(sp_groups).difference(db_groups) missing_from_sp = db_groups.difference(sp_groups) return (missing_from_db, missing_from_sp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mirror_groups_from_stormpath(self): """Helper method for saving to the local db groups that are missing but are on Stormpath"""
APPLICATION = get_application() sp_groups = [g.name for g in APPLICATION.groups] missing_from_db, missing_from_sp = self._get_group_difference(sp_groups) if missing_from_db: groups_to_create = [] for g_name in missing_from_db: groups_to_create.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fmtstring(offset, writes, written=0, max_width=2, target=None): """ Build a format string that writes given data to given locations. Can be used easily creat...
if max_width not in (1, 2, 4): raise ValueError('max_width should be 1, 2 or 4') if target is None: target = pwnypack.target.target addrs = [] cmds = [] piece_writes = [] for write in writes: if len(write) == 2: addr, value = write width = tar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_class(import_path=None): """ Largely based on django.core.files.storage's get_storage_class """
from django.core.exceptions import ImproperlyConfigured if import_path is None: raise ImproperlyConfigured('No class path specified.') try: dot = import_path.rindex('.') except ValueError: raise ImproperlyConfigured("%s isn't a module." % import_path) module, classname = imp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve_private_file(request, path): """ Serve private files to users with read permission. """
logger.debug('Serving {0} to {1}'.format(path, request.user)) if not permissions.has_read_permission(request, path): if settings.DEBUG: raise PermissionDenied else: raise Http404('File not found') return server.serve(request, path=path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symbols_app(parser, _, args): # pragma: no cover """ List ELF symbol table. """
parser.add_argument('file', help='ELF file to list the symbols of') parser.add_argument('symbol', nargs='?', help='show only this symbol') parser.add_argument('--exact', '-e', action='store_const', const=True, help='filter by exact symbol name') args = parser.parse_args(args) print('%-18s %5s %-7...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_symbol_app(parser, _, args): # pragma: no cover """ Extract a symbol from an ELF file. """
parser.add_argument('file', help='ELF file to extract a symbol from') parser.add_argument('symbol', help='the symbol to extract') args = parser.parse_args(args) return ELF(args.file).get_symbol(args.symbol).content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_header(self, data): """ Parse the ELF header in ``data`` and populate the properties. Args: data(bytes): The ELF header. """
(magic, word_size, byte_order, version, osabi, abi_version, _), data = \ unpack('4sBBBBB7s', data[:16]), data[16:] assert magic == self._ELF_MAGIC, 'Missing ELF magic' assert word_size in (1, 2), 'Invalid word size' assert byte_order in (1, 2), 'Invalid byte order' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_file(self, f): """ Parse an ELF file and fill the class' properties. Arguments: f(file or str): The (path to) the ELF file to read. """
if type(f) is str: self.f = open(f, 'rb') else: self.f = f self._parse_header(self.f.read(64))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_section_header(self, section): """ Get a specific section header by index or name. Args: section(int or str): The index or name of the section header to...
self._ensure_section_headers_loaded() if type(section) is int: return self._section_headers_by_index[section] else: return self._section_headers_by_name[section]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_symbol(self, symbol): """ Get a specific symbol by index or name. Args: symbol(int or str): The index or name of the symbol to return. Returns: ELF.Symb...
self._ensure_symbols_loaded() if type(symbol) is int: return self._symbols_by_index[symbol] else: return self._symbols_by_name[symbol]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def connected(self, tables, cols, find_connections=False): ''' Returns a list of tuples of connected table pairs. :param tables: a list of table names :param cols: a list of column names :param find_connections: set this to True to detect relationships from column na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pyc_load(fp): """ Load a .pyc file from a file-like object. Arguments: fp(file): The file-like object to read. Returns: PycFile: The parsed representation o...
magic_1 = U16(fp.read(2), target=MARSHAL_TARGET) magic_2 = U16(fp.read(2), target=MARSHAL_TARGET) internals = MAGIC_MAP.get(magic_1) if internals is None: raise ValueError('Invalid or unknown magic (%d).' % magic_1) if magic_2 != 2573: raise ValueError('Invalid secondary magic (%...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mode(self, predicate, args, recall=1, head=False): ''' Emits mode declarations in Aleph-like format. :param predicate: predicate name :param args: predicate arguments with input/output specification, e.g.: >>> [('+', 'train'), ('-', 'car')] :param r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def all_examples(self, pred_name=None): ''' Emits all examples in prolog form for RSD. :param pred_name: override for the emitted predicate name ''' target = self.db.target_table pred_name = pred_name if pred_name else target examples = self.db.rows(target, [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def background_knowledge(self): ''' Emits the background knowledge in prolog form for RSD. ''' modeslist, getters = [self.mode(self.db.target_table, [('+', self.db.target_table)], head=True)], [] for (table, ref_table) in self.db.connected.keys(): if ref_table == self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def background_knowledge(self): ''' Emits the background knowledge in prolog form for Aleph. ''' modeslist, getters = [self.mode(self.__target_predicate(), [('+', self.db.target_table)], head=True)], [] determinations, types = [], [] for (table, ref_table) in self.db.conn...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def target_Orange_table(self): ''' Returns the target table as an Orange example table. :rtype: orange.ExampleTable ''' table, cls_att = self.db.target_table, self.db.target_att if not self.db.orng_tables: return self.convert_table(table, cls_att=cls_att)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def other_Orange_tables(self): ''' Returns the related tables as Orange example tables. :rtype: list ''' target_table = self.db.target_table if not self.db.orng_tables: return [self.convert_table(table, None) for table in self.db.tables if table != ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def convert_table(self, table_name, cls_att=None): ''' Returns the specified table as an orange example table. :param table_name: table name to convert :cls_att: class attribute name :rtype: orange.ExampleTable ''' import Orange cols = self.d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def orng_type(self, table_name, col): ''' Returns an Orange datatype for a given mysql column. :param table_name: target table name :param col: column to determine the Orange datatype ''' mysql_type = self.types[table_name][col] n_vals = len(self.db.col_v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _discretize_check(self, table, att, col): ''' Replaces the value with an appropriate interval symbol, if available. ''' label = "'%s'" % col if table in self.discr_intervals and att in self.discr_intervals[table]: intervals = self.discr_intervals[table][att] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dataset(self): ''' Returns the DBContext as a list of interpretations, i.e., a list of facts true for each example in the format for TreeLiker. ''' target = self.db.target_table db_examples = self.db.rows(target, [self.db.target_att, self.db.pkeys[target]]) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_prd_file(self): ''' Emits the background knowledge in prd format. ''' prd_str = '' prd_str += '--INDIVIDUAL\n' prd_str += '%s 1 %s cwa\n' % (self.db.target_table, self.db.target_table) prd_str += '--STRUCTURAL\n' for ftable, ptable in self.db.re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def create_fct_file(self): ''' Emits examples in fct format. ''' fct_str = '' fct_str += self.fct_rec(self.db.target_table) return fct_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convex_hull(features): """Returns points on convex hull of an array of points in CCW order."""
points = sorted([s.point() for s in features]) l = reduce(_keep_left, points, []) u = reduce(_keep_left, reversed(points), []) return l.extend(u[i] for i in xrange(1, len(u) - 1)) or l
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disassemble(self, annotate=False, blocks=False): """ Disassemble the bytecode of this code object into a series of opcodes and labels. Can also annotate the ...
ops = disassemble(self.co_code, self.internals) if annotate: ops = [self.annotate_op(op) for op in ops] if blocks: return blocks_from_ops(ops) else: return ops
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_code(self): """ Convert this instance back into a native python code object. This only works if the internals of the code object are compatible with those...
if self.internals is not get_py_internals(): raise ValueError('CodeObject is not compatible with the running python internals.') if six.PY2: return types.CodeType( self.co_argcount, self.co_nlocals, self.co_stacksize, self.co_flags, self.co_code, self.co_consts...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reload_index(self, progress_cb=dummy_progress_cb): """ Read the index, and load the document list from it Arguments: callback --- called during the indexatio...
nb_results = self.index.start_reload_index() progress = 0 while self.index.continue_reload_index(): progress_cb(progress, nb_results, self.INDEX_STEP_LOADING) progress += 1 progress_cb(1, 1, self.INDEX_STEP_LOADING) self.index.end_reload_index()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_label(self, old_label, new_label, callback=dummy_progress_cb): """ Replace 'old_label' by 'new_label' on all the documents. Takes care of updating the...
current = 0 total = self.index.get_nb_docs() self.index.start_update_label(old_label, new_label) while True: (op, doc) = self.index.continue_update_label() if op == 'end': break callback(current, total, self.LABEL_STEP_UPDATING, doc) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy_label(self, label, callback=dummy_progress_cb): """ Remove the label 'label' from all the documents. Takes care of updating the index. """
current = 0 total = self.index.get_nb_docs() self.index.start_destroy_label(label) while True: (op, doc) = self.index.continue_destroy_label() if op == 'end': break callback(current, total, self.LABEL_STEP_DESTROYING, doc) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _update_context(context, postdata): ''' Updates the default selections with user's selections. ''' listCheck = lambda el: el[0] if type(el) == list else el # For handling lists of size 1 widget_id = listCheck(postdata.get('widget_id')) context.target_table = listCheck(postdata.get('target_t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def do_map(input_dict, feature_format, positive_class=None): ''' Maps a new example to a set of features. ''' # Context of the unseen example(s) train_context = input_dict['train_ctx'] test_context = input_dict['test_ctx'] # Currently known examples & background knowledge features = inp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serialize_object(self, obj): """ Write one item to the object stream """
self.start_object(obj) for field in obj._meta.local_fields: if field.serialize and getattr(field, 'include_in_xml', True): if field.rel is None: if self.selected_fields is None or field.attname in self.selected_fields: self.handle_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_m2m_field(self, obj, field): """ while easymode follows inverse relations for foreign keys, for manytomayfields it follows the forward relation. While...
if field.rel.through._meta.auto_created:# and obj.__class__ is not field.rel.to: # keep approximate recursion level with recursion_depth('handle_m2m_field') as recursion_level: # a stack trace is better than python crashing. if ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_capstone(syntax=AsmSyntax.att, target=None): """ Prepare a capstone disassembler instance for a given target and syntax. Args: syntax(AsmSyntax): Th...
if not HAVE_CAPSTONE: raise NotImplementedError('pwnypack requires capstone to disassemble to AT&T and Intel syntax') if target is None: target = pwnypack.target.target if target.arch == pwnypack.target.Target.Arch.x86: if target.bits is pwnypack.target.Target.Bits.bits_32: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disasm(code, addr=0, syntax=None, target=None): """ Disassemble machine readable code into human readable statements. Args: code(bytes): The machine code th...
if target is None: target = pwnypack.target.target if syntax is None: if target.arch is pwnypack.target.Target.Arch.x86: syntax = AsmSyntax.nasm else: syntax = AsmSyntax.att if syntax is AsmSyntax.nasm: if target.arch is not pwnypack.target.Target....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def asm_app(parser, cmd, args): # pragma: no cover """ Assemble code from commandline or stdin. Please not that all semi-colons are replaced with carriage return...
parser.add_argument('source', help='the code to assemble, read from stdin if omitted', nargs='?') pwnypack.main.add_target_arguments(parser) parser.add_argument( '--syntax', '-s', choices=AsmSyntax.__members__.keys(), default=None, ) parser.add_argument( '--address'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disasm_app(_parser, cmd, args): # pragma: no cover """ Disassemble code from commandline or stdin. """
parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) parser.add_argument('code', help='the code to disassemble, read from stdin if omitted', nargs='?') pwnypack.main.add_target_arguments(parser) parser.add_argument( '--syntax', '-s', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disasm_symbol_app(_parser, _, args): # pragma: no cover """ Disassemble a symbol from an ELF file. """
parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) parser.add_argument( '--syntax', '-s', choices=AsmSyntax.__members__.keys(), default=None, ) parser.add_argument('file', help='ELF file to extract a symbol from') par...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def settingsAsFacts(self, settings): """ Parses a string of settings. :param setting: String of settings in the form: """
pattern = re.compile('set\(([a-zA-Z0-9_]+),(\[a-zA-Z0-9_]+)\)') pairs = pattern.findall(settings) for name, val in pairs: self.set(name, val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __scripts(self, filestem): """ Generates the required scripts. """
script_construct = open('%s/%s' % (self.tmpdir, RSD.CONSTRUCT), 'w') script_save = open('%s/%s' % (self.tmpdir, RSD.SAVE), 'w') script_subgroups = open('%s/%s' % (self.tmpdir, RSD.SUBGROUPS), 'w') # Permit the owner to execute and read this script for fn in RSD.SCRIPTS: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deBruijn(n, k): """ An implementation of the FKM algorithm for generating the de Bruijn sequence containing all k-ary strings of length n, as described in "C...
a = [ 0 ] * (n + 1) def gen(t, p): if t > n: for v in a[1:p + 1]: yield v else: a[t] = a[t - p] for v in gen(t + 1, p): yield v for j in range(a[t - p] + 1, k): a[t] = j ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cycle_find(key, width=4): """ Given an element of a de Bruijn sequence, find its index in that sequence. Args: key(str): The piece of the de Bruijn sequence...
key_len = len(key) buf = '' it = deBruijn(width, 26) for i in range(key_len): buf += chr(ord('A') + next(it)) if buf == key: return 0 for i, c in enumerate(it): buf = buf[1:] + chr(ord('A') + c) if buf == key: return i + 1 return -1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cycle_app(parser, cmd, args): # pragma: no cover """ Generate a de Bruijn sequence of a given length. """
parser.add_argument('-w', '--width', type=int, default=4, help='the length of the cycled value') parser.add_argument('length', type=int, help='the cycle length to generate') args = parser.parse_args(args) return cycle(args.length, args.width)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cycle_find_app(_parser, cmd, args): # pragma: no cover """ Find the first position of a value in a de Bruijn sequence. """
parser = argparse.ArgumentParser( prog=_parser.prog, description=_parser.description, ) parser.add_argument('-w', '--width', type=int, default=4, help='the length of the cycled value') parser.add_argument('value', help='the value to determine the position of, read from stdin if missing...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unescape_all(string): """Resolve all html entities to their corresponding unicode character"""
def escape_single(matchobj): return _unicode_for_entity_with_name(matchobj.group(1)) return entities.sub(escape_single, string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(xml_string): """validates a unicode string containing xml"""
xml_file = StringIO.StringIO(xml_string.encode('utf-8')) parser = XmlScanner() parser.setContentHandler(ContentHandler()) try: parser.parse(xml_file) except SAXParseException: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __inst_doc(self, docid, doc_type_name=None): """ Instantiate a document based on its document id. The information are taken from the whoosh index. """
doc = None docpath = self.fs.join(self.rootdir, docid) if not self.fs.exists(docpath): return None if doc_type_name is not None: # if we already know the doc type name for (is_doc_type, doc_type_name_b, doc_type) in DOC_TYPE_LIST: if (...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_doc_from_docid(self, docid, doc_type_name=None, inst=True): """ Try to find a document based on its document id. if inst=True, if it hasn't been instanti...
assert(docid is not None) if docid in self._docs_by_id: return self._docs_by_id[docid] if not inst: return None doc = self.__inst_doc(docid, doc_type_name) if doc is None: return None self._docs_by_id[docid] = doc return doc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _delete_doc_from_index(index_writer, docid): """ Remove a document from the index """
query = whoosh.query.Term("docid", docid) index_writer.delete_by_query(query)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upd_doc(self, doc, index_update=True, label_guesser_update=True): """ Update a document in the index """
if not self.index_writer and index_update: self.index_writer = self.index.writer() if not self.label_guesser_updater and label_guesser_update: self.label_guesser_updater = self.label_guesser.get_updater() logger.info("Updating modified doc: %s" % doc) if index_up...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancel(self): """ Forget about the changes """
logger.info("Index: Index update cancelled") if self.index_writer: self.index_writer.cancel() del self.index_writer self.index_writer = None if self.label_guesser_updater: self.label_guesser_updater.cancel() self.label_guesser_updater = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, obj_id): """ Get a document or a page using its ID Won't instantiate them if they are not yet available """
if BasicPage.PAGE_ID_SEPARATOR in obj_id: (docid, page_nb) = obj_id.split(BasicPage.PAGE_ID_SEPARATOR) page_nb = int(page_nb) return self._docs_by_id[docid].pages[page_nb] return self._docs_by_id[obj_id]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_documents(self, sentence, limit=None, must_sort=True, search_type='fuzzy'): """ Returns all the documents matching the given keywords Arguments: sentenc...
sentence = sentence.strip() sentence = strip_accents(sentence) if sentence == u"": return self.get_all_docs() result_list_list = [] total_results = 0 for query_parser in self.search_param_list[search_type]: query = query_parser["query_parser"]....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_suggestions(self, sentence): """ Search all possible suggestions. Suggestions returned always have at least one document matching. Arguments: sentence -...
if not isinstance(sentence, str): sentence = str(sentence) keywords = sentence.split(" ") query_parser = self.search_param_list['strict'][0]['query_parser'] base_search = u" ".join(keywords).strip() final_suggestions = [] corrector = self.__searcher.correc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_label(self, doc, label, update_index=True): """ Add a label on a document. Arguments: label --- The new label (see labels.Label) doc --- The first docume...
label = copy.copy(label) assert(label in self.labels.values()) doc.add_label(label) if update_index: self.upd_doc(doc) self.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy_index(self): """ Destroy the index. Don't use this Index object anymore after this call. Index will have to be rebuilt from scratch """
self.close() logger.info("Destroying the index ...") rm_rf(self.indexdir) rm_rf(self.label_guesser_dir) logger.info("Done")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_hash_in_index(self, filehash): """ Check if there is a document using this file hash """
filehash = (u"%X" % filehash) results = self.__searcher.search( whoosh.query.Term('docfilehash', filehash)) return bool(results)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_fallback_languages(): """Retrieve the fallback languages from the settings.py"""
lang = translation.get_language() fallback_list = settings.FALLBACK_LANGUAGES.get(lang, None) if fallback_list: return fallback_list return settings.FALLBACK_LANGUAGES.get(lang[:2], [])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_localized_field_name(context, field): """Get the name of the localized field"""
attrs = [ translation.get_language(), translation.get_language()[:2], settings.LANGUAGE_CODE ] def predicate(x): field_name = get_real_fieldname(field, x) if hasattr(context, field_name): return field_name ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field_from_model_by_name(model_class, field_name): """ Get a field by name from a model class without messing with the app cache. """
return first_match(lambda x: x if x.name == field_name else None, model_class._meta.fields)