language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private ProcCode createCode(Code defCode) { if (!defCode.hasPatterns()) { throw new IllegalStateException("Field pattern can't be null."); } if (defCode.getTemplate() == null) { throw new IllegalStateException("Field template can't be null."); } ProcCode...
java
@Override public AuthnContextClassContext apply(AuthenticationContext input) { return input != null ? input.getSubcontext(AuthnContextClassContext.class, false) : null; }
python
def iter_milestones(self, state=None, sort=None, direction=None, number=-1, etag=None): """Iterates over the milestones on this repository. :param str state: (optional), state of the milestones, accepted values: ('open', 'closed') :param str sort: (optional),...
java
public static void reset( final Collection<MasterTriggerRestoreHook<?>> hooks, final Logger log) throws FlinkException { for (MasterTriggerRestoreHook<?> hook : hooks) { final String id = hook.getIdentifier(); try { hook.reset(); } catch (Throwable t) { ExceptionUtils.rethrowIfFatalErrorOrOOM...
java
protected void promptRequiredMissingValues(ShellImpl shell, Iterable<InputComponent<?, ?>> inputs) throws InterruptedException { ShellUIPromptImpl prompt = shell.createPrompt(context); for (InputComponent<?, ?> input : inputs) { if (input.isEnabled() && !input.isDeprecated()) ...
python
def _no_exp(number): r""" Convert a number to a string without using scientific notation. :param number: Number to convert :type number: integer or float :rtype: string :raises: RuntimeError (Argument \`number\` is not valid) """ if isinstance(number, bool) or (not isinstance(number,...
java
public void setBloomFilterColumns(java.util.Collection<String> bloomFilterColumns) { if (bloomFilterColumns == null) { this.bloomFilterColumns = null; return; } this.bloomFilterColumns = new java.util.ArrayList<String>(bloomFilterColumns); }
java
protected Container getContainer(short x) { int i = this.binarySearch(0, size, x); if (i < 0) { return null; } return this.values[i]; }
python
def main(*argv): """ main driver of program """ try: # Inputs # adminUsername = argv[0] adminPassword = argv[1] siteURL = argv[2] username = argv[3] subFolders = argv[4].lower() == "true" # Logic # sh = arcrest.AGOLTokenSecurity...
java
@SuppressWarnings("unchecked") public <A extends Annotation> A getAnnotation(final Method method, final Class<A> annClas) throws AnnotationReadException { final Class<?> clazz = method.getDeclaringClass(); if(xmlInfo != null && xmlInfo.containsClassInfo(clazz.getName())) { ...
java
public static synchronized ExecutionSignature createSignature( final Class<? extends AbstractInvokable> invokableClass, final JobID jobID) { // First, try to load message digest algorithm, if necessary if (messageDigest == null) { try { messageDigest = MessageDigest.getInstance(HASHINGALGORITHM); } ca...
python
def get_metric_details(self, m, **kwargs): # noqa: E501 """Get more details on a metric, including reporting sources and approximate last time reported # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pas...
python
def find_library(library_root, additional_places=None): """ Returns the name of the library without extension :param library_root: root of the library to search, for example "cfitsio_" will match libcfitsio_1.2.3.4.so :return: the name of the library found (NOTE: this is *not* the path), and a director...
java
public DeleteTableResponse deleteTable(String tableName) { checkNotNull(tableName, "request should not be null."); InternalRequest httpRequest = createRequestUnderInstance(HttpMethodName.DELETE, MolaDbConstants.URI_TABLE, tableName); DeleteTableResponse ret = this...
java
public final void commit() throws XAException { if (tc.isEntryEnabled()) Tr.entry(tc, "commit", _resource); Tr.warning(tc, "WTRN0018_1PC_RESOURCE_DOES_NOT_SUPPORT_COMMIT"); if (tc.isEntryEnabled()) Tr.exit(tc, "commit"); throw new XAException(XAException.XAER_PROTO); }
java
public static int getInt(String key, int def) { String value = get(key); if (value == null) { return def; } value = value.trim(); try { return Integer.parseInt(value); } catch (Exception e) { // Ignore } logger.warn( ...
java
public String getContextPath() { ServletRequest request = pageContext.getRequest(); if (request instanceof HttpServletRequest) { return ((HttpServletRequest) request).getContextPath(); } return "/"; }
python
def ap(u, d, M, step, K, eps=0.001, leak=0, initCoeffs=None, N=None, returnCoeffs=False): """ Perform affine projection (AP) adaptive filtering on u to minimize error given by e=d-y, where y is the output of the adaptive filter. Parameters ---------- u : array-like One-dimensiona...
python
def _traverse_relationship_objs(self, rel2src2dsts, goobj_child, goids_seen): """Traverse from source GO up relationships.""" child_id = goobj_child.id goids_seen.add(child_id) ##A self.go2obj[child_id] = goobj_child # Update goids_seen and go2obj with child alt_ids for g...
java
@Override public List<Wave> postBootWaveList() { final List<Wave> waveList = new ArrayList<>(); // Get Java command line parameters final Parameters p = getParameters(); if (p.getRaw().size() >= 1) { // The first parameter must contains the log file to parse ...
python
def log(self, *lines): """will print out the lines in console if debug is enabled for the specific sprite""" if getattr(self, "debug", False): print(dt.datetime.now().time(), end=' ') for line in lines: print(line, end=' ') print()
java
public Symbol getSymbolForInstancesOf(Symbol sym) { FunctionType fn = sym.getFunctionType(); if (fn != null && fn.isNominalConstructor()) { return getSymbolForInstancesOf(fn); } return null; }
python
def configure_logger(self, tc_config_log_filename=None, tc_output_log_filename=None): """Configure selenium instance logger :param tc_config_log_filename: test case specific logging config file :param tc_output_log_filename: test case specific output logger file """ # Get config...
python
def _get_acceptable_response_type(): """Return the mimetype for this request.""" if ('Accept' not in request.headers or request.headers['Accept'] in ALL_CONTENT_TYPES): return JSON acceptable_content_types = set( request.headers['ACCEPT'].strip().split(',')) if acceptable_con...
python
def _build_object(self, nm, clsdata, parents,**kw): logger.debug(util.lazy_format("Building object {0}", nm)) # To support circular references, we tag objects that we're # currently building as "under construction" self.under_construction.add(nm) props = {} defaults = s...
python
def remove_keywords_from_list(self, keyword_list): """To remove keywords present in list Args: keyword_list (list(str)): List of keywords to remove Examples: >>> keyword_processor.remove_keywords_from_list(["java", "python"]}) Raises: AttributeError:...
java
public void index(Record record) { if (directory == null) init(); if (!overwrite && path != null) delete(record); Document doc = new Document(); for (String propname : record.getProperties()) { Property prop = config.getPropertyByName(propname); if (prop == null) throw ...
java
public Cell<C,T> maxSize (float width, float height) { maxWidth = new FixedValue<C, T>(layout.toolkit,width); maxHeight = new FixedValue<C, T>(layout.toolkit,height); return this; }
python
def admin_request_announcement_email(request, form, obj): """Send an admin announcement request email. form: The announcement request form obj: The announcement request object """ subject = "News Post Approval Needed ({})".format(obj.title) emails = [settings.APPROVAL_EMAIL] base_url = re...
java
public static void setLearningRate(ComputationGraph net, ISchedule newLrSchedule) { setLearningRate(net, Double.NaN, newLrSchedule); }
java
public static Object getDefaultValue(Class<? extends Annotation> annotationType, String attributeName) { try { Method method = annotationType.getDeclaredMethod(attributeName, new Class[0]); return method.getDefaultValue(); } catch (Exception ex) { return null;...
java
protected void processTopicSectionInfo(final BuildData buildData, final BaseTopicWrapper<?> topic, final Document doc) { if (doc == null || topic == null) return; final String infoName; if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) { infoName = "info"; } el...
java
protected void initContext() { context = createContext(); SmartFoxContext sfsContext = (SmartFoxContext)context; sfsContext.setApi(getApi()); sfsContext.setExtension(this); }
python
def get_info(self, code): """Return a dict of information about the currency""" currency = self.get_currency(code) info = {} users = list(filter(None, currency['users'].split(','))) if users: info['Users'] = users alt = list(filter(None, currency['alternativ...
python
def _register_server(self, server, timeout=30): '''Register a new SiriDB Server. This method is used by the SiriDB manage tool and should not be used otherwise. Full access rights are required for this request. ''' result = self._loop.run_until_complete( self._protoc...
python
def add_peer(self, peer_addr): "Build a connection to the Hub at a given ``(host, port)`` address" peer = connection.Peer( self._ident, self._dispatcher, peer_addr, backend.Socket()) peer.start() self._started_peers[peer_addr] = peer
java
public ServiceFuture<DatabasePrincipalListResultInner> removePrincipalsAsync(String resourceGroupName, String clusterName, String databaseName, final ServiceCallback<DatabasePrincipalListResultInner> serviceCallback) { return ServiceFuture.fromResponse(removePrincipalsWithServiceResponseAsync(resourceGroupName,...
java
private void updateConduitSyncHandlerConnection(List<String> sourceList, SynchronousHandler handler) { if (sourceList.contains("message")) { logConduit.addSyncHandler(handler); } else { logConduit.removeSyncHandler(handler); } if (sourceList.contains("trace")) { ...
java
public void writeBareObject (Object object) throws IOException { writeBareObject(object, Streamer.getStreamer(Streamer.getStreamerClass(object)), true); }
java
public static BigtableTableAdminClient create( @Nonnull String projectId, @Nonnull String instanceId, @Nonnull EnhancedBigtableTableAdminStub stub) { return new BigtableTableAdminClient(projectId, instanceId, stub); }
python
def asarray(arraylike, strict=True): """ Converts arraylike objects to NumPy ndarray types. Errors if object is not arraylike and strict option is enabled. """ if isinstance(arraylike, np.ndarray): return arraylike elif isinstance(arraylike, list): return np.asarray(arraylike, dt...
python
def widgets(self): """ Get the Ext JS specific customization from the activity. :return: The Ext JS specific customization in `list(dict)` form """ customization = self.activity._json_data.get('customization') if customization and "ext" in customization.keys(): ...
python
def on_created(self, event): '''Fired when something's been created''' if self.trigger != "create": return action_input = ActionInput(event, "", self.name) flows.Global.MESSAGE_DISPATCHER.send_message(action_input)
python
def _delete_cells(self, column_family_id, columns, time_range=None, state=None): """Helper for :meth:`delete_cell` and :meth:`delete_cells`. ``state`` is unused by :class:`DirectRow` but is used by subclasses. :type column_family_id: str :param column_family_id: The column fami...
java
public void addComponent(Object screenField) { // Set up the dependencies if (m_iNamePrefix != null) m_recThis.getField(m_iNamePrefix).addComponent(screenField); m_recThis.getField(m_iNameFirst).addComponent(screenField); if (m_iNameMiddle != null) m_recThis.getField...
java
public static String insert(final String str, final String given, final int begin, final int end) { if (begin < 1 || end > str.length() || end < begin) { return str; } return str.substring(0, begin - 1) + given + str.substring(end); }
python
def _normalized_cookie_tuples(self, attrs_set): """Return list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are th...
python
def ned_to_use(tensor): ''' Converts a tensor in NED coordinate sytem to USE ''' return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T)
python
def calculate_size(self, modules_per_line, number_of_lines, dpi=300): """Calculates the size of the barcode in pixel. :parameters: modules_per_line : Integer Number of modules in one line. number_of_lines : Integer Number of lines of the barcode. ...
python
def get_files(*bases): """ List all files in a data directory. """ for base in bases: basedir, _ = base.split(".", 1) base = os.path.join(os.path.dirname(__file__), *base.split(".")) rem = len(os.path.dirname(base)) + len(basedir) + 2 for...
java
@Override public void run() { while (true) { int prefetchBatchSize; boolean nackQueueMessages = false; List<Message> messages = null; try { if (isClosed()) { break; } synchron...
python
def _get_client_by_id(self, client_id): """Get GRR client dictionary and make sure valid approvals exist. Args: client_id: GRR client ID. Returns: GRR API Client object """ client = self.grr_api.Client(client_id) print('Checking for client approval') self._check_approval_wrappe...
python
def connect_post_namespaced_pod_proxy_with_path(self, name, namespace, path, **kwargs): # noqa: E501 """connect_post_namespaced_pod_proxy_with_path # noqa: E501 connect POST requests to proxy of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asyn...
python
def getargspec(f): """A replacement for inspect.getargspec""" spec = getfullargspec(f) return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)
python
def resendFaxRN_multi(self, CorpNum, OrgRequestNum, SenderNum, SenderName, Receiver, ReserveDT=None, UserID=None, title=None, RequestNum=None): """ 팩스 전송 args CorpNum : 팝빌회원 사업자번호 OrgRequestNum : 원본 팩스 전송시 할당한 전송요청번호 SenderNum...
python
def _processHandler(self, securityHandler, param_dict): """proceses the handler and returns the cookiejar""" cj = None handler = None if securityHandler is None: cj = cookiejar.CookieJar() elif securityHandler.method.lower() == "token": param_dict['token']...
java
public static <T> Optional<T> get(Config config, Function<String, T> getter, String path) { if (!config.hasPath(path)) { return Optional.empty(); } return Optional.of(getter.apply(path)); }
java
void reportChecksumFailure(String file, LocatedBlock lblocks[]) { try { reportBadBlocks(lblocks); } catch (IOException ie) { LOG.info("Found corruption while reading " + file + ". Error repairing corrupt blocks. Bad blocks remain. " + StringUtils.stringifyException(ie...
java
public static sslservicegroup[] get_filtered(nitro_service service, String filter) throws Exception{ sslservicegroup obj = new sslservicegroup(); options option = new options(); option.set_filter(filter); sslservicegroup[] response = (sslservicegroup[]) obj.getfiltered(service, option); return response; }
java
public <T> void queue(StorageRequest<T> req, JsonBatchCallback<T> callback) throws IOException { checkState( !requestsExecutor.isShutdown() && !requestsExecutor.isTerminated(), "requestsExecutor should not be terminated to queue batch requests"); if (maxRequestsPerBatch == 1) { responseFut...
python
def writeTuple(self, val, what): """ Writes a tuple of numbers (on one line). """ # Limit to three values. so RGBA data drops the alpha channel # Format can handle up to 3 texcords val = val[:3] # Make string val = ' '.join([str(v) for v in val]) # Write l...
python
def getnameinfo(sockaddr, flags=0, timeout=30): """Resolve a socket address *sockaddr* back to a ``(node, service)`` tuple. The *flags* argument can be used to modify the resolution process. See the :func:`socket.getnameinfo` function for more information. The address resolution is performed in the li...
java
private Assignment getBestAssignment(Assignment portion, CliqueTree cliqueTree, int initialFactor) { if (cliqueTree.getMarginals().size() == 0) { // Special case where the factor graph has no factors in it. return conditionedValues; } else { // General case SortedSet<Integer> unvisited =...
python
def reset_cmd_timeout(self): """Reset timeout for command execution.""" if self._cmd_timeout: self._cmd_timeout.cancel() self._cmd_timeout = self.loop.call_later(self.client.timeout, self.transport.close)
python
def next_event(self): """Parse the next event out of our receive buffer, update our internal state, and return it. This is a mutating operation -- think of it like calling :func:`next` on an iterator. Returns: : One of three things: 1) An event object -...
java
public BoxFile.Info uploadNewVersion(InputStream fileContent, String fileContentSHA1) { return this.uploadNewVersion(fileContent, fileContentSHA1, null); }
python
def load_default_model_sentencizer(lang): """ Load a generic spaCy model and add the sentencizer for sentence tokenization""" loading_start = time.time() lang_class = get_lang_class(lang) nlp = lang_class() nlp.add_pipe(nlp.create_pipe('sentencizer')) loading_end = time.time() loading_time =...
python
def applyPolicies(self, request): ''' Apply relevant header policies to request. Call me where appropriate in your render_* methods. ''' for policy in self._actingPolicies[request.method]: request = policy.apply(request) return request
java
public void restoreAfterSafeModeRestart() { if (!clusterManager.safeMode) { return; } for (Session session : sessions.values()) { for (ResourceRequestInfo resourceRequestInfo : session.idToRequest.values()) { // The helper method to restore the ResourceRequestInfo instances ...
java
public static SipApplicationSessionKey getSipApplicationSessionKey(final String applicationName, final String id, final String appGeneratedKey) { if (logger.isDebugEnabled()){ logger.debug("getSipApplicationSessionKey - applicationName=" + applicationName + ", id=" + id + ", appGeneratedKey=" + appGeneratedKey);...
python
def GetClass(self, *args, **kwargs): """Retrieve a CIM class from the local repository of this class. For a description of the parameters, see :meth:`pywbem.WBEMConnection.GetClass`. """ cname = args[0] if args else kwargs['ClassName'] try: cc = self.classes...
java
@Override public void execute() throws MojoExecutionException, MojoFailureException { if ( !"pom".equals( project.getPackaging() ) ) { long ts = System.currentTimeMillis(); try { internalExecute(); } finally ...
python
def _addLoggingOptions(addOptionFn): """Adds logging options """ ################################################## # BEFORE YOU ADD OR REMOVE OPTIONS TO THIS FUNCTION, KNOW THAT # YOU MAY ONLY USE VARIABLES ACCEPTED BY BOTH optparse AND argparse # FOR EXAMPLE, YOU MAY NOT USE default=%default O...
python
def same_network(atree, btree) -> bool: """True if given trees share the same structure of powernodes, independently of (power)node names, and same edge topology between (power)nodes. """ return same_hierarchy(atree, btree) and same_topology(atree, btree)
java
@Override public void fit(Dataframe trainingData) { Set<TypeInference.DataType> supportedYDataTypes = getSupportedYDataTypes(); if(supportedYDataTypes != null && !supportedYDataTypes.contains(trainingData.getYDataType())) { throw new IllegalArgumentException("The response variable DataTy...
java
public static <Key, Value> Aggregation<Key, BigInteger, BigInteger> bigIntegerSum() { return new AggregationAdapter(new BigIntegerSumAggregation<Key, Value>()); }
java
public void write(OutputStream out) throws IOException { Writer writer = new OutputStreamWriter(out); write(writer); writer.flush(); }
java
public static FacesBackingBeanFactory get( ServletContext servletContext ) { FacesBackingBeanFactory factory = ( FacesBackingBeanFactory ) servletContext.getAttribute( CONTEXT_ATTR ); assert factory != null : FacesBackingBeanFactory.class.getName() + " was not found in ServletContext...
python
def tr(self, *args, **kwargs): ''' calc_fn.tr(...) yields a copy of calc_fn in which the afferent and efferent values of the function have been translated. The translation is found from merging the list of 0 or more dictionary arguments given left-to-right followed by the keyword argumen...
java
public List<VirtualMachineExtensionImageInner> listVersions(String location, String publisherName, String type, String filter, Integer top, String orderby) { return listVersionsWithServiceResponseAsync(location, publisherName, type, filter, top, orderby).toBlocking().single().body(); }
java
public static KickflipApiClient setup(Context context, String key, String secret) { return setup(context, key, secret, null); }
java
public Collection<String> getEncryptTableNames() { Set<String> result = new LinkedHashSet<>(); for (ShardingEncryptorStrategy each : shardingEncryptorStrategies.values()) { result.addAll(each.getEncryptTableNames()); } return result; }
python
def wait_running(self, timeout=None): """Wait for the thread to pass control to its routine. Args: timeout (float): The maximum amount of time to wait """ flag = self._running.wait(timeout) if flag is False: raise TimeoutExpiredError("Timeout waiting fo...
python
def _log_function(self, handler): """Override Application.log_function so that what to log can be controlled. """ if handler.get_status() < 400: log_method = request_log.info elif handler.get_status() < 500: log_method = request_log.warning else: ...
java
public WeeklyAutoScalingSchedule withSunday(java.util.Map<String, String> sunday) { setSunday(sunday); return this; }
java
public static final AuthToken consumeToken(String encodedJson) throws IllegalArgumentException { String json = StringUtils.newStringUtf8(Base64.decodeBase64(encodedJson)); AuthToken token = fromJSON(json); validateToken(token); return token; }
python
def selfSignCert(self, cert, pkey): ''' Self-sign a certificate. Args: cert (OpenSSL.crypto.X509): The certificate to sign. pkey (OpenSSL.crypto.PKey): The PKey with which to sign the certificate. Examples: Sign a given certificate with a given priva...
java
private static List<Method> requestMappingMethods(Object object) { return getAllMethods(object.getClass(), withModifier(Modifier.PUBLIC)) .stream() // Lookup super classes just in case if the object is a proxy. .filter(m -> getAnnotations(m, FindOption.LOOKUP_SUPE...
python
def get_metadata(audio_filepaths): """ Return a tuple of album, artist, has_embedded_album_art from a list of audio files. """ artist, album, has_embedded_album_art = None, None, None for audio_filepath in audio_filepaths: try: mf = mutagen.File(audio_filepath) except Exception: continue i...
java
public InternalContext createSubContext(VariantIndexer[] indexers, InternalContext localContext, int varSize) { Object[][] myParentScopes = this.parentScopes; //cal the new-context's parent-scopes Object[][] scopes; if (myParentScopes == null) { scopes = new Object[][]{this.v...
python
def output(s): """ Parse, transform, and pretty print the result """ p = Parser() t = ExpressionsTransformer() ast = p.parse(s) logging.debug(ast.pretty()) print(ast.pretty()) d = t.transform(ast) print(json.dumps(d, indent=4)) return d
python
def to_datetime(self, column): ''' This function converts epoch timestamps to datetimes. :param column: column to convert from current state -> datetime ''' if column in self: if self[column].dtype in NUMPY_NUMERICAL: self[column] = pd.to_datetime(sel...
java
public OvhPackAdsl packName_GET(String packName) throws IOException { String qPath = "/pack/xdsl/{packName}"; StringBuilder sb = path(qPath, packName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhPackAdsl.class); }
java
@Override public RegisterAVSDeviceResult registerAVSDevice(RegisterAVSDeviceRequest request) { request = beforeClientExecution(request); return executeRegisterAVSDevice(request); }
python
def array_correlation(x, y, axis=0): """Column- or row-wise Pearson correlation between two arrays Computes sample Pearson correlation between two 1D or 2D arrays (e.g., two n_TRs by n_voxels arrays). For 2D arrays, computes correlation between each corresponding column (axis=0) or row (axis=1) where ...
java
public SIMPIterator getStreams() throws SIMPControllableNotFoundException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getStreams"); assertValidControllable(); Iterator it = null; try { it = _streamSet.iterator(); } catch (SIResourceExce...
python
def event_return(events): ''' Return events to Mongodb server ''' conn, mdb = _get_conn(ret=None) if isinstance(events, list): events = events[0] if isinstance(events, dict): log.debug(events) if PYMONGO_VERSION > _LooseVersion('2.3'): mdb.events.insert_one...
python
def _operation_speak_as_digits(self, content, index, children): """ The operation method of _speak_as method for digits. :param content: The text content of element. :type content: str :param index: The index of pattern in text content of element. :type index: int ...
java
public static void parseXmlAndSetIconicsDrawables(@NonNull Context context, int menuId, @NonNull Menu menu) { parseXmlAndSetIconicsDrawables(context, menuId, menu, false); }
python
def check_threats(**args): """ function to check input filetype against threat extensions list """ is_high_threat = False for val in THREAT_EXTENSIONS.values(): if type(val) == list: for el in val: if args['file_type'] == el: is_high_threat = True break else: if args['file_type'] == val: ...