language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public String eatId() {
if (!matchId())
throw new BadSyntaxException();
String s = tok.sval;
nextToken();
return s;
} |
java | public static String readTextFile(String fileName) {
try {
return readText(new FileInputStream(new File(fileName)));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
} |
java | public String isOn(final String command, final String target) {
LOG.info("Obtain result from | " + command + " | " + target + " |");
return is(command, new String[] { unalias(target) });
} |
java | public static final Number getZeroForClazz(Class<? extends Number> clazz) {
if (Double.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) {
// use doubleValue()
return Double.valueOf(0d);
} else {
return Long.valueOf(0l);
}
} |
java | public Observable<Page<RouteFilterInner>> listByResourceGroupNextAsync(final String nextPageLink) {
return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<RouteFilterInner>>, Page<RouteFilterInner>>() {
@Override
publi... |
python | def filepattern(self, *args, **kwargs):
"""Returns a list of filepatterns, one for each problem."""
return [p.filepattern(*args, **kwargs) for p in self.problems] |
java | public void setResponses(java.util.Collection<ItemResponse> responses) {
if (responses == null) {
this.responses = null;
return;
}
this.responses = new java.util.ArrayList<ItemResponse>(responses);
} |
python | def save(self, path):
"""
Save the file to the specified path
"""
# remember and restore file position
pos = self.tell()
self.seek(0)
with fopen(path, 'wb') as output:
output.truncate(self.length)
for chunk in iter(lambda: self.read(1024),... |
java | @Override
public InputStream getAttachment(final Asset asset, final Attachment attachment) throws IOException, BadVersionException, RequestFailureException {
// accept license for type CONTENT
HttpURLConnection connection;
if (attachment.getType() == AttachmentType.CONTENT) {
co... |
java | private static void dodgePostFixArraysInVarDeclarations(EcjTreePrinter printer) {
printer.skipReferenceTracking(LocalDeclaration.class, TypeReference.class);
printer.skipReferenceTracking(FieldDeclaration.class, TypeReference.class);
} |
java | public ServiceFuture<ServiceObjectiveInner> getAsync(String resourceGroupName, String serverName, String serviceObjectiveName, final ServiceCallback<ServiceObjectiveInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, serverName, serviceObjectiveName), servi... |
java | public static double[] getMinimumValues(Front front) {
if (front == null) {
throw new NullFrontException() ;
} else if (front.getNumberOfPoints() == 0) {
throw new EmptyFrontException() ;
}
int numberOfObjectives = front.getPoint(0).getDimension() ;
double[] minimumValue = new double[n... |
python | def get_area(self):
"""
:returns: The area of the polygon.
"""
if self.area is None:
self.area = self.to_2d().get_shapely().area
return self.area |
java | private String readEc2MetadataUrl(URL url, int connectionTimeoutMs, int readTimeoutMs) throws IOException {
if (url.getProtocol().equalsIgnoreCase("file")) {
url = rewriteUrl(url);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
try (... |
python | def load_writer(writer, ppp_config_dir=None, **writer_kwargs):
"""Find and load writer `writer` in the available configuration files."""
if ppp_config_dir is None:
ppp_config_dir = get_environ_config_dir()
config_fn = writer + ".yaml" if "." not in writer else writer
config_files = config_searc... |
java | public void join() {
try {
if (server != null) server.join();
if (aggregateDaemon != null) aggregateDaemon.join();
} catch (InterruptedException ie) {
// do nothing
}
} |
python | def delete_pre_shared_key(self, endpoint_name, **kwargs): # noqa: E501
"""Remove a pre-shared key. # noqa: E501
Remove a pre-shared key. **Example usage:** ``` curl -H \"authorization: Bearer ${API_TOKEN}\" -X DELETE https://api.us-east-1.mbedcloud.com/v2/device-shared-keys/my-endpoint-0001 ``` #... |
python | def instant_articles(self, **kwargs):
"""
QuerySet including all published content approved for instant articles.
Instant articles are configured via FeatureType. FeatureType.instant_article = True.
"""
eqs = self.search(**kwargs).sort('-last_modified', '-published')
ret... |
java | public static <In extends ImageBase<In>, Out extends ImageBase<Out>, K extends Kernel1D>
void horizontal(K kernel, In input, Out output ) {
switch (input.getImageType().getFamily()) {
case GRAY: {
if (input instanceof GrayF32) {
ConvolveImageNoBorder.horizontal((Kernel1D_F32) kernel, (GrayF32) input, (Gr... |
python | def __safe_handler_callback(self, handler, method_name, *args, **kwargs):
# type: (Any, str, *Any, **Any) -> Any
"""
Calls the given method with the given arguments in the given handler.
Logs exceptions, but doesn't propagate them.
Special arguments can be given in kwargs:
... |
java | private String getProcShortName() {
// could later be extended to some sort of fake numeric PID, e.g. "mysqld-1", from a static
// Map<String execName, Integer id)
if (procShortName == null) {
File exec = getExecutableFile();
procShortName = exec.getName();
}
... |
java | public static String readStream(InputStream stream, String encoding) throws IOException {
InputStreamReader isr = null;
StringBuilder sb = new StringBuilder();
try {
if (encoding == null) {
isr = new InputStreamReader(stream);
} else {
isr = new InputStreamReader(stream, encoding... |
java | public static String plus(CharSequence left, Object value) {
return left + DefaultGroovyMethods.toString(value);
} |
java | protected byte[] getBinaryData(Resource resource, @SuppressWarnings("unused") SlingHttpServletRequest request) throws IOException {
InputStream is = resource.adaptTo(InputStream.class);
if (is == null) {
return null;
}
try {
return IOUtils.toByteArray(is);
}
finally {
is.close(... |
python | def select_action(self, q_values):
"""Return the selected action
The selected action follows the BoltzmannQPolicy with probability epsilon
or return the Greedy Policy with probability (1 - epsilon)
# Arguments
q_values (np.ndarray): List of the estimations of Q for each acti... |
java | @Override
public EClass getIfcElectricMotor() {
if (ifcElectricMotorEClass == null) {
ifcElectricMotorEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(217);
}
return ifcElectricMotorEClass;
} |
python | def exclude_current_instance(self, queryset):
"""
If an instance is being updated, then do not include
that instance itself as a uniqueness conflict.
"""
if self.instance is not None:
return queryset.exclude(pk=self.instance.pk)
return queryset |
python | def popup(self, pos=None):
"""
Pops up this widget at the inputed position. The inputed point should \
be in global space.
:param pos | <QPoint>
:return <bool> success
"""
if self._first and self.centralWidget() is not None:
... |
python | def handle_comm_opened(comm, msg):
"""Static method, called when a widget is constructed."""
version = msg.get('metadata', {}).get('version', '')
if version.split('.')[0] != PROTOCOL_VERSION_MAJOR:
raise ValueError("Incompatible widget protocol versions: received version %r, expected... |
python | async def zip(*sources):
"""Combine and forward the elements of several asynchronous sequences.
Each generated value is a tuple of elements, using the same order as
their respective sources. The generation continues until the shortest
sequence is exhausted.
Note: the different sequences are awaite... |
python | def enostask(new=False):
"""Decorator for an Enos Task.
This decorator lets you define a new Enos task and helps you manage the
environment. It injects the environment in the function called.
Args:
new (bool): indicates if a new environment must be created.
Usually this is set on t... |
java | private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
timeTextField = new JTextField();
toggleTimeMenuButton = new JButton();
spinnerPanel = new JPanel();
increaseButton = new JButton();
decreaseButton = ne... |
java | private <T> T getEnvConfig(Map<String, ?> configs, String key, Class<T> type) {
if(configs.containsKey(key)) {
Object config = configs.get(key);
if(type.isAssignableFrom(config.getClass())) {
return type.cast(config);
}
}
return null;
} |
python | def define_mask_borders(image2d, sought_value, nadditional=0):
"""Generate mask avoiding undesired values at the borders.
Set to True image borders with values equal to 'sought_value'
Parameters
----------
image2d : numpy array
Initial 2D image.
sought_value : int, float, bool
... |
python | def handle_unhandled_exception(exc_type, exc_value, exc_traceback):
"""Handler for unhandled exceptions that will write to the logs"""
if issubclass(exc_type, KeyboardInterrupt):
# call the default excepthook saved at __excepthook__
sys.__excepthook__(exc_type, exc_value, exc_traceback)
... |
python | def reset_caches(self, **kwargs):
"""
Called by ``__init__()`` to initialise the caches for a helper instance.
It is also called by Django's ``setting_changed`` signal to clear the
caches when changes to settings are made.
Although it requires slightly more memory, separate dict... |
java | public static double norm_inf(double[] a) {
double max = Double.NEGATIVE_INFINITY;
for (double d : a) {
if (Math.abs(d) > max) {
max = Math.abs(d);
}
}
return max;
} |
python | def describe_load_balancers(names=None,
load_balancer_arns=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
Describes the specified load balancer or all of your ... |
java | public final DataHash getHash() {
if (outputHash == null) {
byte[] hash = messageDigest.digest();
outputHash = new DataHash(algorithm, hash);
}
return outputHash;
} |
java | private Map<String,Object> getSeverityMetrics(AppdynamicsApplication application, String instanceUrl ) {
long responseTimeSeverity = 0;
long errorRateSeverity = 0;
Map<String,Object> severityMetrics = new HashMap<>();
try {
// NUMBER OF VIOLATIONS
String url = ... |
python | def decay_indexpointer(self):
'''
This private method provides decay indexpointers which allow to
instantaneously decay an abundance vector. These are attributes
are.
Parameters
=================
decay_idp : list
points in the iso_to_plot (i.e. the undecayed abu... |
java | public static <T, X extends Throwable> Tuple3<CompletableFuture<Subscription>, Runnable, CompletableFuture<Boolean>> forEachX(
final Stream<T> stream, final long x, final Consumer<? super T> consumerElement) {
return forEachXEvents(stream, x, consumerElement, e -> {
} , () -> {
});
... |
python | def get_controller_state(self):
"""Returns the current state of the 3d mouse, a dictionary of pos, orn, grasp, and reset."""
dpos = self.control[:3] * 0.005
roll, pitch, yaw = self.control[3:] * 0.005
self.grasp = self.control_gripper
# convert RPY to an absolute orientation
... |
java | public static int getIndex(String[] arr, String str) {
if (arr == null || arr.length == 0 || str == null) {
return -1;
}
int len = arr.length;
for (int i = 0; i < len; i++) {
if (str.compareToIgnoreCase(arr[i]) == 0) {
return i;
}
}
return -1;
} |
java | public long get()
{
long now = CurrentTime.currentTime() / 1000;
long oldSequence;
long newSequence;
do {
oldSequence = _sequence.get();
long oldTime = oldSequence >>> _timeOffset;
if (oldTime != now) {
newSequence = ((now << _timeOffset)
... |
java | @Override
public Response register(String CorpNum, Statement statement, String UserID)
throws PopbillException {
String PostData = toJsonString(statement);
return httppost("/Statement", CorpNum, PostData, UserID, Response.class);
} |
python | def handle_previous(self, command):
"""
Method to generate item from a ItemForm. The form must be exposed on form attribute
@param command: a command tha expose data through form attributte
"""
self.result = command.items
self._to_commit = self.result |
java | protected boolean shouldBeRendered(FacesMessage message, UIMessagesBase uiMessagesBase) {
return (!message.isRendered() || uiMessagesBase.isRedisplay())
&& uiMessagesBase.getSeverity().contains(getSeverityName(message.getSeverity()));
} |
python | def policy_definitions_list(hide_builtin=False, **kwargs):
'''
.. versionadded:: 2019.2.0
List all policy definitions for a subscription.
:param hide_builtin: Boolean which will filter out BuiltIn policy definitions from the result.
CLI Example:
.. code-block:: bash
salt-call azurea... |
python | def _node_has_modifier(graph: BELGraph, node: BaseEntity, modifier: str) -> bool:
"""Return true if over any of a nodes edges, it has a given modifier.
Modifier can be one of:
- :data:`pybel.constants.ACTIVITY`,
- :data:`pybel.constants.DEGRADATION`
- :data:`pybel.constants.TRANSLOCATION`.
... |
java | public ListSecurityConfigurationsResult withSecurityConfigurations(SecurityConfigurationSummary... securityConfigurations) {
if (this.securityConfigurations == null) {
setSecurityConfigurations(new com.amazonaws.internal.SdkInternalList<SecurityConfigurationSummary>(securityConfigurations.length));
... |
java | public static DoubleMatrix gemm(double alpha, DoubleMatrix a,
DoubleMatrix b, double beta, DoubleMatrix c) {
NativeBlas.dgemm('N', 'N', c.rows, c.columns, a.columns, alpha, a.data, 0,
a.rows, b.data, 0, b.rows, beta, c.data, 0, c.rows);
return c;
} |
java | private static void throwAbstractMethodError(Code code, Method method,
Local<String> abstractMethodErrorMessage,
Local<AbstractMethodError> abstractMethodError) {
TypeId<AbstractMethodError> abstractMethodErrorClas... |
java | @Override
public <T> T asFacet(Class<T> facetType)
{
if (facetType == SpanProvider.class)
{
return facetType.cast(new SpanProviderFacet());
}
// TODO amzn/ion-java/issues/17 support seeking over InputStream
if (_input instanceof FromByteArray)
{
... |
java | private void showTooltip() {
Wrap tooltipLabel = new Wrap(toolTipWrapWidth);
tooltipLabel.setForeground(getForeground());
tooltipLabel.setFont(ToolTipButton.this.getFont());
tooltipLabel.setText(text);
JPanel panel = new JPanel();
panel.setBackground(toolTipBackground);
panel.setLayout(new ... |
java | static String getSubclassName(Object testObj) {
Class<?> testClass = testObj.getClass();
String testClassName = testClass.getSimpleName();
String testPackageName = testClass.getPackage().getName();
ReportsDirectory constant = ReportsDirectory.fromObject(testObj);
s... |
java | private int getAromaticNitrogensCount(IAtomContainer ac, IAtom atom) {
List<IAtom> neighbours = ac.getConnectedAtomsList(atom);
int narocounter = 0;
for (IAtom neighbour : neighbours) {
if (neighbour.getSymbol().equals("N") && (Boolean) neighbour.getProperty("IS_IN_AROMATIC_RING")) {... |
java | public void marshall(VTLDevice vTLDevice, ProtocolMarshaller protocolMarshaller) {
if (vTLDevice == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(vTLDevice.getVTLDeviceARN(), VTLDEVICEARN_BINDING);
... |
java | @Override
public synchronized RecordAlert write(int scanId, int pluginId, String alert,
int risk, int confidence, String description, String uri, String param, String attack,
String otherInfo, String solution, String reference, String evidence, int cweId, int wascId, int historyId,
... |
java | public String get(String key) {
try {
Field field;
field = this.getClass().getField(key);
return (String) field.get(this);
} catch(NoSuchFieldException e) {
return (String) antifraud_info.get(key);
} catch(IllegalAccessException e) {
re... |
java | private void calculateOffset(long currentTime, RestRequestResult result) {
// Double-checked locking for better performance
if ((api.getTimeOffset() != null) || (result == null) || (result.getResponse() == null)) {
return;
}
synchronized (api) {
if (api.getTimeOff... |
java | @Override
public CompletableFuture<Void> handleFailedProcess(final String oldHostId) {
log.info("Sweeping orphaned tasks for host {}", oldHostId);
return withRetriesAsync(() -> Futures.doWhileLoop(
() -> postRequest(oldHostId),
List::isEmpty, executor).whenCompleteAsy... |
python | def rephase_pmns_standard(Unu, UeL, UeR):
"""Function to rephase the lepton rotation matrices in order to
obtain the PMNS matrix in standard parametrization.
The input matrices are assumed to diagonalize the charged lepton and
neutrino mass matrices like
```
UeL.conj().T @ Me @ UeR = Me_diag
... |
java | private boolean isDomainExcludedFromProxy(String domainName) {
if (domainName == null || domainName.isEmpty()) {
return false;
}
for (DomainMatcher excludedDomain : proxyExcludedDomainsEnabled) {
if (excludedDomain.matches(domainName)) {
return tru... |
python | def use_astropy_helpers(**kwargs):
"""
Ensure that the `astropy_helpers` module is available and is importable.
This supports automatic submodule initialization if astropy_helpers is
included in a project as a git submodule, or will download it from PyPI if
necessary.
Parameters
----------
... |
python | def fixed_inputs(model, non_fixed_inputs, fix_routine='median', as_list=True, X_all=False):
"""
Convenience function for returning back fixed_inputs where the other inputs
are fixed using fix_routine
:param model: model
:type model: Model
:param non_fixed_inputs: dimensions of non fixed inputs
... |
java | public void setSuppressWarnings(Boolean value) throws CoreException
{
addBuilder(getProject(), ICoreConstants.BUILDER_ID, SUPRESS_WARNINGS_ARGUMENT_KEY, value.toString());
} |
java | @Nullable
public String getStaticContent() {
if (!hasValue()) {
return null;
}
HtmlAttributeValueNode attrValue = (HtmlAttributeValueNode) getChild(1);
if (attrValue.numChildren() == 0) {
return "";
}
if (attrValue.numChildren() > 1) {
return null;
}
StandaloneNode at... |
python | def _get_target_encoder(self, x, y):
"""Return a mapping from categories to average target values.
Args:
x (pandas.Series): a categorical column to encode.
y (pandas.Series): the target column
Returns:
target_encoder (dict): mapping from categories to average ... |
python | def _create_propose_txn(signer, setting_key_value):
"""Creates an individual sawtooth_settings transaction for the given
key and value.
"""
setting_key, setting_value = setting_key_value
nonce = hex(random.randint(0, 2**64))
proposal = SettingProposal(
setting=setting_key,
value=... |
python | def get_visitor(self, node):
"""Return the visitor function for this node or `None` if no visitor
exists for this node. In that case the generic visit function is
used instead.
"""
method = 'visit_' + node.__class__.__name__
return getattr(self, method, None) |
java | @Override
public ResourceSet<InstalledAddOnExtension> read(final TwilioRestClient client) {
return new ResourceSet<>(this, client, firstPage(client));
} |
java | public SDVariable var(@NonNull String name, @NonNull VariableType variableType, WeightInitScheme weightInitScheme,
org.nd4j.linalg.api.buffer.DataType dataType, long... shape) {
if (variables.containsKey(name) && variables.get(name).getVariable().getArr() != null)
throw ... |
python | def send_message(self, payload):
""" Create a post request to the message sender
"""
self.l.info("Creating outbound message request")
result = ms_client.create_outbound(payload)
self.l.info("Created outbound message request")
return result |
java | public static Command newQuery(String identifier,
String name,
Object[] arguments) {
return getCommandFactoryProvider().newQuery( identifier,
name,
... |
java | public DbxAccountInfo getAccountInfo()
throws DbxException
{
String host = this.host.getApi();
String apiPath = "1/account/info";
return doGet(host, apiPath, null, null, new DbxRequestUtil.ResponseHandler<DbxAccountInfo>() {
@Override
public DbxAccountInfo ha... |
java | public static int getSquaredMeasureSpec(final ViewGroup viewGroup, int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = View.MeasureSpec.getMode(widthMeasureSpec);
int widthSize = View.MeasureSpec.getSize(widthMeasureSpec);
int heightMode = View.MeasureSpec.getMode(heightMeasureSpec);
... |
java | public boolean checkIntensity( boolean insideDark , double threshold ) {
if( insideDark )
return averageOutside-averageInside >= threshold;
else
return averageInside-averageOutside >= threshold;
} |
python | def to_dict(self):
""" Transform an attribute to a dict
"""
data = {}
# mandatory characteristics
data["name"] = self.name
data["description"] = self.description if self.description and len(self.description) else None
data["type"] = self.type if self.type and len... |
python | def __choicebox(msg, title, choices):
"""
internal routine to support choicebox() and multchoicebox()
"""
global boxRoot, __choiceboxResults, choiceboxWidget, defaultText
global choiceboxWidget, choiceboxChoices
# -------------------------------------------------------------------
# If choic... |
java | public final void setServicePid(String servicePid) {
synchronized (lock) {
if (servicePid == null) {
serviceProperties.remove(SERVICE_PID);
} else {
serviceProperties.put(SERVICE_PID, servicePid);
}
if (serviceRegistration != null)... |
java | public static Collection<URI> list(URI uri) {
boolean isRepo = URIBuilder.REPO_SCHEME.equals(uri.getScheme());
Preconditions.checkArgument(isRepo, "Not a repository URI: " + uri);
DatasetRepository repo = Registration
.open(URI.create(uri.getRawSchemeSpecificPart()));
// build a URI for each da... |
python | def get_ddl(self, with_comments=True, if_not_exists=False):
"""
Get DDL SQL statement for the given table.
:param with_comments: append comment for table and each column
:return: DDL statement
"""
shard_num = self.shard.shard_num if self.shard is not None else None
... |
python | def publish_if_new(cls):
"""If the station map has changed, publish the new information."""
message = cls.make_message()
if message != cls.last_message:
super(DashboardPubSub, cls).publish(message)
cls.last_message = message |
python | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space derived from
residue-residue distances
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
-------
features ... |
java | public void registerType(Class<?> type) {
if (type == null) {
throw new NullPointerException("Cannot register null type class.");
}
TypeInformation<?> typeInfo = TypeExtractor.createTypeInfo(type);
if (typeInfo instanceof PojoTypeInfo) {
config.registerPojoType(type);
} else {
config.registerKryoTy... |
java | public boolean isValidBlock(int namespaceId, Block b, boolean checkSize)
throws IOException {
File f = null;
;
try {
f = getValidateBlockFile(namespaceId, b, checkSize);
} catch (IOException e) {
DataNode.LOG.warn("Block " + b + " is not valid:", e);
}
return ((f != null) ? is... |
java | private <X> void validate(Class<X> clazz, boolean isEmbeddable)
{
final String mappedSuperClazzErrMsg = "Class:" + clazz
+ "is annotated with @MappedSuperClass and @Entity not allowed";
final String embeddableClazzErrMsg = "Class:" + clazz + "is annotated with @Embeddable and @Entity... |
python | def expectation(self, prep_prog, operator_programs=None):
"""
Calculate the expectation value of operators given a state prepared by
prep_program.
:note: If the execution of ``quil_program`` is **non-deterministic**, i.e., if it includes
measurements and/or noisy quantum gat... |
java | @Override
protected void initializeImpl()
{
//get port name
this.portName=this.factoryConfigurationHolder.getConfigurationValue(FaxClientSpiConfigurationConstants.PORT_NAME_PROPERTY_KEY);
if(this.portName==null)
{
throw new FaxException("Port name not defined in fax4j... |
python | def pdf_result(pdf_binary: bytes,
extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None,
filename: str = None) -> WSGI_TUPLE_TYPE:
"""
Returns ``(contenttype, extraheaders, data)`` tuple for a PDF.
"""
extraheaders = extraheaders or []
if filename:
extraheaders.append... |
java | @SuppressWarnings("unchecked")
private void createInstanceUsingMOF(ManagedObjectFactory<?> ejbManagedObjectFactory) throws InvocationTargetException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "createInstanceUsingMO... |
java | public void execute() throws IOException
{
// Future todo: Use JNI and librsync library?
Runtime run = Runtime.getRuntime();
try
{
String command ;
if(excludeDir != null && !excludeDir.isEmpty())
{
command= "rsync -rv --delete --exclude "+ excludeDir + "... |
java | public double[] getMoneynessAsOffsets() {
DoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);
if(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {
moneyness = moneyness.map(new DoubleUnaryOperator() {
@Override
public double apply... |
python | def genXML(self):
"""
Return XML root
"""
# Check conditions
if self.filename is None or \
self.foldername is None or \
self.imgSize is None:
return None
top = Element('annotation')
if self.verified:
top... |
java | public void setTextureColor(final Color TEXTURE_COLOR) {
model.setTextureColor(TEXTURE_COLOR);
BACKGROUND_FACTORY.recreatePunchedSheetTexture(TEXTURE_COLOR);
reInitialize();
} |
python | def scale(val,
inlow=-1, inhigh=1,
outlow=1000, outhigh=2000):
'''Scale an in value in the range (inlow, inhigh) to the
range (outlow, outhigh).'''
return (
((float(val) - inlow) / (inhigh - inlow)) *
(outhigh - outlow) + outlow
) |
java | private synchronized void initQueryBuilder() throws IOException {
if (queryBuilder == null) {
indexReader = DirectoryReader.open(indexDirectory);
indexSearcher = new IndexSearcher(indexReader);
queryBuilder = new QueryBuilder(writer.getAnalyzer());
}
} |
python | def setup_logger(
base_name,
root_dir=None,
enable_json=True,
json_formatter='tipsi_tools.tipsi_logging.JSFormatter',
loggers={},
):
"""
json_formatter:
'fan.contrib.django.span_formatter.SpanFormatter' - add INSTALLATION_ID, SPAN and etc
"""
if not root_dir:
root_dir = o... |
python | def get_results():
"""Parse all search result pages."""
# store info in a dictionary {name -> shortname}
res = {}
session = requests.Session()
handle_url('http://www.gocomics.com/features', session, res)
handle_url('http://www.gocomics.com/explore/espanol', session, res)
handle_url('http://w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.