language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def build_headers(self): ''' Return the list of headers as two-tuples ''' if not 'Content-Type' in self.headers: content_type = self.content_type if self.encoding != DEFAULT_ENCODING: content_type += '; charset=%s' % self.encoding self....
python
def _insert_item(self, key, new_item, instance, is_after): """Insert a new item before or after another item""" index = self._get_index_for_insert(key, instance) index = index + 1 if is_after else index self.__items = self.__items[:index] + new_item + self.__items[index:] # Make ...
java
static String autoId() { StringBuilder builder = new StringBuilder(); int maxRandom = AUTO_ID_ALPHABET.length(); for (int i = 0; i < AUTO_ID_LENGTH; i++) { builder.append(AUTO_ID_ALPHABET.charAt(RANDOM.nextInt(maxRandom))); } return builder.toString(); }
python
def _define_absl_flags(self, absl_flags): """Defines flags from absl_flags.""" key_flags = set(absl_flags.get_key_flags_for_module(sys.argv[0])) for name in absl_flags: if name in _BUILT_IN_FLAGS: # Do not inherit built-in flags. continue flag_instance = absl_flags[name] # ...
python
def get_toplevel_params(voevent): """ Fetch ungrouped Params from the `What` section of a voevent as an omdict. This fetches 'toplevel' Params, i.e. those not enclosed in a Group element, and returns them as a nested dict-like structure, keyed like ParamName->AttribName. Note that since multip...
java
public void setContentAction(Action.OnActionListener listener, ComponentName activity, Bundle extra) { setContentAction(listener, activity, null, null, extra); }
java
private Label getLabel(String pane) { Label lbl = root.findByName(pane, Label.class); return lbl == null ? createLabel(pane) : lbl; }
python
def get_all_offers(self, params=None): """ Get all offers This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param params: search params :return: list """ if not ...
python
def density(self): """ Returns the density in units of g/cc """ m = Mass(self.composition.weight, "amu") return m.to("g") / (self.volume * Length(1, "ang").to("cm") ** 3)
python
def _task_batcher(tasks, batch_size=None): """Batches large task lists into groups of 100 so that they can all be inserted. """ from itertools import izip_longest if not batch_size: batch_size = DEFAULT_TASK_BATCH_SIZE # Ensure the batch size is under the task api limit. batch_size...
python
def MakeRequest(self, data): """Make a HTTP Post request to the server 'control' endpoint.""" stats_collector_instance.Get().IncrementCounter("grr_client_sent_bytes", len(data)) # Verify the response is as it should be from the control endpoint. respo...
java
public void centerHorizontally(int top) { if (Position.FIXED.getCssName().equals(getElement().getStyle().getPosition())) { show(); // keep position fixed, as may have been set to absolute setPositionFixed(); int left = (Window.getClientWidth() - getOffsetWidth())...
python
def add_softmax(self, name, input_name, output_name): """ Add a softmax layer to the model. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str The output ...
python
def symm_reduce(self, coords_set, threshold=1e-6): """ Reduces the set of adsorbate sites by finding removing symmetrically equivalent duplicates Args: coords_set: coordinate set in cartesian coordinates threshold: tolerance for distance equivalence, used ...
python
def connection(self): """ A context manager that returns a connection to the server using some *session*. """ conn = self.session(**self.options) try: for item in self.middlewares: item(conn) yield conn finally: ...
java
@Override public void nextTuple() { if (this.reloadConfig && this.watcher != null) { Map<String, Object> reloadedConfig = null; try { reloadedConfig = this.watcher.readIfUpdated(); } catch (IOException ex) {...
python
def initialize(config): """Initialize method. :param config: current application config, injected :type config: Config """ service_injection_config = config.get('SERVICE_INJECTION', ()) if not isinstance(service_injection_config, (tuple, list)): service_inje...
java
public static byte[] hexToBytes(String s) { try { if (s == null) return new byte[0]; s = s.toUpperCase(); int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s...
python
def convertToIntRange(val, minValue, maxValue, invalidDefault, emptyValue=''): ''' converToIntRange - Convert input value to an integer within a certain range @param val <None/str/int/float> - The input value @param minValue <None/int> - The minimum value (inclusive), o...
java
private <RowT> ServerStreamingCallable<Query, RowT> createReadRowsCallable( ServerStreamingCallSettings<Query, Row> readRowsSettings, RowAdapter<RowT> rowAdapter) { ServerStreamingCallable<ReadRowsRequest, RowT> merging = new RowMergingCallable<>(stub.readRowsCallable(), rowAdapter); // Copy set...
java
public static void getCommandResultIntoStream( CommandLine cmdLine, File dir, int expectedExit, long timeout, OutputStream stream) throws IOException { getCommandResultIntoStream(cmdLine, dir, expectedExit, timeout, stream, null); }
python
def shuffled_indices_batch_iterator(self, batch_size, shuffle_rng): """ Create an iterator that generates randomly shuffled mini-batches of sample indices. The batches will have `batch_size` elements. The generated mini-batches indices take the form of 1D NumPy integer arrays. ...
python
def clean(self,x): """remove nan and inf rows from x""" return x[~np.any(np.isnan(x) | np.isinf(x),axis=1)]
python
def _add_rule(self, group, role, value): """Implementation detail""" if role not in group: group[role] = list() group[role].append(value) self.invalidate()
java
public Allocation allocate(Mutation mutation, int size) { CommitLogSegment segment = allocatingFrom(); Allocation alloc; while ( null == (alloc = segment.allocate(mutation, size)) ) { // failed to allocate, so move to a new segment with enough room advanceAll...
python
def store(self, key, value): """Add new record to cache key: entry key value: data of entry """ self.client.set(key, value, time=self.timeout)
java
protected String parseScope(ProgramElementDoc doc) { if (doc.isPrivate()) { return "private"; } else if (doc.isProtected()) { return "protected"; } else if (doc.isPublic()) { return "public"; } return ""; }
python
def logical_and_expr(self): """ logical_and_expr: logical_not_expr ('and' logical_not_expr)* """ node = self.logical_not_expr() while self.token.nature == Nature.AND: token = self.token self._process(Nature.AND) node = BinaryOperation(left=no...
python
def bgr2rgb(self): """ Converts data using the cv conversion. """ new_data = cv2.cvtColor(self.raw_data, cv2.COLOR_BGR2RGB) return ColorImage(new_data, frame=self.frame, encoding='rgb8')
java
void toggleSecureServer() { if (m_fieldSecureServer.isEmpty()) { m_fieldExclusiveURL.setEnabled(false); m_fieldExclusiveError.setEnabled(false); return; } m_fieldExclusiveURL.setEnabled(true); m_fieldExclusiveError.setEnabled(true); }
java
private void blur(Bitmap bkg, View view) { long startMs = System.currentTimeMillis(); //define layout params to the previous imageView in order to match its parent mBlurredBackgroundLayoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameL...
java
void fillInConstraintMatrix( ) { int N = listHInv.size(); A.reshape(N*numberOfConstraints(),6); if( A.numRows < notZeros.size ) { throw new IllegalArgumentException("More unknowns than equations"); } double b = knownAspectRatio ? aspectRatio*aspectRatio : 1; for (int i = 0,idx=0; i < N; i++) { Homo...
python
def code128(self, data, **kwargs): """Renders given ``data`` as **Code 128** barcode symbology. :param str codeset: Optional. Keyword argument for the subtype (code set) to render. Defaults to :attr:`escpos.barcode.CODE128_A`. .. warning:: You should draw up your data ...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "PassThroughOperation", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "_SingleOperation") public JAXBElement<PassThroughOperationType> createPassThroughOperation(PassThroughOperationType value) { return new J...
java
public static void step(long seed, Neurons[] neurons, DeepLearningModel.DeepLearningModelInfo minfo, boolean training, double[] responses) { try { for (int i=1; i<neurons.length-1; ++i) { neurons[i].fprop(seed, training); } if (minfo.get_params().autoencoder) { neurons[neurons.leng...
python
def rst_filename_rel_autodoc_index(self, index_filename: str) -> str: """ Returns the filename of the target RST file, relative to a specified index file. Used to make the index refer to the RST. """ index_dir = dirname(abspath(expanduser(index_filename))) return relpath(...
java
public void marshall(PutFileRequest putFileRequest, ProtocolMarshaller protocolMarshaller) { if (putFileRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(putFileRequest.getRepositoryName(), R...
python
def derived_from_all(self, identities: List[QualName]) -> MutableSet[QualName]: """Return list of identities transitively derived from all `identity`.""" if not identities: return set() res = self.derived_from(identities[0]) for id in identities[1:]: res &= self.d...
java
public void marshall(Point point, ProtocolMarshaller protocolMarshaller) { if (point == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(point.getX(), X_BINDING); protocolMarshaller.marshal...
java
public Map<String, Float> getTermAndRank(List<Term> termList) { List<String> wordList = new ArrayList<String>(termList.size()); for (Term t : termList) { if (shouldInclude(t)) { wordList.add(t.word); } } // System.out.println...
java
@Override public synchronized void setFrame(final CEMILData frame) { if (!frame.getDestination().equals(getKey())) throw new KNXIllegalArgumentException("frame key differs from this key"); if (!max) ensureCapacity(); else if (!overwrite && size == timestamps.length) return; final CEMILData[] c = (CEM...
java
public Observable<VpnClientIPsecParametersInner> getVpnclientIpsecParametersAsync(String resourceGroupName, String virtualNetworkGatewayName) { return getVpnclientIpsecParametersWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<VpnClientIPsecParametersInner>, V...
python
def dataframe(self): """ Returns a pandas DataFrame containing all other class properties and values. The index for the DataFrame is the boxscore string. """ if self._points_allowed is None and self._points_scored is None: return None fields_to_include = { ...
java
public static <R> DoubleFunction<R> doubleFunction(CheckedDoubleFunction<R> function, Consumer<Throwable> handler) { return t -> { try { return function.apply(t); } catch (Throwable e) { handler.accept(e); throw new IllegalStat...
java
@Override public T get() throws InterruptedException { while (true) { synchronized (this) { if (completed) { return results == null || results.isEmpty() ? null : results.get(0); } ...
java
public static <E> Iterator<E> cycle(Iterable<E> iterable) { dbc.precondition(iterable != null, "cannot cycle a null iterable"); return new CyclicIterator<E>(iterable.iterator()); }
python
def configure(self, **kwargs): ''' Convenience function to set a number of parameters on this logger and associated handlers and formatters. ''' for kwarg in kwargs: value = kwargs[kwarg] if kwarg == 'level': self.set_level(value) ...
java
@Override public VoltTable runDML(String dml) { String modifiedDml = transformDML(dml); printTransformedSql(dml, modifiedDml); return super.runDML(modifiedDml, false); }
java
@Override public Collection<Asset<?>> assets(boolean useCache) { if (useCache && !cache.isEmpty()) { return new ArrayList<>(cache); } return assets(); }
java
protected byte[] getFieldAsBytes(GenericRecord record, String fieldLocation) throws Exception { Optional<Object> bytesValue = AvroUtils.getFieldValue(record, fieldLocation); if (!bytesValue.isPresent()) { throw new Exception("Bytes value with key " + fieldLocation + " not found in the record"); } ...
python
def main(args): """ Entry point: train or test. """ json.dump(vars(args), open(os.path.join(args.output_dir, 'config.json'), 'w')) if args.gpu_id == -1: ctx = mx.cpu() else: ctx = mx.gpu(args.gpu_id) mx.random.seed(args.seed, ctx=ctx) if args.mode == 'train': t...
python
def _collect_values(handlers, names, user, client, values): """ Get the values from the handlers of the requested claims. """ results = {} def visitor(claim_name, func): data = {'user': user, 'client': client} data.update(values.get(claim_name) or {}) claim_value = func(data) ...
java
public static byte[] loadBytes(URL url) { byte[] bytes = null; try { bytes = loadBytes(url.openStream()); } catch (IOException ex) { // ex.printStackTrace(); } return bytes; }
java
public List<String> getProperties(TableRef tableRef) { List<String> result = new ArrayList<String>(); TableMapping tableMapping = mappedClasses.get(tableRef); if (tableMapping == null) return result; for (ColumnMetaData columnMetaData : tableMapping.getMappedColumns()) { Colu...
java
private Reader getResourceReader(String resource) throws ResourceNotFoundException { List<Class<?>> excluded = new ArrayList<>(); excluded.add(ILessCssResourceGenerator.class); return rsReaderHandler.getResource(bundle, resource, false, excluded); }
java
public BandLU factor(BandMatrix A, boolean inplace) { if (inplace) return factor(A); else return factor(new BandMatrix(A, kl, kl + ku)); }
java
private RedBlackTreeNode<Key, Value> floor(RedBlackTreeNode<Key, Value> x, Key key) { if (x == null) { return null; } int cmp = key.compareTo(x.getKey()); if (cmp == 0) { return x; } if (cmp < 0) { return floor(x.getLeft(), key); } RedBlackTreeNode<Key, Value> t = floor(x.getRight(), key); if (t...
java
private CmsClientTemplateBean getTemplateBean(CmsObject cms, CmsResource resource) throws CmsException { CmsProperty titleProp = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, false); CmsProperty descProp = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_DESCRIPT...
java
public static boolean containsUnspecifiedAttributes(Tag tag, String[] standardAttributesSorted) { for (TagAttribute attribute : tag.getAttributes().getAll()) { final String name = attribute.getLocalName(); if (Arrays.binarySearch(standardAttributesSorted, name) < 0) ...
python
def is_lossy(label): """Check Label file for the compression type. """ val = getkey(from_=label, keyword='INST_CMPRS_TYPE').decode().strip() if val == 'LOSSY': return True else: return False
python
def register(self, condition_set): """ Registers a condition set with the manager. >>> condition_set = MyConditionSet() #doctest: +SKIP >>> gargoyle.register(condition_set) #doctest: +SKIP """ if callable(condition_set): condition_set = condition_set() ...
java
@Override public String dialogScriptSubmit() { if (useNewStyle()) { return super.dialogScriptSubmit(); } StringBuffer result = new StringBuffer(512); result.append("function submitAction(actionValue, theForm, formName) {\n"); result.append("\tif (theForm == null)...
python
def country_map(code): ''' Country mapping ''' code = str(code).upper() global _country_maps return _country_maps.get(code, code)
java
public static IDBAccess createDBAccess(DBType dbType, Properties properties, AuthToken authToken) { return createDBAccess(dbType, properties, null, null, authToken); }
python
def com_google_fonts_check_metadata_italic_style(ttFont, font_metadata): """METADATA.pb font.style "italic" matches font internals?""" from fontbakery.utils import get_name_entry_strings from fontbakery.constants import MacStyle if font_metadata.style != "italic": yield SKIP, "This check only applies to it...
java
protected <T> Parameter<T> createParameter(String parameterName, Class<T> parameterType, EnumSet<Metadata> parameterMetadata) { if ((parameterName == null) || (parameterName.trim().length...
python
def create_api_errorhandler(**kwargs): r"""Create an API error handler. E.g. register a 404 error: .. code-block:: python app.errorhandler(404)(create_api_errorhandler( status=404, message='Not Found')) :param \*\*kwargs: It contains the ``'status'`` and the ``'message'`` ...
java
@SuppressWarnings("ObjectAllocationInLoop") public void add(NodeBase source, NodeBase dest) { // amount of commutative nodes int n = 0; for (NodeBase node : source.getDescendants()) { if (node instanceof CommutativeOperator) { n++; } } ...
java
public Integer getInt(String column) { Number n = getNumber(column); return n != null ? n.intValue() : null; }
java
public String processString(String s) { if (decoderPipeline != null) { return decoderPipeline.processString(s); } else { throw new java.lang.RuntimeException("Decoder Not Initialized"); } }
java
public void marshall(RejectCertificateTransferRequest rejectCertificateTransferRequest, ProtocolMarshaller protocolMarshaller) { if (rejectCertificateTransferRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
java
public CacheEntry filterEntry(String cacheName, CacheEntry cacheEntry) { InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName); try { invalidationTableList.readWriteLock.readLock().lock(); return internalFilterEntry(cacheName, invalidationTableList, cacheEntry); } finally { ...
java
public Object decode(Object object) throws DecoderException { try { char[] charArray = object instanceof String ? ((String) object).toCharArray() : (char[]) object; return decodeHex(charArray); } catch (ClassCastException e) { throw new DecoderException(e.getMessage()); } }
java
public void freeUseCount() { if (_indirectSource != null) { _indirectSource.freeUseCount(); } else if (_useCount != null) { if (_useCount.decrementAndGet() < 0) { closeSelf(); } } }
python
def flux_producers(F, rtol=1e-05, atol=1e-12): r"""Return indexes of states that are net flux producers. Parameters ---------- F : (n, n) ndarray Matrix of flux values between pairs of states. rtol : float relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx)...
python
def unique(iterable): """ Generator yielding each element only once. Note: May consume lots of memory depending on the given iterable. """ yielded = set() for i in iterable: if i in yielded: continue yield i yielded.add(i)
python
def fit(self): """Fit MCMC AgeDepthModel""" self._mcmcfit = self.mcmcsetup.run() self._mcmcfit.burnin(self.burnin) dmin = min(self._mcmcfit.depth_segments) dmax = max(self._mcmcfit.depth_segments) self._thick = (dmax - dmin) / len(self.mcmcfit.depth_segments) self...
python
def _isSetter(node_type, node): """ Determine whether the given node is a setter property. @param node_type: The type of the node to inspect. @param node: The L{logilab.astng.bases.NodeNG} to inspect. @return: a boolean indicating if the given node is a setter. """ if node_type not in ['fu...
java
public void set(Object data, int iOpenMode) throws DBException, RemoteException { int iErrorCode = this.checkCurrentCacheIsPhysical(data); if (iErrorCode != Constants.NORMAL_RETURN) throw new DBException(iErrorCode); // Data probably changed from last time I read it. m_tableRemo...
java
public long[] toLongArray() { long[] copy = new long[size]; for (int i = 0; i < size; i++) { copy[i] = elements[i]; } return copy; }
python
async def on_raw_notice(self, message): """ Modify NOTICE to redirect CTCP messages. """ nick, metadata = self._parse_user(message.source) target, msg = message.params if is_ctcp(msg): self._sync_user(nick, metadata) type, response = parse_ctcp(msg) ...
java
public static base_response disable(nitro_service client, String trapname) throws Exception { snmpalarm disableresource = new snmpalarm(); disableresource.trapname = trapname; return disableresource.perform_operation(client,"disable"); }
python
def add_edge(self, source, target): """Returns a new edge connecting source and target vertices. Args: source: The source Vertex. target: The target Vertex. Returns: A new Edge linking source to target. """ edge = Edge(len(self.edges)) self.edges.append(edge) source.out_e...
python
def run(self, gates, n_qubits, *args, **kwargs): """Run the backend.""" return self._run(gates, n_qubits, args, kwargs)
python
def import_class(clspath): """Given a clspath, returns the class. Note: This is a really simplistic implementation. """ modpath, clsname = split_clspath(clspath) __import__(modpath) module = sys.modules[modpath] return getattr(module, clsname)
java
private void recursiveParseProperties( ITransaction transaction, String currentPath, HttpServletRequest req, XMLWriter generatedXML, int propertyFin...
java
public void addNode(Node node) { // channel 可能为 null ChannelWrapper channel = appContext.getChannelManager().getChannel(node.getGroup(), node.getNodeType(), node.getIdentity()); Set<JobClientNode> jobClientNodes = NODE_MAP.get(node.getGroup()); if (jobClientNodes == null) { ...
python
def bind(self, binding, parameters): """ Create the binding Args: binding (AtlasServiceBinding.Binding): Existing or New binding parameters (dict): Parameters for the binding Returns: Binding: Status Raises: ...
java
@Nonnull public PMessageBuilder<T, F> addTo(@Nonnull F field, Object value) { return addTo(field.getId(), value); }
python
def btc_bitcoind_tx_serialize( tx ): """ Convert a *Bitcoind*-given transaction into its hex string. tx format is {'vin': [...], 'vout': [...], 'locktime': ..., 'version': ...}, with the same formatting rules as getrawtransaction. (in particular, each value in vout is a Decimal, in BTC) ...
python
def rebuild(self): """ Rebuilds the scene based on the current settings. :param start | <QDate> end | <QDate> """ gantt = self.ganttWidget() scale = gantt.timescale() rect = self.sceneRect() header = gantt.tree...
java
public static <V,T,R> Function1<V, R> andThen(final Function1<? super V, ? extends T> before, final Function1<? super T, ? extends R> after) { return compose(after, before); }
java
@Override public int prepare(Xid xid) throws XAException { try { LOG.debug("PhynixxXAResource[" + this.getId() + "]:prepare prepare to perform a commit for XID=" + xid); XATransactionalBranch<C> transactionalBranch = this.xaConnection.toGlobalTransactionBranch(); if (xid...
java
public static int invertedCompare(Solution s1, Solution s2) { int flag = InvertedCompareUtils.ConstraintCompare(s1, s2); if (flag == 0) { flag = InvertedCompareUtils.ParetoObjectiveCompare(s1, s2); } return flag; }
java
@Override public void isLeader() { LOG.warn("Server instance with server id {} is elected as leader", serverId); serviceState.becomingActive(); try { for (ActiveStateChangeHandler handler : activeStateChangeHandlers) { handler.instanceIsActive(); } ...
java
public List<Category> getLEXCategories() { ClientResource resource = new ClientResource(Route.LEX_CATEGORY.url()); try { Representation repr = resource.get(); return mapper.readValue(repr.getText(), new TypeReference<List<Category>>() {}); } catch (IOException ex) { ...
python
def main(): ''' Bootstrapper CLI ''' parser = argparse.ArgumentParser(prog='kclboot', description='kclboot - Kinesis Client Library Bootstrapper') subparsers = parser.add_subparsers(title='Subcommands', help='Additional help', dest='subparser') # Common arguments jar_path_parser =...
java
protected final QueryEngine queryEngine() { if (queryEngine == null) { try { engineInitLock.lock(); if (queryEngine == null) { QueryEngineBuilder builder = null; if (!repoConfig.getIndexProviders().isEmpty()) { ...
java
protected List<Item> parseItems(final Element rssRoot, final Locale locale) { final List<Item> items = new ArrayList<Item>(); for (final Element item : getItems(rssRoot)) { items.add(parseItem(rssRoot, item, locale)); } return items; }
java
public final void deleteSession(SessionName name) { DeleteSessionRequest request = DeleteSessionRequest.newBuilder().setName(name == null ? null : name.toString()).build(); deleteSession(request); }