language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
static List<Fragment> nodeToPlanFragments(Node node, Map<NodeId, Node> nodes, boolean visited) { List<Fragment> subplan = new LinkedList<>(); if (!visited) { node.getFragmentsWithoutDependency().stream() .min(Comparator.comparingDouble(Fragment::fragmentCost)) ...
java
protected NodeData createPageStyle() { NodeData ret = createBlockStyle(); TermFactory tf = CSSFactory.getTermFactory(); ret.push(createDeclaration("position", tf.createIdent("relative"))); ret.push(createDeclaration("border-width", tf.createLength(1f, Unit.px))); ret.push(createDeclarati...
java
private CodeBlock getAdapterParameterList(ConstructorInfo constructorInfo) { List<CodeBlock> blocks = new ArrayList<>(); for (ConstructorInfo.Param param : constructorInfo.constructorParameters()) { if (param instanceof ConstructorInfo.AdapterParam) { ConstructorInfo.AdapterParam adapterParam = (...
java
protected static int calculateShift(int minimumValue, int maximumValue) { int shift = 0; int value = 1; while (value < minimumValue && value < maximumValue) { value <<= 1; shift++; } return shift; }
java
public static vpnurl get(nitro_service service, String urlname) throws Exception{ vpnurl obj = new vpnurl(); obj.set_urlname(urlname); vpnurl response = (vpnurl) obj.get_resource(service); return response; }
java
public DescribeIpGroupsResult withResult(WorkspacesIpGroup... result) { if (this.result == null) { setResult(new com.amazonaws.internal.SdkInternalList<WorkspacesIpGroup>(result.length)); } for (WorkspacesIpGroup ele : result) { this.result.add(ele); } ret...
python
def webify(v: Any, preserve_newlines: bool = True) -> str: """ Converts a value into an HTML-safe ``str`` (formerly, in Python 2: ``unicode``). Converts value ``v`` to a string; escapes it to be safe in HTML format (escaping ampersands, replacing newlines with ``<br>``, etc.). Returns ``""`` fo...
java
private int sequentialFailureCount(List<AuditEvent> events) { int failureCount = 0; for (AuditEvent event : events) { if (event.getType() == failureEventType) { failureCount++; } else if (event.getType() == successEventType) { // Successful authent...
java
private void exteriorAreaInteriorLine_(int half_edge, int id_a) { if (m_matrix[MatrixPredicate.ExteriorInterior] == 1) return; int faceParentage = m_topo_graph.getHalfEdgeFaceParentage(half_edge); int twinFaceParentage = m_topo_graph .getHalfEdgeFaceParentage(m_topo_graph .getHalfEdgeTwin(half_edge)...
java
void zeroWidthSpace(int indentLevel) throws IOException { if (closed) throw new IllegalStateException("closed"); if (column == 0) return; if (this.nextFlush != null) flush(nextFlush); this.nextFlush = FlushType.EMPTY; this.indentLevel = indentLevel; }
python
def list_priority(pr, vb=False, output=False): ''' list words by priority, like this: 1 : list words which the priority is 1, 2+ : list words which the priority is lager than 2, 3-4 : list words which the priority is from 3 to 4. ''' conn = sqlite3.connect(os.path.join(DEFAULT_PATH, 'wor...
python
def _link_to_action_mentions(self, actionmention_filename): """Add action mentions""" parser = GenewaysActionMentionParser(actionmention_filename) self.action_mentions = parser.action_mentions for action_mention in self.action_mentions: hiid = action_mention.hiid ...
java
public static int readInt(DataInput in) throws IOException { byte len=in.readByte(); if(len == 0) return 0; return makeInt(in, len); }
java
@SuppressWarnings("unchecked") protected <K, V, E extends SimpleExpression<? super V>> MapPath<K, V, E> createMap(String property, Class<? super K> key, Class<? super V> value, Class<? super E> queryType) { return add(new MapPath<K, V, E>(key, value, (Class) queryType, forProperty(property))); }
python
def pkcs_i2osp(x,xLen): """ Converts a long (the first parameter) to the associated byte string representation of length l (second parameter). Basically, the length parameters allow the function to perform the associated padding. Input : x nonnegative integer to be converted xLen...
java
public StashTableMetadata getTableMetadata(String table) throws StashNotAvailableException, TableNotStashedException { ImmutableList.Builder<StashFileMetadata> filesBuilder = ImmutableList.builder(); Iterator<S3ObjectSummary> objectSummaries = getS3ObjectSummariesForTable(table); wh...
python
def numenta_new_local_inhibition(self, X, Y): r""" Weight updates for the new local inhibition procedure (experimental and work in progress). See "Numenta’s local inhibition revisited" (Section 6) in `latex/notes.pdf`. Note that we directly encode the "activation probability" $a_{ij}$ as $h_{ij}$. ...
java
private void onRelation(Object entity, Map<String, Object> relationsMap, final Relation relation, final EntityMetadata metadata, final PersistenceDelegator pd, boolean lazilyloaded, Map<Object, Object> relationStack) { final Object entityId = PropertyAccessorHelper.getId(entity, meta...
python
def lstm_with_recurrent_dropout(hidden_size, keep_prob=0.5, **kwargs): """LSTM with recurrent dropout. Args: hidden_size: the LSTM hidden size. keep_prob: the probability to keep an entry when applying dropout. **kwargs: Extra keyword arguments to pass to the LSTM. Returns: A tuple (train_lstm, ...
java
public void dump(Writer writer) { PrintWriter printer = new PrintWriter(writer); for (String sectionType : sectionsByType.keySet()) { int sectionNumber = 0; for (Section section : sectionsByType.get(sectionType)) { printer.printf("%s [%d]%n", sectionType, sectionN...
java
public SimulationJobSummary withRobotApplicationNames(String... robotApplicationNames) { if (this.robotApplicationNames == null) { setRobotApplicationNames(new java.util.ArrayList<String>(robotApplicationNames.length)); } for (String ele : robotApplicationNames) { this.ro...
python
def on_train_end(self, **kwargs: Any) -> None: "Store the notebook and stop run" self.client.log_artifact(run_id=self.run, local_path=self.nb_path) self.client.set_terminated(run_id=self.run)
java
public <T> T patch(final Class<T> type, @DelegatesTo(HttpConfig.class) final Closure closure) { return type.cast(interceptors.get(HttpVerb.PATCH).apply(configureRequest(type, HttpVerb.PATCH, closure), this::doPatch)); }
java
public Optional<SheetBindingErrors<P>> getBySheetIndex(final int sheetIndex) { return list.stream() .filter(b -> b.getSheetIndex() == sheetIndex) .findFirst(); }
python
def setText(self, text): """ This function makes sure that any previously entered text is deleted before setting the value of the field. """ if self.text() == text: return self.touch() maxSize = len(self.text()) + 1 self.device.press('KEYCODE_D...
python
def is_builtin_name(name): """For example, __foo__ or __bar__.""" if name.startswith('__') and name.endswith('__'): return ALL_LOWER_CASE_RE.match(name[2:-2]) is not None return False
python
def get_request_kwargs(self): """Construct keyword parameters for Session.request() and Session.resolve_redirects().""" kwargs = dict(stream=True, timeout=self.aggregate.config["timeout"]) if self.proxy: kwargs["proxies"] = {self.proxytype: self.proxy} if self.scheme ...
java
public static ByComposite composite(By.ByTagName b0, By.ByClassName b1) { return new ByComposite(b0, b1); }
java
@Override public void channelRead0(ChannelHandlerContext context, O response) throws Exception { Envelope envelope = null; try { envelope = convertResponse(response); } catch (ResponseConversionException rce) { logger.log(Level.WARNING, "Failed to convert response", rce); return; } ...
python
def _load_general(data, targets, major_axis): """Load a list of arrays into a list of arrays specified by slices.""" for d_src, d_targets, axis in zip(data, targets, major_axis): # pylint: disable=too-many-nested-blocks if isinstance(d_targets, nd.NDArray): d_src.copyto(d_targets) el...
python
def addElement(self,etype='hex8',corners=[-1.0,-1.0,-1.0,1.,-1.0,-1.0,1.0,1.0,-1.0,-1.0,1.0,-1.0,-1.0,-1.0,1.0,1.0,-1.0,1.0,1.0,1.0,1.0,-1.0,1.0,1.0],name='new_elem'): ''' corners - list of nodal coordinates properly ordered for element type (counter clockwise) ''' lastelm = self.element...
python
def _goto_playing_station(self, changing_playlist=False): """ make sure playing station is visible """ if (self.player.isPlaying() or self.operation_mode == PLAYLIST_MODE) and \ (self.selection != self.playing or changing_playlist): if changing_playlist: self.star...
python
def is_published(self): """ Return true if this resource has published date in the past """ now = datetime.now() published = self.props.published if published: return published < now return False
java
public VariableInfo[] getVariableInfo(TagData data) { VariableInfo[] result = null; TagExtraInfo tei = getTagExtraInfo(); if (tei != null) { result = tei.getVariableInfo( data ); } return result; }
python
def get_guild_info(self, id: str) -> Dict[str, Any]: """Get a guild's information by its id Args: id: snowflake id of the guild Returns: Dictionary data for the guild API object Example: { "id": "41771983423143937", ...
python
def splitname(path): """Split a path into a directory, name, and extensions.""" dirpath, filename = os.path.split(path) # we don't use os.path.splitext here because we want all extensions, # not just the last, to be put in exts name, exts = filename.split(os.extsep, 1) return dirpath, name, ext...
java
@Override public Object convert(Object source) { NodeInterface relatedNode = getRelatedNode(true); if (relatedNode != null) { try { relatedNode.setProperty(targetKey, source); } catch (FrameworkException fex) { logger.warn("Unable to set remote node property {}", targetKey); } } ...
python
def moveToPoint(self, xxx_todo_changeme1): """ Moves the circle to the point x,y """ (x,y) = xxx_todo_changeme1 self.set_cx(float(self.get_cx()) + float(x)) self.set_cy(float(self.get_cy()) + float(y))
python
def destroy(self): """ A reimplemented destructor that cancels the dialog before destroying. """ super(AndroidPopupWindow, self).destroy() window = self.window if window: #: Clear the dismiss listener #: (or we get an error during the ca...
python
def check_password(self, username, password): """The actual password checking logic. Separated from the authenticate code from Django for easier updating""" try: if SUPPORTS_VERIFY: kerberos.checkPassword(username.lower(), password, getattr(settings, "KRB5_SERVICE", ""), geta...
python
def optimizers_with(self, **kwargs) -> [non_linear.NonLinearOptimizer]: """ Load a list of optimizers for phases in the directory with zero or more filters applied. Parameters ---------- kwargs Filters, e.g. pipeline=pipeline1 Returns ------- ...
python
def _handle_processor_error(self, failure): """Handle a failure in the processing of a block of messages This method is called when the processor func fails while processing a block of messages. Since we can't know how best to handle a processor failure, we just :func:`errback` our :fun...
python
def mark_as_inactive(self, kid): """ Mark a specific key as inactive based on the keys KeyID :param kid: The Key Identifier """ k = self.get_key_with_kid(kid) k.inactive_since = time.time()
java
public SVGPath quadTo(double[] c1xy, double[] xy) { return append(PATH_QUAD_TO).append(c1xy[0]).append(c1xy[1]).append(xy[0]).append(xy[1]); }
python
def _read_openjp2(self, rlevel=0, layer=None, area=None, tile=None, verbose=False): """Read a JPEG 2000 image using libopenjp2. Parameters ---------- layer : int, optional Number of quality layer to decode. rlevel : int, optional Fac...
python
def compare(self, other): """Compare the DigitWord with another DigitWord (other) and provided iterated analysis of the matches (none or loose) and the occurrence (one or more) of each DigitEntry in both DigitWords. The method returns a list of Comparison objects.""" self._validate_comp...
python
def run_gvcftyper(vrn_files, out_file, region, data): """Produce joint called variants from input gVCF files. """ if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: license = license_export(data) ref_file = dd.get_ref_file(data) ...
java
private ArrayList<String> getActions() { String actionList = getString(KEY_ACTIONS); if (actionList.equals(NO_STRING_VALUE)) { return new ArrayList<>(); } else { return deserializeString(actionList); } }
python
def find_file(pattern, path): """ A bit like grep. Finds a pattern, looking in path. Returns the filename. """ for fname in glob.iglob(path): with open(fname) as f: if re.search(pattern, f.read()): return fname return
java
public final EObject ruleXVariableDeclaration() throws RecognitionException { EObject current = null; Token lv_writeable_1_0=null; Token otherlv_2=null; Token otherlv_6=null; EObject lv_type_3_0 = null; AntlrDatatypeRuleToken lv_name_4_0 = null; AntlrDatatypeRu...
python
def join_path(*path_to_join, **kwargs): """Join input path to sample data path (usually in ~/lisa_data) :param path_to_join: one or more paths :param get_root: return dataset root path. If false, the path would be into "medical/orig" :return: joined path """ if "get_root" in kwargs: get...
python
def putdata(self, value, blc=(), trc=(), inc=()): """Put image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The da...
java
@Override public ByteBuffer serialize(String object) { int length = object.length(); try(ByteArrayOutputStream bout = new ByteArrayOutputStream(length)) { int i = 0; for (; i < length; i++) { char c = object.charAt(i); if (c == 0x0000 || c > 0x007f) { break; } ...
python
def _get_migrate_command(): ''' Returns the command shared by the different migration types ''' tunnel = __salt__['config.option']('virt.tunnel') if tunnel: salt.utils.versions.warn_until( 'Sodium', '\'virt.tunnel\' has been deprecated in favor of ' '\'vir...
java
public void execute( TransformerImpl transformer) throws TransformerException { SerializationHandler rhandler = transformer.getSerializationHandler(); XPathContext xctxt = transformer.getXPathContext(); int sourceNode = xctxt.getCurrentNode(); String nodeName = m_name_av...
java
private void registerAnyProvidedPrefixes(String ns, Node node, JSModule module) { int pos = ns.indexOf('.'); while (pos != -1) { String prefixNs = ns.substring(0, pos); pos = ns.indexOf('.', pos + 1); if (providedNames.containsKey(prefixNs)) { providedNames.get(prefixNs).addProvide(nod...
java
public void getPersistentData(ObjectOutputStream oos) { if (tc.isEntryEnabled()) SibTr.entry(tc, "getPersistentData", oos); try { HashMap hm = new HashMap(); if (durablePseudoDestID != null) hm.put("durablePseudoDestID", durablePseudoDestID.toByteArray()); if (durableSubN...
python
def mouse_event_callback(self, window, xpos, ypos): """ Mouse event callback from glfw. Translates the events forwarding them to :py:func:`cursor_event`. Args: window: The window xpos: viewport x pos ypos: viewport y pos """ ...
python
def print_map(self): """Open impact report dialog used to tune report when printing.""" # Check if selected layer is valid impact_layer = self.iface.activeLayer() if impact_layer is None: # noinspection PyCallByClass,PyTypeChecker QMessageBox.warning( ...
java
public static <T, U> Collector<T, ?, Seq<U>> maxAll(Function<? super T, ? extends U> function, Comparator<? super U> comparator) { return collectingAndThen(maxAllBy(function, comparator), t -> t.map(function)); }
java
public void doPost(HttpServletRequest sreq, HttpServletResponse sres) throws ServletException, IOException { doGet(sreq,sres); }
java
public static VehicleInterface build(String interfaceName, Context context, String resource) throws VehicleInterfaceException { return build(findClass(interfaceName), context, resource); }
java
private int compareIdentifiers(String ident1, String ident2) { if (isInt(ident1) && isInt(ident2)) { return Integer.parseInt(ident1) - Integer.parseInt(ident2); } else { return ident1.compareTo(ident2); } }
java
public SwipeViewGroup setContentView(View contentView){ if(this.contentView != null) removeView(contentView); addView(contentView); this.contentView = contentView; return this; }
java
public Message addContent(String name, String type, String value) { content.put(name, new Content(type, value)); return this; }
python
def element(cls, name, parent=None, interleave=None, occur=0): """Create an element node.""" node = cls("element", parent, interleave=interleave) node.attr["name"] = name node.occur = occur return node
python
def subscribe(self, _func=None, needs=(), returns=(), modifies=(), **conditions): """Add a hook to a pangler. This method can either be used as a decorator for a function or method, or standalone on a callable. * `needs` is an iterable of parameters that this hook operates...
python
def _get_flat_path(path_pb): """Convert a legacy "Path" protobuf to a flat path. For example Element { type: "parent" id: 59 } Element { type: "child" name: "naem" } would convert to ``('parent', 59, 'child', 'naem')``. :type pa...
java
public void setApiKeyInputStream(InputStream apiKeyInputStream) { this.clientBuilder.setApiKey(ApiKeys.builder().setInputStream(apiKeyInputStream).build()); }
python
def _get_interpolator(method, vectorizeable_only=False, **kwargs): '''helper function to select the appropriate interpolator class returns interpolator class and keyword arguments for the class ''' interp1d_methods = ['linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',...
python
def validate_regex(regex, sub_service): """Is the regex valid for StackInABox routing? :param regex: Python regex object to match the URI :param sub_service: boolean for whether or not the regex is for a sub-service :raises: InvalidRouteRegexError if the reg...
java
protected void gitCreateAndCheckout(final String newBranchName, final String fromBranchName) throws MojoFailureException, CommandLineException { getLog().info( "Creating a new branch '" + newBranchName + "' from '" + fromBranchName + "' and checkin...
java
public RestTemplateBuilder additionalInterceptors( ClientHttpRequestInterceptor... interceptors) { Assert.notNull(interceptors, "interceptors must not be null"); return additionalInterceptors(Arrays.asList(interceptors)); }
python
def request(self, session_id): """Force the termination of a NETCONF session (not the current one!) *session_id* is the session identifier of the NETCONF session to be terminated as a string """ node = new_ele("kill-session") sub_ele(node, "session-id").text = session_id ...
java
private void escape(String value) { int n = value.length(); int i = 0; for (int j = 0; j < n; ++j) { char c = value.charAt(j); int k = ESCAPED_CHARS.indexOf(c); if (k >= 0 || c < ' ') { if (i < j) { append(value, i, j); ...
java
@Override public LogProperties logProperties() { if (tc.isDebugEnabled()) Tr.debug(tc, "logProperties", _fileLogProperties); return _fileLogProperties; }
python
def transform(self, column): """Applies an exponential to values to turn them positive numbers. Args: column (pandas.DataFrame): Data to transform. Returns: pd.DataFrame """ self.check_data_type() return pd.DataFrame({self.col_name: np.exp(colum...
java
public void marshall(SpekeKeyProvider spekeKeyProvider, ProtocolMarshaller protocolMarshaller) { if (spekeKeyProvider == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(spekeKeyProvider.getCertificate...
java
protected void setupForExpandedWar() { webapp.setServerClasses(getServerClasses()); webapp.setDescriptor(webapp + "/WEB-INF/web.xml"); webapp.setResourceBase(resourceBase); webapp.setParentLoaderPriority(false); }
python
def replace_text(filepath, to_replace, replacement): """ Replaces a string in a given file with another string :param file: the file in which the string has to be replaced :param to_replace: the string to be replaced in the file :param replacement: the string which replaces 'to_...
java
@Override public GetInvalidationResult getInvalidation(GetInvalidationRequest request) { request = beforeClientExecution(request); return executeGetInvalidation(request); }
java
public Vector3f set(int index, FloatBuffer buffer) { MemUtil.INSTANCE.get(this, index, buffer); return this; }
python
def old_checksum(self): """Get the checksum stored in :attr:`checksum_file` (a string or :data:`None`).""" if self.context.is_file(self.checksum_file): logger.debug("Reading saved checksum from %s ..", format_path(self.checksum_file)) checksum = self.context.read_file(self.checks...
java
public void addNewArray(String name, Class<?> aClass, int size) throws IOException { addNewArray(name, Typ.getTypeFor(aClass), size); }
java
@Override public T addPackages(final boolean recursive, final Filter<ArchivePath> filter, final Package... packages) throws IllegalArgumentException { return addPackages(recursive, filter, null, packages); }
java
public void close() { readyState = ReadyState.CLOSING; try { webSocketSession.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, null)); } catch (IOException e) { e.printStackTrace(); } }
java
private String getBuildType(final CCTask task) { final String outType = task.getOuttype(); if ("executable".equals(outType)) { return "exeproject"; } else if ("static".equals(outType)) { return "libraryproject"; } return "dllproject"; }
python
def _exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place...
java
@FFDCIgnore(BAD_PARAM.class) private boolean isEncodingForWASClassic(ClientRequestInfo ri) { try { int IBM_PV_TC_ID = 0x49424d0a; ri.get_effective_component(IBM_PV_TC_ID); return true; } catch (BAD_PARAM bpe) { // Expected if not talking to a WAS Class...
java
public static String cleanUp(String classname) { String result; result = classname; if (result.contains("/")) result = result.replace("/", "."); if (result.contains("\\")) result = result.replace("\\", "."); if (result.endsWith(".class")) result = result.substring(0, result.lengt...
java
public static <T> Future<T> accumulate(final Monoid<T> reducer, final Iterable<Future<T>> fts) { return sequence(fts).map(s -> s.reduce(reducer) ); }
python
def save_xml(self, doc, element): '''Save this configuration set into an xml.dom.Element object.''' element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id) for c in self._config_data: new_element = doc.createElementNS(RTS_NS, RTS_NS_S + ...
python
def cast_bytes(s, encoding='utf8', errors='strict'): """cast str or bytes to bytes""" if isinstance(s, bytes): return s elif isinstance(s, str): return s.encode(encoding, errors) else: raise TypeError("Expected unicode or bytes, got %r" % s)
java
private void init(final List<Integer> variables, final BackboneType type) { this.type = type; this.candidates = new Stack<>(); this.assumptions = new LNGIntVector(variables.size()); this.backboneMap = new HashMap<>(); for (final Integer var : variables) { this.backbon...
java
public Object unmarshalRootElement(Reader inStream, BaseXmlTrxMessageIn soapTrxMessage) throws Exception { String xml = Utility.transferURLStream(null, null, inStream, null); soapTrxMessage.getMessage().setXML(xml); return xml; }
java
boolean isMonitored(HttpSession session) { boolean monitor = false; if (null != session && session.getAttribute(Constants.Options.OPTIONS) != null) { monitor = ((Options) session.getAttribute(Constants.Options.OPTIONS)).isMonitor(); } return monitor; }
java
public static int decodeDesc(byte[] src, int srcOffset, BigInteger[] valueRef) throws CorruptEncodingException { int headerSize; int bytesLength; byte[] bytes; try { int header = src[srcOffset]; if (header == NULL_BYTE_HIGH || header == NULL_...
java
private MediaTracker getTracker() { // Opt: Only synchronize if trackerObj comes back null? // If null, synchronize, re-check for null, and put new tracker synchronized(this) { if (tracker == null) { @SuppressWarnings("serial") Component comp = new Com...
python
def retrieve_instance_links(self): """Appends on existing instance links Returns: instance_links: A dictionary containing all the instance links in LINKS and not in pipeline_config """ instance_links = {} self.log.debug("LINKS IS %s", LINKS) for key, value in...
java
public ArrayList<WebElement> getWebElements(){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "getWebElements()"); } return webUtils.getWebElements(false); }