language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def runWizard( self ): """ Runs the current wizard. """ plugin = self.currentPlugin() if ( plugin and plugin.runWizard(self) ): self.accept()
java
@Override public void handleNotification(Notification notification, Object handback) { String notificationType = notification.getType(); if (notificationType.equals(JMXConnectionNotification.OPENED)) { managementContext.incrementManagementSessionCount(); } else if (notificationTy...
python
def make_public(self, container, ttl=None): """ Enables CDN access for the specified container, and optionally sets the TTL for the container. """ return self._set_cdn_access(container, public=True, ttl=ttl)
python
def init_git_version(cls, v_str): r"""Parse git version string and store the resulting tuple on self. :returns: the parsed version tuple Only the first 3 digits are kept. This is good enough for the few version dependent cases we need, and coarse enough to avoid more complicated ...
java
public static Set<String> extractDocAnnotation(String anno, JavadocComment jdoc){ String content = jdoc.getContent().replaceAll("\n[ \t]+\\* ?","\n"); //remove the * at the beginning of a line Set<String> result = new LinkedHashSet<>(); while(content.contains(anno)){ int begin = con...
python
def _get_unit_data_from_expr(unit_expr, unit_symbol_lut): """ Grabs the total base_value and dimensions from a valid unit expression. Parameters ---------- unit_expr: Unit object, or sympy Expr object The expression containing unit symbols. unit_symbol_lut: dict Provides the uni...
java
private void sendLockFailError( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp ) throws IOException { final Hashtable<String, WebdavStatus> errorList = new Hashtable<String, WebdavStatus>(); errorList.put( _path, SC_LOCKED ); sendReport( req, resp,...
python
def set_zero_config(self): """Set config such that radiative forcing and temperature output will be zero This method is intended as a convenience only, it does not handle everything in an obvious way. Adjusting the parameter settings still requires great care and may behave unepexctedly...
java
public ServiceFuture<OperationStatusResponseInner> beginPowerOffAsync(String resourceGroupName, String vmScaleSetName, String instanceId, final ServiceCallback<OperationStatusResponseInner> serviceCallback) { return ServiceFuture.fromResponse(beginPowerOffWithServiceResponseAsync(resourceGroupName, vmScaleSetNa...
java
public Vector3f lerp(Vector3fc other, float t, Vector3f dest) { dest.x = x + (other.x() - x) * t; dest.y = y + (other.y() - y) * t; dest.z = z + (other.z() - z) * t; return dest; }
python
def get_code(self): """Get the stub code for this node. The stub code for a node consists of the type annotations of its variables, followed by the prototypes of its functions/methods and classes. :sig: () -> List[str] :return: Lines of stub code for this node. """ ...
java
public boolean addConverter(byte[] source, byte[] destination, int n) { if (started) return false; TranscoderDB.Entry entry = TranscoderDB.getEntry(source, destination); if (entry == null) return false; Transcoder transcoder = entry.getTranscoder(); if (transcoder == null) r...
java
public static URI addPathComponent(URI uri, String component) { if (uri != null && component != null) try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), Optional.ofNullable(uri.getPath()).map(path -> join(path, component, '/')).orElse(component...
java
protected void prepareConduitSelector(Message message, URI currentURI, boolean proxy) { try { cfg.prepareConduitSelector(message); } catch (Fault ex) { LOG.warning("Failure to prepare a message from conduit selector"); } message.getExchange().put(ConduitSelector....
java
public NotificationChain basicSetOptions(Options newOptions, NotificationChain msgs) { Options oldOptions = options; options = newOptions; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SimpleAntlrPackage.ANTLR_GRAMMAR__OPTIONS, oldO...
python
def getPostStates(self): ''' Slightly extends the base version of this method by recalculating aLvlNow to account for the consumer's (potential) misperception about their productivity level. Parameters ---------- None Returns ------- None ...
java
public static CPRuleUserSegmentRel findByCommerceUserSegmentEntryId_Last( long commerceUserSegmentEntryId, OrderByComparator<CPRuleUserSegmentRel> orderByComparator) throws com.liferay.commerce.product.exception.NoSuchCPRuleUserSegmentRelException { return getPersistence() .findByCommerceUserSegmentEntry...
java
public HalfEdge getEdge(int i) { HalfEdge he = he0; while (i > 0) { he = he.next; i--; } while (i < 0) { he = he.prev; i++; } return he; }
java
private static SymbolType typeVariableOf(String typeVariable, final String name, final int arrayCount, final List<SymbolType> upperBounds, final List<SymbolType> lowerBounds) { return new SymbolType(name, arrayCount, upperBounds, lowerBounds, typeVariable); }
java
public static void writeResources(Element node, XMLResources resources, XMLBuilder builder) { if (resources != null) { final Element resourcesNode = builder.createElement(NODE_RESOURCES); for (final java.util.Map.Entry<Long, Entry> pair : resources.getPairs().entrySet()) { final Entry e = pair.getValue(); ...
python
def _extract_services_list_helper(services): """Extract a OrderedDict of {service: [ports]} of the supplied services for use by the other functions. The services object can either be: - None : no services were passed (an empty dict is returned) - a list of strings - A dictionary (optional...
java
public ServiceFuture<LiveEventInner> createAsync(String resourceGroupName, String accountName, String liveEventName, LiveEventInner parameters, Boolean autoStart, final ServiceCallback<LiveEventInner> serviceCallback) { return ServiceFuture.fromResponse(createWithServiceResponseAsync(resourceGroupName, accountN...
java
@SuppressWarnings({"UnusedDeclaration", "UnusedAssignment", "unchecked"}) public static void main(String[] pArgs) { int howMany = 1000; if (pArgs.length > 0) { howMany = Integer.parseInt(pArgs[0]); } long start; long end; /* int[] intArr...
java
protected static MessageResourceBundleFacade loadFacade(String path) { synchronized (cacheMap) { if (!initialized) { DisposableUtil.add(new Disposable() { public void dispose() { clear(); initialized = false; ...
java
public void encodeNBitUnsignedInteger(int b, int n) throws IOException { if (b < 0 || n < 0) { throw new IllegalArgumentException( "Encode negative value as unsigned integer is invalid!"); } assert (b >= 0); assert (n >= 0); ostream.writeBits(b, n); }
java
@Override public void command(String... args) { addArgument(File.class, "xml-config-file-path"); super.command(args); configFile = getArgument("xml-config-file-path"); readConfig(); if (watch) { Thread thread = new Thread(this, configFile+" wa...
python
def check_int_param(self, param, low, high, name): """ Check if the value of the given parameter is in the given range and an int. Designed for testing parameters like `mu` and `eps`. To pass this function the variable `param` must be able to be converted into a float wit...
java
public static void recycleNodes(Collection<AccessibilityNodeInfoCompat> nodes) { if (nodes == null) { return; } for (AccessibilityNodeInfoCompat node : nodes) { if (node != null) { node.recycle(); } } nodes.clear(); }
python
def get_package(name, version, paths=None): """Get an exact version of a package. Args: name (str): Name of the package, eg 'maya'. version (Version or str): Version of the package, eg '1.0.0' paths (list of str, optional): paths to search for package, defaults to `config.pa...
python
def reduce_cpu(f, x, axes, dtype): """NumPy's reduce in terms of fold.""" axes = _get_axes(axes, x.ndim) if not axes: return x permute = [n for n in range(x.ndim) if n not in axes] permute = axes + permute T = x.transpose(permute=permute) N = len(axes) t = T.type.at(N, dtype=d...
java
public boolean syncClonedListener(BaseField field, FieldListener listener, boolean bInitCalled) { if (!bInitCalled) ((WriteOnChangeHandler)listener).init(null, m_bRefreshAfterWrite); return super.syncClonedListener(field, listener, true); }
java
private static final int ntvGetType(int ntv) { return (ntv==NTV_NONE_) ? NumericType.NONE : (ntv<NTV_DIGIT_START_) ? NumericType.DECIMAL : (ntv<NTV_NUMERIC_START_) ? NumericType.DIGIT : NumericType.NUMERIC; }
java
public String getTableNames(boolean bAddQuotes) { return (m_tableName == null) ? Record.formatTableNames(ISSUE_HISTORY_FILE, bAddQuotes) : super.getTableNames(bAddQuotes); }
python
def remove_bgp(self, **kwargs): """Remove BGP process completely. Args: vrf (str): The VRF for this BGP process. rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. callback (function): A function executed u...
java
public ORecordIteratorCluster<REC> setRange(final long iFrom, final long iEnd) { firstClusterPosition = iFrom; rangeTo = iEnd; current.clusterPosition = firstClusterPosition; return this; }
java
static void ensureHostnamePatternMatchesDefaultHostname(String hostnamePattern, String defaultHostname) { if ("*".equals(hostnamePattern)) { return; } // Pretty convoluted way to validate but it's done only once and // we don't need to duplicate the pattern matching logic. ...
java
public static void requireArgValid(@NotNull final String name, @NotNull final String value) throws ConstraintViolationException { // CHECKSTYLE:ON final String trimmedValue = value.trim(); Contract.requireArgNotEmpty(name, trimmedValue); }
python
def preorder(self, funct, stopOn=None): """ Iterates in preorder, calling the function with the current node. If stopOn is set to True or False, it will stop on true or false. """ if funct(self.symbol) == stopOn and stopOn is not None: return stopOn if stopOn is ...
python
def transitive_subgraph_of_addresses_bfs(self, addresses, predicate=None, dep_predicate=None): """Returns the transitive dependency closure of `addresses` using BFS. :API: public ...
python
def _validated(self, data): """Validate data if any subschema validates it.""" errors = [] for sub in self.schemas: try: return sub(data) except NotValid as ex: errors.extend(ex.args) raise NotValid(' and '.join(errors))
java
public FluentSelect selectByValue(final String value) { executeAndWrapReThrowIfNeeded(new SelectByValue(value), Context.singular(context, "selectByValue", null, value), true); return new FluentSelect(super.delegate, currentElement.getFound(), this.context, monitor, booleanInsteadOfNotFoundException); ...
java
public static host_interface delete(nitro_service client, host_interface resource) throws Exception { resource.validate("delete"); return ((host_interface[]) resource.perform_operation(client, "delete"))[0]; }
java
public static <T> boolean forall(Iterator<T> iterator, Function1<? super T, Boolean> predicate) { if (predicate == null) throw new NullPointerException("predicate"); while(iterator.hasNext()) { if (!predicate.apply(iterator.next())) return false; } return true; }
java
public void setLicenseConfigurations(java.util.Collection<LicenseConfiguration> licenseConfigurations) { if (licenseConfigurations == null) { this.licenseConfigurations = null; return; } this.licenseConfigurations = new java.util.ArrayList<LicenseConfiguration>(licenseCo...
java
public static Object newInstanceFromName(String className, ClassLoader classLoader) { try { Class<?> clazz = Class.forName(className, true, classLoader); return clazz.newInstance(); } catch (Exception e) { String m = "Couldn't create instance from name " + classN...
python
def image_to_string(image, lang=None, config='', nice=0, output_type=Output.STRING): ''' Returns the result of a Tesseract OCR run on the provided image to string ''' args = [image, 'txt', lang, config, nice] return { ...
java
private void writeMainPage(int userPage, int oidPage, int schemaPage, int indexPage, int freeSpaceIndexPage, int pageCount, StorageChannelOutput out, long lastUsedOid, long txId) { rootPageID = (rootPageID + 1) % 2; out.seekPageForWrite(PAGE_TYPE.ROOT_PAGE, rootPages[rootPageID]); //********** ...
java
public ColorRecord getColorRecord (String className, String colorName) { ClassRecord record = getClassRecord(className); if (record == null) { log.warning("Requested unknown color class", "className", className, "colorName", colorName, new Exception()); return...
java
private String format(Object o) { return shellSession.format(o, Converter.INSPECT).toString(); }
python
def decode_keys(self, keys): """ Run the decoder on a dict of values """ return dict(((k, self.decode(v)) for k, v in six.iteritems(keys)))
java
public boolean isTerminated() { final Thread executingThread = this.environment.getExecutingThread(); if (executingThread.getState() == Thread.State.TERMINATED) { return true; } return false; }
python
def get_prime(bits, k=64): """ Return a random prime up to a certain length. This function uses random.SystemRandom. """ if bits % 8 != 0 or bits == 0: raise ValueError("bits must be >= 0 and divisible by 8") while True: n = int.from_bytes(os.urandom(bits // 8), "big") ...
python
def send(self, obj, encoding='utf-8'): """ Sends a python object to the backend. The object **must be JSON serialisable**. :param obj: object to send :param encoding: encoding used to encode the json message into a bytes array, this should match CodeEdit.file.encodin...
java
@Override public final String optString(final String key, final String defaultValue) { String result = optString(key); return result == null ? defaultValue : result; }
python
def linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis, enable_warning=True): """A datetime-version that takes datetime object list as x_axis """ numeric_datetime_axis = [ totimestamp(a_datetime) for a_datetime in datetime_axis ] numer...
java
private Set<Method> collectOverloadedMethods(JavaClass cls) { Set<Method> overloads = new HashSet<>(); Method[] methods = cls.getMethods(); int numMethods = methods.length; for (int i = 0; i < numMethods; i++) { boolean foundOverload = false; for (int j = i + ...
java
public void move(String resourceGroupName, String workflowName, WorkflowInner move) { moveWithServiceResponseAsync(resourceGroupName, workflowName, move).toBlocking().single().body(); }
java
public void normalize() { double angle = this.getAngle(); if (Utils.within(angle, 0, 1) || Utils.within(angle, 180, 1)) { // almost horizontal this.setLine(this.x1, this.y1, this.x2, this.y1); } else if (Utils.within(angle, 90, 1) || Utils.within(angle, 270, 1)) { // almost ...
python
def to_mesh(obj): ''' to_mesh(obj) yields a Mesh object that is equivalent to obj or identical to obj if obj is itself a mesh object. The following objects can be converted into meshes: * a mesh object * a tuple (coords, faces) where coords is a coordinate matrix and faces is a matrix of ...
python
def load_url(self, url, fname, repo=None, timeout=120, post=None, fail=False, write=True, json_sort=None, cache_only=False, archived_mode=None, ...
java
ServiceRefAmp lookup(String path, PodRef podCaller) { if (_linkServiceRef.address().startsWith("local:")) { int p = path.indexOf('/', 1); if (p > 0) { // champ path is /pod.0/path // return (ServiceRefAmp) _champService.lookup(path); return (ServiceRefAmp) _rampManager.s...
python
def mark_as_read(self, room_name): """ message_ids return an array with unread message ids ['131313231', '323131'] """ api_meth = self.set_user_items_url(room_name) message_ids = self.unread_items(room_name).get('chat') if message_ids: return self.post...
java
public PrintStream format(String format, Object ... args) { try { synchronized (this) { ensureOpen(); if ((formatter == null) || (formatter.locale() != Locale.getDefault())) formatter = new Formatter((Appendable) WeakProxy.forOb...
python
def logs(self, num=None, source=None, ps=None, tail=False): """Returns the requested log.""" # Bootstrap payload package. payload = {'logplex': 'true'} if num: payload['num'] = num if source: payload['source'] = source if ps: payloa...
java
public static boolean setFeatureStyle(PolylineOptions polylineOptions, GeoPackage geoPackage, FeatureRow featureRow, float density) { FeatureStyleExtension featureStyleExtension = new FeatureStyleExtension(geoPackage); return setFeatureStyle(polylineOptions, featureStyleExtension, featureRow, density)...
python
def prettify(elem): """Return a pretty-printed XML string for the Element.""" rough_string = E.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent=' ').strip()
java
protected void dupHideCheck(List<PDefinition> list, NameScope scope) { LexNameList allnames = af.createPDefinitionListAssistant().getVariableNames(list); for (ILexNameToken n1 : allnames) { LexNameList done = new LexNameList(); for (ILexNameToken n2 : allnames) { if (n1 != n2 && n1.equals(n2) && !...
java
public void marshall(MountPoint mountPoint, ProtocolMarshaller protocolMarshaller) { if (mountPoint == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(mountPoint.getContainerPath(), CONTAINERPATH_BIND...
python
def hline( self, x: int, y: int, width: int, bg_blend: int = tcod.constants.BKGND_DEFAULT, ) -> None: """Draw a horizontal line on the console. This always uses ord('─'), the horizontal line character. Args: x (int): The x coordinate from...
python
def _drop_membership_multicast_socket(self): """ Drop membership to multicast :rtype: None """ # Leave group self._multicast_socket.setsockopt( socket.IPPROTO_IP, socket.IP_DROP_MEMBERSHIP, self._membership_request ) se...
java
public void inc(E e, long n) { if (counters != null && counters.containsKey(e)) { counters.get(e).inc(n); } }
java
private String [] processName (String qName, boolean isAttribute, boolean useException) throws SAXException { String parts[] = nsSupport.processName(qName, nameParts, isAttribute); if (parts == null) { if (useException) throw makeException("U...
java
private <Q extends T> Q dispatch(final Q event, boolean stopOnFirstException) { if (event == null) { throw new IllegalArgumentException("event is null"); } if (this.baseClass != null && !this.baseClass.isAssignableFrom(event.getClass())) { throw new IllegalArgumentException("event of type " + event.getCla...
java
public static boolean recursiveClean(final File fileToRemove) { if (fileToRemove == null) return true; Boolean fileExists = Boolean.FALSE; final File f_fileToRemove = fileToRemove; try { fileExists = AccessController.doPrivileged(new java.security.PrivilegedExce...
java
public FutureData<PreparedHistoricsQuery> prepare(String hash, long start, long end, String name, String... sources) { return prepare(hash, start, end, name, -1, sources); }
java
public static double diffNormP1(DMatrixD1 a , DMatrixD1 b ) { if( a.numRows != b.numRows || a.numCols != b.numCols ) { throw new IllegalArgumentException("Both matrices must have the same shape."); } final int size = a.getNumElements(); double total=0; for( int ...
java
public WriteableScope dupUnshared(Symbol newOwner) { if (shared > 0) { //The nested Scopes might have already added something to the table, so all items //that don't originate in this Scope or any of its outer Scopes need to be cleared: Set<Scope> acceptScopes...
java
public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1, Date modified, long fileSize, ProgressListener listener) { URL uploadURL = CONTENT_URL_TEMPLATE.build(this.getAPI().getBaseUploadURL(), this.getID()); BoxMultipartRequest request = new Box...
java
private static void setPluginProps(final String pluginDirName, final AbstractPlugin plugin, final Properties props) throws Exception { final String author = props.getProperty(Plugin.PLUGIN_AUTHOR); final String name = props.getProperty(Plugin.PLUGIN_NAME); final String version = props.getPropert...
java
static final int crc8(final byte[] input, final int offset, final int len) { final int poly = 0x0D5; int crc = 0; for (int i = 0; i < len; i++) { final byte c = input[offset + i]; crc ^= c; for (int j = 0; j < 8; j++) { if ((crc & 0x80) != 0) { crc = ((crc << 1) ^ poly); } else { crc <<...
java
private String getOrInferGroup(Method method) { ShellMethod methodAnn = AnnotationUtils.getAnnotation(method, ShellMethod.class); if (!methodAnn.group().equals(ShellMethod.INHERITED)) { return methodAnn.group(); } Class<?> clazz = method.getDeclaringClass(); ShellCommandGroup classAnn = AnnotationUtils.get...
java
@Override public CommerceWarehouse findByG_C_Last(long groupId, long commerceCountryId, OrderByComparator<CommerceWarehouse> orderByComparator) throws NoSuchWarehouseException { CommerceWarehouse commerceWarehouse = fetchByG_C_Last(groupId, commerceCountryId, orderByComparator); if (commerceWarehouse !=...
python
def set_value(self, comp_str, comp_att): """ Set the value of component. By default, the component has a simple value. :param string comp_att: attribute associated with value of component :returns: None :exception: ValueError - incorrect value of component TEST:...
python
def get_person_by_nickname(self, nickname): """Retrieves a person by nickname""" return next((person for person in self.get_all_people() if person.nickname.lower() == nickname.lower()), None)
python
def _FindKeys(self, key, names, matches): """Searches the plist key hierarchy for keys with matching names. If a match is found a tuple of the key name and value is added to the matches list. Args: key (dict[str, object]): plist key. names (list[str]): names of the keys to match. mat...
python
def update_team_days_off(self, days_off_patch, team_context, iteration_id): """UpdateTeamDaysOff. Set a team's days off for an iteration :param :class:`<TeamSettingsDaysOffPatch> <azure.devops.v5_0.work.models.TeamSettingsDaysOffPatch>` days_off_patch: Team's days off patch containting a list of...
python
def read_header(stream): """Return tuple(version_long, num_entries) from the given stream""" type_id = stream.read(4) if type_id != b"DIRC": raise AssertionError("Invalid index file header: %r" % type_id) version, num_entries = unpack(">LL", stream.read(4 * 2)) # TODO: handle version 3: ext...
java
public GeneralNames get(String name) throws IOException { if (name.equalsIgnoreCase(ISSUER)) { return names; } else { throw new IOException("Attribute name not recognized by " + "CertAttrSet:CertificateIssuer"); } }
python
def http_context(self, worker_ctx): """ Attempt to extract HTTP context if an HTTP entrypoint was used. """ http = {} if isinstance(worker_ctx.entrypoint, HttpRequestHandler): try: request = worker_ctx.args[0] try: if reques...
python
def invoke(self, args, kwargs): """ Send the required soap message to invoke the specified method @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The resul...
java
public TechnologyTagModel addTagToFileModel(FileModel fileModel, String tagName, TechnologyTagLevel level) { Traversable<Vertex, Vertex> q = getGraphContext().getQuery(TechnologyTagModel.class) .traverse(g -> g.has(TechnologyTagModel.NAME, tagName)); TechnologyTagModel technology...
python
def mse(predicted, actual): """ Mean squared error of predictions. .. versionadded:: 0.5.0 Parameters ---------- predicted : ndarray Predictions on which to measure error. May contain a single or multiple column but must match `actual` in shape. actual : ndarray ...
java
protected final void addAllFilesToSuccessfullyUploadedFiles() { for (Iterator<UploadFile> iterator = params.files.iterator(); iterator.hasNext(); ) { UploadFile file = iterator.next(); if (!successfullyUploadedFiles.contains(file.path)) { successfullyUploadedFiles.add(fi...
python
def estimate_hz(self,R,z,dz=10.**-8.,**kwargs): """ NAME: estimate_hz PURPOSE: estimate the exponential scale height at R INPUT: R - Galactocentric radius (can be Quantity) dz - z range to use (can be Quantity) density kwargs ...
python
def remove_variable(self, name): """Remove a variable from the problem.""" index = self._get_var_index(name) # Remove from matrix self._A = np.delete(self.A, index, 1) # Remove from bounds del self.bounds[name] # Remove from var list del self._variables[na...
java
protected List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory) throws IOException { return getRecursiveThriftFiles(project, outputDirectory, new ArrayList<File>()); }
python
def parse_transmission_id(header, reference_id=None): """\ Returns the transmission ID of the cable. If no transmission identifier was found, ``None`` is returned. `header` The cable's header `reference_id` The cable's reference ID. """ m = _TID_PATTERN.search(header) if...
java
private void processArgs(final String[] arguments) { args = argumentParser.processArgs(arguments); final Map<String, Object> definedProps = new HashMap<>(args.definedProps); buildFile = args.buildFile; if (args.justPrintUsage || args.justPrintVersion || args.justPrintDiagnostics || args...
python
def verify_api(self, ret): ''' this method helps determine if the given stage_name is already on a deployment label matching the input api_name, swagger_file. If yes, returns abort with comment indicating already at desired state. If not and there is previous deployment labels i...
java
public static void decode(byte[] bytes, OutputStream out) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(bytes); decode(in, out, false); }