language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def generate_user(self, subid=None):
'''generate a new user on the filesystem, still session based so we
create a new identifier. This function is called from the users new
entrypoint, and it assumes we want a user generated with a token.
since we don't have a database proper, we write the fol... |
java | private void addNewArtifacts(List<ArtifactoryRepo> enabledRepos) {
long start = System.currentTimeMillis();
int count = 0;
for (ArtifactoryRepo repo : enabledRepos) {
for (BinaryArtifact artifact : nullSafe(artifactoryClient.getArtifacts(repo.getInstanceUrl(), repo.getRepoName(... |
java | public String getSFieldProperty(String strFieldName)
{
String strValue = super.getSFieldProperty(strFieldName);
if (strValue == null)
if (this.getParentScreen() != null)
if (DBConstants.SUBMIT.equalsIgnoreCase(this.getParentScreen().getProperty(DBParams.COMMAND)))
... |
java | public ParameterBuilder<T> defaultOsgiConfigProperty(String value) {
if (value == null || !OSGI_CONFIG_PROPERTY_PATTERN.matcher(value).matches()) {
throw new IllegalArgumentException("Invalid value: " + value);
}
this.defaultOsgiConfigProperty = value;
return this;
} |
python | def unlock_variable(self, key, access_key, force=False):
"""Unlocks a global variable
:param key: the key of the global variable to be unlocked
:param access_key: the access key to be able to unlock the global variable
:param force: if the variable should be unlocked forcefully
... |
java | protected P upConvertPayload(GenericRecord inputRecord) throws DataConversionException {
try {
Schema payloadSchema = getPayloadSchema(inputRecord);
// Set writer schema
latestPayloadReader.setSchema(payloadSchema);
byte[] payloadBytes = getPayloadBytes(inputRecord);
Decoder decoder =... |
python | def l2n(l, c):
"host to network long"
c = []
c.append(int((l >> 24) & U32(0xFF)))
c.append(int((l >> 16) & U32(0xFF)))
c.append(int((l >> 8) & U32(0xFF)))
c.append(int((l ) & U32(0xFF)))
return c |
python | def list_services(self, limit=None, marker=None):
"""List CDN services."""
return self._services_manager.list(limit=limit, marker=marker) |
java | public final void mDECR() throws RecognitionException {
try {
int _type = DECR;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:191:6: ( '--' )
// src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:191:8: '--'
{
match("--"); if (state.failed) ret... |
python | def delete(self, key):
"""Remove the given key from the cache."""
if not self.debug:
self.database.delete(self.make_key(key)) |
python | def random_draw(self, size=None):
"""Draw random samples of the hyperparameters.
Parameters
----------
size : None, int or array-like, optional
The number/shape of samples to draw. If None, only one sample is
returned. Default is None.
"""
... |
python | def stop(name):
"""
Stop project's container.
"""
container_name = get_container_name(name)
client = docker.Client()
try:
client.stop(container_name)
except docker.errors.NotFound:
pass
except docker.errors.APIError as error:
die(error.explanation.decode()) |
java | private void writeTheLines(final BufferedOutputStream stream)
throws IOException {
for (final User user : users) {
final String string = createLine(user);
stream.write(string.getBytes(StandardCharsets.UTF_8));
stream.write('\n');
}
} |
python | def _recurse(coreml_tree, scikit_tree, tree_id, node_id, scaling = 1.0, mode = 'regressor',
n_classes = 2, tree_index = 0):
"""Traverse through the tree and append to the tree spec.
"""
if not(HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disab... |
java | public static void setAppLaunchCount(Context context, long appLaunchCount) {
SharedPreferences prefs = getSharedPreferences(context);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putLong(PREF_KEY_APP_LAUNCH_COUNT, appLaunchCount);
prefsEditor.commit();
} |
java | @CanIgnoreReturnValue
@Override
public <T> T callWithTimeout(
Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible)
throws Exception {
checkNotNull(callable);
checkNotNull(timeoutUnit);
checkArgument(timeoutDuration > 0, "timeout must be positive: %s", ti... |
java | public static void configure(InputStream is) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
try {
String[] names = {
"ch.qos.logback.classic.LoggerContext",
"ch.qos.logback.classic.joran.JoranConfigurator",
};
for (String name : names) {
Class.forName(name, fal... |
java | public static <I> JMFileSubscriber<I> buildJsonStringFileSubscriber(
String filePath, Function<Object, String> toStringFunction) {
return new JMFileSubscriber<>(filePath, toStringFunction);
} |
python | def template_gen(method, lowcut, highcut, samp_rate, filt_order,
length, prepick, swin, process_len=86400,
all_horiz=False, delayed=True, plot=False, debug=0,
return_event=False, min_snr=None, parallel=False,
num_cores=False, save_progress=False, **kwa... |
java | @Override
public Retina retinaByName(String name) throws ApiException {
List<Retina> retinas = api.getRetinas(name);
if (retinas == null || retinas.size() == 0) {
return null;
}
return retinas.get(0);
} |
java | public static String toDebugString(String name, ByteBuffer byteBuffer) {
return name + "(pos:" + byteBuffer.position() + " lim:" + byteBuffer.limit()
+ " remain:" + byteBuffer.remaining() + " cap:" + byteBuffer.capacity() + ")";
} |
python | def open(self, baudrate=BAUDRATE, no_reader_thread=False):
"""
Opens the device.
:param baudrate: baudrate to use with the device
:type baudrate: int
:param no_reader_thread: whether or not to automatically start the
reader thread.
:type ... |
java | @Override
public String toApiImport(String name) {
if (!apiPackage().isEmpty())
return apiPackage();
else if (trimApiPaths)
return trimmedPaths.get(name).substring(1).replace('/', '.');
else
return super.toApiImport(name);
} |
java | @SuppressWarnings( "unchecked" )
private <T> Class<T> loadClassIfVisible( String className, ClassLoader classLoader )
{
try
{
Class<T> klass = (Class<T>) classLoader.loadClass( className );
return klass;
}
catch ( ClassNotFoundException e )
{
... |
python | def _get_blkid_type(self):
"""Retrieves the FS type from the blkid command."""
try:
result = _util.check_output_(['blkid', '-p', '-O', str(self.offset), self.get_raw_path()])
if not result:
return None
# noinspection PyTypeChecker
blkid_re... |
python | def get_user(uid):
"""Get an user by the UID.
:param str uid: UID to find
:return: the user
:rtype: User object
:raises ValueError: uid is not an integer
:raises KeyError: if user does not exist
"""
if db is not None:
try:
uid = uid.decode('utf-8')
except Att... |
java | protected void processIntersectionsRemoveHorizontal()
{
for (Iterator<Separator> hit = hsep.iterator(); hit.hasNext(); )
{
Separator hs = hit.next();
for (Separator vs : vsep)
{
if (hs.intersects(vs))
{
hit.remove();
... |
python | def get_tx_identity_info(self, tx_ac):
"""returns features associated with a single transcript.
:param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
:type tx_ac: str
# database output
-[ RECORD 1 ]--+-------------
tx_ac | NM_199425.2
al... |
java | private void visitComponentModel(final ObjectGraphNode node) {
ComponentModel model = (ComponentModel) node.getValue();
ComponentModel sharedModel = null;
List<Field> fieldList = ReflectionUtil.getAllFields(node.getValue(), true, false);
Field[] fields = fieldList.toArray(new Field[fieldList.size()]);
for (... |
python | def get_item(env, name, default=None):
""" Get an item from a dictionary, handling nested lookups with dotted notation.
Args:
env: the environment (dictionary) to use to look up the name.
name: the name to look up, in dotted notation.
default: the value to return if the name if not found.
Returns:
... |
python | def modify(*units):
"""set the unit defined by in-game tag with desired properties
NOTE: all units must be owned by the same player or the command fails."""
ret = []
for unit in units: # add one command for each attribute
for attr, idx in [("energy", 1), ("life", 2), ("shields", 3)]: # see debug... |
python | def convert_tdc_to_channel(channel):
''' Converts TDC words at a given channel to common TDC header (0x4).
'''
def f(value):
filter_func = logical_and(is_tdc_word, is_tdc_from_channel(channel))
select = filter_func(value)
value[select] = np.bitwise_and(value[select], 0x0FFFFFFF... |
python | def parse_psql_array(inp):
"""
:param inp: a string encoding an array
:return: the array of elements as represented by the input
"""
inp = unescape_sql(inp)
# Strip '{' and '}'
if inp.startswith("{") and inp.endswith("}"):
inp = inp[1:-1]
lst = []
elem = ""
in_quotes, es... |
java | public double[] generate(WindowType windowType, int nSamples) {
// generate nSamples window function values
// for index values 0 .. nSamples - 1
int m = nSamples / 2;
double r;
double pi = Math.PI;
double[] w = new double[nSamples];
switch (windowType) {
case BARTLETT: // Bart... |
java | protected void shutdown() throws InterruptedException {
if (m_deadConnectionFuture != null) {
m_deadConnectionFuture.cancel(false);
try {m_deadConnectionFuture.get();} catch (Throwable t) {}
}
if (m_topologyCheckFuture != null) {
m_topologyCheckFuture.cancel(f... |
python | def selected(self, new):
"""Set selected from list or instance of object or name.
Over-writes existing selection
"""
def preprocess(item):
if isinstance(item, str):
return self.options[item]
return item
items = coerce_to_list(new, preproce... |
python | def _add_message_field(self, field_name, value, params):
"""Converts a . delimitied field name to a message field in parameters.
This adds the field to the params dict, broken out so that message
parameters appear as sub-dicts within the outer param.
For example:
{'a.b.c': ['foo']}
becomes:
... |
python | def add_peer_to_group(self, group_jid, peer_jid):
"""
Adds someone to a group
:param group_jid: The JID of the group into which to add a user
:param peer_jid: The JID of the user to add
"""
log.info("[+] Requesting to add user {} into the group {}".format(peer_jid, group... |
python | def digest(algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY):
"""
<Purpose>
Provide the caller with the ability to create digest objects without having
to worry about crypto library availability or which library to use. The
caller also has the option of specifying which hash algorith... |
python | def load_window_settings(self, prefix, default=False, section='main'):
"""Load window layout settings from userconfig-based configuration
with *prefix*, under *section*
default: if True, do not restore inner layout"""
get_func = CONF.get_default if default else CONF.get
wind... |
java | public static Trades adaptTrades(WexTrade[] bTCETrades, CurrencyPair currencyPair) {
List<Trade> tradesList = new ArrayList<>();
long lastTradeId = 0;
for (WexTrade bTCETrade : bTCETrades) {
// Date is reversed order. Insert at index 0 instead of appending
long tradeId = bTCETrade.getTid();
... |
java | static TaskInstance createTaskInstance(Long taskId, String masterOwnerId,
String title, String comment, Instant due, Long userId, Long secondaryOwner)
throws ServiceException, DataAccessException {
CodeTimer timer = new CodeTimer("createTaskInstance()", true);
TaskTemplate task = TaskTem... |
java | public void comment(char[] ch, int start, int length) throws SAXException
{
if (m_firstTagNotEmitted)
{
flush();
}
m_handler.comment(ch, start, length);
} |
python | def handle_hooks(self, hooks, hook_type, *args):
'''
Processes hooks of the specified type.
:param hook_type: The type of hook, including ``before``, ``after``,
``on_error``, and ``on_route``.
:param \*args: Arguments to pass to the hooks.
'''
i... |
java | public void sendAndReceive(HttpMessage message, HttpRequestConfig requestConfig) throws IOException {
if (message == null) {
throw new IllegalArgumentException("Parameter message must not be null.");
}
if (requestConfig == null) {
throw new IllegalArgumentException("... |
java | protected void localRelease() {
super.localRelease();
_currentItem = null;
_currentIndex = -1;
_iterator = null;
_defaultText = null;
_renderState = INIT;
_haveKids = false;
_contentBuffer = null;
_padContext = null;
_ignoreNulls = false;
... |
python | def do_ignore(self, arg):
"""ignore bpnumber [count]
Set the ignore count for the given breakpoint number. If
count is omitted, the ignore count is set to 0. A breakpoint
becomes active when the ignore count is zero. When non-zero,
the count is decremented each time the breakp... |
java | private Object handleInvocation(ManagedBeanInvocation mbeanInvocation) {
Message response = endpointAdapter.handleMessage(endpointConfiguration.getMessageConverter()
.convertInbound(mbeanInvocation, endpointConfiguration, null));
ManagedBeanResult serviceResult = null;
if (respo... |
python | def _generate_perfect_bst(height):
"""Generate a perfect BST (binary search tree) and return its root.
:param height: Height of the BST.
:type height: int
:return: Root node of the BST.
:rtype: binarytree.Node
"""
max_node_count = 2 ** (height + 1) - 1
node_values = list(range(max_node_... |
java | @Override
public void visitMethod(Method obj) {
try {
if (obj.isSynthetic()) {
return;
}
if (Values.CONSTRUCTOR.equals(getMethodName()) && javaClass.getClassName().contains("$")) {
return;
}
List<String> types = SignatureUtils.getParameterSignatures(obj.getSignature());
if ((types.isEmpty... |
java | @Deprecated
@Override
protected int subParse(String text, int start, char ch, int count, boolean obeyCount, boolean allowNegative,
boolean[] ambiguousYear, Calendar cal) {
// Logic to handle numeric 'G' eras for chinese calendar, and to skip special 2-digit year
// handling for chine... |
python | def GetWSAActionFault(operation, name):
"""Find wsa:Action attribute, and return value or WSA.FAULT
for the default.
"""
attr = operation.faults[name].action
if attr is not None:
return attr
return WSA.FAULT |
java | private void addInfoForRoutingBackToContainer(SipApplicationRouterInfo routerInfo, String applicationSessionId, String applicationName) throws ParseException, SipException {
final Request request = (Request) super.message;
final javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI(
sipFactoryImpl... |
python | def cli(obj, scopes):
"""List permissions."""
client = obj['client']
query = [('scopes', s) for s in scopes]
if obj['output'] == 'json':
r = client.http.get('/perms', query)
click.echo(json.dumps(r['permissions'], sort_keys=True, indent=4, ensure_ascii=False))
else:
headers ... |
java | private void cleanApps() {
File AppsDir = new File(serverConfigDir.getAbsolutePath(), "apps");
if (AppsDir.exists()) {
cleanDir(AppsDir);
log(MessageFormat.format(messages.getString("info.element.cleaned"), "apps"));
} else {
log(MessageFormat.format(messages.... |
java | public static Set<IProcessor> createSpringStandardProcessorsSet(
final String dialectPrefix, final boolean renderHiddenMarkersBeforeCheckboxes) {
/*
* It is important that we create new instances here because, if there are
* several dialects in the TemplateEngine that extend Standa... |
python | def fit(self, X, y=None):
"""Perform HDBSCAN clustering from features or distance matrix.
Parameters
----------
X : array or sparse (CSR) matrix of shape (n_samples, n_features), or \
array of shape (n_samples, n_samples)
A feature array, or array of distance... |
java | public static boolean isAnnotationDeclaredLocally(Class<? extends Annotation> annotationType, Class<?> clazz) {
Assert.notNull(annotationType, "Annotation type must not be null");
Assert.notNull(clazz, "Class must not be null");
boolean declaredLocally = false;
try {
for (Annotation ann : clazz.getDeclaredAn... |
java | @Deprecated
public int getLevel() {
Level level = loggerProxy.getLevel();
return level != null ? level.intValue() : 0;
} |
python | def squared_toroidal_dist(p1, p2, world_size=(60, 60)):
"""
Separated out because sqrt has a lot of overhead
"""
halfx = world_size[0]/2.0
if world_size[0] == world_size[1]:
halfy = halfx
else:
halfy = world_size[1]/2.0
deltax = p1[0] - p2[0]
if deltax < -halfx:
... |
java | public void addLessOrEqualThan(Object attribute, Object value)
{
// PAW
// addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getAlias()));
addSelectionCriteria(ValueCriteria.buildNotGreaterCriteria(attribute, value, getUserAlias(attribute)));
} |
python | def disable(identifier, children_only=False):
"""
Disable an include type
:param identifier: module or name of the include type
:param children_only: disable the include type only for child processes, not the current process
The ``identifier`` can be specified in multiple ways to disable an includ... |
python | def load_model(self, fname):
"""
Load the model from a file.
The model is loaded from an XGBoost internal binary format which is
universal among the various XGBoost interfaces. Auxiliary attributes of
the Python Booster object (such as feature_names) will not be loaded.
... |
java | @Override
public void destroyXAResource(XAResource xa) throws DestroyXAResourceException {
final boolean trace = TraceComponent.isAnyTracingEnabled();
if (trace && tc.isEntryEnabled())
Tr.entry(this, tc, "destroyXAResource", xa);
ManagedConnection mc = ((WSXAResource) xa).getMa... |
python | def get_portchannel_info_by_intf_output_lacp_receive_machine_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
output = ET.SubElem... |
java | public static LinkedBuffer encode(final byte[] input, int inOffset, int inLen,
final WriteSession session, final LinkedBuffer lb) throws IOException
{
int outputSize = ((inLen + 2) / 3) * 4;
session.size += outputSize;
final int available = lb.buffer.length - lb.offset;
... |
java | public static Client getClient(ClientConfig config, String[] servers,
int port) throws Exception {
config.setTopologyChangeAware(true); // Set client to be topology-aware
final Client client = ClientFactory.createClient(config);
for (String server : servers) {
// Try conn... |
java | public static void defineOrder(ProcessedInput processedInput, QueryParameters parameters) {
String parameterName = null;
for (int i = 0; i < processedInput.getAmountOfParameters(); i++) {
parameterName = processedInput.getParameterName(i);
if (parameterName != null) {
... |
python | def remove_stale_css(portal):
"""Removes stale CSS
"""
logger.info("Removing stale css ...")
for css in CSS_TO_REMOVE:
logger.info("Unregistering CSS %s" % css)
portal.portal_css.unregisterResource(css) |
python | def _distance_matrix_generic(x, centering, exponent=1):
"""Compute a centered distance matrix given a matrix."""
_check_valid_dcov_exponent(exponent)
x = _transform_to_2d(x)
# Calculate distance matrices
a = distances.pairwise_distances(x, exponent=exponent)
# Double centering
a = centeri... |
python | def parse(
response_text: str, *, batch: bool, validate_against_schema: bool = True
) -> Union[JSONRPCResponse, List[JSONRPCResponse]]:
"""
Parses response text, returning JSONRPCResponse objects.
Args:
response_text: JSON-RPC response string.
batch: If the response_text is an empty str... |
python | def find_mismatch(first, second, indent=''):
"""
Finds where two objects differ, iterating down into nested containers
(i.e. dicts, lists and tuples) They can be nested containers
any combination of primary dtypes, str, int, float, dict and lists
Parameters
----------
first : dict | list | ... |
java | protected void registerNativeAlpn(SSLEngine engine) {
if (isNativeAlpnActive()) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "registerNativeAlpn entry " + engine);
}
try {
String[] protocols = new String[] {... |
java | public void setArtifacts(java.util.Collection<Artifact> artifacts) {
if (artifacts == null) {
this.artifacts = null;
return;
}
this.artifacts = new java.util.ArrayList<Artifact>(artifacts);
} |
python | def _arevalid(self, datatype):
'''Checks if the given datatype is valid in meta (for array-like types)'''
# Datatype not specified
if datatype not in self.meta:
return datatype in Dap._optional_meta, []
# Required datatype empty
if datatype in self._required_meta and... |
java | private void persistRealmChanges() {
configManager.persistProperties(realm.getProperties(), new File(applicationContentDir, PersistablePropertiesRealm.REALM_FILE_NAME), null);
} |
python | def log_setup(debug_bool):
"""Set up logging.
We output only to stdout. Instead of also writing to a log file, redirect stdout to
a log file when the script is executed from cron.
"""
level = logging.DEBUG if debug_bool else logging.INFO
logging.config.dictConfig(
{
"vers... |
python | def _do_load(
self, data, many=None, partial=None, unknown=None,
postprocess=True,
):
"""Deserialize `data`, returning the deserialized result.
:param data: The data to deserialize.
:param bool many: Whether to deserialize `data` as a collection. If `None`, the
v... |
python | def exists(Name, region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI example::
salt myminion boto_cloudwatch_event.exists myevent regio... |
java | private Node tryFoldChildAddString(Node n, Node left, Node right) {
if (NodeUtil.isLiteralValue(right, false) &&
left.isAdd()) {
Node ll = left.getFirstChild();
Node lr = ll.getNext();
// Left's right child MUST be a string. We would not want to fold
// foo() + 2 + 'a' because we ... |
python | def get_verified_jwt(
providers, audiences,
check_authorization_header=True, check_query_arg=True,
request=None, cache=memcache):
"""
This function will extract, verify, and parse a JWT token from the
Authorization header or access_token query argument.
The JWT is assumed to contain an issuer and a... |
java | public List<CorporationRolesHistoryResponse> getCorporationsCorporationIdRolesHistory(Integer corporationId,
String datasource, String ifNoneMatch, Integer page, String token) throws ApiException {
ApiResponse<List<CorporationRolesHistoryResponse>> resp = getCorporationsCorporationIdRolesHistoryWith... |
python | def fetch(self, end=values.unset, start=values.unset):
"""
Fetch a UsageInstance
:param unicode end: The end
:param unicode start: The start
:returns: Fetched UsageInstance
:rtype: twilio.rest.preview.wireless.sim.usage.UsageInstance
"""
return self._pro... |
java | public static List<String> loadScript(String path) {
List<String> result = new ArrayList<String>();
URL url = CassandraUtils.class.getResource(path);
LOGGER.debug(url.toString());
LOGGER.info("Loading script from: " + url);
try (BufferedReader br = new BufferedReader(new InputStr... |
java | public ServiceFuture<ExpressRouteCircuitPeeringInner> getAsync(String resourceGroupName, String circuitName, String peeringName, final ServiceCallback<ExpressRouteCircuitPeeringInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, circuitName, peeringName), s... |
python | def get_versions(reporev=True):
"""Get version information for components used by Spyder"""
import sys
import platform
import qtpy
import qtpy.QtCore
revision = None
if reporev:
from spyder.utils import vcs
revision, branch = vcs.get_git_revision(os.path.dirname(__dir__))
... |
java | public void putKeyColumnOnlyIfItIsNotYetChangedInTx(final AbstractDynamoDbStore store, final StaticBuffer key, final StaticBuffer column,
final StaticBuffer expectedValue) {
expectedValues.computeIfAbsent(store, s -> new HashMap<>());
expectedValues.get(store).computeIfAbsent(key, k -> new HashM... |
java | public static ValidatingStreamReader createValidatingStreamReader
(BranchingReaderSource input, ReaderCreator owner,
ReaderConfig cfg, InputBootstrapper bs, boolean forER)
throws XMLStreamException
{
ValidatingStreamReader sr = new ValidatingStreamReader
(bs, input, owne... |
python | def _encode(self, value):
"Return a bytestring representation of the value. Taken from redis-py connection.py"
if isinstance(value, bytes):
return value
elif isinstance(value, (int, long)):
value = str(value).encode('utf-8')
elif isinstance(value, float):
... |
python | def _add_styles(self, add_paragraph=True, add_text=True):
"""
Adds paragraph and span wrappers if necessary based on style
"""
p_styles = self.get_para_styles()
t_styles = self.get_span_styles()
for s in self.slide.pending_styles:
if isinstance(s, ParagraphSty... |
python | def verify2(self):
"""Last verification step.
The derived keys (output, input) are returned here.
"""
output_key = hkdf_expand('MediaRemote-Salt',
'MediaRemote-Write-Encryption-Key',
self._shared)
input_key = hkd... |
python | def handle(self, addrport='', *args, **options):
"""Handle the management command."""
server = WebserverThread(addrport, *args, **options)
server.start()
options['camera'] = 'djcelery.snapshot.Camera'
options['prog_name'] = 'djcelerymon'
ev.run(*args, **options) |
python | def department_show(self, department_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/departments#get-department-by-id"
api_path = "/api/v2/departments/{department_id}"
api_path = api_path.format(department_id=department_id)
return self.call(api_path, **kwargs) |
java | @Override
public boolean apply(List<E> tokens) {
if (this.find(tokens) != null) {
return true;
} else {
return false;
}
} |
python | def is_stalemate(self) -> bool:
"""Checks if the current position is a stalemate."""
if self.is_check():
return False
if self.is_variant_end():
return False
return not any(self.generate_legal_moves()) |
java | public JobSchedulePatchOptions withOcpDate(DateTime ocpDate) {
if (ocpDate == null) {
this.ocpDate = null;
} else {
this.ocpDate = new DateTimeRfc1123(ocpDate);
}
return this;
} |
java | @Override
public DeclineInvitationsResult declineInvitations(DeclineInvitationsRequest request) {
request = beforeClientExecution(request);
return executeDeclineInvitations(request);
} |
python | def sort(records: Sequence[Record]) -> List[Record]:
"Sort records into a canonical order, suitable for comparison."
return sorted(records, key=_record_key) |
python | def _reduce_output(self, outputs, seq_lengths):
"""Reduces the output of an LSTM step
Args:
outputs: (torch.FloatTensor) the hidden state outputs from the
lstm, with shape [batch_size, max_seq_length, hidden_size]
"""
batch_size = outputs.shape[0]
red... |
java | protected void agentCreated (ClientObject client, int agentId)
{
FoundAgent found = resolve(client, agentId, "agentCreated");
if (found == null) {
return;
}
log.info("Agent creation confirmed", "agent", found.agent.which());
if (found.state == AgentState.STARTED... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.