language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
|---|---|
python
|
def format_t_into_dhms_format(timestamp):
""" Convert an amount of second into day, hour, min and sec
:param timestamp: seconds
:type timestamp: int
:return: 'Ad Bh Cm Ds'
:rtype: str
>>> format_t_into_dhms_format(456189)
'5d 6h 43m 9s'
>>> format_t_into_dhms_format(3600)
'0d 1h 0m 0s'
"""
mins, timestamp = divmod(timestamp, 60)
hour, mins = divmod(mins, 60)
day, hour = divmod(hour, 24)
return '%sd %sh %sm %ss' % (day, hour, mins, timestamp)
|
java
|
public void marshall(GetLoadBalancerRequest getLoadBalancerRequest, ProtocolMarshaller protocolMarshaller) {
if (getLoadBalancerRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getLoadBalancerRequest.getLoadBalancerName(), LOADBALANCERNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
|
python
|
def qteRemoveKey(self, keysequence: QtmacsKeysequence):
"""
Remove ``keysequence`` from this key map.
|Args|
* ``keysequence`` (**QtmacsKeysequence**): key sequence to
remove from this key map.
|Returns|
**None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type.
"""
# Get a dedicated reference to self to facilitate traversing
# through the key map.
keyMap = self
# Keep a reference to the root element in the key map.
keyMapRef = keyMap
# Get the key sequence as a list of tuples, where each tuple
# contains the the control modifier and the key code, and both
# are specified as Qt constants.
keysequence = keysequence.toQtKeylist()
# ------------------------------------------------------------
# Remove the leaf element from the tree.
# ------------------------------------------------------------
for key in keysequence[:-1]:
# Quit if the key does not exist. This can happen if the
# user tries to remove a key that has never been
# registered.
if key not in keyMap:
return
# Go one level down in the key-map tree.
keyMap = keyMap[key]
# The specified key sequence does not exist if the leaf
# element (ie. last entry in the key sequence) is missing.
if keysequence[-1] not in keyMap:
return
else:
# Remove the leaf.
keyMap.pop(keysequence[-1])
# ------------------------------------------------------------
# Prune the prefix path defined by ``keysequence`` and remove
# all empty dictionaries. Start at the leaf level.
# ------------------------------------------------------------
# Drop the last element in the key sequence, because it was
# removed in the above code fragment already.
keysequence = keysequence[:-1]
# Now successively remove the key sequence in reverse order.
while(len(keysequence)):
# Start at the root and move to the last branch level
# before the leaf level.
keyMap = keyMapRef
for key in keysequence[:-1]:
keyMap = keyMap[key]
# If the leaf is a non-empty dictionary then another key
# with the same prefix still exists. In this case do
# nothing. However, if the leaf is now empty it must be
# removed.
if len(keyMap[key]):
return
else:
keyMap.pop(key)
|
python
|
def get_pipeline_inputs(job, input_flag, input_file):
"""
Get the input file from s3 or disk, untargz if necessary and then write to file job store.
:param job: job
:param str input_flag: The name of the flag
:param str input_file: The value passed in the config file
:return: The jobstore ID for the file
"""
work_dir = job.fileStore.getLocalTempDir()
job.fileStore.logToMaster('Obtaining file (%s) to the file job store' % os.path.basename(
input_file))
if input_file.startswith('http'):
assert input_file.startswith('https://s3'), input_file + ' is not an S3 file'
input_file = get_file_from_s3(job, input_file, write_to_jobstore=False)
elif input_file.startswith('S3'):
input_file = get_file_from_s3(job, input_file, write_to_jobstore=False)
else:
assert os.path.exists(input_file), 'Bogus Input : ' + input_file
# If the file isn't a tarball, then it is a single file that is tar.gzipped for the
# sake of maximum compression instead of enveloping a folder. Thus it should be
# decompressed before writing to job store. Also, this is cool but they will by
# default also be dumped into the cache!
if 'tar' not in input_flag:
input_file = untargz(input_file, work_dir)
return job.fileStore.writeGlobalFile(input_file)
|
java
|
public void setSnippetEnd(int v) {
if (Cooccurrence_Type.featOkTst && ((Cooccurrence_Type)jcasType).casFeat_snippetEnd == null)
jcasType.jcas.throwFeatMissing("snippetEnd", "ch.epfl.bbp.uima.types.Cooccurrence");
jcasType.ll_cas.ll_setIntValue(addr, ((Cooccurrence_Type)jcasType).casFeatCode_snippetEnd, v);}
|
python
|
def valid_kbreak_matchings(start_edges, result_edges):
""" A staticmethod check implementation that makes sure that degrees of vertices, that are affected by current :class:`KBreak`
By the notion of k-break, it shall keep the degree of vertices in :class:`bg.breakpoint_graph.BreakpointGraph` the same, after its application.
By utilizing the Counter class, such check is performed, as the number the vertex is mentioned corresponds to its degree.
:param start_edges: a list of pairs of vertices, that specifies where edges shall be removed by :class:`KBreak`
:type start_edges: ``list(tuple(vertex, vertex), ...)``
:param result_edges: a list of pairs of vertices, that specifies where edges shall be created by :class:`KBreak`
:type result_edges: ``list(tuple(vertex, vertex), ...)``
:return: a flag indicating if the degree of vertices are equal in start / result edges, targeted by :class:`KBreak`
:rtype: ``Boolean``
"""
start_stats = Counter(vertex for vertex_pair in start_edges for vertex in vertex_pair)
result_stats = Counter(vertex for vertex_pair in result_edges for vertex in vertex_pair)
return start_stats == result_stats
|
python
|
def enbw(wnd):
""" Equivalent Noise Bandwidth in bins (Processing Gain reciprocal). """
return sum(el ** 2 for el in wnd) / sum(wnd) ** 2 * len(wnd)
|
java
|
@Override
public Date parseTime(String input) throws ParseException {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "parseTime parsing [" + input + "]");
}
String data = input;
int i = data.indexOf(';', 0);
// PK20062 - check for excess data following the date value
if (-1 != i) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Ignoring excess data following semi-colon in date");
}
// strip off trailing whitespace before semi-colon
for (; i > 20; i--) {
char c = data.charAt(i - 1);
if (' ' != c && '\t' != c) {
break;
}
}
if (20 >= i) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Not enough data left to make a valid date");
}
throw new ParseException("Invalid date [" + input + "]", 0);
}
data = input.substring(0, i);
}
Date parsedDate = attemptParse(getFormat().get1123Parse(), data);
if (null == parsedDate) {
parsedDate = attemptParse(getFormat().get1036Parse(), data);
if (null == parsedDate) {
parsedDate = attemptParse(getFormat().getAsciiParse(), data);
if (null == parsedDate) {
parsedDate = attemptParse(getFormat().get2109Parse(), data);
if (null == parsedDate) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Time does not match supported formats");
}
throw new ParseException("Unparseable [" + data + "]", 0);
}
}
}
}
return parsedDate;
}
|
java
|
@SuppressWarnings("unchecked")
private static List<String> toList(Object object) {
List<String> list = new ArrayList<String>();
if (object == null || object == JSONObject.NULL) {
return null;
}
if (object instanceof List) {
return ((List<String>) object);
} else if (object instanceof JSONArray) {
for (int i = 0; i < ((JSONArray) object).length(); i++) {
try {
list.add(String.valueOf((((JSONArray) object).get(i))));
} catch (JSONException ex) {
//issue converting the list. return null
return null;
}
}
} else {
list.add(object.toString());
}
return list;
}
|
java
|
public OmdbBuilder setImdbId(final String imdbId) throws OMDBException {
if (StringUtils.isBlank(imdbId)) {
throw new OMDBException(ApiExceptionType.UNKNOWN_CAUSE, "Must provide an IMDB ID!");
}
params.add(Param.IMDB, imdbId);
return this;
}
|
java
|
void setTokenKind(int newKind) {
org.drools.constraint.parser.JavaToken token = (org.drools.constraint.parser.JavaToken)token();
token.setKind(newKind);
}
|
python
|
def _X_selected(X, selected):
"""Split X into selected features and other features"""
n_features = X.shape[1]
ind = np.arange(n_features)
sel = np.zeros(n_features, dtype=bool)
sel[np.asarray(selected)] = True
non_sel = np.logical_not(sel)
n_selected = np.sum(sel)
X_sel = X[:, ind[sel]]
X_not_sel = X[:, ind[non_sel]]
return X_sel, X_not_sel, n_selected, n_features
|
java
|
public void marshall(ServiceSetting serviceSetting, ProtocolMarshaller protocolMarshaller) {
if (serviceSetting == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(serviceSetting.getSettingId(), SETTINGID_BINDING);
protocolMarshaller.marshall(serviceSetting.getSettingValue(), SETTINGVALUE_BINDING);
protocolMarshaller.marshall(serviceSetting.getLastModifiedDate(), LASTMODIFIEDDATE_BINDING);
protocolMarshaller.marshall(serviceSetting.getLastModifiedUser(), LASTMODIFIEDUSER_BINDING);
protocolMarshaller.marshall(serviceSetting.getARN(), ARN_BINDING);
protocolMarshaller.marshall(serviceSetting.getStatus(), STATUS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
|
python
|
def get_depth2goobjs(go2obj, max_depth=2):
"""Init depth2goobjs using list sorted by depth, get level-00/01 GO terms."""
depth2goobjs = {d:list() for d in range(max_depth+1)}
goid_seen = set()
for _, goobj in sorted(go2obj.items(), key=lambda t: t[1].depth):
# Save depth-00, depth-01, depth-02
if goobj.depth > max_depth:
break
goid = goobj.id
if not goobj.is_obsolete and goid not in goid_seen:
depth2goobjs[goobj.depth].append(goobj)
goid_seen.add(goid)
return depth2goobjs
|
java
|
public boolean addContentFontFaceContainerStyle(final FontFaceContainerStyle ffcStyle) {
final FontFace fontFace = ffcStyle.getFontFace();
if (fontFace != null) {
this.fontFaces.add(fontFace);
}
return this.addContentStyle(ffcStyle);
}
|
java
|
public static ObjectMapper buildObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new StdDateFormat());
objectMapper.setPropertyNamingStrategy(new PropertyNamingStrategy.SnakeCaseStrategy());
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
configureCredentialDetailTypeMapping(objectMapper);
return objectMapper;
}
|
java
|
private static <A> ProgramChromosome<A> create(
final Tree<? extends Op<A>, ?> program,
final Predicate<? super ProgramChromosome<A>> validator,
final ISeq<? extends Op<A>> operations,
final ISeq<? extends Op<A>> terminals
) {
final ISeq<ProgramGene<A>> genes = FlatTreeNode.of(program).stream()
.map(n -> new ProgramGene<>(
n.getValue(), n.childOffset(), operations, terminals))
.collect(ISeq.toISeq());
return new ProgramChromosome<>(genes, validator, operations, terminals);
}
|
java
|
private void runInternal(IMarker marker) throws CoreException {
Assert.isNotNull(marker);
PendingRewrite pending = resolveWithoutWriting(marker);
if(pending == null){
return;
}
try {
IRegion region = completeRewrite(pending);
if(region == null){
return;
}
IEditorPart part = EditorUtility.isOpenInEditor(pending.originalUnit);
if (part instanceof ITextEditor) {
((ITextEditor) part).selectAndReveal(region.getOffset(), region.getLength());
}
} finally {
pending.originalUnit.discardWorkingCopy();
}
}
|
java
|
@SuppressWarnings({"unused", "WeakerAccess"})
public void recordScreen(String screenName){
if(screenName == null || (!currentScreenName.isEmpty() && currentScreenName.equals(screenName))) return;
getConfigLogger().debug(getAccountId(), "Screen changed to " + screenName);
currentScreenName = screenName;
recordPageEventWithExtras(null);
}
|
python
|
def listify(val, return_type=tuple):
"""
Examples:
>>> listify('abc', return_type=list)
['abc']
>>> listify(None)
()
>>> listify(False)
(False,)
>>> listify(('a', 'b', 'c'), return_type=list)
['a', 'b', 'c']
"""
# TODO: flatlistify((1, 2, 3), 4, (5, 6, 7))
if val is None:
return return_type()
elif isiterable(val):
return return_type(val)
else:
return return_type((val, ))
|
python
|
def security(policy, app_secret):
"""
Creates a valid signature and policy based on provided app secret and
parameters
```python
from filestack import Client, security
# a policy requires at least an expiry
policy = {'expiry': 56589012, 'call': ['read', 'store', 'pick']}
sec = security(policy, 'APP_SECRET')
client = Client('API_KEY', security=sec)
```
"""
validate(policy)
policy_enc = base64.urlsafe_b64encode(json.dumps(policy).encode('utf-8'))
signature = hmac.new(app_secret.encode('utf-8'),
policy_enc,
hashlib.sha256).hexdigest()
return {'policy': policy_enc, 'signature': signature}
|
java
|
static void modifyProfiles(File destination, Map<String, Profile> modifications) {
final boolean inPlaceModify = destination.exists();
File stashLocation = null;
// Stash the original file, before we apply the changes
if (inPlaceModify) {
boolean stashed = false;
try {
// We can't use File.createTempFile, since it will always create
// that file no matter what, and File.reNameTo does not allow
// the destination to be an existing file
stashLocation = new File(destination.getParentFile(),
destination.getName() + ".bak."
+ UUID.randomUUID().toString());
stashed = destination.renameTo(stashLocation);
if (LOG.isDebugEnabled()) {
LOG.debug(String
.format("The original credentials file is stashed to loaction (%s).",
stashLocation.getAbsolutePath()));
}
} finally {
if (!stashed) {
throw new SdkClientException(
"Failed to stash the existing credentials file " +
"before applying the changes.");
}
}
}
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(destination), StringUtils.UTF8);
ProfilesConfigFileWriterHelper writerHelper = new ProfilesConfigFileWriterHelper(writer, modifications);
if (inPlaceModify) {
Scanner existingContent = new Scanner(stashLocation, StringUtils.UTF8.name());
writerHelper.writeWithExistingContent(existingContent);
} else {
writerHelper.writeWithoutExistingContent();
}
// Make sure the output is valid and can be loaded by the loader
new ProfilesConfigFile(destination);
if ( inPlaceModify && !stashLocation.delete() ) {
if (LOG.isDebugEnabled()) {
LOG.debug(String
.format("Successfully modified the credentials file. But failed to " +
"delete the stashed copy of the original file (%s).",
stashLocation.getAbsolutePath()));
}
}
} catch (Exception e) {
// Restore the stashed file
if (inPlaceModify) {
boolean restored = false;
try {
// We don't really care about what destination.delete()
// returns, since the file might not have been created when
// the error occurred.
if ( !destination.delete() ) {
LOG.debug("Unable to remove the credentials file "
+ "before restoring the original one.");
}
restored = stashLocation.renameTo(destination);
} finally {
if (!restored) {
throw new SdkClientException(
"Unable to restore the original credentials file. " +
"File content stashed in " + stashLocation.getAbsolutePath());
}
}
}
throw new SdkClientException(
"Unable to modify the credentials file. " +
"(The original file has been restored.)",
e);
} finally {
try {
if (writer != null) writer.close();
} catch (IOException e) {}
}
}
|
python
|
def cli_print(msg, color='', end=None, file=sys.stdout, logger=_LOG):
"""Print the message to file and also log it.
This function is intended as a 'tee' mechanism to enable the CLI interface as
a first-class citizen, while ensuring that everything the operator sees also
has an analogous logging entry in the test record for later inspection.
Args:
msg: The message to print/log.
color: Optional colorama color string to be applied to the message. You can
concatenate colorama color strings together in order to get any set of
effects you want.
end: A custom line-ending string to print instead of newline.
file: A file object to which the baracketed text will be written. Intended
for use with CLI output file objects like sys.stdout.
logger: A logger to use, or None to disable logging.
"""
if logger:
logger.debug('-> {}'.format(msg))
if CLI_QUIET:
return
if end is None:
end = _linesep_for_file(file)
file.write('{color}{msg}{reset}{end}'.format(
color=color, msg=msg, reset=colorama.Style.RESET_ALL, end=end))
|
java
|
protected SQLException markPossiblyBroken(SQLException e) {
String state = e.getSQLState();
boolean alreadyDestroyed = false;
ConnectionState connectionState = this.getConnectionHook() != null ? this.getConnectionHook().onMarkPossiblyBroken(this, state, e) : ConnectionState.NOP;
if (state == null){ // safety;
state = "08999";
}
if (((sqlStateDBFailureCodes.contains(state) || connectionState.equals(ConnectionState.TERMINATE_ALL_CONNECTIONS)) && this.pool != null) && this.pool.getDbIsDown().compareAndSet(false, true) ){
logger.error("Database access problem. Killing off this connection and all remaining connections in the connection pool. SQL State = " + state);
this.pool.connectionStrategy.terminateAllConnections();
this.pool.destroyConnection(this);
this.logicallyClosed.set(true);
alreadyDestroyed = true;
for (int i=0; i < this.pool.partitionCount; i++) {
// send a signal to try re-populating again.
this.pool.partitions[i].getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important.
}
}
//case where either the connection is closed or
//two concurrent connections loose connections with
//the 08S01 code but one one is killed in the code
//above give dbIsDown is set for the first connection
if (state.equals("08003") || sqlStateDBFailureCodes.contains(state) || e.getCause() instanceof SocketException) {
if (!alreadyDestroyed) {
this.pool.destroyConnection(this);
this.logicallyClosed.set(true);
getOriginatingPartition().getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important.
}
}
// SQL-92 says:
// Class values that begin with one of the <digit>s '5', '6', '7',
// '8', or '9' or one of the <simple Latin upper case letter>s 'I',
// 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
// 'W', 'X', 'Y', or 'Z' are reserved for implementation-specified
// conditions.
// FIXME: We should look into this.connection.getMetaData().getSQLStateType();
// to determine if we have SQL:92 or X/OPEN sqlstatus codes.
// char firstChar = state.charAt(0);
// if it's a communication exception, a mysql deadlock or an implementation-specific error code, flag this connection as being potentially broken.
// state == 40001 is mysql specific triggered when a deadlock is detected
// state == HY000 is firebird specific triggered when a connection is broken
char firstChar = state.charAt(0);
if (connectionState.equals(ConnectionState.CONNECTION_POSSIBLY_BROKEN) || state.equals("40001") ||
state.equals("HY000") ||
state.startsWith("08") || (firstChar >= '5' && firstChar <='9') /*|| (firstChar >='I' && firstChar <= 'Z')*/){
this.possiblyBroken = true;
}
// Notify anyone who's interested
if (this.possiblyBroken && (this.getConnectionHook() != null)){
this.possiblyBroken = this.getConnectionHook().onConnectionException(this, state, e);
}
return e;
}
|
java
|
private void initRandom() {
try {
random = new SecureRandom();
} catch (Exception e) {
log.warn("Could not generate SecureRandom for session-id randomness", e);
random = new Random();
weakRandom = true;
}
}
|
python
|
def GetAncestors(self):
"""Yields all ancestors of a path.
The ancestors are returned in order from closest to the farthest one.
Yields:
Instances of `rdf_objects.PathInfo`.
"""
current = self
while True:
current = current.GetParent()
if current is None:
return
yield current
|
java
|
@Override
public ListUserHierarchyGroupsResult listUserHierarchyGroups(ListUserHierarchyGroupsRequest request) {
request = beforeClientExecution(request);
return executeListUserHierarchyGroups(request);
}
|
java
|
private static void stitchChunks(Configuration conf, JobConf jobConf,
final Arguments args) throws IOException {
//check if the file system is the dfs
FileSystem dstfs = args.dst.getFileSystem(conf);
DistributedFileSystem dstdistfs = DFSUtil.convertToDFS(dstfs);
if(dstdistfs == null) {
throw new IOException("No distributed file system found!");
}
else {
int totfiles = jobConf.getInt(SRC_COUNT_LABEL, -1);
String dstChunkFileDirList = jobConf.get(DST_CHUNK_FILE_LIST_LABEL);
if ( "".equals(dstChunkFileDirList)) {
throw new RuntimeException("Invalid chunk file dir list (" +
dstChunkFileDirList + ")");
}
Path dstPath = args.dst;
Path tmpPath = new Path(jobConf.get(TMP_DIR_LABEL));
SequenceFile.Reader in = null;
try {
in = new SequenceFile.Reader(
new Path(dstChunkFileDirList).getFileSystem(jobConf),
new Path(dstChunkFileDirList), jobConf);
IntWritable chunkNum = new IntWritable();
Text dstFilePathText = new Text();
while (in.next(chunkNum, dstFilePathText)) {
stitchChunkFile(conf, jobConf, dstdistfs, dstFilePathText.toString(),
chunkNum.get(), dstPath, tmpPath, totfiles);
}
}
finally{
checkAndClose(in);
}
}
}
|
java
|
private void parsePlurals(JsonObject root, String type, Map<String, PluralData> map) {
JsonObject node = resolve(root, "supplemental", type);
for (Map.Entry<String, JsonElement> entry : node.entrySet()) {
String language = entry.getKey();
PluralData data = new PluralData();
for (Map.Entry<String, JsonElement> ruleNode : entry.getValue().getAsJsonObject().entrySet()) {
String category = ruleNode.getKey().replaceFirst("^pluralRule-count-", "");
String value = ruleNode.getValue().getAsString();
Maybe<Pair<Node<PluralType>, CharSequence>> result = PluralRuleGrammar.parse(value);
if (result.isNothing()) {
throw new IllegalArgumentException(format("failed to parse rule: \"%s\"", StringEscapeUtils.escapeJava(value)));
}
Struct<PluralType> rule = result.get()._1.asStruct();
Node<PluralType> conditionNode = findChild(rule, PluralType.OR_CONDITION);
Node<PluralType> sampleNode = findChild(rule, PluralType.SAMPLE);
String sample = sampleNode == null ? "" : (String) sampleNode.asAtom().value();
data.add(category, new PluralData.Rule(value, conditionNode, sample));
}
map.put(language, data);
}
}
|
java
|
@Override
public void infoSeeFromEast(ControllerPlayer c, double distance, double direction, double distChange,
double dirChange, double bodyFacingDirection, double headFacingDirection) {
switch (qualifier) {
case 'l' :
switch (number) {
case 50 :
c.infoSeeFlagLeft(Flag.OTHER_50, distance, direction, distChange, dirChange,
bodyFacingDirection, headFacingDirection);
break;
case 40 :
c.infoSeeFlagLeft(Flag.OTHER_40, distance, direction, distChange, dirChange,
bodyFacingDirection, headFacingDirection);
break;
case 30 :
c.infoSeeFlagLeft(Flag.OTHER_30, distance, direction, distChange, dirChange,
bodyFacingDirection, headFacingDirection);
break;
case 20 :
c.infoSeeFlagLeft(Flag.OTHER_20, distance, direction, distChange, dirChange,
bodyFacingDirection, headFacingDirection);
break;
case 10 :
c.infoSeeFlagLeft(Flag.OTHER_10, distance, direction, distChange, dirChange,
bodyFacingDirection, headFacingDirection);
break;
}
;
break;
case 'r' :
switch (number) {
case 50 :
c.infoSeeFlagLeft(Flag.OWN_50, distance, direction, distChange, dirChange, bodyFacingDirection,
headFacingDirection);
break;
case 40 :
c.infoSeeFlagLeft(Flag.OWN_40, distance, direction, distChange, dirChange, bodyFacingDirection,
headFacingDirection);
break;
case 30 :
c.infoSeeFlagLeft(Flag.OWN_30, distance, direction, distChange, dirChange, bodyFacingDirection,
headFacingDirection);
break;
case 20 :
c.infoSeeFlagLeft(Flag.OWN_20, distance, direction, distChange, dirChange, bodyFacingDirection,
headFacingDirection);
break;
case 10 :
c.infoSeeFlagLeft(Flag.OWN_10, distance, direction, distChange, dirChange, bodyFacingDirection,
headFacingDirection);
break;
}
;
break;
case '0' :
c.infoSeeFlagLeft(Flag.CENTER, distance, direction, distChange, dirChange, bodyFacingDirection,
headFacingDirection);
break;
}
}
|
java
|
public static <T, R, E extends Throwable> @NonNull Function<T, R> unwrappingRethrowFunction(final @NonNull ThrowingFunction<T, R, E> function) {
return input -> {
try {
return function.throwingApply(input);
} catch(final Throwable t) {
throw rethrow(unwrap(t));
}
};
}
|
java
|
public void write(RowOutputInterface out) {
out.writeSize(storageSize);
out.writeData(rowData, tTable.colTypes);
out.writeEnd();
hasDataChanged = false;
}
|
python
|
def dict2pb(cls, adict, strict=False):
"""
Takes a class representing the ProtoBuf Message and fills it with data from
the dict.
"""
obj = cls()
for field in obj.DESCRIPTOR.fields:
if not field.label == field.LABEL_REQUIRED:
continue
if not field.has_default_value:
continue
if not field.name in adict:
raise ConvertException('Field "%s" missing from descriptor dictionary.'
% field.name)
field_names = set([field.name for field in obj.DESCRIPTOR.fields])
if strict:
for key in adict.keys():
if key not in field_names:
raise ConvertException(
'Key "%s" can not be mapped to field in %s class.'
% (key, type(obj)))
for field in obj.DESCRIPTOR.fields:
if not field.name in adict:
continue
msg_type = field.message_type
if field.label == FD.LABEL_REPEATED:
if field.type == FD.TYPE_MESSAGE:
for sub_dict in adict[field.name]:
item = getattr(obj, field.name).add()
item.CopyFrom(dict2pb(msg_type._concrete_class, sub_dict))
else:
# fix python3 map用法变更
list(map(getattr(obj, field.name).append, adict[field.name]))
else:
if field.type == FD.TYPE_MESSAGE:
value = dict2pb(msg_type._concrete_class, adict[field.name])
getattr(obj, field.name).CopyFrom(value)
elif field.type in [FD.TYPE_UINT64, FD.TYPE_INT64, FD.TYPE_SINT64]:
setattr(obj, field.name, int(adict[field.name]))
else:
setattr(obj, field.name, adict[field.name])
return obj
|
python
|
def norm_zero_one(array, dim=None):
"""
normalizes a numpy array from 0 to 1 based in its extent
Args:
array (ndarray):
dim (int):
Returns:
ndarray:
CommandLine:
python -m utool.util_alg --test-norm_zero_one
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utool as ut
>>> array = np.array([ 22, 1, 3, 2, 10, 42, ])
>>> dim = None
>>> array_norm = norm_zero_one(array, dim)
>>> result = ut.repr2(list(array_norm), precision=3)
>>> print(result)
[0.512, 0.000, 0.049, 0.024, 0.220, 1.000]
"""
if not util_type.is_float(array):
array = array.astype(np.float32)
array_max = array.max(dim)
array_min = array.min(dim)
array_exnt = np.subtract(array_max, array_min)
array_norm = np.divide(np.subtract(array, array_min), array_exnt)
return array_norm
|
java
|
@Override
public ListAliasesResult listAliases(ListAliasesRequest request) {
request = beforeClientExecution(request);
return executeListAliases(request);
}
|
python
|
def new_cbuf(self, input, null_if_empty=True):
"""
Converts the input into a raw C buffer
:param input: The input
:param null_if_empty: If the input is empty
:return: A tuple of buffer,length
"""
if not isinstance(input, bytes) and input:
input = input.encode('utf-8')
if not input and null_if_empty:
return self._ffi.NULL, 0
cbuf = self._ffi.new('char[]', input)
self._bufs.append(cbuf)
return cbuf, len(input)
|
java
|
public void shutdown() {
logger.warn("Shutting down FlowRunnerManager...");
if (this.azkabanProps.getBoolean(ConfigurationKeys.AZKABAN_POLL_MODEL, false)) {
this.pollingService.shutdown();
}
this.executorService.shutdown();
boolean result = false;
while (!result) {
logger.info("Awaiting Shutdown. # of executing flows: " + getNumRunningFlows());
try {
result = this.executorService.awaitTermination(1, TimeUnit.MINUTES);
} catch (final InterruptedException e) {
logger.error(e);
}
}
logger.warn("Shutdown FlowRunnerManager complete.");
}
|
python
|
def _matching_pattern_sets(self):
"""Returns an iterator containing all PatternSets that match this
directory.
This is build by chaining the this-directory specific PatternSet
(self.matched_and_subdir), the local (non-inheriting) PatternSet
(self.matched_no_subdir) with all the inherited PatternSets
that match this directory and all its parents (self.match_inherit)."""
gather = []
if self.matched_and_subdir:
gather.append(self.matched_and_subdir.iter())
gather.append(self.matched_no_subdir.iter())
ref = self
while ref is not None:
if ref.matched_inherit:
gather.append(ref.matched_inherit.iter())
if ref.parent_has_patterns:
ref = ref.parent
else:
ref = None
return chain.from_iterable(gather)
|
java
|
@Override
public StandardJavaFileManager getStandardFileManager(
DiagnosticListener<? super JavaFileObject> diagnosticListener,
Locale locale,
Charset charset) {
Context context = new Context();
context.put(Locale.class, locale);
if (diagnosticListener != null)
context.put(DiagnosticListener.class, diagnosticListener);
PrintWriter pw = (charset == null)
? new PrintWriter(System.err, true)
: new PrintWriter(new OutputStreamWriter(System.err, charset), true);
context.put(Log.outKey, pw);
return new JavacFileManager(context, true, charset);
}
|
python
|
def aesthetics(cls):
"""
Return a set of all non-computed aesthetics for this stat.
stats should not override this method.
"""
aesthetics = cls.REQUIRED_AES.copy()
calculated = get_calculated_aes(cls.DEFAULT_AES)
for ae in set(cls.DEFAULT_AES) - set(calculated):
aesthetics.add(ae)
return aesthetics
|
java
|
NameWithINode getSourceFile(String parity, String prefix) throws IOException {
if (isHarFile(parity)) {
return null;
}
// remove the prefix
String src = parity.substring(prefix.length());
byte[][] components = INodeDirectory.getPathComponents(src);
INode inode = namesystem.dir.getINode(components);
return new NameWithINode(src, inode);
}
|
java
|
@Check
public void checkContainerType(SarlAgent agent) {
final XtendTypeDeclaration declaringType = agent.getDeclaringType();
if (declaringType != null) {
final String name = canonicalName(declaringType);
assert name != null;
error(MessageFormat.format(Messages.SARLValidator_28, name),
agent,
null,
INVALID_NESTED_DEFINITION);
}
}
|
java
|
private static void onBind(Class clazz)
{
if (((MetamodelImpl) em.getMetamodel()).getEntityMetadataMap().isEmpty())
{
EntityMetadata metadata = new EntityMetadata(clazz);
metadata.setPersistenceUnit(getPersistenceUnit());
setSchemaAndPU(clazz, metadata);
new TableProcessor(em.getEntityManagerFactory().getProperties(),
((EntityManagerFactoryImpl) em.getEntityManagerFactory()).getKunderaMetadataInstance())
.process(clazz, metadata);
KunderaMetadata kunderaMetadata = ((EntityManagerFactoryImpl) em.getEntityManagerFactory())
.getKunderaMetadataInstance();
new IndexProcessor(kunderaMetadata).process(clazz, metadata);
ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
((MetamodelImpl) em.getMetamodel()).addEntityMetadata(clazz, metadata);
((MetamodelImpl) em.getMetamodel()).addEntityNameToClassMapping(clazz.getSimpleName(), clazz);
appMetadata.getMetamodelMap().put(getPersistenceUnit(), em.getMetamodel());
Map<String, List<String>> clazzToPuMap = new HashMap<String, List<String>>();
List<String> persistenceUnits = new ArrayList<String>();
persistenceUnits.add(getPersistenceUnit());
clazzToPuMap.put(clazz.getName(), persistenceUnits);
appMetadata.setClazzToPuMap(clazzToPuMap);
new SchemaConfiguration(em.getEntityManagerFactory().getProperties(), kunderaMetadata, getPersistenceUnit())
.configure();
}
}
|
python
|
def _parse_shard_list(shard_list, current_shard_list):
"""
parse shard list
:param shard_list: format like: 1,5-10,20
:param current_shard_list: current shard list
:return:
"""
if not shard_list:
return current_shard_list
target_shards = []
for n in shard_list.split(","):
n = n.strip()
if n.isdigit() and n in current_shard_list:
target_shards.append(n)
elif n:
rng = n.split("-")
if len(rng) == 2:
s = rng[0].strip()
e = rng[1].strip()
if s.isdigit() and e.isdigit():
for x in range(int(s), int(e)+1):
if str(x) in current_shard_list:
target_shards.append(str(x))
logger.info("parse_shard, shard_list: '{0}' current shard '{1}' result: '{2}'".format(shard_list,
current_shard_list, target_shards))
if not target_shards:
raise LogException("InvalidParameter", "There's no available shard with settings {0}".format(shard_list))
return target_shards
|
python
|
def raise_201(instance, location):
"""Abort the current request with a 201 (Created) response code. Sets the
Location header correctly. If the location does not start with a slash,
the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
:type instance: :class:`webob.resource.Resource`
:raises: :class:`webob.exceptions.ResponseException` of status 201
"""
_set_location(instance, location)
instance.response.status = 201
raise ResponseException(instance.response)
|
java
|
protected String randomValue(List<String> values) {
if (values == null || values.isEmpty()) {
throw new InvalidFunctionUsageException("No values to choose from");
}
final int idx = random.nextInt(values.size());
return values.get(idx);
}
|
python
|
def _complete_word(self, symbol, attribute):
"""Suggests context completions based exclusively on the word
preceding the cursor."""
#The cursor is after a %(,\s and the user is looking for a list
#of possibilities that is a bit smarter that regular AC.
if self.context.el_call in ["sub", "fun", "assign", "arith"]:
if symbol == "":
#The only possibilities are local vars, global vars or functions
#presented in that order of likelihood.
return self._complete_values()
else:
#It is also possible that subroutines are being called, but that
#the full name hasn't been entered yet.
return self._complete_values(symbol)
else:
return self.context.module.completions(symbol, attribute, True)
|
python
|
def groups_data(self):
"""All data about all groups (get-only).
:getter: Returns all data about all groups
:type: list of GroupData
"""
return _ListProxy(GroupData(num, name, symbol, variant)
for (num, name, symbol, variant)
in zip(range(self.groups_count),
self.groups_names,
self.groups_symbols,
self.groups_variants))
|
java
|
private Duration getRangeDurationSubDay(ProjectCalendar projectCalendar, TimescaleUnits rangeUnits, DateRange range, List<TimephasedWork> assignments, int startIndex)
{
throw new UnsupportedOperationException("Please request this functionality from the MPXJ maintainer");
}
|
java
|
@SuppressWarnings("unchecked")
public EList<IfcPhysicalQuantity> getQuantities() {
return (EList<IfcPhysicalQuantity>) eGet(Ifc2x3tc1Package.Literals.IFC_ELEMENT_QUANTITY__QUANTITIES, true);
}
|
python
|
def rollforward(self, dt):
"""
Roll provided date forward to next offset only if not on offset.
"""
if not self.onOffset(dt):
if self.n >= 0:
return self._next_opening_time(dt)
else:
return self._prev_opening_time(dt)
return dt
|
python
|
def is_empty(self):
"""True if only a single empty `a:p` element is present."""
ps = self.p_lst
if len(ps) > 1:
return False
if not ps:
raise InvalidXmlError('p:txBody must have at least one a:p')
if ps[0].text != '':
return False
return True
|
java
|
@Override
public void trimContexts()
{
for (int index = 0; index < this.frames.length; ++index) {
final Frame f = this.frames[index];
f.trimRecursive();
}
this.frame_index = 0;
}
|
java
|
public static String findCurrentWordFromCursor(String text, int cursor) {
if (text.length() <= cursor + 1) {
// return last word
if (text.contains(SPACE)) {
if (doWordContainEscapedSpace(text)) {
if (doWordContainOnlyEscapedSpace(text))
return switchEscapedSpacesToSpacesInWord(text);
else {
return switchEscapedSpacesToSpacesInWord(findEscapedSpaceWordCloseToEnd(text));
}
}
else {
if (text.lastIndexOf(SPACE) >= cursor) // cant use lastIndexOf
return text.substring(text.substring(0, cursor).lastIndexOf(SPACE)).trim();
else
return text.substring(text.lastIndexOf(SPACE)).trim();
}
}
else
return text.trim();
}
else {
String rest;
if (text.length() > cursor + 1)
rest = text.substring(0, cursor + 1);
else
rest = text;
if (doWordContainOnlyEscapedSpace(rest)) {
if (cursor > 1 &&
text.charAt(cursor) == SPACE_CHAR && text.charAt(cursor - 1) == SPACE_CHAR)
return "";
else
return switchEscapedSpacesToSpacesInWord(rest);
}
else {
if (cursor > 1 &&
text.charAt(cursor) == SPACE_CHAR && text.charAt(cursor - 1) == SPACE_CHAR)
return "";
// only if it contains a ' ' and its not at the end of the string
if (rest.trim().contains(SPACE))
return rest.substring(rest.trim().lastIndexOf(" ")).trim();
else
return rest.trim();
}
}
}
|
java
|
public static Map<String, Long> buildCountMap(Pattern pattern,
String text) {
return buildCountMap(pattern.splitAsStream(text));
}
|
java
|
public static Treenode search(Treenode start, String text, ITreenodeSearch search) {
return search(start.getTreeview(), text, search);
}
|
python
|
def set_cols_width(self, array):
"""Set the desired columns width
- the elements of the array should be integers, specifying the
width of each column. For example:
[10, 20, 5]
"""
self._check_row_size(array)
try:
array = map(int, array)
if reduce(min, array) <= 0:
raise ValueError
except ValueError:
sys.stderr.write("Wrong argument in column width specification\n")
raise
self._width = array
|
python
|
def generate_method(service_module, service_name, method_name):
"""Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called
"""
assert service_module
assert service_name
assert method_name
args_type = getattr(service_module, method_name + '_args')
result_type = getattr(service_module, method_name + '_result', None)
serializer = ThriftSerializer(result_type)
# oneway not currently supported
# TODO - write test for this
if result_type is None:
def not_supported(self, *args, **kwags):
raise OneWayNotSupportedError(
'TChannel+Thrift does not currently support oneway procedues'
)
return not_supported
result_spec = result_type.thrift_spec
# result_spec is a tuple of tuples in the form:
#
# (fieldId, fieldType, fieldName, ...)
#
# Where "..." is other information we don't care about right now.
#
# result_spec will be empty if there is no return value or exception for
# the method.
#
# Its first element, with field ID 0, contains the spec for the return
# value. It is None if the result type is void but the method may still
# throw exceptions.
#
# Elements after the first one are specs for the exceptions.
endpoint = '%s::%s' % (service_name, method_name)
@gen.coroutine
def send(self, *args, **kwargs):
params = inspect.getcallargs(
getattr(service_module.Iface, method_name), self, *args, **kwargs
)
params.pop('self') # self is already known
# $methodName_args is the implicit struct containing the various
# method parameters.
call_args = args_type()
for name, value in params.items():
setattr(call_args, name, value)
tracer = tracing.ClientTracer(channel=self.tchannel)
span, headers = tracer.start_span(
service=service_name, endpoint=method_name, headers={}
)
body = serializer.serialize_body(call_args)
header = serializer.serialize_header(headers)
# Glue for old API.
if hasattr(self.tchannel, 'request'):
tracing.apply_trace_flag(span, self.trace, True)
with span:
response = yield self.tchannel.request(
hostport=self.hostport, service=self.service
).send(
arg1=endpoint,
arg2=header,
arg3=body, # body
headers=self.protocol_headers,
)
body = yield response.get_body()
else:
with span:
response = yield self.tchannel.call(
scheme=schemes.THRIFT,
service=self.service,
arg1=endpoint,
arg2=header,
arg3=body,
hostport=self.hostport,
trace=self.trace,
tracing_span=span
# TODO: Need to handle these!
# headers=self.protocol_headers,
)
body = response.body
call_result = serializer.deserialize_body(body)
if not result_spec:
# void return type and no exceptions allowed
raise gen.Return(None)
for exc_spec in result_spec[1:]:
# May have failed with an exception
exc = getattr(call_result, exc_spec[2])
if exc is not None:
raise exc
if result_spec[0]:
# Non-void return type. Return the result.
success = getattr(call_result, result_spec[0][2])
if success is not None:
raise gen.Return(success)
else:
# No return type specified and no exceptions raised.
raise gen.Return(None)
# Expected a result but nothing was present in the object. Something
# went wrong.
from thrift import Thrift
raise Thrift.TApplicationException(
Thrift.TApplicationException.MISSING_RESULT,
'%s failed: did not receive a result as expected' % method_name
)
# TODO: We should probably throw a custom exception instead.
send.__name__ = method_name
return send
|
java
|
public Object doRemoteAction(String strCommand, Map<String, Object> properties) throws DBException, RemoteException
{
return null; // Not supported
}
|
python
|
def directed_predicates_in_expression(expression: ShExJ.shapeExpr, cntxt: Context) -> Dict[IRIREF, PredDirection]:
""" Directed predicates in expression -- return all predicates in shapeExpr along with which direction(s) they
evaluate
:param expression: Expression to scan
:param cntxt:
:return:
"""
dir_predicates: Dict[IRIREF, PredDirection] = {}
def predicate_finder(predicates: Dict[IRIREF, PredDirection], tc: ShExJ.TripleConstraint, _: Context) -> None:
if isinstance(tc, ShExJ.TripleConstraint):
predicates.setdefault(tc.predicate, PredDirection()).dir(tc.inverse is None or not tc.inverse)
def triple_expr_finder(predicates: Dict[IRIREF, PredDirection], expr: ShExJ.shapeExpr, cntxt_: Context) -> None:
if isinstance(expr, ShExJ.Shape) and expr.expression is not None:
cntxt_.visit_triple_expressions(expr.expression, predicate_finder, predicates)
# TODO: follow_inner_shapes as True probably goes too far, but we definitely need to cross shape/triplecons
cntxt.visit_shapes(expression, triple_expr_finder, dir_predicates, follow_inner_shapes=False)
return dir_predicates
|
python
|
def has_item(self, url):
"""
Test if required item exists in the cache.
"""
_hash = self.build_hash(url)
query = {'_id': _hash}
doc = self.dbase.cache.find_one(query, {'id': 1})
return doc is not None
|
python
|
def iscode(obj):
"""A replacement for inspect.iscode() which we can't used because we may be
using a different version of Python than the version of Python used
in creating the byte-compiled objects. Here, the code types may mismatch.
"""
return inspect.iscode(obj) or isinstance(obj, Code3) or isinstance(obj, Code2)
|
java
|
public EClass getIfcElementComponentType() {
if (ifcElementComponentTypeEClass == null) {
ifcElementComponentTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(199);
}
return ifcElementComponentTypeEClass;
}
|
python
|
def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
"""
column = col[self.col_name].replace({np.nan: np.inf})
frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict()
# next set probability ranges on interval [0,1]
start = 0
end = 0
num_vals = len(col)
for val in frequencies:
prob = frequencies[val] / num_vals
end = start + prob
interval = (start, end)
mean = np.mean(interval)
std = prob / 6
self.probability_map[val] = (interval, mean, std)
start = end
|
java
|
public static Request newUploadVideoRequest(Session session, File file,
Callback callback) throws FileNotFoundException {
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(file.getName(), descriptor);
return new Request(session, MY_VIDEOS, parameters, HttpMethod.POST, callback);
}
|
python
|
def prettyfy(response, format='json'):
"""A wrapper for pretty_json and pretty_xml
"""
if format == 'json':
return pretty_json(response.content)
else:
return pretty_xml(response.content)
|
java
|
public static Map<String, List<String>> startConfig(Map<String, Object> config, boolean restart) {
Map<String, List<String>> rc = load(config, true, restart);
return start(rc, true, restart);
}
|
python
|
def get_default(self, section, option):
"""
Get Default value for a given (section, option)
-> useful for type checking in 'get' method
"""
section = self._check_section_option(section, option)
for sec, options in self.defaults:
if sec == section:
if option in options:
return options[ option ]
else:
return NoDefault
|
java
|
private String getBasePath(String path1, String path2) {
StringBuffer base = new StringBuffer();
path1 = path1.replace('\\', '/');
path2 = path2.replace('\\', '/');
String[] parts1 = path1.split("/");
String[] parts2 = path2.split("/");
for (int i = 0; i < parts1.length; i++) {
if (i >= parts2.length) {
break;
}
if (parts1[i].equals(parts2[i])) {
base.append(parts1[i] + "/");
}
}
return base.toString();
}
|
java
|
public DeviceEnvelope addDevice(Device device) throws ApiException {
ApiResponse<DeviceEnvelope> resp = addDeviceWithHttpInfo(device);
return resp.getData();
}
|
java
|
public void setFlattenWriter(Writer w, boolean inclComments,
boolean inclConditionals, boolean inclPEs)
{
mFlattenWriter = new DTDWriter(w, inclComments, inclConditionals,
inclPEs);
}
|
java
|
public LineString toLineString(List<LatLng> latLngs, boolean hasZ,
boolean hasM) {
LineString lineString = new LineString(hasZ, hasM);
populateLineString(lineString, latLngs);
return lineString;
}
|
python
|
def jks_pkey_decrypt(data, password_str):
"""
Decrypts the private key password protection algorithm used by JKS keystores.
The JDK sources state that 'the password is expected to be in printable ASCII', though this does not appear to be enforced;
the password is converted into bytes simply by taking each individual Java char and appending its raw 2-byte representation.
See sun/security/provider/KeyProtector.java in the JDK sources.
"""
password_bytes = password_str.encode('utf-16be') # Java chars are UTF-16BE code units
data = bytearray(data)
iv, data, check = data[:20], data[20:-20], data[-20:]
xoring = zip(data, _jks_keystream(iv, password_bytes))
key = bytearray([d^k for d,k in xoring])
if hashlib.sha1(bytes(password_bytes + key)).digest() != check:
raise BadHashCheckException("Bad hash check on private key; wrong password?")
key = bytes(key)
return key
|
java
|
public FieldInfo addField(Modifiers modifiers,
String fieldName,
TypeDesc type) {
FieldInfo fi = new FieldInfo(this, modifiers, fieldName, type);
mFields.add(fi);
return fi;
}
|
python
|
def generate_params(n_items, interval=5.0, ordered=False):
r"""Generate random model parameters.
This function samples a parameter independently and uniformly for each
item. ``interval`` defines the width of the uniform distribution.
Parameters
----------
n_items : int
Number of distinct items.
interval : float
Sampling interval.
ordered : bool, optional
If true, the parameters are ordered from lowest to highest.
Returns
-------
params : numpy.ndarray
Model parameters.
"""
params = np.random.uniform(low=0, high=interval, size=n_items)
if ordered:
params.sort()
return params - params.mean()
|
java
|
public static Collection<String> getPropertyNames(
final Class<?> clazz
)
{
if (clazz == null) {
throw new IllegalArgumentException( "no class specified" );
}
Map<String, PropertyAccessor> accessors = _getAccessors( clazz );
return accessors.keySet();
}
|
java
|
@Override
public List<CommerceShippingFixedOption> findAll(int start, int end) {
return findAll(start, end, null);
}
|
python
|
def metric_from_cell(cell):
"""Calculates the metric matrix from cell, which is given in the
Cartesian system."""
cell = np.asarray(cell, dtype=float)
return np.dot(cell, cell.T)
|
python
|
def _trans_as_path(self, as_path_list):
"""Translates Four-Octet AS number to AS_TRANS and separates
AS_PATH list into AS_PATH and AS4_PATH lists if needed.
If the neighbor does not support Four-Octet AS number,
this method constructs AS4_PATH list from AS_PATH list and swaps
non-mappable AS number in AS_PATH with AS_TRANS, then
returns AS_PATH list and AS4_PATH list.
If the neighbor supports Four-Octet AS number, returns
the given AS_PATH list and None.
"""
def _swap(n):
if is_valid_old_asn(n):
# mappable
return n
else:
# non-mappable
return bgp.AS_TRANS
# If the neighbor supports Four-Octet AS number, returns
# the given AS_PATH list and None.
if self.is_four_octet_as_number_cap_valid():
return as_path_list, None
# If the neighbor does not support Four-Octet AS number,
# constructs AS4_PATH list from AS_PATH list and swaps
# non-mappable AS number in AS_PATH with AS_TRANS.
else:
new_as_path_list = []
for as_path in as_path_list:
if isinstance(as_path, set):
path_set = set()
for as_num in as_path:
path_set.add(_swap(as_num))
new_as_path_list.append(path_set)
elif isinstance(as_path, list):
path_list = list()
for as_num in as_path:
path_list.append(_swap(as_num))
new_as_path_list.append(path_list)
else:
# Ignore invalid as_path type
pass
# If all of the AS_PATH list is composed of mappable four-octet
# AS numbers only, returns the given AS_PATH list
# Assumption: If the constructed AS_PATH list is the same as
# the given AS_PATH list, all AS number is mappable.
if as_path_list == new_as_path_list:
return as_path_list, None
return new_as_path_list, as_path_list
|
python
|
def send_and_match_output(self,
send,
matches,
shutit_pexpect_child=None,
retry=3,
strip=True,
note=None,
echo=None,
loglevel=logging.DEBUG):
"""Returns true if the output of the command matches any of the strings in
the matches list of regexp strings. Handles matching on a per-line basis
and does not cross lines.
@param send: See send()
@param matches: String - or list of strings - of regexp(s) to check
@param shutit_pexpect_child: See send()
@param retry: Number of times to retry command (default 3)
@param strip: Whether to strip output (defaults to True)
@param note: See send()
@type send: string
@type matches: list
@type retry: integer
@type strip: boolean
"""
shutit_global.shutit_global_object.yield_to_draw()
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child
shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child)
return shutit_pexpect_session.send_and_match_output(send,
matches,
retry=retry,
strip=strip,
note=note,
echo=echo,
loglevel=loglevel)
|
python
|
def snakify(name, sep='_'):
''' Convert CamelCase to snake_case. '''
name = re.sub("([A-Z]+)([A-Z][a-z])", r"\1%s\2" % sep, name)
name = re.sub("([a-z\\d])([A-Z])", r"\1%s\2" % sep, name)
return name.lower()
|
java
|
public void mergeSourceData(Record recSource, Record recDest, boolean bFound)
{
for (int iFieldSeq = 0; iFieldSeq < recSource.getFieldCount(); iFieldSeq++)
{
BaseField fldSource = recSource.getField(iFieldSeq);
BaseField fldDest = recDest.getField(fldSource.getFieldName());
if (fldDest != null)
if (!fldSource.isNull())
fldDest.moveFieldToThis(fldSource);
}
}
|
python
|
def classify(self, text=u''):
""" Predicts the Language of a given text.
:param text: Unicode text to be classified.
"""
text = self.lm.normalize(text)
tokenz = LM.tokenize(text, mode='c')
result = self.lm.calculate(doc_terms=tokenz)
#print 'Karbasa:', self.karbasa(result)
if self.unk and self.lm.karbasa(result) < self.min_karbasa:
lang = 'unk'
else:
lang = result['calc_id']
return lang
|
python
|
def get(self, user_id, lang='zh_CN'):
"""
获取用户基本信息(包括UnionID机制)
详情请参考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140839
:param user_id: 普通用户的标识,对当前公众号唯一
:param lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
:return: 返回的 JSON 数据包
使用示例::
from wechatpy import WeChatClient
client = WeChatClient('appid', 'secret')
user = client.user.get('openid')
"""
assert lang in ('zh_CN', 'zh_TW', 'en'), 'lang can only be one of \
zh_CN, zh_TW, en language codes'
return self._get(
'user/info',
params={
'openid': user_id,
'lang': lang
}
)
|
python
|
def _ImportModuleHookBySuffix(name, package=None):
"""Callback when a module is imported through importlib.import_module."""
_IncrementNestLevel()
try:
# Really import modules.
module = _real_import_module(name, package)
finally:
if name.startswith('.'):
if package:
name = _ResolveRelativeImport(name, package)
else:
# Should not happen. Relative imports require the package argument.
name = None
if name:
_ProcessImportBySuffix(name, None, None)
return module
|
java
|
public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) {
return splitByWholeSeparatorWorker(str, separator, -1, true);
}
|
python
|
def add_role_info(self, role_name, role_type, host_id, config=None):
"""
Add a role info. The role will be created along with the service setup.
@param role_name: Role name
@param role_type: Role type
@param host_id: The host where the role should run
@param config: (Optional) A dictionary of role config values
"""
if self.roles is None:
self.roles = [ ]
api_config_list = config is not None and config_to_api_list(config) or None
self.roles.append({
'name' : role_name,
'type' : role_type,
'hostRef' : { 'hostId' : host_id },
'config' : api_config_list })
|
java
|
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "chooseEngineServerAlias", new Object[] { keyType, issuers, engine });
String rc = null;
if (null != customKM && customKM instanceof X509ExtendedKeyManager) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "chooseEngineServerAlias, using customKM -> " + customKM.getClass().getName());
rc = ((X509ExtendedKeyManager) customKM).chooseEngineServerAlias(keyType, issuers, engine);
} else {
rc = chooseServerAlias(keyType, issuers);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "chooseEngineServerAlias: " + rc);
return rc;
}
|
java
|
public static <T> T[] toArray(Collection<T> col, Class<T> cls)
{
T[] arr = (T[]) Array.newInstance(cls, col.size());
return col.toArray(arr);
}
|
python
|
def get_col_rgba(color, transparency=None, opacity=None):
"""This class converts a Gdk.Color into its r, g, b parts and adds an alpha according to needs
If both transparency and opacity is None, alpha is set to 1 => opaque
:param Gdk.Color color: Color to extract r, g and b from
:param float | None transparency: Value between 0 (opaque) and 1 (transparent) or None if opacity is to be used
:param float | None opacity: Value between 0 (transparent) and 1 (opaque) or None if transparency is to be used
:return: Red, Green, Blue and Alpha value (all between 0.0 - 1.0)
"""
r, g, b = color.red, color.green, color.blue
# Convert from 0-6535 to 0-1
r /= 65535.
g /= 65535.
b /= 65535.
if transparency is not None or opacity is None:
transparency = 0 if transparency is None else transparency # default value
if transparency < 0 or transparency > 1:
raise ValueError("Transparency must be between 0 and 1")
alpha = 1 - transparency
else:
if opacity < 0 or opacity > 1:
raise ValueError("Opacity must be between 0 and 1")
alpha = opacity
return r, g, b, alpha
|
python
|
def devices(self):
"""Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
"""
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
|
python
|
def can_replicate_commands(self):
"""
Whether Redis supports single command replication.
"""
if not hasattr(self, '_can_replicate_commands'):
info = self.redis.info('server')
version_info = info['redis_version'].split('.')
major, minor = int(version_info[0]), int(version_info[1])
result = major > 3 or major == 3 and minor >= 2
self._can_replicate_commands = result
return self._can_replicate_commands
|
java
|
public static <T> ArrayList<T> sortThis(ArrayList<T> list, Comparator<? super T> comparator)
{
int size = list.size();
if (ArrayListIterate.canAccessInternalArray(list))
{
Arrays.sort(ArrayListIterate.getInternalArray(list), 0, size, comparator);
}
else
{
Collections.sort(list, comparator);
}
return list;
}
|
python
|
def to_method(func):
"""
Lift :func:`func` to a method; it will be called with the first argument
'self' ignored.
:param func: Any callable object
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Wrapper function.
"""
return func(*args[1:], **kwargs)
return wrapper
|
java
|
private Description handleLocal(DCLInfo info, VisitorState state) {
JCExpressionStatement expr = getChild(info.synchTree().getBlock(), JCExpressionStatement.class);
if (expr == null) {
return Description.NO_MATCH;
}
if (expr.getStartPosition() > ((JCTree) info.innerIf()).getStartPosition()) {
return Description.NO_MATCH;
}
if (!(expr.getExpression() instanceof JCAssign)) {
return Description.NO_MATCH;
}
JCAssign assign = (JCAssign) expr.getExpression();
if (!Objects.equals(ASTHelpers.getSymbol(assign.getVariable()), info.sym())) {
return Description.NO_MATCH;
}
Symbol sym = ASTHelpers.getSymbol(assign.getExpression());
if (!(sym instanceof VarSymbol)) {
return Description.NO_MATCH;
}
VarSymbol fvar = (VarSymbol) sym;
if (fvar.getKind() != ElementKind.FIELD) {
return Description.NO_MATCH;
}
return handleField(info.outerIf(), fvar, state);
}
|
python
|
def _handle_result_line(self, sline):
"""
Parses the data line and adds to the dictionary.
:param sline: a split data line to parse
:returns: the number of rows to jump and parse the next data line or
return the code error -1
"""
# If there are less values founded than headers, it's an error
if len(sline) != len(self._columns):
self.err("One data line has the wrong number of items")
return -1
result = ''
name = ''
for idx, val in enumerate(sline):
if self._columns[idx] == 'Analyte Name':
name = val
elif self._columns[idx] == 'Analyte Result':
result = self._convert_result(val)
if not self._cur_values.get(self._keyword, None):
self._cur_values[self._keyword] = {}
self._cur_values[self._keyword][name] = result
# Each line goes to result values as well in case AS'es for each
# Analyte is created in Bika. For those kind of AS'es, keywords must be
# the same as Analyte Name field from CSV.
self._cur_values[name] = {
'DefaultResult': 'Analyte Result',
'Remarks': '',
'Analyte Result': result,
}
# Adding this result to the previous results
# in the self._cur_values dictionary, as an interim field.
for key in self._cur_values:
if key == name:
continue
self._cur_values[key][name] = result
return 0
|
java
|
public void setPosition(float x, float y, float z) {
getTransform().setPosition(x, y, z);
if (mTransformCache.setPosition(x, y, z)) {
onTransformChanged();
}
}
|
java
|
public BeanLazyOutputHandler handle(List<QueryParameters> outputList) throws MjdbcException {
if (outputList instanceof QueryParametersLazyList) {
return new BeanLazyOutputHandler(this.type, this.processor, (QueryParametersLazyList) outputList);
} else {
throw new MjdbcRuntimeException("LazyOutputHandler can be used only together with LazyStatementHandler. \n" +
"Please assign LazyStatementHandler to this QueryRunner or create new QueryRunnerService via MjdbcFactory");
}
}
|
java
|
public static ImmutableSet<String> wordSet(final Class<?> origin, final String resource) throws IOException {
return ImmutableSet.copyOf(new HashSet<String>() {{
readResource(origin, resource, new NullReturnLineProcessor() {
@Override
public boolean processLine(@Nonnull final String line) {
final String l = simplify(line);
// add to the containing HashSet we are currently in the init block of
if (!l.isEmpty() && !l.startsWith("#")) {
for (final String part : SPACES.split(l)) {
add(clean(part));
}
}
return true;
}
});
}});
}
|
java
|
public BoundingBox overlap(BoundingBox projectedCoverage) {
BoundingBox overlap = null;
if (point) {
overlap = projectedBoundingBox;
} else {
overlap = projectedBoundingBox.overlap(projectedCoverage);
}
return overlap;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.