language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public final void ruleOpMulti() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXbase.g:496:2: ( ( ( rule__OpMulti__Alternatives ) ) ) // InternalXbase.g:497:2: ( ( rule__OpMulti__Alternatives ) ) { // InternalX...
python
def dump(device, destination, level=0, label=None, noerase=None): ''' Dump filesystem device to the media (file, tape etc). Required parameters: * **device**: XFS device, content of which to be dumped. * **destination**: Specifies a dump destination. Valid options are: * **label**: Label...
python
def add_shape(self, autoshape_type_id, left, top, width, height): """Return new |Shape| object appended to this shape tree. *autoshape_type_id* is a member of :ref:`MsoAutoShapeType` e.g. ``MSO_SHAPE.RECTANGLE`` specifying the type of shape to be added. The remaining arguments specify t...
python
def _merge_struct(lhs, rhs, type_): """Helper for '_merge_by_type'.""" fields = type_.struct_type.fields lhs, rhs = list(lhs.list_value.values), list(rhs.list_value.values) candidate_type = fields[len(lhs) - 1].type first = rhs.pop(0) if first.HasField("null_value") or candidate_type.code in _UN...
java
public static MethodNode findMethod(ClassNode clazz, String name) { for (MethodNode method : clazz.methods) { if (method.name.equals(name)) { return method; } } return null; }
python
def remove_handler(): """Remove the user, group and policies for Blockade.""" logger.debug("[#] Removing user, group and permissions for Blockade") client = boto3.client("iam", region_name=PRIMARY_REGION) iam = boto3.resource('iam') account_id = iam.CurrentUser().arn.split(':')[4] try: ...
java
public static DoubleMatrix2D subdiagonalMultiply(final DoubleMatrix2D A, final DoubleMatrix2D B){ final int r = A.rows(); final int rc = A.columns(); final int c = B.columns(); if(r != c){ throw new IllegalArgumentException("The result must be square"); } boolean useSparsity = A instanceof Spa...
java
public static File createCsvFile(String outputCsvPath, String model, String metaFilePath) { if (!outputCsvPath.endsWith(File.separator) && !outputCsvPath.equals("")) { outputCsvPath += File.separator; } String domeInfo = ""; if (metaFilePath != null) { try { ...
java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Special case methods are looked up from a map and invoked. // Do not trace because this includes some basic things like hashcode and equals. // Important special case methods will take care of tracing themselv...
java
static int indexOfSerial(final double[] incr, final double v) { int index = -1; for (int i = 0; i < incr.length && index == -1; ++i) { if (incr[i] >= v) { index = i; } } return index; }
java
public Assignment fullModel(final BDD bdd) { final int modelBDD = this.kernel.fullSatOne(bdd.index()); return createAssignment(modelBDD); }
python
def _get_filehandler_with_formatter(logname, formatter=None): """ Return a logging FileHandler for given logname using a given logging formatter :param logname: Name of the file where logs will be stored, ".log" extension will be added :param formatter: An instance of logging.Formatter or None if th...
java
@Override public KamNode replaceNode(KamNode kamNode, FunctionEnum function, String label) { final int nodeId = kamNode.getId(); final KamNode replacement = new KamNodeImpl(this, nodeId, function, label); return replaceNode(kamNode, replacement); }
java
public boolean createVolumes() throws TargetException { String zoneName = OpenstackIaasHandler.findZoneName( this.novaApi, this.targetProperties ); for( String storageId : OpenstackIaasHandler.findStorageIds( this.targetProperties )) { // Prepare the parameters String name = OpenstackIaasHandler.findStorage...
java
public void add(InputSplit s) throws IOException { if (null == splits) { throw new IOException("Uninitialized InputSplit"); } if (fill == splits.length) { throw new IOException("Too many splits"); } splits[fill++] = s; totsize += s.getLength(); }
python
def make_pvc( name, storage_class, access_modes, storage, labels=None, annotations=None, ): """ Make a k8s pvc specification for running a user notebook. Parameters ---------- name: Name of persistent volume claim. Must be unique within the namespace the object is ...
python
def to_pb(self): """Converts the column family to a protobuf. :rtype: :class:`.table_v2_pb2.ColumnFamily` :returns: The converted current object. """ if self.gc_rule is None: return table_v2_pb2.ColumnFamily() else: return table_v2_pb2.ColumnFamil...
python
def _update_labels(self, label, crop_box, height, width): """Convert labels according to crop box""" xmin = float(crop_box[0]) / width ymin = float(crop_box[1]) / height w = float(crop_box[2]) / width h = float(crop_box[3]) / height out = label.copy() out[:, (1, 3...
java
@Override public String getType(final Uri uri) { final String name = getDatasetOrThrowException(uri).getClass().getName(); final String type = String.format("vnd.android.cursor.dir/%s", name); return type.toLowerCase(Locale.getDefault()); }
python
def wait_processed(self, timeout): """Wait until time outs, or this event is processed. Event must be waitable for this operation to have described semantics, for non-waitable returns true immediately. in timeout of type int Maximum time to wait for event processing, in ms; ...
python
def to_bytes(self): ''' Create bytes from properties ''' # Verify that properties make sense self.sanitize() # Start with the type bitstream = BitArray('uint:4=%d' % self.message_type) # Add padding bitstream += self._reserved1 # Add the...
java
public static HsqlException error(String message, String sqlState, int i) { return new HsqlException(message, sqlState, i); }
java
public final CharsetEncoder onUnmappableCharacter(CodingErrorAction newAction) { if (newAction == null) throw new IllegalArgumentException("Null action"); unmappableCharacterAction = newAction; implOnUnmappableCharacter(newAct...
python
def get_brightness(self, refresh=False): """Get dimmer brightness. Refresh data from Vera if refresh is True, otherwise use local cache. Refresh is only needed if you're not using subscriptions. Converts the Vera level property for dimmable lights from a percentage to the 0 - 25...
python
def expect(obj, strict=None, times=None, atleast=None, atmost=None, between=None): """Stub a function call, and set up an expected call count. Usage:: # Given `dog` is an instance of a `Dog` expect(dog, times=1).bark('Wuff').thenReturn('Miau') dog.bark('Wuff') dog.ba...
java
public void marshall(DeleteAppLaunchConfigurationRequest deleteAppLaunchConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (deleteAppLaunchConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { pr...
java
static CmsSearchReplaceSettings getSettingsFromState(String state) { try { state = new URLCodec().decode(state); } catch (DecoderException e1) { // } CmsSearchReplaceSettings settings = null; String typeString = A_CmsWorkplaceApp.getParamFromState(state, ...
python
def remove_rules(self, doc): """Remove a grammar rules from _self.rules_, _self.rule2func_, and _self.rule2name_ """ # remove blanks lines and comment lines, e.g. lines starting with "#" doc = os.linesep.join([s for s in doc.splitlines() if s and not re.match("^\s*#", s)]) ...
java
public final static boolean isUrlAddress(String str, ADictionary dic) { int prIndex = str.indexOf("://"); if ( prIndex > -1 && ! StringUtil.isLatin(str, 0, prIndex) ) { return false; } int sIdx = prIndex > -1 ? prIndex + 3 : 0; int slIndex = str.indexOf('...
java
@Deprecated public OIndex<?> getIndex() { Set<OIndex<?>> indexes = owner.getInvolvedIndexes(name); if (indexes != null && !indexes.isEmpty()) return indexes.iterator().next(); return null; }
java
@Override public CPDefinitionVirtualSetting fetchByPrimaryKey(Serializable primaryKey) { Serializable serializable = entityCache.getResult(CPDefinitionVirtualSettingModelImpl.ENTITY_CACHE_ENABLED, CPDefinitionVirtualSettingImpl.class, primaryKey); if (serializable == nullModel) { return null; } CPDefi...
python
def save(self, *args, **kwargs): """Capitalize the first letter of the block name.""" letter = getattr(self, "block_letter", None) if letter and len(letter) >= 1: self.block_letter = letter[:1].upper() + letter[1:] super(EighthBlock, self).save(*args, **kwargs)
java
private void displayTable(TransferTable t) { tCurrent = t; if (t == null) { return; } tSourceTable.setText(t.Stmts.sSourceTable); tDestTable.setText(t.Stmts.sDestTable); tDestDrop.setText(t.Stmts.sDestDrop); tDestCreateIndex.setText(t.Stmts.sDestCre...
java
public void billingAccount_line_serviceName_phone_PUT(String billingAccount, String serviceName, OvhPhone body) throws IOException { String qPath = "/telephony/{billingAccount}/line/{serviceName}/phone"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toString(), body); }
python
def set_bn_eval(m:nn.Module)->None: "Set bn layers in eval mode for all recursive children of `m`." for l in m.children(): if isinstance(l, bn_types) and not next(l.parameters()).requires_grad: l.eval() set_bn_eval(l)
java
protected final Artifact createArtifact(org.eclipse.aether.artifact.Artifact artifact) { return createArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()); }
python
def DbPutDeviceAlias(self, argin): """ Define alias for a given device name :param argin: Str[0] = device name Str[1] = alias name :type: tango.DevVarStringArray :return: :rtype: tango.DevVoid """ self._log.debug("In DbPutDeviceAlias()") if len(argin) <...
python
def _execute_xmpp(connected_callback): """Connects to the XMPP server and executes custom code :param connected_callback: function to execute after connecting :return: return value of the callback """ from indico_chat.plugin import ChatPlugin check_config() jid = ChatPlugin.settings.get('b...
python
def required(self, fn): """Request decorator. Forces authentication.""" @functools.wraps(fn) def decorated(*args, **kwargs): if (not self._check_auth() # Don't try to force authentication if the request is part # of the authentication process - otherwise...
python
def get_repositories(self, project=None, include_links=None, include_all_urls=None, include_hidden=None): """GetRepositories. [Preview API] Retrieve git repositories. :param str project: Project ID or project name :param bool include_links: [optional] True to include reference links. The...
java
public DescribeAccountAuditConfigurationResult withAuditCheckConfigurations(java.util.Map<String, AuditCheckConfiguration> auditCheckConfigurations) { setAuditCheckConfigurations(auditCheckConfigurations); return this; }
java
public @Nonnull JsonBuilder put(String key, String s) { object.put(key, primitive(s)); return this; }
java
public PagedList<SecretItem> listSecretVersions(final String vaultBaseUrl, final String secretName) { return getSecretVersions(vaultBaseUrl, secretName); }
java
public void ready(VirtualConnection readyVc) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "ready", readyVc); AcceptListener acceptListener = (AcceptListener) config.getPropertyBag() .get(JFapChannelFactory.ACCEPT_LISTENER);...
python
def run_crate( version, env=None, setting=None, crate_root=None, keep_data=False, disable_java_magic=False, ): """Launch a crate instance. Supported version specifications: - Concrete version like "0.55.0" or with wildcard: "1.1.x" - An alias (one...
java
public static RDistinct DISTINCT() { RDistinct ret = RFactory.DISTINCT(); ASTNode an = APIObjectAccess.getAstNode(ret); an.setClauseType(ClauseType.RETURN); return ret; }
java
private void loadAllPanels(final JPanel mainPanel) { SwingUtilities.invokeLater(() -> { int numPanels = wizardComponents.length; for (int i1 = 0; i1 < numPanels; i1++) { mainPanel.remove(wizardComponents[i1]); } for (int i2 = 0; i2 < numPanels; i2+...
java
private List<String> getFedoraTables() { try { InputStream in = getClass().getClassLoader() .getResourceAsStream(DBSPEC_LOCATION); List<TableSpec> specs = TableSpec.getTableSpecs(in); ArrayList<String> names = new ArrayList<Stri...
python
def step_impl12(context, runs): """Check called apps / files. :param runs: expected number of records. :param context: test context. """ executor_ = context.fuzz_executor stats = executor_.stats count = stats.cumulated_counts() assert count == runs, "VERIFY: Number of recorded runs."
java
public final void forInit() throws RecognitionException { int forInit_StartIndex = input.index(); ParserRuleReturnScope variableModifier12 =null; ParserRuleReturnScope type13 =null; try { if ( state.backtracking>0 && alreadyParsedRule(input, 101) ) { return; } // src/main/resources/org/drools/compiler/...
java
public java.util.List<String> getAccountAliases() { if (accountAliases == null) { accountAliases = new com.amazonaws.internal.SdkInternalList<String>(); } return accountAliases; }
python
def extract(self, item): """Creates an readability document and returns an ArticleCandidate containing article title and text. :param item: A NewscrawlerItem to parse. :return: ArticleCandidate containing the recovered article data. """ doc = Document(deepcopy(item['spider_resp...
java
public void convertAndWriteXML(String xml, String path) { ClassProject classProject = (ClassProject)this.getMainRecord(); Record recProgramControl = this.getRecord(ProgramControl.PROGRAM_CONTROL_FILE); Model model = (Model)this.unmarshalMessage(xml); String name = model.getN...
java
private void writeObject(java.io.ObjectOutputStream out) throws IOException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "writeObject : " + ivPuId + ", " + ivJ2eeName); out.writeObject(ivPuId); out.writeObject(ivJ2eeName); // d510184 i...
java
public IpSet withIpAddresses(String... ipAddresses) { if (this.ipAddresses == null) { setIpAddresses(new java.util.ArrayList<String>(ipAddresses.length)); } for (String ele : ipAddresses) { this.ipAddresses.add(ele); } return this; }
python
def decorate_with_validators(func, func_signature=None, # type: Signature **validators # type: Validator ): """ Utility method to decorate the provided function with the provided input and output Validator objects. ...
python
def _get_qgen_var(self, generators, base_mva): """ Returns the generator reactive power variable set. """ Qg = array([g.q / base_mva for g in generators]) Qmin = array([g.q_min / base_mva for g in generators]) Qmax = array([g.q_max / base_mva for g in generators]) retur...
python
def integrate(ii, r0, c0, r1, c1): """ Use an integral image to integrate over a given window. Parameters ---------- ii : ndarray Integral image. r0, c0 : int Top-left corner of block to be summed. r1, c1 : int Bottom-right corner of block to be summed. Returns ...
python
def merge_modified_section_data(self): """Update the PE image content with any individual section data that has been modified.""" for section in self.sections: section_data_start = adjust_FileAlignment( section.PointerToRawData, self.OPTIONAL_HEADER.FileAlignment ) ...
java
@Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { target.setTypeMap(map); }
python
def choose_tool_key(full_configuration, keys): """ Select the key for a tool from a list of supported tools. This function is designed to help when multiple keys can be used to specify an option (e.g., during migration from one name to another). The values in keys should be ordered based on prefer...
python
def get_other_answers(pool, seeded_answers, get_student_item_dict, algo, options): """ Select other student's answers from answer pool or seeded answers based on the selection algorithm Args: pool (dict): answer pool, format: { option1_index: { studen...
java
public boolean shouldAggregateSoils(HashMap<String, String> currentSoil, HashMap<String, String> previousSoil) { float ruCurrent; float ruPrevious; float resultFirstRule; float resultSecRule; boolean firstRule; boolean secRule; // ru in mm/m ruCurrent = (parseFloat(currentSoil.get(SLDUL)) - parseFloat(...
python
def initialize(): """ Initializes the cauldron library by confirming that it can be imported by the importlib library. If the attempt to import it fails, the system path will be modified and the attempt retried. If both attempts fail, an import error will be raised. """ cauldron_module = ge...
java
public static String trStyleHtmlContent(String style, String... content) { return tagStyleHtmlContent(Html.Tag.TR, style, content); }
python
def is_valid_address (s): """ returns True if address is a valid Bluetooth address valid address are always strings of the form XX:XX:XX:XX:XX:XX where X is a hexadecimal character. For example, 01:23:45:67:89:AB is a valid address, but IN:VA:LI:DA:DD:RE is not """ try: ...
java
public static Date parse(String source, final String pattern) { if (StringUtils.isBlank(pattern)) { return parseISO8601DateString(source); } else { try { // SimpleDateFormat is not fully ISO8601 compatible, so we replace 'Z' by +0000 if (StringUtils.contains(source, "Z")) { source = StringUt...
python
def get_float(prompt=None): """ Read a line of text from standard input and return the equivalent float as precisely as possible; if text does not represent a double, user is prompted to retry. If line can't be read, return None. """ while True: s = get_string(prompt) if s is Non...
java
@Override public void run() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "run", Thread.currentThread().getName() + " " + this.in.getReadListener()); } try { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnable...
python
def as_dict(self): """ Create a dictionary representation of a PWInput object Returns: dict """ pwinput_dict = {'structure': self.structure.as_dict(), 'pseudo': self.pseudo, 'sections': self.sections, ...
java
public long readVarLong() throws IOException { boolean more; long result = 0; do { int b = in.readUnsignedByte(); more = (b & 0x80) == 0x80; result = 128 * result + (b & 0x7F); // TODO Check for long overflow } while (more); return result; }
python
def startsafe(self, project, **parameters): """Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for the global parameters. Returns a ``CLAMData`` object or raises exceptions. This version, unlike ``start()``, raises Exceptions (``ParameterError``) on parameter ...
java
private String format(Object o) { String result; if (o == null) { result = ""; } else { if (o instanceof Boolean == true) { result = LocaleData.getString(m_locale, (((Boolean) o).booleanValue() == true ? LocaleData.YES : LocaleData.NO)); ...
python
def is_watching(self, username): """Check if user is being watched by the given user :param username: Check if username is watching you """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type...
python
def remove_event_type(self, name): """Remove event type based on name.""" if name not in self.event_types: lg.info('Event type ' + name + ' was not found.') events = self.rater.find('events') # list is necessary so that it does not remove in place for e in list(eve...
python
def convert_block(G, h, dim, **kwargs): r""" Applies the clique conversion method to a single positive semidefinite block of a cone linear program .. math:: \begin{array}{ll} \mbox{maximize} & -h^T z \\ \mbox{subject to} & G^T z + c = 0 \\ &...
python
def force_bytes(bytes_or_unicode, encoding='utf-8', errors='backslashreplace'): 'Convert passed string type to bytes, if necessary.' if isinstance(bytes_or_unicode, bytes): return bytes_or_unicode return bytes_or_unicode.encode(encoding, errors)
java
public ServiceFuture<List<VirtualMachineImageResourceInner>> listAsync(String location, String publisherName, String offer, String skus, String filter, Integer top, String orderby, final ServiceCallback<List<VirtualMachineImageResourceInner>> serviceCallback) { return ServiceFuture.fromResponse(listWithServiceR...
java
@Override public boolean authenticate(String base, String filter, String password, AuthenticationErrorCallback errorCallback) { return authenticate(LdapUtils.newLdapName(base), filter, password, new NullAuthenticatedLdapEntryContextCallback(), errorCallback); }
python
def _mark_updated(self): """Update the updated timestamp.""" timestamp = datetime.datetime.utcnow().isoformat() DB.set_hash_value(self.key, 'updated', timestamp)
java
private static OrderedJSONObject setCommonJSONElements(OrderedJSONObject obj, Object representation, String description) { obj.put("Representation", representation); obj.put("Description", description); return obj; }
java
public DescribeTrainingJobResult withHyperParameters(java.util.Map<String, String> hyperParameters) { setHyperParameters(hyperParameters); return this; }
java
public Collection<Issue> issues(IssueFilter filter) { return get(Issue.class, (filter != null) ? filter : new IssueFilter()); }
java
public static com.liferay.commerce.product.model.CPDefinitionOptionValueRel updateCPDefinitionOptionValueRel( com.liferay.commerce.product.model.CPDefinitionOptionValueRel cpDefinitionOptionValueRel) { return getService() .updateCPDefinitionOptionValueRel(cpDefinitionOptionValueRel); }
java
public static <T1, T2, T3, T4, T5> Func5<T1, T2, T3, T4, T5, Observable<Void>> toAsync(Action5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5> action) { return toAsync(action, Schedulers.computation()); }
java
public static String byte2FitMemoryString(final long byteNum) { if (byteNum < 0) { return "shouldn't be less than zero!"; } else if (byteNum < MemoryConst.KB) { return String.format("%d B", byteNum); } else if (byteNum < MemoryConst.MB) { return String.format(...
java
protected boolean checkResourcePermissions(CmsPermissionSet required, boolean neededForFolder) { return checkResourcePermissions( required, neededForFolder, Messages.get().container( Messages.GUI_ERR_RESOURCE_PERMISSIONS_2, getParamResource(),...
python
def do_file_sub(self, srcpath, regexp, subst): '''Apply a regexp substitution to a file archived by sosreport. srcpath is the path in the archive where the file can be found. regexp can be a regexp string or a compiled re object. subst is a string to replace each occurance of regexp in...
java
public static char getChecksum(String text) { int mul = 3; int total = 0; for (int k = text.length() - 1; k >= 0; --k) { int n = text.charAt(k) - '0'; total += mul * n; mul ^= 2; } return (char)(((10 - (total % 10)) % 10) + '0'); }
python
def project_create_notif(self, tenant_id, tenant_name): """Tenant Create notification. """ if not self.fw_init: return self.os_helper.create_router('_'.join([fw_constants.TENANT_EDGE_RTR, tenant_name]), ...
python
def Feature_Engineering(DataFrame,train): """ Extracts important features and writes them in usable form Deletes features of little importance :param DataFrame: This is the file name of a csv file we wish to convert into a usable DataFrame. :param train: This is training set corresponding to ou...
java
public ServiceFuture<PredictionQueryResult> queryPredictionsAsync(UUID projectId, PredictionQueryToken query, final ServiceCallback<PredictionQueryResult> serviceCallback) { return ServiceFuture.fromResponse(queryPredictionsWithServiceResponseAsync(projectId, query), serviceCallback); }
python
def initialize_ordered_bulk_op(self, bypass_document_validation=False): """**DEPRECATED** - Initialize an ordered batch of write operations. Operations will be performed on the server serially, in the order provided. If an error occurs all remaining operations are aborted. :Par...
java
public String getString(String key) { try { return this.getStringImpl(key); } catch (MissingResourceException e) { return handleMissingResourceException(e); } }
java
public void insertAfter(Token before, TokenList list ) { Token after = before.next; before.next = list.first; list.first.previous = before; if( after == null ) { last = list.last; } else { after.previous = list.last; list.last.next = after; ...
java
public static <K, V, P> V getIfAbsentPutWith( Map<K, V> map, K key, Function<? super P, ? extends V> function, P parameter) { V result = map.get(key); if (MapIterate.isAbsent(result, map, key)) { result = function.valueOf(parameter)...
java
public boolean getTransacted() throws IllegalStateException { if (_sessionClosed) { throw new IllegalStateException(NLS.getFormattedMessage( ("ILLEGAL_STATE_CWSJR1131"), new Object[] { "getTransacted"}, null)); } if (_sessionInvalidated) { ...
java
private boolean isMapAttribute(PluralAttribute<? super X, ?, ?> attribute) { return attribute != null && attribute.getCollectionType().equals(CollectionType.MAP); }
java
public static void extractChunkPart(Chunk ic, Chunk oc, int startRow, int nrows, Futures fs) { try { NewChunk dst = new NewChunk(oc); dst._len = dst._sparseLen = 0; NewChunk src = new NewChunk(ic); src = ic.inflate_impl(src); assert src._len == ic._len; // Iterate over values ski...
java
public Dispatcher getInstance() { try { return (Dispatcher) Class.forName(dispatcherImpl) .getConstructor(Configuration.class).newInstance(conf); } catch (InstantiationException e) { throw new AssertionError(e); } catch (IllegalAccessException e) { ...