language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected void initializeTraining(){ if(!initializedTraining) { if(trainingConfig == null) { throw new ND4JIllegalStateException("Please specify a training config with setTrainingConfig"); } //First: infer the variables to be optimized if required ...
java
@NotNull public static <T> Collector<T, ?, List<T>> toList() { return new CollectorsImpl<T, List<T>, List<T>>( new Supplier<List<T>>() { @NotNull @Override public List<T> get() { return new ArrayList<T>(); ...
java
public ServiceFuture<PersistedFace> addFaceFromStreamAsync(String faceListId, byte[] image, AddFaceFromStreamOptionalParameter addFaceFromStreamOptionalParameter, final ServiceCallback<PersistedFace> serviceCallback) { return ServiceFuture.fromResponse(addFaceFromStreamWithServiceResponseAsync(faceListId, image...
python
def update_progress( self, completed_count, total_count, update_frequency=1, ): """ Update the task backend with both an estimated percentage complete and number of seconds remaining until completion. ``completed_count`` Number of task "units" that ha...
python
def _reversedict(d): """ Internal helper for generating reverse mappings; given a dictionary, returns a new dictionary with keys and values swapped. """ return dict(list(zip(list(d.values()), list(d.keys()))))
java
@Deprecated public static RequestAsyncTask executeGraphPathRequestAsync(Session session, String graphPath, Callback callback) { return newGraphPathRequest(session, graphPath, callback).executeAsync(); }
python
def box_filter(array, n_iqr=1.5, return_index=False): """Box plot outlier detector. :param array: array of data. :param n_std: default 1.5, exclude data out of ``n_iqr`` IQR. :param return_index: boolean, default False, if True, only returns index. """ if not isinstance(array, np.ndarray): ...
java
private synchronized String createDelimitedList(String preferred) { StringBuffer listBuf = new StringBuffer(); int prefIndex = order.indexOf(preferred); // remove preferred and add it back at the end to ensure it is not // duplicated in the list returned if (prefIndex != -1) { listBuf.append(preferred); ...
python
def logger(self, iteration, ret): """Print out relevant information at each epoch""" print("Learning rate: {:f}".format(self.lr_scheduler.get_lr()[0])) entropies = getEntropies(self.model) print("Entropy and max entropy: ", float(entropies[0]), entropies[1]) print("Training time for epoch=", self.ep...
java
public static Map<String, Object> transformPrincipalAttributesListIntoMap(final List<String> list) { val map = transformPrincipalAttributesListIntoMultiMap(list); return CollectionUtils.wrap(map); }
java
public Node parse(Reader in) throws IOException, SAXException { InputSource is = new InputSource(in); getXMLReader().parse(is); return parent; }
java
public void commit() throws SQLException { if (useConnection == null) { LOG.info("Commit operation not supported when using datasets unless using withTransaction or cacheConnection - attempt to commit ignored"); return; } try { useConnection.commit(); ...
java
public List<List<String>> getImplicitPermissionsForUser(String user) { List<String> roles = new ArrayList<>(); roles.add(user); roles.addAll(this.getImplicitRolesForUser(user)); List<List<String>> res = new ArrayList<>(); for (String n : roles) { res.addAll(this.getPe...
java
public static BigInteger decode(String s) { byte[] bytes = Base64.decodeBase64(s); BigInteger bi = new BigInteger(1, bytes); return bi; }
python
def get_project(url=None, username=None, password=None, token=None, scope=None, scope_id=None, env_filename=None, status=ScopeStatus.ACTIVE): """ Retrieve and return the KE-chain project to be used throughout an app. This helper is made to bootstrap a pykechain enabled python script or an j...
java
public void updateFeedback(String feedbackId, @FeedbackEvent.FeedbackType String feedbackType, String description, String screenshot) { navigationTelemetry.updateFeedbackEvent(feedbackId, feedbackType, description, screenshot); }
python
def make_spiral_texture(spirals=6.0, ccw=False, offset=0.0, resolution=1000): """Makes a texture consisting of a spiral from the origin. Args: spirals (float): the number of rotations to make ccw (bool): make spirals counter-clockwise (default is clockwise) offset (float): if non-zero, ...
java
public void load(Reader in) { try { doLoad(in); } catch (Exception e) { throw Exceptions.propagate(e); } }
python
def ReadFlowRequestsReadyForProcessing(self, client_id, flow_id, next_needed_request, cursor=None): """Reads all requests for a flow that can be process...
java
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); int count = s.readInt(); char[] value = (char[]) s.readObject(); append(value, 0, count); }
java
public ServiceFuture<List<P2SVpnServerConfigurationInner>> listByVirtualWanAsync(final String resourceGroupName, final String virtualWanName, final ListOperationCallback<P2SVpnServerConfigurationInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByVirtualWanSinglePageAsync(res...
python
def ping_hub(self): ''' Attempt to ping the ZeroMQ plugin hub to verify connection is alive. If ping is successful, record timestamp. If ping is unsuccessful, call `on_heartbeat_error` method. ''' if self.plugin is not None: try: self.plugin.e...
java
public Observable<Page<EnvironmentInner>> listNextAsync(final String nextPageLink) { return listNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<EnvironmentInner>>, Page<EnvironmentInner>>() { @Override public Page<EnvironmentInner> call(...
java
public RateLimiter getRateLimiter() { double currentThroughput = DatabaseDescriptor.getCompactionThroughputMbPerSec() * 1024.0 * 1024.0; // if throughput is set to 0, throttling is disabled if (currentThroughput == 0 || StorageService.instance.isBootstrapMode()) currentThroughput...
java
protected static Object getObject(String property, String defaultValue, Class cls) { Object result; String tmpStr; String[] tmpOptions; result = null; try { tmpStr = get(property, defaultValue); tmpOptions = Utils.splitOptions(tmpStr); if (tm...
python
def _parse_stack_cfg(content): ''' Allow top level cfg to be YAML ''' try: obj = salt.utils.yaml.safe_load(content) if isinstance(obj, list): return obj except Exception as e: pass return content.splitlines()
java
@Override protected InetAddress isAcceptable(NetworkInterface networkInterface, InetAddress address) throws SocketException { if( networkInterface.isPointToPoint() ) return address; return null; }
java
public ServiceFuture<Void> reimageAsync(String poolId, String nodeId, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromHeaderResponse(reimageWithServiceResponseAsync(poolId, nodeId), serviceCallback); }
java
public static <T extends ImageBase<T>> void plus(T input, double value, T output) { if( input instanceof ImageGray) { if (GrayU8.class == input.getClass()) { PixelMath.plus((GrayU8) input, (int) value, (GrayU8) output); } else if (GrayS8.class == input.getClass()) { PixelMath.plus((GrayS8) input, (int) ...
java
public ApiSuccessResponse addRecentTarget(RecentTargetData recentTargetData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = addRecentTargetWithHttpInfo(recentTargetData); return resp.getData(); }
java
public static String encodeUrlPath(String href, String encoding) throws UnsupportedEncodingException { if(href.startsWith("tel:")) return href.replace(' ', '-'); int len = href.length(); int pos = 0; int stopAt; { int anchorAt = href.lastIndexOf('#'); int paramsAt = href.lastIndexOf('?', (anchorAt==-1 ?...
java
private static ObjectSchema readSchema(String url, String user, String pass, SyntaxToJavaClass syntaxToJavaClass, Set<String> binarySet, Set<String> objectClasses) throws NamingException, ClassNotFoundException { // Set up environment Hashtable<String, String> env = new Ha...
java
public static <T extends Geometry> JTSGeometryExpression<T> asJTSGeometry( Expression<T> expr) { Expression<T> underlyingMixin = ExpressionUtils.extract(expr); return new JTSGeometryExpression<T>(underlyingMixin) { private static final long serialVersionUID = -671404400557042000...
python
def should_bypass_proxies(url, no_proxy): """ Returns whether we should bypass proxies or not. :rtype: bool """ # Prioritize lowercase environment variables over uppercase # to keep a consistent behaviour with other http projects (curl, wget). get_proxy = lambda k: os.environ.get(k) or os.e...
python
def _mixed_precision_is_enabled(hparams): """Should be the same as in common_attention, avoiding import.""" activation_dtype = hparams.activation_dtype weight_dtype = hparams.weight_dtype return activation_dtype == tf.float16 and weight_dtype == tf.float32
java
protected <T> T create(Class<T> type, Map<String, String> config) { // Use #doInstantiate so inheriting classes can override it, as #instantiate is static final. T instance = doInstantiate(type, config); if (instance instanceof AsyncInitialize) { asyncInitializeAwaiting.incrementAnd...
java
@Override public void setVariables(Map<String, String> variables) { injectVariables(variables, element); /** * This is valid: * <code> * select(element(ById.class, "element-id"})).index(intVar("element-index")) * </code> * and it will be resolved to ...
java
@Nonnull @ReturnsMutableCopy public static <T> ICommonsList <T> getAllSPIImplementations (@Nonnull final Class <T> aSPIClass, @Nullable final Logger aLogger) { return getAllSPIImplementations (aSPIClass, ClassLoaderHelper.getDefaultClassLoader (),...
python
def checkURL(cls, trust_root, url): """quick func for validating a url against a trust root. See the TrustRoot class if you need more control.""" tr = cls.parse(trust_root) return tr is not None and tr.validateURL(url)
java
public void searchGuildID(String name, Callback<List<String>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.GUILD, name)); gw2API.searchGuildID(name).enqueue(callback); }
python
def _update_record(self, record_id, name, address, ttl): """Updates an existing record.""" data = json.dumps({'record': {'name': name, 'content': address, 'ttl': ttl}}) headers = {'Content-Type': 'application/json'} ...
python
def contextMenuEvent(self, event): """ Creates and executes the context menu for the tree view """ menu = QtWidgets.QMenu(self) for action in self.actions(): menu.addAction(action) openAsMenu = self.createOpenAsMenu(parent=menu) menu.insertMenu(self.closeIte...
python
def _init_c2ps(self, go_sources, traverse_child): """Traverse up children.""" if not traverse_child: return {} c2ps = defaultdict(set) goids_seen = set() go2obj = self.go2obj for goid_src in go_sources: goobj_src = go2obj[goid_src] if g...
java
public CertificateAddHeaders withLastModified(DateTime lastModified) { if (lastModified == null) { this.lastModified = null; } else { this.lastModified = new DateTimeRfc1123(lastModified); } return this; }
java
@FFDCIgnore({ InterruptedException.class }) public synchronized void waitForComplete() { // Don't bother waiting if the vm has been shutdown in the meanwhile... while (done.get() == false && !shutdownHook.vmShutdown()) { try { // refresh packages should not take a long ti...
python
def ensure_views(): ''' This function makes sure that all the views that should exist in the design document do exist. ''' # Get the options so we have the URL and DB.. options = _get_options(ret=None) # Make a request to check if the design document exists. _response = _request("GET",...
java
public void findStronglyConnectedComponents(GraphType g, GraphToolkit<GraphType, EdgeType, VertexType> toolkit) { // Perform the initial depth first search DepthFirstSearch<GraphType, EdgeType, VertexType> initialDFS = new DepthFirstSearch<>(g); if (m_vertexChooser != null) { initia...
java
private IRStatement maybeWrapProgramEvaluateForManangedProgram( DynamicFunctionSymbol dfs, IRStatement methodBody ) { if( dfs.getDisplayName().equals( "evaluate" ) ) { IType[] argTypes = dfs.getArgTypes(); if( argTypes.length == 1 && argTypes[0] == JavaTypes.IEXTERNAL_SYMBOL_MAP() ) { ...
python
def pprint(object, stream=None, indent=1, width=80, depth=None): """Pretty-print a Python object to a stream [default is sys.stdout].""" printer = PrettyPrinter( stream=stream, indent=indent, width=width, depth=depth) printer.pprint(object)
java
private Settings enrichWithOfflineMode(Settings settings) { String goOffline = SecurityActions.getProperty(ALT_MAVEN_OFFLINE); if (goOffline != null && goOffline.length() > 0) { settings.setOffline(Boolean.valueOf(goOffline)); } return settings; }
python
def parse_changes(): """ grab version from CHANGES and validate entry """ with open('CHANGES') as changes: for match in re.finditer(RE_CHANGES, changes.read(1024), re.M): if len(match.group(1)) != len(match.group(3)): error('incorrect underline in CHANGES') date...
java
public final void ruleXExpressionInClosure() throws RecognitionException { int stackSize = keepStackSize(); try { // InternalXbase.g:821:2: ( ( ( rule__XExpressionInClosure__Group__0 ) ) ) // InternalXbase.g:822:2: ( ( rule__XExpressionInClosure__Group__0 ) ) ...
python
def is_docstring(tokens, previous_logical): """Return found docstring 'A docstring is a string literal that occurs as the first statement in a module, function, class,' http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring """ for token_type, text, start, _, _ in tokens: if token...
python
def _prepare_insert(self, tmpl, record_class, field_names, placeholder_for_id=False): """ With transaction isolation level of "read committed" this should generate records with a contiguous sequence of integer IDs, using an indexed ID column, the database-side SQL max function, the ...
java
@Override public DescribeSpotInstanceRequestsResult describeSpotInstanceRequests(DescribeSpotInstanceRequestsRequest request) { request = beforeClientExecution(request); return executeDescribeSpotInstanceRequests(request); }
java
public static void mkdirsWithRecursivePermission(final FileSystem fs, final Path path, FsPermission perm) throws IOException { mkdirsWithRecursivePermissionWithRetry(fs, path, perm, NO_RETRY_CONFIG); }
python
def sanitize_excel_sheet_name(sheet_name, replacement_text=""): """ Replace invalid characters for an Excel sheet name within the ``sheet_name`` with the ``replacement_text``. Invalid characters are as follows: |invalid_excel_sheet_chars|. The ``sheet_name`` truncate to 31 characters (max sh...
python
def _CreateLineStringForShape(self, parent, shape): """Create a KML LineString using coordinates from a shape. Args: parent: The parent ElementTree.Element instance. shape: The transitfeed.Shape instance. Returns: The LineString ElementTree.Element instance or None if coordinate_list is ...
python
def pop(self, n=1, raw=False, delete=True): """Pop status queue :param int n: number of messages to return as part of peek. :param bool raw: should message content be returned as is (no parsing). :param bool delete: should message be deleted after pop. default is True as this is expected...
python
def _anonymize_table(cls, table_data, pii_fields): """Anonymize in `table_data` the fields in `pii_fields`. Args: table_data (pandas.DataFrame): Original dataframe/table. pii_fields (list[dict]): Metadata for the fields to transform. Result: pandas.DataFrame...
java
public Pair<String, String> decryptResetToken(String encryptedToken) throws RuntimeException { // USER_ID-sep-DIGESTED_HASH-sep-System.currentTimeMillis String decriptedMessage = tokenEncryptor.decrypt(encryptedToken); String[] decriptArray = decriptedMessage.split(SEPARATOR); if (decriptAr...
python
def create(self, create_missing=None): """Manually fetch a complete set of attributes for this entity. For more information, see `Bugzilla #1219653 <https://bugzilla.redhat.com/show_bug.cgi?id=1219653>`_. """ return Media( self._server_config, id=self.cr...
python
def main(argv=None, input_stream=stdin, output_stream=stdout, error_stream=stderr): """runs inline function - more info run `cbox --help`""" args = _parse_args(argv) args_dict = args.__dict__.copy() inline_str = args_dict.pop('inline') modules = args_dict.pop('modules') func = get_inli...
python
def clean(self): '''Clean the workspace''' if self.config.clean: logger.info('Cleaning') self.execute(self.config.clean)
java
public void processSpace(Properties properties) { try { Transform transform = null; // If the user specified a transform, then apply it and update the // matrix file String transformClass = properties.getProperty(MATRIX_TRANSFORM_PROPERTY); ...
java
public SIMPPtoPOutboundTransmitControllable getPtoPOutboundTransmit() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getPtoPOutboundTransmit"); SIMPPtoPOutboundTransmitControllable control = null; if(xmitPointControl != null) { control = xmitPointContr...
python
def get_areas(self, area_id=None, **kwargs): """ Alias for get_elements() but filter the result by Area :param area_id: The Id of the area :type area_id: Integer :return: List of elements """ return self.get_elements(Area, elem_id=area_id, **kwargs)
java
public static final void replaceSMILESWithTemporaryIds(HELM2Notation helm2notation) throws NotationException, HELM2HandledException, ChemistryException, CTKException, MonomerLoadingException, JDOMException { for (int i = 0; i < helm2notation.getListOfPolymers().size(); i++) { /* First save intern smiles to t...
java
public void updateImage() { if (m_iCurrentState == ON) this.setIcon(m_iconOn); else if (m_iCurrentState == OFF) this.setIcon(m_iconOff); else this.setIcon(m_iconNull); }
python
def list_firewall_policies(self, retrieve_all=True, **_params): """Fetches a list of all firewall policies for a project.""" # Pass filters in "params" argument to do_request return self.list('firewall_policies', self.firewall_policies_path, retrieve_all, **_params)
java
@Override public BatchDeleteImportDataResult batchDeleteImportData(BatchDeleteImportDataRequest request) { request = beforeClientExecution(request); return executeBatchDeleteImportData(request); }
python
def izip_exact(*iterables): """ A lazy izip() that ensures that all iterables have the same length. A LengthMismatch exception is raised if the iterables' lengths differ. Examples -------- >>> list(zip_exc([])) [] >>> list(zip_exc((), (), ())) [] >>> list(zi...
python
def varvalu(self, varn=None): ''' $foo $foo.bar $foo.bar() $foo[0] $foo.bar(10) ''' self.ignore(whitespace) if varn is None: varn = self.varname() varv = s_ast.VarValue(kids=[varn]) # handle derefs and calls... ...
java
public static <T> ListMarshaller<T> of( BytesReader<T> elementReader, BytesWriter<? super T> elementWriter) { return new ListMarshaller<>(elementReader, elementWriter); }
java
public int getBatchSize() { if (isBatch()) { String batchSize = getProperty(PersistenceProperties.KUNDERA_BATCH_SIZE); int batch_Size = Integer.valueOf(batchSize); if (batch_Size == 0) { throw new IllegalArgumentException("kunde...
python
def filter_rows_with_differences(rows): """ Find all rows with differences in the status column. """ if not rows: # empty table return [] if len(rows[0].results) == 1: # table with single column return [] def get_index_of_column(name, cols): for i in ran...
python
def trace_dispatch(self, frame, event, arg): """This function is called every line, function call, function return and exception during trace""" fun = getattr(self, 'handle_' + event, None) if not fun: return self.trace_dispatch below, continue_below = self.check_belo...
python
def copy(source): "Copy a docstring from another source function (if present)" def do_copy(target): if source.__doc__: target.__doc__ = source.__doc__ return target return do_copy
python
def merge_deltas(stmts_in): """Gather and merge original Influence delta information from evidence. This function is only applicable to Influence Statements that have subj and obj deltas. All other statement types are passed through unchanged. Polarities and adjectives for subjects and objects respect...
python
def clear_global(self): """Clear only any cached global data. """ vname = self.varname logger.debug(f'global clearning {vname}') if vname in globals(): logger.debug('removing global instance var: {}'.format(vname)) del globals()[vname]
python
def create(self, index, doc_type, body, id=None, **query_params): """ Adds a typed JSON document in a specific index, making it searchable. Behind the scenes this method calls index(..., op_type='create') `<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html>`...
python
def image_update_properties(request, image_id, remove_props=None, **kwargs): """Add or update a custom property of an image.""" return glanceclient(request, '2').images.update(image_id, remove_props, **kwargs...
python
def present(name, brand, zonepath, properties=None, resources=None): ''' Ensure a zone with certain properties and resources name : string name of the zone brand : string brand of the zone zonepath : string path of the zone properties : list of key-value pairs di...
python
def _thread_main(self): """The entry point for the worker thread. Pulls pending data off the queue and writes them in batches to the specified tracing backend using the exporter. """ quit_ = False while True: items = self._get_items() data = [] ...
python
def _create_at(self, timestamp=None, id=None, forced_identity=None, **kwargs): """ WARNING: Only for internal use and testing. Create a Versionable having a version_start_date and version_birth_date set to some pre-defined timestamp :param timestamp: point in...
python
def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """ Create an instance of :class:`~ShellCommand` and run it Args: command (str): :class:`~ShellCommand` block (bool): See :class:`~ShellCommand` ...
python
def unpack(iterable, count, fill=None): """ The iter data unpack function. Example 1: In[1]: source = 'abc' In[2]: a, b = safe_unpack(source, 2) In[3]: print(a, b) a b Example 2: In[1]: source = 'abc' In[2]: a, b, c, d = safe_unpack(source, 4) In...
python
def create_cherry_pick(self, cherry_pick_to_create, project, repository_id): """CreateCherryPick. [Preview API] Cherry pick a specific commit or commits that are associated to a pull request into a new branch. :param :class:`<GitAsyncRefOperationParameters> <azure.devops.v5_0.git.models.GitAsync...
python
def tss(self, up=0, down=0): """ Return a start, end tuple of positions around the transcription-start site Parameters ---------- up : int if greature than 0, the strand is used to add this many upstream bases in the appropriate direction ...
python
def rmdir(self, dir_name): """Remove cur_dir/name.""" self.check_write(dir_name) path = normpath_url(join_url(self.cur_dir, dir_name)) # write("REMOVE %r" % path) shutil.rmtree(path)
java
public void clearTempFiles(boolean preserveZipFile) { //delete the temp sql file File sqlFile = new File(dirName + "/sql/" + sqlFileName); if(sqlFile.exists()) { boolean res = sqlFile.delete(); logger.debug(LOG_PREFIX + ": " + sqlFile.getAbsolutePath() + " deleted ...
python
def download_dataset(storage_client, image_batches, target_dir, local_dataset_copy=None): """Downloads dataset, organize it by batches and rename images. Args: storage_client: instance of the CompetitionStorageClient image_batches: subclass of ImageBatchesBase with data about images ...
java
@Override public CPDefinitionOptionValueRel findByUuid_C_Last(String uuid, long companyId, OrderByComparator<CPDefinitionOptionValueRel> orderByComparator) throws NoSuchCPDefinitionOptionValueRelException { CPDefinitionOptionValueRel cpDefinitionOptionValueRel = fetchByUuid_C_Last(uuid, companyId, orderByC...
python
def insertChild(self, childItem, position=None): """ Inserts a child item to the current item. The childItem must not yet have a parent (it will be set by this function). IMPORTANT: this does not let the model know that items have been added. Use BaseTreeModel.insertItem ins...
java
public void registerTimeout(final K key, final long delay, final TimeUnit unit) { Preconditions.checkState(timeoutListener != null, "The " + getClass().getSimpleName() + " has not been started."); if (timeouts.containsKey(key)) { unregisterTimeout(key); } timeouts.put(key, new Timeout<>(timeoutListener,...
python
def show(self, display=None): """Removes the display style attribute. If a display type is provided """ self._stable = False if not display: self.attrs["style"].pop("display") else: self.attrs["style"]["display"] = display return self
java
@SuppressWarnings("unchecked") @Override public EList<MethodMetric> getMethods() { return (EList<MethodMetric>) eGet(StorePackage.Literals.INTERFACE_METRIC__METHODS, true); }
java
@Override public void onDraw() { // draw is only expected if the controller is attached if (mIsControllerAttached) { return; } // something went wrong here; controller is not attached, yet the hierarchy has to be drawn // log error and attach the controller FLog.w( DraweeEventTr...
python
def asluav_status_send(self, LED_status, SATCOM_status, Servo_status, Motor_rpm, force_mavlink1=False): ''' Extended state information for ASLUAVs LED_status : Status of the position-indicator LEDs (uint8_t) SATCOM_status : Stat...
java
private static Properties loadProperties(String propertiesFile) { Properties properties = new Properties(); try (InputStream is = new FileInputStream(propertiesFile)) { properties.load(is); } catch (IOException e) { throw new RuntimeException("failed to load properties", e); } return pro...