language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def add_cell_argument(self, name, help, required=False): """ Add a cell only argument. Args: name: name of the argument. No need to start with "-" or "--". help: the help string of the argument. required: Whether it is required in cell content. """ for action in self._actions: ...
java
public boolean has(Element ele) { return tmap.containsKey(ele) && !tmap.get(ele).isEmpty(); }
python
def to_json(self): """Convert the EPW to a dictionary.""" # load data if it's not loaded if not self.is_data_loaded: self._import_data() def jsonify_dict(base_dict): new_dict = {} for key, val in base_dict.items(): new_dict[key] = val....
java
protected ArrayList<SAXMotif> getAllMotifs(GrammarRules grammarRules) { // result ArrayList<SAXMotif> allMotifs = new ArrayList<SAXMotif>(); int ruleNumber = grammarRules.size(); // iterate over all rules for (int i = 0; i < ruleNumber; i++) { // iterate over all segments/motifs/...
java
protected void writeln (BufferedWriter bout, String line) throws IOException { bout.write(line); bout.newLine(); }
java
public static InstallKernel getInstance(File installRoot) { if (installKernel == null) { installKernel = new InstallKernelImpl(installRoot); } return installKernel; }
java
@Override public void close() { if (closed) return; closed = true; try { selector.close(); } catch (Exception e) { logger.log("Failed to close selctor for: '" + name + "'", e); } try { channel.close(); } catch (Exception e) { logger.log("Failed to clo...
java
public void marshall(DeleteConnectorDefinitionRequest deleteConnectorDefinitionRequest, ProtocolMarshaller protocolMarshaller) { if (deleteConnectorDefinitionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
java
@SuppressWarnings({"unchecked"}) public void reduce(Object key, Iterator values, OutputCollector output, Reporter reporter) throws IOException { Reducer reducer = chain.getReducer(); if (reducer != null) { reducer.reduce(key, values, chain.getReducerCollector(output, reporter), ...
python
def plot_trajectory_projection(self, x_axis, y_axis, *args, **kwargs): """ Plots trajectory projection on the specified x and y axes See :meth:`InferenceResult.plot_trajectory_projection()` for information on the arguments and keyword arguments :param ...
java
private void generateTableAttributeUpdates(long currentOffset, long newOffset, int processedCount, UpdateInstructions update) { // Add an Update for the INDEX_OFFSET to indicate we have indexed everything up to this offset. Preconditions.checkArgument(currentOffset <= newOffset, "newOffset must be large...
java
private void updateMinMax(int index) { if (index >= min.getSize()) { return; } int sum = 0; for (int i=0; i<index; i++) { sum += Math.abs(current.get(i)); } int m = radius - sum; min.set(index, -m); ...
java
public boolean addRecordOwner(RecordOwnerParent recordOwner) { if (recordOwner instanceof RemoteRecordOwner) return false; // Sessions have their own owner hierarchy - Don't need to manage them if (m_recordOwnerCollection == null) m_recordOwnerCollection = new RecordOwnerCollection(this); ...
java
public <ResultT> ResultT findOne( final Bson filter, final RemoteFindOptions options, final Class<ResultT> resultClass) { return proxy.findOne(filter, options, resultClass); }
java
public EClass getIfcCrewResource() { if (ifcCrewResourceEClass == null) { ifcCrewResourceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(129); } return ifcCrewResourceEClass; }
java
public static String toPySanitizedContentOrdainer(SanitizedContentKind contentKind) { // Sanitization classes are defined in sanitize.py. return Preconditions.checkNotNull( KIND_TO_PY_SANITIZED_NAME.get(contentKind), "expected to have an ordainer for %s", contentKind); }
java
public void registerOutParameter(int parameterIndex, int sqlType, String typeName) { record(parameterIndex, getDeclaredMethod(CallableStatement.class, "registerOutParameter", int.class, int.class, int.class), parameterIndex, sqlType, typeName); }
java
private byte[] readBytes(final int numBytes, String messageType) throws IOException { final String errMsg = isNullOrEmpty(messageType) ? "Error reading from ssh-agent." : "Error reading " + messageType + " from ssh-agent."; final byte[] result = new byte[numB...
python
def _kwargs_from_dict(cls, a_dict: dict) -> dict: """Modify __init__ arguments from an external dictionary. Template method for from dict. Override if necessary (like it's done in Histogram1D). """ from .binnings import BinningBase kwargs = { "binnings": [Bin...
python
def _loop(self): """Handle data.""" request = {} connected = False while True: timeout = None sockets = [self.request_queue, self.signal] if not connected: try: self._clear_request(request) self._...
python
def firmware_autoupgrade_params_path(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware = ET.SubElement(config, "firmware", xmlns="urn:brocade.com:mgmt:brocade-firmware") autoupgrade_params = ET.SubElement(firmware, "autoupgrade-params") pa...
java
public final DetectIntentResponse detectIntent(String session, QueryInput queryInput) { DetectIntentRequest request = DetectIntentRequest.newBuilder().setSession(session).setQueryInput(queryInput).build(); return detectIntent(request); }
java
static String cleanPath( String path ) { return path .replaceFirst( "^" + ServletRegistrationComponent.REST_CONTEXT + "/", "/" ) .replaceFirst( "^" + ServletRegistrationComponent.WEBSOCKET_CONTEXT + "/", "/" ) .replaceFirst( "\\?.*", "" ); }
python
def start(name='all', user=None, conf_file=None, bin_env=None): ''' Start the named service. Process group names should not include a trailing asterisk. user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path ...
java
@Override public Iterator<Row<K, C>> iterator() { return new Iterator<Row<K, C>>() { private KeyRange range; private org.apache.cassandra.thrift.KeySlice lastRow; private List<org.apache.cassandra.thrift.KeySlice> list = null; private Iterator<org.apache.cassa...
java
@Override public void endVisit(ParenthesizedExpression node) { Expression expr = node.getExpression(); if (expr instanceof ParenthesizedExpression) { Expression inner = ((ParenthesizedExpression) expr).getExpression(); if (isEqualityExpression(inner)) { node.replaceWith(TreeUtil.remove(exp...
java
protected CmsResource getResource(CmsObject cms, I_CmsSearchDocument doc, CmsResourceFilter filter) { try { CmsObject clone = OpenCms.initCmsObject(cms); clone.getRequestContext().setSiteRoot(""); return clone.readResource(doc.getPath(), filter); } catch (CmsExceptio...
python
def create_namespaced_pod_template(self, namespace, body, **kwargs): # noqa: E501 """create_namespaced_pod_template # noqa: E501 create a PodTemplate # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True...
python
def process_subscription_data(post_data): """Process the subscription data according to out model""" subscription_data = post_data.pop("subscription", {}) # As our database saves the auth and p256dh key in separate field, # we need to refactor it and insert the auth and p256dh keys in the same dictionar...
java
private synchronized void changeState(PrimitiveState state) { if (this.state != state) { this.state = state; stateChangeListeners.forEach(l -> threadContext.execute(() -> l.accept(state))); } }
java
private static boolean multiPointContainsMultiPoint_( MultiPoint multipoint_a, MultiPoint multipoint_b, double tolerance, ProgressTracker progress_tracker) { Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D(); multipoint_a.queryEnvelope2D(env_a); multipoint_b.queryEnvelope2D(env_b); if (!envel...
java
@Override public boolean addAll(Collection<? extends Pair<K, V>> c) { return backedSet.addAll(c); }
python
def pdf_extract_text(path, pdfbox_path, pwd='', timeout=120): """Utility to use PDFBox from pdfbox.apache.org to extract Text from a PDF Parameters ---------- path : str Path to source pdf-file pdfbox_path : str Path to pdfbox-app-x.y.z.jar pwd : str, optional Passwo...
python
def create_or_update_entity(self, name, entity_id=None, metadata=None, policies=None, disabled=False, mount_point=DEFAULT_MOUNT_POINT): """Create or update an Entity. Supported methods: POST: /{mount_point}/entity. Produces: 200 application/json :par...
python
def get_longitude(self, ip): ''' Get longitude ''' rec = self.get_all(ip) return rec and rec.longitude
java
@Override public void setConfigs(List<String> configs) { configList.clear(); if (configs != null) { configList.addAll(configs); } }
java
public boolean isVisited(final URI path) { final URI localPath = stripFragment(path).normalize(); return visitSet.contains(localPath); }
java
public Observable<ServiceResponseWithHeaders<Page<NodeFile>, FileListFromComputeNodeHeaders>> listFromComputeNodeWithServiceResponseAsync(final String poolId, final String nodeId, final Boolean recursive, final FileListFromComputeNodeOptions fileListFromComputeNodeOptions) { return listFromComputeNodeSinglePage...
java
@Override public void put(String key, String groupId, String templateId, String version, Template<?> template) { if(key == null) { Map<String, Template<?>> vMap = gtvTable.get(groupId, templateId); if(vMap == null) { vMap = new HashMap<String, Template<?>>(); gtvTable.put(groupId, templateId, vMap); ...
java
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor) throws RestClientException { Assert.notNull(url, "'url' must not be null"); Assert.notNull(method, "'method' must not be null"); ClientHttpResponse response = null; try { ClientH...
java
public static long convolveSparse(GrayS64 integral , IntegralKernel kernel , int x , int y ) { return ImplIntegralImageOps.convolveSparse(integral,kernel,x,y); }
java
public static Builder newBuilder(TableId table, Iterable<RowToInsert> rows) { return newBuilder(table).setRows(rows); }
java
public void marshall(RegisterRdsDbInstanceRequest registerRdsDbInstanceRequest, ProtocolMarshaller protocolMarshaller) { if (registerRdsDbInstanceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
java
public DescribeFpgaImagesResult withFpgaImages(FpgaImage... fpgaImages) { if (this.fpgaImages == null) { setFpgaImages(new com.amazonaws.internal.SdkInternalList<FpgaImage>(fpgaImages.length)); } for (FpgaImage ele : fpgaImages) { this.fpgaImages.add(ele); } ...
java
private CmsCreatableListItem makeDetailPageItem(CmsNewResourceInfo typeInfo) { CmsListInfoBean info = new CmsListInfoBean(); String subtitle = typeInfo.getSubTitle(); String title = Messages.get().key( typeInfo.isFunction() ? Messages.GUI_FUNCTION_PAGE_TITLE_1 : Messages.GUI_DETAIL_...
java
public void setValue(List<Tag> value) throws IllegalArgumentException { this.type = null; this.value.clear(); for(Tag tag : value) { this.add(tag); } }
java
@NonNull public IconicsDrawable backgroundContourWidthRes(@DimenRes int sizeResId) { return backgroundContourWidthPx(mContext.getResources().getDimensionPixelSize(sizeResId)); }
python
def update(self): ''' Update our object's data ''' self._json = self._request( method='GET', url=self.API )._json
python
def getWhoisInfo(domain): """ Method that trie to recover the whois info from a domain. Args: ----- domain: The domain to verify. Returns: -------- dict: A dictionary containing the result as an i3visio entity with its `value`, `type` and `attributes`. """ n...
java
protected void processForActor(final LmlParser parser, final LmlTag tag, final Actor actor, final String rawAttributeData) { parser.throwErrorIfStrict("\"" + tag.getTagName() + "\" tag has a table cell attribute, but is not directly in a table. Cannot set table cell attribute value w...
java
public synchronized boolean containsValue(Object value) { if(size == 0) { return false; } else { try { XAttributeMap map = deserialize(); return map.containsValue(value); } catch (IOException e) { e.printStackTrace(); return false; } } }
java
public void submitTask(final String jobId, final String taskId, final URI jobJarUri, final URI confUri, final String command) throws IOException { final List<ResourceFile> resources = new ArrayList<>(); final ResourceFile jarSourceFile = new ResourceFile() .withBlobSourc...
java
static List<String> sanitizeInput(List<String> words) { words = words.stream() .map(s -> s.replaceAll("^\\n+|\\n+$", "")) // CR at beginning/end of line introduced by backslash continuation .map(s -> s.replaceAll("\\n+", " ")) // CR in middle of word introduced by return inside a quoted string .collect(Colle...
python
def evaluateModel(model, loader, device, batches_in_epoch=sys.maxsize, criterion=F.nll_loss, progress=None): """ Evaluate pre-trained model using given test dataset loader. :param model: Pretrained pytorch model :type model: torch.nn.Module :param loader: test dataset load...
python
def send(self, event_data): """ Sends an event data and blocks until acknowledgement is received or operation times out. :param event_data: The event to be sent. :type event_data: ~azure.eventhub.common.EventData :raises: ~azure.eventhub.common.EventHubError if the messa...
python
def filter_options(cls, kwargs, keys): """ Make optional kwargs valid and optimized for each template engines. :param kwargs: keyword arguements to process :param keys: optional argument names >>> Engine.filter_options(dict(aaa=1, bbb=2), ("aaa", )) {'aaa': 1} >...
java
private void performArchive() throws Exception { // The source dir points to the target/classes directory where the Maven resources plugin // has copied the XAR files during the process-resources phase. // For package.xml, however, we look in the resources directory (i.e. src/main/resources)...
java
public boolean isSubtypes(List<Type> ts, List<Type> ss) { while (ts.tail != null && ss.tail != null /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ && isSubtype(ts.head, ss.head)) { ts = ts.tail; ss = ss.tail; } return ts.tail == null && ss.tail ...
python
def handle_annotation_pattern(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE ANNOTATION X AS PATTERN "Y"``. :raises: RedefinedAnnotationError """ annotation = tokens['name'] self.raise_for_redefined_annotation(line, posi...
java
public static double computeL2(DoubleTuple t) { double sum = 0; for (int i=0; i<t.getSize(); i++) { double ti = t.get(i); sum += ti * ti; } return Math.sqrt(sum); }
python
def format_rpc(data): """Format an RPC call and response. Args: data (tuple): A tuple containing the address, rpc_id, argument and response payloads and any error code. Returns: str: The formated RPC string. """ address, rpc_id, args, resp, _status = data name = r...
java
public static void redirectPermanently(CmsJspActionElement jsp, String target) { target = OpenCms.getLinkManager().substituteLink(jsp.getCmsObject(), target); jsp.getResponse().setHeader(HEADER_CONNECTION, "close"); try { HttpServletResponse response = jsp.getResponse(); ...
java
@Override public final Map<String, JSType> getPropertyTypeMap() { Map<String, JSType> propTypeMap = new LinkedHashMap<>(); updatePropertyTypeMap(this, propTypeMap, new HashSet<FunctionType>()); return propTypeMap; }
python
def activate_retry(request, activation_key, template_name='userena/activate_retry_success.html', extra_context=None): """ Reissue a new ``activation_key`` for the user with the expired ``activation_key``. If ``activation_key`` does not exists, or ``USERENA_ACTIVATI...
python
def delete(self): """ Remove object :return: None """ logging.debug('Remove {x.__class__.__name__} [{x.name}]'.format(x=self)) request_url = self._artifactory.drive + '/api/{uri}/{x.name}'.format(uri=self._uri, x=self) r = self._session.delete( request...
java
@SuppressWarnings("unused") public static Date fromRfcDateTime(final String val) throws BadDateException { try { return fromRfcDateTime(val, Timezones.getDefaultTz()); } catch (BadDateException bde) { throw bde; } catch (Throwable t) { throw new BadDateException(); } }
python
def participate(self): """Finish reading and send text""" try: while True: left = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.ID, "left_button")) ) right = WebDriverWait(self.driver, 10).until( ...
python
def handleResponse(self, data): """Called when all response data has been received.""" self.factory.response_xml = data if self.status == '200': self.factory.parseErrorAndResponse(data) self.factory.deferred = None self.transport.loseConnection()
java
private static void fillDefaultProperties(final Properties props) { System.out.println("Setting default properties..."); // parser props.put(ParserRunner.DATASET_FILE, "./data/ml-100k/ml-100k/u.data"); props.put(ParserRunner.DATASET_PARSER, "net.recommenders.rival.split.parser.MovielensP...
python
def runcall(self, func, *args, **kw): """ Profile a single function call. """ # XXX where is this used ? can be removed ? self.enable_by_count() try: return func(*args, **kw) finally: self.disable_by_count()
python
def check_address(self, address): """Checks an address is not the same character repeated or an empty sequence""" if address is None: self.raise_error(InvalidAddress, details='address is None') if all(letter == address[0] for letter in address) or len(address) < self.minFundingAddres...
java
public void sendData() throws IOException { if (_writer != null) { _writer.write(_buffer.toString()); _writer.flush(); _buffer = new StringBuffer(); } }
python
def prune(self, dir): """Filter out files from 'dir/'.""" match = translate_pattern(os.path.join(dir, '**')) return self._remove_files(match.match)
python
def qnm_freq_decay(f_0, tau, decay): """Return the frequency at which the amplitude of the ringdown falls to decay of the peak amplitude. Parameters ---------- f_0 : float The ringdown-frequency, which gives the peak amplitude. tau : float The damping time of the sinusoid. d...
python
def convert_to_pypi_version(version): """ Convert a git tag version string into something compatible with `PEP-440 <https://www.python.org/dev/peps/pep-0440/>`_. :param version: The input version string, normally directly out of git describe. :return: PEP-440 version string Usage:: >>> conv...
python
def _on_run(self): ''' just loop and write responses ''' try: while True: try: try: cmd = self.cmdQueue.get(1, 0.1) except _queue.Empty: if self.killReceived: ...
java
private static String preferISAC(String sdpDescription) { String[] lines = sdpDescription.split("\r\n"); int mLineIndex = -1; String isac16kRtpMap = null; Pattern isac16kPattern = Pattern.compile("^a=rtpmap:(\\d+) ISAC/16000[\r]?$"); for (int i = 0; (...
python
def parse(self, buffer): """This method is used to parse an existing datagram into its corresponding TftpPacket object. The buffer is the raw bytes off of the network.""" log.debug("parsing a %d byte packet" % len(buffer)) (opcode,) = struct.unpack(str("!H"), buffer[:2]) ...
python
def send_signal(self, signal, app_id): """Transmit a signal to applications. .. warning:: In current implementations of SARK, signals are highly likely to arrive but this is not guaranteed (especially when the system's network is heavily utilised). Users should treat...
python
def solvemdbi_ism(ah, rho, b, axisM, axisK): r""" Solve a multiple diagonal block linear system with a scaled identity term by iterated application of the Sherman-Morrison equation. The computation is performed in a way that avoids explictly constructing the inverse operator, leading to an :math...
python
def to_hdf5(self, h5group): """ Save a dictionnary-like object inside a h5 file group """ # Write attributes name = 'label_type' if self.__getattribute__(name) is not None: h5group.attrs[name] = self.__getattribute__(name) for name in ['label', 'descr...
java
@Override public boolean contains(Object elem) { if (elem == null) return false; if (elem instanceof Number) return contains(((Number)elem).longValue()); return false; }
java
@SuppressWarnings("unchecked") @Override public final <T> T remove(final IKey<T> key) { return (T) config.remove(key.key()); }
python
def sendAppliedToOwner(self, context={}): """ Sent to project owner when user applies to a project """ super(ApplyMail, self).__init__(self.apply.project.owner.email, self.async, self.apply.project.owner.locale) return self.sendEmail('volunteerApplied-ToOwner', 'New volunteer', context)
python
def get_record_pos(self, record): """ Given a record, get the word's part of speech. Here we're going to return MeCab's part of speech (written in Japanese), though if it's a stopword we prefix the part of speech with '~'. """ if self.is_stopword_record(record): ...
java
private MetadataVersion parsePreRelease() { ensureValidLookahead(CharType.DIGIT, CharType.LETTER, CharType.HYPHEN); List<String> idents = new ArrayList<String>(); do { idents.add(preReleaseIdentifier()); if (chars.positiveLookahead(CharType.DOT)) { consumeNextCharacter(CharType.DOT); ...
java
public BooleanConditionBuilder must(ConditionBuilder... conditionBuilders) { if (must == null) { must = new ArrayList<>(conditionBuilders.length); } for (ConditionBuilder conditionBuilder : conditionBuilders) { must.add(conditionBuilder.build()); } return ...
java
protected String fixedInput ( String type, String name, Object value, String extra) { StringBuilder buf = new StringBuilder(); buf.append("<input type=\"").append(type).append("\""); buf.append(" name=\"").append(name).append("\""); buf.append(" value=\"").append(value).appen...
java
@Override public ListRegexMatchSetsResult listRegexMatchSets(ListRegexMatchSetsRequest request) { request = beforeClientExecution(request); return executeListRegexMatchSets(request); }
java
@Override public void cacheResult(CommerceShippingMethod commerceShippingMethod) { entityCache.putResult(CommerceShippingMethodModelImpl.ENTITY_CACHE_ENABLED, CommerceShippingMethodImpl.class, commerceShippingMethod.getPrimaryKey(), commerceShippingMethod); finderCache.putResult(FINDER_PATH_FETCH_BY_G_E, ...
java
public static void checkNotNullOrEmpty(String param, String errorMessagePrefix) throws IllegalArgumentException { checkNotNull(param, errorMessagePrefix); checkArgument(!param.isEmpty(), (errorMessagePrefix != null ? errorMessagePrefix : "Parameter") + " must not be empty.");...
java
public static <K, V> Map<K, List<V>> toListMap(Iterable<? extends Map<K, V>> mapList) { return MapUtil.toListMap(mapList); }
python
def gather_hinting(config, rules, valid_paths): """ Construct hint arguments for datanommer from a list of rules. """ hinting = collections.defaultdict(list) for rule in rules: root, name = rule.code_path.split(':', 1) info = valid_paths[root][name] if info['hints-callable']: ...
java
public CassandraJavaRDD<R> withConnector(CassandraConnector connector) { CassandraRDD<R> newRDD = rdd().withConnector(connector); return wrap(newRDD); }
python
def remove_description(self): """ Removes the description node from the metadata node, if present. :return: Returns True if the description node is removed. Returns False if the node is not present. """ description_node = self.metadata.find('description') if description_...
python
def is_orthogonal(dicoms, log_details=False): """ Validate that volume is orthonormal :param dicoms: check that we have a volume without skewing """ first_image_orient1 = numpy.array(dicoms[0].ImageOrientationPatient)[0:3] first_image_orient2 = numpy.array(dicoms[0].ImageOrientationPatient)[3:6...
java
protected void writeSearchAndBeanMetawidget(final Map<Object, Object> context, final int searchMetawidgetIndent, final int beanMetawidgetIndent, final Map<String, String> existingNamespaces) { StringWriter stringWriter = new StringWriter(); this.searchMetawidget.write(stringWriter...
python
def _build_vertex_data(self): """Rebuild the vertex buffers used for rendering the image when using the subdivide method. """ grid = self._grid w = 1.0 / grid[1] h = 1.0 / grid[0] quad = np.array([[0, 0, 0], [w, 0, 0], [w, h, 0], [0, 0, 0...
java
public LazyArray optJSONArray(int index) throws LazyException{ LazyNode token=getOptionalValueToken(index); if(token==null)return null; if(token.type==LazyNode.VALUE_NULL)return null; if(token.type!=LazyNode.ARRAY)return null; LazyArray arr= new LazyArray(token); arr.parent=this; return arr; }
python
def objectgetter(model, attr_name='pk', field_name='pk'): """ Helper that returns a function suitable for use as the ``fn`` argument to the ``permission_required`` decorator. Internally uses ``get_object_or_404``, so keep in mind that this may raise ``Http404``. ``model`` can be a model class, mana...