language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private Map<String, String> prepareHeaderRowDataMap(List<String> header, List<String> rowData) { Map<String, String> headerRowDataMap = new HashMap<>(); if (header.size() == rowData.size()) { for (int i = 0; i < header.size(); i++) { if (null != header.get(i)) { ...
python
def d_x(data, axis, boundary='forward-backward'): ''' Calculates a second-order centered finite difference of data along the specified axis. Parameters ---------- data : ndarray Data on which we are taking a derivative. axis : int Index of the data array on which to take the difference. boundary : string,...
java
public DataObjectModel view(Collection<? extends DataObject> dos) { DataObjectModel view = clone(); view.propertyList = new ArrayList<String>(); Set<String> propertySet = new HashSet<String>(); for (DataObject dob : dos) { for (String property : propertyLis...
python
def NS(domain, resolve=True, nameserver=None): ''' Return a list of IPs of the nameservers for ``domain`` If ``resolve`` is False, don't resolve names. CLI Example: .. code-block:: bash salt ns1 dig.NS google.com ''' dig = ['dig', '+short', six.text_type(domain), 'NS'] if na...
python
def ufloatDict_stdev(self, ufloat_dict): 'This gives us a dictionary of nominal values from a dictionary of uncertainties' return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.std_dev, ufloat_dict.values())))
java
@Override public DescribeReplicationTasksResult describeReplicationTasks(DescribeReplicationTasksRequest request) { request = beforeClientExecution(request); return executeDescribeReplicationTasks(request); }
java
static int gcd(int a, int b) { while (a != b) { if (a > b) { int na = a % b; if (na == 0) return b; a = na; } else { int nb = b % a; if (nb == 0) return a; b = nb; } } return a; }
java
protected boolean calculateGestureTransform( Matrix outTransform, @LimitFlag int limitTypes) { TransformGestureDetector detector = mGestureDetector; boolean transformCorrected = false; outTransform.set(mPreviousTransform); if (mIsRotationEnabled) { float angle = detector.getRotation() ...
python
def factory_profiles(self): '''The factory profiles of all loaded modules.''' with self._mutex: if not self._factory_profiles: self._factory_profiles = [] for fp in self._obj.get_factory_profiles(): self._factory_profiles.append(utils.nvlis...
java
public final boolean awaitUninterruptibly() { try { return await(15, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } }
java
@SuppressWarnings("PMD") static Double eval(String expr, Map<String, ? extends Number> vars) { Deque<Double> stack = new ArrayDeque<>(); String[] parts = expr.split("[,\\s]+"); for (String part : parts) { switch (part) { case ":add": binaryOp(stack, (a, b) -> a + b); break; ca...
python
def has_relationship(self, left_id, left_type, right_id, right_type, rel_type='Related To'): """ Checks if the two objects are related Args: left_id: The CRITs ID of the first indicator left_type: The CRITs TLO type of the first indicator ...
java
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the threshold, loadfactor, and any hidden stuff s.defaultReadObject(); // Read in number of buckets and allocate the bucket array; int numBuckets = s.readInt(...
python
def rm(*components, **kwargs): """ Remove a file or directory. If path is a directory, this recursively removes the directory and any contents. Non-existent paths are silently ignored. Supports Unix style globbing by default (disable using glob=False). For details on globbing pattern expansion...
python
def get_url(url, data=None, cached=True, cache_key=None, crawler='urllib'): """Retrieves the HTML code for a given URL. If a cached version is not available, uses phantom_retrieve to fetch the page. data - Additional data that gets passed onto the crawler. cached - If True, retrieves the URL from the ...
java
private void showAssertInfo(IAssert<?> assertCommand, AssertionError ex, boolean failedTest) { ITestResult testResult = Reporter.getCurrentTestResult(); // Checks whether the soft assert was called in a TestNG test run or else within a Java application. String methodName = "main"; if (t...
java
private IMolecularFormula getFormula(List<IIsotope> isoToCond_new, int[] value_In) { IMolecularFormula mf = builder.newInstance(IMolecularFormula.class); for (int i = 0; i < isoToCond_new.size(); i++) { if (value_In[i] != 0) { for (int j = 0; j < value_In[i]; j++) ...
python
def time_iteration(model, initial_guess=None, dprocess=None, with_complementarities=True, verbose=True, grid={}, maxit=1000, inner_maxit=10, tol=1e-6, hook=None, details=False): ''' Finds a global solution for ``model`` using backward time-iteration. This al...
python
def grains(**kwargs): ''' Get grains for minion. .. code-block: bash salt '*' nxos.cmd grains ''' if not DEVICE_DETAILS['grains_cache']: ret = salt.utils.nxos.system_info(show_ver(**kwargs)) log.debug(ret) DEVICE_DETAILS['grains_cache'].update(ret['nxos']) retur...
python
def get_uri(self, ncname: str) -> Optional[str]: """ Get the URI associated with ncname @param ncname: """ uri = cu.expand_uri(ncname + ':', self.curi_maps) return uri if uri and uri.startswith('http') else None
java
public void setBaselineFinish(int baselineNumber, Date value) { set(selectField(AssignmentFieldLists.BASELINE_FINISHES, baselineNumber), value); }
python
def pool_create(hypervisor, identifier, pool_path): """Storage pool creation. The following values are set in the XML configuration: * name * target/path * target/permission/label """ path = os.path.join(pool_path, identifier) if not os.path.exists(path): os.makedirs(pat...
java
public DoubleColumn map(ToDoubleFunction<Double> fun) { DoubleColumn result = DoubleColumn.create(name()); for (double t : this) { try { result.append(fun.applyAsDouble(t)); } catch (Exception e) { result.appendMissing(); } } ...
java
public TldExtensionType<TldTaglibType<T>> getOrCreateTaglibExtension() { List<Node> nodeList = childNode.get("taglib-extension"); if (nodeList != null && nodeList.size() > 0) { return new TldExtensionTypeImpl<TldTaglibType<T>>(this, "taglib-extension", childNode, nodeList.get(0)); }...
python
def redirect_stdout(self): """Redirect stdout to file so that it can be tailed and aggregated with the other logs.""" self.hijacked_stdout = sys.stdout self.hijacked_stderr = sys.stderr # 0 must be set as the buffer, otherwise lines won't get logged in time. sys.stdout = open(sel...
java
public List<StorageTierView> getTierViewsBelow(String tierAlias) { int ordinal = getTierView(tierAlias).getTierViewOrdinal(); return mTierViews.subList(ordinal + 1, mTierViews.size()); }
python
def _generate_list_skippers(self): """ Generate the list of skippers of page. :return: The list of skippers of page. :rtype: hatemile.util.html.htmldomelement.HTMLDOMElement """ container = self.parser.find( '#' + AccessibleNavigationImplementati...
java
public CreateResolverRuleRequest withTargetIps(TargetAddress... targetIps) { if (this.targetIps == null) { setTargetIps(new java.util.ArrayList<TargetAddress>(targetIps.length)); } for (TargetAddress ele : targetIps) { this.targetIps.add(ele); } return thi...
java
@Override public void initialize(String path, List<String> columns) throws IOException, UnsupportedOperationException { super.initialize(path, columns); initializeInternal(); }
java
public void tickets_ticketId_score_POST(Long ticketId, String score, String scoreComment) throws IOException { String qPath = "/support/tickets/{ticketId}/score"; StringBuilder sb = path(qPath, ticketId); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "score", score); addBody(o, "scoreCo...
python
def detect(self, text): """Detect language of the input text :param text: The source text(s) whose language you want to identify. Batch detection is supported via sequence input. :type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, iterator, gener...
python
def create_prj_browser(self, ): """Create the project browser This creates a combobox brower for projects and adds it to the ui :returns: the created combo box browser :rtype: :class:`jukeboxcore.gui.widgets.browser.ComboBoxBrowser` :raises: None """ prj...
python
def _t_update_b(self): r""" A method to update 'b' array at each time step according to 't_scheme' and the source term value """ network = self.project.network phase = self.project.phases()[self.settings['phase']] Vi = network['pore.volume'] dt = self.sett...
python
def p(self, path): """ provide absolute path within the container :param path: path with container :return: str """ if path.startswith("/"): path = path[1:] p = os.path.join(self.mount_point, path) logger.debug("path = %s", p) return p
python
def format_stack_trace_json(self): """Convert a StackTrace object to json format.""" stack_trace_json = {} if self.stack_frames: stack_trace_json['stack_frames'] = { 'frame': self.stack_frames, 'dropped_frames_count': self.dropped_frames_count ...
java
public final LogMetric updateLogMetric(MetricName metricName, LogMetric metric) { UpdateLogMetricRequest request = UpdateLogMetricRequest.newBuilder() .setMetricName(metricName == null ? null : metricName.toString()) .setMetric(metric) .build(); return updateLogMetri...
java
public Observable<P2SVpnServerConfigurationInner> createOrUpdateAsync(String resourceGroupName, String virtualWanName, String p2SVpnServerConfigurationName, P2SVpnServerConfigurationInner p2SVpnServerConfigurationParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, virtualWanName, p2SV...
python
def region_option(f): """ Configures --region option for CLI :param f: Callback Function to be passed to Click """ def callback(ctx, param, value): state = ctx.ensure_object(Context) state.region = value return value return click.option('--region', ...
java
public void startMethod(String methodName, String type, short flags) { short methodNameIndex = itsConstantPool.addUtf8(methodName); short typeIndex = itsConstantPool.addUtf8(type); itsCurrentMethod = new ClassFileMethod(methodName, methodNameIndex, type, typeIndex, flags); it...
java
public static boolean renderBehaviorizedAttribute( FacesContext facesContext, ResponseWriter writer, String componentProperty, UIComponent component, String eventName, Collection<ClientBehaviorContext.Parameter> eventParameters, Map<String, List<ClientBehavior>> clientBeh...
python
def fit_circle_check(points, scale, prior=None, final=False, verbose=False): """ Fit a circle, and reject the fit if: * the radius is larger than tol.radius_min*scale or tol.radius_max*scale * any segment spans more than...
java
@Override public ListTypedLinkFacetNamesResult listTypedLinkFacetNames(ListTypedLinkFacetNamesRequest request) { request = beforeClientExecution(request); return executeListTypedLinkFacetNames(request); }
java
private static void drawLine(int x0, int y0, int x1, int y1, boolean[][] pic) { final int xres = pic.length, yres = pic[0].length; // Ensure bounds y0 = (y0 < 0) ? 0 : (y0 >= yres) ? (yres - 1) : y0; y1 = (y1 < 0) ? 0 : (y1 >= yres) ? (yres - 1) : y1; x0 = (x0 < 0) ? 0 : (x0 >= xres) ? (xres - 1) : ...
java
private void removePartitionResults(QueryResult queryResult, int partitionId) { List<QueryResultRow> rows = queryResult.getRows(); rows.removeIf(resultRow -> getPartitionId(resultRow) == partitionId); }
python
def load_db(file, db, verbose=True): """ Load :class:`mongomock.database.Database` from a local file. :param file: file path. :param db: instance of :class:`mongomock.database.Database`. :param verbose: bool, toggle on log. :return: loaded db. """ db_data = json.load(file, verbose=verbo...
python
def save_to_db(model_text_id, parsed_values): """save to db and return saved object""" Model = apps.get_model(model_text_id) # normalise values and separate to m2m, simple simple_fields = {} many2many_fields = {} for field, value in parsed_values.items(): if ...
python
def count_missing(self, axis=None): """Count missing genotypes. Parameters ---------- axis : int, optional Axis over which to count, or None to perform overall count. """ b = self.is_missing() return np.sum(b, axis=axis)
java
public void save() throws IOException { FileChooser.SimpleFileFilter filter = FileChooser.SimpleFileFilter.getWritableImageFIlter(); JFileChooser chooser = FileChooser.getInstance(); chooser.setFileFilter(filter); chooser.setAcceptAllFileFilterUsed(false); chooser.setSelectedFile...
python
def tensor_dim_to_mesh_dim_size(layout, mesh_shape, tensor_dim): """How many ways does a tensor dimension get split. This is used to "cheat" when building the mtf graph and peek at how a tensor dimension will be split. Returns 1 if the tensor dimension is not split. Args: layout: an input to convert_to...
java
public double evaluate(Map<String, Double> localVariables) { if (this.root == null) { throw new RuntimeException("[function error] evaluation failed " + "because function is not loaded"); } return this.root.evaluate(localVariables); }
java
boolean checkTag(long bucketIndex, int posInBucket, long tag) { long tagStartIdx = getTagOffset(bucketIndex, posInBucket); final int bityPerTag = bitsPerTag; for (long i = 0; i < bityPerTag; i++) { if (memBlock.get(i + tagStartIdx) != ((tag & (1L << i)) != 0)) return false; } return true; }
java
public PutEventsResult withEntries(PutEventsResultEntry... entries) { if (this.entries == null) { setEntries(new java.util.ArrayList<PutEventsResultEntry>(entries.length)); } for (PutEventsResultEntry ele : entries) { this.entries.add(ele); } return this; ...
java
public boolean validate(DependencyExplorerOutput output, InvalidKeys invalidKeys) { Collection<Map.Entry<Key<?>, String>> invalidRequiredKeys = invalidKeys.getInvalidRequiredKeys(); for (Map.Entry<Key<?>, String> error : invalidRequiredKeys) { reportError(output, error.getKey(), error.getValue())...
java
public static <T> CallbackList<T> create(Callback<T> callback) { CallbackList<T> list = new CallbackList<T>(); list.add(callback); return list; }
java
private Map<PortalDataKey, Set<BucketTuple>> prepareImportQueue( final ITenant tenant, final Set<Resource> templates) throws Exception { final Map<PortalDataKey, Set<BucketTuple>> rslt = new HashMap<>(); Resource rsc = null; try { for (Resource r : templates) { ...
java
public final Parser<RECORD> addDissector(final Dissector dissector) { assembled = false; if (dissector != null) { allDissectors.add(dissector); } return this; }
java
private void createCountersManager() { UnsafeBuffer counterLabelsBuffer = monitorFileWriter.createServiceCounterLabelsBuffer(index); UnsafeBuffer counterValuesBuffer = monitorFileWriter.createServiceCounterValuesBuffer(index); countersManager = new CountersManager(counterLabelsBuffer, counterVa...
java
@Override public void onNotificationMessageClicked(Context context, com.xiaomi.mipush.sdk.MiPushMessage miPushMessage) { processMiNotification(miPushMessage); }
java
public void destroy() { WaylandClientCore.INSTANCE() .wl_proxy_destroy(this.pointer); ObjectCache.remove(this.pointer); this.jObjectPointer.close(); }
python
def listdict_to_listlist_and_matrix(sparse): """Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation :param sparse: graph in listdict representation :returns: couple with listlist representation, and weight matrix :complexity: lin...
java
public Integer getAndIncrementIDSeq(final String id) { Validate.notNull(id, "ID cannot be null"); Integer count = this.idCounts.get(id); if (count == null) { count = Integer.valueOf(1); } this.idCounts.put(id, Integer.valueOf(count.intValue() + 1)); return cou...
java
private void scheduleRetryFuture() { Log.v(Log.TAG_SYNC, "%s: Failed to xfer; will retry in %d sec", this, RETRY_DELAY_SECONDS); synchronized (executor) { if (!executor.isShutdown()) { this.retryFuture = executor.schedule(new Runnable() { public void run()...
java
private void triggerEvents(WebElement element, WebDriver driver) { if ("input".equalsIgnoreCase(element.getTagName())) { driver.findElement(By.tagName("body")).click(); } }
java
public synchronized void commit() throws SQLException { checkClosed(); try { sessionProxy.commit(false); } catch (HsqlException e) { throw Util.sqlException(e); } }
python
def reactions(columns, n_results, write_db, queries): """Search for reactions""" if not isinstance(queries, dict): query_dict = {} for q in queries: key, value = q.split('=') if key == 'distinct': if value in ['True', 'true']: query_dic...
java
public Timestamp getTimestamp(final int columnIndex) throws SQLException { try { return getValueObject(columnIndex).getTimestamp(); } catch (ParseException e) { throw SQLExceptionMapper.getSQLException("Could not parse field as date"); } }
python
def ethernet_connected_chips(self): """Iterate over the coordinates of Ethernet connected chips. Yields ------ ((x, y), str) The coordinate and IP address of each Ethernet connected chip in the system. """ for xy, chip_info in six.iteritems(self):...
java
static public BigInteger[] randomBigIntegers(double start, double end, int size){ Preconditions.checkArgument(start < end, "Start must be less than end."); Random random = new Random(); random.setSeed(System.currentTimeMillis()); BigInteger[] result = new BigInteger[size]; for (int i = 0; i < size; i ++){ ...
java
public static void quickSort(double[] array, int[] idx, int from, int to) { if (from < to) { double temp = array[to]; int tempIdx = idx[to]; int i = from - 1; for (int j = from; j < to; j++) { if (array[j] <= temp) { i++; double tempValue = array[j]; array[j] = array[i]; array[i] =...
java
public static <T extends Trainable> T load(Class<T> aClass, String storageName, Configuration configuration) { try { Constructor<T> constructor = aClass.getDeclaredConstructor(String.class, Configuration.class); constructor.setAccessible(true); return constructor.newInstance(...
java
@Override public String getSurname() { final NameableVisitor visitor = new NameableVisitor(); this.accept(visitor); return visitor.getSurname(); }
python
def get(self, bucket: str, key: str) -> bytes: """ Retrieves the data for a given object in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which metadata is being retrieved. :return: the data """ try:...
python
def contract(self, x): """ Run .contract(x) on all segmentlists. """ for value in self.itervalues(): value.contract(x) return self
java
public void recreateUISharedContexts(Session session) { uiContexts.clear(); for (Context context : session.getContexts()) { Context uiContext = context.duplicate(); uiContexts.put(context.getIndex(), uiContext); } }
python
def _pick_or_create_inserted_op_moment_index( self, splitter_index: int, op: ops.Operation, strategy: InsertStrategy) -> int: """Determines and prepares where an insertion will occur. Args: splitter_index: The index to insert at. op: The operation that wi...
java
public static <A, B> FeatureGenerator<A, B> combinedFeatureGenerator( Iterable<FeatureGenerator<A, B>> generators) { return new CombinedFeatureGenerator<A, B>(generators); }
java
public void marshall(Message message, ProtocolMarshaller protocolMarshaller) { if (message == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(message.getContentType(), CONTENTTYPE_BINDING); ...
java
public MtasToken getObjectById(String field, int docId, int mtasId) throws IOException { try { Long ref; Long objectRefApproxCorrection; IndexDoc doc = getDoc(field, docId); IndexInput inObjectId = indexInputList.get("indexObjectId"); IndexInput inObject = indexInputList.get("obj...
java
public void setPanel(int panelId) { m_panel.showWidget(panelId); removeAllButtons(); if (panelId == PANEL_SELECT) { for (CmsPushButton button : m_publishSelectPanel.getButtons()) { addButton(button); } m_publishSelectPanel.updateDialogTitle();...
java
public static KV<String, SplitWord> remove(String key) { MyStaticValue.ENV.remove(key); return CRF.remove(key); }
java
public static <T> Matcher<Iterable<? extends T>> containsInRelativeOrder(final Iterable<T> items) { return IsIterableContainingInRelativeOrder.containsInRelativeOrder(items); }
python
def request(self, msgtype, msgid, method, params=[]): """Handle an incoming call request.""" result = None error = None exception = None try: result = self.dispatch.call(method, params) except Exception as e: error = (e.__class__.__name__, str(e))...
java
public static OrtcMessage parseMessage(String message) throws IOException { OrtcOperation operation = null; String JSONMessage = null; String parsedMessage = null; String filteredByServer = null; String seqId = null; String messageChannel = null; String messageId ...
java
@Override public boolean isDurable() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "isDurable"); final boolean dur = (_isPubSub && dispatcherState.isDurable()); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) ...
python
def make_scores( ic50_y, ic50_y_pred, sample_weight=None, threshold_nm=500, max_ic50=50000): """ Calculate AUC, F1, and Kendall Tau scores. Parameters ----------- ic50_y : float list true IC50s (i.e. affinities) ic50_y_pred : float list p...
java
public void save(String property, String messageKey, Object... args) { assertObjectNotNull("messageKey", messageKey); doSaveInfo(prepareUserMessages(property, messageKey, args)); }
python
def geometry(obj): """ Apply ``vtkGeometryFilter``. """ gf = vtk.vtkGeometryFilter() gf.SetInputData(obj) gf.Update() return gf.GetOutput()
java
@SuppressWarnings("unchecked") static Widget createWidget(final GVRSceneObject sceneObject) throws InstantiationException { Class<? extends Widget> widgetClass = GroupWidget.class; NodeEntry attributes = new NodeEntry(sceneObject); String className = attributes.getClassName(); ...
python
def get(self, path, local_path): """ Download file from (s)FTP to local filesystem. """ normpath = os.path.normpath(local_path) folder = os.path.dirname(normpath) if folder and not os.path.exists(folder): os.makedirs(folder) tmp_local_path = local_pat...
java
public static float readFloat(InputStream is) throws IOException { byte[] bytes = new byte[4]; is.read(bytes); return getFloat(bytes); }
python
def _parse_tensor(self, indices=False): '''Parse a tensor.''' if indices: self.line = self._skip_lines(1) tensor = np.zeros((3, 3)) for i in range(3): tokens = self.line.split() if indices: tensor[i][0] = float(tokens[1]) ...
java
@SuppressWarnings("unchecked") public static UniversalIdStrMessage newInstance() { Date now = new Date(); UniversalIdStrMessage msg = new UniversalIdStrMessage(); msg.setId(QueueUtils.IDGEN.generateId128Hex().toLowerCase()).setTimestamp(now); return msg; }
python
def _create_and_rotate_coordinate_arrays(self, x, y, orientation): """ Create pattern matrices from x and y vectors, and rotate them to the specified orientation. """ # Using this two-liner requires that x increase from left to # right and y decrease from left to right; I...
java
public ListenableFuture<JsonRpcResponse> invoke(JsonRpcRequest request) { Service service = services.lookupByName(request.service()); if (service == null) { JsonRpcError error = new JsonRpcError(HttpResponseStatus.BAD_REQUEST, "Unknown service: " + request.service()); JsonRpcResponse respo...
java
@Override public void setOutputType(TypeInformation<OUT> outTypeInfo, ExecutionConfig executionConfig) { StreamingFunctionUtils.setOutputType(userFunction, outTypeInfo, executionConfig); }
java
public Observable<ServiceResponse<Void>> downloadWithServiceResponseAsync(String resourceGroupName, String virtualWANName, GetVpnSitesConfigurationRequest request) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and...
java
public static String getForwardURI(HttpServletRequest request) { String result = (String) request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE); if (GrailsStringUtils.isBlank(result)) result = request.getRequestURI(); return result; }
python
def unit_vector(self): """Generate a unit vector (norm = 1)""" x = -math.cos(self.rpitch) * math.sin(self.ryaw) y = -math.sin(self.rpitch) z = math.cos(self.rpitch) * math.cos(self.ryaw) return Vector3(x, y, z)
python
def find_loader(self, fullname): """Try to find a loader for the specified module, or the namespace package portions. Returns (loader, list-of-portions). This method is deprecated. Use find_spec() instead. """ spec = self.find_spec(fullname) if spec is None: ...
python
def from_array(array): """ Deserialize a new WebhookInfo from a given dictionary. :return: new WebhookInfo instance. :rtype: WebhookInfo """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="...