language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def provision_devices(self, devices):
"""Provision multiple devices with a single API call
This method takes an iterable of dictionaries where the values in the dictionary are
expected to match the arguments of a call to :meth:`provision_device`. The
contents of each dictionary will be... |
java | @Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case TypesPackage.JVM_PRIMITIVE_TYPE__SIMPLE_NAME:
setSimpleName((String)newValue);
return;
}
super.eSet(featureID, newValue);
} |
python | def _get_required_params_for_conversion(self, event_key, event_tags):
""" Get parameters that are required for the conversion event to register.
Args:
event_key: Key representing the event which needs to be recorded.
event_tags: Dict representing metadata associated with the event.
Returns:
... |
java | public static Date parseEpochTimestamp(String value)
{
Date result = null;
if (value.length() > 0)
{
if (!value.equals("-1 -1"))
{
Calendar cal = DateHelper.popCalendar(JAVA_EPOCH);
int index = value.indexOf(' ');
if (index == -1)
... |
python | def _parse_target(target, listen, udp, ipv6):
"""
Takes the basic version of the user args and extract as much data as
possible from target. Returns a tuple that is its arguments but
sanitized.
"""
if isinstance(target, str):
if target.startswith('nc '):
... |
java | public com.google.api.ads.adwords.axis.v201809.cm.AppUrl[] getAppUrls() {
return appUrls;
} |
python | def get_license_summary(license_code):
""" Gets the license summary and permitted, forbidden and required
behaviour """
try:
abs_file = os.path.join(_ROOT, "summary.json")
with open(abs_file, 'r') as f:
summary_license = json.loads(f.read())[license_code]
# prints summary
print(Fore.YELLOW ... |
python | def add_z(xy: np.ndarray, z: float) -> np.ndarray:
"""
Turn a 2-D transform matrix into a 3-D transform matrix (scale/shift only,
no rotation).
:param xy: A two-dimensional transform matrix (a 3x3 numpy ndarray) in the
following form:
[ 1 0 x ]
[ 0 1 y ]
... |
python | def calculate(ctx, slot, challenge, totp, digits):
"""
Perform a challenge-response operation.
Send a challenge (in hex) to a YubiKey slot with a challenge-response
credential, and read the response. Supports output as a OATH-TOTP code.
"""
controller = ctx.obj['controller']
if not challeng... |
python | def add_inputs(self, private_key=None, address=None, amount='all', max_ins=None, password=None, services=None, **modes):
"""
Make call to external service to get inputs from an address and/or private_key.
`amount` is the amount of [currency] worth of inputs (in satoshis) to add from
this... |
python | def include_once(filename, lineno, local_first):
""" Performs a file inclusion (#include) in the preprocessor.
Writes down that "filename" was included at the current file,
at line <lineno>.
The file is ignored if it was previuosly included (a warning will
be emitted though).
If local_first is... |
java | @Override
public boolean contains(ChronoElement<?> element) {
if (element == null) {
return false;
}
Object[] keys = this.keys;
if (keys == null) {
if (element == PlainDate.YEAR) {
return (this.ints[0] != Integer.MIN_VALUE);
} el... |
python | def conversion_rate(self):
"""
The percentage of participants that have converted for this variant.
Returns a > 0 float representing a percentage rate.
"""
participants = self.participant_count
if participants == 0:
return 0.0
return self.experiment.c... |
python | def get(self, path):
""" Perform a GET request with GSSAPI authentication """
# Generate token
service_name = gssapi.Name('HTTP@{0}'.format(self.url.netloc),
gssapi.NameType.hostbased_service)
ctx = gssapi.SecurityContext(usage="initiate", name=service_... |
python | async def _query(server, method, parameters, timeout=DEFAULT_TIMEOUT, verify_ssl=True,
loop: asyncio.AbstractEventLoop=None):
"""Formats and performs the asynchronous query against the API
:param server: The server to query.
:param method: The method name.
:param parameters: A dict of ... |
java | public static LanguageConfiguration get(InputStream configuration) {
try {
return unmarshal(configuration);
} catch (JAXBException e) {
throw new InitializationException("Invalid configuration file.", e);
}
} |
java | protected List<SQLiteUpdateTask> buildTaskList(int previousVersion, int currentVersion) {
List<SQLiteUpdateTask> result = new ArrayList<>();
for (Pair<Integer, ? extends SQLiteUpdateTask> item : this.options.updateTasks) {
if (item.value0 - 1 == previousVersion) {
result.add(item.value1);
previousVersio... |
python | def _read_subtitles(self, lines):
"""
Read text fragments from a subtitles format text file.
:param list lines: the lines of the subtitles text file
:raises: ValueError: if the id regex is not valid
"""
self.log(u"Parsing fragments from subtitles text format")
id... |
java | public void setCommercePriceEntryService(
com.liferay.commerce.price.list.service.CommercePriceEntryService commercePriceEntryService) {
this.commercePriceEntryService = commercePriceEntryService;
} |
python | def flushmany(self):
"""Send a potentially huge number of pending signals over the message bus.
This method assumes that the number of pending signals might
be huge, so that they might not fit into memory. However,
`SignalBus.flushmany` is not very smart in handling concurrent
s... |
java | public void perform(final ResourceVisitor visitor, final ResourceFilter filter)
{
perform(root, visitor, acceptAll, filter);
} |
java | public static void shuffle(long[] longArray) {
int swapPlace = -1;
for(int i = 0; i < longArray.length; i++) {
swapPlace = (int) (Math.random() * (longArray.length - 1 ));
XORSwap.swap(longArray, i, swapPlace);
}
} |
java | public ViewQuery onError(final OnError onError) {
params[PARAM_ONERROR_OFFSET] = "on_error";
params[PARAM_ONERROR_OFFSET+1] = onError.identifier();
return this;
} |
java | @Override
@Transactional
public Snapshot transferError(String snapshotId, String errorDetails)
throws SnapshotException {
try {
Snapshot snapshot = getSnapshot(snapshotId);
// Set snapshot state in the db
snapshot = changeSnapshotStatus(snapshot, SnapshotStat... |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'entity') and self.entity is not None:
_dict['entity'] = self.entity
if hasattr(self, 'location') and self.location is not None:
_dict['location'] = self.locati... |
java | public static float triArea2D(float[] verts, int a, int b, int c) {
float abx = verts[b] - verts[a];
float abz = verts[b + 2] - verts[a + 2];
float acx = verts[c] - verts[a];
float acz = verts[c + 2] - verts[a + 2];
return acx * abz - abx * acz;
} |
java | private Array _deserializeArray(Element el) throws ConverterException {
Array array = new ArrayImpl();
NodeList list = el.getChildNodes();
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node node = list.item(i);
if (node instanceof Element) try {
array.append(_deserialize((Element) node));... |
python | def modify_filename_id(filename):
"""Modify filename to have a unique numerical identifier."""
split_filename = os.path.splitext(filename)
id_num_re = re.compile('(\(\d\))')
id_num = re.findall(id_num_re, split_filename[-2])
if id_num:
new_id_num = int(id_num[-1].lstrip('(').rstrip(')')) + 1... |
java | public StrBuilder appendln(final StringBuilder str, final int startIndex, final int length) {
return append(str, startIndex, length).appendNewLine();
} |
python | def mtxmg(m1, m2, ncol1, nr1r2, ncol2):
"""
Multiply the transpose of a matrix with
another matrix, both of arbitrary size.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/mtxmg_c.html
:param m1: nr1r2 X ncol1 double precision matrix.
:type m1: NxM-Element Array of floats
:param m2... |
java | public List<Blog> userFollowing(Map<String, ?> options) {
return requestBuilder.get("/user/following", options).getBlogs();
} |
java | static SelectOptions newOptions() {
SelectOptions options = JavaScriptObject.createObject().cast();
options.init(Styles.FONT_AWESOME_BASE, IconType.CHECK.getCssName());
return options;
} |
python | def _compute_iso_line(self):
""" compute LineVisual vertices, connects and color-index
"""
level_index = []
connects = []
verts = []
# calculate which level are within data range
# this works for now and the existing examples, but should be tested
# thoro... |
python | def lookup_field_value(self, context, obj, field):
"""
Looks up the field value for the passed in object and field name.
Note that this method is actually called from a template, but this provides a hook
for subclasses to modify behavior if they wish to do so.
This may be used ... |
java | public Observable<ServiceResponse<Page<DeletedSasDefinitionItem>>> getDeletedSasDefinitionsNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = Str... |
java | public static TransientNodeData createNodeData(NodeData parent, InternalQName name, InternalQName primaryTypeName,
InternalQName[] mixinTypesName, String identifier, AccessControlList acl)
{
TransientNodeData nodeData = null;
QPath path = QPath.makeChildPath(parent.getQPath(), name);
nodeData... |
java | public VirtualNetworkInner getByResourceGroup(String resourceGroupName, String virtualNetworkName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, virtualNetworkName).toBlocking().single().body();
} |
java | public static List<File> findFiles(final File dir, final String filenameToSearch)
{
final List<File> foundedFileList = new ArrayList<>();
final String regex = RegExExtensions.replaceWildcardsWithRE(filenameToSearch);
final String[] children = dir.list();
for (final String filename : children)
{
if (filena... |
java | public static String formatMode(short mode, boolean directory, boolean hasExtended) {
StringBuilder str = new StringBuilder();
if (directory) {
str.append("d");
} else {
str.append("-");
}
str.append(new Mode(mode).toString());
if (hasExtended) {
str.append("+");
}
retu... |
java | @Override
@SuppressWarnings("unchecked")
public <E> Matcher<E> getMatcher() {
Matcher<E> localMatcher = (Matcher<E>) MatcherHolder.get();
Assert.state(localMatcher != null || matcher != null,
"A reference to a Matcher used by this Searcher ({0}) for searching and matching elements in the collection w... |
python | def apply2(self, func, *args, **kwargs):
"""
Apply a function on the wrapped tensor. The tensor
will be the second argument of func.
This is because many symbolic functions
(such as tensorpack's layers) takes 'scope' as the first argument.
Returns:
LinearWra... |
java | void clearValues(boolean start) {
if (start) {
mStartValues.viewValues.clear();
mStartValues.idValues.clear();
mStartValues.itemIdValues.clear();
mStartValues.nameValues.clear();
mStartValuesList = null;
} else {
mEndValues.viewValu... |
java | @Override
public BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len) throws IOException {
return new BlockLocation[] {
new LocalBlockLocation(hostName, file.getLen())
};
} |
java | public Response.ResponseBuilder getTimeGateBuilder(final LdpRequest req, final String baseUrl) {
final String identifier = getBaseUrl(baseUrl, req) + req.getPartition() + req.getPath();
return Response.status(FOUND)
.location(fromUri(identifier + "?version=" + req.getDatetime().getInstant().... |
java | public static void readGPX(Connection connection, String fileName, String tableReference, boolean deleteTables) throws IOException, SQLException {
File file = URIUtilities.fileFromString(fileName);
if (FileUtil.isFileImportable(file, "gpx")) {
GPXDriverFunction gpxdf = new GPXDriverFunction(... |
python | def from_pandas(cls, index):
"""Create baloo MultiIndex from pandas MultiIndex.
Parameters
----------
index : pandas.multi.MultiIndex
Returns
-------
MultiIndex
"""
from pandas import MultiIndex as PandasMultiIndex
check_type(index, Pand... |
java | public InvocationRouter<InvocationBaratine> buildRouter(WebApp webApp)
{
// find views
InjectorAmp inject = webApp.inject();
buildViews(inject);
ArrayList<RouteMap> mapList = new ArrayList<>();
ServicesAmp manager = webApp.services();
ServiceRefAmp serviceRef = manager.newService(new Rout... |
java | @Override
public Entity findOneById(Object id) {
if (cacheable
&& !transactionInformation.isEntireRepositoryDirty(getEntityType())
&& !transactionInformation.isEntityDirty(EntityKey.create(getEntityType(), id))) {
return l2Cache.get(delegate(), id);
}
return delegate().findOneById(id... |
python | def _parse(self, line):
"""Parse the output line"""
try:
result = line.split(':', maxsplit=4)
filename, line_num_txt, column_txt, message_type, text = result
except ValueError:
return
try:
self.line_num = int(line_num_txt.strip())
... |
java | public JSONObject deleteSynonym(String objectID, boolean forwardToReplicas, RequestOptions requestOptions) throws AlgoliaException {
if (objectID == null || objectID.length() == 0) {
throw new AlgoliaException("Invalid objectID");
}
try {
return client.deleteRequest("/1/indexes/" + encodedIndexN... |
java | @SuppressWarnings("unchecked")
public Method[] findAdaptMethodsTo(Class to) {
Method[] methods = mAdaptMethods;
List<Method> candidates = new ArrayList<Method>(methods.length);
for (int i=methods.length; --i>=0; ) {
Method method = methods[i];
if (to.isAssignabl... |
python | def operation(self, url, idp_entity_id, op, **opargs):
"""
This is the method that should be used by someone that wants
to authenticate using SAML ECP
:param url: The page that access is sought for
:param idp_entity_id: The entity ID of the IdP that should be
used fo... |
java | private static Var parseVar(String varLine) {
String[] ws = whitespace.split(varLine);
String name = ws[0];
List<String> stateNames = Arrays.asList(comma.split(ws[1]));
int numStates = stateNames.size();
return new Var(VarType.PREDICTED, numStates, name, stateNames);
} |
python | def _set_defaults(self):
"""
Set default values to fields. We assume that they are not yet populated
as this method is called just after creation of a new pk.
"""
for field_name in self._fields:
if field_name in self._init_fields:
continue
... |
java | @Override
public Time scheduleAlarm(final int offset, final EventHandler<Alarm> handler) {
final Time alarm = new ClientAlarm(this.timer.getCurrent() + offset, handler);
if (LOG.isLoggable(Level.FINEST)) {
final int eventQueueLen;
synchronized (this.schedule) {
eventQueueLen = this.numC... |
java | private void deleteRelation(Object connection, EntityMetadata entityMetadata, String rowKey)
{
List<String> relations = entityMetadata.getRelationNames();
if (relations != null)
{
for (String relation : relations)
{
if (resource != null && resource.is... |
python | def connect(self, **kwargs):
"""
Connect to the Redis Server
:param kwargs: Parameters passed directly to redis library
:return: Boolean indicating if connection successful
:kwarg host: Hostname of the Redis server
:kwarg port: Port of the Redis server
:kwarg pa... |
python | def update(self, values):
"""Add new declarations to this set/
Args:
values (dict(name, declaration)): the declarations to ingest.
"""
for k, v in values.items():
root, sub = self.split(k)
if sub is None:
self.declarations[root] = v
... |
python | def relu(inplace:bool=False, leaky:float=None):
"Return a relu activation, maybe `leaky` and `inplace`."
return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky is not None else nn.ReLU(inplace=inplace) |
java | public static String parse(String commandLine, final CommandLineParser.CallbackHandler handler, boolean strict) throws CommandFormatException {
if(commandLine == null) {
return null;
}
final ParsingStateCallbackHandler callbackHandler = getCallbackHandler(handler);
return Sta... |
java | @SuppressWarnings("unchecked")
private void updateMap(Map<String, Object> parentMap, String paramName, Object paramValue) {
Object currentValue = parentMap.get(paramName);
if (currentValue == null || !(currentValue instanceof Map)) {
if (paramValue instanceof Map) {
... |
java | public void defineOwnProperties(Context cx, ScriptableObject props) {
Object[] ids = props.getIds(false, true);
ScriptableObject[] descs = new ScriptableObject[ids.length];
for (int i = 0, len = ids.length; i < len; ++i) {
Object descObj = ScriptRuntime.getObjectElem(props, ids[i], c... |
python | def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... |
python | def instances_changed(self):
"""True if any instance has changed."""
value = bool(lib.EnvGetInstancesChanged(self._env))
lib.EnvSetInstancesChanged(self._env, int(False))
return value |
java | public synchronized static Bitmap createScaledBitmapFromLocalImageSource(String fileUrl, int maxWidth, int maxHeight, Bitmap.Config config, int orientation)
throws FileNotFoundException {
Bitmap tempBitmap = null;
if (URLUtil.isContentUrl(fileUrl)) {
try {
Uri uri = Uri.parse(fileUrl);
tempBitmap = c... |
java | public ByteBuffer getIndicesBuffer() {
final ByteBuffer buffer = CausticUtil.createByteBuffer(indices.size() * DataType.INT.getByteSize());
for (int i = 0; i < indices.size(); i++) {
buffer.putInt(indices.get(i));
}
buffer.flip();
return buffer;
} |
java | private Token encapsulatedTokenLexer(Token tkn, int c) throws IOException {
// save current line
int startLineNumber = getLineNumber();
// ignore the given delimiter
// assert c == delimiter;
for (;;) {
c = in.read();
if (c == '\\' && strategy.getUnicodeE... |
python | def pts_change_axis(pts=[], flip=[False, False], offset=[0.0, 0.0]):
'''Return given point with axes flipped and offset, converting points between cartesian axis layouts.
For example, SVG Y-axis increases top to bottom but DXF is bottom to top.
'''
assert isinstance(pts, list) and len(pts) > 0
l_pt_prev... |
java | public boolean isSpecTopicInLevelByTopicID(final Integer topicId) {
final SpecTopic foundTopic = getClosestTopicByDBId(topicId, false);
return foundTopic != null;
} |
python | def all_arch_srcarch_kconfigs():
"""
Generates Kconfig instances for all the architectures in the kernel
"""
os.environ["srctree"] = "."
os.environ["HOSTCC"] = "gcc"
os.environ["HOSTCXX"] = "g++"
os.environ["CC"] = "gcc"
os.environ["LD"] = "ld"
for arch, srcarch in all_arch_srcarch... |
java | public <T extends Model> T setBigDecimal(String attributeName, Object value) {
Converter<Object, BigDecimal> converter = modelRegistryLocal.converterForValue(
attributeName, value, BigDecimal.class);
return setRaw(attributeName, converter != null ? converter.convert(value) : Convert.toBi... |
java | protected void compareNodeList(final List<Node> controlChildren,
final List<Node> testChildren,
final int numNodes,
final DifferenceListener listener,
final ElementQualifier elemen... |
java | public static <W extends WitnessType<W>,A> CompletableFutureT<W,A> fromAnyM(final AnyM<W,A> anyM) {
return of(anyM.map(e-> {
CompletableFuture<A> f = new CompletableFuture<A>();
f.complete(e);
return f;
}));
} |
java | @Override
public boolean visit(MethodDeclaration node) {
if (isSerializationMethod(node.getExecutableElement())) {
node.remove();
}
return false;
} |
python | def send_frame(self, frame):
"""
Sends a frame to the other end of the connection.
"""
self._sendbuf += self._send_streamify(frame)
self._sendbuf_event.set() |
python | def cudnnConvolutionForward(handle, alpha, srcDesc, srcData, wDesc, w,
convDesc, algo, workspace, workSpaceSizeInBytes, beta,
destDesc, destData):
""""
Perform forward convolution. All of the form "output = alpha * Op(inputs) + beta * output".
This fu... |
python | def env_get(context):
"""Get $ENVs into the pypyr context.
Context is a dictionary or dictionary-like. context is mandatory.
context['env']['get'] must exist. It's a dictionary.
Values are the names of the $ENVs to write to the pypyr context.
Keys are the pypyr context item to which to write the $... |
java | public static MozuUrl getUnitsOfMeasureUrl(String filter, String responseFields)
{
UrlFormatter formatter = new UrlFormatter("/api/platform/reference/unitsofmeasure?filter={filter}&responseFields={responseFields}");
formatter.formatUrl("filter", filter);
formatter.formatUrl("responseFields", responseFields);... |
java | private void zSetAllColumnEditorsAndRenderers(JTable table) {
// These variables decide how many samples to look at in each column.
int maxStartRowsToRead = 30;
int maxBulkRowsToRead = 70;
int maxFoundSamplesToExamine = 21;
// Gather some variables that we will need..
Tab... |
python | def _set_bfd_vxlan(self, v, load=False):
"""
Setter method for bfd_vxlan, mapped from YANG variable /hardware/custom_profile/kap_custom_profile/bfd_vxlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bfd_vxlan is considered as a private
method. Backends... |
java | public synchronized void addHttpContent(HttpContent httpContent) {
contentObservable.notifyAddListener(httpContent);
if (messageFuture != null) {
if (ioException != null) {
blockingEntityCollector.addHttpContent(new DefaultLastHttpContent());
messageFuture.not... |
java | @Nullable
public static Number numberValue(TreePath exprPath, Context context) {
Constant val = DataFlow.expressionDataflow(exprPath, context, CONSTANT_PROPAGATION);
if (val == null || !val.isConstant()) {
return null;
}
return val.getValue();
} |
python | async def set_power(self, value: bool):
"""Toggle the device on and off."""
if value:
status = "active"
else:
status = "off"
# TODO WoL works when quickboot is not enabled
return await self.services["system"]["setPowerStatus"](status=status) |
python | def compare_string(self, expected_str, actual_str):
"""
Returns True if the two strings are equal, False otherwise
The time taken is independent of the number of characters that match
For the sake of simplicity, this function executes in constant time only
when the two strings ha... |
java | private String getFileName(String fileName) {
if (fileName != null) {
int index = fileName.indexOf(':');
if (index < 0) {
return fileName;
} else {
fileName = fileName.substring(index + 1);
index = fileName.lastIndexOf('/');
... |
java | protected void scheduleRunAsync(Runnable runnable, Time delay) {
scheduleRunAsync(runnable, delay.getSize(), delay.getUnit());
} |
java | public final JsDestinationAddress createJsSystemDestinationAddress(String prefix
,SIBUuid8 meId
)
throws NullPoint... |
java | public CmsRelationFilter filterUserDefined() {
CmsRelationFilter filter = (CmsRelationFilter)clone();
if (filter.m_types.isEmpty()) {
filter.m_types.addAll(CmsRelationType.getAllUserDefined());
} else {
filter.m_types = new HashSet<CmsRelationType>(CmsRelationType.filter... |
java | public void marshall(CreateVpcLinkRequest createVpcLinkRequest, ProtocolMarshaller protocolMarshaller) {
if (createVpcLinkRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createVpcLinkReques... |
java | public static String getEntityClassName(Class<?> clazz) {
String name = clazz.getName();
int dollar = name.indexOf("_$$_");
if (-1 == dollar) {
return name;
} else {
return name.substring(0, dollar);
}
} |
python | def rotate_around_vector_v3(v, angle_rad, norm_vec):
""" rotate v around norm_vec by angle_rad."""
cos_val = math.cos(angle_rad)
sin_val = math.sin(angle_rad)
## (v * cosVal) +
## ((normVec * v) * (1.0 - cosVal)) * normVec +
## (v ^ normVec) * sinVal)
#line1: scaleV3(v,cosVal)
#line2: do... |
java | public String getStringOutput(String appenderName, String encoding) throws UnsupportedEncodingException {
AdminToolLog4j2OutputStream baos = outputStreams.get(appenderName);
String output = "";
if (null != baos) {
output = baos.getAndReset(encoding);
}
return output.trim().isEmpty() ? null : output;
... |
java | public final EObject ruleXAndExpression() throws RecognitionException {
EObject current = null;
EObject this_XEqualityExpression_0 = null;
EObject lv_rightOperand_3_0 = null;
enterRule();
try {
// InternalXbaseWithAnnotations.g:960:2: ( (this_XEqualityExpressio... |
java | public static UserThreadPool getUserThread(String service) {
return userThreadMap == null ? null : userThreadMap.get(service);
} |
python | def get_data_id_by_slug(self, slug):
"""Find data object ID for given slug.
This method queries the Resolwe API and requires network access.
"""
resolwe_host = os.environ.get('RESOLWE_HOST_URL')
url = urllib.parse.urljoin(resolwe_host, '/api/data?slug={}&fields=id'.format(slug))... |
java | public static MozuUrl getAvailablePaymentActionsForReturnUrl(String paymentId, String returnId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/returns/{returnId}/payments/{paymentId}/actions");
formatter.formatUrl("paymentId", paymentId);
formatter.formatUrl("returnId", returnId);
return new M... |
java | public static byte[] unGzip(InputStream in, int length) throws UtilException {
GZIPInputStream gzi = null;
FastByteArrayOutputStream bos = null;
try {
gzi = (in instanceof GZIPInputStream) ? (GZIPInputStream)in : new GZIPInputStream(in);
bos = new FastByteArrayOutputStream(length);
IoUtil.copy(gzi,... |
java | private Map<Integer,Set<Integer>> getCategoryArticleMap(Wikipedia pWiki, Set<Integer> pNodes) throws WikiPageNotFoundException {
Map<Integer,Set<Integer>> categoryArticleMap = new HashMap<Integer,Set<Integer>>();
int progress = 0;
for (int node : pNodes) {
progress++;
Ap... |
python | def get_tac_permissions(calendar_id):
"""
Return a list of sorted Permission objects representing
the user permissions of a given Tacoma calendar.
:return: a list of trumba.Permission objects
corresponding to the given campus calendar.
None if error, [] if not exists
raise ... |
java | public InternalRunner createStrict(Class<?> klass) throws InvocationTargetException {
return create(klass, new Supplier<MockitoTestListener>() {
public MockitoTestListener get() {
return new MismatchReportingTestListener(Plugins.getMockitoLogger());
}
});
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.