language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public static String verifyReadFile(File file){
if (file == null){
return "The file is null.";
}
String absolutePath=file.getAbsolutePath();
if (!file.exists()){
return "The path '"+absolutePath+"' do not exits.";
}
if (!file.isFile()){
return "The path '"+absolutePath+"' is not a file.";
}
if (!file.canRead()){
return "We have not permision to read the path:'"+absolutePath+"'.";
}
return null;
} |
java | public Set<String> names() {
TreeSet<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
for (int i = 0, size = size(); i < size; i++) {
result.add(name(i));
}
return Collections.unmodifiableSet(result);
} |
python | def full_url(self):
"""Return the full reddit URL associated with the usernote.
Arguments:
subreddit: the subreddit name for the note (PRAW Subreddit object)
"""
if self.link == '':
return None
else:
return Note._expand_url(self.link, self.subreddit) |
python | def emoticons(string):
'''emot.emoticons is use to detect emoticons from text
>>> text = "I love python 👨 :-)"
>>> emot.emoticons(text)
>>> {'value': [':-)'], 'location': [[16, 19]], 'mean': ['Happy face smiley'], 'flag': True}
'''
__entities = []
flag = True
try:
pattern = u'(' + u'|'.join(k for k in emo_unicode.EMOTICONS) + u')'
__entities = []
__value = []
__location = []
matches = re.finditer(r"%s"%pattern,str(string))
for et in matches:
__value.append(et.group().strip())
__location.append([et.start(),et.end()])
__mean = []
for each in __value:
__mean.append(emo_unicode.EMOTICONS_EMO[each])
if len(__value) < 1:
flag = False
__entities = {
'value' : __value,
'location' : __location,
'mean' : __mean,
'flag' : flag
}
except Exception as e:
__entities = [{'flag' : False}]
#print("No emoiticons found")
return __entities
return __entities |
python | def basic_dependencies(self):
"""
Accesses basic dependencies from the XML output
:getter: Returns the dependency graph for basic dependencies
:type: corenlp_xml.dependencies.DependencyGraph
"""
if self._basic_dependencies is None:
deps = self._element.xpath('dependencies[@type="basic-dependencies"]')
if len(deps) > 0:
self._basic_dependencies = DependencyGraph(deps[0])
return self._basic_dependencies |
java | public void close() throws IOException {
for (;;) {
int state = this.state;
if (isClosed(state)) {
return;
}
// Once a close operation happens, the channel is considered shutdown.
if (casState(state, state | STATE_ALL_MASK)) {
break;
}
}
int res = close(fd);
if (res < 0) {
throw newIOException("close", res);
}
} |
java | public SearchResults query(WaybackRequest wbRequest) throws ResourceIndexNotAvailableException, ResourceNotInArchiveException, BadQueryException, AccessControlException {
while(true) {
RangeMember best = findBestMember();
if(best == null) {
throw new ResourceIndexNotAvailableException("Unable to find active range for request.");
}
best.noteConnectionStart();
SearchResults results;
try {
results = best.query(wbRequest);
best.noteConnectionSuccess();
return results;
} catch (ResourceIndexNotAvailableException e) {
best.noteConnectionFailure();
} catch (ResourceNotInArchiveException e1) {
// need to catch and rethrow so we do accounting on
// activeConnections. ResourceNotInArchive is still a
// "connection success".
best.noteConnectionSuccess();
throw e1;
}
}
} |
python | def led_control_encode(self, target_system, target_component, instance, pattern, custom_len, custom_bytes):
'''
Control vehicle LEDs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
instance : Instance (LED instance to control or 255 for all LEDs) (uint8_t)
pattern : Pattern (see LED_PATTERN_ENUM) (uint8_t)
custom_len : Custom Byte Length (uint8_t)
custom_bytes : Custom Bytes (uint8_t)
'''
return MAVLink_led_control_message(target_system, target_component, instance, pattern, custom_len, custom_bytes) |
java | public static QName tagToQName(final String tag,
final Map<String, String> nsRegistry) {
final String[] split = tag.split("\\:");
if (split.length <= 1) {
return new QName(split[0]);
} else {
final String namespace = nsRegistry.get(split[0]);
if (namespace != null) {
return new QName(namespace, split[1]);
} else {
return new QName(split[1]);
}
}
} |
java | public long write(short type, byte[][] data)
throws InterruptedException, IOException {
try {
return super.put(type, data, true);
} catch (InterruptedException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Throwable e) {
throw new DelegatedRuntimeException(e);
}
} |
java | synchronized public OpenFileInfo[] iterativeGetOpenFiles(
String prefix, int millis, String startAfter) {
final long thresholdMillis = System.currentTimeMillis() - millis;
// this flag is for subsequent calls that included a 'start'
// parameter. in those cases, we need to throw out the first
// result
boolean skip = false;
String jumpTo = startAfter;
if (jumpTo == null || jumpTo.compareTo("") == 0)
jumpTo = prefix;
else
skip = true;
ArrayList<OpenFileInfo> entries = new ArrayList<OpenFileInfo>();
final int srclen = prefix.length();
for(Map.Entry<String, LeaseOpenTime> entry : sortedLeasesByPath.tailMap(jumpTo).entrySet()) {
final String p = entry.getKey();
if (!p.startsWith(prefix)) {
// traversed past the prefix, so we're done
OpenFileInfo[] result = entries.toArray(
new OpenFileInfo[entries.size()]);
return result;
}
if (skip) {
skip = false;
} else if (p.length() == srclen || p.charAt(srclen) == Path.SEPARATOR_CHAR) {
long openTime = entry.getValue().openTime;
if (openTime <= thresholdMillis) {
entries.add(new OpenFileInfo(entry.getKey(), openTime));
if (entries.size() >= rpcBatchSize) {
// reached the configured batch size, so return this subset
OpenFileInfo[] result = entries.toArray(
new OpenFileInfo[entries.size()]);
return result;
}
}
}
}
// reached the end of the list of files, so we're done
OpenFileInfo[] result = entries.toArray(
new OpenFileInfo[entries.size()]);
return result;
} |
python | def fill(duration, point):
"""
fills the subsequence of the point with repetitions of its subsequence and
sets the ``duration`` of each point.
"""
point['sequence'] = point['sequence'] * (point[DURATION_64] / (8 * duration)) | add({DURATION_64: duration})
return point |
python | def correct_html(self, root, children, div_math, insert_idx, text):
"""Separates out <div class="math"> from the parent tag <p>. Anything
in between is put into its own parent tag of <p>"""
current_idx = 0
for idx in div_math:
el = markdown.util.etree.Element('p')
el.text = text
el.extend(children[current_idx:idx])
# Test to ensure that empty <p> is not inserted
if len(el) != 0 or (el.text and not el.text.isspace()):
root.insert(insert_idx, el)
insert_idx += 1
text = children[idx].tail
children[idx].tail = None
root.insert(insert_idx, children[idx])
insert_idx += 1
current_idx = idx+1
el = markdown.util.etree.Element('p')
el.text = text
el.extend(children[current_idx:])
if len(el) != 0 or (el.text and not el.text.isspace()):
root.insert(insert_idx, el) |
python | def get_by_id(self, id, change_notes=False):
""" Get a :class:`skosprovider.skos.Concept` or :class:`skosprovider.skos.Collection` by id
:param (str) id: integer id of the :class:`skosprovider.skos.Concept` or :class:`skosprovider.skos.Concept`
:return: corresponding :class:`skosprovider.skos.Concept` or :class:`skosprovider.skos.Concept`.
Returns None if non-existing id
"""
graph = uri_to_graph('%s/%s.rdf' % (self.url, id), session=self.session)
if graph is False:
log.debug('Failed to retrieve data for %s/%s.rdf' % (self.url, id))
return False
# get the concept
things = things_from_graph(graph, self.subclasses, self.concept_scheme)
if len(things) == 0:
return False
c = things[0]
return c |
python | def dumps(cls, obj, protocol=0):
"""
Equivalent to pickle.dumps except that the HoloViews option
tree is saved appropriately.
"""
cls.save_option_state = True
val = pickle.dumps(obj, protocol=protocol)
cls.save_option_state = False
return val |
python | def _run_serial_ops(state):
'''
Run all ops for all servers, one server at a time.
'''
for host in list(state.inventory):
host_operations = product([host], state.get_op_order())
with progress_spinner(host_operations) as progress:
try:
_run_server_ops(
state, host,
progress=progress,
)
except PyinfraError:
state.fail_hosts({host}) |
python | def _deep_value(*args, **kwargs):
""" Drills down into tree using the keys
"""
node, keys = args[0], args[1:]
for key in keys:
node = node.get(key, {})
default = kwargs.get('default', {})
if node in ({}, [], None):
node = default
return node |
java | public Criteria startsWith(Iterable<String> values) {
Assert.notNull(values, "Collection must not be null");
for (String value : values) {
startsWith(value);
}
return this;
} |
java | public static XID parse(String idString) {
UUID uuid = UUID.fromString(idString);
return new XID(uuid);
} |
python | def addproperties(
names,
bfget=None, afget=None, enableget=True,
bfset=None, afset=None, enableset=True,
bfdel=None, afdel=None, enabledel=True
):
"""Decorator in charge of adding python properties to cls.
{a/b}fget, {a/b}fset and {a/b}fdel are applied to all properties matching
names in taking care to not forget default/existing properties. The
prefixes *a* and *b* are respectively for after and before default/existing
property getter/setter/deleter execution.
These getter, setter and deleter functions are called before existing or
default getter, setter and deleters. Default getter, setter and deleters
are functions which uses an attribute with a name starting with '_' and
finishing with the property name (like the python language convention).
.. seealso::
_protectedattrname(name)
:param str(s) names: property name(s) to add.
:param bfget: getter function to apply to all properties before
default/existing getter execution. Parameters are a decorated cls
instance and a property name.
:param afget: fget function to apply to all properties after
default/existing getter execution. Parameters are a decorated cls
instance and a property name.
:param bool enableget: if True (default), enable existing or default getter
. Otherwise, use only fget if given.
:param bfset: fset function to apply to all properties before
default/existing setter execution. Parameters are a decorated cls
instance and a property name.
:param afset: fset function to apply to all properties after
default/existing setter execution. Parameters are a decorated cls
instance and a property name.
:param bool enableset: if True (default), enable existing or default setter
. Otherwise, use only fset if given.
:param bfdel: fdel function to apply to all properties before
default/existing deleter execution. Parameters are a decorated cls
instance and a property name.
:param bfdel: fdel function to apply to all properties after
default/existing deleter execution. Parameters are a decorated cls
instance and a property name.
:param bool enabledel: if True (default), enable existing or default
deleter. Otherwise, use only fdel if given.
:return: cls decorator.
"""
# ensure names is a list
names = ensureiterable(names, exclude=string_types)
if isinstance(bfget, MethodType):
finalbfget = lambda self, name: bfget(name)
else:
finalbfget = bfget
if isinstance(afget, MethodType):
finalafget = lambda self, name: afget(name)
else:
finalafget = afget
if isinstance(bfset, MethodType):
finalbfset = lambda self, value, name: bfset(value, name)
else:
finalbfset = bfset
if isinstance(afset, MethodType):
finalafset = lambda self, value, name: afset(value, name)
else:
finalafset = afset
if isinstance(bfdel, MethodType):
finalbfdel = lambda self, name: bfdel(name)
else:
finalbfdel = bfdel
if isinstance(afdel, MethodType):
finalafdel = lambda self, name: afdel(name)
else:
finalafdel = afdel
def _addproperties(cls):
"""Add properties to cls.
:param type cls: cls on adding properties.
:return: cls
"""
for name in names:
protectedattrname = _protectedattrname(name)
# try to find an existing property
existingproperty = getattr(cls, name, None)
if isinstance(existingproperty, property):
_fget = existingproperty.fget
_fset = existingproperty.fset
_fdel = existingproperty.fdel
else:
_fget, _fset, _fdel = None, None, None
# construct existing/default getter
if _fget is None:
def _fget(protectedattrname):
"""Simple getter wrapper."""
def _fget(self):
"""Simple getter."""
return getattr(self, protectedattrname, None)
return _fget
_fget = _fget(protectedattrname)
_fget.__doc__ = 'Get this {0}.\n:return: this {0}.'.format(
name
)
# transform method to function in order to add self in parameters
if isinstance(_fget, MethodType):
final_fget = lambda self: _fget()
else:
final_fget = _fget
# construct existing/default setter
if _fset is None:
def _fset(protectedattrname):
"""Simple setter wrapper."""
def _fset(self, value):
"""Simple setter."""
setattr(self, protectedattrname, value)
return _fset
_fset = _fset(protectedattrname)
_fset.__doc__ = (
'Change of {0}.\n:param {0}: {0} to use.'.format(name)
)
# transform method to function in order to add self in parameters
if isinstance(_fset, MethodType):
final_fset = lambda self, value: _fset(value)
else:
final_fset = _fset
# construct existing/default deleter
if _fdel is None:
def _fdel(protectedattrname):
"""Simple deleter wrapper."""
def _fdel(self):
"""Simple deleter."""
if hasattr(self, protectedattrname):
delattr(self, protectedattrname)
return _fdel
_fdel = _fdel(protectedattrname)
_fdel.__doc__ = 'Delete this {0}.'.format(name)
# transform method to function in order to add self in parameters
if isinstance(_fdel, MethodType):
final_fdel = lambda self: _fdel()
else:
final_fdel = _fdel
def _getter(final_fget, name):
"""Property getter wrapper."""
def _getter(self):
"""Property getter."""
result = None
# start to process input bfget
if finalbfget is not None:
result = finalbfget(self, name)
# process cls getter
if enableget:
result = final_fget(self)
# finish to process afget
if finalafget is not None:
result = finalafget(self, name)
return result
return _getter
_getter = _getter(final_fget, name)
_getter.__doc__ = final_fget.__doc__ # update doc
def _setter(final_fset, name):
"""Property setter wrapper."""
def _setter(self, value):
"""Property setter."""
# start to process input bfset
if finalbfset is not None:
finalbfset(self, value, name)
# finish to process cls setter
if enableset:
final_fset(self, value)
# finish to process afset
if finalafset is not None:
finalafset(self, value, name)
return _setter
_setter = _setter(final_fset, name)
_setter.__doc__ = final_fset.__doc__ # update doc
def _deleter(final_fdel, name):
"""Property deleter wrapper."""
def _deleter(self):
"""Property deleter."""
# start to process input fdel
if finalbfdel is not None:
finalbfdel(self, name)
# finish to process cls deleter
if enabledel:
final_fdel(self)
# finish to process afget
if finalafdel is not None:
finalafdel(self, name)
return _deleter
_deleter = _deleter(final_fdel, name)
_deleter.__doc__ = final_fdel.__doc__ # update doc
# get property name
doc = '{0} property.'.format(name)
propertyfield = property(
fget=_getter, fset=_setter, fdel=_deleter, doc=doc
)
# put property name in cls
setattr(cls, name, propertyfield)
return cls # finish to return the cls
return _addproperties |
python | def complex_type(name=None):
'''Decorator for registering complex types'''
def wrapped(cls):
ParseType.type_mapping[name or cls.__name__] = cls
return cls
return wrapped |
java | private Object execute(Object o, Method m, Object... args) throws CommandActionExecutionException {
Object result = null;
try {
m.setAccessible(true); // suppress Java language access
if (isCompileWeaving() && metaHolder.getAjcMethod() != null) {
result = invokeAjcMethod(metaHolder.getAjcMethod(), o, metaHolder, args);
} else {
result = m.invoke(o, args);
}
} catch (IllegalAccessException e) {
propagateCause(e);
} catch (InvocationTargetException e) {
propagateCause(e);
}
return result;
} |
java | @Override
public String quit() {
checkIsInMultiOrPipeline();
client.quit();
String quitReturn = client.getStatusCodeReply();
client.disconnect();
return quitReturn;
} |
java | public static FsPermission deserializeWriterDirPermissions(State state, int numBranches, int branchId) {
return new FsPermission(state.getPropAsShortWithRadix(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_DIR_PERMISSIONS, numBranches, branchId),
FsPermission.getDefault().toShort(), ConfigurationKeys.PERMISSION_PARSING_RADIX));
} |
python | def _get_version():
"""Return the project version from VERSION file."""
with open(os.path.join(os.path.dirname(__file__), PACKAGE_NAME, 'VERSION'), 'rb') as f:
version = f.read().decode('ascii').strip()
return version |
java | public Structure getStructureForDomain(String scopId) throws IOException, StructureException {
return getStructureForDomain(scopId, ScopFactory.getSCOP());
} |
python | def forms(self, req, tag):
"""
Make and return some forms, using L{self.parameter.getInitialLiveForms}.
@return: some subforms.
@rtype: C{list} of L{LiveForm}
"""
liveForms = self.parameter.getInitialLiveForms()
for liveForm in liveForms:
liveForm.setFragmentParent(self)
return liveForms |
java | @Override
public boolean isValidGroup(String groupSecurityName) throws RegistryException {
for (UserRegistry registry : delegates) {
if (registry.isValidGroup(groupSecurityName)) {
return true;
}
}
return false;
} |
python | def map_cluster(events, cluster):
"""
Maps the cluster hits on events. Not existing hits in events have all values set to 0
"""
cluster = np.ascontiguousarray(cluster)
events = np.ascontiguousarray(events)
mapped_cluster = np.zeros((events.shape[0], ), dtype=dtype_from_descr(data_struct.ClusterInfoTable))
mapped_cluster = np.ascontiguousarray(mapped_cluster)
analysis_functions.map_cluster(events, cluster, mapped_cluster)
return mapped_cluster |
java | public void setResources(java.util.Collection<String> resources) {
if (resources == null) {
this.resources = null;
return;
}
this.resources = new java.util.ArrayList<String>(resources);
} |
python | def salt(self):
"""
Generates a salt via pgcrypto.gen_salt('algorithm').
"""
cursor = connections[PGCRYPTOAUTH_DATABASE].cursor()
cursor.execute("SELECT gen_salt('%s')" % PGCRYPTOAUTH_ALGORITHM)
return cursor.fetchall()[0][0] |
java | @Override
public synchronized void onFileCreate(File file) {
final Set<DetectedWebJar> listOfDetectedWebJarLib = isWebJar(file);
if (listOfDetectedWebJarLib != null) {
JarFile jar = null;
try {
jar = new JarFile(file);
List<FileWebJarLib> installed = new ArrayList<>();
for (DetectedWebJar detected : listOfDetectedWebJarLib) {
FileWebJarLib lib = expand(detected, jar);
if (lib != null) {
libs.add(lib);
installed.add(lib);
LOGGER.info("{} unpacked to {}", lib.name, lib.root.getAbsolutePath());
}
}
controller.addWebJarLibs(installed);
} catch (IOException e) {
LOGGER.error("Cannot open the jar file {}", file.getAbsolutePath(), e);
} finally {
IOUtils.closeQuietly(jar);
}
}
} |
java | public OCommandExecutorSQLTraverse parse(final OCommandRequest iRequest) {
super.parse(iRequest);
final int pos = parseFields();
if (pos == -1)
throw new OCommandSQLParsingException("Traverse must have the field list. Use " + getSyntax());
int endPosition = text.length();
int endP = textUpperCase.indexOf(" " + OCommandExecutorSQLTraverse.KEYWORD_LIMIT, parserGetCurrentPosition());
if (endP > -1 && endP < endPosition)
endPosition = endP;
compiledFilter = OSQLEngine.getInstance().parseFromWhereCondition(text.substring(pos, endPosition), context);
traverse.predicate(compiledFilter);
optimize();
parserSetCurrentPosition(compiledFilter.parserIsEnded() ? endPosition : compiledFilter.parserGetCurrentPosition() + pos);
parserSkipWhiteSpaces();
if (!parserIsEnded()) {
if (parserOptionalKeyword(KEYWORD_LIMIT, KEYWORD_SKIP)) {
final String w = tempResult.toString();
if (w.equals(KEYWORD_LIMIT))
parseLimit(w);
else if (w.equals(KEYWORD_SKIP))
parseSkip(w);
}
}
if (limit == 0 || limit < -1)
throw new IllegalArgumentException("Limit must be > 0 or = -1 (no limit)");
else
traverse.limit(limit);
traverse.context(((OCommandRequestText) iRequest).getContext());
return this;
} |
java | private static Object injectAndPostConstruct(Object injectionProvider, Class Klass, List injectedBeanStorage)
{
Object instance = null;
if (injectionProvider != null)
{
try
{
Object managedObject = _FactoryFinderProviderFactory.INJECTION_PROVIDER_INJECT_CLASS_METHOD.invoke(injectionProvider, Klass);
instance = _FactoryFinderProviderFactory.MANAGED_OBJECT_GET_OBJECT_METHOD.invoke(managedObject, null);
if (instance != null) {
Object creationMetaData = _FactoryFinderProviderFactory.MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD.invoke
(managedObject, CreationalContext.class);
addBeanEntry(instance, creationMetaData, injectedBeanStorage);
_FactoryFinderProviderFactory.INJECTION_PROVIDER_POST_CONSTRUCT_METHOD.invoke(
injectionProvider, instance, creationMetaData);
}
} catch (Exception ex)
{
throw new FacesException(ex);
}
}
return instance;
} |
java | public static <A,S> Transition<A,S> create(S fromState, A action, S toState){
return new Transition<A, S>(fromState, action, toState);
} |
java | public Observable<ServiceResponse<HybridConnectionLimitsInner>> getHybridConnectionPlanLimitWithServiceResponseAsync(String resourceGroupName, String name) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (name == null) {
throw new IllegalArgumentException("Parameter name is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.getHybridConnectionPlanLimit(resourceGroupName, name, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<HybridConnectionLimitsInner>>>() {
@Override
public Observable<ServiceResponse<HybridConnectionLimitsInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<HybridConnectionLimitsInner> clientResponse = getHybridConnectionPlanLimitDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} |
python | def k_to_R_value(k, SI=True):
r'''Returns the R-value of a substance given its thermal conductivity,
Will return R-value in SI units unless SI is false. SI units are
m^2 K/(W*inch); Imperial units of R-value are ft^2 deg F*h/(BTU*inch).
Parameters
----------
k : float
Thermal conductivity of a substance [W/m/K]
SI : bool, optional
Whether to use the SI conversion or not
Returns
-------
R_value : float
R-value of a substance [m^2 K/(W*inch) or ft^2 deg F*h/(BTU*inch)]
Notes
-----
Provides the reverse conversion of R_value_to_k.
Examples
--------
>>> k_to_R_value(R_value_to_k(0.12)), k_to_R_value(R_value_to_k(0.71, SI=False), SI=False)
(0.11999999999999998, 0.7099999999999999)
References
----------
.. [1] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010.
'''
r = k_to_thermal_resistivity(k)
if SI:
return r*inch
else:
return r/(foot**2*degree_Fahrenheit*hour/Btu/inch) |
python | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: WorkspaceContext for this WorkspaceInstance
:rtype: twilio.rest.taskrouter.v1.workspace.WorkspaceContext
"""
if self._context is None:
self._context = WorkspaceContext(self._version, sid=self._solution['sid'], )
return self._context |
java | @Override
public CreateBranchResult createBranch(CreateBranchRequest request) {
request = beforeClientExecution(request);
return executeCreateBranch(request);
} |
python | def locale_negotiator(request):
"""Locale negotiator base on the `Accept-Language` header"""
locale = 'en'
if request.accept_language:
locale = request.accept_language.best_match(LANGUAGES)
locale = LANGUAGES.get(locale, 'en')
return locale |
python | def connect_host(kwargs=None, call=None):
'''
Connect the specified host system in this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f connect_host my-vmware-config host="myHostSystemName"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The connect_host function must be called with '
'-f or --function.'
)
host_name = kwargs.get('host') if kwargs and 'host' in kwargs else None
if not host_name:
raise SaltCloudSystemExit(
'You must specify name of the host system.'
)
# Get the service instance
si = _get_si()
host_ref = salt.utils.vmware.get_mor_by_property(si, vim.HostSystem, host_name)
if not host_ref:
raise SaltCloudSystemExit(
'Specified host system does not exist.'
)
if host_ref.runtime.connectionState == 'connected':
return {host_name: 'host system already connected'}
try:
task = host_ref.ReconnectHost_Task()
salt.utils.vmware.wait_for_task(task, host_name, 'connect host', 5, 'info')
except Exception as exc:
log.error(
'Error while connecting host %s: %s',
host_name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return {host_name: 'failed to connect host'}
return {host_name: 'connected host'} |
python | def _load_report(infile):
'''Loads report file into a dictionary. Key=reference name.
Value = list of report lines for that reference'''
report_dict = {}
f = pyfastaq.utils.open_file_read(infile)
first_line = True
for line in f:
line = line.rstrip()
if first_line:
expected_first_line = '#' + '\t'.join(report.columns)
if line != expected_first_line:
pyfastaq.utils.close(f)
raise Error('Error reading report file. Expected first line of file is\n' + expected_first_line + '\nbut got:\n' + line)
first_line = False
else:
line_dict = ReportFilter._report_line_to_dict(line)
if line_dict is None:
pyfastaq.utils.close(f)
raise Error('Error reading report file at this line:\n' + line)
ref_name = line_dict['ref_name']
ctg_name = line_dict['ctg']
if ref_name not in report_dict:
report_dict[ref_name] = {}
if ctg_name not in report_dict[ref_name]:
report_dict[ref_name][ctg_name] = []
report_dict[ref_name][ctg_name].append(line_dict)
pyfastaq.utils.close(f)
return report_dict |
python | def _update_indexes_for_mutated_object(collection, obj):
"""If an object is updated, this will simply remove
it and re-add it to the indexes defined on the
collection."""
for index in _db[collection].indexes.values():
_remove_from_index(index, obj)
_add_to_index(index, obj) |
python | def flasher(msg, severity=None):
"""Flask's flash if available, logging call if not"""
try:
flash(msg, severity)
except RuntimeError:
if severity == 'danger':
logging.error(msg)
else:
logging.info(msg) |
python | def resize_matrix(usv, num_rows, num_cols):
"""Apply algorith 2 in https://arxiv.org/pdf/1901.08910.pdf.
Args:
usv: matrix to reduce given in SVD form with the spectrum s in
increasing order.
num_rows: number of rows in the output matrix.
num_cols: number of columns in the output matrix.
Returns:
A resized version of (u, s, v) whose non zero singular values will be
identical to the largest singular values in s.
"""
u, s, v = usv
k = min(num_rows, num_cols)
u_random_proj = transform.resize(u[:, :k], (num_rows, k))
v_random_proj = transform.resize(v[:k, :], (k, num_cols))
u_random_proj_orth = _closest_column_orthogonal_matrix(u_random_proj)
v_random_proj_orth = _closest_column_orthogonal_matrix(v_random_proj.T).T
return np.matmul(u_random_proj_orth,
np.matmul(np.diag(s[::-1][:k]), v_random_proj_orth)) |
java | public static Class<?> getCollectionFieldType(Field collectionField, int nestingLevel) {
return ResolvableType.forField(collectionField).getNested(nestingLevel).asCollection().resolveGeneric();
} |
java | public static void logNoMoreArticles(final Logger logger,
final ArchiveDescription archive)
{
logger.logMessage(Level.INFO, "Archive " + archive.toString()
+ " contains no more articles");
} |
java | public static void initiateInstance(final String title, final String styleName) {
INSTANCE = new ColorPicker(styleName, title, null);
} |
java | private synchronized Object invokeTarget(Object base, Object[] pars)
throws Throwable {
Reflect.logInvokeMethod("Invoking method (entry): ", this, pars);
List<Object> params = collectParamaters(base, pars);
Reflect.logInvokeMethod("Invoking method (after): ", this, params);
if (getParameterCount() > 0)
return getMethodHandle().invokeWithArguments(params);
if (isStatic() || this instanceof ConstructorInvocable)
return getMethodHandle().invoke();
return getMethodHandle().invoke(params.get(0));
} |
java | public List<Presence> getAvailablePresences(BareJid bareJid) {
List<Presence> allPresences = getAllPresences(bareJid);
List<Presence> res = new ArrayList<>(allPresences.size());
for (Presence presence : allPresences) {
if (presence.isAvailable()) {
// No need to clone presence here, getAllPresences already returns clones
res.add(presence);
}
}
return res;
} |
java | private <T> Observable<PollingState<T>> updateStateFromAzureAsyncOperationHeaderOnPostOrDeleteAsync(final PollingState<T> pollingState) {
return pollAsync(pollingState.azureAsyncOperationHeaderLink(), pollingState.loggingContext())
.flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() {
@Override
public Observable<PollingState<T>> call(Response<ResponseBody> response) {
final AzureAsyncOperation asyncOperation;
try {
asyncOperation = AzureAsyncOperation.fromResponse(restClient().serializerAdapter(), response);
} catch (CloudException exception) {
return Observable.error(exception);
}
pollingState.withStatus(asyncOperation.status());
pollingState.withErrorBody(asyncOperation.getError());
pollingState.withResponse(response);
try {
T resource = restClient().serializerAdapter().deserialize(asyncOperation.rawString(), pollingState.resourceType());
pollingState.withResource(resource);
} catch (IOException e) {
// Ignore and let resource be null
}
return Observable.just(pollingState);
}
});
} |
java | public static byte[] i2cWriteRequest(byte slaveAddress, byte... bytesToWrite) {
byte[] result = new byte[bytesToWrite.length * 2 + 5];
result[0] = START_SYSEX;
result[1] = I2C_REQUEST;
result[2] = slaveAddress;
result[3] = I2C_WRITE;
//TODO replace I2C_WRITE with generated slave address (MSB) to support 10-bit mode
// see https://github.com/firmata/protocol/blob/master/i2c.md
for (int x = 0; x < bytesToWrite.length; x++) {
int skipIndex = x * 2 + 4;
result[skipIndex] = (byte) (bytesToWrite[x] & 0x7F);
result[skipIndex + 1] = (byte) (((bytesToWrite[x] & 0xFF) >>> 7) & 0x7F);
}
result[result.length - 1] = END_SYSEX;
return result;
} |
python | def _init_map(self):
"""stub"""
self.my_osid_object_form._my_map['zoneConditions'] = \
self._zone_conditions_metadata['default_object_values'][0]
self.my_osid_object_form._my_map['coordinateConditions'] = \
self._coordinate_conditions_metadata['default_object_values'][0]
self.my_osid_object_form._my_map['spatialUnitConditions'] = \
self._spatial_unit_conditions_metadata['default_object_values'][0] |
java | public int bump(CmsUUID id) {
CmsDetailPageInfo info = m_infoById.get(id);
if (info == null) {
throw new IllegalArgumentException();
}
String type = info.getType();
List<CmsDetailPageInfo> infos = m_map.get(type);
int oldPos = infos.indexOf(info);
infos.remove(oldPos);
infos.add(0, info);
return oldPos;
} |
java | private static void setupContextClassLoader(GroovyShell shell) {
final Thread current = Thread.currentThread();
class DoSetContext implements PrivilegedAction {
ClassLoader classLoader;
public DoSetContext(ClassLoader loader) {
classLoader = loader;
}
public Object run() {
current.setContextClassLoader(classLoader);
return null;
}
}
AccessController.doPrivileged(new DoSetContext(shell.getClassLoader()));
} |
java | public static <K> void validateConfiguredTypes(CacheConfig cacheConfig, K key) throws ClassCastException {
Class keyType = cacheConfig.getKeyType();
validateConfiguredKeyType(keyType, key);
} |
python | def send_email_sns(sender, subject, message, topic_ARN, image_png):
"""
Sends notification through AWS SNS. Takes Topic ARN from recipients.
Does not handle access keys. Use either
1/ configuration file
2/ EC2 instance profile
See also https://boto3.readthedocs.io/en/latest/guide/configuration.html.
"""
from boto3 import resource as boto3_resource
sns = boto3_resource('sns')
topic = sns.Topic(topic_ARN[0])
# Subject is max 100 chars
if len(subject) > 100:
subject = subject[0:48] + '...' + subject[-49:]
response = topic.publish(Subject=subject, Message=message)
logger.debug(("Message sent to SNS.\nMessageId: {},\nRequestId: {},\n"
"HTTPSStatusCode: {}").format(response['MessageId'],
response['ResponseMetadata']['RequestId'],
response['ResponseMetadata']['HTTPStatusCode'])) |
python | def list_ikepolicies(self, retrieve_all=True, **_params):
"""Fetches a list of all configured IKEPolicies for a project."""
return self.list('ikepolicies', self.ikepolicies_path, retrieve_all,
**_params) |
python | def user_process(self, input_data):
"""
:param input_data:
:return: output_data, list of next model instance. For example, if
model is :class:`~crawl_zillow.model.State`, then next model is
:class:`~crawl_zillow.model.County`.
"""
url = input_data.doc.url
self.logger.info("Crawl %s ." % url, 1)
output_data = OutputData(data=list())
try:
html = get_html(
url,
wait_time=Config.Crawler.wait_time,
driver=self._selenium_driver,
**input_data.get_html_kwargs)
# some this model's attributes will also available in next model
d = input_data.doc.to_dict()
del d[primary_key]
del d[status_key]
del d[edit_at_key]
del d[n_children_key]
try:
for href, name in htmlparser.get_items(html):
data = {
primary_key: href,
self.next_model_col_name: name,
}
data.update(d)
next_model_instance = self.next_model(**data)
output_data.data.append(next_model_instance)
self.logger.info(Status.S50_Finished.description, 1)
output_data.status = Status.S50_Finished.id
except Exception as e:
raise exc.ParseError
except exc.CaptchaError as e:
time.sleep(10.0) # Wait for 10 seconds to solve Captcha
self.logger.info(Status.S20_WrongPage.description, 1)
output_data.status = Status.S20_WrongPage.id
output_data.errors = e
except exc.WrongHtmlError as e:
self.logger.info(Status.S20_WrongPage.description, 1)
output_data.status = Status.S20_WrongPage.id
output_data.errors = e
except exc.ParseError as e:
self.logger.info(Status.S30_ParseError.description, 1)
output_data.status = Status.S30_ParseError.id
output_data.errors = e
except exc.ServerSideError as e:
self.logger.info(Status.S60_ServerSideError.description, 1)
output_data.status = Status.S60_ServerSideError.id
output_data.errors = e
except Exception as e:
self.logger.info(Status.S10_HttpError.description, 1)
output_data.status = Status.S10_HttpError.id
output_data.errors = e
# output_data.data = output_data.data[:2] # COMMENT OUT IN PROD
return output_data |
java | public Data readAsData(long sequence) {
checkReadSequence(sequence);
Object rbItem = readOrLoadItem(sequence);
return serializationService.toData(rbItem);
} |
python | def _set_platform_specific_keyboard_shortcuts(self):
"""
QtDesigner does not support QKeySequence::StandardKey enum based default keyboard shortcuts.
This means that all default key combinations ("Save", "Quit", etc) have to be defined in code.
"""
self.action_new_phrase.setShortcuts(QKeySequence.New)
self.action_save.setShortcuts(QKeySequence.Save)
self.action_close_window.setShortcuts(QKeySequence.Close)
self.action_quit.setShortcuts(QKeySequence.Quit)
self.action_undo.setShortcuts(QKeySequence.Undo)
self.action_redo.setShortcuts(QKeySequence.Redo)
self.action_cut_item.setShortcuts(QKeySequence.Cut)
self.action_copy_item.setShortcuts(QKeySequence.Copy)
self.action_paste_item.setShortcuts(QKeySequence.Paste)
self.action_delete_item.setShortcuts(QKeySequence.Delete)
self.action_configure_autokey.setShortcuts(QKeySequence.Preferences) |
java | void submitForm(CmsForm formParam, final Map<String, String> fieldValues, Set<String> editedFields) {
String modelGroupId = null;
if (CmsInheritanceContainerEditor.getInstance() != null) {
CmsInheritanceContainerEditor.getInstance().onSettingsEdited();
}
if (m_contextsWidget != null) {
String newTemplateContexts = m_contextsWidget.getFormValueAsString();
if ((newTemplateContexts == null) || "".equals(newTemplateContexts)) {
newTemplateContexts = CmsTemplateContextInfo.EMPTY_VALUE;
// translate an empty selection to "none"
}
fieldValues.put(CmsTemplateContextInfo.SETTING, newTemplateContexts);
}
final boolean hasFormatterChanges;
if (m_formatterSelect != null) {
fieldValues.put(
CmsFormatterConfig.getSettingsKeyForContainer(m_containerId),
m_formatterSelect.getFormValueAsString());
hasFormatterChanges = true;
} else {
hasFormatterChanges = false;
}
if (m_createNewCheckBox != null) {
m_elementWidget.setCreateNew(m_createNewCheckBox.isChecked());
fieldValues.put(CmsContainerElement.CREATE_AS_NEW, Boolean.toString(m_createNewCheckBox.isChecked()));
}
if (m_modelGroupSelect != null) {
GroupOption group = GroupOption.valueOf(m_modelGroupSelect.getFormValueAsString());
switch (group) {
case disabled:
fieldValues.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.noGroup.name());
fieldValues.put(CmsContainerElement.USE_AS_COPY_MODEL, Boolean.toString(false));
break;
case copy:
fieldValues.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.isModelGroup.name());
fieldValues.put(CmsContainerElement.USE_AS_COPY_MODEL, Boolean.toString(true));
break;
case reuse:
fieldValues.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.isModelGroup.name());
fieldValues.put(CmsContainerElement.USE_AS_COPY_MODEL, Boolean.toString(false));
break;
default:
break;
}
if (group != GroupOption.disabled) {
modelGroupId = CmsContainerpageController.getServerId(m_elementBean.getClientId());
}
}
if ((m_modelGroupBreakUp != null) && m_modelGroupBreakUp.isChecked()) {
fieldValues.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.noGroup.name());
}
final Map<String, String> filteredFieldValues = new HashMap<String, String>();
for (Map.Entry<String, String> entry : fieldValues.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if ((value != null) && (value.length() > 0)) {
filteredFieldValues.put(key, value);
}
}
final String changeModelGroupId = modelGroupId;
m_controller.reloadElementWithSettings(
m_elementWidget,
m_elementBean.getClientId(),
filteredFieldValues,
new I_CmsSimpleCallback<CmsContainerPageElementPanel>() {
public void execute(CmsContainerPageElementPanel result) {
if (isTemplateContextChanged()) {
// if the context multiselect box isn't displayed, of course it can't change values,
// and this code won't be executed.
CmsContainerpageController.get().handleChangeTemplateContext(
result,
filteredFieldValues.get(CmsTemplateContextInfo.SETTING));
}
if (hasFormatterChanges) {
updateCss();
}
if (result.getElement().getInnerHTML().contains(CmsGwtConstants.FORMATTER_RELOAD_MARKER)
&& !CmsContainerpageController.get().isGroupcontainerEditing()) {
CmsContainerpageController.get().reloadPage();
}
if (m_modelGroupSelect != null) {
m_controller.setModelGroupElementId(changeModelGroupId);
}
}
});
} |
java | public static BufferedImage resize(BufferedImage src, int targetSize,
BufferedImageOp... ops) throws IllegalArgumentException,
ImagingOpException {
return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetSize,
targetSize, ops);
} |
python | def models_get(self, resource_url):
"""Get handle for model resource at given Url.
Parameters
----------
resource_url : string
Url for subject resource at SCO-API
Returns
-------
models.ModelHandle
Handle for local copy of subject resource
"""
# Get resource directory, Json representation, active flag, and cache id
obj_dir, obj_json, is_active, cache_id = self.get_object(resource_url)
# Create model handle.
model = ModelHandle(obj_json)
# Add resource to cache if not exists
if not cache_id in self.cache:
self.cache_add(resource_url, cache_id)
# Return subject handle
return model |
java | PageFlowController popUntil( HttpServletRequest request, Class stopAt, boolean onlyIfPresent )
{
if (onlyIfPresent && lastIndexOf(stopAt) == -1) {
return null;
}
while ( ! isEmpty() )
{
PageFlowController popped = pop( request ).getPageFlow();
if ( popped.getClass().equals( stopAt ) )
{
//
// If we've popped everything from the stack, remove the stack attribute from the session.
//
if ( isEmpty() ) destroy( request );
return popped;
}
else
{
//
// We're discarding the popped page flow. Invoke its destroy() callback, unless it's longLived.
//
if ( ! popped.isLongLived() ) popped.destroy( request.getSession( false ) );
}
}
destroy( request ); // we're empty -- remove the attribute from the session.
return null;
} |
java | public static String unescape(String input, char escapeCharacter) {
if (input == null) {
return null;
}
StringBuilder builder = new StringBuilder();
for (int i = 0; i < input.length(); ) {
if (input.charAt(i) == escapeCharacter) {
builder.append(input.charAt(i + 1));
i = i + 2;
} else {
builder.append(input.charAt(i));
i++;
}
}
return builder.toString();
} |
java | @Transactional
@Override
public PrincipalUser findUserByUsername(String userName) {
requireNotDisposed();
requireArgument(userName != null && !userName.trim().isEmpty(), "User name cannot be null or empty.");
PrincipalUser result = PrincipalUser.findByUserName(emf.get(), userName);
_logger.debug("Retrieving user having username {} from db.", userName);
return result;
} |
python | async def _read_messages(self):
"""Process messages received on the WebSocket connection.
Iteration terminates when the client is stopped or it disconnects.
"""
while not self._stopped and self._websocket is not None:
async for message in self._websocket:
if message.type == aiohttp.WSMsgType.TEXT:
payload = message.json()
event = payload.pop("type", "Unknown")
self._dispatch_event(event, data=payload)
elif message.type == aiohttp.WSMsgType.ERROR:
break |
java | public Double getDouble(String column) {
Number n = getNumber(column);
return n != null ? n.doubleValue() : null;
} |
java | public static DataSet newDataSet(final String keyColumnName, final String valueColumnName, final Map<?, ?> m) {
final List<Object> keyColumn = new ArrayList<>(m.size());
final List<Object> valueColumn = new ArrayList<>(m.size());
for (Map.Entry<?, ?> entry : m.entrySet()) {
keyColumn.add(entry.getKey());
valueColumn.add(entry.getValue());
}
final List<String> columnNameList = N.asList(keyColumnName, valueColumnName);
final List<List<Object>> columnList = N.asList(keyColumn, valueColumn);
return newDataSet(columnNameList, columnList);
} |
python | def ng_set_ctrl_property(self, element, prop, value):
"""
:Description: Will set value of property of element's controller.
:Warning: This will only work for angular.js 1.x.
:Warning: Requires angular debugging to be enabled.
:param element: Element for browser instance to target.
:type element: WebElement
:param prop: Property of element's angular scope to target.
:type prop: string
:example: 'messages.total'
:param value: Value to specify to angular element's controller's property.
:type value: None, bool, int, float, string
"""
self.browser.execute_script(
'angular.element(arguments[0]).controller()%s = %s;' % (
self.__d2b_notation(prop=prop), self.__type2js(value=value)
), element) |
java | @SuppressWarnings("PMD.PreserveStackTrace")
public Object extractObject(ObjectToJsonConverter pConverter, Object pValue,
Stack<String> pPathParts,boolean jsonify) throws AttributeNotFoundException {
CompositeData cd = (CompositeData) pValue;
String pathPart = pPathParts.isEmpty() ? null : pPathParts.pop();
if (pathPart != null) {
try {
return pConverter.extractObject(cd.get(pathPart), pPathParts, jsonify);
} catch (InvalidKeyException exp) {
return pConverter.getValueFaultHandler().handleException(new AttributeNotFoundException("Invalid path '" + pathPart + "'"));
}
} else {
return jsonify ? extractCompleteCdAsJson(pConverter, cd, pPathParts) : cd;
}
} |
python | def seek(self, offset: int = 0, *args, **kwargs):
"""
A shortcut to ``self.fp.seek``.
"""
return self.fp.seek(offset, *args, **kwargs) |
python | def Run(self, args):
"""Reads a buffer on the client and sends it to the server."""
# Make sure we limit the size of our output
if args.length > constants.CLIENT_MAX_BUFFER_SIZE:
raise RuntimeError("Can not read buffers this large.")
data = vfs.ReadVFS(args.pathspec, args.offset, args.length)
digest = hashlib.sha256(data).digest()
# Now report the hash of this blob to our flow as well as the offset and
# length.
self.SendReply(
rdf_client.BufferReference(
offset=args.offset, length=len(data), data=digest)) |
java | public void marshall(UpdateIndexingConfigurationRequest updateIndexingConfigurationRequest, ProtocolMarshaller protocolMarshaller) {
if (updateIndexingConfigurationRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(updateIndexingConfigurationRequest.getThingIndexingConfiguration(), THINGINDEXINGCONFIGURATION_BINDING);
protocolMarshaller.marshall(updateIndexingConfigurationRequest.getThingGroupIndexingConfiguration(), THINGGROUPINDEXINGCONFIGURATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | @Override
public Stream<Chunk<byte[], BytesReference>> chunks() {
Iterator<Chunk<byte[], BytesReference>> iterator = new Iterator<Chunk<byte[], BytesReference>>() {
Chunk<byte[], BytesReference> nextData = null;
@Override
public boolean hasNext() {
if (nextData != null) {
return true;
} else {
try {
nextData = readChunk();
return nextData != null;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@Override
public Chunk<byte[], BytesReference> next() {
if (nextData != null || hasNext()) {
Chunk<byte[], BytesReference> data = nextData;
nextData = null;
return data;
} else {
throw new NoSuchElementException();
}
}
};
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator,
Spliterator.ORDERED | Spliterator.NONNULL), false);
} |
java | @Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case XtypePackage.XFUNCTION_TYPE_REF__PARAM_TYPES:
return ((InternalEList<?>)getParamTypes()).basicRemove(otherEnd, msgs);
case XtypePackage.XFUNCTION_TYPE_REF__RETURN_TYPE:
return basicSetReturnType(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
} |
python | def unders_to_dashes_in_keys(self) -> None:
"""Replaces underscores with dashes in key names.
For each attribute in a mapping, this replaces any underscores \
in its keys with dashes. Handy because Python does not \
accept dashes in identifiers, while some YAML-based formats use \
dashes in their keys.
"""
for key_node, _ in self.yaml_node.value:
key_node.value = key_node.value.replace('_', '-') |
python | def MakeProto():
"""Make sure our protos have been compiled to python libraries."""
# Start running from one directory above the grr directory which is found by
# this scripts's location as __file__.
cwd = os.path.dirname(os.path.abspath(__file__))
# Find all the .proto files.
protos_to_compile = []
for (root, _, files) in os.walk(cwd):
for filename in files:
full_filename = os.path.join(root, filename)
if full_filename.endswith(".proto"):
proto_stat = os.stat(full_filename)
pb2_path = full_filename.rsplit(".", 1)[0] + "_pb2.py"
try:
pb2_stat = os.stat(pb2_path)
if pb2_stat.st_mtime >= proto_stat.st_mtime:
continue
except (OSError, IOError):
pass
protos_to_compile.append(full_filename)
if protos_to_compile:
# Find the protoc compiler.
protoc = os.environ.get("PROTOC", "protoc")
try:
output = subprocess.check_output([protoc, "--version"])
except (IOError, OSError):
raise RuntimeError("Unable to launch %s protoc compiler. Please "
"set the PROTOC environment variable.", protoc)
if b"3.6.1" not in output:
raise RuntimeError("Incompatible protoc compiler detected. "
"We need 3.6.1 not %s" % output)
for proto in protos_to_compile:
command = [
protoc,
# Write the python files next to the .proto files.
"--python_out",
ROOT,
"--proto_path=%s" % ROOT,
proto
]
print(
"Compiling %s with (cwd: %s): %s" % (proto, ROOT, " ".join(command)))
# The protoc compiler is too dumb to deal with full paths - it expects a
# relative path from the current working directory.
subprocess.check_call(command, cwd=ROOT) |
python | def element_href_use_filter(name, _filter):
""" Get element href using filter
Filter should be a valid entry point value, ie host, router, network,
single_fw, etc
:param name: name of element
:param _filter: filter type, unknown filter will result in no matches
:return: element href (if found), else None
"""
if name and _filter:
element = fetch_meta_by_name(name, filter_context=_filter)
if element.json:
return element.json.pop().get('href') |
java | protected void findRoot(Collection<CmsResource> resources) throws CmsException {
m_commonRoot = getCommonSite(resources);
String commonPath = getCommonAncestorPath(resources);
try {
m_rootResource = m_cms.readResource(m_commonRoot, m_filter);
} catch (CmsVfsResourceNotFoundException e) {
String currentPath = commonPath;
String lastWorkingPath = null;
while (m_cms.existsResource(currentPath, m_filter)) {
lastWorkingPath = currentPath;
currentPath = CmsResource.getParentFolder(currentPath);
}
m_rootResource = m_cms.readResource(lastWorkingPath, m_filter);
m_commonRoot = lastWorkingPath;
}
m_knownResources.add(m_rootResource);
} |
java | private List<String> pruneSuggestions(final List<String> suggestions) {
List<String> prunedSuggestions = new ArrayList<>(suggestions.size());
for (final String suggestion : suggestions) {
if (suggestion.indexOf(' ') == -1) {
prunedSuggestions.add(suggestion);
} else {
String[] complexSug = suggestion.split(" ");
if (!bannedSuffixes.contains(complexSug[1])) {
prunedSuggestions.add(suggestion);
}
}
}
return prunedSuggestions;
} |
python | def _InvokeGitkitApi(self, method, params=None, need_service_account=True):
"""Invokes Gitkit API, with optional access token for service account.
Args:
method: string, the api method name.
params: dict of optional parameters for the API.
need_service_account: false if service account is not needed.
Raises:
GitkitClientError: if the request is bad.
GitkitServerError: if Gitkit can not handle the request.
Returns:
API response as dict.
"""
body = simplejson.dumps(params) if params else None
req = urllib_request.Request(self.google_api_url + method)
req.add_header('Content-type', 'application/json')
if need_service_account:
if self.credentials:
access_token = self.credentials.get_access_token().access_token
elif self.service_account_email and self.service_account_key:
access_token = self._GetAccessToken()
else:
raise errors.GitkitClientError('Missing service account credentials')
req.add_header('Authorization', 'Bearer ' + access_token)
try:
binary_body = body.encode('utf-8') if body else None
raw_response = urllib_request.urlopen(req, binary_body).read()
except urllib_request.HTTPError as err:
if err.code == 400:
raw_response = err.read()
else:
raise
return self._CheckGitkitError(raw_response) |
java | public VarBindingDef bind( VarDef varDef, VarValueDef valueDef)
{
if( valueDef != null && !varDef.isApplicable( valueDef))
{
throw new IllegalArgumentException( "Value=" + valueDef + " is not defined for var=" + varDef);
}
varDef_ = varDef;
valueDef_ = valueDef;
effCondition_ = null;
return this;
} |
java | public ApiResponse<List<CharacterContractsBidsResponse>> getCharactersCharacterIdContractsContractIdBidsWithHttpInfo(
Integer characterId, Integer contractId, String datasource, String ifNoneMatch, String token)
throws ApiException {
com.squareup.okhttp.Call call = getCharactersCharacterIdContractsContractIdBidsValidateBeforeCall(characterId,
contractId, datasource, ifNoneMatch, token, null);
Type localVarReturnType = new TypeToken<List<CharacterContractsBidsResponse>>() {
}.getType();
return apiClient.execute(call, localVarReturnType);
} |
java | public static <E> Object result(final Iterable<E> iterable, final Predicate<E> pred) {
for (E element : iterable) {
if (pred.test(element)) {
if (element instanceof Map.Entry) {
if (((Map.Entry) element).getValue() instanceof Supplier) {
return ((Supplier) ((Map.Entry) element).getValue()).get();
}
return ((Map.Entry) element).getValue();
}
return element;
}
}
return null;
} |
java | public Matrix4f translation(Vector3fc offset) {
return translation(offset.x(), offset.y(), offset.z());
} |
java | public static P<String> fullTextMatch(String configuration,final String value){
return fullTextMatch(configuration,false, value);
} |
python | def get_field_kwargs(self, field_name, model_field):
"""
Creates a default instance of a basic non-relational field.
"""
kwargs = {}
validator_kwarg = list(model_field.validators)
# The following will only be used by ModelField classes.
# Gets removed for everything else.
kwargs['model_field'] = model_field
if model_field.verbose_name and needs_label(model_field, field_name):
kwargs['label'] = capfirst(model_field.verbose_name)
if model_field.help_text:
kwargs['help_text'] = model_field.help_text
max_digits = getattr(model_field, 'max_digits', None)
if max_digits is not None:
kwargs['max_digits'] = max_digits
decimal_places = getattr(model_field, 'decimal_places', None)
if decimal_places is not None:
kwargs['decimal_places'] = decimal_places
if isinstance(model_field, models.TextField):
kwargs['style'] = {'base_template': 'textarea.html'}
if isinstance(model_field, models.AutoField) \
or not model_field.editable:
# If this field is read-only, then return early.
# Further keyword arguments are not valid.
kwargs['read_only'] = True
return kwargs
if model_field.has_default or model_field.blank or model_field.null:
kwargs['required'] = False
if model_field.null and not isinstance(model_field,
models.NullBooleanField):
kwargs['allow_null'] = True
if model_field.blank and (
isinstance(model_field, models.CharField) or
isinstance(model_field, models.TextField) or
isinstance(model_field, columns.Text)
):
kwargs['allow_blank'] = True
if isinstance(model_field, models.FilePathField):
kwargs['path'] = model_field.path
if model_field.match is not None:
kwargs['match'] = model_field.match
if model_field.recursive is not False:
kwargs['recursive'] = model_field.recursive
if model_field.allow_files is not True:
kwargs['allow_files'] = model_field.allow_files
if model_field.allow_folders is not False:
kwargs['allow_folders'] = model_field.allow_folders
if model_field.choices:
# If this model field contains choices, then return early.
# Further keyword arguments are not valid.
kwargs['choices'] = model_field.choices
return kwargs
# Our decimal validation is handled in the field code,
# not validator code.
# (In Django 1.9+ this differs from previous style)
if isinstance(model_field, models.DecimalField) and DecimalValidator:
validator_kwarg = [
validator for validator in validator_kwarg
if not isinstance(validator, DecimalValidator)
]
# Ensure that max_length is passed explicitly as a keyword arg,
# rather than as a validator.
max_length = getattr(model_field, 'max_length', None)
if max_length is not None and (
isinstance(model_field, models.CharField) or
isinstance(model_field, models.TextField)):
kwargs['max_length'] = max_length
validator_kwarg = [
validator for validator in validator_kwarg
if not isinstance(validator, validators.MaxLengthValidator)
]
# Ensure that min_length is passed explicitly as a keyword arg,
# rather than as a validator.
min_length = next((
validator.limit_value for validator in validator_kwarg
if isinstance(validator, validators.MinLengthValidator)
), None)
if min_length is not None and isinstance(model_field,
models.CharField):
kwargs['min_length'] = min_length
validator_kwarg = [
validator for validator in validator_kwarg
if not isinstance(validator, validators.MinLengthValidator)
]
# Ensure that max_value is passed explicitly as a keyword arg,
# rather than as a validator.
max_value = next((
validator.limit_value for validator in validator_kwarg
if isinstance(validator, validators.MaxValueValidator)
), None)
if max_value is not None and isinstance(model_field,
NUMERIC_FIELD_TYPES):
kwargs['max_value'] = max_value
validator_kwarg = [
validator for validator in validator_kwarg
if not isinstance(validator, validators.MaxValueValidator)
]
# Ensure that max_value is passed explicitly as a keyword arg,
# rather than as a validator.
min_value = next((
validator.limit_value for validator in validator_kwarg
if isinstance(validator, validators.MinValueValidator)
), None)
if min_value is not None and isinstance(model_field,
NUMERIC_FIELD_TYPES):
kwargs['min_value'] = min_value
validator_kwarg = [
validator for validator in validator_kwarg
if not isinstance(validator, validators.MinValueValidator)
]
# URLField does not need to include the URLValidator argument,
# as it is explicitly added in.
if isinstance(model_field, models.URLField):
validator_kwarg = [
validator for validator in validator_kwarg
if not isinstance(validator, validators.URLValidator)
]
# EmailField does not need to include the validate_email argument,
# as it is explicitly added in.
if isinstance(model_field, models.EmailField):
validator_kwarg = [
validator for validator in validator_kwarg
if validator is not validators.validate_email
]
# SlugField do not need to include the 'validate_slug' argument,
if isinstance(model_field, models.SlugField):
validator_kwarg = [
validator for validator in validator_kwarg
if validator is not validators.validate_slug
]
# IPAddressField do not need to include the 'validate_ipv46_address'
# argument,
if isinstance(model_field, models.GenericIPAddressField):
validator_kwarg = [
validator for validator in validator_kwarg
if validator is not validators.validate_ipv46_address
]
if getattr(model_field, 'unique', False):
warnings.warn(
'UniqueValidator is currently not supported '
'in DjangoCassandraSerializer'
)
if validator_kwarg:
kwargs['validators'] = validator_kwarg
return kwargs |
python | def __dict_to_pod_spec(spec):
'''
Converts a dictionary into kubernetes V1PodSpec instance.
'''
spec_obj = kubernetes.client.V1PodSpec()
for key, value in iteritems(spec):
if hasattr(spec_obj, key):
setattr(spec_obj, key, value)
return spec_obj |
java | public ModuleInfoList filter(final ModuleInfoFilter filter) {
final ModuleInfoList moduleInfoFiltered = new ModuleInfoList();
for (final ModuleInfo resource : this) {
if (filter.accept(resource)) {
moduleInfoFiltered.add(resource);
}
}
return moduleInfoFiltered;
} |
java | public static int findFirstNotOf(String container, String chars, int begin){
//find the first occurrence of characters not in the charSeq from begin forward
for (int i = begin; i < container.length() && i >=0; ++i)
if (!chars.contains("" + container.charAt(i)))
return i;
return -1;
} |
python | def set_burnstages_upgrade_massive(self):
'''
Outputs burnign stages as done in burningstages_upgrade (nugridse)
'''
burn_info=[]
burn_mini=[]
for i in range(len(self.runs_H5_surf)):
sefiles=se(self.runs_H5_out[i])
burn_info.append(sefiles.burnstage_upgrade())
mini=sefiles.get('mini')
#zini=sefiles.get('zini')
burn_mini.append(mini)
for i in range(len(self.runs_H5_surf)):
print 'Following returned for each initial mass'
print '[burn_cycles,burn_ages, burn_abun, burn_type,burn_lifetime]'
print '----Mini: ',burn_mini[i],'------'
print burn_info[i] |
java | public List<GitlabGroupMember> getGroupMembers(Integer groupId) {
String tailUrl = GitlabGroup.URL + "/" + groupId + GitlabGroupMember.URL + PARAM_MAX_ITEMS_PER_PAGE;
return retrieve().getAll(tailUrl, GitlabGroupMember[].class);
} |
java | @Provides protected RendererAdapter<TvShowViewModel> provideTvShowRendererAdapter(
LayoutInflater layoutInflater,
TvShowCollectionRendererBuilder tvShowCollectionRendererBuilder,
TvShowCollectionViewModel tvShowCollectionViewModel) {
return new RendererAdapter<TvShowViewModel>(layoutInflater, tvShowCollectionRendererBuilder,
tvShowCollectionViewModel);
} |
java | public static int getHFTACount(File fileLocation) {
Document qtree = getQTree(fileLocation);
int count;
count = qtree.getElementsByTagName("HFTA").getLength();
return count;
} |
python | def fetch(self, keyDict):
"""Like update(), but for retrieving values.
"""
for key in keyDict.keys():
keyDict[key] = self.tbl[key] |
python | def _delete_collection(self, **kwargs):
"""wrapped with delete_collection, override that in a sublcass to customize """
error_message = "The request must include \"requests_params\": {\"params\": \"options=<glob pattern>\"} as kwarg"
try:
if kwargs['requests_params']['params'].split('=')[0] != 'options':
raise MissingRequiredRequestsParameter(error_message)
except KeyError:
raise
requests_params = self._handle_requests_params(kwargs)
delete_uri = self._meta_data['uri']
session = self._meta_data['bigip']._meta_data['icr_session']
session.delete(delete_uri, **requests_params) |
java | static public ObjectName registerMBean(final String serviceName,
final String nameName,
final Object theMbean) {
final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = getMBeanName(serviceName, nameName);
try {
mbs.registerMBean(theMbean, name);
return name;
} catch (InstanceAlreadyExistsException ie) {
// Ignore if instance already exists
} catch (Exception e) {
e.printStackTrace();
}
return null;
} |
java | public void push(String name, String value, long timestamp) throws IOException {
graphiteSender.send(name, value, timestamp);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.