language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected List<Node> getTransformableNodes(final List<Node> childNodes) { final List<Node> nodes = new LinkedList<Node>(); for (final Node childNode : childNodes) { if (isTransformableNode(childNode)) { nodes.add(childNode); } } return nodes; ...
java
public boolean isForwardToHtml() { if (!isHtmlResponse()) { // e.g. exception, AJAX return false; } final HtmlResponse htmlResponse = ((HtmlResponse) actionResponse); return !htmlResponse.isRedirectTo() && isHtmlTemplateResponse(htmlResponse); }
python
def fit(self, X, y): """ Fit MLKR model Parameters ---------- X : (n x d) array of samples y : (n) data labels """ X, y = self._prepare_inputs(X, y, y_numeric=True, ensure_min_samples=2) n, d = X.shape if y.shape[0] != n: ...
python
def SmartUnicode(string): """Returns a unicode object. This function will always return a unicode object. It should be used to guarantee that something is always a unicode object. Args: string: The string to convert. Returns: a unicode object. """ if isinstance(string, Text): return string ...
java
@Override public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { return true; }
java
protected void assertExtractSource(File archive) throws FileNotFoundException, IllegalArgumentException { if (archive.isDirectory()) { throw new IllegalArgumentException("Can not extract " + archive + ". Source is a directory."); } else if (!archive.exists()) { throw new FileNotF...
python
def start_check (aggregate, out): """Start checking in background and write encoded output to out.""" # check in background t = threading.Thread(target=director.check_urls, args=(aggregate,)) t.start() # time to wait for new data sleep_seconds = 2 # current running time run_seconds = 0 ...
java
@Deprecated public static synchronized void suppressMethod(Class<?> cls, Class<?>... additionalClasses) { SuppressCode.suppressMethod(cls, additionalClasses); }
java
public Record getRecord(String strFileName) { Record record = super.getRecord(strFileName); if (record == null) if (Script.SCRIPT_FILE.equalsIgnoreCase(strFileName)) record = new Script(this); return record; }
java
public final void attribute(String name, boolean value) throws IllegalStateException, IllegalArgumentException, IOException { attribute(name, value ? "true" : "false"); }
python
def _gte(field, value, document): """ Returns True if the value of a document field is greater than or equal to a given value """ try: return document.get(field, None) >= value except TypeError: # pragma: no cover Python < 3.0 return False
python
def _validate_outgroup(self, outgroup): """All voucher codes in our datasets have dashes converted to underscores.""" if outgroup: outgroup = outgroup.replace("-", "_") good_outgroup = False for seq_record in self.seq_records: if seq_record.voucher_cod...
java
@Override public int width() { return calledNextStartPosition ? (noMorePositions ? 0 : spans1.spans.endPosition() - spans1.spans.startPosition()) : 0; }
java
public static List<CDKRMap> makeAtomsMapOfBondsMap(List<CDKRMap> list, IAtomContainer sourceGraph, IAtomContainer targetGraph) { if (list == null) { return (list); } List<CDKRMap> result = new ArrayList<CDKRMap>(); for (int i = 0; i < list.size(); i++) { ...
python
def get_domain_name(url): """ Extract a domain name from the url (without subdomain). Args: url (str): Url. Returns: str: Domain name. Raises: DomainNotMatchedError: If url is wrong. Examples: >>> get_domain_name('https://vod.tvp.pl/video/') 'tvp.pl' ...
python
def get_mailbox_stats(self): """ Get global stats about mailboxes Parses <stats numMboxes="6" totalSize="141077"/> :returns: dict with stats """ resp = self.request_single('GetMailboxStats') ret = {} for k, v in resp.items(): ret[k] = int(v) ...
python
def get_xlmhg_pval2(N, K, X, L, stat, tol=DEFAULT_TOL): """Calculate the XL-mHG p-value using "Algorithm 2". Parameters ---------- N: int The length of the list. K: int The number of 1's in the list. X: int The XL-mHG ``X`` parameter. L: int The XL-mHG ``L`` ...
java
public String buildSelectDirectEditButtonStyle(String htmlAttributes) { int selectedIndex = Integer.parseInt(getParamTabEdDirectEditButtonStyle()); return buildSelectButtonStyle(htmlAttributes, selectedIndex); }
java
@Override protected void configure() { // Primitive mappers primitiveType( boolean.class ).serializer( BooleanJsonSerializer.class ).deserializer( BooleanJsonDeserializer.class ); primitiveType( char.class ).serializer( CharacterJsonSerializer.class ).deserializer( CharacterJsonDeserializer....
java
public final void synpred31_InternalPureXbase_fragment() throws RecognitionException { // InternalPureXbase.g:3189:4: ( ( ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) ) // InternalPureXbase.g:3189:5: ( ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmForm...
java
@Override protected List<ConfigIssue> init() { List<ConfigIssue> issues = super.init(); if (getContext().getOutputLanes().size() != 1) { issues.add(getContext().createConfigIssue( null, null, Errors.API_00, getInfo().getInstanceName(), 1, getContext().getO...
java
public static WrapSeekable<FSDataInputStream> openPath( FileSystem fs, Path p) throws IOException { return new WrapSeekable<FSDataInputStream>( fs.open(p), fs.getFileStatus(p).getLen(), p); }
python
def process_post(self): """ Analyse the POST request: * check that the LoginTicket is valid * check that the user sumited credentials are valid :return: * :attr:`INVALID_LOGIN_TICKET` if the POSTed LoginTicket is not valid ...
java
public static CommercePriceList fetchByG_S_First(long groupId, int status, OrderByComparator<CommercePriceList> orderByComparator) { return getPersistence() .fetchByG_S_First(groupId, status, orderByComparator); }
python
def connect(host=None, port=rethinkdb.DEFAULT_PORT, timeout=20, verify=True, **kwargs): """ RethinkDB semantic connection wrapper raises <brain.connection.BrainNotReady> if connection verification fails :param verify: <bool> (default True) whether to run...
java
static SortedRangeSet of(Type type, Object first, Object... rest) { List<Range> ranges = new ArrayList<>(rest.length + 1); ranges.add(Range.equal(type, first)); for (Object value : rest) { ranges.add(Range.equal(type, value)); } return copyOf(type, ranges); }
python
def introspect_access_token(self, access_token_value): # type: (str) -> Dict[str, Union[str, List[str]]] """ Returns authorization data associated with the access token. See <a href="https://tools.ietf.org/html/rfc7662">"Token Introspection", Section 2.2</a>. """ if acces...
java
public static ComputationGraphSpace fromYaml(String yaml) { try { return YamlMapper.getMapper().readValue(yaml, ComputationGraphSpace.class); } catch (IOException e) { throw new RuntimeException(e); } }
python
def setHintColor(self, color): """ Sets the hint color for this combo box provided its line edit is an XLineEdit instance. :param color | <QColor> """ lineEdit = self.lineEdit() if isinstance(lineEdit, XLineEdit): lineEdit.setHintColor(co...
java
public static int cuGraphGetNodes(CUgraph hGraph, CUgraphNode nodes[], long numNodes[]) { return checkResult(cuGraphGetNodesNative(hGraph, nodes, numNodes)); }
python
def maybe_sendraw(self, host_port: Tuple[int, int], messagedata: bytes): """ Send message to recipient if the transport is running. """ # Don't sleep if timeout is zero, otherwise a context-switch is done # and the message is delayed, increasing its latency sleep_timeout = self.throttle...
java
protected void processAcksAndFails(int srcTaskId, int taskId, HeronTuples.HeronControlTupleSet controlTupleSet) { HeronTuples.HeronTupleSet.Builder out = HeronTuples.HeronTupleSet.newBuilder(); out.setSrcTaskId(srcTaskId); // First go over emits. This makes sure that ne...
python
def server_receives_message(self, *parameters): """Receive a message with template defined using `New Message` and validate field values. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is...
java
protected void addSessionValue(final HttpServletRequest request, final String key, final Object value) { List l = (List) request.getSession(true).getAttribute(key); if (l == null) { l = new ArrayList(); } l.add(value); request.getSession(true).setAttribute(key, l); }
python
def make_agent( agent_type, env, policy_hparams, policy_dir, sampling_temp, sim_env_kwargs_fn=None, frame_stack_size=None, rollout_agent_type=None, batch_size=None, inner_batch_size=None, env_type=None, **planner_kwargs ): """Factory function for Agents.""" if batch_size is None: batch_size = env.ba...
python
def rename(self, old_task_name, new_task_name): """ Renames an existing task directory. `old_task_name` Current task name. `new_task_name` New task name. Returns ``True`` if rename successful. """ if not old_task_name or ...
python
def upload_archive(self, data_collected, content_type, duration): """ Do an HTTPS Upload of the archive """ if self.config.legacy_upload: return self._legacy_upload_archive(data_collected, duration) file_name = os.path.basename(data_collected) upload_url = sel...
java
public String eatStringConstant() { if (!matchStringConstant()) throw new BadSyntaxException(); /* * The input string constant is a quoted string token likes 'str', and * its token type (ttype) is the quote character. So the string * constants are not converted to lower case. */ String s = ...
java
public void setDisplayName(String displayName) { if (CmsStringUtil.isEmpty(displayName) || (IGNORE_DISPLAY_NAME.equals(displayName))) { m_displayName = null; setDisplayed(false); } else { m_displayName = displayName; m_displayNameForConfiguration = displa...
java
public static Client getInstance(String datasourceName, PageContext pc, Log log) throws PageException { Struct _sct = _loadData(pc, datasourceName, "client", SCOPE_CLIENT, log, false); if (_sct == null) _sct = new StructImpl(); return new ClientDatasource(pc, datasourceName, _sct); }
java
public FieldList move(int iRelPosition) throws DBException { Record record = ((QueryRecord)m_record).moveTableQuery(iRelPosition); if (record != null) return (QueryRecord)m_record; else return null; }
python
def _push(self, mtd, args, name=None): ''' Adds a command to the queue. @param mtd: Method to invoke to process the command @type mtd: method @param args: Arguments to apply when invoking the method @type args: tuple @param name: Name associated with the command ...
python
def _new_serial(ca_name): ''' Return a serial number in hex using os.urandom() and a Unix timestamp in microseconds. ca_name name of the CA CN common name in the request ''' hashnum = int( binascii.hexlify( b'_'.join(( salt.utils.stringuti...
java
public static Map<String, CmsJspObjectValueWrapper> wrapSettings(CmsObject cms, Map<String, String> settings) { Map<String, CmsJspObjectValueWrapper> wrappedSettings = null; if (settings != null) { wrappedSettings = new HashMap<String, CmsJspObjectValueWrapper>(settings.size()); ...
java
@PostConstruct public void acquireConnections() throws JMSException { LOGGER.debug("Initializing: {}", this.getClass().getCanonicalName()); connection = connectionFactory.createConnection(); connection.start(); jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ...
java
public final void remove(final int index) { AbstractItem removedItem = items.remove(index); if (removedItem instanceof Item && ((Item) removedItem).getIcon() != null) { iconCount--; } else if (removedItem instanceof Divider) { dividerCount--; } rawItems ...
python
def sample_batch_transitions(self, batch_size, forward_steps=1): """ Return indexes of next sample""" batches = [ self._sample_batch_prioritized( segment_tree, batch_size, self.deque.frame_history, forward_steps=forward_steps ) for segment_tree in self...
java
@Override public PType caseALetStm(ALetStm node, TypeCheckInfo question) throws AnalysisException { node.setType(typeCheckLet(node, node.getLocalDefs(),node.getStatement(),question)); return node.getType(); }
python
def log_wrapper(self): """ Wrapper to set logging parameters for output """ log = logging.getLogger('client.py') # Set the log format and log level try: debug = self.params["debug"] log.setLevel(logging.DEBUG) except KeyError: ...
python
def add_routes(fapp, routes, prefix=""): """Batch routes registering Register routes to a blueprint/flask_app previously collected with :func:`routes_collector`. :param fapp: bluprint or flask_app to whom attach new routes. :param routes: dict of routes collected by :func:`routes_collector` :p...
python
def _number(text): ''' Convert a string to a number. Returns an integer if the string represents an integer, a floating point number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return int(text) try: return float(text) exce...
python
def run(self, duration, obs=None): """Run the simulation. Parameters ---------- duration : Real a duration for running a simulation. A simulation is expected to be stopped at t() + duration. obs : list of Obeservers, optional observers ...
java
public static UserAuthentication checkIfActive(UserAuthentication userAuth, User user, boolean throwException) { if (userAuth == null || user == null || user.getIdentifier() == null) { if (throwException) { throw new BadCredentialsException("Bad credentials."); } else { logger.debug("Bad credentials. {}...
java
@Indexable(type = IndexableType.DELETE) @Override public CPMeasurementUnit deleteCPMeasurementUnit( CPMeasurementUnit cpMeasurementUnit) { return cpMeasurementUnitPersistence.remove(cpMeasurementUnit); }
java
protected <S extends State, N> S getPartitionedState( N namespace, TypeSerializer<N> namespaceSerializer, StateDescriptor<S, ?> stateDescriptor) throws Exception { /* TODO: NOTE: This method does a lot of work caching / retrieving states just to update the namespace. This method should be removed ...
java
public void getWorldRotation(int boneindex, Quaternionf q) { Bone bone = mBones[boneindex]; if ((bone.Changed & LOCAL_ROT) == LOCAL_ROT) { calcWorld(bone, mSkeleton.getParentBoneIndex(boneindex)); } bone.WorldMatrix.getUnnormalizedRotation(q); q.normalize...
java
protected void appendFieldJSON(StringBuilder jsonTemplate, String type, String name, String id, String jsType) { jsonTemplate .append("'") .append(name) .append("' : ") .append(jsType) .append(appendExtractionExpression(type, name, id, jsType)) ...
java
public String fmtpl(String d, int pad) { int length = d.length(); int extra = pad - length; if (extra < 0) { extra = 0; } String v = d; for (int i = 0; i < extra; i++) { v = " " + v; } return v; }
python
def generic_loss(top_out, targets, model_hparams, vocab_size, weights_fn): """Compute loss numerator and denominator for one shard of output.""" del vocab_size # unused arg logits = top_out logits = common_attention.maybe_upcast(logits, hparams=model_hparams) cutoff = getattr(model_hparams, "video_modality_l...
java
public OnlineClustering<T> generate() { return new StreamingKMeansClustering<T>( alpha, beta, gamma, numClusters, logNumPoints); }
java
public static <T> List<T> handleWorkBookToBeans(Class<T> clazz, Workbook workbook) throws ReadExcelException { List<Map<String, Object>> listMap = ReadExcelUtils.handleWorkBookToMapList(workbook); List<T> beans = new ArrayList<T>(); for (Map<String, Object> map : listMap) { T bean = ...
python
def has_object_permission(self, request, view, obj): """ Checks if user is superuser or it has permission over object Parameters ---------- request view obj Returns ------- """ return ( request.user.is_superuser or ...
java
@NonNull public Flowable<Changes> observeChangesOfUri(@NonNull Uri uri, @NonNull BackpressureStrategy backpressureStrategy) { return observeChangesOfUris(Collections.singleton(uri), backpressureStrategy); }
python
def set_value(self, value): """The value have to be in the form '10px' or '10%', so numeric value plus measure unit """ v = 0 measure_unit = 'px' try: v = int(float(value.replace('px', ''))) except ValueError: try: v = int(float(val...
java
public void auditPortableMediaCreate( RFC3881EventOutcomeCodes eventOutcome, String submissionSetUniqueId, String patientId, List<CodedValueType> purposesOfUse) { if (!isAuditorEnabled()) { return; } ExportEvent exportEvent = new ExportEvent(true, eventOutcome, new IHETransactionEventType...
java
private String createSpan(final List<String> lemmas, final int from, final int to) { String lemmaSpan = ""; for (int i = from; i < to; i++) { lemmaSpan += lemmas.get(i) + "_"; } lemmaSpan += lemmas.get(to); return lemmaSpan; }
python
def _LowerBoundSearch(partitions, hash_value): """Searches the partition in the partition array using hashValue. """ for i in xrange(0, len(partitions) - 1): if partitions[i].CompareTo(hash_value) <= 0 and partitions[i+1].CompareTo(hash_value) > 0: return i r...
java
boolean isDisplayNameUnique(String displayName, String currentJobName) { Collection<TopLevelItem> itemCollection = items.values(); // if there are a lot of projects, we'll have to store their // display names in a HashSet or something for a quick check for(TopLevelItem item : itemCollec...
java
private static Map<?, ?> mapOfEntries( Entry<?, ?>... entries ) { Map<Object, Object> looseTypedMap = new LinkedHashMap<>( entries.length ); for (Entry<?, ?> entry : entries) looseTypedMap.put(entry.getKey(), entry.getValue()); return looseTypedMap; }
java
public static CmsDependencyIconActionType valueOf(String value) throws CmsIllegalArgumentException { Iterator<CmsDependencyIconActionType> iter = VALUES.iterator(); while (iter.hasNext()) { CmsDependencyIconActionType target = iter.next(); if (value.equals(target.getId())) { ...
java
public static void addString(ByteBuffer buffer, String val) { addBytes(buffer, StringUtils.toUtf8(val)); }
java
public void setShape(double width , double height ) { points2D3D.get(0).location.set(-width/2,-height/2,0); points2D3D.get(1).location.set(-width/2, height/2,0); points2D3D.get(2).location.set( width/2, height/2,0); points2D3D.get(3).location.set( width/2,-height/2,0); }
python
def dataReceived(self, data): """ After receiving the data, generate the deferreds and add myself to it. """ def write(result): print "Writing %r" % result self.transport.write(result) d = self.d() d.addCallback(write) # errors are silently ignore...
java
@SuppressWarnings("unchecked") private static <T> T getCachedReference(Project project, String key, Supplier<T> supplier) { if (project == null) { throw new IllegalArgumentException("Gradle project reference cannot be null."); } Project rootProject = project.getRootProject(); ...
python
def treat_machine_dict(machine): ''' Make machine presentable for outside world. !!!Modifies the input machine!!! @param machine: @type machine: dict @return: the modified input machine @rtype: dict ''' machine.update({ 'id': machine.get('id', ''), 'image': machine....
java
protected void marshalSaxResult(Object graph, SAXResult saxResult) throws XmlMappingException { ContentHandler contentHandler = saxResult.getHandler(); Assert.notNull(contentHandler, "ContentHandler not set on SAXResult"); LexicalHandler lexicalHandler = saxResult.getLexicalHandler(); marshalSaxHandlers(graph, ...
python
def _str_to_windows(self, input_str, window_length, curse_forward): """ Divide an input string to a list of substrings based on window_length and curse_forward values :param input_str: str :param window_length: int :param curse_forward: int :return: list [str] """...
java
public Tag decorate(Tag tag) { if (XHTML_NAMESPACE.equals(tag.getNamespace())) { String n = tag.getLocalName(); if ("a".equals(n)) { return new Tag(tag.getLocation(), HtmlLibrary.NAMESPACE, "commandLink", tag.getQName(), tag ...
java
protected static void requestAuthenticated(final Request request) { if (null == request) { return; } if (!WonderPush.isInitialized()) { WonderPush.safeDefer(new Runnable() { @Override public void run() { requestAuthenti...
python
def visit_Num(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s number as string.""" return str(node.n)
java
@Override public IPermission newPermission(String owner, IAuthorizationPrincipal principal) { IPermission p = getPermissionStore().newInstance(owner); if (principal != null) { String pString = getPrincipalString(principal); p.setPrincipal(pString); } return p;...
python
def Convert(self, metadata, interface, token=None): """Converts Interface to ExportedNetworkInterfaces.""" ip4_addresses = [] ip6_addresses = [] for addr in interface.addresses: if addr.address_type == addr.Family.INET: ip4_addresses.append(addr.human_readable_address) elif addr.addr...
java
private void init() { TreeNode delegateRoot = null; if (delegate != null) { delegateRoot = (TreeNode) delegate.getRoot(); } thisToDelegate.clear(); delegateToThis.clear(); if (delegateRoot == null) { root = null; ...
java
public InjectorBuilder combineWith(Module ... modules) { List<Module> m = new ArrayList<>(); m.add(module); m.addAll(Arrays.asList(modules)); this.module = Modules.combine(m); return this; }
java
@Override public final IoBuffer putChar(int index, char value) { autoExpand(index, 2); buf().putChar(index, value); return this; }
java
@Override public StreamOperatorStateContext streamOperatorStateContext( @Nonnull OperatorID operatorID, @Nonnull String operatorClassName, @Nonnull KeyContext keyContext, @Nullable TypeSerializer<?> keySerializer, @Nonnull CloseableRegistry streamTaskCloseableRegistry, @Nonnull MetricGroup metricGroup) thr...
java
private void collectBindings(List<SitebricksModule.LinkingBinder> bindings, Set<PageBook.Page> pagesToCompile) { // Reverse the method map for easy lookup of HTTP method annotations. Map<Class<? extends Annotation>, String> methodSet = null; //go thru bindings and obtain pag...
java
public boolean contains(int o) { if (isEmpty() || o > last || o < 0) { return false; } // check if the element is within a literal word int block = maxLiteralLengthDivision(o); int bit = maxLiteralLengthModulus(o); for (int i = 0; i <= lastWordIndex; i++) { final int w =...
python
def default(self, o): """ Overriding default method for JSON encoding. This method does two things: (a) If an object has a to_dict property, return the to_dict output. (b) If the @module and @class keys are not in the to_dict, add them to the output automatically. If the object h...
python
def writeString(self, u): """ Write a unicode to the data stream. """ s = self.context.getBytesForString(u) self.writeBytes(s)
java
public int getFirstPredicateOpPos(int opPos) throws javax.xml.transform.TransformerException { int stepType = m_opMap.elementAt(opPos); if ((stepType >= OpCodes.AXES_START_TYPES) && (stepType <= OpCodes.AXES_END_TYPES)) { return opPos + m_opMap.elementAt(opPos + 2); } else...
java
public static final int pwr2LawNext(final int ppo, final int curPoint) { final int cur = (curPoint < 1) ? 1 : curPoint; int gi = (int)round(log2(cur) * ppo); //current generating index int next; do { next = (int)round(pow(2.0, (double) ++gi / ppo)); } while ( next <= curPoint); return next...
java
@Override public Object readValue(final Attribute _attribute, final List<Object> _objectList) throws CacheReloadException { final Object ret; if (!_attribute.getSqlColNames().isEmpty()) { if (_objectList.size() < 1) { ret = null; ...
python
def list_tags(self): """ List Tags and return JSON encoded result. """ try: tags = Tags.list() except NipapError, e: return json.dumps({'error': 1, 'message': e.args, 'type': type(e).__name__}) return json.dumps(tags, cls=NipapJSONEncoder)
java
public void setTargetLocations(java.util.Collection<TargetLocation> targetLocations) { if (targetLocations == null) { this.targetLocations = null; return; } this.targetLocations = new com.amazonaws.internal.SdkInternalList<TargetLocation>(targetLocations); }
python
def get_all_files_in_range(dirname, starttime, endtime, pad=64): """Returns all files in dirname and all its subdirectories whose names indicate that they contain segments in the range starttime to endtime""" ret = [] # Maybe the user just wants one file... if os.path.isfile(dirname): ...
python
def parse(self): """Parse our string and return a Survey object, None, or raise :exc:`ParseException`""" if not self.survey_str: return None lines = self.survey_str.splitlines() if len(lines) < 10: raise ParseException("Expected at least 10 lines in a Compass Surv...
java
protected JwtSigner createSigner(SignatureAlgorithm alg, Key key) { return new DefaultJwtSigner(alg, key, base64UrlEncoder); }
python
def validate (properties): """ Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties. """ if isinstance(properties, Property): properties = [properties] assert is_iterable_typed(properties, Property) for p in properties...
java
@SideOnly(Side.CLIENT) public static void addDestroyEffects(World world, BlockPos pos, ParticleManager particleManager, IBlockState... states) { if (ArrayUtils.isEmpty(states)) states = new IBlockState[] { world.getBlockState(pos) }; byte nb = 4; ParticleDigging.Factory factory = new ParticleDigging.Factory...