language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def on_click_plot_widget(self, event): """ When the plot control is toggled, set visibility and hand down source""" self.plot.source = self.sources self.plot.visible = event.new if self.plot.visible: self.plot.watchers.append( self.select.widget.link(self.plot...
python
def get_redirect_url(request): """Redirects to referring page, or CAS_REDIRECT_URL if no referrer is set. """ next_ = request.GET.get(REDIRECT_FIELD_NAME) if not next_: redirect_url = resolve_url(django_settings.CAS_REDIRECT_URL) if django_settings.CAS_IGNORE_REFERER: ne...
java
public TileSetColorCSPACE createTileSetColorCSPACEFromString(EDataType eDataType, String initialValue) { TileSetColorCSPACE result = TileSetColorCSPACE.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + ...
python
def apply_on_csv_string(rules_str, func): """ Splits a given string by comma, trims whitespace on the resulting strings and applies a given ```func``` to each item. """ splitted = rules_str.split(",") for str in splitted: func(str.strip())
java
boolean canBeFoldedWith(MouseState ms) { return ms.buttonsPressed.equals(buttonsPressed) && ms.wheel == wheel; }
python
def sort(self, key, *get_patterns, by=None, offset=None, count=None, asc=None, alpha=False, store=None): """Sort the elements in a list, set or sorted set.""" args = [] if by is not None: args += [b'BY', by] if offset is not None and count is not Non...
java
@Override public boolean createExtensionsTable() { verifyWritable(); boolean created = false; ExtensionsDao dao = getExtensionsDao(); try { if (!dao.isTableExists()) { created = tableCreator.createExtensions() > 0; } } catch (SQLException e) { throw new GeoPackageException("Failed to check if "...
java
@SuppressWarnings("unchecked") public ITemplate getTemplate(String template, Object... args) { return getTemplate(null, template, args); }
python
def write_error(*args, **kwargs): """Redirectable wrapper for print sys.stderr statements.""" if _logger: kwargs.pop("end", None) kwargs.pop("file", None) _logger.error(*args, **kwargs) else: print(*args, file=sys.stderr, **kwargs)
java
private String isSpecialMBean(ObjectName nameObject) { String domain = nameObject.getDomain(); if ("org.apache.activemq".equals(domain)) { String destinationType = nameObject.getKeyProperty("destinationType"); // see: org.apache.activemq.command.ActiveMQDestination.getDestination...
java
@SideOnly(Side.CLIENT) public static void updateGui(TileEntity te) { if (te != currentTileEntity) return; currenGui.updateGui(); }
java
private void removeTimedOutLocks(long timeout) { int count = 0; long maxAge = System.currentTimeMillis() - timeout; boolean breakFromLoop = false; ObjectLocks temp = null; synchronized (locktable) { Iterator it = locktable.values().iterator(); /**...
java
public static TextCorpusStored compose(String lang, TextCorpusLayerStoredAbstract... layers) { TextCorpusStored tc = new TextCorpusStored(lang); for (TextCorpusLayerStoredAbstract layer : layers) { tc.layersInOrder[TextCorpusLayerTag.getFromClass(layer.getClass()).ordinal()] = layer; ...
java
protected void passOver(PageElement element) throws TechnicalException, FailureException { try { final String javascript = "var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0...
java
private boolean isFieldVisited(Object object, Field objectField, Field field) { Map<String, Set<String>> bag = visitedFields.get(object); if (bag == null) { return false; } String objectFiledKey = objectField == null ? "" : objectField.toGenericString(); Set<String> ...
python
def predict(self, X, exposure=None): """ preduct expected value of target given model and input X often this is done via expected value of GAM given input X Parameters --------- X : array-like of shape (n_samples, m_features), default: None containing the inp...
java
public static netprofile[] get_filtered(nitro_service service, String filter) throws Exception{ netprofile obj = new netprofile(); options option = new options(); option.set_filter(filter); netprofile[] response = (netprofile[]) obj.getfiltered(service, option); return response; }
python
def _augment_file(self, f): """ Augment a FileRecord with methods to get the data URL and to download, returning the updated file for use in generator functions :internal: """ def get_url(target): if target.file_size is None: return None ...
java
public VnetGatewayInner getVnetGateway(String resourceGroupName, String name, String vnetName, String gatewayName) { return getVnetGatewayWithServiceResponseAsync(resourceGroupName, name, vnetName, gatewayName).toBlocking().single().body(); }
python
def simple_password(request): """ Checks a password """ if request.method == "POST": form = PasswordForm(data=request.POST) if form.is_valid(): # TODO: set session with better param request.session["simple_auth"] = True return redirect(form.cleaned_dat...
python
def _get_operations(self, context): """Returns a list of operations that need to be performed to turn the cached source code into the one in the buffer.""" #Most of the time, the real-time update is going to fire with #incomplete statements that don't result in any changes being made ...
java
public com.google.protobuf.AnyOrBuilder getResponseOrBuilder() { if (resultCase_ == 5) { return (com.google.protobuf.Any) result_; } return com.google.protobuf.Any.getDefaultInstance(); }
python
def _set_mac_move(self, v, load=False): """ Setter method for mac_move, mapped from YANG variable /mac_address_table/mac_move (container) If this variable is read-only (config: false) in the source YANG file, then _set_mac_move is considered as a private method. Backends looking to populate this var...
python
def bn_drop_lin(n_in:int, n_out:int, bn:bool=True, p:float=0., actn:Optional[nn.Module]=None): "Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`." layers = [nn.BatchNorm1d(n_in)] if bn else [] if p != 0: layers.append(nn.Dropout(p)) layers.append(...
java
public AwsSecurityFindingFilters withNetworkSourceDomain(StringFilter... networkSourceDomain) { if (this.networkSourceDomain == null) { setNetworkSourceDomain(new java.util.ArrayList<StringFilter>(networkSourceDomain.length)); } for (StringFilter ele : networkSourceDomain) { ...
java
static public int indexOf(String[] strings, String targetString) { if (strings == null) return -1; for (int i = 0; i < strings.length; i++) { if (strings[i] == null) { if (targetString == null) { return i; } } else {...
java
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jSplitPane1 = new javax.swing.JSplitPane(); topWrapper = new javax.swing.JPanel(); ...
python
def xml(self, attribs = None,elements = None, skipchildren = False): """See :meth:`AbstractElement.xml`""" attribs = {} if not self.offset is None: attribs['{' + NSFOLIA + '}offset'] = str(self.offset) if self.parent and self.ref: attribs['{' + NSFOLIA + '}ref'] =...
python
def read_from_endpoint(self, endpoint, timeout=15): """ Blocking read from an endpoint. Will block until a message is received, or it times out. Also see :meth:`get_endpoint_queue` if you are considering calling this in a loop. .. warning:: Avoid calling this method from an e...
python
def prepare_model(module: Union[types.ModuleType, str], timestep: PeriodABC.ConstrArg = None): """Prepare and return the model of the given module. In usual HydPy projects, each hydrological model instance is prepared in an individual control file. This allows for "polluting" the nam...
python
def get_ext(self, format=None, **kwargs): """Returns new file extension based on a processor's `format` parameter. Overwrite if different extension should be set ex: `'.txt'` or `None` if this processor does not change file's extension. """ try: format = format or se...
python
def search_schema_path(self, index, **options): """ Builds a Yokozuna search Solr schema URL. :param index: a name of a yz solr schema :type index: string :param options: optional list of additional arguments :type index: dict :rtype URL string """ ...
python
def get_edges_with_citation(self, citation: Citation) -> List[Edge]: """Get the edges with the given citation.""" return self.session.query(Edge).join(Evidence).filter(Evidence.citation == citation)
python
def _init_map(self): """Have to call these all separately because they are "end" classes, with no super() in them. Non-cooperative.""" ItemTextsFormRecord._init_map(self) ItemFilesFormRecord._init_map(self) edXBaseFormRecord._init_map(self) IRTItemFormRecord._init_map(sel...
java
@Override public Collection<Event> findEvents(SearchCriteria criteria) { ensureInitialized(); Preconditions.checkNotNull(criteria, "criteria must be non-null"); Collection<Event> matches = new ArrayList<>(); User user = criteria.getUser(); DetectionPoint detectionPoint = criteria.getDetectionPo...
java
@Override protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException { File repoFile = null; try { repoFile = new File(getSettings().getDataDirectory(), "jsrepository.json"); } catch (FileNotFoundException ex) { this.setEnabled(false); ...
java
public void setInstanceGroupIds(java.util.Collection<String> instanceGroupIds) { if (instanceGroupIds == null) { this.instanceGroupIds = null; return; } this.instanceGroupIds = new com.amazonaws.internal.SdkInternalList<String>(instanceGroupIds); }
python
def from_data(room, conn, data): """Construct a ChatMessage instance from raw protocol data""" files = list() rooms = dict() msg = str() for part in data["message"]: ptype = part["type"] if ptype == "text": val = part["value"] ...
java
public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) { if (callable == null) throw new NullPointerException(); return new PrivilegedCallableUsingCurrentClassLoader<T>(callable); }
java
public int getSpanFlags(Object what) { int count = mSpanCount; Object[] spans = mSpans; for (int i = count - 1; i >= 0; i--) { if (spans[i] == what) { return mSpanFlags[i]; } } return 0; }
python
def on_unexpected_error(e): # pragma: no cover """Catch-all error handler Unexpected errors will be handled by this function. """ sys.stderr.write('Unexpected error: {} ({})\n'.format( str(e), e.__class__.__name__)) sys.stderr.write('See file slam_error.log for additional details.\n') ...
python
def _parse_makefile(filename, vars=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ # Regexes needed for parsing Makefile (and similar syntaxes...
java
public ServiceFuture<ApplicationGatewayBackendHealthInner> backendHealthAsync(String resourceGroupName, String applicationGatewayName, final ServiceCallback<ApplicationGatewayBackendHealthInner> serviceCallback) { return ServiceFuture.fromResponse(backendHealthWithServiceResponseAsync(resourceGroupName, applica...
java
public List<String> getPathsForBuckets(CmsFlexRequestKey key) { PathsBean pathBean = key.getPaths(); List<String> paths = Lists.newArrayList(); if (m_uri != null) { paths.add(pathBean.getUri()); paths.add(pathBean.getDetailElement()); } if (m_site != null...
java
public void setListSymbol(Chunk symbol) { if (this.symbol == null) { this.symbol = symbol; if (this.symbol.getFont().isStandardFont()) { this.symbol.setFont(font); } } }
python
def export(self, out_filename): """Export desired threads as a zipfile to out_filename. """ with zipfile.ZipFile(out_filename, 'w', zipfile.ZIP_DEFLATED) as arc: id_list = list(self.get_thread_info()) for num, my_info in enumerate(id_list): logging.info('W...
python
def _apply_validator_chain(chain, value, handler): """Apply validators in sequence to a value.""" if hasattr(chain, 'validate'): # not a list chain = [chain, ] for validator in chain: if hasattr(validator, 'validate'): value = validator.validate(value, handler) else: ...
java
public Vector3i set(int index, IntBuffer buffer) { MemUtil.INSTANCE.get(this, index, buffer); return this; }
java
public EList<JvmAnnotationReference> getValues() { if (values == null) { values = new EObjectContainmentEList<JvmAnnotationReference>(JvmAnnotationReference.class, this, TypesPackage.JVM_ANNOTATION_ANNOTATION_VALUE__VALUES); } return values; }
java
@Override public Long hdel(String key, long field) { return this.hdel(key, Long.toString(field)); }
java
private void print(String level, SAXParseException exception) { if (level.equals("warning")) { logger.warn("** " + level + ": " + exception.getMessage()); logger.warn(" URI = " + exception.getSystemId()); logger.warn(" line = " + exception.getLineNumber()); } els...
java
private boolean buildList(List<List<Vertex>> theList, int index, BuildStep follow) { // Each time this method is called, we're examining a new list // from the global list. So, we have to start by getting the list // that contains the set of Vertexes we're consider...
python
def um_date_to_date(d): """ Convert a string with format 'year, month, day, hour, minute, second' to a datetime date. """ return datetime.datetime(year=d[0], month=d[1], day=d[2], hour=d[3], minute=d[4], second=d[5])
java
protected int countToken(String token, String target) { int tokenIndex = 0; int count = 0; while (tokenIndex != -1) { tokenIndex = target.indexOf(token, tokenIndex); if (tokenIndex > -1) { tokenIndex++; count++; } } ...
java
public void saveContainerpage(final Runnable... afterSaveActions) { if (hasPageChanged()) { final CmsRpcAction<Long> action = new CmsRpcAction<Long>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override ...
python
def safe_datetime_cast(self, col): """Parses string values into datetime. Args: col(pandas.DataFrame): Data to transform. Returns: pandas.Series """ casted_dates = pd.to_datetime(col[self.col_name], format=self.date_format, errors='coerce') if l...
python
def _parse_patient_variants(self, file): """ :param file: file handler :return: """ patient_var_map = self._convert_variant_file_to_dict(file) gene_coordinate_map = self._parse_gene_coordinates( self.map_files['gene_coord_map']) rs_map = self._parse_rs...
python
def fix_normals(self, multibody=None): """ Find and fix problems with self.face_normals and self.faces winding direction. For face normals ensure that vectors are consistently pointed outwards, and that self.faces is wound in the correct direction for all connected compo...
java
public static <T> Stream<T> findAll(Class<T> clazz) { ServiceLoader<T> load = ServiceLoader.load(clazz); return StreamSupport.stream(load.spliterator(), false); }
java
public static boolean doRaid(Configuration conf, FileStatus stat, Path destPath, Codec codec, Statistics statistics, Progressable reporter, boolean doSimulate, int targetRepl, int metaRepl) throws IOException { boolean succeed = false; for (EncodingCandidate ec : RaidNode.splitPaths(conf, ...
java
@SuppressWarnings("unchecked") public static <T> Iterable<String> getSubclassesNames(Class<T> superClass, ClassLoader classLoader) { return readIndexFile(classLoader, SUBCLASS_INDEX_PREFIX + superClass.getCanonicalName()); }
java
public static <T extends Comparable<?>> DateTimePath<T> dateTimePath(Class<? extends T> type, Path<?> parent, String property) { return new DateTimePath<T>(type, PathMetadataFactory.forProperty(parent, property)); }
python
def _derive_db(self): """ this may not have a client on __init__, so this is deferred to a @property descriptor """ client = self while hasattr(client, 'proxied'): client = client.proxied if hasattr(client, 'client'): client = client.client...
java
public void setArtifactId(final String artifactId) { if (artifactId == null && this.artifactId == null) { return; } else if (artifactId == null) { removeChild(this.artifactId); this.artifactId = null; } else if (this.artifactId == null) { this.arti...
python
def add_chain(self, chain): """ Add block in a chain in the correct order. Also add all of the blocks to the cache before doing a purge. """ with self._lock: chain.sort(key=lambda x: x.block_num) for block in chain: block_id = block.header_...
java
public static YamlNode nullToNode(YamlNode value) { return Optional.ofNullable(value).orElseGet(YamlNullNode::instance); }
java
@Override public Void call() throws Exception { OutputStream out = null; InputStream in = null; try { out = new FileOutputStream(destination); in = new FileInputStream(source); JasperCompileManager.compileReportToStream(in, out); if (verbose) {...
python
def _handledFailedSuccessor(self, jobNode, jobGraph, successorJobStoreID): """Deal with the successor having failed. Return True if there are still active successors. Return False if all successors have failed and the job is queued to run to handle the failed successors.""" logger.debug(...
java
private boolean canMoveValue(Scope scope, Node valueNode) { // the value is only movable if it's // a) nothing, // b) a constant literal, // c) a function, or // d) an array/object literal of movable values. // e) a function stub generated by CrossChunkMethodMotion. if (valueNode == null || ...
python
def validateMasterArgument(self, master_arg): """ Parse the <master> argument. @param master_arg: the <master> argument to parse @return: tuple of master's host and port @raise UsageError: on errors parsing the argument """ if master_arg[:5] == "http:": ...
java
public <T> List<T> getBeans(Class<T> klass) { List<T> list = new ArrayList<>(); for (String name : getIoc().getNamesByType(klass)) { if (name == null) continue; list.add(getIoc().get(klass, name)); } return list; }
python
def signup(request, signup_form=SignupForm, template_name='userena/signup_form.html', success_url=None, extra_context=None): """ Signup of an account. Signup requiring a username, email and password. After signup a user gets an email with an activation link used to activate their ...
java
protected List<CmsResource> getSubscribedResources(CmsObject cms, String param, int numResults) throws CmsException { List<CmsResource> result = OpenCms.getSubscriptionManager().readSubscribedResources( cms, getSubscriptionFilter(cms, param)); Collections.sort(result, I_CmsR...
python
def tokenize(self, docs): """ The first pass consists of converting documents into "transactions" (sets of their tokens) and the initial frequency/support filtering. Then iterate until we close in on a final set. `docs` can be any iterator or generator so long as it yie...
java
public String loadPreference(String key, String defaultValue) { String value = getSharedPreferences().getString(key, defaultValue); logLoad(key, value); return value; }
python
def _remap_fields(cls, kwargs): """Map fields from kwargs into dict acceptable by NIOS""" mapped = {} for key in kwargs: if key in cls._remap: mapped[cls._remap[key]] = kwargs[key] else: mapped[key] = kwargs[key] return mapped
python
def build_and_install_wheel(python): """Build a binary distribution wheel and install it""" dist_type = "bdist_wheel" if not SDIST else "sdist" return_code = run_command("{} setup.py {}".format(python, dist_type)) if return_code != 0: print("Building and installing wheel failed.") exit(r...
java
public static double pow(Number baseNumber, int exponent) { return exponent < 1 ? 1 : exponent > 1 ? baseNumber.doubleValue() * pow(baseNumber, exponent - 1) : baseNumber.doubleValue(); }
java
public void warning( String sourceClass, String sourceMethod, String msg ) { logp(Level.WARNING, sourceClass, sourceMethod, msg); }
java
public static ExtractFromRow extractUniqueKey( final int rowWidth, TypeSystem types ) { final TypeFactory<NodeKey> keyType = types.getNodeKeyFactory(); assert rowWidth > 0; if (rowWidth == 1) { return new ExtractFromRow() { ...
java
@Override public CreateConfigurationSetResult createConfigurationSet(CreateConfigurationSetRequest request) { request = beforeClientExecution(request); return executeCreateConfigurationSet(request); }
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.CHARACTER_ROTATION__CHAR_ROT: return CHAR_ROT_EDEFAULT == null ? charRot != null : !CHAR_ROT_EDEFAULT.equals(charRot); } return super.eIsSet(featureID); }
java
public void init(BaseField field, Record record, String keyAreaName, boolean bCloseOnFree, Converter convFlag) { m_convFlag = convFlag; super.init(field, record, keyAreaName, bCloseOnFree, false, true); }
java
public final static String process(final File file, final Configuration configuration) throws IOException { final FileInputStream input = new FileInputStream(file); final String ret = process(input, configuration); input.close(); return ret; }
java
private Map<Name, ExecutableElement> noArgMethodsIn(DeclaredType in) { TypeElement autoValueType = MoreElements.asType(typeUtils.asElement(in)); List<ExecutableElement> allMethods = ElementFilter.methodsIn(elementUtils.getAllMembers(autoValueType)); Map<Name, ExecutableElement> map = new LinkedHashM...
java
public void marshall(GetVoiceConnectorTerminationRequest getVoiceConnectorTerminationRequest, ProtocolMarshaller protocolMarshaller) { if (getVoiceConnectorTerminationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { pr...
java
public void setRoomConfigs(String roomName, HashMap<String, String> customConfigs) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { MUCLightSetConfigsIQ mucLightSetConfigIQ = new MUCLightSetConfigsIQ(room, roomName, customConfigs); connection.crea...
java
public static boolean delete(Path targetPath) { debug(log, "delete", targetPath); try { Files.delete(targetPath); return true; } catch (Exception e) { return JMExceptionManager.handleExceptionAndReturnFalse(log, e, "delete", targetPath); ...
java
public void addVirtualSelectNode(Integer originalId, Integer virtualId, List<String> selectedNames) { if (virtualSelectNodes.containsKey(virtualId)) { throw new IllegalStateException("Already has virtual select node with id " + virtualId); } virtualSelectNodes.put(virtualId, new Tuple2<Integer, List<Stri...
python
def shift_view(request, semester, pk, profile=None): """ View the details of a particular RegularWorkshift. """ shift = get_object_or_404(RegularWorkshift, pk=pk) page_name = shift.workshift_type.title if shift.is_manager_shift: president = Manager.objects.filter( incumbent_...
java
public static FastMoney ofMinor(CurrencyUnit currency, long amountMinor) { return ofMinor(currency, amountMinor, currency.getDefaultFractionDigits()); }
python
def nside2pixarea(nside, degrees=False): """Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`.""" area = nside_to_pixel_area(nside) if degrees: return area.to(u.deg ** 2).value else: return area.to(u.sr).value
java
@Deprecated public static void createAndRegisterWithMonitoredResource( Duration exportInterval, MonitoredResource monitoredResource) throws IOException { checkNotNull(exportInterval, "exportInterval"); checkNotNull(monitoredResource, "monitoredResource"); checkArgument( !DEFAULT_PROJECT_ID.i...
python
def _create_enum_class(ffi, type_name, prefix, flags=False): """Returns a new shiny class for the given enum type""" class _template(int): _map = {} @property def value(self): return int(self) def __str__(self): return self._map.get(self, "Unknown") ...
java
@Override public Set<String> getSupportedOptions() { return new HashSet<String>(Arrays.asList(IFIXES_OPTION, VERBOSE_OPTION)); }
python
def list_dvss(datacenter=None, dvs_names=None, service_instance=None): ''' Returns a list of distributed virtual switches (DVSs). The list can be filtered by the datacenter or DVS names. datacenter The datacenter to look for DVSs in. Default value is None. dvs_names List of...
python
def add_source(self, tier): """ Schedule this tier to be called when another tier emits. """ tier.add_dest(self) self.sources.append(tier)
python
def print_computation_log(self, aggregate = False): """ Print the computation log of a simulation. If ``aggregate`` is ``False`` (default), print the value of each computed vector. If ``aggregate`` is ``True``, only print the minimum, maximum, and average value of each comp...
python
def substitute_minor_for_major(progression, substitute_index, ignore_suffix=False): """Substitute minor chords for its major equivalent. 'm' and 'm7' suffixes recognized, and ['II', 'III', 'VI'] if there is no suffix. Examples: >>> substitute_minor_for_major(['VI'], 0) ['I'] >>> su...
java
public boolean compare(Object o) { if (!basicEquals(o)) return false; QueryParameter that = (QueryParameter) o; // compare sources to have the same select no matter of letter-case and // white spaces if (!StringUtil.equalsText(source, that.source)) return false; if (!StringUtil.equalsText(defaultSou...