language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _check_cores_output_sizes(self): """Checks the output_sizes of the cores of the DeepRNN module. Raises: ValueError: if the outputs of the cores cannot be concatenated along their first dimension. """ for core_sizes in zip(*tuple(_get_flat_core_sizes(self._cores))): first_core_li...
java
public ListAssert<Object> isArray() { Node node = assertType(ARRAY); return new JsonListAssert((List<?>)node.getValue(), path.asPrefix(), configuration) .as("Different value found in node \"%s\"", path); }
java
@Override public Object getValue(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException("context is null"); } Object result = null; if (isResolvable(base)) { int index = toIndex(null, property); List<?> list = (List<?>) base; result = index < 0 || i...
java
private void checkDirectory(File d, String dtype) { if (!d.isAbsolute()) { throw new IllegalArgumentException(dtype + " directory must be an absolute path (" + d.getPath() + ")"); } if (!d.exists()) { throw new IllegalArgumentException(dtype ...
java
@Override public HttpRequest convertRequest(Envelope request) { ByteBuf requestBuffer = Unpooled.buffer(request.getSerializedSize()); try { OutputStream outputStream = new ByteBufOutputStream(requestBuffer); request.writeTo(outputStream); outputStream.flush(); } catch (IOException e) { ...
python
def _select_features_to_plot(self, X): """ Select features to plot. feature_index is always used as the filter and if filter_names is supplied, a new feature_index is computed from those names. """ if self.feature_index: if self.feature_names: ...
java
private static boolean hasValidSubscriptionType(RosterPacket.Item item) { switch (item.getItemType()) { case none: case from: case to: case both: return true; default: return false; } }
java
@Deprecated protected void handleComputeFields(int julianDay) { int era, year; int[] fields = new int[3]; jdToCE(julianDay, getJDEpochOffset(), fields); // fields[0] eyear // fields[1] month // fields[2] day if (isAmeteAlemEra()) { era = AMETE_AL...
python
def get_assessment_part(self): """If there's an AssessmentSection ask it first for the part. This will take advantage of the fact that the AssessmentSection may have already cached the Part in question. """ if self._magic_parent_id is None: assessment_part_id = Id(s...
java
@Override public CPInstance fetchByG_ST_First(long groupId, int status, OrderByComparator<CPInstance> orderByComparator) { List<CPInstance> list = findByG_ST(groupId, status, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; }
java
public static SSLSocketFactory getSslSocketFactory() { if (!sslDisabled) { return SSLSocketFactory.getSocketFactory(); } try { final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {}; final SSLContext ctx = SSLContext.getInstance("TLS"); final X509TrustManager tm = new ...
java
void writeConfigPropsDeclare(Definition def, Writer out, int indent) throws IOException { if (getConfigProps(def) == null) return; for (int i = 0; i < getConfigProps(def).size(); i++) { writeWithIndent(out, indent, "/** " + getConfigProps(def).get(i).getName() + " */\n"); ...
python
def _set_status(self, status, result=None): """ update operation status :param str status: New status :param cdumay_result.Result result: Execution result """ logger.info( "{}.SetStatus: {}[{}] status update '{}' -> '{}'".format( self.__class__.__name...
python
def generate_wf_state_log(self): """ Logs the state of workflow and content of task_data. """ output = '\n- - - - - -\n' output += "WORKFLOW: %s ( %s )" % (self.current.workflow_name.upper(), self.current.workflow.name) output +...
python
def simplify(self, options=None): """ returns a dict describing a simple snapshot of this change, and its children if any. """ simple = { "class": type(self).__name__, "is_change": self.is_change(), "description": self.get_description(), ...
python
def _pusher_connect_handler(self, data): """Event handler for the connection_established event. Binds the shortlink_scanned event """ self.channel = self.pusher.subscribe(self.pos_callback_chan) for listener in self.pusher_connected_listeners: listener(data)
python
def _run_raw(self, cmd, ignore_errors=False): """Runs command directly, skipping tmux interface""" # TODO: capture stdout/stderr for feature parity with aws_backend result = os.system(cmd) if result != 0: if ignore_errors: self.log(f"command ({cmd}) failed.") assert False, "_run_ra...
java
public ISREInstall getDefaultSRE() { final Object[] objects = this.sresList.getCheckedElements(); if (objects.length == 0) { return null; } return (ISREInstall) objects[0]; }
python
def _handle_processing_error(err, errstream, client): """Handle ProcessingError exceptions.""" errors = sorted(err.events, key=operator.attrgetter("index")) failed = [e.event for e in errors] silent = all(isinstance(e.error, OutOfOrderError) for e in errors) if errstream: _deliver_errored_e...
python
def install_packages(): """ Install a set of baseline packages and configure where necessary """ if env.verbosity: print env.host, "INSTALLING & CONFIGURING NODE PACKAGES:" #Get a list of installed packages p = run("dpkg -l | awk '/ii/ {print $2}'").split('\n') #Remove apparmor...
python
def _distribution_info(self): """Creates the distribution name and the expected extension for the CSPICE package and returns it. :return (distribution, extension) tuple where distribution is the best guess from the strings available within the platform_urls list ...
java
public Property getProperty(String... name) { if (name == null || name.length == 0) return null; for (Property p : properties) { if (Objects.equals(name[0], p.name)) { if (name.length == 1) return p; else return p.getPr...
java
public static String documentToPrettyString(Document document) { StringWriter stringWriter = new StringWriter(); OutputFormat prettyPrintFormat = OutputFormat.createPrettyPrint(); XMLWriter xmlWriter = new XMLWriter(stringWriter, prettyPrintFormat); try { xmlWriter.write(doc...
python
def get_last_lineno(node): """Recursively find the last line number of the ast node.""" max_lineno = 0 if hasattr(node, "lineno"): max_lineno = node.lineno for _, field in ast.iter_fields(node): if isinstance(field, list): for value in field: if isinstance(v...
java
public Collection<Book> getAvailableBooks() { synchronized (librarian) { Collection<Book> books = new LinkedList<Book>(); for (Entry<String, Integer> entry : isbns_to_quantities.entrySet()) { if (entry.getValue() > 0) { books.add(getBook(entry.getKey()...
java
public static String padRight(CharSequence self, Number numberOfChars, CharSequence padding) { String s = self.toString(); int numChars = numberOfChars.intValue(); if (numChars <= s.length()) { return s; } else { return s + getPadding(padding.toString(), numChars ...
java
public void setField(String name, MLArray value, int index) { keys.add(name); currentIndex = index; if ( mlStructArray.isEmpty() || mlStructArray.size() <= index ) { mlStructArray.add(index, new LinkedHashMap<String, MLArray>() ); } mlStructArray....
java
public LocalTime withSecond(int second) { if (this.second == second) { return this; } SECOND_OF_MINUTE.checkValidValue(second); return create(hour, minute, second, nano); }
python
def properties_dict_for(self, index): """ Return a dictionary, containing properties as keys and indices as index Thus, the indices for each constraint, which is contained will be collected as one dictionary Example: let properties: 'one':[1,2,3,4], 'two':[3,5,6] ...
java
protected boolean hasOnlyProblemResources() { return m_model.getGroups().get(m_groupIndex).getResources().size() == m_model.countResourcesInGroup( new CmsPublishDataModel.HasProblems(), m_model.getGroups().get(m_groupIndex).getResources()); }
java
public List<T> apply(List<T> selectedCandidates, Random rng) { List<T> population = selectedCandidates; for (EvolutionaryOperator<T> operator : pipeline) { population = operator.apply(population, rng); } return population; }
python
def _store_parameters(self): """Store startup params and config in datadir/.mlaunch_startup.""" datapath = self.dir out_dict = { 'protocol_version': 2, 'mtools_version': __version__, 'parsed_args': self.args, 'unknown_args': self.unknown_args, ...
python
def quantile_for_list_of_values(self, **kwargs): """Returns Manager containing quantiles along an axis for numeric columns. Returns: DataManager containing quantiles of original DataManager along an axis. """ if self._is_transposed: kwargs["axis"] = kwargs.get("a...
java
public static UserPreferences getProjectPreferences(IProject project, boolean forceRead) { try { UserPreferences prefs = (UserPreferences) project.getSessionProperty(SESSION_PROPERTY_USERPREFS); if (prefs == null || forceRead) { prefs = readUserPreferences(project); ...
python
def _get_jacobian_hessian_strategy(self): """ Figure out how to calculate the jacobian and hessian. Will return a tuple describing how best to calculate the jacobian and hessian, repectively. If None, it should be calculated using the available analytical method. :return...
python
def _key_parenleft(self, text): """Action for '('""" self.hide_completion_widget() if self.get_current_line_to_cursor(): last_obj = self.get_last_obj() if last_obj and not last_obj.isdigit(): self.insert_text(text) self.show_object_i...
java
public static CommerceDiscountRel fetchByCN_CPK_Last(long classNameId, long classPK, OrderByComparator<CommerceDiscountRel> orderByComparator) { return getPersistence() .fetchByCN_CPK_Last(classNameId, classPK, orderByComparator); }
java
public void messageReceived(Object message) { if (message instanceof Packet) { try { messageReceived(conn, (Packet) message); } catch (Exception e) { log.warn("Exception on packet receive", e); } } else { // raw buff...
java
public String get(final Object key) { if (this._current.containsKey(key)) { return this._current.get(key); } else if (this._parent != null) { return this._parent.get(key); } else { return null; } }
java
public static Object createInstance(String name, Object... args) throws Exception { return createInstance(name, (String) null, args); }
java
public static <A> RegExp<A> buildConcat(List<RegExp<A>> concatTerms) { if(concatTerms.isEmpty()) return new EmptyStr<A>(); Iterator<RegExp<A>> it = concatTerms.iterator(); RegExp<A> re = it.next(); while(it.hasNext()) { re = new Concat<A>(re, it.next()); } return re; }
java
public void pushBrowserHistory(String strHistory, String browserTitle, boolean bPushToBrowser) { if (bPushToBrowser) if (this.getBrowserManager() != null) this.getBrowserManager().pushBrowserHistory(strHistory, browserTitle); // Let browser know about the new screen }
python
def rgevolve_leadinglog(self, scale_out): """Compute the leading logarithmix approximation to the solution of the SMEFT RGEs from the initial scale to `scale_out`. Returns a dictionary with parameters and Wilson coefficients. Much faster but less precise that `rgevolve`. """ ...
python
def T2(word, rules): '''Split any VV sequence that is not a genuine diphthong or long vowel. E.g., [ta.e], [ko.et.taa]. This rule can apply within VVV+ sequences.''' WORD = word offset = 0 for vv in vv_sequences(WORD): seq = vv.group(1) if not phon.is_diphthong(seq) and not phon.is...
java
protected static void removeTralingZeros( StringBuilder sb ) { int endIndex = sb.length(); if (endIndex > 0) { --endIndex; int index = endIndex; while (sb.charAt(index) == '0') { --index; } if (index < endIndex) sb.delete(index ...
java
@SuppressWarnings("PMD.GuardLogStatement") public W acquire() throws InterruptedException { // Stop draining, because we obviously need this kind of buffers Optional.ofNullable(idleTimer.getAndSet(null)).ifPresent( timer -> timer.cancel()); if (createdBufs.get() < maximumBufs) { ...
java
public ServiceInstanceQuery getInQueryCriterion(String key, List<String> list){ QueryCriterion c = new InQueryCriterion(key, list); addQueryCriterion(c); return this; }
python
def to_xml(self): """Get this batch as XML""" assert self.connection != None s = '<?xml version="1.0" encoding="UTF-8"?>\n' s += '<InvalidationBatch xmlns="http://cloudfront.amazonaws.com/doc/%s/">\n' % self.connection.Version for p in self.paths: s += ' <Path>%s</...
java
@POST @Path("me/username") @RolesAllowed({"ROLE_ADMIN", "ROLE_USER"}) public Response changeUsername(@Context HttpServletRequest request, UsernameRequest usernameRequest) { Long userId = (Long) request.getAttribute(OAuth2Filter.NAME_USER_ID); return changeUsername(userId, usernameRequest); }
java
public static void loadCustomerProperties(Properties props){ for(Entry<Object, Object> entry : props.entrySet()){ setProperty((String)entry.getKey(), entry.getValue()); } }
java
@Override public int add(DownloadRequest request) throws IllegalArgumentException { checkReleased("add(...) called on a released ThinDownloadManager."); if (request == null) { throw new IllegalArgumentException("DownloadRequest cannot be null"); } return mRequestQueue.add...
python
def get_node(request): """MNCore.getCapabilities() → Node.""" api_major_int = 2 if d1_gmn.app.views.util.is_v2_api(request) else 1 node_pretty_xml = d1_gmn.app.node.get_pretty_xml(api_major_int) return django.http.HttpResponse(node_pretty_xml, d1_common.const.CONTENT_TYPE_XML)
python
def run_program(program, args=None, **subprocess_kwargs): """ Run program in a separate process. NOTE: returns the process object created by `subprocess.Popen()`. This can be used with `proc.communicate()` for example. If 'shell' appears in the kwargs, it must be False, otherwise ...
python
def profile_methods(self, method_list): """帮助函数执行时记录数据.""" self.method_exec_info = [] # 开始数据记录进程 self.record_thread.stop_flag = False self.record_thread.start() for name in method_list: if name not in self.check_macthing_object.MATCHING_METHODS.keys(): ...
java
public void extractZipEntry(final ZipFile zipFile, final ZipEntry target, final File toDirectory) throws IOException { ZipExtensions.extractZipEntry(zipFile, target, toDirectory); }
java
public Future<AuthenticationResult> acquireTokenByAuthorizationCode( final String authorizationCode, final URI redirectUri, final ClientCredential credential, final AuthenticationCallback callback) { this.validateAuthCodeRequestInput(authorizationCode, redirectUri, ...
python
def setup_injection_workflow(workflow, output_dir=None, inj_section_name='injections', exttrig_file=None, tags =None): """ This function is the gateway for setting up injection-generation jobs in a workflow. It should be possible for this function to...
python
def checkForDuplicateInputs(rootnames): """ Check input files specified in ASN table for duplicate versions with multiple valid suffixes (_flt and _flc, for example). """ flist = [] duplist = [] for fname in rootnames: # Look for any recognized CTE-corrected products f1 = f...
java
final public int PlusMinus() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case 7: jj_consume_token(7); {if (true) return Operator.PLUS;} break; case 8: jj_consume_token(8); {if (true) return Operator.MINUS;} break; default: jj_la1[6] = j...
python
def fix_e251(self, result): """Remove whitespace around parameter '=' sign.""" line_index = result['line'] - 1 target = self.source[line_index] # This is necessary since pycodestyle sometimes reports columns that # goes past the end of the physical line. This happens in cases li...
python
def validate_backup_window(window): """Validate PreferredBackupWindow for DBInstance""" hour = r'[01]?[0-9]|2[0-3]' minute = r'[0-5][0-9]' r = ("(?P<start_hour>%s):(?P<start_minute>%s)-" "(?P<end_hour>%s):(?P<end_minute>%s)") % (hour, minute, hour, minute) range_regex = re.compile(r) m...
java
public static String getName(String fileName){ int dot = fileName.lastIndexOf('.'); return dot==-1 ? fileName : fileName.substring(0, dot); }
python
def get_git_home(path='.'): """Get Git path from the current context.""" ctx = click.get_current_context(silent=True) if ctx and GIT_KEY in ctx.meta: return ctx.meta[GIT_KEY] from git import Repo return Repo(path, search_parent_directories=True).working_dir
java
@PostConstruct public void initialize() { try { Class.forName("org.hl7.fhir.instance.model.QuestionnaireResponse"); myValidateResponses = true; } catch (ClassNotFoundException e) { myValidateResponses = Boolean.FALSE; } }
python
def prox_soft(X, step, thresh=0): """Soft thresholding proximal operator """ thresh_ = _step_gamma(step, thresh) return np.sign(X)*prox_plus(np.abs(X) - thresh_, step)
python
def reloadFileOfCurrentItem(self, rtiRegItem=None): """ Finds the repo tree item that holds the file of the current item and reloads it. Reloading is done by removing the repo tree item and inserting a new one. The new item will have by of type rtiRegItem.cls. If rtiRegItem is None (the...
java
public int findNode(int element) { int hash = m_hash.getHash(element); int ptr = getFirstInBucket(hash); while (ptr != -1) { int e = m_lists.getElement(ptr); if (m_hash.equal(e, element)) { return ptr; } ptr = m_lists.getNext(ptr); } return -1; }
python
def get_dict(self, domain=None, path=None): """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements.""" dictionary = {} for cookie in iter(self): if (domain is None or cookie.dom...
python
def connect(dbapi_connection, connection_record): """ Called once by SQLAlchemy for each new SQLite DB-API connection. Here is where we issue some PRAGMA statements to configure how we're going to access the SQLite database. @param dbapi_connection: A newly connecte...
java
public void addHistoryEntry(Query q) { try { Query queryCopy = q.clone(); // remove it first in order to let it appear on the beginning of the list state.getHistory().removeItem(queryCopy); state.getHistory().addItemAt(0, queryCopy); searchView.getControlPanel().getQueryPanel().u...
python
def collect_blocks(self): """ Collect the blocks in a list """ if self.mode == 'spark': return self.values.tordd().sortByKey().values().collect() if self.mode == 'local': return self.values.values.flatten().tolist()
java
private static int readFully(InputStream in, ByteArrayOutputStream bout, int length) throws IOException { int read = 0; byte[] buffer = new byte[2048]; while (length > 0) { int n = in.read(buffer, 0, length<2048?length:2048); if (n <= 0) { brea...
python
def sudo_command(self, command, bufsize=-1): """Sudo a command on the SSH server. Delegates to :func`~ssh.Connection.exec_command` :param command: the command to execute :type command: str :param bufsize: interpreted the same way as by the built-in C{file()} function in python ...
python
def es_query_template(path): """ RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE :param path: THE NESTED PATH (NOT INCLUDING TABLE NAME) :return: (es_query, es_filters) TUPLE """ if not is_text(path): Log.error("expecting path to be a string") if path != ".": f0 = {} ...
python
def unbind(self, queue, exchange, routing_key='', arguments={}, ticket=None, cb=None): ''' Unbind a queue from an exchange. This is always synchronous. ''' args = Writer() args.write_short(ticket or self.default_ticket).\ write_shortstr(queue).\ ...
python
def add_event_listener(self, event, function): """ Add an event listen for a particular event. Depending on the event there may or may not be parameters passed to function. Most escape streams also allow for an empty set of parameters (with a default value). Providing these defa...
java
protected <T> T parse(JsonReaderI<T> mapper) throws ParseException { this.pos = -1; T result; try { read(); result = readFirst(mapper); if (checkTaillingData) { if (!checkTaillingSpace) skipSpace(); if (c != EOI) throw new ParseException(pos - 1, ERROR_UNEXPECTED_TOKEN, c); } } cat...
java
public Blog blogInfo(String blogName) { Map<String, String> map = new HashMap<String, String>(); map.put("api_key", this.apiKey); return requestBuilder.get(JumblrClient.blogPath(blogName, "/info"), map).getBlog(); }
java
@Override public JobExecutionResult execute(String jobName) throws Exception { Plan p = createProgramPlan(jobName); PlanExecutor executor = PlanExecutor.createLocalExecutor(); initLogging(); return executor.executePlan(p); }
java
private boolean observeJavaObject(Object object) { // Ignore pure JS objects, this is to avoid impacting pure Vue.js components if (object.getClass() == JsObject.class) { return false; } // Don't observe Java classes if (object instanceof Class) { return true; } // Check if we ...
java
@Override public void clear() { // iterate over all keys in originalMap and set them to null in deltaMap for (K key : originalMap.keySet()) { deltaMap.put(key, ErasureUtils.<Collection<V>>uncheckedCast(removedValue)); } }
python
def add_operations_bulk(self, payload): """Add operations to a group of agents. :param list payload: contains the informations necessary for the action. It's in the form [{"id": agent_id, "operations": operations}] With id that is an str containing only characters in "a-zA-Z0-9_-" and must be betwe...
python
def add_entity_errors( self, property_name, direct_errors=None, schema_errors=None ): """ Attach nested entity errors Accepts a list errors coming from validators attached directly, or a dict of errors produced by a nested schema. :param prope...
java
public static synchronized ClassLoader getClassLoader () { final Class caller = getCallerClass (0); final ClassLoadContext ctx = new ClassLoadContext (caller); return s_strategy.getClassLoader (ctx); }
java
public Flow withEntitlements(Entitlement... entitlements) { if (this.entitlements == null) { setEntitlements(new java.util.ArrayList<Entitlement>(entitlements.length)); } for (Entitlement ele : entitlements) { this.entitlements.add(ele); } return this; ...
python
def _check_global_settings(): """Makes sure that the global settings environment variable and file exist for configuration. """ global settings if settings is not None: #We must have already loaded this and everything was okay! return True from os import getenv result = ...
python
def cash(self): """ [float] 可用资金 """ return sum(account.cash for account in six.itervalues(self._accounts))
java
public void setISSN(String v) { if (Journal_Type.featOkTst && ((Journal_Type)jcasType).casFeat_ISSN == null) jcasType.jcas.throwFeatMissing("ISSN", "de.julielab.jules.types.Journal"); jcasType.ll_cas.ll_setStringValue(addr, ((Journal_Type)jcasType).casFeatCode_ISSN, v);}
python
def bounds_handler(ctx, param, value): """Handle different forms of bounds.""" retval = from_like_context(ctx, param, value) if retval is None and value is not None: try: value = value.strip(", []") retval = tuple(float(x) for x in re.split(r"[,\s]+", value)) asse...
java
public static ClassLoader getSystemToolClassLoader() { try { Class<? extends JavaCompiler> c = instance().getSystemToolClass(JavaCompiler.class, defaultJavaCompilerName); return c.getClassLoader(); } catch (Throwable e) { return trace(WARNING, e); ...
java
public boolean printData(PrintWriter out, int iPrintOptions) { this.addHiddenParam(out, TrxMessageHeader.LOG_TRX_ID, this.getProperty(TrxMessageHeader.LOG_TRX_ID)); return super.printData(out, iPrintOptions); // Don't print }
python
def create_regular_expression(self, regexp): """ Create a regular expression for this inspection situation context. The inspection situation must be using an inspection context that supports regex. :param str regexp: regular expression string :raises CreateElemen...
python
def insert_short(self, index, value): """Inserts an unsigned short in a certain position in the packet""" format = '!H' self.data.insert(index, struct.pack(format, value)) self.size += 2
python
async def _dump_tuple(self, writer, elem, elem_type, params=None): """ Dumps tuple of elements to the writer. :param writer: :param elem: :param elem_type: :param params: :return: """ if len(elem) != len(elem_type.f_specs()): raise Val...
python
def convolve(input, weights, mask=None, slow=False): """2 dimensional convolution. This is a Python implementation of what will be written in Fortran. Borders are handled with reflection. Masking is supported in the following way: * Masked points are skipped. * Parts of the input whic...
java
public <T> void serialize(SerializerContext serializerContext, ElementDescriptor<T> descriptor, T rootObject) throws SerializerException, IOException { serializerContext.serializer.startDocument(null, null); useNamespace(serializerContext, descriptor.qualifiedName); bindNamespaces(serializerContext); mChildWri...
java
private static Iterator<?> computeIteratedObjectIterator(final Object iteratedObject) { if (iteratedObject == null) { return Collections.EMPTY_LIST.iterator(); } if (iteratedObject instanceof Collection<?>) { return ((Collection<?>)iteratedObject).iterator(); } ...
java
protected final void addRepeatable(String annotationName, io.micronaut.core.annotation.AnnotationValue annotationValue) { if (StringUtils.isNotEmpty(annotationName) && annotationValue != null) { Map<String, Map<CharSequence, Object>> allAnnotations = getAllAnnotations(); addRepeatableIn...
python
def loadLayer(filename, name = None, provider=None): ''' Tries to load a layer from the given file :param filename: the path to the file to load. :param name: the name to use for adding the layer to the current project. If not passed or None, it will use the filename basename ''' name = na...
java
public TupleRefBuilder bindings( Stream<VarBinding> bindings) { bindings.forEach( binding -> tupleRef_.addVarBinding( binding)); return this; }