language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | protected double invCdfRootFinding(double p, double tol)
{
if (p < 0 || p > 1)
throw new ArithmeticException("Value of p must be in the range [0,1], not " + p);
//two special case checks, as they can cause a failure to get a positive and negative value on the ends, which means we can... |
python | def check_shapes(pfeed, *, as_df=False, include_warnings=False):
"""
Analog of :func:`check_frequencies` for ``pfeed.shapes``
"""
table = 'shapes'
problems = []
# Preliminary checks
if pfeed.shapes is None:
return problems
f = pfeed.shapes.copy()
problems = check_for_requir... |
java | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.severe("Binary content has been requested");
String repository = request.getParameter("repository");
String workspace = request.getParameter... |
java | public boolean isValidToken() {
try {
// Response response = wsBase.path(TEST_CONFIGS).request(MediaType.APPLICATION_JSON_TYPE).get();
// return response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL;
LoadZone zone = getLoadZone(LoadZone.AMAZON_US_ASHBURN.ui... |
python | def get_summary(self):
""" Return the function summary
Returns:
(str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries)
"""
func_summaries = [f.get_summary() for f in self.functions]
modif_summaries = [f.get_summary() for ... |
java | public void removeLine(final Line line)
{
if (line.previous == null)
{
this.lines = line.next;
}
else
{
line.previous.next = line.next;
}
if (line.next == null)
{
this.lineTail = line.previous;
}
else... |
python | def save(self, obj, data, is_m2m=False):
"""
If this field is not declared readonly, the object's attribute will
be set to the value returned by :meth:`~import_export.fields.Field.clean`.
"""
if not self.readonly:
attrs = self.attribute.split('__')
for att... |
java | static List<JQLPlaceHolder> removeDynamicPlaceHolder(List<JQLPlaceHolder> placeHolders) {
List<JQLPlaceHolder> result = new ArrayList<>();
for (JQLPlaceHolder item : placeHolders) {
if (item.type != JQLPlaceHolderType.DYNAMIC_SQL) {
result.add(item);
}
}
return result;
} |
java | public static Object createObject(String rawJSON) throws TwitterException {
try {
JSONObject json = new JSONObject(rawJSON);
JSONObjectType.Type jsonObjectType = JSONObjectType.determine(json);
switch (jsonObjectType) {
case SENDER:
return ... |
python | def process_messages_loop_internal(self):
"""
Busy loop that processes incoming WorkRequest messages via functions specified by add_command.
Terminates if a command runs shutdown method
"""
logging.info("Starting work queue loop.")
self.connection.receive_loop_with_callba... |
python | def request_motion_detection_enable(blink, network, camera_id):
"""
Enable motion detection for a camera.
:param blink: Blink instance.
:param network: Sync module network id.
:param camera_id: Camera ID of camera to enable.
"""
url = "{}/network/{}/camera/{}/enable".format(blink.urls.base_... |
java | public void run() {
boolean process = true;
synchronized(this) {
BlockEncodeRequest ber = manager.getWaitingRequest();
if(ber != null && ber.frameNumber < 0)
ber = null;
while(ber != null && process) {
if(ber.frameNumber < 0) {
process = false;
}
else... |
python | def fibre_channel_wwns():
'''
Return list of fiber channel HBA WWNs
'''
grains = {'fc_wwn': False}
if salt.utils.platform.is_linux():
grains['fc_wwn'] = _linux_wwns()
elif salt.utils.platform.is_windows():
grains['fc_wwn'] = _windows_wwns()
return grains |
java | public static void writeCollection(XMLOutput xmlOutput, Collection<? extends XMLWriteable> collection) throws IOException {
for (XMLWriteable obj : collection) {
obj.writeXML(xmlOutput);
}
} |
java | public static void createTables( Connection connection ) throws IOException, SQLException {
StringBuilder sB = new StringBuilder();
sB.append("CREATE TABLE ");
sB.append(TABLE_IMAGES);
sB.append(" (");
sB.append(ImageTableFields.COLUMN_ID.getFieldName());
sB.append(" INTE... |
java | public final void addItemStream(final ItemStream itemStream, long lockID, final Transaction transaction) throws MessageStoreException
{
// Defect 410652
// Check the transaction being used is from the same MessageStore as
// ours so that we don't get a mismatch and run the possibility of
... |
java | @Override
protected void checkPrimitiveValidity() {
BusPrimitiveInvalidity invalidityReason = null;
if (this.itineraries.isEmpty()) {
invalidityReason = new BusPrimitiveInvalidity(
BusPrimitiveInvalidityType.NO_ITINERARY_IN_LINE,
null);
} else {
final Iterator<BusItinerary> iterator = this.itiner... |
java | @Override public void set(FieldType field, Object value)
{
if (field != null)
{
int index = field.getValue();
if (m_eventsEnabled)
{
fireFieldChangeEvent((ResourceField) field, m_array[index], value);
}
m_array[index] = value;
}
} |
java | public void marshall(GetDomainNamesRequest getDomainNamesRequest, ProtocolMarshaller protocolMarshaller) {
if (getDomainNamesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getDomainNamesRe... |
python | def memoize(method):
"""A new method which acts like the given method but memoizes arguments
See https://en.wikipedia.org/wiki/Memoization for the general idea
>>> @memoize
... def test(arg):
... print('called')
... return arg + 1
>>> test(1)
called
2
>>> test(2)
cal... |
python | def statuses_destroy(self, id, trim_user=None):
"""
Destroys the status specified by the ID parameter.
https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
... |
java | public final void crc32(Register dst, Register src)
{
assert(dst.isRegType(REG_GPD) || dst.isRegType(REG_GPQ));
emitX86(INST_CRC32, dst, src);
} |
java | private void addDescendantElements() throws NodeSelectorException {
for (Node node : nodes) {
List<Node> nl;
if (node instanceof Document || node instanceof Element) {
nl = DOMHelper.getElementsByTagName(node, selector.getTagName());
} else {
t... |
python | def dtype(self):
"""Data-type of the array's elements.
Returns
-------
numpy.dtype
This NDArray's data type.
Examples
--------
>>> x = mx.nd.zeros((2,3))
>>> x.dtype
<type 'numpy.float32'>
>>> y = mx.nd.zeros((2,3), dtype='int... |
java | private void checkDescendantNames(Name name, boolean nameIsDefined) {
if (name.props != null) {
for (Name prop : name.props) {
// if the ancestor of a property is not defined, then we should emit
// warnings for all references to the property.
boolean propIsDefined = false;
if ... |
python | def get_zone_temperature(self, zone_name):
"""
Get the temperature for a zone
"""
zone = self.get_zone(zone_name)
if zone is None:
raise RuntimeError("Unknown zone")
return zone['currentTemperature'] |
java | public FactorEnrollmentResponse activateFactor(long userId, long deviceId) throws OAuthSystemException, OAuthProblemException, URISyntaxException
{
cleanError();
prepareToken();
URIBuilder url = new URIBuilder(settings.getURL(Constants.ACTIVATE_FACTOR_URL, userId, deviceId));
OneloginURLConnectionClien... |
java | @SuppressWarnings("checkstyle:magicnumber")
public TextStyle capacityMethodInvocation() {
final TextStyle textStyle = extensionMethodInvocation().copy();
//textStyle.setColor(new RGB(128, 36, 0));
textStyle.setStyle(SWT.ITALIC);
return textStyle;
} |
python | def predict(self, data, output_margin=False, ntree_limit=None, validate_features=True):
"""
Predict with `data`.
.. note:: This function is not thread safe.
For each booster object, predict can only be called from one thread.
If you want to run prediction using multiple thr... |
java | public final EObject ruleXAdditiveExpression() throws RecognitionException {
EObject current = null;
EObject this_XMultiplicativeExpression_0 = null;
EObject lv_rightOperand_3_0 = null;
enterRule();
try {
// InternalSARL.g:13044:2: ( (this_XMultiplicativeExpres... |
python | def send_mail(subject, message_plain, message_html, email_from, email_to,
custom_headers={}, attachments=()):
"""
Build the email as a multipart message containing
a multipart alternative for text (plain, HTML) plus
all the attached files.
"""
if not message_plain and not message_h... |
python | def add_custom_func(self, func, dim, *args, **kwargs):
""" adds a user defined function to extract features
Parameters
----------
func : function
a user-defined function, which accepts mdtraj.Trajectory object as
first parameter and as many optional and named arg... |
python | def component_doi(soup):
"""
Look for all object-id of pub-type-id = doi, these are the component DOI tags
"""
component_doi = []
object_id_tags = raw_parser.object_id(soup, pub_id_type = "doi")
# Get components too for later
component_list = components(soup)
position = 1
for tag... |
java | private static void checkLineFeed(final InputStream input,
final ByteArrayOutputStream baos, final Integer position)
throws IOException {
if (input.read() != '\n') {
throw new HttpException(
HttpURLConnection.HTTP_BAD_REQUEST,
String.format(
... |
java | protected PageContext getPageContext()
{
JspContext ctxt = getJspContext();
if (ctxt instanceof PageContext)
return (PageContext) ctxt;
// assert the page context and log an error in production
assert(false) : "The JspContext was not a PageContext";
logger.error(... |
python | def _serialiseFirstJob(self, jobStore):
"""
Serialises the root job. Returns the wrapping job.
:param toil.jobStores.abstractJobStore.AbstractJobStore jobStore:
"""
# Check if the workflow root is a checkpoint but not a leaf vertex.
# All other job vertices in the graph... |
java | public boolean isExpired() {
if (_service.getTtl() == 0) {
return false;
}
long t = this.cacheStartTime.getTime();
Date validTime = new Date(t + (_service.getTtl() * ONE_MINUTE_IN_MILLIS));
Date now = new Date();
return (now.getTime() > validTime.getTime());
} |
java | public final EObject ruleXAssignment() throws RecognitionException {
EObject current = null;
EObject lv_value_3_0 = null;
EObject this_XConditionalExpression_4 = null;
EObject lv_rightOperand_7_0 = null;
enterRule();
try {
// InternalPureXbase.g:653:2:... |
java | public final <R> R get(ChronoFunction<? super T, R> function) {
return function.apply(this.getContext());
} |
java | public static Fraction of(double value) {
final int sign = value < 0 ? -1 : 1;
value = Math.abs(value);
if (value > Integer.MAX_VALUE || Double.isNaN(value)) {
throw new ArithmeticException("The value must not be greater than Integer.MAX_VALUE or NaN");
}
final int wh... |
java | @Override
@SuppressWarnings("PMD.SystemPrintln")
int execute(OptionsAndArgs pOpts, Object pVm, VirtualMachineHandler pHandler) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
String agentUrl = checkAgentUrl(pVm);
boolean quiet = pOpts.isQuiet();
if (agen... |
python | def get(self, floating_ip_id):
"""Fetches the floating IP.
:returns: FloatingIp object corresponding to floating_ip_id
"""
fip = self.client.show_floatingip(floating_ip_id).get('floatingip')
self._set_instance_info(fip)
return FloatingIp(fip) |
java | public Class<?> findLoadedOrDefineClass(ClassLoader classLoader, String className, byte[] classbytes)
{
Class<?> klass = findLoadedClass(classLoader, className);
if (klass == null)
{
try
{
klass = defineClass(classLoader, className, classbytes);
... |
java | public void outputAnnotationIndex(PrintWriter writer) {
for (String ann : annotationIndex.keySet()) {
writer.print(ann);
writer.print(": ");
Set<String> classes = annotationIndex.get(ann);
Iterator<String> it = classes.iterator();
while (it.hasNext()) ... |
java | public void dereferenceControllable()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "dereferenceControllable");
destinationManager = null;
aliasDest = null;
index = null;
mpControl = null;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEn... |
java | public INDArray outputSingle(MultiDataSetIterator iterator){
Preconditions.checkArgument(numOutputArrays == 1, "Cannot use this method with nets that have more" +
" than 1 output array. This network has %s outputs", numOutputArrays);
return output(iterator)[0];
} |
python | def tempdir():
"""Creates a temporary directory"""
directory_path = tempfile.mkdtemp()
def clean_up(): # pylint: disable=missing-docstring
shutil.rmtree(directory_path, onerror=on_error)
with cd(directory_path, clean_up):
yield directory_path |
python | def successors(self):
"""Yield Compounds below self in the hierarchy.
Yields
-------
mb.Compound
The next Particle below self in the hierarchy
"""
if not self.children:
return
for part in self.children:
# Parts local to the cu... |
python | def find(self, node, path):
"""Wrapper for lxml`s find."""
return node.find(path, namespaces=self.namespaces) |
python | def renderFromWorkitem(self, copied_from, keep=False,
encoding="UTF-8", **kwargs):
"""Render the template directly from some to-be-copied
:class:`rtcclient.workitem.Workitem` without saving to a file
:param copied_from: the to-be-copied
:class:`rtcclient.w... |
python | def _from_dict(cls, _dict):
"""Initialize a SemanticRolesResultSubject object from a json dictionary."""
args = {}
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'entities' in _dict:
args['entities'] = [
SemanticRolesEntity._from_dict(x)
... |
java | public static Long toTimestamp(String dateStr, TimeZone tz) {
int length = dateStr.length();
String format;
if (length == 21) {
format = DEFAULT_DATETIME_FORMATS[1];
} else if (length == 22) {
format = DEFAULT_DATETIME_FORMATS[2];
} else if (length == 23) {
format = DEFAULT_DATETIME_FORMATS[3];
} e... |
python | def create_protocol(name, **kwargs):
"""
Returns an instance of the protocol with the given name.
:type name: str
:param name: The name of the protocol.
:rtype: Protocol
:return: An instance of the protocol.
"""
cls = protocol_map.get(name)
if not cls:
raise ValueError('Un... |
java | public Future<AuthenticationResult> acquireTokenByRefreshToken(
final String refreshToken, final ClientCredential credential,
final AuthenticationCallback callback) {
return acquireTokenByRefreshToken(refreshToken, credential,
(String) null, callback);
} |
java | public static float copySign(float magnitude, float sign) {
return Math.copySign(magnitude, (Float.isNaN(sign)?1.0f:sign));
} |
java | @Override
public void initialRecoveryFailed(RecoveryAgent recoveryAgent, FailureScope failureScope) throws InvalidFailureScopeException {
if (tc.isEntryEnabled())
Tr.entry(tc, "initialRecoveryFailed", new Object[] { recoveryAgent, failureScope, this });
final boolean removed = removeRec... |
java | public void addMessageListener(DigitalChannel channel, MessageListener<? extends Message> messageListener) {
addListener(channel.getIdentifier(), messageListener.getMessageType(), messageListener);
} |
python | def delete_framework(cls, framework=None):
# type: (Optional[Framework]) -> bool
# pylint: disable=W0212
"""
Removes the framework singleton
:return: True on success, else False
"""
if framework is None:
framework = cls.__singleton
if framewo... |
python | def TimestampToRDFDatetime(timestamp):
"""Converts MySQL `TIMESTAMP(6)` columns to datetime objects."""
# TODO(hanuszczak): `timestamp` should be of MySQL type `Decimal`. However,
# it is unclear where this type is actually defined and how to import it in
# order to have a type assertion.
if timestamp is None... |
java | public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args) {
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) {
throw new IllegalArgumentException("Could not find method [" + methodName + "] on tar... |
java | public static boolean isValidBuildMetaData(String buildMetaData) {
if (buildMetaData == null) {
return false;
} else if (buildMetaData.isEmpty()) {
return true;
}
return parseID(buildMetaData.toCharArray(), buildMetaData, 0, true, true, false,
nul... |
java | public static ns_detail_vlan[] get(nitro_service client) throws Exception
{
ns_detail_vlan resource = new ns_detail_vlan();
resource.validate("get");
return (ns_detail_vlan[]) resource.get_resources(client);
} |
java | public Flux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) {
Mono<PagedResponse<ConfigurationSetting>> result;
if (selector != null) {
String fields = getSelectQuery(selector.fields());
result = service.listKeyValueRevisions(serviceEndpoint, selector.key(), ... |
python | def _batch_iterator(self, N=1):
"""Returns N lists of records.
This can be used on any iterator, for example to batch up
SeqRecord objects from Bio.SeqIO.parse(...), or to batch
Alignment objects from Bio.AlignIO.parse(...), or simply
lines from a file handle.
This is a... |
python | def ensure_init(path):
'''
ensure directories leading up to path are importable, omitting
parent directory, eg path='/hooks/helpers/foo'/:
hooks/
hooks/helpers/__init__.py
hooks/helpers/foo/__init__.py
'''
for d, dirs, files in os.walk(os.path.join(*path.split('/')[:2])):
... |
java | private void initialize() {
// enables the options dialog to be in front, but an modal dialog
// stays on top of the main application window, but doesn't block childs
// Examples of childs: help window and client certificate viewer
this.setModalityType(ModalityType.DOCUMENT_MODAL);
... |
java | public List<UIComponent> getComponentResources(FacesContext context,
String target) {
if (target == null) {
throw new NullPointerException();
}
List<UIComponent> resources = getComponentResources(context,
... |
python | def compiler(name):
"""
Get a usable clang++ plumbum command.
This searches for a usable clang++ in the llvm binary path
Returns:
plumbum Command that executes clang++
"""
pinfo = __get_paths()
_compiler = local[name]
_compiler = _compiler.setenv(
PATH=pinfo["path"], LD... |
python | def get_instances(self):
"""
Returns a flat list of the names of services created
in this space.
"""
services = []
for resource in self._get_instances():
services.append(resource['entity']['name'])
return services |
java | void assertParent(Collection<Class<? extends Element>> permittedParents) throws InvalidInputException {
if (!permittedParents.contains(this.getParent().getClass())) {
throw new InvalidInputException("Element \"" + this.getMessageMLTag() + "\" is not allowed as a child of \""
+ this.getParent().getMe... |
java | public SparseDoubleVector getColumnVector(int column) {
checkIndices(0, column);
SparseDoubleVector columnValues =
new SparseHashDoubleVector(values.length);
columnValues.set(column, values[column]);
return columnValues;
} |
python | def start(nick, host, port=6667, username=None, password=None, channels=None, use_ssl=False, use_sasl=False,
char='!', allow_hosts=False, allow_nicks=False, disable_query=True):
'''
IRC Bot for interacting with salt.
nick
Nickname of the connected Bot.
host
irc server (exampl... |
python | def fs_cache(app_name='', cache_type='', idx=1,
expires=DEFAULT_EXPIRES, cache_dir='', helper_class=_FSCacher):
"""
A decorator to cache results of functions returning
pd.DataFrame or pd.Series objects under:
<cache_dir>/<app_name>/<cache_type>/<func_name>.<param_string>.csv,
missing pa... |
java | public String remainder() {
final String remainder = queue.substring(pos, queue.length());
pos = queue.length();
return remainder;
} |
java | public void putMany(final Iterable<A> items, final PipelineContext context) {
final Iterable<S> transforming = new TransformingIterable(items, context);
sink.putMany(storedType, transforming, context);
} |
python | def create(self, bucket, descriptor, force=False):
"""https://github.com/frictionlessdata/tableschema-bigquery-py#storage
"""
# Make lists
buckets = bucket
if isinstance(bucket, six.string_types):
buckets = [bucket]
descriptors = descriptor
if isinsta... |
python | def categories_for_actions(actions):
"""
Given an iterable of actions, return a mapping of action groups.
actions: {'ec2:authorizesecuritygroupingress', 'iam:putrolepolicy', 'iam:listroles'}
Returns:
{
'ec2': {'Write'},
'iam': {'Permissions', 'List'})
}
... |
java | private static int getType(int ch)
{
if (UCharacterUtility.isNonCharacter(ch)) {
// not a character we return a invalid category count
return NON_CHARACTER_;
}
int result = UCharacter.getType(ch);
if (result == UCharacterCategory.SURROGATE) {
if (c... |
java | public Expression asCheap() {
if (isCheap()) {
return this;
}
return new Expression(resultType, features.plus(Feature.CHEAP)) {
@Override
protected void doGen(CodeBuilder adapter) {
Expression.this.gen(adapter);
}
};
} |
java | public static Object applyEqualityOperator
(Object pLeft,
Object pRight,
EqualityOperator pOperator,
Logger pLogger)
throws ELException {
if (pLeft == pRight) {
return PrimitiveObjects.getBoolean(pOperator.apply(true, pLogger));
... |
python | def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID}) |
python | def mark_entities_to_export(self, export_config):
"""
Apply the specified :class:`meteorpi_model.ExportConfiguration` to the database, running its contained query and
creating rows in t_observationExport or t_fileExport for matching entities.
:param ExportConfiguration export_config:
... |
python | def class_balancing_sampler(y, indices):
"""
Construct a `WeightedSubsetSampler` that compensates for class
imbalance.
Parameters
----------
y: NumPy array, 1D dtype=int
sample classes, values must be 0 or positive
indices: NumPy array, 1D dtype=int
... |
java | @Override
protected Type getReturnType(final int mOp1, final int mOp2) throws TTXPathException {
Type type1;
Type type2;
try {
type1 = Type.getType(mOp1).getPrimitiveBaseType();
type2 = Type.getType(mOp2).getPrimitiveBaseType();
} catch (final IllegalStateExc... |
java | protected synchronized boolean cancel(Object x) {
// First check the expedited buffer
synchronized (lock) {
if (expeditedPutIndex > expeditedTakeIndex) {
for (int i = expeditedTakeIndex; i < expeditedPutIndex; i++) {
if (expeditedBuffer[i] == x) {
... |
python | def pformat(tree):
"""Recursively formats a tree into a nice string representation.
Example Input:
yahoo = tt.Tree(tt.Node("CEO"))
yahoo.root.add(tt.Node("Infra"))
yahoo.root[0].add(tt.Node("Boss"))
yahoo.root[0][0].add(tt.Node("Me"))
yahoo.root.add(tt.Node("Mobile"))
yahoo.root.a... |
python | def expand(string, vars, local_vars={}):
"""Expand a string containing $vars as Ninja would.
Note: doesn't handle the full Ninja variable syntax, but it's enough
to make configure.py's use of it work.
"""
def exp(m):
var = m.group(1)
if var == '$':
return '$'
ret... |
java | private RValue executeVariableAccess(Expr.VariableAccess expr, CallStack frame) {
Decl.Variable decl = expr.getVariableDeclaration();
return frame.getLocal(decl.getName());
} |
python | def pairwise(reference_intervals, reference_labels,
estimated_intervals, estimated_labels,
frame_size=0.1, beta=1.0):
"""Frame-clustering segmentation evaluation by pair-wise agreement.
Examples
--------
>>> (ref_intervals,
... ref_labels) = mir_eval.io.load_labeled_inter... |
python | def _execute_cell(args, cell_body):
"""Implements the BigQuery cell magic used to execute BQ queries.
The supported syntax is:
%%bigquery execute [-q|--sql <query identifier>] <other args>
[<YAML or JSON cell_body or inline SQL>]
Args:
args: the arguments following '%bigquery execute'.
cell_body:... |
python | def _contents_changed(self):
"""Activate submit_btn."""
desc_chars = (len(self.input_description.toPlainText()) -
self.initial_chars)
if desc_chars < DESC_MIN_CHARS:
self.desc_chars_label.setText(
u"{} {}".format(DESC_MIN_CHARS - desc_chars,
... |
python | def time_snowflake(datetime_obj, high=False):
"""Returns a numeric snowflake pretending to be created at the given date.
When using as the lower end of a range, use time_snowflake(high=False) - 1 to be inclusive, high=True to be exclusive
When using as the higher end of a range, use time_snowflake(high=Tru... |
python | def norm_score(self):
"""Return the normalized score.
Equals 1.0 for a z-score of 0, falling to 0.0 for extremely positive
or negative values.
"""
cdf = (1.0 + math.erf(self.score / math.sqrt(2.0))) / 2.0
return 1 - 2*math.fabs(0.5 - cdf) |
java | public static void assertEqualBeans(Object expected, Object actual) throws ComparisonFailure {
// Do *NOT* rely on expected/actual java.lang.Object.equals(Object);
// and obviously neither e.g. java.util.Objects.equals(Object, Object) based on. it
final String expectedAsText = generator.getExpre... |
python | def pvsyst_celltemp(self, poa_global, temp_air, wind_speed=1.0):
"""Uses :py:func:`pvsyst_celltemp` to calculate module temperatures
based on ``self.racking_model`` and the input parameters.
Parameters
----------
See pvsystem.pvsyst_celltemp for details
Returns
... |
python | def filter(self, data):
"""
Filters the dataset(s). When providing a list, this can be used to create compatible train/test sets,
since the filter only gets initialized with the first dataset and all subsequent datasets get transformed
using the same setup.
NB: inputformat(Insta... |
java | private Artifact getArtifactFromMavenCoordinates(final String artifact) throws MojoFailureException {
String[] parts = StringUtils.split(artifact, ":");
String version;
String packaging = null;
String classifier = null;
switch (parts.length) {
case 3:
// groupId:artifactId:version
... |
python | def import_json():
'''
Import a json module, starting with the quick ones and going down the list)
'''
for fast_json in ('ujson', 'yajl', 'json'):
try:
mod = __import__(fast_json)
log.trace('loaded %s json lib', fast_json)
return mod
except ImportError... |
java | private Page createPageWithExtractedDictionary(Page page)
{
Block[] blocks = new Block[page.getChannelCount()];
Block dictionary = ((DictionaryBlock) page.getBlock(channels[0])).getDictionary();
// extract data dictionary
blocks[channels[0]] = dictionary;
// extract hash di... |
java | @Override
protected boolean parseCmdLineArgs(String[] args) throws IllegalArgumentException {
if (action.equals(ACTION_HELP)) {
if (args.length == 0)
helpAction(null);
else
helpAction(args[0]);
return true;
}
if (action.e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.