language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private boolean removeFile(File f) { if (Utils.fileIsFile(f)) { return Utils.deleteFile(f); } else { //delete directory f.. boolean ok = true; //remove all the children.. File children[] = Utils.listFiles(f); if (children != null) {...
java
private void addSwitchConstraints(ReconfigurationProblem rp) { // Switches capacity limitation List<Task> tasksList = new ArrayList<>(); List<IntVar> heightsList = new ArrayList<>(); for(Switch sw : net.getSwitches()) { // Only if the capacity is limited ...
java
public void itemStateChanged(ItemEvent iEvt) { String item = (String) iEvt.getItem(); int i; for (i = 0; i < localeCount; i++) { if (locales[i].getDisplayName().equals(item)) break; } setLocale(locales[i], false); }
python
def find_matches(text, collection, start_only=False, fuzzy=True, casing=None): """Find completion matches for the given text. Given the user's input text and a collection of available completions, find completions matching the last word of the text. If `start_only` is True, the t...
python
def remove_file(self, path): """Removes the given file""" self.get_file(path).remove() self.remove_cache_buster(path)
python
def update(self, request, id): """Update an object.""" try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'er...
java
public Object extractObject(Object pValue, Stack<String> pPathParts, boolean pJsonify) throws AttributeNotFoundException { ObjectSerializationContext stackContext = stackContextLocal.get(); String limitReached = checkForLimits(pValue, stackContext); Stack<String> pathStack = pPathPar...
java
private void LaunchWebPage(InteractiveObject interactiveObjectFinal, String url) { if (webPagePlusUISceneObject == null) { final String urlFinal = url; final GVRSceneObject gvrSceneObjectAnchor = interactiveObjectFinal.getSensor().getOwnerObject(); gvrContext.getActivity().ru...
java
public byte[] convertToByteSilent(String htmlInput) { try { return convertToByte(htmlInput.getBytes(getEncoding())); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn(Messages.get().getBundle().key(Messages.LOG_CONVERSION_BYTE_FAILED_0), e); ...
java
private void checkRecordAnnotation(final Class<?> tableClass, final AnnotationReader annoReader) { final int horizontalSize = FieldAccessorUtils.getPropertiesWithAnnotation( tableClass, annoReader, XlsHorizontalRecords.class) .size(); final int verticalSize = Fiel...
python
def _list_resource(self, resource): """ List all instances of the given resource type. Use the specific list_<resource>() methods instead: list_collections() list_experiments() list_channels() list_coordinate_frames() Args: re...
python
def update(args): """ Run site update --------------- Run updates for site or all installed. :: usage: main.py update [-h] [-v] [-p PATH] [SITE] Run site update positional arguments: SITE Path to site or name (project.branch) optional ar...
java
public void classify() { long start = System.currentTimeMillis(); if(log.isInfoEnabled()) log.info("Classifying with " + numThreads + " threads"); // Create contexts for init concepts in the ontology int numConcepts = factory.getTotalConcepts(); for (int i = 0; i < n...
java
@Inline(value="$2.$3copyOf($1)", imported=ImmutableSet.class) public static <T> Set<T> immutableCopy(Set<? extends T> set) { return ImmutableSet.copyOf(set); }
java
public static Date addDate(final Date date, final Integer different) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, different); return cal.getTime(); }
python
def spawn(func, kwargs): """Spawn a thread, and join it after the context is over.""" t = threading.Thread(target=func, kwargs=kwargs) t.start() yield t.join()
python
def resize_state_port_meta(state_m, factor, gaphas_editor=True): """ Resize data and logical ports relative positions """ # print("scale ports", factor, state_m, gaphas_editor) if not gaphas_editor and isinstance(state_m, ContainerStateModel): port_models = state_m.input_data_ports[:] + state_m.outp...
python
def update_loci(self): """Goes through and combines loci until we have one set meeting our overlap definition""" # Create sub-loci for each chromosome lbc = {} chroms = sorted([x.range.chr for x in self.loci]) for chrom in chroms: lbc[chrom] = Loci() for x in self.loci: lbc[x.range.chr].add_locu...
python
def update(self, typ, id, **kwargs): """ update just fields sent by keyword args """ return self._load(self._request(typ, id=id, method='PUT', data=kwargs))
python
def teardown_request(self, func: Callable) -> Callable: """Add a teardown request function to the Blueprint. This is designed to be used as a decorator, and has the same arguments as :meth:`~quart.Quart.teardown_request`. It applies only to requests that are routed to an endpoint in thi...
python
def remove(self, component): # type: (str) -> None """ Kills/Removes the component with the given name :param component: A component name :raise KeyError: Unknown component """ with self.__lock: # Find its factory factory = self.__names.po...
java
@Override public void initialize(String name, final Scheduler scheduler) throws SchedulerException { logger.info("Registering Quartz shutdown hook."); Thread t = new Thread("Quartz Shutdown-Hook") { @Override public void run() { logger.info("Shutting down Quartz..."...
java
synchronized public WebPage[] getCachedPages(WebSiteRequest req) throws IOException, SQLException { WebPage[] myPages=this.pages; if(myPages==null) myPages=this.pages=getWebPages(req); return myPages; }
python
def _add_image(collection, image): ''' Add image to given dictionary ''' image_prep = { 'id': image.id, 'name': image.name, 'created_at': image.created_at, 'file': image.file, 'min_disk': image.min_disk, 'min_ram': image.min_ram, ...
python
def init_app(self, app): """ Adds the flask url routes for the apidoc files. :param app: the flask application. """ self.app = app self.dynamic_url = self.app.config.get('APIDOC_DYNAMIC_URL', self.dynamic_url) self.allow_absolute_url = self.app.config.get('APIDO...
python
def process_request(self, request_object): """Process Update Resource Request""" # Retrieve the object by its identifier entity = request_object.entity_cls.get(request_object.identifier) # Update the object and return the updated data resource = entity.update(request_object.dat...
python
def userinfo_json(request, user_id): """ Return the user's information in a json object """ data = {'first_name': '', 'last_name': '', 'email': '', 'slug': '', 'bio': '', 'phone': '', 'is_active': False} try: member = S...
python
def normalize_total(adata, target_sum=None, fraction=1, key_added=None, layers=None, layer_norm=None, inplace=True): """\ {norm_descr} {params_bulk} {norm_return} {examples} """ if fraction < 0 or fraction > 1: raise ValueError('Choose fraction between 0 and 1....
java
public void startSwipe(ViewHolder viewHolder) { if (!mCallback.hasSwipeFlag(mRecyclerView, viewHolder)) { Log.e(TAG, "Start swipe has been called but swiping is not enabled"); return; } if (viewHolder.itemView.getParent() != mRecyclerView) { Log.e(TAG, "Start ...
java
private Object inheritedStrategy(UrlInfo urlInfo, ResponseHelper responseHelper) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class<?> clazz = Class.forName(urlInfo.getController()); Method setResponseHelper = clazz.getMet...
python
def certificate(args): """ %prog certificate tpffile certificatefile Generate certificate file for all overlaps in tpffile. tpffile can be generated by jcvi.formats.agp.tpf(). North chr1 2 0 AC229737.8 telomere 58443 South chr1 2 1 AC229737.8 AC202463.29 58443 37835 58443 + N...
python
def get_words(self): """ Returns the document words. :return: Document words. :rtype: list """ words = [] block = self.document().findBlockByLineNumber(0) while block.isValid(): blockWords = foundations.strings.get_words(foundations.strings.t...
python
def node_inclusion_predicate_builder(nodes: Iterable[BaseEntity]) -> NodePredicate: """Build a function that returns true for the given nodes.""" nodes = set(nodes) @node_predicate def node_inclusion_predicate(node: BaseEntity) -> bool: """Return true if the node is in the given set of nodes.""...
python
def __save_shadow_copy(self): """ Saves a copy of the stored routine source with pure SQL (if shadow directory is set). """ if not self.shadow_directory: return destination_filename = os.path.join(self.shadow_directory, self._routine_name) + '.sql' if os.pat...
java
public static final void nodeName(String name) { if (tc.isEntryEnabled()) Tr.entry(tc, "nodeName", name); _nodeName = name; if (tc.isEntryEnabled()) Tr.exit(tc, "nodeName"); }
java
protected String getStringMethodParam(String methodName, String paramKey, String defaultValue) { if (CommonUtils.isEmpty(configContext)) { return defaultValue; } String o = (String) configContext.get(buildMethodKey(methodName, paramKey)); if (o == null) { o = (Str...
python
def get_v_eff_stress_at_depth(self, y_c): """ Determine the vertical effective stress at a single depth z_c. :param y_c: float, depth from surface """ sigma_v_c = self.get_v_total_stress_at_depth(y_c) pp = self.get_hydrostatic_pressure_at_depth(y_c) sigma_veff_c ...
python
def fix_variables(bqm, sampling_mode=True): """Determine assignments for some variables of a binary quadratic model. Roof duality finds a lower bound for the minimum of a quadratic polynomial. It can also find minimizing assignments for some of the polynomial's variables; these fixed variables take the...
python
def weed(self): """ Get rid of key value pairs that are not standard """ _ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k]
java
public Candlestick data(Double open, Double close, Double min, Double max) { Object[] kData = new Object[]{open, close, min, max}; super.data(kData); return this; }
python
def l_system(axiom, transformations, iterations=1, angle=45, resolution=1): """Generates a texture by running transformations on a turtle program. First, the given transformations are applied to the axiom. This is repeated `iterations` times. Then, the output is run as a turtle program to get a texture...
python
def inject_module(module, *args, **kwargs): """ Imports a function from a python module :module: and executes it with *args, **kwargs arguments. Dotted referencing can be used to specify the function from the module. For example, the following code will execute func1 and func2 from module mymodule with...
python
def l2_norm(x, filters=None, epsilon=1e-6, name=None, reuse=None): """Layer normalization with l2 norm.""" if filters is None: filters = shape_list(x)[-1] with tf.variable_scope(name, default_name="l2_norm", values=[x], reuse=reuse): scale = tf.get_variable( "l2_norm_scale", [filters], initializer...
python
def point_predict(f, x, size=1, nugget=None): """ point_predict(f, x[, size, nugget]) Makes 'size' simulations for f(x) + N(0,nugget). Simulated values of f(x_i) are uncorrelated for different i. Useful for geostatistical predictions. """ orig_shape = x.shape x = regularize_array(x) ...
java
public String describeDayOfMonth(final Map<CronFieldName, CronField> fields) { final String description = DescriptionStrategyFactory.daysOfMonthInstance( resourceBundle, fields.containsKey(CronFieldName.DAY_OF_MONTH) ? fields.get(CronFieldName.DAY_OF_MONTH).getExpression() : null...
python
def collide(cls, data, params): """ Calculate boundaries of geometry object Uses Strategy """ xminmax = ['xmin', 'xmax'] data, width = cls._collide_setup(data, params) if params.get('width', None) is None: params['width'] = width # Reorder by...
python
def semiconvergents(x): """Semiconvergents of continued fraction expansion of a Fraction x.""" (q, n), d = divmod(x.numerator, x.denominator), x.denominator yield Fraction(q) p0, q0, p1, q1 = 1, 0, q, 1 while n: (q, n), d = divmod(d, n), n for _ in range(q): p0, q0 = p0+...
python
def unpublish(self, path): """Make public file or folder private (delete public url)""" data = """ <propertyupdate xmlns="DAV:"> <remove> <prop> <public_url xmlns="urn:yandex:disk:meta" /> </prop> </remove> </propertyupdate> """ _check_dst_absolute(pat...
java
public static base_response delete(nitro_service client, vrid resource) throws Exception { vrid deleteresource = new vrid(); deleteresource.id = resource.id; deleteresource.all = resource.all; return deleteresource.delete_resource(client); }
python
def get_cameras_signal_strength(self): """Return a list of signal strength of all cameras.""" signal_strength = {} if not self.camera_properties: return None for camera in self.camera_properties: serialnum = camera.get('serialNumber') cam_strength = c...
java
protected void removeEmptyDirectories(File outputDirectory) { if (outputDirectory.exists()) { for (File file : outputDirectory.listFiles(new EmptyDirectoryFilter())) { file.delete(); } } }
python
def _normalize_joliet_path(self, joliet_path): # type: (str) -> bytes ''' An internal method to check whether this ISO does or does not require a Joliet path. If a Joliet path is required, the path is normalized and returned. Parameters: joliet_path - The jolie...
python
def detach_children(self): """ Erase references to children without deleting them. These children might be used somewhere else, otherwise they will be taken care by ``Python``'s garbage collector. """ for node in self.get_child_nodes(): node.set_parent(None) ...
java
public void dismiss(boolean animated) { if (animated) { if (visibilityChangeListener != null) { visibilityChangeListener.onAlertDismissStarted(this); } startAnimation(fadeOutAnimation); } else { setVisibility(GONE); } }
python
def items(self): """ Get a queryset, cache infos for standardized access to them later then compute the maximum of entries to define the priority of each items. """ queryset = self.get_queryset() self.cache_infos(queryset) self.set_max_entries() re...
python
def limit(self, keys): ''' Remove all keys other than the keys specified. ''' if not isinstance(keys, list) and not isinstance(keys, tuple): keys = [keys] remove_keys = [k for k in self.keys() if k not in keys] for k in remove_keys: self.pop(k)
java
public synchronized void replaceModel (MaxentModel model) { replacementThread = Thread.currentThread(); while (!replacementCanProceed) Thread.yield(); setter.setModel(model); replacementThread = null; }
python
def initialize_logger(): """Initialize steppy logger. This logger is used throughout the steppy library to report computation progress. Example: Simple use of steppy logger: .. code-block:: python initialize_logger() logger = get_logger() ...
java
protected void afterStartEventParser(CanalEventParser eventParser) { // 读取一下历史订阅的filter信息 List<ClientIdentity> clientIdentitys = metaManager.listAllSubscribeInfo(destination); for (ClientIdentity clientIdentity : clientIdentitys) { subscribeChange(clientIdentity); } }
java
@Override public BigDecimalAttribute plus(BigDecimalAttribute attribute) { return (BigDecimalAttribute) MappedAttributeUtil.plus(this, (NumericAttribute) attribute); }
java
public EClass getIfcRelSpaceBoundary() { if (ifcRelSpaceBoundaryEClass == null) { ifcRelSpaceBoundaryEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(484); } return ifcRelSpaceBoundaryEClass; }
java
@ConditionalOnSingleCandidate(CallCredentials.class) @Bean StubTransformer stubCallCredentialsTransformer(final CallCredentials credentials) { return CallCredentialsHelper.fixedCredentialsStubTransformer(credentials); }
java
public static String quote(final String value) { if (value == null) { return null; } String result = value; if (!result.startsWith("\"")) { result = "\"" + result; } if (!result.endsWith("\"")) { result = result + "\""; } ...
java
public static List<CommerceTierPriceEntry> findByUuid_C(String uuid, long companyId) { return getPersistence().findByUuid_C(uuid, companyId); }
java
public <M extends Map<K, List<V>>> M grouping(Supplier<M> mapSupplier) { return grouping(mapSupplier, Collectors.toList()); }
java
public Bucket<Data> getEmptyBucketWithSameProperties() throws FileLockException, IOException { Bucket<Data> newBucket = new Bucket<Data>(this.bucketId, gp); return newBucket; }
java
public void setStatements(List<AstNode> statements) { if (this.statements != null) { this.statements.clear(); } for (AstNode s : statements) { addStatement(s); } }
python
def clone_workspace(self) -> None: """ Pose a dialog to name and clone a workspace. """ def clone_clicked(text): if text: command = Workspace.CloneWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(comman...
java
private void moveMethods(Collection<NameInfo> allNameInfo) { boolean hasStubDeclaration = idGenerator.hasGeneratedAnyIds(); for (NameInfo nameInfo : allNameInfo) { if (!nameInfo.isReferenced()) { // The code below can't do anything with unreferenced name // infos. They should be skipped t...
java
public List<DataItem> decode() throws CborException { List<DataItem> dataItems = new LinkedList<>(); DataItem dataItem; while ((dataItem = decodeNext()) != null) { dataItems.add(dataItem); } return dataItems; }
python
def remove_vectored_io_slice_suffix_from_name(name, slice): # type: (str, int) -> str """Remove vectored io (stripe) slice suffix from a given name :param str name: entity name :param int slice: slice num :rtype: str :return: name without suffix """ suffix = '.bxslice-{}'.format(slice) ...
java
public JsonWriter prop(String name, @Nullable Number value) { return name(name).value(value); }
java
public JobFlowInstancesDetail withInstanceGroups(InstanceGroupDetail... instanceGroups) { if (this.instanceGroups == null) { setInstanceGroups(new com.amazonaws.internal.SdkInternalList<InstanceGroupDetail>(instanceGroups.length)); } for (InstanceGroupDetail ele : instanceGroups) { ...
java
public int findInContent(String content) { int n = content.length(); int m = pattern.length(); int skip; char val; for (int i = 0; i <= n - m; i = i + skip) { skip = 0; for (int j = m - 1; j >= 0; j--) { if (pattern.charAt(j) != c...
java
public static String fieldNodeFormat(Collection<FieldNode> fieldNodes) { StringBuilder s = new StringBuilder(); int n = 0; for (FieldNode fieldNode : fieldNodes) { if (n > 0) { s.append(" "); } s.append("'").append(fieldNodeFormat(fieldNode)).append("'"); n++; } return s.toString(); }
java
public static String urlDecode(String content, TestContext context) { return new UrlDecodeFunction().execute(Collections.singletonList(content), context); }
python
def sync_one(self, aws_syncr, amazon, route): """Make sure this role exists and has only what policies we want it to have""" route_info = amazon.route53.route_info(route.name, route.zone) target = route.record_target if callable(target): target = target(amazon) if no...
python
def strip_stat(value): """ Remove calc function that mark calculated aesthetics Parameters ---------- value : object Aesthetic value. In most cases this will be a string but other types will pass through unmodified. Return ------ out : object Aesthetic value wit...
python
def easeOutElastic(n, amplitude=1, period=0.3): """An elastic tween function that overshoots the destination and then "rubber bands" into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1....
python
def sparsify(sess, eval_model, pruning_strategy, pruning_params): """Prune the weights of a model and evaluate.""" weights = tf.trainable_variables() def should_prune(name): """Whether to prune a weight or not.""" in_whitelist = not pruning_params.white_list or any( e in name for e in pruning_par...
java
@NotNull public static <T, U, A, R> Collector<T, ?, R> flatMapping( @NotNull final Function<? super T, ? extends Stream<? extends U>> mapper, @NotNull final Collector<? super U, A, R> downstream) { final BiConsumer<A, ? super U> accumulator = downstream.accumulator(); return...
python
def start(self): """Schedule the timeout. This is called on construction, so it should not be called explicitly, unless the timer has been canceled.""" assert not self._timer, '%r is already started; to restart it, cancel it first' % self loop = evergreen.current.loop cu...
python
def xml_marshal_complete_multipart_upload(uploaded_parts): """ Marshal's complete multipart upload request based on *uploaded_parts*. :param uploaded_parts: List of all uploaded parts, ordered by part number. :return: Marshalled XML data. """ root = s3_xml.Element('CompleteMultipartUpload', {'x...
python
def arguments_from_optionable(parser, component, prefix=""): """ Add argparse arguments from all options of one :class:`Optionable` >>> # Let's build a dummy optionable component: >>> comp = Optionable() >>> comp.add_option("num", Numeric(default=1, max=12, help="An exemple of option")) >>> comp.ad...
python
def _copy_status(self, filename, size, sent): """ Echo status of an SCP operation. Purpose: Callback function for an SCP operation. Used to show | the progress of an actively running copy. This directly | prints to stdout, one line for each file as it's copied. ...
python
def uniq(iterable): """ Yield the unique items of an iterable, preserving order. http://mail.python.org/pipermail/tutor/2002-March/012930.html Example: >>> x = uniq([0, 0, 2, 6, 2, 0, 5]) >>> list(x) [0, 2, 6, 5] """ temp_dict = {} for e in iterable: if e not in temp_dict: yield temp_dict.setdefault(e,...
java
@Override protected XMLEvent internalNextEvent() throws XMLStreamException { // If there is an iterator to read from reset was called, use the iterator // until it runs out of events. if (this.bufferReader != null) { final XMLEvent event = this.bufferReader.next(); /...
python
def finalizeTempDfa (tempStates): """finalizeTempDfa (tempStates) Input domain: tempState := [ nfaClosure : Long, [ tempArc ], accept : Boolean ] tempArc := [ label, arrow, nfaClosure ] Output domain: state := [ arcMap, accept : Boolean ] """ states = [] accepts = [] stateMap =...
python
def create_in_cluster(self): """ call Kubernetes API and create this Deployment in cluster, raise ConuException if the API call fails :return: None """ try: self.api.create_namespaced_deployment(self.namespace, self.body) except ApiException as e: ...
python
def _get_rsa_public_key(cert): """ PyOpenSSL does not provide a public method to export the public key from a certificate as a properly formatted ASN.1 RSAPublicKey structure. There are 'hacks' which use dump_privatekey(crypto.FILETYPE_ASN1, <public_key>), but this dumps the public key w...
python
def create_permission_request(self, customer, pos_id, pos_tid, scope, ledger=None, text=None, callback_uri=None, expires_in=None): """Create permission request The call is idempotent; that is, if one posts the same pos_id and p...
python
def get(self, key): """ Returns the list of values associated with the key. ``None`` if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's c...
python
def handler_for(obj): """return the handler for the object type""" for handler_type in handlers: if isinstance(obj, handler_type): return handlers[handler_type] try: for handler_type in handlers: if issubclass(obj, handler_type): return handlers[handl...
python
def particle_number_concentration(ConcMat, material): """Return the number of particles in suspension. :param ConcMat: Concentration of the material :type ConcMat: float :param material: The material in solution :type material: floc_model.Material """ return ConcMat.to(material.Density.unit...
python
def backbone(self): """Returns a new `Polymer` containing only the backbone atoms. Notes ----- Metadata is not currently preserved from the parent object. Sequence data is retained, but only the main chain atoms are retained. Returns ------- bb_poly : Po...
java
public LogBuilder append (Object... args) { if (args != null && args.length > 1) { for (int ii = 0, nn = args.length - (args.length % 2); ii < nn; ii += 2) { if (_hasArgs) { _log.append(", "); } else { if (_log.length() > 0)...
java
@Override @Transactional(readOnly = true, isolation = Isolation.SERIALIZABLE) public void export( List<EntityType> entityTypes, List<Package> packages, Path downloadFilePath, Progress progress) { requireNonNull(progress); if (!(entityTypes.isEmpty() && packages.isEmpty())) { tr...
python
def jscanner(url): """Extract endpoints from JavaScript code.""" response = requester(url, main_url, delay, cook, headers, timeout, host, proxies, user_agents, failed, processed) # Extract URLs/endpoints matches = rendpoint.findall(response) # Iterate over the matches, match is a tuple for...
java
public void prepare(Properties p, Connection cnx) { this.tablePrefix = p.getProperty("com.enioka.jqm.jdbc.tablePrefix", ""); queries.putAll(DbImplBase.queries); for (Map.Entry<String, String> entry : DbImplBase.queries.entrySet()) { queries.put(entry.getKey(), this.adaptS...
java
public void addTableField(String fieldLabel, JTable field, List<JButton> buttons) { validateNotTabbed(); JScrollPane scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); scrollPane.setViewportView(field); field.setFillsViewportHeight(true); // T...