language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public AVQuery<T> whereEqualTo(String key, Object value) {
conditions.whereEqualTo(key, value);
return this;
} |
java | public SDVariable logLoss(String name, @NonNull SDVariable label, @NonNull SDVariable predictions) {
return logLoss(name, label, predictions, null, LossReduce.MEAN_BY_NONZERO_WEIGHT_COUNT, LogLoss.DEFAULT_EPSILON);
} |
java | public String getString() throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(buf);
int c;
StringWriter w = new StringWriter();
while (((c = in.read()) != 0) && (c != -1)) {
w.write((char) c);
}
return w.getBuffer()... |
python | def _bytes_to_json(value):
"""Coerce 'value' to an JSON-compatible representation."""
if isinstance(value, bytes):
value = base64.standard_b64encode(value).decode("ascii")
return value |
java | @SuppressWarnings("unchecked")
private static void readDB(String dbName) {
PersistenceManager pm = ZooJdoHelper.openDB(dbName);
pm.currentTransaction().begin();
//Extents are one way to get objects from a database:
System.out.println("Person extent: ");
Extent<Person> ext = pm.... |
java | public static ItemViewHolder createViewHolder(View view, Class<? extends ItemViewHolder> itemViewHolderClass) {
try {
Constructor<? extends ItemViewHolder> constructor = itemViewHolderClass.getConstructor(View.class);
return constructor.newInstance(view);
} catch (IllegalAccessEx... |
python | def get_service_account_token(request, service_account='default'):
"""Get the OAuth 2.0 access token for a service account.
Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.
service_account (str): The string 'default' or a service account email
... |
python | def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
"""Extracts relevant TimeMachine entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted ... |
java | public String[] lookupAllPrefixes(String uri)
{
java.util.ArrayList foundPrefixes = new java.util.ArrayList();
Enumeration prefixes = m_namespaces.keys();
while (prefixes.hasMoreElements())
{
String prefix = (String) prefixes.nextElement();
String uri2 = looku... |
python | def Match(addr1, addr2):
"""Return true iff addr1 matches addr2."""
if _debug: Match._debug("Match %r %r", addr1, addr2)
if (addr2.addrType == Address.localBroadcastAddr):
# match any local station
return (addr1.addrType == Address.localStationAddr) or (addr1.addrType == Address.localBroadc... |
python | def update():
"""
Called by XMLHTTPrequest function periodically to get new graph data.
Usage description:
This function queries the database and returns all the newly added values.
:return: JSON Object, passed on to the JS script.
"""
assert request.method == "POST", "POST request expecte... |
python | def _prepPointsForSegments(points):
"""
Move any off curves at the end of the contour
to the beginning of the contour. This makes
segmentation easier.
"""
while 1:
point = points[-1]
if point.segmentType:
break
else:
point = points.pop()
... |
python | def ticket_forms_reorder(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_forms#reorder-ticket-forms"
api_path = "/api/v2/ticket_forms/reorder.json"
return self.call(api_path, method="PUT", data=data, **kwargs) |
python | def check(operations, loud=False):
"""Check all the things
:param operations: The operations to check
:param loud: `True` if checkers should prettyprint their status to stderr. `False` otherwise.
:returns: A tuple of overall success, and a detailed execution log for all the operations
"""
if n... |
python | def is_page_content_is_already_updated(self, page_id, body):
"""
Compare content and check is already updated or not
:param page_id: Content ID for retrieve storage value
:param body: Body for compare it
:return: True if the same
"""
confluence_content = (self.get... |
python | async def connect(
self, server, port, nickname, password=None, username=None,
ircname=None, connect_factory=connection.AioFactory()
):
"""Connect/reconnect to a server.
Arguments:
* server - Server name
* port - Port number
* nickname - The nickname
... |
python | def build_query(self,
product=None,
component=None,
version=None,
long_desc=None,
bug_id=None,
short_desc=None,
cc=None,
assigned_to=None,
r... |
python | def push_image(self, image, insecure=False):
"""
push provided image to registry
:param image: ImageName
:param insecure: bool, allow connecting to registry over plain http
:return: str, logs from push
"""
logger.info("pushing image '%s'", image)
logger.d... |
java | public static long getMonthStartTime(final long time) {
final Calendar start = Calendar.getInstance();
start.setTimeInMillis(time);
final int year = start.get(Calendar.YEAR);
final int month = start.get(Calendar.MONTH);
start.set(year, month, 1, 0, 0, 0);
start.set(Calend... |
java | public Collection<?> getOverrides() {
List<Object> r = new ArrayList<>();
for (JobProperty<? super JobT> p : properties)
r.addAll(p.getJobOverrides());
return r;
} |
java | @Nonnull
public static LLogicalBinaryOperator logicalBinaryOperatorFrom(Consumer<LLogicalBinaryOperatorBuilder> buildingFunction) {
LLogicalBinaryOperatorBuilder builder = new LLogicalBinaryOperatorBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
java | @Override
public ExportCertificateResult exportCertificate(ExportCertificateRequest request) {
request = beforeClientExecution(request);
return executeExportCertificate(request);
} |
java | protected Dataset<Sequence> getDataset(SequenceFeaturizer<Annotation> featurizer) {
Corpus c = Corpus
.builder()
.corpusType(corpusType)
.source(corpus)
.format(corpusFormat)
.build();
AnnotatableType[] requi... |
java | public EClass getIfcQuantityArea() {
if (ifcQuantityAreaEClass == null) {
ifcQuantityAreaEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(413);
}
return ifcQuantityAreaEClass;
} |
python | def download(url, proxies=None):
"""
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy stri... |
java | public void scan(byte[] instructionList, Callback callback) {
boolean wide = false;
for (int index = 0; index < instructionList.length;) {
short opcode = unsignedValueOf(instructionList[index]);
callback.handleInstruction(opcode, index);
if (DEBUG) {
... |
java | private String discover(final String url) throws TimezonesException {
/* For the moment we'll try to find it via .well-known. We may have to
* use DNS SRV lookups
*/
// String domain = hi.getHostname();
// int lpos = domain.lastIndexOf(".");
//int lpos2 = domain.lastIndexOf(".", lpos - 1);
// ... |
java | @Override
public Object visitFunctionParameters(ExcellentParser.FunctionParametersContext ctx) {
List<Object> parameters = new ArrayList<>();
for (ExcellentParser.ExpressionContext expression : ctx.expression()) {
parameters.add(visit(expression));
}
return parameters;
... |
python | def remove_job_resolver(self, job_resolver):
"""Remove job_resolver from the list of job resolvers.
Keyword arguments:
job_resolver -- Function reference of the job resolver to be removed.
"""
for i, r in enumerate(self.job_resolvers()):
if job_resolver == r:
... |
python | def unsetenv(key):
"""Like `os.unsetenv` but takes unicode under Windows + Python 2
Args:
key (pathlike): The env var to unset
"""
key = path2fsn(key)
if is_win:
# python 3 has no unsetenv under Windows -> use our ctypes one as well
try:
del_windows_env_var(key)... |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case DroolsPackage.DOCUMENT_ROOT__MIXED:
return mixed != null && !mixed.isEmpty();
case DroolsPackage.DOCUMENT_ROOT__XMLNS_PREFIX_MAP:
return xMLNSPrefixMap != null && !xMLNSPrefixMap.isEmpty();
case DroolsPackage.DOCUMENT_ROOT__X... |
python | def region_by_identifier(self, identifier):
"""Return region of interest corresponding to the supplied identifier.
:param identifier: integer corresponding to the segment of interest
:returns: `jicbioimage.core.region.Region`
"""
if identifier < 0:
raise(ValueError(... |
python | def _convert_from(data):
"""Internal function that will be hooked to the native `json.loads`
Find the right deserializer for a given value, taking into account
the internal deserializer registry.
"""
try:
module, klass_name = data['__class__'].rsplit('.', 1)
klass = getattr(import_m... |
python | def evaluate_model_single_recording(model_file, recording):
"""
Evaluate a model for a single recording.
Parameters
----------
model_file : string
Model file (.tar)
recording :
The handwritten recording.
"""
(preprocessing_queue, feature_list, model,
output_semantic... |
python | def deduce_chirality(obj):
'''
deduce_chirality(x) attempts to deduce the chirality of x ('lh', 'rh', or 'lr') and yeilds the
deduced string. If no chirality can be deduced, yields None. Note that a if x is either None
or Ellipsis, this is converted into 'lr'.
'''
# few simple tests:
try... |
java | public static DataSourcePropertyProvider getProvider(final DataSource dataSource) {
String dataSourceClassName = dataSource.getClass().getName();
return DATA_SOURCE_PROPERTY_PROVIDERS.containsKey(dataSourceClassName) ? DATA_SOURCE_PROPERTY_PROVIDERS.get(dataSourceClassName) : new DefaultDataSourceProper... |
java | public void removeAttribute(final String attributeName) throws DevFailed {
final AttributeImpl toRemove = dynamicAttributes.get(attributeName.toLowerCase(Locale.ENGLISH));
if (toRemove == null)
throw DevFailedUtils.newDevFailed("API_AttributeNotFound", "Attribute \'" + attributeName + "\' no... |
python | def get_wrapper_class(backend_name):
"""Return the WRAPPER_CLASS for a given backend.
:rtype: pyvisa.highlevel.VisaLibraryBase
"""
try:
return _WRAPPERS[backend_name]
except KeyError:
if backend_name == 'ni':
from .ctwrapper import NIVisaLibrary
_WRAPPERS['ni... |
python | def _serialize_datetime(value):
"""Serialize a DateTime object to its proper ISO-8601 representation."""
if not isinstance(value, (datetime, arrow.Arrow)):
raise ValueError(u'The received object was not a datetime: '
u'{} {}'.format(type(value), value))
return value.isoforma... |
python | def stop(self):
"""Stop the Client, disconnect from queue
"""
if self.__end.is_set():
return
self.__end.set()
self.__send_retry_requests_timer.cancel()
self.__threadpool.stop()
self.__crud_threadpool.stop()
self.__amqplink.stop()
self._... |
python | def remove_file_from_s3(awsclient, bucket, key):
"""Remove a file from an AWS S3 bucket.
:param awsclient:
:param bucket:
:param key:
:return:
"""
client_s3 = awsclient.get_client('s3')
response = client_s3.delete_object(Bucket=bucket, Key=key) |
java | @Bean(initMethod = "start")
KafkaCollector kafka(
ZipkinKafkaCollectorProperties properties,
CollectorSampler sampler,
CollectorMetrics metrics,
StorageComponent storage) {
return properties.toBuilder().sampler(sampler).metrics(metrics).storage(storage).build();
} |
java | @Override
public DisassociateTagOptionFromResourceResult disassociateTagOptionFromResource(DisassociateTagOptionFromResourceRequest request) {
request = beforeClientExecution(request);
return executeDisassociateTagOptionFromResource(request);
} |
java | public static void verifyThrowable(ThrowingCallable actor, Class<? extends Throwable> clazz) {
validateArguments(actor, clazz);
catchThrowable(actor, clazz, true);
} |
java | public Authentication doAuthenticate(final DmfTenantSecurityToken securityToken) {
resolveTenant(securityToken);
PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(null, null);
for (final PreAuthenticationFilter filter : filterChain) {
final ... |
python | def set_theme(self, theme_name, toplevel=None, themebg=None):
"""Redirect the set_theme call to also set Tk background color"""
if self._toplevel is not None and toplevel is None:
toplevel = self._toplevel
if self._themebg is not None and themebg is None:
themebg = self._... |
python | def observation(self, frame):
"""Add single zero row/column to observation if needed."""
if frame.shape == self.observation_space.shape:
return frame
else:
extended_frame = np.zeros(self.observation_space.shape,
self.observation_space.dtype)
assert self.HW_A... |
java | @Override
public FreeMarkerConfigurer freeMarkerConfigurer() {
FreeMarkerConfigurer result = super.freeMarkerConfigurer();
// Look up unknown templates in the FreemarkerTemplate repository
result.setPostTemplateLoaders(new RepositoryTemplateLoader(dataService));
return result;
} |
java | public Object getListFieldValue(String fieldName, int index) {
Object ret = null;
Object val = getFieldValue(fieldName, true); // internal
if (val instanceof List<?>) {
List<?> list = (List<?>)val;
Object cval = list.get(index);
DomainObject gdo = getForRawObject(cval);
if (gdo != null)
re... |
python | def delete_selected_tree(self, modeladmin, request, queryset):
"""
Deletes multiple instances and makes sure the MPTT fields get recalculated properly.
(Because merely doing a bulk delete doesn't trigger the post_delete hooks.)
"""
# If the user has not yet confirmed the deletion... |
python | def with_meter(name, tick_interval=meter.DEFAULT_TICK_INTERVAL):
"""
Call-counting decorator: each time the wrapped function is called
the named meter is incremented by one.
metric_args and metric_kwargs are passed to new_meter()
"""
try:
mmetric = new_meter(name, tick_interval)
exc... |
python | def pretty_print(self, as_list=False, show_datetime=True):
"""
Return a Unicode string pretty print of the log entries.
:param bool as_list: if ``True``, return a list of Unicode strings,
one for each entry, instead of a Unicode string
:param bool show_datet... |
java | private static LinkedHashMap<Class<?>, Integer> createRegisteredSubclassTags(LinkedHashSet<Class<?>> registeredSubclasses) {
final LinkedHashMap<Class<?>, Integer> classToTag = new LinkedHashMap<>();
int id = 0;
for (Class<?> registeredClass : registeredSubclasses) {
classToTag.put(registeredClass, id);
id... |
python | def which(program, path=None):
"""
Returns the full path of shell commands.
Replicates the functionality of system which (1) command. Looks
for the named program in the directories indicated in the $PATH
environment variable, and returns the full path if found.
Examples:
>>> system.wh... |
python | def dir():
"""Return the list of patched function names. Used for patching
functions imported from the module.
"""
dir = [
'access', 'chdir', 'chmod', 'chown', 'close', 'fstat', 'fsync',
'getcwd', 'lchmod', 'link', 'listdir', 'lstat', 'makedirs',
'mkdi... |
java | void initButtons() {
m_okButton = new Button(CmsVaadinUtils.getMessageText(org.opencms.workplace.Messages.GUI_DIALOG_BUTTON_OK_0));
m_okButton.addClickListener(new ClickListener() {
private static final long serialVersionUID = 1L;
public void buttonClick(ClickEvent event) {
... |
python | def handle_process_output(process, stdout_handler, stderr_handler,
finalizer=None, decode_streams=True):
"""Registers for notifications to lean that process output is ready to read, and dispatches lines to
the respective line handlers.
This function returns once the finalizer retur... |
java | @SuppressWarnings("serial")
public static Type[] forTypeParameters(final Class<?> type) {
Type[] result = new Type[type.getTypeParameters().length];
for (int i = 0; i < result.length; i++) {
final int index = i;
result[i] = forTypeProvider(new DefaultTypeProvider() {
... |
java | public static void main(String[] args)
{
try
{
if (args.length == 0)
{
System.err.println("Usage java " + Cryption.class.getName()
+ " <text>");
return;
}
final String decryptedPassword;
if (args[0].equals("-d"))
{
if (args.length > 2)
{
StringBuild... |
java | public Bean<T> create() {
if (!passivationCapable) {
return new ImmutableBean<T>(beanClass, name, qualifiers, scope, stereotypes, types, alternative, nullable, injectionPoints, beanLifecycle, toString);
} else {
return new ImmutablePassivationCapableBean<T>(id, beanClass, name, q... |
java | public boolean complete(UUID value) {
return root.complete(new Tree((Tree) null, null, value));
} |
java | Bitmap generateGradient() {
int[][] pixels = new int[1080][1920];
for (int y = 0; y < 1080; y++) {
for (int x = 0; x < 1920; x++) {
int r = (int) (y / 1080f * 255);
int g = (int) (x / 1920f * 255);
int b = (int) ((Math.hypot(x, y) / Math.hypot(1080, 1920)) * 255);
pixels[y]... |
python | def get_column_def(self):
"""
Returns a column definition for CQL table definition
"""
static = "static" if self.static else ""
db_type = self.db_type.format(self.value_type.db_type)
return '{} {} {}'.format(self.cql, db_type, static) |
java | protected void clearPartitions() {
for (int i = this.partitionsBeingBuilt.size() - 1; i >= 0; --i) {
final HashPartition<BT, PT> p = this.partitionsBeingBuilt.get(i);
try {
p.clearAllMemory(this.availableMemory);
} catch (Exception e) {
LOG.error("Error during partition cleanup.", e);
}
}
this... |
java | public Matrix4x3f shadow(float lightX, float lightY, float lightZ, float lightW, Matrix4x3f planeTransform) {
return shadow(lightX, lightY, lightZ, lightW, planeTransform, this);
} |
java | @BetaApi
public final Operation setNamedPortsInstanceGroup(
String instanceGroup,
InstanceGroupsSetNamedPortsRequest instanceGroupsSetNamedPortsRequestResource) {
SetNamedPortsInstanceGroupHttpRequest request =
SetNamedPortsInstanceGroupHttpRequest.newBuilder()
.setInstanceGroup(i... |
python | def animate(self, sprite, duration = None, easing = None, on_complete = None,
on_update = None, round = False, **kwargs):
"""Interpolate attributes of the given object using the internal tweener
and redrawing scene after every tweener update.
Specify the sprite and sprite's... |
python | def accelerated_proximal_gradient(x, f, g, gamma, niter, callback=None,
**kwargs):
r"""Accelerated proximal gradient algorithm for convex optimization.
The method is known as "Fast Iterative Soft-Thresholding Algorithm"
(FISTA). See `[Beck2009]`_ for more information.
... |
java | public Response put(String endpoint, Request params, File file) {
return call(Method.PUT, endpoint, params, file);
} |
java | private static JsonNode toJson(AggregatedHttpMessage res, @Nullable JsonNodeType expectedNodeType) {
final String content = toString(res);
final JsonNode node;
try {
node = Jackson.readTree(content);
} catch (JsonParseException e) {
throw new CentralDogmaException... |
java | public static Option provision(final InputStream... streams) {
validateNotNull(streams, "streams");
final UrlProvisionOption[] options = new UrlProvisionOption[streams.length];
int i = 0;
for (InputStream stream : streams) {
options[i++] = streamBundle(stream);
}
... |
python | def _as_json(self, **kwargs) -> str:
""" Convert a JsonObj into straight json text
:param kwargs: json.dumps arguments
:return: JSON formatted str
"""
return json.dumps(self, default=self._default, **kwargs) |
java | public ListTeamMembersResult withTeamMembers(TeamMember... teamMembers) {
if (this.teamMembers == null) {
setTeamMembers(new java.util.ArrayList<TeamMember>(teamMembers.length));
}
for (TeamMember ele : teamMembers) {
this.teamMembers.add(ele);
}
return th... |
python | def create_graph(grid):
"""
This function creates a graph of vertices and edges from segments returned by SLIC.
:param array grid: A grid of segments as returned by the slic function defined in skimage library
:return: A graph as [vertices, edges]
"""
try:
import numpy as np
except I... |
java | private static void initializeDrawee(Context context, @Nullable DraweeConfig draweeConfig) {
if (FrescoSystrace.isTracing()) {
FrescoSystrace.beginSection("Fresco.initializeDrawee");
}
sDraweeControllerBuilderSupplier =
new PipelineDraweeControllerBuilderSupplier(context, draweeConfig);
Si... |
java | public static DataSource getDataSource(final String jndiName)
throws FactoryException {
Validate.notBlank(jndiName, "The validated character sequence 'jndiName' is null or empty");
// no need for defensive copies of Strings
try {
// the initial context is created from ... |
python | def write_to_screen(self, cli, screen, mouse_handlers, write_position):
"""
Render the prompt to a `Screen` instance.
:param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class
to which the output has to be written.
"""
if not self.children:
r... |
python | def update_option_value_by_id(cls, option_value_id, option_value, **kwargs):
"""Update OptionValue
Update attributes of OptionValue
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.update_optio... |
java | protected T popFrontEntry() {
if (head == null) {
return null;
}
T next = head.getNext();
if (next != null) {
next.setPrev(null);
} else {
last = null;
}
T e = head;
head = next;
e.setNext(null);
size--;
... |
java | public static boolean isValidJavaIdentifier(String name) {
if (isBlank(name)) {
return false;
}
final char[] chars = name.toCharArray();
if (!Character.isJavaIdentifierStart(chars[0])) {
return false;
}
for (char c : chars) {
if (!Cha... |
python | def load_ini(self):
""" Load the given .INI file.
"""
if not self.config_file:
return
# Load INI file
ini_file = ConfigParser.SafeConfigParser()
if not ini_file.read(self.config_file):
raise ConfigParser.ParsingError("Global configuration file %r ... |
java | protected void checkHealth(long threshold, NodeHealthChecker healthChecker) {
final int state = this.state;
if (anyAreSet(state, REMOVED | ACTIVE_PING)) {
return;
}
healthCheckPing(threshold, healthChecker);
} |
java | public void setSelectionMode(final @SelectionMode int mode) {
final @SelectionMode int oldMode = this.selectionMode;
this.selectionMode = mode;
switch (mode) {
case SELECTION_MODE_RANGE:
clearSelection();
break;
case SELECTION_MODE_MULTIPLE:
break;
case SELECTION_MO... |
java | protected double[] firstHit(Instance inst) {
boolean fired = false;
int countFired = 0;
double[] votes = new double[this.numClass];
for (int j = 0; j < this.ruleSet.size(); j++) {
if (this.ruleSet.get(j).ruleEvaluate(inst) == true) {
countFired = countFired + 1;
for (int z = 0; z < this.numClass; z++... |
python | def set_bounds(self, new_bounds):
"""
A method that allows changing the lower and upper searching bounds
Parameters
----------
new_bounds : dict
A dictionary with the parameter name and its new bounds
"""
for row, key in enumerate(self.keys):
... |
python | def get_solution(self, parameters=None):
"""stub"""
if not self.has_solution():
raise IllegalState()
return DisplayText(self.my_osid_object._my_map['solution']) |
java | private MethodRefAmp findLocalMethod()
{
ServiceRefAmp serviceRefLocal = _serviceRef.getLocalService();
if (serviceRefLocal == null) {
return null;
}
if (_type != null) {
return serviceRefLocal.methodByName(_name, _type);
}
else {
return serviceRefLocal.methodByName(_na... |
java | public void copyFile( File sourceFile, File targetFile )
throws MojoExecutionException
{
makeDirectoryIfNecessary( targetFile.getParentFile() );
try
{
FileUtils.copyFile( sourceFile, targetFile );
}
catch ( IOException e )
{
throw n... |
python | def convert_collection_values_according_to_pep(coll_to_convert: Union[Dict, List, Set, Tuple],
desired_type: Type[T],
conversion_finder: 'ConversionFinder', logger: Logger, **kwargs) \
-> T:
"""
... |
java | @Override
public FacilityRequestMessage createFAR() {
FacilityRequestMessage msg = new FacilityRequestMessageImpl(_FAR_HOLDER.mandatoryCodes,
_FAR_HOLDER.mandatoryVariableCodes, _FAR_HOLDER.optionalCodes, _FAR_HOLDER.mandatoryCodeToIndex,
_FAR_HOLDER.mandatoryVariableCodeToIn... |
python | def transform(self, X):
"""Make subset after fit
Parameters
----------
X: numpy ndarray, {n_samples, n_features}
New data, where n_samples is the number of samples and n_features is the number of features.
Returns
-------
X_transformed: array-like, s... |
python | def _validate(self, writing=False):
"""Verify that the box obeys the specifications."""
# channel type and association must be specified.
if not ((len(self.index) == len(self.channel_type)) and
(len(self.channel_type) == len(self.association))):
msg = ("The length of ... |
java | public EntryStream<K, V> prepend(K k1, V v1, K k2, V v2) {
@SuppressWarnings("unchecked")
SimpleImmutableEntry<K, V>[] array = new SimpleImmutableEntry[] { new SimpleImmutableEntry<>(k1, v1),
new SimpleImmutableEntry<>(k2, v2) };
return prependSpliterator(null, Spliterators.s... |
java | public NextResponse delete2(final String url, final Map<String, String> forms)
throws IOException {
return delete(url, forms, null);
} |
python | async def ask_opinion(self, addr, artifact):
"""Ask an agent's opinion about an artifact.
:param str addr: Address of the agent which opinion is asked
:type addr: :py:class:`~creamas.core.agent.CreativeAgent`
:param object artifact: artifact to be evaluated
:returns: agent's eva... |
python | def ensure_directory(directory):
"""
Create the directories along the provided directory path that do not exist.
"""
directory = os.path.expanduser(directory)
try:
os.makedirs(directory)
except OSError as e:
if e.errno != errno.EEXIST:
raise e |
python | def authenticate(self, username: str, password: str) -> bool:
"""Do an Authentricate request and save the cookie returned to be used
on the following requests.
Return True if the request was successfull
"""
self.username = username
self.password = password
auth_p... |
java | static <T> KryoSerializerSnapshotData<T> createFrom(
Class<T> typeClass,
LinkedHashMap<Class<?>, SerializableSerializer<?>> defaultKryoSerializers,
LinkedHashMap<Class<?>, Class<? extends Serializer<?>>> defaultKryoSerializerClasses,
LinkedHashMap<String, KryoRegistration> kryoRegistrations) {
return new Kry... |
python | def import_committees_from_legislators(current_term, abbr):
""" create committees from legislators that have committee roles """
# for all current legislators
for legislator in db.legislators.find({'roles': {'$elemMatch': {
'term': current_term, settings.LEVEL_FIELD: abbr}}}):
# for al... |
java | public void marshall(DeviceFilter deviceFilter, ProtocolMarshaller protocolMarshaller) {
if (deviceFilter == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deviceFilter.getAttribute(), ATTRIBUTE_BIND... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.