language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def set_style(network_id, ndex_cred=None, template_id=None): """Set the style of the network to a given template network's style Parameters ---------- network_id : str The UUID of the NDEx network whose style is to be changed. ndex_cred : dict A dictionary of NDEx credentials. t...
python
def format_metadata_to_key(key_metadata): """ <Purpose> Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA) according to the keytype of 'key_metadata'. The dict returned by this function has the exact format as the dict returned by one of the key generations functions, like ge...
java
private MediaType findContentType(final String url) { if (url == null) { return null; } if (url.startsWith("file")) { return APPLICATION_OCTET_STREAM_TYPE; } else if (url.startsWith("http")) { try (CloseableHttpClient httpClient = HttpClients.createDe...
java
@Override public DescriptorValue calculate(IAtomContainer container) { IAtomContainer local = AtomContainerManipulator.removeHydrogens(container); int tradius = PathTools.getMolecularGraphRadius(local); int tdiameter = PathTools.getMolecularGraphDiameter(local); DoubleArrayResult r...
java
public static double ioa(double[] prediction, double[] validation, double pow) { double ioa; int td_size = prediction.length; int vd_size = validation.length; if (td_size != vd_size) { throw new IllegalArgumentException("Data sets in ioa does not match!"); } ...
java
public void delete(Vertex vtx) { if (vtx.prev == null) { head = vtx.next; } else { vtx.prev.next = vtx.next; } if (vtx.next == null) { tail = vtx.prev; } else { vtx.next.prev = vtx.prev; } }
python
def deleteoutputfile(project, filename, credentials=None): """Delete an output file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable if filename: filename = filename.replace("..","") #Simple security if not filename or len(filename) == 0: ...
python
def short_description(self): """ Ensure that the admin ``list_display`` renders the correct verbose name for translated fields. The :func:`~django.contrib.admin.utils.label_for_field` function uses :func:`~django.db.models.Options.get_field_by_name` to find the find and ``verbose_name``...
python
def simplex_find_tree(self): ''' API: simplex_find_tree(self) Description: Assumes a feasible flow solution stored in 'flow' attribute's of arcs and converts this solution to a feasible spanning tree solution. Pre: (1) 'flow' at...
java
public void printScreen(PrintWriter out, ResourceBundle reg) throws DBException { this.getScreenFieldView().printScreen(out, reg); }
java
public void sendToUser(String topicURI, Object event, String eligibleUser) { sendToUsers(topicURI, event, Collections.singleton(eligibleUser)); }
java
private int getHydrogenCount(IAtomContainer ac, IAtom atom) { List<IAtom> neighbours = ac.getConnectedAtomsList(atom); int hcounter = 0; for (IAtom neighbour : neighbours) { if (neighbour.getSymbol().equals("H")) { hcounter += 1; } } return...
java
public final String toJsonStringAndClose( final Reader source) throws Exception { StringBuffer sb = new StringBuffer(); int chi; boolean isStartSpaces = false; while ((chi = source.read()) != -1) { char ch = (char) chi; isStartSpaces = addJsonChar(ch, sb, isStartSpaces); } source...
python
def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode='0600'): ''' .. versionadded:: 0.17.0 Create a block device, character device, or fifo pipe. Identical to the gnu mknod. CLI Examples: .. code-block:: bash ...
python
def addTrail(self, offset=None, maxlength=None, n=25, c=None, alpha=None, lw=1): """Add a trailing line to actor. :param offset: set an offset vector from the object center. :param maxlength: length of trailing line in absolute units :param n: number of segments to control precision ...
java
public Long getLong(String nameSpace, String cellName) { return getValue(nameSpace, cellName, Long.class); }
java
public void setRuleGroups(java.util.Collection<SubscribedRuleGroupSummary> ruleGroups) { if (ruleGroups == null) { this.ruleGroups = null; return; } this.ruleGroups = new java.util.ArrayList<SubscribedRuleGroupSummary>(ruleGroups); }
java
@SuppressWarnings("unchecked") public Map toMap() { HashMap map = new HashMap(); map.put("code", code); map.put("message", message); if (data != null) map.put("data", data); return map; }
java
public SDVariable lstmCell(String baseName, LSTMCellConfiguration configuration) { return new LSTMCell(sd, configuration).outputVariables(baseName)[0]; }
python
def local_get_state(self, device, id_override=None, type_override=None): """ Get device state via local API, and fall back to online API. Args: device (WinkDevice): The device the change is being requested for. id_override (String, optional): A device ID used to override...
python
def flash(self, flash): """ Turn on or off flashing of the device's LED for physical identification purposes. """ self.m_objPCANBasic.SetValue(self.m_PcanHandle, PCAN_CHANNEL_IDENTIFYING, bool(flash))
python
def indicators(self, indicator_data): """Generator for indicator values. Some indicator such as Files (hashes) and Custom Indicators can have multiple indicator values (e.g. md5, sha1, sha256). This method provides a generator to iterate over all indicator values. Both the **su...
python
def delete_volume(self, volume_name: str): """Removes/stops a docker volume. Only the manager nodes can delete a volume Args: volume_name (string): Name of the volume """ # Raise an exception if we are not a manager if not self._manager: raise Ru...
python
def removeReader(self, selectable): """Remove a FileDescriptor for notification of data available to read.""" try: if selectable.disconnected: self._reads[selectable].kill(block=False) del self._reads[selectable] else: self._reads[s...
java
@Override public final void visit(final FamilyDocumentMongo document) { gedObject = new Family(parent, new ObjectId(document.getString())); }
python
def calibrate(self, data, calibration): """Calibrate the data.""" tic = datetime.now() channel_name = self.channel_name if calibration == 'counts': res = data elif calibration in ['radiance', 'reflectance', 'brightness_temperature']: # Choose calibration ...
java
public void importAccessControlEntries( CmsRequestContext context, CmsResource resource, List<CmsAccessControlEntry> acEntries) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc)...
python
def default_capability(self): """Set capability name in md. Every ResourceSync document should have the top-level capability attributes. """ if ('capability' not in self.md and self.capability_name is not None): self.md['capability'] = self.capability_name
python
def get_create_options(self): """Returns valid options for ordering a dedicated host.""" package = self._get_package() # Locations locations = [] for region in package['regions']: locations.append({ 'name': region['location']['location']['longName'], ...
python
def load_stylesheet(): """ Loads the stylesheet for use in a pyqt5 application. :return the stylesheet string """ # Smart import of the rc file f = QtCore.QFile(':qdarkgraystyle/style.qss') if not f.exists(): _logger().error('Unable to load stylesheet, file not found in ' ...
python
def replace_baseline_repr(self, linenum, update): """Replace individual baseline representation. :param int linenum: location of baseline representation :param str update: new baseline representation text (with delimiters) """ # use property to access lines to read them from fi...
java
public static void solveBlock( final int blockLength , final boolean upper , final DSubmatrixD1 T , final DSubmatrixD1 B , final boolean transT ,final boolean transB ) { int Trows = T.row1-T.row0; ...
java
public Set<DOCUMENT> query(Iterable<KEY> keys) { return query(keys, d -> true); }
java
@Override public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { OutputStreamWriter outputStreamWriter = null; ...
java
public void registerHanders(String packageString) { List<String> list = AnnotationDetector.scanAsList(ExceptionHandler.class, packageString); for (String handler : list) { // System.out.println(handler); JKExceptionHandler<? extends Throwable> newInstance = JKObjectUtil.newInstance(handler); Class<? e...
java
public long getAndDecrement(T obj) { long prev, next; do { prev = get(obj); next = prev - 1; } while (!compareAndSet(obj, prev, next)); return prev; }
java
public static void updateFilter(FullFrameRect rect, int newFilter) { Texture2dProgram.ProgramType programType; float[] kernel = null; float colorAdj = 0.0f; if (VERBOSE) Log.d(TAG, "Updating filter to " + newFilter); switch (newFilter) { case FILTER_NONE: ...
python
def get_link_text_from_selector(selector): """ A basic method to get the link text from a link text selector. """ if selector.startswith('link='): return selector.split('link=')[1] elif selector.startswith('link_text='): return selector.split('link_text=')[1] return selector
java
public void setChannel(PrivateChannel channel) { if (this.channel != channel) { if (this.channel != null) { ((Cleanupable) this.channel).cleanup(); } this.channel = channel; } }
python
def configure_error_handlers(app): """ Configure application error handlers """ def render_error(error): return (render_template('errors/%s.html' % error.code, title=error_messages[error.code], code=error.code), error.code) for (errcode, title) in error_messages.iteritems(): ...
python
def publish_message(self, exchange, routing_key, properties, body, no_serialization=False, no_encoding=False, channel=None, conn...
java
protected boolean checkvalue(String colorvalue) { boolean valid = validateColorValue(colorvalue); if (valid) { if (colorvalue.length() == 4) { char[] chr = colorvalue.toCharArray(); for (int i = 1; i < 4; i++) { String foo = String.valueOf...
java
private Manifest createManifest( File jar, Map<String, String> manifestentries ) throws MojoExecutionException { JarFile jarFile = null; try { jarFile = new JarFile( jar ); // read manifest from jar Manifest manifest = jarFile.getManifest(); ...
java
public DateFormat getDateFormat(int dateStyle, int timeStyle) { if (dateStyle == DF_NONE && timeStyle == DF_NONE || dateStyle < 0 || dateStyle >= DF_LIMIT || timeStyle < 0 || timeStyle >= DF_LIMIT) { throw new IllegalArgumentException("Illegal date format style argume...
java
public static <T> GenericResponseBuilder<T> notAcceptable(List<Variant> variants) { return GenericResponses.<T>status(Response.Status.NOT_ACCEPTABLE).variants(variants); }
java
public void put(String classname, ClassDescriptor cld) { cld.setRepository(this); // BRJ synchronized (descriptorTable) { descriptorTable.put(classname, cld); List extentClasses = cld.getExtentClasses(); for (int i = 0; i < extentClasses.size(); ++i...
java
public static String toHex(final byte[] data, final String sep) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.length; ++i) { final int no = data[i] & 0xff; if (no < 0x10) sb.append('0'); sb.append(Integer.toHexString(no)); if (sep != null && i < data.length - 1) sb.ap...
java
protected boolean isEquivalentInTheSet(Node node, boolean direction, Set<Node> set) { for (Node eq : direction == UPWARD ? node.getUpperEquivalent() : node.getLowerEquivalent()) { if (set.contains(eq)) return true; boolean isIn = isEquivalentInTheSet(eq, direction, set); if (isIn) return true; } ...
python
def send_data_on_udp(ip_address, port, data): """Helper function to send a string over UDP to a specific IP/port.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.sendto(data.encode('utf-8'), (ip_address, port)) except: LOGGER.exception('Failed to send trace to X-Ray ...
java
public static KFMsgRecord msgrecordGetrecord(String access_token, int endtime, int pageindex, int pagesize, int starttime) { String jsonPostData = String.format("{\"endtime\":%1d,\"pageindex\":%2d,\"pagesize\":%3d,\"starttime\":%4d}", endtime, pageindex, pagesize, starttime); HttpUriReq...
java
public EEnum getRenderingIntentIOCARI() { if (renderingIntentIOCARIEEnum == null) { renderingIntentIOCARIEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(181); } return renderingIntentIOCARIEEnum; }
java
@Override public List<CPAttachmentFileEntry> findByC_C_LtD_S(long classNameId, long classPK, Date displayDate, int status) { return findByC_C_LtD_S(classNameId, classPK, displayDate, status, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
def pyxb_is_v1(pyxb_obj): """ Args: pyxb_obj : PyXB object PyXB object holding an unknown type. Returns: bool: **True** if ``pyxb_obj`` holds an API v1 type. """ # TODO: Will not detect v1.2 as v1. return ( pyxb_obj._element().name().namespace() == d1_common.types.dataon...
python
async def send_photo(self, path, entity): """Sends the file located at path to the desired entity as a photo""" await self.send_file( entity, path, progress_callback=self.upload_progress_callback ) print('Photo sent!')
java
private void grantRecursiveRawAclEntry(String entityPath, String rawAclEntry) throws NotFoundException { Entity[] children = storageDao.getEntityChildren(entityPath); if (children.length == 0) { return; } for (Entity child : children) { grantNodeRawAclEntry(child...
java
private int groupIndexForPoint(int pointIndex) { if (this.pointCoordinates == null || pointIndex < 0 || pointIndex >= this.pointCoordinates.length) { throw new IndexOutOfBoundsException(); } if (this.partIndexes == null) { return 0; } for (int i = 0; i < this.partIndexes.length; ++i) { if (pointInd...
java
@Override public InformationMessage createINF(int cic) { InformationMessage msg = createINF(); CircuitIdentificationCode code = this.parameterFactory.createCircuitIdentificationCode(); code.setCIC(cic); msg.setCircuitIdentificationCode(code); return msg; }
python
def imageinfo(self, files): """ Returns imageinfo query string """ files = '|'.join([safequote(x) for x in files]) self.set_status('imageinfo', files) return self.IMAGEINFO.substitute( WIKI=self.uri, ENDPOINT=self.endpoint, FILES=file...
python
def unpack(self, buff, offset=0): """Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. It is an inplace method and it receives the binary data of the message **without the header**. This...
python
def get_index_range(working_dir): """ Get the bitcoin block index range. Mask connection failures with timeouts. Always try to reconnect. The last block will be the last block to search for names. This will be NUM_CONFIRMATIONS behind the actual last-block the cryptocurrency node knows abou...
java
public void register(Context context) { if (mRegisteredContext != null) { throw new IllegalStateException("Already registered"); } mRegisteredContext = context; context.registerReceiver(this, mPackageFilter); }
python
def export(self, validate=True): """ Method to output the xml as string. It will finalize the batches and then calculate the checksums (amount sum and transaction count), fill these into the group header and output the XML. """ self._finalize_batch() ctrl_sum_tot...
java
public OperationFuture<List<Server>> reboot(Server... serverRefs) { return powerOperationResponse( Arrays.asList(serverRefs), "Reboot", client.reboot(ids(serverRefs)) ); }
java
public static CProduct fetchByUuid_C_Last(String uuid, long companyId, OrderByComparator<CProduct> orderByComparator) { return getPersistence() .fetchByUuid_C_Last(uuid, companyId, orderByComparator); }
java
public int compareSpecificness(final Class<?>[] a, boolean a_varArgs, final Class<?>[] b, boolean b_varArgs) { final int a_fixLen = a.length - (a_varArgs ? 1 : 0); final int b_fixLen = b.length - (b_varArgs ? 1 : 0); final int fixLen = Math.min(a_fixLen, b_fixLen); int c = 0; // result o...
python
def smooth_image(image, sigma, sigma_in_physical_coordinates=True, FWHM=False, max_kernel_width=32): """ Smooth an image ANTsR function: `smoothImage` Arguments --------- image Image to smooth sigma Smoothing factor. Can be scalar, in which case the same sigma is...
java
Response delete(URI uri) { HttpConnection connection = Http.DELETE(uri); return executeToResponse(connection); }
python
def update_user_display_name(user,**kwargs): """ Update a user's display name """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==user.id).one() user_i.display_name = user.display_name return user_i except NoResul...
python
def html(self, text=TEXT): """ Generate an HTML file from the report data. """ self.logger.debug("Generating the HTML report{}..." .format(["", " (text only)"][text])) html = [] for piece in self._pieces: if isinstance(piece, string_types): ...
java
@Override public boolean removeByValue(int value) { int index=binarySearch(value); if(index<0) return false; removeAtIndex(index); return true; }
python
def find_amplitude(chunk): """ Calculate the 0-1 amplitude of an ndarray chunk of audio samples. Samples in the ndarray chunk are signed int16 values oscillating anywhere between -32768 and 32767. Find the amplitude between 0 and 1 by summing the absolute values of the minimum and maximum, and divi...
java
@Override public int advance(int target) throws IOException { reset(); if (docId == NO_MORE_DOCS) { return docId; } else if (target < docId) { // should not happen docId = NO_MORE_DOCS; return docId; } else { // advance 1 int spans1DocId = spans1.spans.docID(); ...
python
def isLocked(self): ''' Checks if the device screen is locked. @return True if the device screen is locked ''' self.__checkTransport() lockScreenRE = re.compile('mShowingLockscreen=(true|false)') dwp = self.shell('dumpsys window policy') m = lockScreenRE...
java
public ServerBuilder http2MaxStreamsPerConnection(long http2MaxStreamsPerConnection) { checkArgument(http2MaxStreamsPerConnection > 0 && http2MaxStreamsPerConnection <= 0xFFFFFFFFL, "http2MaxStreamsPerConnection: %s (expected: a positive 32-bit unsigned integer)", ...
python
def main(command_line=True, **kwargs): """ NAME cit_magic.py DESCRIPTION converts CIT and .sam format files to magic_measurements format files SYNTAX cit_magic.py [command line options] OPTIONS -h: prints the help message and quits. -usr USER: identify u...
python
def from_ranges(ranges, name, data_key, start_key='offset', length_key='length'): """ Creates a list of commands from a list of ranges. Each range is converted to two commands: a start_* and a stop_*. """ commands = [] for r in ranges: data = r[data_key] ...
python
def calculate_error(self): """Estimate the numerical error based on the fluxes calculated by the current and the last method. >>> from hydpy.models.test_v1 import * >>> parameterstep() >>> model.numvars.idx_method = 2 >>> results = numpy.asarray(fluxes.fastaccess._q_resu...
python
def epcrparsethreads(self): """ Parse the ePCR results, and run BLAST on the parsed results """ from Bio import SeqIO # Create the threads for the BLAST analysis for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': threads =...
java
public void addEdge(DiEdge e) { if (edges.add(e)) { int s = e.get1(); int t = e.get2(); addNode(s); addNode(t); predecessors.get(t).add(s); successors.get(s).add(t); } }
python
def min_temperature(self, unit='kelvin'): """Returns a tuple containing the min value in the temperature series preceeded by its timestamp :param unit: the unit of measure for the temperature values. May be among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' :...
java
@Nonnull public AS2ClientResponse sendSynchronous () throws AS2ClientBuilderException { // Perform SMP client lookup performSMPClientLookup (); // Set derivable values setDefaultDerivedValues (); // Verify the whole data set verifyContent (); // Build message // 1. read business ...
java
@Override public void resetValue() { super.resetValue(); this.setSubmittedValue(null); getStateHelper().remove(PropertyKeys.localValueSet); getStateHelper().remove(PropertyKeys.valid); }
java
public List<Map.Entry<String, Float>> analogy(String A, String B, String C, int size) { Vector a = storage.get(A); Vector b = storage.get(B); Vector c = storage.get(C); if (a == null || b == null || c == null) { return Collections.emptyList(); } L...
java
@Override public synchronized void run() { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "run: size=" + ivAllRemoteAsyncResults.size()); if (ivIsCanceled) { //if this instance has been canceled, we ...
java
public Page<Dataset> listDatasets() { // [START bigquery_list_datasets] // List datasets in the default project Page<Dataset> datasets = bigquery.listDatasets(DatasetListOption.pageSize(100)); for (Dataset dataset : datasets.iterateAll()) { // do something with the dataset } // [END bigque...
python
def dynamic_content_item_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/dynamic_content#show-item" api_path = "/api/v2/dynamic_content/items/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
python
def transform_sqlvm_group_output(result): ''' Transforms the result of SQL virtual machine group to eliminate unnecessary parameters. ''' from collections import OrderedDict from msrestazure.tools import parse_resource_id try: resource_group = getattr(result, 'resource_group', None) or p...
java
@Override public void write(TextWriterStream out, String label, Object object) { StringBuilder buf = new StringBuilder(100); if(label != null) { buf.append(label).append('='); } if(object != null) { buf.append(object.toString()); } out.commentPrintLn(buf); }
python
def record_stage_state(self, phase, stage): """Record the completion times of phases and stages""" key = '{}-{}'.format(phase, stage if stage else 1) self.buildstate.state[key] = time()
python
def remote(self): """ Return the remote for this partition :return: """ from ambry.exc import NotFoundError ds = self.dataset if 'remote_name' not in ds.data: raise NotFoundError('Could not determine remote for partition: {}'.format(self.identity.f...
java
public static void splitAssociated( List<AssociatedTriple> pairs , List<Point2D_F64> view1 , List<Point2D_F64> view2 , List<Point2D_F64> view3 ) { for( AssociatedTriple p : pairs ) { view1.add(p.p1); view2.add(p.p2); view3.add(p.p3); } }
java
public static Builder in (TimeZone zone, Locale locale) { return with(Calendar.getInstance(zone, locale)); }
python
def _transpose_dict_list(dict_list): """Transpose a nested dict[list] into a list[nested dict].""" # 1. Unstack numpy arrays into list dict_list = utils.map_nested(np_to_list, dict_list, dict_only=True) # 2. Extract the sequence length (and ensure the length is constant for all # elements) length = {'value...
java
public IJsonMarshaller getJsonMarshaller(Annotation[] annotations) throws JsonMarshallerException { if (annotations != null) { for (Annotation annotation : annotations) { if (JsonUnmarshaller.class.isAssignableFrom(annotation.annotationType())) { return getJsonMarshallerFromAnnotation((JsonUnmarshalle...
python
def xrange(self, stream, start='-', stop='+', count=None): """Retrieve messages from a stream.""" if count is not None: extra = ['COUNT', count] else: extra = [] fut = self.execute(b'XRANGE', stream, start, stop, *extra) return wait_convert(fut, parse_mess...
python
def tarbell_spreadsheet(command, args): """ Open context spreadsheet """ with ensure_settings(command, args) as settings, ensure_project(command, args) as site: try: # First, try to get the Google Spreadsheet URL spreadsheet_url = _google_spreadsheet_url(site.project.SPRE...
java
private void start() { System.out.print("Starting " + DISPLAY_NAME + "..."); System.out.flush(); // Consume configuration from Grakn config file into Cassandra config file initialiseConfig(); Future<Executor.Result> result = daemonExecutor.executeAsync(storageCommand(), graknHo...
java
public static <T, U extends Comparable<? super U>> Collector<T, ?, Seq<T>> maxAllBy(Function<? super T, ? extends U> function) { return maxAllBy(function, naturalOrder()); }
python
def get_params_from_func(func: Callable, signature: Signature=None) -> Params: """Gets all parameters from a function signature. :param func: The function to inspect. :param signature: An inspect.Signature instance. :returns: A named tuple containing information about all, optional, required an...
java
public final int childItemPosition(int childAdapterPosition) { int itemCount = 0; int parentCount = parentItemCount(); for (int i = 0; i < parentCount; i++) { itemCount += 1; if (isExpanded(i)) { int childCount = childItemCount(i); itemCo...