language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void doPrevious(final Wave wave) { if (this.eventList != null && this.timeFrame > 0) { hideCurrent(this.eventList.get(this.timeFrame)); } }
java
public void setAuthorizationRules(java.util.Collection<AuthorizationRule> authorizationRules) { if (authorizationRules == null) { this.authorizationRules = null; return; } this.authorizationRules = new com.amazonaws.internal.SdkInternalList<AuthorizationRule>(authorizati...
java
public void marshall(BatchDetachTypedLinkResponse batchDetachTypedLinkResponse, ProtocolMarshaller protocolMarshaller) { if (batchDetachTypedLinkResponse == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { } catch (Exception e) { ...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.CRC_RESOURCE_MANAGEMENT__FMT_QUAL: setFmtQual(FMT_QUAL_EDEFAULT); return; case AfplibPackage.CRC_RESOURCE_MANAGEMENT__RM_VALUE: setRMValue(RM_VALUE_EDEFAULT); return; case AfplibPackage.CRC_RESOURCE_MANAGEM...
java
private Object find( SearchComparator comp, Object searchKey) { SearchNode point = getSearchNode(); Object ret = null; boolean gotit = optimisticFind(comp, searchKey, point); if (gotit == pessimisticNeeded) pessim...
python
def get_self_url(request_data): """ Returns the URL of the current host + current view + query. :param request_data: The request as a dict :type: dict :return: The url of current host + current view + query :rtype: string """ self_url_host = OneLogin_Sam...
java
@Override public DBCluster modifyDBCluster(ModifyDBClusterRequest request) { request = beforeClientExecution(request); return executeModifyDBCluster(request); }
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "segments") public JAXBElement<CurveSegmentArrayPropertyType> createSegments(CurveSegmentArrayPropertyType value) { return new JAXBElement<CurveSegmentArrayPropertyType>(_Segments_QNAME, CurveSegmentArrayPropertyType.class, null, value); }
java
@XmlElementDecl(namespace = "http://www.w3.org/ns/prov#", name = "actedOnBehalfOf") public JAXBElement<ActedOnBehalfOf> createActedOnBehalfOf(ActedOnBehalfOf value) { return new JAXBElement<ActedOnBehalfOf>(_ActedOnBehalfOf_QNAME, ActedOnBehalfOf.class, null, value); }
python
def _get_systemd_services(root): ''' Use os.listdir() to get all the unit files ''' ret = set() for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,): # Make sure user has access to the path, and if the path is a # link it's likely that another entry in SYSTEM_CONFIG_PATHS #...
python
def sample(self, pmf=None, replace=True): """Sample an item from the strata Parameters ---------- pmf : array-like, shape=(n_strata,), optional, default None probability distribution to use when sampling from the strata. If not given, use the stratum weights. ...
java
private void changePage(final int direction) { int currentPage = pages.indexOf(cardManager.getVisible()); currentPage = Math.min(2, Math.max(0, currentPage + direction)); cardManager.makeVisible(pages.get(currentPage)); prevButton.setDisabled(currentPage == 0); nextButton.setDisabled(currentPage == 2); fi...
java
public MultiLineString toMultiLineStringFromList( List<List<LatLng>> polylineList) { return toMultiLineStringFromList(polylineList, false, false); }
java
private long finalizeFlv() { long bytesTransferred = 0L; if (!finalized.get()) { log.debug("Finalizing {}", filePath); try { // read file info if it exists File tmpFile = new File(filePath + ".info"); if (tmpFile.exists()) { ...
python
def fastrcnn_outputs(feature, num_classes, class_agnostic_regression=False): """ Args: feature (any shape): num_classes(int): num_category + 1 class_agnostic_regression (bool): if True, regression to N x 1 x 4 Returns: cls_logits: N x num_class classification logits ...
python
def wait(self, dwMilliseconds = None): """ Waits for the next debug event. @see: L{cont}, L{dispatch}, L{loop} @type dwMilliseconds: int @param dwMilliseconds: (Optional) Timeout in milliseconds. Use C{INFINITE} or C{None} for no timeout. @rtype: L{Event}...
java
public void setPreparationThreads(int preparationThreads) { this.preparationThreads = preparationThreads; this.threadPool = java.util.concurrent.Executors.newFixedThreadPool(preparationThreads); }
python
def MakeDeployableBinary(self, template_path, output_path): """Repackage the template zip with the installer.""" context = self.context + ["Client Context"] zip_data = io.BytesIO() output_zip = zipfile.ZipFile( zip_data, mode="w", compression=zipfile.ZIP_DEFLATED) z_template = zipfile.ZipF...
java
private double winkler(double totalScore, String S, String T) { totalScore = totalScore + (getPrefix(S, T) * 0.1 * (1.0 - totalScore)); return totalScore; }
java
private Iterable<String> retainExistingRoles(final Collection<String> roles) { final List<String> existingRoles = getRoles(); existingRoles.retainAll(roles); return existingRoles; }
python
def _generate_transformations(self, structure): """ The central problem with trying to enumerate magnetic orderings is that we have to enumerate orderings that might plausibly be magnetic ground states, while not enumerating orderings that are physically implausible. The problem ...
python
def update_confirmation_comment(self, confirmation_comment_id, confirmation_comment_dict): """ Updates a confirmation comment :param confirmation_comment_id: the confirmation comment id :param confirmation_comment_dict: dict :return: dict """ return self._create_...
python
def get_metric_by_week(self, unique_identifier, metric, from_date, limit=10, **kwargs): """ Returns the ``metric`` for ``unique_identifier`` segmented by week starting from``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metr...
python
def gfstep(time): """ Return the time step set by the most recent call to :func:`gfsstp`. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfstep_c.html :param time: Ignored ET value. :type time: float :return: Time step to take. :rtype: float """ time = ctypes.c_double(time...
java
public int getStatus() { Integer intStatus = (Integer)this.getFieldData(m_iStatusField); if (intStatus != null) return intStatus.intValue(); return 0; }
python
def roles(self, value): """ Setter for **self.__roles** attribute. :param value: Attribute value. :type value: dict """ if value is not None: assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format("roles", value) for key ...
java
public void setTypeResolver(RelationshipResolver resolver, Class<?> type) { if (resolver != null) { String typeName = ReflectionUtils.getTypeName(type); if (typeName != null) { typedResolvers.put(type, resolver); } } }
python
def _axis_properties(self, axis, title_size, title_offset, label_angle, label_align, color): """Assign axis properties""" if self.axes: axis = [a for a in self.axes if a.scale == axis][0] self._set_axis_properties(axis) self._set_all_axis_colo...
java
public static void centerDialog(JDialog dialog) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = dialog.getSize(); dialog.setLocation(screenSize.width / 2 - frameSize.width / 2, screenSize.height / 2 - frameSize.height / 2); dialog.setLocationByPlat...
java
private boolean performFlushIfRequired() throws IOException { if (anyAreSet(state, FLUSHING_BUFFER)) { final ByteBuffer[] bufs = new ByteBuffer[additionalBuffer == null ? 1 : 2]; long totalLength = 0; bufs[0] = currentBuffer.getBuffer(); totalLength += bufs[0].rem...
java
protected String createCanonicalRequest(SignableRequest<?> request, String contentSha256) { /* This would url-encode the resource path for the first time. */ final String path = SdkHttpUtils.appendUri( request.getEndpoint().getPath(), request.getResourcePath()); fina...
python
def _reverse_convert(x, factor1, factor2): """ Converts mixing ratio x in c1 - c2 tie line to that in comp1 - comp2 tie line. Args: x (float): Mixing ratio x in c1 - c2 tie line, a float between 0 and 1. factor1 (float): Compositional ratio betwee...
python
def delete(self, id): '''Delete a single item with the given ID''' if not self._item_path: raise AttributeError('delete is not available for %s' % self._item_name) target = self._item_path % id self._redmine.delete(target) return None
python
def bingham_mean(dec=None, inc=None, di_block=None): """ Calculates the Bingham mean and associated statistical parameters from either a list of declination values and a separate list of inclination values or from a di_block (a nested list a nested list of [dec,inc,1.0]). Returns a dictionary with t...
java
private void send(ByteBuffer data) { try { this.socket.send(new DatagramPacket( data.array(), data.capacity(), this.address)); } catch (IOException ioe) { logger.info("Error sending datagram packet to tracker at {}: {}.", this.address, ioe.getMessage()); ...
python
def process_spider_output(self, response, result, spider): ''' Ensures the meta data from the response is passed through in any Request's generated from the spider ''' self.logger.debug("processing meta passthrough middleware") for x in result: # only operate ...
python
def stop_choose(self): """Marks the item as the one the user is not in.""" if self.choosed: self.choosed = False self.pos = self.pos + Sep(-5, 0)
python
def duplicate_items(*collections): """Search for duplicate items in all collections. Examples -------- >>> duplicate_items([1, 2], [3]) set() >>> duplicate_items({1: 'a', 2: 'a'}) set() >>> duplicate_items(['a', 'b', 'a']) {'a'} >>> duplicate_items([1, 2], {3: 'hi', 4: 'ha'}, (2...
java
private void fillBuffer() throws IOException { if (!endOfInput && (lastCoderResult == null || lastCoderResult.isUnderflow())) { encoderIn.compact(); int position = encoderIn.position(); // We don't use Reader#read(CharBuffer) here because it is more efficient // t...
python
def latencies(self): """List[Tuple[:class:`int`, :class:`float`]]: A list of latencies between a HEARTBEAT and a HEARTBEAT_ACK in seconds. This returns a list of tuples with elements ``(shard_id, latency)``. """ return [(shard_id, shard.ws.latency) for shard_id, shard in self.shards.ite...
java
@Override public void onNDArray(INDArray arr) { try (AeronNDArrayPublisher publisher = AeronNDArrayPublisher.builder().streamId(streamId).ctx(aeronContext) .channel(masterUrl).build()) { publisher.publish(arr); log.debug("NDArray PublishingListener publishing ...
python
def awsRetry(f): """ This decorator retries the wrapped function if aws throws unexpected errors errors. It should wrap any function that makes use of boto """ @wraps(f) def wrapper(*args, **kwargs): for attempt in retry(delays=truncExpBackoff(), timeout=...
java
public com.cloudant.client.api.model.Response removeAttachment(String id, String rev, String attachmentName) { Response couchDbResponse = db.removeAttachment(id, rev, attachmentName); com.cloudant.client.api.model.Response response = new com.cloudant.client.api.model .Response(couchDbRes...
python
def environ(on=os, **kw): """Update one or more environment variables. Preserves the previous environment variable (if available) and can be applied to remote connections that offer an @environ@ attribute using the @on@ argument. """ originals = list() for key in kw: o...
java
public List<Path> getExtraFilesDirectories() { return extraFilesDirectories == null ? null : extraFilesDirectories.stream().map(File::toPath).collect(Collectors.toList()); }
java
@Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(id); dest.writeString(alert); dest.writeString(url); dest.writeString(payload); dest.writeString(mid); dest.writeString(sound); dest.writeString(String.valueOf(bridge)); dest.writeString(priority); dest.writeString(visibil...
python
def get_schema_from_list(table_name, frum): """ SCAN THE LIST FOR COLUMN TYPES """ columns = UniqueIndex(keys=("name",)) _get_schema_from_list(frum, ".", parent=".", nested_path=ROOT_PATH, columns=columns) return Schema(table_name=table_name, columns=list(columns))
java
public Template parseTeaTemplate(String templateName) throws IOException { if (templateName == null) { return null; } preserveParseTree(templateName); compile(templateName); CompilationUnit unit = getCompilationUnit(templateName, null); if (unit == null) { ...
python
def send(self, api, force_send): """ Send this item using api. :param api: D4S2Api sends messages to D4S2 :param force_send: bool should we send even if the item already exists """ item_id = self.get_existing_item_id(api) if not item_id: item_id = self...
java
public void marshall(ListTagsForStreamRequest listTagsForStreamRequest, ProtocolMarshaller protocolMarshaller) { if (listTagsForStreamRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listTag...
python
def expand_multirow_data(data): """ Converts multirow cells to a list of lists and informs the number of lines of each row. Returns: tuple: new_data, row_heights """ num_cols = len(data[0]) # number of columns # calculates row heights row_heights = [] for mlrow in...
python
def forcemigrate(app=None): """Force migrations to apply for a given app.""" if app is None: abort("No app name given.") local("./manage.py migrate {} --fake".format(app)) local("./manage.py migrate {}".format(app))
java
protected static MPResourceArray processMethodBulk(Class clazz, String methodName, String param1, Boolean useCache) throws MPException { HashMap<String, String> mapParams = new HashMap<String, String>(); mapParams.put("param1", param1); return processMethodBulk(clazz, methodName, mapParams, useC...
python
def _array_to_table(arr, rownames, colnames, n_digits): """Print an array with row and column names Example: mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat beta[1,1] 0.0 0.0 1.0 -2.0 -0.7 0.0 0.7 2.0 4000 1 beta[1,2] 0.0 0.0 1.0 -2.1 -0.7 0.0 0.7 2...
java
public void write(DataOutput out) throws IOException { out.writeInt(bytesPerCRC); out.writeLong(crcPerBlock); md5.write(out); }
java
public List<CmsJspNavElement> getNavigationForFolder( String folder, Visibility visibility, CmsResourceFilter resourceFilter) { folder = CmsFileUtil.removeTrailingSeparator(folder); List<CmsJspNavElement> result = new ArrayList<CmsJspNavElement>(); List<CmsResource> res...
java
private static short readLEShort(InputStream in) throws IOException { short s = (byte)in.read(); s |= (byte)in.read() << 8; return s; }
java
public static String getTarballResourceNameFromUrl(String url) { String resourceName = url.substring(url.lastIndexOf('/') + 1); return resourceName; }
java
public String removeResponseBaggage(String key) { if (BAGGAGE_ENABLE && key != null) { return responseBaggage.remove(key); } return null; }
python
def fix_groups(groups): """Takes care of strange group numbers.""" _groups = [] for g in groups: try: if not float(g) > 0: _groups.append(1000) else: _groups.append(int(g)) except TypeError as e: logging.info("Error in readi...
java
public void setDBEngineVersions(java.util.Collection<DBEngineVersion> dBEngineVersions) { if (dBEngineVersions == null) { this.dBEngineVersions = null; return; } this.dBEngineVersions = new java.util.ArrayList<DBEngineVersion>(dBEngineVersions); }
java
public void setFormat(int formatElementIndex, Format newFormat) { int formatNumber = 0; for (int partIndex = 0; (partIndex = nextTopLevelArgStart(partIndex)) >= 0;) { if (formatNumber == formatElementIndex) { setCustomArgStartFormat(partIndex, newFormat); retu...
java
public final EObject entryRuleNumberLiteral() throws RecognitionException { EObject current = null; EObject iv_ruleNumberLiteral = null; try { // InternalSimpleExpressions.g:469:2: (iv_ruleNumberLiteral= ruleNumberLiteral EOF ) // InternalSimpleExpressions.g:470:2: iv_...
java
public NewChunk asciiToUpper(NewChunk nc) { // copy existing data nc = this.extractRows(nc, 0,_len); //update offsets and byte array for(int i= 0; i < nc._sslen; i++) { if (nc._ss[i] > 0x60 && nc._ss[i] < 0x7B) // check for capital letter nc._ss[i] -= 0x20; // upper it } return nc...
python
def remove_duplicate_edges_undirected(udg): """Removes duplicate edges from an undirected graph.""" # With undirected edges, we need to hash both combinations of the to-from node ids, since a-b and b-a are equivalent # --For aesthetic, we sort the edge ids so that lower edges ids are kept lookup = {} ...
python
def scheme_specification(cls): """ :meth:`.WSchemeHandler.scheme_specification` method implementation """ return WSchemeSpecification( 'file', WURIComponentVerifier(WURI.Component.path, WURIComponentVerifier.Requirement.optional) )
java
public void validateAttributesForm( AttributeSwapRequest attributeSwapRequest, MessageContext context) { final RequestContext requestContext = RequestContextHolder.getRequestContext(); final ExternalContext externalContext = requestContext.getExternalContext(); final Set<String> swap...
python
def mld_snooping_ipv6_pim_snooping_pimv6_enable(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") mld_snooping = ET.SubElement(config, "mld-snooping", xmlns="urn:brocade.com:mgmt:brocade-mld-snooping") ipv6 = ET.SubElement(mld_snooping, "ipv6") pim...
java
private static int getLoggedinState(Context context, String uid) { Cursor cursor = context.getContentResolver().query( LOGGED_IN_URI.buildUpon().appendPath(uid).build(), null, // projection null, // selection clause null, // selection args null); // sort order ...
java
public ServiceFuture<Void> beginRefreshMemberSchemaAsync(String resourceGroupName, String serverName, String databaseName, String syncGroupName, String syncMemberName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginRefreshMemberSchemaWithServiceResponseAsync(resourceGroupN...
python
def replay_scope(self, sess): """Enters a replay scope that unsets it at the end.""" current_replay = self.replay(sess) try: self.set_replay(sess, True) yield finally: self.set_replay(sess, current_replay)
python
def _should_send_property(self, key, value): """Check the property lock (property_lock)""" to_json = self.trait_metadata(key, 'to_json', self._trait_to_json) if key in self._property_lock: # model_state, buffer_paths, buffers split_value = _remove_buffers({ key: to_json(v...
java
public static void setupClasspath( final Path distributedClassPath, final Path intermediateClassPath, final Job job ) throws IOException { String classpathProperty = System.getProperty("druid.hadoop.internal.classpath"); if (classpathProperty == null) { classpathProperty = Syst...
python
def add_number_mapping(self, abi, number, name): """ Associate a syscall number with the name of a function present in the underlying SimLibrary :param abi: The abi for which this mapping applies :param number: The syscall number :param name: The name of the function ...
python
def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field. """ attrs = attrs or {} attrs.update(self.form.get_widget_attrs(self)) if hasattr(self.field, 'widget_css_classes'): css_classes = self.field.widget_css_classes el...
python
def delete_branch(self, project, repository, name, end_point): """ Delete branch from related repo :param self: :param project: :param repository: :param name: :param end_point: :return: """ url = 'rest/branch-utils/1.0/projects/{project}/...
python
def get_pd_by_name(self, name): """ Get ScaleIO ProtectionDomain object by its name :param name: Name of ProtectionDomain :return: ScaleIO ProtectionDomain object :raise KeyError: No ProtetionDomain with specified name found :rtype: ProtectionDomain object """ ...
python
def connect(self, uri=None, cleansession=None, cafile=None, capath=None, cadata=None, extra_headers={}): """ Connect to a remote broker. At first, a network connection is established with the...
python
def update(self, d, ignore_errors=True, block_user_signals=False): """ Supply a dictionary or databox with a header of the same format and see what happens! (Hint: it updates the existing values.) This will store non-existent key-value pairs in the dictionary self._lazy...
python
def remove_pattern(self, pattern): """ Removes given pattern from the Model. :param pattern: Pattern. :type pattern: unicode :return: Method success. :rtype: bool """ for index, node in enumerate(self.root_node.children): if node.name != patt...
java
public void postKey (long time, Key key, boolean pressed, char typedCh, int modFlags) { kevQueue.add(key == null ? new Keyboard.TypedEvent(modFlags, time, typedCh) : new Keyboard.KeyEvent(modFlags, time, key, pressed)); }
java
public static String captureStackTrace(Throwable e) { StringWriter buffer = new StringWriter(); e.printStackTrace(new PrintWriter(buffer)); return buffer.toString(); }
java
protected LightweightTypeReference getCommonSuperType(List<LightweightTypeReference> types, ITypeReferenceOwner owner) { return services.getTypeConformanceComputer().getCommonSuperType(types, owner); }
java
@Override @SuppressWarnings("unchecked") public <T extends CMAResource> T setEnvironmentId(String environmentId) { return (T) setId(environmentId); }
python
def refreshUi( self ): """ Load the plugin information to the interface. """ dataSet = self.dataSet() if not dataSet: return False # lookup widgets based on the data set information for widget in self.findChildren(QWidget): pro...
python
def my_info(self, access_token): """doc: http://open.youku.com/docs/doc?id=23 """ url = 'https://openapi.youku.com/v2/users/myinfo.json' data = {'client_id': self.client_id, 'access_token': access_token} r = requests.post(url, data=data) check_error(r) ...
python
def owned_attributes(self): """ Returns a list of attributes owned by this service. """ attributes = self._get_object(self.update_api.attributes.owned) return [ExistOwnedAttributeResponse(attribute) for attribute in attributes]
java
@JsonValue public Object toJsonValue() { if (flags != null) return flags; if (mode != null) return mode; return null; }
java
public PipeBlobBuilder add(String name, Object value){ elements.add(PipeDataElement.newInstance(name, value)); return this; }
python
def set_key(self, key, modifiers: typing.List[Key]=None): """This is called when the user successfully finishes recording a key combination.""" if modifiers is None: modifiers = [] # type: typing.List[Key] if key in self.KEY_MAP: key = self.KEY_MAP[key] self._set...
python
def dict_merge(base, addition, append_lists=False): """Merge one dictionary with another, recursively. Fields present in addition will be added to base if not present or merged if both values are dictionaries or lists (with append_lists=True). If the values are different data types, the value in additio...
python
def load(path): """Loads a pushdb maintained in a properties file at the given path.""" with open(path, 'r') as props: properties = Properties.load(props) return PushDb(properties)
java
private static int toSeleniumCoordinate(Object openCVCoordinate) { if (openCVCoordinate instanceof Long) { return ((Long) openCVCoordinate).intValue(); } if (openCVCoordinate instanceof Double) { return ((Double) openCVCoordinate).intValue(); } return (int...
python
def append(self, row=None): """append(row=None) :param row: a list of values to apply to the newly append row or :obj:`None` :type row: [:obj:`object`] or :obj:`None` :returns: :obj:`Gtk.TreeIter` of the appended row :rtype: :obj:`Gtk.TreeIter` If `row` is :obj:`None` ...
java
public DateTime toDomain(Date from) { if (from == null) { return null; } return new DateTime(from.getTime()); }
python
def _add_log2_depth(in_file, out_file, data): """Create a CNVkit cnn file with depths http://cnvkit.readthedocs.io/en/stable/fileformats.html?highlight=cnn#target-and-antitarget-bin-level-coverages-cnn """ if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: ...
python
def application(tokens): """Matches function call (application).""" tokens = iter(tokens) func = next(tokens) paren = next(tokens) if func and func.name == "symbol" and paren.name == "lparen": # We would be able to unambiguously parse function application with # whitespace between t...
java
protected void onItemLongClick(View view, int position){ if(itemLongClickListener != null) itemLongClickListener.onItemLongClick(view, getItem(position), position); }
python
def destroy(self): """ Custom destructor that deletes the fragment and removes itself from the adapter it was added to. """ #: Destroy fragment fragment = self.fragment if fragment: #: Stop listening fragment.setFragmentListener(None) ...
java
public Geometry createGeometry(Geometry geometry) { if (geometry instanceof Point) { return createPoint(geometry.getCoordinate()); } else if (geometry instanceof LinearRing) { return createLinearRing(geometry.getCoordinates()); } else if (geometry instanceof LineString) { return createLineString(geometry...