language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def flag_values_dict(self):
"""Returns a dictionary that maps flag names to flag values."""
return {name: flag.value for name, flag in six.iteritems(self._flags())} |
java | public float getY() {
if (DocumentElement_Type.featOkTst && ((DocumentElement_Type)jcasType).casFeat_y == null)
jcasType.jcas.throwFeatMissing("y", "ch.epfl.bbp.uima.types.DocumentElement");
return jcasType.ll_cas.ll_getFloatValue(addr, ((DocumentElement_Type)jcasType).casFeatCode_y);} |
python | def Shell(device, *command):
"""Runs a command on the device and prints the stdout.
Args:
command: Command to run on the target.
"""
if command:
return device.StreamingShell(' '.join(command))
else:
# Retrieve the initial terminal prompt to use as a delimiter for future reads
... |
java | @Override
public <V> Iterator<VertexProperty<V>> properties(String... propertyKeys) {
ArrayList<VertexProperty<V>> ans = new ArrayList<VertexProperty<V>>();
if (propertyKeys.length == 0) {
if (this.properties == null) return Collections.emptyIterator();
propertyKeys = this.properties... |
java | void addPosition( String filename, int line, int column ) {
LessFilePosition pos = new LessFilePosition( filename, line, column );
if( !positions.contains( pos ) ) {
this.positions.add( pos );
}
} |
java | public TemplateFilter where(Predicate<TemplateMetadata> predicate) {
checkNotNull(predicate, "Predicate must be not a null");
this.predicate = this.predicate.and(predicate);
return this;
} |
python | def set_attr_text(self, attr_key, attr_val, el_idx=0):
"""Set the value of the selected attribute of the selected element.
Args:
attr_key : str
Name of attribute for which to search
attr_val : str
Text to set for the attribute.
el_idx : int
... |
java | int getTrieSize() {
int size = 0;
try {
// The trie serialize function returns the size of the data written.
// null output stream says give size only, don't actually write anything.
size = fTrie.serialize(null, true, dm );
} catch (IOException e) {
... |
java | static <IN, OUT> SelectBuilder<IN, OUT> fromSelect(final PatternSelectFunction<IN, OUT> function) {
return new SelectBuilder<>(function);
} |
java | public ServiceFuture<BuildTaskInner> beginUpdateAsync(String resourceGroupName, String registryName, String buildTaskName, BuildTaskUpdateParameters buildTaskUpdateParameters, final ServiceCallback<BuildTaskInner> serviceCallback) {
return ServiceFuture.fromResponse(beginUpdateWithServiceResponseAsync(resourceG... |
python | def present(email, profile="splunk", **kwargs):
'''
Ensure a user is present
.. code-block:: yaml
ensure example test user 1:
splunk.user_present:
- realname: 'Example TestUser1'
- name: 'exampleuser'
- email: 'example@domain.com'
... |
python | def get_sys_cmd_output(cmd):
"""
通过 ``subprocess`` 运行 ``cmd`` 获取系统输出
- ``cmd`` 为数组形式
- 需要符合 ``subprocess`` 调用标准
- 返回
- err信息,
- 使用 ``换行符\\n`` 分隔的数组
:param cmd:
:type cmd: list, str
:return:
:rtype:
"""
_e, op = None, ''
if not isinstance(cmd, list)... |
java | public static String resolveHostName(String hostName) {
Boolean knownLoopback = null;
try {
knownLoopback = InetAddress.getByName(hostName).isLoopbackAddress();
} catch (UnknownHostException ex) {
knownLoopback = (hostName.equals("127.0.0.1") || hostName.equals("localhost"));
}
if (known... |
python | def get_requirements(source):
"""Get the requirements from the given ``source``
Parameters
----------
source: str
The filename containing the requirements
"""
install_reqs = parse_requirements(filename=source, session=PipSession())
return [str(ir.req) for ir in install_reqs] |
python | def prais(pmat):
"""
Prais conditional mobility measure.
Parameters
----------
pmat : matrix
(k, k), Markov probability transition matrix.
Returns
-------
pr : matrix
(1, k), conditional mobility measures for each of the k classes.
Notes
-----
Prais... |
java | public void onNotify(Notify ntfy,
SubscriptionClientChildSbbLocalObject subscriptionChild) {
// compile diff
if (ntfy.getStatus().equals(SubscriptionStatus.terminated)) {
try {
final String notifier = ntfy.getNotifier();
subscriptionChild.remove();
getParent()
.subscriptionTerminated(
... |
python | def split_into(iterable, sizes):
"""Yield a list of sequential items from *iterable* of length 'n' for each
integer 'n' in *sizes*.
>>> list(split_into([1,2,3,4,5,6], [1,2,3]))
[[1], [2, 3], [4, 5, 6]]
If the sum of *sizes* is smaller than the length of *iterable*, then the
remaining i... |
java | public static Setting of(String description, DoubleProperty property) {
return new Setting<>(
description,
Field.ofDoubleType(property)
.label(description)
.render(new SimpleDoubleControl()),
property);
} |
java | public final synchronized void flush() throws Exception {
List<Long> sortedKeys = new ArrayList<Long>(buffer.keySet());
Collections.sort(sortedKeys);
while (sortedKeys.size() > 0) {
long firstKey = sortedKeys.get(0);
int firstDataLength = buffer.get(firstKey).length;
... |
java | private static synchronized void lazyInit() {
if (registry==null) {
InputStream isXml = ProteinModification.class.getResourceAsStream(DIR_XML_PTM_LIST);
lazyInit(isXml);
}
} |
java | public Map<String,InputType> getLayerActivationTypes(boolean addPreprocIfNecessary, InputType... inputTypes){
if (inputTypes == null || inputTypes.length != networkInputs.size()) {
throw new IllegalArgumentException(
"Invalid number of InputTypes: cannot add preprocessors if num... |
java | public LogWithPatternAndLevel get(String pattern, Level level) {
return get(pattern).get(level);
} |
java | public static void registerMavenLogger(Log innerLogger) {
if (INSTANCE == null) {
INSTANCE = new MavenLoggerFactory(innerLogger);
}
if (INSTANCE.innerLogger != innerLogger) {
throw new IllegalArgumentException(
"You've previously register a org.apache.maven.plugin.logging.Log that is NOT the one that ... |
java | protected boolean checkResourcePermissions(
CmsPermissionSet required,
boolean neededForFolder,
CmsMessageContainer errorMessage) {
boolean hasPermissions = false;
try {
CmsResource res;
if (neededForFolder) {
// check permissions for the ... |
python | def show_loadbalancer(self, lbaas_loadbalancer, **_params):
"""Fetches information for a load balancer."""
return self.get(self.lbaas_loadbalancer_path % (lbaas_loadbalancer),
params=_params) |
java | public static NfsStatus fromValue(int value) {
NfsStatus status = VALUES.get(value);
if (status == null) {
status = new NfsStatus(value);
VALUES.put(value, status);
}
return status;
} |
python | def get_indices(self, fit=None, tmin=None, tmax=None, specimen=None):
"""
Finds the appropriate indices in self.Data[self.s]['zijdplot_steps']
given a set of upper/lower bounds. This is to resolve duplicate
steps using the convention that the first good step of that name is
the i... |
java | public <TDPO> TransformedDataProviderContext transform(Transformer<DPO, TDPO> ruleInputTransformer) {
List<Transformer> addedTransformers = new ArrayList<Transformer>();
if (ruleInputTransformer != null) {
addedTransformers.add(ruleInputTransformer);
}
return new Transformed... |
java | public String retrieveData(String baseData, String type) {
String result;
InputStream stream = getClass().getClassLoader().getResourceAsStream(baseData);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader;
if (stream == null) {
... |
python | def get_category_activities(self, category_id = None):
"""Return activities for category. If category is not specified, will
return activities that have no category"""
category_id = category_id or -1
return self._to_dict(('id', 'name', 'category_id', 'category'), self.conn.GetCategoryAct... |
java | Node cloneOrImportNode(short operation, Node node, boolean deep) {
NodeImpl copy = shallowCopy(operation, node);
if (deep) {
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
copy.appendChild(cloneOrImportNode(operation, list.item... |
java | public void openCategories(CmsResource resource) {
getRpcProxy(I_CmsGwtDialogClientRpc.class).openCategoriesDialog(
resource.getStructureId().toString(),
OpenCms.getWorkplaceManager().isDisplayCategorySelectionCollapsed());
} |
java | public char[] toCharArray() {
final char[] b = new char[this.len];
if (this.len > 0) {
System.arraycopy(this.array, 0, b, 0, this.len);
}
return b;
} |
java | public static <L, R> @NonNull Pair<L, R> right(final @Nullable R right) {
return of(null, right);
} |
java | public UpdateOptions copy() {
return new UpdateOptions()
.bypassDocumentValidation(getBypassDocumentValidation())
.collation(getCollation())
.multi(isMulti())
.upsert(isUpsert())
.writeConcern(getWriteConcern());
} |
python | def model_deleted(sender, instance,
using,
**kwargs):
"""
Automatically triggers "deleted" actions.
"""
opts = get_opts(instance)
model = '.'.join([opts.app_label, opts.object_name])
distill_model_event(instance, model, 'deleted') |
python | def clean_column_values(df, inplace=True):
r""" Convert dollar value strings, numbers with commas, and percents into floating point values
>>> df = get_data('us_gov_deficits_raw')
>>> df2 = clean_column_values(df, inplace=False)
>>> df2.iloc[0]
Fiscal year ... |
java | @Override
public CleanupSnapshotTaskResult cleanupSnapshot(String spaceId)
throws ContentStoreException {
CleanupSnapshotTaskParameters taskParams =
new CleanupSnapshotTaskParameters();
taskParams.setSpaceId(spaceId);
String taskResult =
contentStore.performT... |
java | public void setIconTranslate( Float[] value) {
PropertyValue propertyValue = iconTranslate(value);
constantPropertyUsageMap.put(PROPERTY_ICON_TRANSLATE, propertyValue);
layer.setProperties(propertyValue);
} |
java | public void overrideSetting(String name, float value) {
overrides.put(name, Float.toString(value));
} |
python | def get_post_reference_section_keyword_patterns():
"""Return a list of compiled regex patterns for keywords.
Keywords that can often be found after, and therefore suggest the end of
a reference section in a full-text document.
:return: (list) of compiled regex patterns.
"""
compiled_patterns =... |
java | protected void setAdditionalInfoToEventCallBackStruct(EventCallBackStruct callback_struct,
String device_name, String attribute, String event_name,
String[]filters, EventChannelStruct channel_struct) throws DevFailed{
String constraint_expr = buil... |
python | def get_sessionless_launch_url_for_external_tool_courses(self, course_id, assignment_id=None, id=None, launch_type=None, module_item_id=None, url=None):
"""
Get a sessionless launch url for an external tool.
Returns a sessionless launch url for an external tool.
NOTE: Eit... |
java | public void addPropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)
{
this.propertyChangeDelegate.addPropertyChangeListener(propertyName, listener);
} |
java | public static EntityGetOperation<AssetDeliveryPolicyInfo> get(String assetDeliveryPolicyId) {
return new DefaultGetOperation<AssetDeliveryPolicyInfo>(ENTITY_SET, assetDeliveryPolicyId,
AssetDeliveryPolicyInfo.class);
} |
java | @SuppressWarnings({ "unchecked", "rawtypes" })
public Map<String, List<String>> parameters() {
return (Map<String, List<String>>) (Map) parameters.asMap();
} |
java | public static String format(String format, int value) {
prec = 0;
point = false;
df = null;
analyse_format(format);
StringBuilder out = new StringBuilder();
if (df != null)
out.append(df.format(value));
else
out.append(value);
if... |
python | def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
if isinstance(self.input.payload, Instance):
inst = self.input.payload
data = Instances.template_instances(inst.datas... |
java | public static String join(Object[] objects, String separator)
{
return objects != null ? join(Arrays.asList(objects), separator) : null;
} |
java | private void paintCells(SeaGlassContext context, Graphics g, int rMin, int rMax, int cMin, int cMax) {
JTableHeader header = table.getTableHeader();
TableColumn draggedColumn = (header == null) ? null : header.getDraggedColumn();
TableColumnModel cm = table.getColumnModel();
... |
python | def snap(args):
"""
%prog snap species gffile fastafile
Train SNAP model given gffile and fastafile. Whole procedure taken from:
<http://gmod.org/wiki/MAKER_Tutorial_2012>
"""
p = OptionParser(snap.__doc__)
p.set_home("maker")
opts, args = p.parse_args(args)
if len(args) != 3:
... |
python | def format_info(info_list):
"""Turn a 2-dimension list of bytes into a 1-dimension list of bytes with
correct spacing"""
max_lengths = []
if info_list:
nr_columns = len(info_list[0])
else:
nr_columns = 0
for i in range(nr_columns):
max_lengths.append(max([len(info[i]) fo... |
python | def kill(self):
"Kill the daemon instance."
if self.pid:
try:
os.kill(self.pid, signal.SIGTERM)
# Raises an OSError for ESRCH when we've killed it.
while True:
os.kill(self.pid, signal.SIGTERM)
time.sleep... |
java | public void updateGroupMembers(long logIndex, Collection<Endpoint> members) {
assert committedGroupMembers == lastGroupMembers
: "Cannot update group members to: " + members + " at log index: " + logIndex + " because last group members: "
+ lastGroupMembers + " is different than ... |
java | private void createVersion(Node fileNode, InputStream inputStream, List<String> mixins) throws RepositoryException
{
if (!fileNode.isCheckedOut())
{
fileNode.checkout();
fileNode.getSession().save();
}
updateContent(fileNode, inputStream, mixins);
fileNode.... |
java | public synchronized void updateByteMetrics(long bytesWritten, int branchIndex) {
TaskMetrics metrics = TaskMetrics.get(this);
String forkBranchId = TaskMetrics.taskInstanceRemoved(this.taskId);
Counter taskByteCounter = metrics.getCounter(MetricGroup.TASK.name(), forkBranchId, BYTES);
long inc = bytesW... |
java | public static <T1, T2, T3, R> FluentFunctions.FluentTriFunction<T1, T2, T3, R> ofChecked(final CheckedTriFunction<T1, T2, T3, R> fn) {
return new FluentTriFunction<>(
softenTriFunction(fn));
} |
java | public int queryForInt(String sql) throws SQLException {
Number number = queryForObject(sql, Integer.class);
return (number != null ? number.intValue() : 0);
} |
java | protected void traverseJar(File file, TraversalState state) {
JarFile jar;
JarEntry entry;
Enumeration enm;
if (isLoggingEnabled())
getLogger().log(Level.INFO, "Analyzing jar: " + file);
if (!file.exists()) {
getLogger().log(Level.WARNING, "Jar does not exist: " + file);
retur... |
java | @SuppressWarnings("checkstyle:parameternumber")
private void calcChildrenRowIds(final List<RowIdWrapper> rows, final RowIdWrapper row,
final TableModel model,
final RowIdWrapper parent, final Set<?> expanded, final ExpandMode mode,
final boolean forUpdate, final boolean editable) {
// Add row
rows.add(row... |
python | def init(plugindirs=[]):
"""Initialize the plugin framework"""
# initialize the builtin plugins
from .translators import yang,yin,dsdl
yang.pyang_plugin_init()
yin.pyang_plugin_init()
dsdl.pyang_plugin_init()
# initialize installed plugins
for ep in pkg_resources.iter_entry_points(grou... |
java | public ResourceAssignment addResourceAssignment(Resource resource)
{
ResourceAssignment assignment = getExistingResourceAssignment(resource);
if (assignment == null)
{
assignment = new ResourceAssignment(getParentFile(), this);
m_assignments.add(assignment);
getParentFil... |
python | def _create_filters(col_params, extractors):
"""Creates filters for the given col_params.
Args:
col_params: List of ListSessionGroupsRequest.ColParam protobufs.
extractors: list of extractor functions of the same length as col_params.
Each element should extract the column described by the correspond... |
java | public byte[] toBytes() {
byte[] data = new byte[4];
data[0] = (byte) (packetBodyLength & 0xFF);
data[1] = (byte) (packetBodyLength >>> 8);
data[2] = (byte) (packetBodyLength >>> 16);
data[3] = getPacketSequenceNumber();
return data;
} |
python | def search(query, tld='com', lang='en', num=10, start=0, stop=None, pause=2.0,
only_standard=False):
"""
Search the given query string using Google.
@type query: str
@param query: Query string. Must NOT be url-encoded.
@type tld: str
@param tld: Top level domain.
@... |
python | def as_unordered(self, inplace=False):
"""
Set the Categorical to be unordered.
Parameters
----------
inplace : bool, default False
Whether or not to set the ordered attribute in-place or return
a copy of this categorical with ordered set to False.
... |
java | @Override
@Transactional(enabled = false)
public CommerceWarehouseItem createCommerceWarehouseItem(
long commerceWarehouseItemId) {
return commerceWarehouseItemPersistence.create(commerceWarehouseItemId);
} |
java | public Title getOutgoingLinks(int i) {
if (Descriptor_Type.featOkTst && ((Descriptor_Type)jcasType).casFeat_outgoingLinks == null)
jcasType.jcas.throwFeatMissing("outgoingLinks", "de.julielab.jules.types.wikipedia.Descriptor");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Descript... |
java | @SuppressWarnings("static-method")
protected ReferenceContext extractReferencableElements(String text) {
final ReferenceContext context = new ReferenceContext();
// Visit the links and record the transformations
final MutableDataSet options = new MutableDataSet();
final Parser parser = Parser.builder(options)... |
python | def on_put(self, req, resp, **kwargs):
"""Respond on PUT requests using ``self.update()`` handler."""
validated = self.require_validated(req)
return super().on_put(
req, resp,
handler=partial(self._update, validated=validated),
**kwargs
) |
python | def exp(x):
"""
Exponential function
"""
if isinstance(x, UncertainFunction):
mcpts = np.exp(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.exp(x) |
python | def clean(self, value):
"""clean a value, converting and performing bounds checking"""
if not isinstance(value, self.t):
value = self.t(value)
if not self.allow_negative and value < 0:
raise ValueError('value was negative')
if not self.allow_positive and value >... |
python | def dispatch_hook(cls, _pkt=None, *args, **kargs):
"""
If the TLS class was called on raw SSLv2 data, we want to return an
SSLv2 record instance. We acknowledge the risk of SSLv2 packets with a
msglen of 0x1403, 0x1503, 0x1603 or 0x1703 which will never be casted
as SSLv2 records... |
python | def mft_record_size(self):
"""
Returns:
int: MFT record size in bytes
"""
if self.extended_bpb.clusters_per_mft < 0:
return 2 ** abs(self.extended_bpb.clusters_per_mft)
else:
return self.clusters_per_mft * self.sectors_per_cluster * \
... |
java | @Override
public void runReport(Map<String, Object> extra) {
rows = new ArrayList<Map<String, Object>>(data != null ? data : new ArrayList<Map<String, Object>>());
if (parameterConfig != null)
{
for (final ParamConfig paramConfig : parameterConfig)
{
i... |
java | public void readCoordinate(int[] row, int[] column, double[] dataR,
double[] dataI) throws IOException {
int size = row.length;
if (size != column.length || size != dataR.length
|| size != dataI.length)
throw new IllegalArgumentException(
"All ... |
java | private static boolean isKeySupported(String key) {
if (Arrays.asList(SUPPORTED_KEYS).contains(key))
return true;
if (key.endsWith(URL_SUFFIX) || key.endsWith(APIKEY_SUFFIX) ||
key.endsWith(USER_SUFFIX) || key.endsWith(PWD_SUFFIX) || key.endsWith(USERPWD_SUFFIX))
retu... |
java | public static RawData nl2br(Object data) {
return new RawData(StringEscapeUtils.escapeHtml4(str(data)).replaceAll("(\\r\\n|\\n|\\r)", "<br/>"));
} |
python | def remove_last_match(self, address, size):
"""
Removes the last buffer from the watch object
to match the given address and size.
@type address: int
@param address: Memory address of buffer to stop watching.
@type size: int
@param size: Size in bytes of buffe... |
python | def init_pool(self):
"""Initialize multiprocessing pool if necessary."""
# initialize the pool if needed
if self.pool is None:
if self.nproc > 1:
self.pool = mp.Pool(processes=self.nproc)
else:
self.pool = None
else:
pr... |
java | static Map<String, BitSet> readCapabilities(File sysPath) {
Map<String, BitSet> capsMap = new HashMap<String, BitSet>();
File[] capsFiles = new File(sysPath, "device/capabilities").listFiles();
if (capsFiles == null) {
return capsMap;
}
for (int i = 0; i < capsFiles.l... |
java | public static HtmlTree IFRAME(String src, String name, String title) {
HtmlTree htmltree = new HtmlTree(HtmlTag.IFRAME);
htmltree.addAttr(HtmlAttr.SRC, nullCheck(src));
htmltree.addAttr(HtmlAttr.NAME, nullCheck(name));
htmltree.addAttr(HtmlAttr.TITLE, nullCheck(title));
return ht... |
java | private byte[] decrypt(byte[] in, int inOff, int inLen) {
// 获取曲线点
final byte[] c1 = new byte[this.curveLength * 2 + 1];
System.arraycopy(in, inOff, c1, 0, c1.length);
ECPoint c1P = this.ecParams.getCurve().decodePoint(c1);
if (c1P.multiply(this.ecParams.getH()).isInfinity()) {
throw new CryptoExce... |
python | def light_on(self, button: Button):
"""Turn the light on for the given Button.
NOTE! If yuo turn the "Off" button light on, the fader won't
report value updates when it's moved."""
self.outport.send(mido.Message('polytouch', note=button.light, value=1)) |
java | public static void skip(InputStream stream, long skip) throws IOException
{
long count = skip;
while (count > 0)
{
count -= stream.skip(count);
}
} |
python | def login(self, subject, authc_token):
"""
Login authenticates a user using an AuthenticationToken. If authentication is
successful AND the Authenticator has determined that authentication is
complete for the account, login constructs a Subject instance representing
the authenti... |
python | def codenerix(request):
'''
Codenerix CONTEXT
'''
# Get values
DEBUG = getattr(settings, 'DEBUG', False)
VERSION = getattr(settings, 'VERSION', _('WARNING: No version set to this code, add VERSION contant to your configuration'))
# Set environment
return {
'DEBUG': DEBUG,
... |
java | @Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MethodSymbol method = ASTHelpers.getSymbol(tree);
boolean checkReturn = hasDirectAnnotationWithSimpleName(method, CHECK_RETURN_VALUE);
boolean canIgnore = hasDirectAnnotationWithSimpleName(method, CAN_IGNORE_RETURN_VALUE);
... |
python | def Trho_iddeg(rho,mu,mu_e):
'''
T(rho) that separates ideal gas and degenerate pressure dominated regions.
Kippenhahn & Weigert, Eq. 16.6
Parameters
----------
rho : float
Density array [cgs].
mu : float
Mean molecular weight.
mu_e : float
Mean molecular weigh... |
python | def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Run tumor only smCounter2 calling.
"""
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and not paired.normal_bam, ("smCounter2 supports tumor-only variant calling: %s" %
... |
java | public static <A extends Result, B extends VisualizationItem> void findNewSiblings(VisualizerContext context, Object start, Class<? super A> type1, Class<? super B> type2, BiConsumer<A, B> handler) {
// Search start in first hierarchy:
final ResultHierarchy hier = context.getHierarchy();
final Hierarchy<Obj... |
java | private void compactAndRemove(final E[] buffer, final int mask, int removeHashIndex) {
// remove(9a): [9a,9b,10a,9c,10b,11a,null] -> [9b,9c,10a,10b,null,11a,null]
removeHashIndex = removeHashIndex & mask;
int j = removeHashIndex;
while(true) {
int k;
// skip eleme... |
java | public static <T> ChronoFormatter.Builder<T> setUp(
Chronology<T> chronology,
Locale locale
) {
return new Builder<>(chronology, locale);
} |
python | def pearson_C_calc(chi_square, POP):
"""
Calculate C (Pearson's C).
:param chi_square: chi squared
:type chi_square : float
:param POP: population
:type POP : int
:return: C as float
"""
try:
C = math.sqrt(chi_square / (POP + chi_square))
return C
except Exceptio... |
java | public PythonDataStream<SingleOutputStreamOperator<PyObject>> map(
MapFunction<PyObject, PyObject> mapper) throws IOException {
return new PythonSingleOutputStreamOperator(stream.map(new PythonMapFunction(mapper)));
} |
python | def get_coh_PTF_files(cp, ifos, run_dir, bank_veto=False, summary_files=False):
"""
Retrieve files needed to run coh_PTF jobs within a PyGRB workflow
Parameters
----------
cp : pycbc.workflow.configuration.WorkflowConfigParser object
The parsed configuration options of a pycbc.workflow.core.Wor... |
python | def _GetDirectory(self):
"""Retrieves a directory.
Returns:
APFSDirectory: directory or None if not available.
"""
if self._fsapfs_file_entry.number_of_sub_file_entries <= 0:
return None
return APFSDirectory(self._file_system, self.path_spec) |
java | public static void makeStringResponse(HttpResponse response, String s) {
StringEntity entity = new StringEntity(s, ContentType.TEXT_PLAIN);
entity.setContentEncoding("utf-8");
response.setEntity(entity);
} |
java | private byte[] readRequestBody() {
int bytesLeft = m_request.getContentLength();
if (bytesLeft <= 0) {
return new byte[0];
}
int totalBytesRead = 0;
try {
byte[] byteBuffer = new byte[bytesLeft];
try (InputStream inputStream = m_reque... |
java | public static Resources getBaseResources( String baseName, Locale locale, ClassLoader classLoader )
{
synchronized( ResourceManager.class )
{
Resources resources = getCachedResource( baseName + "_" + locale.hashCode() );
if( null == resources )
{
r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.