language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void search() throws IOException { String url = String.format(SEARCH_URL, term, (weightClass != null) ? weightClass.getValue() : "", page ); dryEvents = new ArrayList<>(); dryFighters = new ArrayList<>(); List<SherdogBase...
python
def skip(instance, action, peek=False, unskip=False): """Returns True if the transition is to be SKIPPED peek - True just checks the value, does not set. unskip - remove skip key (for manual overrides). called with only (instance, action_id), this will set the request variable preventing the ...
python
def add_arguments(parser): '''Add command-line arguments for yakonfig proper. This is part of the :class:`~yakonfig.Configurable` interface, and is usually run by including :mod:`yakonfig` in the :func:`parse_args()` module list. :param argparse.ArgumentParser parser: command-line argument p...
java
private void set(String name, String location) { if (name != null && name.contains(PATH_SEPARATOR_STR)) throw new IllegalArgumentException( "Network location name contains /: "+name); this.name = (name==null)?"":name; this.location = location; }
java
public boolean repeatsMonthlyOnDayCount() { if (this.freq != MONTHLY) { return false; } if (bydayCount != 1 || bymonthdayCount != 0) { return false; } if (bydayNum[0] <= 0) { return false; } return true; }
java
public static InsnList merge(Object... insns) { Validate.notNull(insns); Validate.noNullElements(insns); InsnList ret = new InsnList(); for (Object insn : insns) { if (insn instanceof AbstractInsnNode) { // add single instruction AbstractInsnN...
java
public String getWorkspaceKey() { if (workspaceKey == null) { // Value is idempotent, so it's okay to do this without synchronizing ... workspaceKey = key.substring(WORKSPACE_START_INDEX, WORKSPACE_END_INDEX); } return workspaceKey; }
python
def widget(self, which_viz='viz'): ''' Generate a widget visualization using the widget. The export_viz_to_widget method passes the visualization JSON to the instantiated widget, which is returned and visualized on the front-end. ''' if hasattr(self, 'widget_class') == True: # run cluster...
python
def debug(ftn, txt): """Used for debugging.""" if debug_p: sys.stdout.write("{0}.{1}:{2}\n".format(modname, ftn, txt)) sys.stdout.flush()
java
public void setTextFontFamilyName(byte[] fields, String[] fontFamilies) { if (fontFamilies == null) fontFamilies = new String[0]; for (byte field : fields) { getFieldInfos(field).m_fontFamilyNames = fontFamilies; } notifyListeners(); }
python
def gpio_get(self, pins=None): """Returns a list of states for the given pins. Defaults to the first four pins if an argument is not given. Args: self (JLink): the ``JLink`` instance pins (list): indices of the GPIO pins whose states are requested Returns: ...
java
public Iterable<String> listStashTableNames() throws StashNotAvailableException { return Iterables.transform(listStashTables(), new Function<StashTable, String>() { @Override public String apply(StashTable stashTable) { return stashTable.getTableName(); ...
python
def delete_rpms(self, repo_name, rpms, env): """ `repo_name` - Name of the repository rpms live in (includes -env) `rpms` - A list of rpm filenames to delete `env` - Environment we're currently deleting in Delete rpms from a repository in specified environments """ ...
java
public static HebrewCalendar of( int year, HebrewMonth month, int dom ) { int m = month.getValue(); if (!CALSYS.isValid(HebrewEra.ANNO_MUNDI, year, m, dom)) { throw new IllegalArgumentException( "Invalid Hebrew date: year=" + year + ", month=" + ...
java
public WarProbeOption overlay(String overlayPath) { overlays.add(new File(overlayPath).toURI().toString()); return this; }
python
def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol)
python
def dirint(ghi, solar_zenith, times, pressure=101325., use_delta_kt_prime=True, temp_dew=None, min_cos_zenith=0.065, max_zenith=87): """ Determine DNI from GHI using the DIRINT modification of the DISC model. Implements the modified DISC model known as "DIRINT" introduced in [1]. DIRINT ...
python
def _cache(cpath, arg): ''' IMap._cache(cpath, arg) is an internally-called method that saves the dict of arguments to cache files in the given cpath directory. ''' if not os.path.isdir(cpath): os.makedirs(cpath) for (k,v) in six.iteritems(arg): save(os.path...
java
private void fatal(String message, char textFound, String textExpected) throws SAXException { fatal(message, Character.valueOf(textFound).toString(), textExpected); }
java
void collectRangeVariables(RangeVariable[] rangeVariables, Set set) { for (int i = 0; i < nodes.length; i++) { if (nodes[i] != null) { nodes[i].collectRangeVariables(rangeVariables, set); } } if (subQuery != null && subQuery.queryExpression != null) { ...
java
public static ApkMeta getMetaInfo(byte[] apkData, Locale locale) throws IOException { try (ByteArrayApkFile apkFile = new ByteArrayApkFile(apkData)) { apkFile.setPreferredLocale(locale); return apkFile.getApkMeta(); } }
java
@SuppressWarnings("unchecked") @Override public EList<IfcTypeObject> getDefinesType() { return (EList<IfcTypeObject>) eGet(Ifc4Package.Literals.IFC_PROPERTY_SET_DEFINITION__DEFINES_TYPE, true); }
java
public boolean visitTree(VisitContext context, VisitCallback callback) { // First check to see whether we are visitable. If not // short-circuit out of this subtree, though allow the // visit to proceed through to other subtrees. if (!isVisitable(context))...
java
public final byte[] decompress(byte[] src, int srcOff, int srcLen, int maxDestLen) { byte[] decompressed = new byte[maxDestLen]; final int decompressedLength = decompress(src, srcOff, srcLen, decompressed, 0, maxDestLen); if (decompressedLength != decompressed.length) { decompressed = Arrays.copyOf(de...
java
public static <T extends ImageGray<T>> void orderBandsIntoRGB(Planar<T> image , BufferedImage input ) { boolean swap = swapBandOrder(input); // Output formats are: RGB and RGBA if( swap ) { if( image.getNumBands() == 3 ) { int bufferedImageType = input.getType(); if( bufferedImageType == BufferedIm...
java
public static boolean equal(Object obj1, Object obj2) { if (obj1 == obj2) { return true; } if (obj1 == null || obj2 == null) { return false; } if (obj1.getClass().isArray()) { return equalsArray(obj1, obj2); } // this does not h...
python
def send_keys(self, keys): """Send keys to the device.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(self._timeout) sock.connect((self._ip, self._port['cmd'])) # mandatory dance version_info = sock.recv(15) ...
python
def flush(name, family='ipv4', **kwargs): ''' .. versionadded:: 2014.7.0 Flush current nftables state family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} for ignore in _STATE_INTERNA...
python
def __parse_aliases_stream(self, stream): """Parse aliases stream. The stream contains a list of usernames (they can be email addresses their username aliases. Each line has a username and an alias separated by tabs. Comment lines start with the hash character (#). Example: ...
java
private boolean isValid(final String fileType) { boolean result = false; if (fileType != null && fileType.length() > 1) { // the shortest I can think of would be something like ".h" if (fileType.startsWith(".")) { // assume it's a file extension result = true; } else if (fileType.length() > 2 && fileType....
python
def time_correlation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None): """ calculates time correlation. Raises P to power 'times' by diagonalization. If rdl tuple (R, D, L) is given, it will be used for further calculation. """ if rdl is None: raise ValueError("no rdl decompo...
java
@Override public Object get(String propName) { if (propName.equals("mappedProperties")) { return getMappedProperties(); } return super.get(propName); }
python
def DFS(G): """ Algorithm for depth-first searching the vertices of a graph. """ if not G.vertices: raise GraphInsertError("This graph have no vertices.") color = {} pred = {} reach = {} finish = {} def DFSvisit(G, current, time): color[current] = 'grey' ...
java
public final EObject entryRuleInternalRichString() throws RecognitionException { EObject current = null; EObject iv_ruleInternalRichString = null; try { // InternalSARL.g:11032:59: (iv_ruleInternalRichString= ruleInternalRichString EOF ) // InternalSARL.g:11033:2: iv_r...
python
def _is_reference(bpe): """Return True if the element is an entity reference.""" if isinstance(bpe, _bp('ProteinReference')) or \ isinstance(bpe, _bpimpl('ProteinReference')) or \ isinstance(bpe, _bp('SmallMoleculeReference')) or \ isinstance(bpe, _bpimpl('SmallMoleculeReference')) or \ ...
python
def best_training_job(self): """Return name of the best training job for the latest hyperparameter tuning job. Raises: Exception: If there is no best training job available for the hyperparameter tuning job. """ self._ensure_last_tuning_job() tuning_job_describe_res...
python
def read_aims(filename): """Method to read FHI-aims geometry files in phonopy context.""" lines = open(filename, 'r').readlines() cell = [] is_frac = [] positions = [] symbols = [] magmoms = [] for line in lines: fields = line.split() if not len(fields): con...
python
def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]], gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]: """ Takes a predicted answer and a gold answer (that are both either a string or a list of strings), and returns exact match and the DROP F1 metric for the...
python
async def set_builtin_type_codec(self, typename, *, schema='public', codec_name, format=None): """Set a builtin codec for the specified scalar data type. This method has two uses. The first is to register a builtin codec...
python
def with_slots(cls): """ Decorator for a class with _slots_. It automatically defines the methods __eq__, __ne__, assert_equal. """ def _compare(self, other): for slot in self.__class__._slots_: attr = operator.attrgetter(slot) source = attr(self) target =...
python
def matches_sample(output, target, threshold, is_correct, actual_output): """ Check if a sample with the given network output, target output, and threshold is the classification (is_correct, actual_output) like true positive or false negative """ return (bool(output > threshold) ...
java
@Override public AssociateHostedConnectionResult associateHostedConnection(AssociateHostedConnectionRequest request) { request = beforeClientExecution(request); return executeAssociateHostedConnection(request); }
java
public static BufferedImage loadPGM( InputStream inputStream , BufferedImage storage ) throws IOException { DataInputStream in = new DataInputStream(inputStream); readLine(in); String line = readLine(in); while( line.charAt(0) == '#') line = readLine(in); String s[] = line.split(" "); int w = Integer.pa...
java
public GeoMultiPoint addPoint(GeoPoint point) { Contracts.assertNotNull( point, "point" ); this.points.add( point ); return this; }
python
def read_tsv(cls, filepath_or_buffer: str, gene_table: ExpGeneTable = None, encoding='UTF-8'): """Read expression profile from a tab-delimited text file. Parameters ---------- path: str The path of the text file. gene_table: `ExpGeneTable` object, op...
python
def GrantApproval(self, requestor_username, approval_id, grantor_username): """Grants approval for a given request using given username.""" try: approval = self.approvals_by_username[requestor_username][approval_id] approval.grants.append( rdf_objects.ApprovalGrant( grantor_u...
python
def __write(self, thePath, theData): """ Write data to a file. @type thePath: str @param thePath: The file path. @type theData: str @param theData: The data to write. """ fd = open(thePath, "wb") fd.write(theData) fd.c...
python
def _spoken_representation_L2(lst_lst_char): """ >>> lst = [['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']] >>> _spoken_representation_L2(lst) '-- --- .-. ... . (space) -.-. --- -.. .' """ s = '' inter_char = ' ' inter_word = ' (space) ' for i, word in enumerate(lst_lst_char): ...
python
def close(self): """shut down the pool's workers this method sets the :attr:`closing` attribute, lines up the :attr:`closed` attribute to be set once any queued data has been processed, and raises a PoolClosed() exception in any coroutines still blocked on :meth:`get`. "...
python
def vector(p1, p2): """Vector from p1 to p2. :param p1: coordinates of point p1 :param p2: coordinates of point p2 :returns : numpy array with vector coordinates """ return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in range(len(p1))])
java
public boolean deleteDefaultBucketAcl(String bucketName) { // [START deleteDefaultBucketAcl] boolean deleted = storage.deleteDefaultAcl(bucketName, User.ofAllAuthenticatedUsers()); if (deleted) { // the acl entry was deleted } else { // the acl entry was not found } // [END deleteDef...
python
def _print_table_ontologies(): """ list all local files 2015-10-18: removed 'cached' from report 2016-06-17: made a subroutine of action_listlocal() """ ontologies = get_localontologies() ONTOSPY_LOCAL_MODELS = get_home_location() if ontologies: print("") temp...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.BPT__PTDO_NAME: setPTdoName(PTDO_NAME_EDEFAULT); return; case AfplibPackage.BPT__TRIPLETS: getTriplets().clear(); return; } super.eUnset(featureID); }
java
public static <T extends Event> HandlerRegistration bind(EventTarget target, EventType<T, ?> type, EventCallbackFn<T> listener) { return bind(target, type.name, e -> listener.onEvent(Js.cast(e))); }
python
def mod_aggregate(low, chunks, running): ''' The mod_aggregate function which looks up all rules in the available low chunks and merges them into a single rules ref in the present low data ''' rules = [] agg_enabled = [ 'append', 'insert', ] if low.get('fun') not ...
java
public static InsnList combineObjectArrays(Variable destArrayVar, Variable firstArrayVar, Variable secondArrayVar) { Validate.notNull(destArrayVar); Validate.notNull(firstArrayVar); Validate.notNull(secondArrayVar); Validate.isTrue(destArrayVar.getType().equals(Type.getType(Object[].clas...
python
def type(self): """Returns 'number', 'string', 'date' or 'unknown' based on the type of the value""" if isinstance(self.value, numbers.Number): return "number" if isinstance(self.value, basestring): return "string" return "unknown"
python
def dannotsagg2dannots2dalignbedannot(cfg): """ Map aggregated annotations to queries step#9 :param cfg: configuration dict """ datatmpd=cfg['datatmpd'] dannotsagg=del_Unnamed(pd.read_csv(cfg['dannotsaggp'],sep='\t')) dalignbedstats=del_Unnamed(pd.read_csv(cfg['dalignbedstatsp'],se...
java
public static lbmonitor[] get(nitro_service service) throws Exception{ lbmonitor obj = new lbmonitor(); lbmonitor[] response = (lbmonitor[])obj.get_resources(service); return response; }
java
@Override public ExternalEventAggregationConfiguration exportData(String id) { final ExternalEventAggregationConfiguration externalData = new ExternalEventAggregationConfiguration(); // Copy interval configs final List<ExternalAggregatedIntervalConfig> aggregatedIntervalConf...
java
public Observable<NetworkSecurityGroupInner> updateTagsAsync(String resourceGroupName, String networkSecurityGroupName, Map<String, String> tags) { return updateTagsWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, tags).map(new Func1<ServiceResponse<NetworkSecurityGroupInner>, NetworkSecuri...
python
def _times(t0, hours): """ Return a (list of) datetime(s) given an initial time and an (list of) hourly offset(s). Arguments: t0 -- initial time hours -- hourly offsets from t0 """ if not isinstance(hours, Iterable): return Tide._times(t0, [hours])[0] elif not isinstance(hours[0], datetime): retur...
java
private Node insertEndpointBefore(Node camel) { // if there is endpoints then the cut-off is after the last Node endpoint = null; for (int i = 0; i < camel.getChildNodes().getLength(); i++) { Node found = camel.getChildNodes().item(i); String name = found.getNodeName(); ...
java
public MBlockPos offset(EnumFacing facing, int n) { return new MBlockPos( this.getX() + facing.getFrontOffsetX() * n, this.getY() + facing.getFrontOffsetY() * n, this.getZ() + facing.getFrontOffsetZ() * n); }
java
@SuppressWarnings("all") public void retain() { if (allocationDebugging) { AllocationDebugger.getInstance().retain(this); } final int baseCount = refcount.getAndIncrement(); if (allocationDebugging && baseCount < 1) { throw new RuntimeException("attempt...
python
def _to_inline_css(self, style): """ Return inline CSS from CSS key / values """ return "; ".join(['{}: {}'.format(convert_style_key(k), v) for k, v in style.items()])
java
@Override public final AbstractGauge init(final int WIDTH, final int HEIGHT) { if (WIDTH <= 1 || HEIGHT <= 1) { return this; } if (isLcdVisible()) { if (isDigitalFont()) { setLcdValueFont(getModel().getDigitalBaseFont().deriveFont(0.7f * WIDTH * 0.15f)...
python
def _linux_brshow(br=None): ''' Internal, returns bridges and enslaved interfaces (GNU/Linux - brctl) ''' brctl = _tool_path('brctl') if br: cmd = '{0} show {1}'.format(brctl, br) else: cmd = '{0} show'.format(brctl) brs = {} for line in __salt__['cmd.run'](cmd, python...
java
public void resolveHRefs(URI uri) { if (mLocation != null && !mLocation.isAbsolute()) { mLocation = uri.resolve(mLocation); } List<URI> hrefs = mHrefs; for (int i = 0, count = hrefs.size(); i < count; ++i) { URI href = hrefs.get(i); if (!href.isAbsolute()) { hrefs.set(i, uri.resolve(href))...
java
public int getNameAndTypeIndex(String name, String descriptor) { for (ConstantInfo ci : listConstantInfo(NameAndType.class)) { NameAndType nat = (NameAndType) ci; int nameIndex = nat.getName_index(); String str = getString(nameIndex); if (name.equals(s...
python
def download(name, course, github='SheffieldML/notebook/master/lab_classes/'): """Download a lab class from the relevant course :param course: the course short name to download the class from. :type course: string :param reference: reference to the course for downloading the class. :type reference: ...
python
def createUsageReport(self, reportname, queries, metadata, since="LAST_DAY", fromValue=None, toValue=None, aggregationInterval=None ...
python
def offsets(self, group=None): """Get internal consumer offset values Keyword Arguments: group: Either "fetch", "commit", "task_done", or "highwater". If no group specified, returns all groups. Returns: A copy of internal offsets struct """ ...
java
public Observable<ComapiResult<ConversationDetails>> getConversation(@NonNull final String conversationId) { final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueGetConversation(conversationId); } else if (TextUtils.isEmpty(token)...
java
public Observable<OperationStatusResponseInner> beginDeallocateAsync(String resourceGroupName, String vmScaleSetName) { return beginDeallocateWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Ov...
java
boolean needToCheckExclude() { if (null == m_excludeResultPrefixes && null == getPrefixTable() && m_ExtensionElementURIs==null // JJK Bugzilla 1133 ) return false; else { // Create a new prefix table if one has not already been created. if (null == ge...
python
def setCredentialValues(self, username=None, password=None, public_key=None, private_key=None, new=False): """Set the values in disk.0.os.credentials.*.""" credentials_base = "disk.0.os.credentials." if new: credentials_base = "disk.0.os.credentials.new." if username: ...
java
static ConnectionSpec convertSpec(com.squareup.okhttp.ConnectionSpec spec) { Preconditions.checkArgument(spec.isTls(), "plaintext ConnectionSpec is not accepted"); List<com.squareup.okhttp.TlsVersion> tlsVersionList = spec.tlsVersions(); String[] tlsVersions = new String[tlsVersionList.size()]; for (in...
python
def loadFile(self, fileName: str=None): """ Overload this method with applet specific code that can make sense of the passed ``fileName`` argument. In many case this will literally mean a file name, but could equally well be a URL (eg. ``QWebView`` based applets) or any other res...
java
public Pager<DeployKey> getProjectDeployKeys(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException { return (new Pager<DeployKey>(this, DeployKey.class, itemsPerPage, null, "projects", getProjectIdOrPath(projectIdOrPath), "deploy_keys")); }
java
public void rollbackSetRollbackAndThrowException(List objects) { log.info("rollbackSetRollbackAndThrowException method was called"); storeObjects(objects); getSessionContext().setRollbackOnly(); // to notify the client about the failure we throw an exception // if we do...
python
def prepare_url(hostname, path, params=None): """ Prepare Elasticsearch request url. :param hostname: host name :param path: request path :param params: optional url params :return: """ url = hostname + path if params: url = url + '?' ...
python
def proj4_to_epsg(projection): """Attempts to convert a PROJ4 projection object to an EPSG code and returns None if conversion fails""" def make_definition(value): return {x.strip().lower() for x in value.split('+') if x} # Use the EPSG in the definition if available match = EPSG_RE.search(pro...
java
public void setMode(double newMode) { double oldMode = mode; mode = newMode; boolean oldModeESet = modeESet; modeESet = true; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.TRIANGULAR_DISTRIBUTION_TYPE__MODE, oldMode, mode, !oldModeESet)); }
python
def authenticate(realm, authid, details): """ application_name : name of your application version : version of your application required_components dictionary of components required for you application and their version required { "component" : "1.1", "component2" : "0...
python
def get_power(self): """Get current power.""" self.get_status() try: self.consumption = self.data['power'] except TypeError: self.consumption = 0 return self.consumption
python
def get_readout_time(self, child, duration): """Calculate the readout time of the detector from the EPICS driver: - Set exposure and acquire period to same value - Acquire period will be set to lowest acceptable value - Difference will be readout time (this value is affected ...
java
@Override public void close(FutureCallback<Void> callback) throws IllegalStateException { assertOpen(); Future<?> future = this.eventGroup.shutdownGracefully(0L, 5L, TimeUnit.SECONDS); future.addListener(new NetworkManagerVoidFutureCallback(callback)); }
java
public static RequestedAttribute CURRENT_FAMILY_NAME(Boolean isRequired, boolean includeFriendlyName) { return create(AttributeConstants.EIDAS_CURRENT_FAMILY_NAME_ATTRIBUTE_NAME, includeFriendlyName ? AttributeConstants.EIDAS_CURRENT_FAMILY_NAME_ATTRIBUTE_FRIENDLY_NAME : null, Attribute.URI_REFERENCE, i...
python
def update(self, initiation_actions=values.unset): """ Update the AssistantInitiationActionsInstance :param dict initiation_actions: The initiation_actions :returns: Updated AssistantInitiationActionsInstance :rtype: twilio.rest.preview.understand.assistant.assistant_initiation...
python
def add_user_action_sets(self, _type, name, description, version='v1.0'): """ 创建数据源 https://wximg.qq.com/wxp/pdftool/get.html?id=rkalQXDBM&pa=39 :param _type: 用户行为源类型 :param name: 用户行为源名称 必填 :param description: 用户行为源描述,字段长度最小 1 字节,长度最大 128 字节 :param version: 版本号 ...
java
protected ClassMapping writeClassMapping (Class<?> sclass) throws IOException { // create our classmap if necessary if (_classmap == null) { _classmap = Maps.newHashMap(); } // look up the class mapping record ClassMapping cmap = _classmap.get(sclass); ...
python
def subgroup(self, t, i): """Handle parenthesis.""" current = [] # (?flags) flags = self.get_flags(i) if flags: self.flags(flags[2:-1]) return [flags] # (?#comment) comments = self.get_comments(i) if comments: return ...
java
public List<String> documentIds() { List<String> documentIds = new ArrayList<String>(); List<DocumentRevision> docs = CollectionUtils.newArrayList(iterator()); for (DocumentRevision doc : docs) { documentIds.add(doc.getId()); } return documentIds; }
java
public Matrix subtract(Matrix B) { Matrix toReturn = getThisSideMatrix(B); toReturn.mutableSubtract(1.0, B); return toReturn; }
java
public void setQueryTimeoutMs(long millis) throws SQLException { checkClosed(); if (millis < 0) { throw new PSQLException(GT.tr("Query timeout must be a value greater than or equals to 0."), PSQLState.INVALID_PARAMETER_VALUE); } timeout = millis; }
java
public Query addRangeRefinement(String navigationName, String low, String high, boolean exclude) { return addRefinement(navigationName, new RefinementRange().setLow(low).setHigh(high).setExclude(exclude)); }
python
def add_row(self, obj): """ fill a new row with the given obj obj instance of the exporter's model """ row = {} for column in self.headers: value = '' if '__col__' in column: if isinstance(column['__col__'], C...
python
def get_columns_diff(changes): """Add the changed columns as a diff attribute. - changes: a list of changes (get_model_changes query.all()) Return: the same list, to which elements we added a "diff" attribute containing the changed columns. Diff defaults to []. """ for change in changes: ...
java
public boolean remove(Object o) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.remove(o); } finally { lock.unlock(); } }