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 parse(db_folder, out_folder): """ Parse a cronos database. Convert the database located in ``db_folder`` into CSV files in the directory ``out_folder``. """
# The database structure, containing table and column definitions as # well as other data. stru_dat = get_file(db_folder, 'CroStru.dat') # Index file for the database, which contains offsets for each record. data_tad = get_file(db_folder, 'CroBank.tad') # Actual data records, can only be decode...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode1(self): """Return the base64 encoding of the figure file and insert in html image tag."""
data_uri = b64encode(open(self.path, 'rb').read()).decode('utf-8').replace('\n', '') return '<img src="data:image/png;base64,{0}">'.format(data_uri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode2(self): """Return the base64 encoding of the fig attribute and insert in html image tag."""
buf = BytesIO() self.fig.savefig(buf, format='png', bbox_inches='tight', dpi=100) buf.seek(0) string = b64encode(buf.read()) return '<img src="data:image/png;base64,{0}">'.format(urlquote(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 loadFromDisk(self, calculation): """ Read the spectra from the files generated by Quanty and store them as a list of spectum objects. """
suffixes = { 'Isotropic': 'iso', 'Circular Dichroism (R-L)': 'cd', 'Right Polarized (R)': 'r', 'Left Polarized (L)': 'l', 'Linear Dichroism (V-H)': 'ld', 'Vertical Polarized (V)': 'v', 'Horizontal Polarized (H)': 'h', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateResultsView(self, index): """ Update the selection to contain only the result specified by the index. This should be the last index of the model. Final...
flags = (QItemSelectionModel.Clear | QItemSelectionModel.Rows | QItemSelectionModel.Select) self.resultsView.selectionModel().select(index, flags) self.resultsView.resizeColumnsToContents() self.resultsView.setFocus()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updatePlotWidget(self): """Updating the plotting widget should not require any information about the current state of the widget."""
pw = self.getPlotWidget() pw.reset() results = self.resultsModel.getCheckedItems() for result in results: if isinstance(result, ExperimentalData): spectrum = result.spectra['Expt'] spectrum.legend = '{}-{}'.format(result.index, 'Expt') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def row(self): """Return the row of the child."""
if self.parent is not None: children = self.parent.getChildren() # The index method of the list object. return children.index(self) else: return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent(self, index): """Return the index of the parent for a given index of the child. Unfortunately, the name of the method has to be parent, even though a ...
childItem = self.item(index) parentItem = childItem.parent if parentItem == self.rootItem: parentIndex = QModelIndex() else: parentIndex = self.createIndex(parentItem.row(), 0, parentItem) return parentIndex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setData(self, index, value, role): """Set the role data for the item at index to value."""
if not index.isValid(): return False item = self.item(index) column = index.column() if role == Qt.EditRole: items = list() items.append(item) if self.sync: parentIndex = self.parent(index) # Iterate over...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flags(self, index): """Return the active flags for the given index. Add editable flag to items other than the first column. """
activeFlags = (Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable) item = self.item(index) column = index.column() if column > 0 and not item.childCount(): activeFlags = activeFlags | Qt.ItemIsEditable return activeFlags
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getModelData(self, modelData, parentItem=None): """Return the data contained in the model."""
if parentItem is None: parentItem = self.rootItem for item in parentItem.getChildren(): key = item.getItemData(0) if item.childCount(): modelData[key] = odict() self._getModelData(modelData[key], item) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _contextMenu(self, pos): """Handle plot area customContextMenuRequested signal. :param QPoint pos: Mouse position relative to plot area """
# Create the context menu. menu = QMenu(self) menu.addAction(self._zoomBackAction) # Displaying the context menu at the mouse position requires # a global position. # The position received as argument is relative to PlotWidget's # plot area, and thus needs to be...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convolve_fft(array, kernel): """ Convolve an array with a kernel using FFT. Implemntation based on the convolve_fft function from astropy. https://github.com...
array = np.asarray(array, dtype=np.complex) kernel = np.asarray(kernel, dtype=np.complex) if array.ndim != kernel.ndim: raise ValueError("Image and kernel must have same number of " "dimensions") array_shape = array.shape kernel_shape = kernel.shape new_shape...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def diagonalize(self): '''Diagonalize the tensor.''' self.eigvals, self.eigvecs = np.linalg.eig( (self.tensor.transpose() + self.tensor) / 2.0) self.eigvals = np.diag(np.dot( np.dot(self.eigvecs.transpose(), self.tensor), self.eigvecs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _skip_lines(self, n): '''Skip a number of lines from the output.''' for i in range(n): self.line = next(self.output) return self.line
<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_tensor(self, indices=False): '''Parse a tensor.''' if indices: self.line = self._skip_lines(1) tensor = np.zeros((3, 3)) for i in range(3): tokens = self.line.split() if indices: tensor[i][0] = float(tokens[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 __validate(self, target, value, oldvalue, initiator): """ Method executed when the event 'set' is triggered. :param target: Object triggered :param value: Ne...
if value == oldvalue: return value if self.allow_null and value is None: return value if self.check_value(value): return value else: if self.throw_exception: if self.message: self.message = self.messag...
<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_event(self): """ Create an SQLAlchemy event listening the 'set' in a particular column. :rtype : object """
if not event.contains(self.field, 'set', self.__validate): event.listen(self.field, 'set', self.__validate, retval=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 stop(self): """ Remove the listener to stop the validation """
if event.contains(self.field, 'set', self.__validate): event.remove(self.field, 'set', self.__validate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Restart the listener """
if not event.contains(self.field, 'set', self.__validate): self.__create_event()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nhapDaiHan(self, cucSo, gioiTinh): """Nhap dai han Args: cucSo (TYPE): Description gioiTinh (TYPE): Description Returns: TYPE: Description """
for cung in self.thapNhiCung: khoangCach = khoangCachCung(cung.cungSo, self.cungMenh, gioiTinh) cung.daiHan(cucSo + khoangCach * 10) return 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 nt2aa(ntseq): """Translate a nucleotide sequence into an amino acid sequence. Parameters ntseq : str Nucleotide sequence composed of A, C, G, or T (uppercase...
nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3, 'a': 0, 'c': 1, 'g': 2, 't': 3} aa_dict ='KQE*TPASRRG*ILVLNHDYTPASSRGCILVFKQE*TPASRRGWMLVLNHDYTPASSRGCILVF' return ''.join([aa_dict[nt2num[ntseq[i]] + 4*nt2num[ntseq[i+1]] + 16*nt2num[ntseq[i+2]]] for i in range(0, len(ntseq), 3) if i+2 < len(ntseq)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nt2codon_rep(ntseq): """Represent nucleotide sequence by sequence of codon symbols. 'Translates' the nucleotide sequence into a symbolic representation of 'a...
# nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3, 'a': 0, 'c': 1, 'g': 2, 't': 3} #Use single characters not in use to represent each individual codon --- this function is called in constructing the codon dictionary codon_rep ='\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cutR_seq(seq, cutR, max_palindrome): """Cut genomic sequence from the right. Parameters seq : str Nucleotide sequence to be cut from the right cutR : int cut...
complement_dict = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} #can include lower case if wanted if cutR < max_palindrome: seq = seq + ''.join([complement_dict[nt] for nt in seq[cutR - max_palindrome:]][::-1]) #reverse complement palindrome insertions else: seq = seq[:len(seq) - cutR + max_pali...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cutL_seq(seq, cutL, max_palindrome): """Cut genomic sequence from the left. Parameters seq : str Nucleotide sequence to be cut from the right cutL : int cutL...
complement_dict = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} #can include lower case if wanted if cutL < max_palindrome: seq = ''.join([complement_dict[nt] for nt in seq[:max_palindrome - cutL]][::-1]) + seq #reverse complement palindrome insertions else: seq = seq[cutL-max_palindrome:] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_sub_codons_left(codons_dict): """Generate the sub_codons_left dictionary of codon prefixes. Parameters codons_dict : dict Dictionary, keyed by the a...
sub_codons_left = {} for aa in codons_dict.keys(): sub_codons_left[aa] = list(set([x[0] for x in codons_dict[aa]] + [x[:2] for x in codons_dict[aa]])) return sub_codons_left
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_steady_state_dist(R): """Calculate the steady state dist of a 4 state markov transition matrix. Parameters R : ndarray Markov transition matrix Returns ...
#Calc steady state distribution for a dinucleotide bias matrix w, v = np.linalg.eig(R) for i in range(4): if np.abs(w[i] - 1) < 1e-8: return np.real(v[:, i] / np.sum(v[:, i])) 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 rnd_ins_seq(ins_len, C_R, CP_first_nt): """Generate a random insertion nucleotide sequence of length ins_len. Draws the sequence identity (for a set length) ...
nt2num = {'A': 0, 'C': 1, 'G': 2, 'T': 3} num2nt = 'ACGT' if ins_len == 0: return '' seq = num2nt[CP_first_nt.searchsorted(np.random.random())] ins_len += -1 while ins_len > 0: seq += num2nt[C_R[nt2num[seq[-1]], :].searchsorted(np.random.random())] ins_len += -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 update_rates(self): """ Creates or updates rates for a source """
source, created = RateSource.objects.get_or_create(name=self.get_source_name()) source.base_currency = self.get_base_currency() source.save() for currency, value in six.iteritems(self.get_rates()): try: rate = Rate.objects.get(source=source, currency=currenc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def showDosHeaderData(peInstance): """ Prints IMAGE_DOS_HEADER fields. """
dosFields = peInstance.dosHeader.getFields() print "[+] IMAGE_DOS_HEADER values:\n" for field in dosFields: if isinstance(dosFields[field], datatypes.Array): print "--> %s - Array of length %d" % (field, len(dosFields[field])) counter = 0 for element in do...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def showFileHeaderData(peInstance): """ Prints IMAGE_FILE_HEADER fields. """
fileHeaderFields = peInstance.ntHeaders.fileHeader.getFields() print "[+] IMAGE_FILE_HEADER values:\n" for field in fileHeaderFields: print "--> %s = 0x%08x" % (field, fileHeaderFields[field].value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def showOptionalHeaderData(peInstance): """ Prints IMAGE_OPTIONAL_HEADER fields. """
print "[+] IMAGE_OPTIONAL_HEADER:\n" ohFields = peInstance.ntHeaders.optionalHeader.getFields() for field in ohFields: if not isinstance(ohFields[field], datadirs.DataDirectory): print "--> %s = 0x%08x" % (field, ohFields[field].value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def showDataDirectoriesData(peInstance): """ Prints the DATA_DIRECTORY fields. """
print "[+] Data directories:\n" dirs = peInstance.ntHeaders.optionalHeader.dataDirectory counter = 1 for dir in dirs: print "[%d] --> Name: %s -- RVA: 0x%08x -- SIZE: 0x%08x" % (counter, dir.name.value, dir.rva.value, dir.size.value) counter += 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 showSectionsHeaders(peInstance): """ Prints IMAGE_SECTION_HEADER for every section present in the file. """
print "[+] Sections information:\n" print "--> NumberOfSections: %d\n" % peInstance.ntHeaders.fileHeader.numberOfSections.value for section in peInstance.sectionHeaders: fields = section.getFields() for field in fields: if isinstance(fields[field], datatypes.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 showImports(peInstance): """ Shows imports information. """
iidEntries = peInstance.ntHeaders.optionalHeader.dataDirectory[consts.IMPORT_DIRECTORY].info if iidEntries: for iidEntry in iidEntries: fields = iidEntry.getFields() print "module: %s" % iidEntry.metaData.moduleName.value for field in fields: pri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def showExports(peInstance): """ Show exports information """
exports = peInstance.ntHeaders.optionalHeader.dataDirectory[consts.EXPORT_DIRECTORY].info if exports: exp_fields = exports.getFields() for field in exp_fields: print "%s -> %x" % (field, exp_fields[field].value) for entry in exports.exportTable: entry_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFields(self): """ Returns all the class attributues. @rtype: dict @return: A dictionary containing all the class attributes. """
d = {} for i in self._attrsList: key = i value = getattr(self, i) d[key] = value return 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 calc_euler_tour(g, start, end): '''Calculates an Euler tour over the graph g from vertex start to vertex end. Assumes start and end are odd-degree vertices and that there are no other odd-degree vertices.''' even_g = nx.subgraph(g, g.nodes()).copy() if end in even_g.neighbors(start): # I...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def greedy_trails(subg, odds, verbose): '''Greedily select trails by making the longest you can until the end''' if verbose: print('\tCreating edge map') edges = defaultdict(list) for x,y in subg.edges(): edges[x].append(y) edges[y].append(x) if verbose: print('\tS...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decompose_graph(g, heuristic='tour', max_odds=20, verbose=0): '''Decompose a graph into a set of non-overlapping trails.''' # Get the connected subgraphs subgraphs = [nx.subgraph(g, x).copy() for x in nx.connected_components(g)] chains = [] num_subgraphs = len(subgraphs) step = 0 while ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lerp(self, a, t): """ Lerp. Linear interpolation from self to a"""
return self.plus(a.minus(self).times(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 interpolate(self, other, t): """ Create a new vertex between this vertex and `other` by linearly interpolating all properties using a parameter of `t`. Subcl...
return Vertex(self.pos.lerp(other.pos, t), self.normal.lerp(other.normal, 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 splitPolygon(self, polygon, coplanarFront, coplanarBack, front, back): """ Split `polygon` by this plane if needed, then put the polygon or polygon fragments...
COPLANAR = 0 # all the vertices are within EPSILON distance from plane FRONT = 1 # all the vertices are in front of the plane BACK = 2 # all the vertices are at the back of the plane SPANNING = 3 # some vertices are in front, some in the back # Classify each point as well as th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invert(self): """ Convert solid space to empty space and empty space to solid space. """
for poly in self.polygons: poly.flip() self.plane.flip() if self.front: self.front.invert() if self.back: self.back.invert() temp = self.front self.front = self.back self.back = temp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clipPolygons(self, polygons): """ Recursively remove all polygons in `polygons` that are inside this BSP tree. """
if not self.plane: return polygons[:] front = [] back = [] for poly in polygons: self.plane.splitPolygon(poly, front, back, front, back) if self.front: front = self.front.clipPolygons(front) if self.back: back = 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 clipTo(self, bsp): """ Remove all polygons in this BSP tree that are inside the other BSP tree `bsp`. """
self.polygons = bsp.clipPolygons(self.polygons) if self.front: self.front.clipTo(bsp) if self.back: self.back.clipTo(bsp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allPolygons(self): """ Return a list of all polygons in this BSP tree. """
polygons = self.polygons[:] if self.front: polygons.extend(self.front.allPolygons()) if self.back: polygons.extend(self.back.allPolygons()) return polygons
<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_rate(currency): """Returns the rate from the default currency to `currency`."""
source = get_rate_source() try: return Rate.objects.get(source=source, currency=currency).value except Rate.DoesNotExist: raise CurrencyConversionException( "Rate for %s in %s do not exists. " "Please run python manage.py update_rates" % ( currency, 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 get_rate_source(): """Get the default Rate Source and return it."""
backend = money_rates_settings.DEFAULT_BACKEND() try: return RateSource.objects.get(name=backend.get_source_name()) except RateSource.DoesNotExist: raise CurrencyConversionException( "Rate for %s source do not exists. " "Please run python manage.py update_rates" % ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base_convert_money(amount, currency_from, currency_to): """ Convert 'amount' from 'currency_from' to 'currency_to' """
source = get_rate_source() # Get rate for currency_from. if source.base_currency != currency_from: rate_from = get_rate(currency_from) else: # If currency from is the same as base currency its rate is 1. rate_from = Decimal(1) # Get rate for currency_to. rate_to = get_...
<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_money(amount, currency_from, currency_to): """ Convert 'amount' from 'currency_from' to 'currency_to' and return a Money instance of the converted am...
new_amount = base_convert_money(amount, currency_from, currency_to) return moneyed.Money(new_amount, currency_to)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_date(format_string=None, datetime_obj=None): """ Format a datetime object with Java SimpleDateFormat's-like string. If datetime_obj is not given - use...
datetime_obj = datetime_obj or datetime.now() if format_string is None: seconds = int(datetime_obj.strftime("%s")) milliseconds = datetime_obj.microsecond // 1000 return str(seconds * 1000 + milliseconds) else: formatter = SimpleDateFormat(format_string) return forma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allZero(buffer): """ Tries to determine if a buffer is empty. @type buffer: str @param buffer: Buffer to test if it is empty. @rtype: bool @return: C{True} i...
allZero = True for byte in buffer: if byte != "\x00": allZero = False break return allZero
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readAlignedString(self, align = 4): """ Reads an ASCII string aligned to the next align-bytes boundary. @type align: int @param align: (Optional) The value w...
s = self.readString() r = align - len(s) % align while r: s += self.data[self.offset] self.offset += 1 r -= 1 return s.rstrip("\x00")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readAt(self, offset, size): """ Reads as many bytes indicated in the size parameter at the specific offset. @type offset: int @param offset: Offset of the va...
if offset > self.length: if self.log: print "Warning: Trying to read: %d bytes - only %d bytes left" % (nroBytes, self.length - self.offset) offset = self.length - self.offset tmpOff = self.tell() self.setOffset(offset) r = self.read(size) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self, message, channel_name=None, fail_silently=False, options=None): # type: (Text, Optional[str], bool, Optional[SendOptions]) -> None """Send a notif...
if channel_name is None: channels = self.settings["CHANNELS"] else: try: channels = { "__selected__": self.settings["CHANNELS"][channel_name] } except KeyError: raise Exception("channels does not exi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, method, path, params=None, headers=None, cookies=None, data=None, json=None, allow_redirects=None, timeout=None): """ Prepares and sends an HTT...
headers = headers or {} timeout = timeout if timeout is not None else self._timeout allow_redirects = allow_redirects if allow_redirects is not None else self._allow_redirects if self._keep_alive and self.__session is None: self.__session = requests.Session() if se...
<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_genomic_CDR3_anchor_pos_and_functionality(anchor_pos_file_name): """Read anchor position and functionality from file. Parameters anchor_pos_file_name : ...
anchor_pos_and_functionality = {} anchor_pos_file = open(anchor_pos_file_name, 'r') first_line = True for line in anchor_pos_file: if first_line: first_line = False continue split_line = line.split(',') split_line = [x.strip() for x in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_cutV_genomic_CDR3_segs(self): """Add palindromic inserted nucleotides to germline V sequences. The maximum number of palindromic insertions are appe...
max_palindrome = self.max_delV_palindrome self.cutV_genomic_CDR3_segs = [] for CDR3_V_seg in [x[1] for x in self.genV]: if len(CDR3_V_seg) < max_palindrome: self.cutV_genomic_CDR3_segs += [cutR_seq(CDR3_V_seg, 0, len(CDR3_V_seg))] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_cutJ_genomic_CDR3_segs(self): """Add palindromic inserted nucleotides to germline J sequences. The maximum number of palindromic insertions are appe...
max_palindrome = self.max_delJ_palindrome self.cutJ_genomic_CDR3_segs = [] for CDR3_J_seg in [x[1] for x in self.genJ]: if len(CDR3_J_seg) < max_palindrome: self.cutJ_genomic_CDR3_segs += [cutL_seq(CDR3_J_seg, 0, len(CDR3_J_seg))] else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_cutD_genomic_CDR3_segs(self): """Add palindromic inserted nucleotides to germline V sequences. The maximum number of palindromic insertions are appe...
max_palindrome_L = self.max_delDl_palindrome max_palindrome_R = self.max_delDr_palindrome self.cutD_genomic_CDR3_segs = [] for CDR3_D_seg in [x[1] for x in self.genD]: if len(CDR3_D_seg) < min(max_palindrome_L, max_palindrome_R): self.cutD_genomic_CDR3_segs ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def verify_and_fill_address_paths_from_bip32key(address_paths, master_key, network): ''' Take address paths and verifies their accuracy client-side. Also fills in all the available metadata (WIF, public key, etc) ''' assert network, network wallet_obj = Wallet.deserialize(master_key, network=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self, lam, initial_values=None): '''Run the graph-fused logit lasso with a fixed lambda penalty.''' if initial_values is not None: if self.k == 0 and self.trails is not None: betas, zs, us = initial_values else: betas, us = initial_values ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def data_log_likelihood(self, successes, trials, beta): '''Calculates the log-likelihood of a Polya tree bin given the beta values.''' return binom.logpmf(successes, trials, 1.0 / (1 + np.exp(-beta))).sum()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn_worker(params): """ This method has to be module level function :type params: Params """
setup_logging(params) log.info("Adding worker: idx=%s\tconcurrency=%s\tresults=%s", params.worker_index, params.concurrency, params.report) worker = Worker(params) worker.start() worker.join()
<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_plateaus(data, edges, plateau_size, plateau_vals, plateaus=None): '''Creates plateaus of constant value in the data.''' nodes = set(edges.keys()) if plateaus is None: plateaus = [] for i in range(len(plateau_vals)): if len(nodes) == 0: break ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pretty_str(p, decimal_places=2, print_zero=True, label_columns=False): '''Pretty-print a matrix or vector.''' if len(p.shape) == 1: return vector_str(p, decimal_places, print_zero) if len(p.shape) == 2: return matrix_str(p, decimal_places, print_zero, label_columns) raise Exception('...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def matrix_str(p, decimal_places=2, print_zero=True, label_columns=False): '''Pretty-print the matrix.''' return '[{0}]'.format("\n ".join([(str(i) if label_columns else '') + vector_str(a, decimal_places, print_zero) for i, a in enumerate(p)]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def vector_str(p, decimal_places=2, print_zero=True): '''Pretty-print the vector values.''' style = '{0:.' + str(decimal_places) + 'f}' return '[{0}]'.format(", ".join([' ' if not print_zero and a == 0 else style.format(a) for a in p]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nearly_unique(arr, rel_tol=1e-4, verbose=0): '''Heuristic method to return the uniques within some precision in a numpy array''' results = np.array([arr[0]]) for x in arr: if np.abs(results - x).min() > rel_tol: results = np.append(results, x) return 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_delta(D, k): '''Calculate the k-th order trend filtering matrix given the oriented edge incidence matrix and the value of k.''' if k < 0: raise Exception('k must be at least 0th order.') result = D for i in range(k): result = D.T.dot(result) if i % 2 == 0 else D.dot(result) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def decompose_delta(deltak): '''Decomposes the k-th order trend filtering matrix into a c-compatible set of arrays.''' if not isspmatrix_coo(deltak): deltak = coo_matrix(deltak) dk_rows = deltak.shape[0] dk_rowbreaks = np.cumsum(deltak.getnnz(1), dtype="int32") dk_cols = deltak.col.astyp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hasMZSignature(self, rd): """ Check for MZ signature. @type rd: L{ReadData} @param rd: A L{ReadData} object. @rtype: bool @return: True is the given L{ReadDa...
rd.setOffset(0) sign = rd.read(2) if sign == "MZ": return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hasPESignature(self, rd): """ Check for PE signature. @type rd: L{ReadData} @param rd: A L{ReadData} object. @rtype: bool @return: True is the given L{ReadDa...
rd.setOffset(0) e_lfanew_offset = unpack("<L", rd.readAt(0x3c, 4))[0] sign = rd.readAt(e_lfanew_offset, 2) if sign == "PE": return True return False
<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): """ Performs validations over some fields of the PE structure to determine if the loaded file has a valid PE format. @raise PEException: If a...
# Ange Albertini (@angie4771) can kill me for this! :) if self.dosHeader.e_magic.value != consts.MZ_SIGNATURE: raise excep.PEException("Invalid MZ signature. Found %d instead of %d." % (self.dosHeader.magic.value, consts.MZ_SIGNATURE)) if self.dosHeader.e_lfanew.value > len...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def readFile(self, pathToFile): """ Returns data from a file. @type pathToFile: str @param pathToFile: Path to the file. @rtype: str @return: The data from file....
fd = open(pathToFile, "rb") data = fd.read() fd.close() return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getPaddingDataToSectionOffset(self): """ Returns the data between the last section header and the begenning of data from the first section. @rtype: str @ret...
start = self._getPaddingToSectionOffset() end = self.sectionHeaders[0].pointerToRawData.value - start return self._data[start:start+end]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getSignature(self, readDataInstance, dataDirectoryInstance): """ Returns the digital signature within a digital signed PE file. @type readDataInstance: L{Re...
signature = "" if readDataInstance is not None and dataDirectoryInstance is not None: securityDirectory = dataDirectoryInstance[consts.SECURITY_DIRECTORY] if(securityDirectory.rva.value and securityDirectory.size.value): readDataInstance.set...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getOverlay(self, readDataInstance, sectionHdrsInstance): """ Returns the overlay data from the PE file. @type readDataInstance: L{ReadData} @param readDataI...
if readDataInstance is not None and sectionHdrsInstance is not None: # adjust the offset in readDataInstance to the RawOffset + RawSize of the last section try: offset = sectionHdrsInstance[-1].pointerToRawData.value + sectionHdrsInstance[-1].sizeOfRawData.va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getOffsetFromRva(self, rva): """ Converts an offset to an RVA. @type rva: int @param rva: The RVA to be converted. @rtype: int @return: An integer value repr...
offset = -1 s = self.getSectionByRva(rva) if s != offset: offset = (rva - self.sectionHeaders[s].virtualAddress.value) + self.sectionHeaders[s].pointerToRawData.value else: offset = rva return offset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getRvaFromOffset(self, offset): """ Converts a RVA to an offset. @type offset: int @param offset: The offset value to be converted to RVA. @rtype: int @retur...
rva = -1 s = self.getSectionByOffset(offset) if s: rva = (offset - self.sectionHeaders[s].pointerToRawData.value) + self.sectionHeaders[s].virtualAddress.value return rva
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getSectionByOffset(self, offset): """ Given an offset in the file, tries to determine the section this offset belong to. @type offset: int @param offset: Off...
index = -1 for i in range(len(self.sectionHeaders)): if (offset < self.sectionHeaders[i].pointerToRawData.value + self.sectionHeaders[i].sizeOfRawData.value): index = i break return 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 getSectionIndexByName(self, name): """ Given a string representing a section name, tries to find the section index. @type name: str @param name: A section na...
index = -1 if name: for i in range(len(self.sectionHeaders)): if self.sectionHeaders[i].name.value.find(name) >= 0: index = i break return 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 getSectionByRva(self, rva): """ Given a RVA in the file, tries to determine the section this RVA belongs to. @type rva: int @param rva: RVA value. @rtype: in...
index = -1 if rva < self.sectionHeaders[0].virtualAddress.value: return index for i in range(len(self.sectionHeaders)): fa = self.ntHeaders.optionalHeader.fileAlignment.value prd = self.sectionHeaders[i].pointerToRawData.value sr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getPaddingToSectionOffset(self): """ Returns the offset to last section header present in the PE file. @rtype: int @return: The offset where the end of the ...
return len(str(self.dosHeader) + str(self.dosStub) + str(self.ntHeaders) + str(self.sectionHeaders))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fullLoad(self): """Parse all the directories in the PE file."""
self._parseDirectories(self.ntHeaders.optionalHeader.dataDirectory, self.PE_TYPE)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fixPe(self): """ Fixes the necessary fields in the PE file instance in order to create a valid PE32. i.e. SizeOfImage. """
sizeOfImage = 0 for sh in self.sectionHeaders: sizeOfImage += sh.misc self.ntHeaders.optionaHeader.sizeoOfImage.value = self._sectionAlignment(sizeOfImage + 0x1000)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDataAtRva(self, rva, size): """ Gets binary data at a given RVA. @type rva: int @param rva: The RVA to get the data from. @type size: int @param size: The...
return self.getDataAtOffset(self.getOffsetFromRva(rva), size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDataAtOffset(self, offset, size): """ Gets binary data at a given offset. @type offset: int @param offset: The offset to get the data from. @type size: in...
data = str(self) return data[offset:offset+size]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseDelayImportDirectory(self, rva, size, magic = consts.PE32): """ Parses the delay imports directory. @type rva: int @param rva: The RVA where the delay ...
return self.getDataAtRva(rva, size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseBoundImportDirectory(self, rva, size, magic = consts.PE32): """ Parses the bound import directory. @type rva: int @param rva: The RVA where the bound i...
data = self.getDataAtRva(rva, size) rd = utils.ReadData(data) boundImportDirectory = directories.ImageBoundImportDescriptor.parse(rd) # parse the name of every bounded import. for i in range(len(boundImportDirectory) - 1): if hasattr(boundImportDirectory[i],...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseLoadConfigDirectory(self, rva, size, magic = consts.PE32): """ Parses IMAGE_LOAD_CONFIG_DIRECTORY. @type rva: int @param rva: The RVA where the IMAGE_L...
# print "RVA: %x - SIZE: %x" % (rva, size) # I've found some issues when parsing the IMAGE_LOAD_CONFIG_DIRECTORY in some DLLs. # There is an inconsistency with the size of the struct between MSDN docs and VS. # sizeof(IMAGE_LOAD_CONFIG_DIRECTORY) should be 0x40, in fact, that's the si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseTlsDirectory(self, rva, size, magic = consts.PE32): """ Parses the TLS directory. @type rva: int @param rva: The RVA where the TLS directory starts. @t...
data = self.getDataAtRva(rva, size) rd = utils.ReadData(data) if magic == consts.PE32: return directories.TLSDirectory.parse(rd) elif magic == consts.PE64: return directories.TLSDirectory64.parse(rd) else: raise excep.InvalidParameter...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseRelocsDirectory(self, rva, size, magic = consts.PE32): """ Parses the relocation directory. @type rva: int @param rva: The RVA where the relocation dir...
data = self.getDataAtRva(rva, size) #print "Length Relocation data: %x" % len(data) rd = utils.ReadData(data) relocsArray = directories.ImageBaseRelocation() while rd.offset < size: relocEntry = directories.ImageBaseRelocationEntry.parse(rd) rel...
<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_addresses_on_both_chains(wallet_obj, used=None, zero_balance=None): ''' Get addresses across both subchains based on the filter criteria passed in Returns a list of dicts of the following form: [ {'address': '1abc123...', 'path': 'm/0/9', 'pubkeyhex': '0123456...'}, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dump_all_keys_or_addrs(wallet_obj): ''' Offline-enabled mechanism to dump addresses ''' print_traversal_warning() puts('\nDo you understand this warning?') if not confirm(user_prompt=DEFAULT_PROMPT, default=False): puts(colored.red('Dump Cancelled!')) return mpub = wal...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dump_selected_keys_or_addrs(wallet_obj, used=None, zero_balance=None): ''' Works for both public key only or private key access ''' if wallet_obj.private_key: content_str = 'private keys' else: content_str = 'addresses' if not USER_ONLINE: puts(colored.red('\nInterne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dump_private_keys_or_addrs_chooser(wallet_obj): ''' Offline-enabled mechanism to dump everything ''' if wallet_obj.private_key: puts('Which private keys and addresses do you want?') else: puts('Which addresses do you want?') with indent(2): puts(colored.cyan('1: Acti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_merge_commands(self, config, file_config): """ Netmiko is being used to push set commands. """
if self.loaded is False: if self._save_backup() is False: raise MergeConfigException('Error while storing backup ' 'config.') if self.ssh_connection is False: self._open_ssh() if file_config: if isin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_config(self): """ Netmiko is being used to obtain config diffs because pan-python doesn't support the needed command. """
if self.ssh_connection is False: self._open_ssh() self.ssh_device.exit_config_mode() diff = self.ssh_device.send_command("show config diff") return diff.strip()