language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _normalize_subplot_ids(fig): """ Make sure a layout subplot property is initialized for every subplot that is referenced by a trace in the figure. For example, if a figure contains a `scatterpolar` trace with the `subplot` property set to `polar3`, this function will make sure the figure's layo...
python
def multiply_frequencies(signal, fs, frange, calibration_frequencies, attendB): """Given a vector of dB attenuations, adjust signal by multiplication in the frequency domain""" npts = len(signal) padto = 1 << (npts - 1).bit_length() X = np.fft.rfft(signal, n=padto) npts = padto f = np....
java
public static Route HEAD(String uriPattern, RouteHandler routeHandler) { return new Route(HttpConstants.Method.HEAD, uriPattern, routeHandler); }
python
def run_example(): r""" Runs the example. """ weather = mc_e.get_weather_data('weather.csv') my_turbine, e126, dummy_turbine = mc_e.initialize_wind_turbines() example_farm, example_farm_2 = initialize_wind_farms(my_turbine, e126) example_cluster = initialize_wind_turbine_cluster(example_far...
python
def list_supported_drivers(): """Returns dictionary with driver classes names as keys.""" def convert_oslo_config(oslo_options): options = [] for opt in oslo_options: tmp_dict = {k: str(v) for k, v in vars(opt).items() if not k.startsw...
python
def delete_event_public_discount(self, id, discount_id, **data): """ DELETE /events/:id/public_discounts/:discount_id/ Deletes a public discount. """ return self.delete("/events/{0}/public_discounts/{0}/".format(id,discount_id), data=data)
java
public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException, IllegalArgumentException { Params.notNull(inputStream, "Input stream"); Params.notNull(outputStream, "Output stream"); Params.isFalse(inputStream instanceof ZipInputStream, "Input stream is ZIP."); Par...
java
protected void setHeadersByAuthorizationPolicy( Message message, URI currentURI ) { Headers headers = new Headers(message); AuthorizationPolicy effectiveAuthPolicy = getEffectiveAuthPolicy(message); String authString = authSupplier.getAuthorization(effectiveAuthPolicy...
python
def rate_limit(function): """Return a decorator that enforces API request limit guidelines. We are allowed to make a API request every api_request_delay seconds as specified in praw.ini. This value may differ from reddit to reddit. For reddit.com it is 2. Any function decorated with thi...
java
public void changePassword(String newPassword) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { if (!connection().isSecureConnection() && !allowSensitiveOperationOverInsecureConnection) { throw new IllegalStateException("Changing password over insecure co...
python
def frustum_height_at_distance(vfov_deg, distance): """Calculate the frustum height (in world units) at a given distance (in world units) from the camera. """ height = 2.0 * distance * np.tan(np.radians(vfov_deg * 0.5)) return height
java
public BoxCollaborationWhitelistExemptTarget.Info getInfo() { URL url = COLLABORATION_WHITELIST_EXEMPT_TARGET_ENTRY_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.GET); BoxJSONResponse respons...
python
def main(argv=None): """Entry point for the `simpl` command.""" # # `simpl server` # logging.basicConfig(level=logging.INFO) server_func = functools.partial(server.main, argv=argv) server_parser = server.attach_parser(default_subparser()) server_parser.set_defaults(_func=server_func) ...
python
def execute_on_key(self, key, entry_processor): """ Applies the user defined EntryProcessor to the entry mapped by the key. Returns the object which is the result of EntryProcessor's process method. :param key: (object), specified key for the entry to be processed. :param entry_...
python
def appendDefaultDrop(self): """ Add a DROP policy at the end of the rules """ self.filters.append('-A INPUT -j DROP') self.filters.append('-A OUTPUT -j DROP') self.filters.append('-A FORWARD -j DROP') return self
java
@Override public final void reportLocalError() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "reportLocalError"); // Only need to set to LOCAL_ERROR // if we are currently OK. We don't want // to overwrite a GLOBAL_ERROR. ...
java
public void init(Record record, Record recHistory, String iHistoryDateSeq, BaseField fldSourceHistoryDate, boolean bCloseOnFree, String strRecHistoryClass, String iSourceHistoryDateSeq) { if (iHistoryDateSeq == null) iHistoryDateSeq = recHistory.getField(recHistory.getFieldCount() - 1).getFieldN...
java
@Override public void onTag(int fieldNumber, FieldDescriptor fieldDescriptor, Object tagValue) { if (payloadStarted) { if (skipping == 0) { AttributeNode<FieldDescriptor, Integer> attrNode = currentNode.getChild(fieldNumber); if (attrNode != null) { // process only 'interesting...
java
private void readResources(Project project, HashMap<BigInteger, ProjectCalendar> calendarMap) { Project.Resources resources = project.getResources(); if (resources != null) { for (Project.Resources.Resource resource : resources.getResource()) { readResource(resource, c...
python
def name2rgb(hue): """Originally used to calculate color based on module name. """ r, g, b = colorsys.hsv_to_rgb(hue / 360.0, .8, .7) return tuple(int(x * 256) for x in [r, g, b])
python
def is_scalar(self): """ :return: :rtype: bool """ return \ isinstance(self._element_template, Boolean) or \ isinstance(self._element_template, Float) or \ isinstance(self._element_template, Integer) or \ isinstance(self._element_t...
java
private void loadAllParts() throws IOException { // Get first boundary String line = _in.readLine(); if (!line.equals(_boundary)) { log.warn(line); throw new IOException("Missing initial multi part boundary"); } // Read each pa...
python
def merge_entities(doc): """Merge entities into a single token. doc (Doc): The Doc object. RETURNS (Doc): The Doc object with merged entities. DOCS: https://spacy.io/api/pipeline-functions#merge_entities """ with doc.retokenize() as retokenizer: for ent in doc.ents: attrs =...
python
def process(self, sched, coro): """Add the timeout in the scheduler, check for defaults.""" super(TimedOperation, self).process(sched, coro) if sched.default_timeout and not self.timeout: self.set_timeout(sched.default_timeout) if self.timeout and self.timeout != -1: ...
java
@Override public MetadataLocation buildObject(String namespaceURI, String localName, String namespacePrefix) { return new MetadataLocationImpl(namespaceURI, localName, namespacePrefix); }
java
@Override public final Manufacture process( final Map<String, Object> pAddParam, final Manufacture pEntity, final IRequestData pRequestData) throws Exception { Manufacture entity = this.prcAccEntityPbCopy .process(pAddParam, pEntity, pRequestData); entity.setItsQuantity(BigDecimal.ZERO...
java
private void unsafeSendRequest(final ChannelHandlerContext ctx, final ByteBuf request, final Promise<DcpResponse> promise) { if (!ctx.executor().inEventLoop()) { throw new IllegalStateException("Must not be called outside event loop"); } ...
python
def _download_linkode(self): """Download content from Linkode pastebin.""" # build the API url linkode_id = self.url.split("/")[-1] if linkode_id.startswith("#"): linkode_id = linkode_id[1:] url = "https://linkode.org/api/1/linkodes/" + linkode_id req = reque...
java
public int write(OutputStreamWithBuffer os, char []cbuf, int off, int len) throws IOException { for (int i = 0; i < len; i++) { write(os, cbuf[off + i]); } return len; }
python
def is_in_team(self, team_id): """Test if user is in team""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.teams or team_id in self.child_teams_ids
python
def function_body(self): """ function_body: '{' (statement)* '}' """ root = FunctionBody() self._process(Nature.LBRACKET) while self.token.nature != Nature.RBRACKET: root.children.append(self.statement()) self._process(Nature.RBRACKET) return...
python
def search_external_subtitles(path, directory=None): """Search for external subtitles from a video `path` and their associated language. Unless `directory` is provided, search will be made in the same directory as the video file. :param str path: path to the video. :param str directory: directory to s...
python
def get_avatar(from_header, size=64, default="retro"): """Get the avatar URL from the email's From header. Args: from_header (str): The email's From header. May contain the sender's full name. Returns: str: The URL to that sender's avatar. """ params = OrderedDict([("s", size), ("d...
python
def NewFromRgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color...
java
private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) { String[] columnNames = associationKey.getMetadata().getRowKeyColumnNames(); Object[] columnValues = new Object[columnNames.length]; for ( int i = 0; i < columnNames.length; i++ ) { String columnNa...
java
public static PersistenceBrokerInternal currentPersistenceBroker(PBKey key) throws PBFactoryException, PersistenceBrokerException { HashMap map = (HashMap) currentBrokerMap.get(); WeakHashMap set; PersistenceBrokerInternal broker = null; if(map == null) {...
java
public Sql[] generateSqlIfExists(final DropSpatialIndexStatement statement, final Database database) { final String catalogName = statement.getTableCatalogName(); final String schemaName = statement.getTableSchemaName(); final String tableName = statement.getTableName(); final SpatialIn...
python
def __write_filter_dic(wk_sheet, column): ''' return filter dic for certain column ''' row1_val = wk_sheet['{0}1'.format(column)].value row2_val = wk_sheet['{0}2'.format(column)].value row3_val = wk_sheet['{0}3'.format(column)].value row4_val = wk_sheet['{0}4'.format(column)].value if r...
java
public static Properties readProperties( InputStream stream, Properties mappings, boolean closeStream ) throws IOException { try { Properties p = new Properties(); p.load( stream ); mappings.putAll( p ); boolean doAgain = true; whil...
python
def filecache(seconds_of_validity=None, fail_silently=False): ''' filecache is called and the decorator should be returned. ''' def filecache_decorator(function): @_functools.wraps(function) def function_with_cache(*args, **kwargs): try: key = _args_key(functi...
java
public Long zcount(Object key, double min, double max) { Jedis jedis = getJedis(); try { return jedis.zcount(keyToBytes(key), min, max); } finally {close(jedis);} }
java
public MapWithProtoValuesFluentAssertion<M> ignoringExtraRepeatedFieldElementsOfFieldsForValues( Iterable<Integer> fieldNumbers) { return usingConfig(config.ignoringExtraRepeatedFieldElementsOfFields(fieldNumbers)); }
python
async def send(self, data, room=None, skip_sid=None, namespace=None, callback=None, **kwargs): """Send a message to one or more connected clients. This function emits an event with the name ``'message'``. Use :func:`emit` to issue custom event names. :param data: The...
java
@Override public String toJSONString() { final JSONObject object = toJSONObject(); if (null != object) { return object.toString(); } return null; }
python
def dist01(graph, weight, source=0, target=None): """Shortest path in a 0,1 weighted graph :param graph: directed graph in listlist or listdict format :param weight: matrix or adjacency dictionary :param int source: vertex :param target: exploration stops once distance to target is found :retur...
java
protected AbstractConfiguration addMixInAnnotations( Class<?> target, Class<?> mixinSource ) { mapMixInAnnotations.put( target, mixinSource ); return this; }
java
@SuppressWarnings("unchecked") public static <T extends Number> T isNumber( String value, Class<T> adaptee ) { if (value == null) { return null; } if (adaptee == null) { adaptee = (Class<T>) Double.class; } if (adaptee.isAssignableFrom(Double.class)) {...
java
public Vector3d fma(Vector3dc a, Vector3dc b) { return fma(a, b, thisOrNew()); }
java
private boolean isNullified(Object target, Field field) { Class<?> type = field.getType(); Object value = null; try { value = field.get(target); } catch (IllegalArgumentException | IllegalAccessException e) { throw new IrohException(e); ...
java
public List<Relationship> getPrerequisiteRelationships() { final List<Relationship> prerequisiteRelationships = new LinkedList<Relationship>(); for (final Relationship r : relationships) { if (r.getType() == RelationshipType.PREREQUISITE) { prerequisiteRelationships.add(r); ...
python
def _reverse_queue(self): u"""When socket.timeout has occurred for Zabbix server, this method is called. Enqueue items in self.pool[]. """ while self.pool: item = self.pool.pop() self.queue.put(item, block=False)
java
@Provides protected TvShowCollectionRendererBuilder provideTvShowCollectionRendererBuilder( Context context) { List<Renderer<TvShowViewModel>> prototypes = new LinkedList<Renderer<TvShowViewModel>>(); prototypes.add(new TvShowRenderer(context)); return new TvShowCollectionRendererBuilder(prototypes); ...
java
private Type extractContainingType(Attribute.Compound ca, DiagnosticPosition pos, TypeSymbol annoDecl) { // The next three checks check that the Repeatable annotation // on the declaration of the annotation type that is re...
python
def _blkid_output(out, fs_type=None): ''' Parse blkid output. ''' flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split('\n\n')): dev = {} for items in flt(dev_meta.strip().split('\n')): key, val = items.split('=', 1) ...
java
public void setAdditionalTreatments(java.util.Collection<TreatmentResource> additionalTreatments) { if (additionalTreatments == null) { this.additionalTreatments = null; return; } this.additionalTreatments = new java.util.ArrayList<TreatmentResource>(additionalTreatments...
java
private static boolean obtainLicenseAgreement(LicenseProvider licenseProvider) { // Prompt for word-wrapped display of license agreement & information boolean view; SelfExtract.wordWrappedOut(SelfExtract.format("showAgreement", "--viewLicenseAgreement")); view = SelfExtract.getResponse(...
java
public void add(String name, V value) { List<V> lo = get(name); if (lo == null) { lo = new ArrayList<>(); } lo.add(value); super.put(name, lo); }
python
def serve_forever(self): """Call the main loop.""" # Set the server login/password (if -P/--password tag) if self.args.password != "": self.add_user(self.args.username, self.args.password) # Serve forever self.server.serve_forever()
java
public PubsubFuture<Void> deleteTopic(final String project, final String topic) { return deleteTopic(canonicalTopic(project, topic)); }
java
public SimpleArrayGrid view(int offset, int width) { return new SimpleArrayGrid(array, width, height, this.offset + offset, length, boxed); }
python
def _tokenize_chinese_chars(self, text): """Adds whitespace around any CJK character.""" output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") ...
python
def get_pixbeam(self, ra, dec): """ Determine the beam in pixels at the given location in sky coordinates. Parameters ---------- ra , dec : float The sly coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools....
python
def visit_Assign(self, node): """ Create Assign node for final Cxx representation. It tries to handle multi assignment like: >> a = b = c = 2 If only one local variable is assigned, typing is added: >> int a = 2; TODO: Handle case of multi-assignement for som...
java
private static boolean scanArchive(Connector cmd) { if (cmd == null) return true; if (cmd.getVersion() == Version.V_16 || cmd.getVersion() == Version.V_17) { if (!cmd.isMetadataComplete()) return true; } return false; }
java
public static boolean lasRecordEqual( LasRecord dot1, LasRecord dot2 ) { double delta = 0.000001; boolean check = NumericsUtilities.dEq(dot1.x, dot2.x, delta); if (!check) { return false; } check = NumericsUtilities.dEq(dot1.y, dot2.y, delta); if (!check) { ...
python
def blob_get(self, table, digest, chunk_size=1024 * 128): """ Returns a file like object representing the contents of the blob with the given digest. """ response = self._request('GET', _blob_path(table, digest), stream=True) if response.status == 404: raise D...
python
def _get_spot_history(ctx, instance_type): """ Returns list of 1,000 most recent spot market data points represented as SpotPriceHistory objects. Note: The most recent object/data point will be first in the list. :rtype: list[SpotPriceHistory] """ one_week_ago = datetime.datetime.now() - datet...
java
public java.util.List<AvailableProcessorFeature> getValidProcessorFeatures() { if (validProcessorFeatures == null) { validProcessorFeatures = new com.amazonaws.internal.SdkInternalList<AvailableProcessorFeature>(); } return validProcessorFeatures; }
java
public <T> T mock(Class<T> typeToMock) { return mock(typeToMock, namingScheme.defaultNameFor(typeToMock)); }
java
public void setRestrictions(List<IRule> rulesNew) throws CDKException { Iterator<IRule> itRules = rulesNew.iterator(); while (itRules.hasNext()) { IRule rule = itRules.next(); if (rule instanceof ElementRule) { mfRange = (MolecularFormulaRange) ((Object[]) rule.g...
java
public void setSecrets(java.util.Collection<Secret> secrets) { if (secrets == null) { this.secrets = null; return; } this.secrets = new com.amazonaws.internal.SdkInternalList<Secret>(secrets); }
python
def xtime(b, n): """Repeated polynomial multiplication in GF(2^8).""" b = b.reshape(8) for _ in range(n): b = exprzeros(1) + b[:7] ^ uint2exprs(0x1b, 8) & b[7]*8 return b
python
def add_values_to_bundle_safe(connection, bundle, values): """ Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added. Args: connection: An opened Connection instance. bundle: Bundle instance to add values in. values: Values, ...
java
public Observable<Page<DeletedSiteInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<DeletedSiteInner>>, Page<DeletedSiteInner>>() { @Override public Page<DeletedSiteInner> call(...
java
public Matrix4f translate(float x, float y, float z, Matrix4f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.translation(x, y, z); return translateGeneric(x, y, z, dest); }
java
static int calculateChecksum(ByteBuf data, int offset, int length) { Crc32c crc32 = new Crc32c(); try { crc32.update(data, offset, length); return maskChecksum((int) crc32.getValue()); } finally { crc32.reset(); } }
java
public synchronized void synchronizeWith(UpdateSynchronizer newsync) { // LoggingUtil.warning("Synchronizing: " + sync + " " + newsync, new // Throwable()); if(synchronizer == newsync) { LoggingUtil.warning("Double-synced to the same plot!", new Throwable()); return; } if(synchronizer !=...
java
public static SqlInfo getSqlInfoSimply(String nsAtZealotId, Object paramObj) { String[] arr = nsAtZealotId.split(ZealotConst.SP_AT); if (arr.length != LEN) { throw new ValidFailException("nsAtZealotId参数的值必须是xml文件中的 nameSpace + '@@' + zealotId 节点的值," + "如:'student@@queryS...
python
def setWorkingPlayAreaSize(self, sizeX, sizeZ): """Sets the Play Area in the working copy.""" fn = self.function_table.setWorkingPlayAreaSize fn(sizeX, sizeZ)
python
def fill_missing_fields(self, data, columns): """ This method fills with 0's missing fields :param data: original Pandas dataframe :param columns: list of columns to be filled in the DataFrame :type data: pandas.DataFrame :type columns: list of strings :returns: Pandas...
python
def get_services_supported(self): """Return a ServicesSupported bit string based in introspection, look for helper methods that match confirmed and unconfirmed services.""" if _debug: Application._debug("get_services_supported") services_supported = ServicesSupported() # look t...
java
public final int compare(final Activation existing, final Activation adding) { final int s1 = existing.getSalience(); final int s2 = adding.getSalience(); if ( s1 > s2 ) { return 1; } else if ( s1 < s2 ) { return -1; } ...
python
def FromReplica(self, replica): """ Get AccountState object from a replica. Args: replica (obj): must have ScriptHash, IsFrozen, Votes and Balances members. Returns: AccountState: """ return AccountState(replica.ScriptHash, replica.IsFrozen, repli...
java
private JSONObject setInternal( String key, Object value, JsonConfig jsonConfig ) { return _setInternal( key, processValue( key, value, jsonConfig ), jsonConfig ); }
python
def to_dict(self, omit=()): """ Return a (shallow) copy of self cast to a dictionary, optionally omitting some key/value pairs. """ result = self.__dict__.copy() for key in omit: if key in result: del result[key] return result
java
private static void checkExtraFields(JSTuple tuple, int startCol, int count) throws JMFSchemaViolationException { for (int i = startCol; i < count; i++) { JMFType field = tuple.getField(i); if (field instanceof JSVariant) { JMFType firstCase = ((JSVariant)field).getCase(0); if (firstCase...
python
def insert(self, index, option): """ Insert a new `option` in the Combo at `index`. :param int option: The index of where to insert the option. :param string option: The option to insert into to the Combo. """ option = str(option) self._o...
java
protected synchronized IndexWriter getIndexWriter() throws IOException { if (indexReader != null) { indexReader.close(); log.debug("closing IndexReader."); indexReader = null; } if (indexWriter == null) { IndexWriterConfig config = new IndexWriterConf...
java
public static PropertyDocument makePropertyDocument( PropertyIdValue propertyId, List<MonolingualTextValue> labels, List<MonolingualTextValue> descriptions, List<MonolingualTextValue> aliases, List<StatementGroup> statementGroups, DatatypeIdValue datatypeId) { return makePropertyDocument(propertyId, label...
python
def complete(self): """ Consider a transcript complete if it has start and stop codons and a coding sequence whose length is divisible by 3 """ return ( self.contains_start_codon and self.contains_stop_codon and self.coding_sequence is not None...
python
def isglob(value): """ Windows non traduce automaticamente i wildchars così lo facciamo a mano tramite glob. :param value: Espressione glob per la lista dei files. :type value: str """ if os.name == 'nt': if isinstance(value, basestring): value = glob.glob(value) ret...
java
public ListAccountSasResponseInner listAccountSAS(String resourceGroupName, String accountName, AccountSasParameters parameters) { return listAccountSASWithServiceResponseAsync(resourceGroupName, accountName, parameters).toBlocking().single().body(); }
python
def middle(self): """ Returns the middle point of the bounding box :return: middle point :rtype: (float, float) """ return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2
python
def input_identity(interface = TerminalInterface()): """Get the full name, email address and SMTP information from the user.""" while True: identity = interface.input_fields(""" In order to send your files via email, I need to get your name and email address you will be using to s...
python
def parameterized_expectations(model, verbose=False, initial_dr=None, pert_order=1, with_complementarities=True, grid={}, distribution={}, maxit=100, tol=1e-8, inner_maxit=10, direct=False): ...
python
def matrix_str(p, decimal_places=2, print_zero=True, label_columns=False): '''Pretty-print the matrix.''' return '[{0}]'.format("\n ".join([(str(i) if label_columns else '') + vector_str(a, decimal_places, print_zero) for i, a in enumerate(p)]))
java
public Subscription changeOfferChangeCaptureDateAndRefund( String subscription, Offer offer ) { return changeOfferChangeCaptureDateAndRefund( new Subscription( subscription ), offer ); }
java
private static List<Class<?>> getAncestorClasses(Object o, Predicate<? super Class<?>> predicate) { if (o == null) { return Collections.emptyList(); } List<Class<?>> matches = new ArrayList<>(); Set<Class<?>> seen = new HashSet<>(); Queue<Class<?>> queue = new LinkedList<>(); ...
java
public static boolean is_yay(String str) { if (is_yan(str) || is_vargiya5(str) || is_vargiya4(str) || is_vargiya3(str) || is_vargiya2(str) || is_vargiya1(str)) return true; return false; }
java
protected static String printException(final Throwable throwable) { if (null == throwable) { return null; } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(baos); throwable.printStackTrace(prin...