language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static Request newUpdateOpenGraphObjectRequest(Session session, String id, String title, String imageUrl,
String url, String description, GraphObject objectProperties, Callback callback) {
OpenGraphObject openGraphObject = OpenGraphObject.Factory.createForPost(OpenGraphObject.class, null, tit... |
java | public final void nonWildcardTypeArguments() throws RecognitionException {
int nonWildcardTypeArguments_StartIndex = input.index();
try {
if ( state.backtracking>0 && alreadyParsedRule(input, 136) ) { return; }
// src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:1275:5: ( '<' typeList '>'... |
java | public void patch(String jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions) {
patchWithServiceResponseAsync(jobId, jobPatchParameter, jobPatchOptions).toBlocking().single().body();
} |
java | @SuppressWarnings("unchecked")
public EList<IfcStructuralLoadGroup> getLoadedBy() {
return (EList<IfcStructuralLoadGroup>) eGet(Ifc2x3tc1Package.Literals.IFC_STRUCTURAL_ANALYSIS_MODEL__LOADED_BY,
true);
} |
python | def c_drop(self, frequency):
'''
Capacitance of an electrode covered in liquid, normalized per unit
area (i.e., units are F/mm^2).
'''
try:
return np.interp(frequency,
self._c_drop['frequency'],
self._c_drop['c... |
python | def event_actions(self):
"""
Take actions for timed events
Returns
-------
None
"""
system = self.system
dae = system.dae
if self.switch:
system.Breaker.apply(self.t)
for item in system.check_event(self.t):
... |
java | public void mTokens() throws RecognitionException {
// InternalSimpleExpressions.g:1:8: ( T__11 | T__12 | T__13 | T__14 | T__15 | T__16 | T__17 | T__18 | T__19 | T__20 | T__21 | T__22 | T__23 | T__24 | T__25 | RULE_ID | RULE_INT | RULE_STRING | RULE_ML_COMMENT | RULE_SL_COMMENT | RULE_WS | RULE_ANY_OTHER )
... |
java | @Override
public LookupInBuilder lookupIn(String docId) {
AsyncLookupInBuilder asyncBuilder = asyncBucket.lookupIn(docId);
return new LookupInBuilder(asyncBuilder, kvTimeout, TIMEOUT_UNIT);
} |
java | @Factory
public static <T extends Throwable> Matcher<T> hasCause(final Matcher<?> matcher) {
return new ThrowableCauseMatcher<T>(matcher);
} |
java | @Override
protected boolean hasUnderflow(N node) {
if(node.isLeaf()) {
return node.getNumEntries() < leafMinimum;
}
else {
return node.getNumEntries() < dirMinimum;
}
} |
java | public void setBandwidthSegment(com.google.api.ads.admanager.axis.v201902.BandwidthGroupTargeting bandwidthSegment) {
this.bandwidthSegment = bandwidthSegment;
} |
java | private Zxid getNextProposedZxid() {
if (lastProposedZxid.getEpoch() != establishedEpoch) {
lastProposedZxid = new Zxid(establishedEpoch, -1);
}
lastProposedZxid = new Zxid(establishedEpoch,
lastProposedZxid.getXid() + 1);
return lastProposedZxid;
} |
java | private CmsXmlContent writeContent(CmsObject cms, CmsFile file, CmsXmlContent content, String encoding)
throws CmsException {
String decodedContent = content.toString();
try {
file.setContents(decodedContent.getBytes(encoding));
} catch (UnsupportedEncodingException e) {
... |
python | def do_load(self, filename):
"""Load disk image for analysis"""
try:
self.__session.load(filename)
except IOError as e:
self.logger.error(e.strerror) |
python | def delete_campaign(self, campaign_id):
"""Delete an update campaign.
:param str campaign_id: Campaign ID to delete (Required)
:return: void
"""
api = self._get_api(update_service.DefaultApi)
api.update_campaign_destroy(campaign_id)
return |
java | public NimbusClient createClient(String host, int port)
{
Map<String, Object> nimbusConf = Maps.newHashMap();
nimbusConf.put(Config.NIMBUS_HOST, host);
nimbusConf.put(Config.NIMBUS_THRIFT_PORT, port);
nimbusConf.put(Config.STORM_THRIFT_TRANSPORT_PLUGIN,
"backtype.stor... |
java | public void lockResource(CmsRequestContext context, CmsResource resource, CmsLockType type) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
checkOfflineProject(dbc);
checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, false, Cm... |
python | def delete_object(self, bucket, obj, version_id):
"""Delete an existing object.
:param bucket: The bucket (instance or id) to get the object from.
:param obj: A :class:`invenio_files_rest.models.ObjectVersion`
instance.
:param version_id: The version ID.
:returns: A ... |
java | @Nullable
private static String getQualifiedNameThroughCast(Node node) {
if (node.isName()) {
String name = node.getString();
return name.isEmpty() ? null : name;
} else if (node.isGetProp()) {
String left = getQualifiedNameThroughCast(node.getFirstChild());
if (left == null) {
... |
python | def _ident(*elements):
"""Return True if all sequences are equal.
"""
try:
# for hashable elements
return len(set(elements)) == 1
except TypeError:
# for unhashable elements
for e1, e2 in zip(elements, elements[1:]):
if e1 !... |
python | def apply(self, total_fee, refund_fee, out_refund_no, transaction_id=None,
out_trade_no=None, fee_type='CNY', op_user_id=None,
device_info=None, refund_account='REFUND_SOURCE_UNSETTLED_FUNDS',
notify_url=None):
"""
申请退款
:param total_fee: 订单总金额,单位为分
... |
java | Node parseAndRecordTypeNode(JsDocToken token) {
return parseAndRecordTypeNode(token, stream.getLineno(), stream.getCharno(),
token == JsDocToken.LEFT_CURLY, false);
} |
python | def set_plot_tcrhoc(self,linestyle=['-'],burn_limit=0.997,marker=['o'],markevery=500,end_model=[-1],deg_line=True):
'''
Plots HRDs
end_model - array, control how far in models a run is plottet, if -1 till end
symbs_1 - set symbols of runs
'''
if len(linestyle)==0:
linestyle=200*['-']
... |
java | public static List<Integer> exactTokenFinder(final String pattern,
final String[] tokens) {
final String[] patternTokens = pattern.split(" ");
int i, j;
final int patternLength = patternTokens.length;
final int sentenceLength = tokens.length;
final List<Integer> neTokens = new ArrayList<Intege... |
java | @Override
public <T> T create(EntityCreateOperation<T> creator)
throws ServiceException {
try {
return service.create(creator);
} catch (UniformInterfaceException e) {
throw processCatch(new ServiceException(e));
} catch (ClientHandlerException e) {
... |
java | public static void dump(Node alt, int lv, PrintWriter out) {
for (int i = 0; i < lv; i++)
out.print(" ");
out.println(alt.cs != null ? ('"'+alt.cs.toString()+'"') : "(null)");
if (alt.branches != null) {
for (Node br : alt.branches) {
dump(br, lv + 1, out... |
python | def render_subcommand(args):
"""Render a subcommand for human-centric viewing"""
if args.subcommand == 'delete':
return 'delete ' + args.delete_subcommand
if args.subcommand in ('wal-prefetch', 'wal-push', 'wal-fetch'):
return None
return args.subcommand |
java | public void reset() {
this.getElement().clear();
Grid.driver().findElement(By.tagName("body")).click();
this.calendar = Calendar.getInstance();
this.getElement().click();
} |
java | @Deprecated
public void addPrimaryKey(String... primaryKeyFieldName) {
StringBuilder sb = new StringBuilder(getProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, ""));
Joiner.on(",").appendTo(sb, primaryKeyFieldName);
setProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, sb.toString());
} |
python | def _clone(self, deepcopy=True, base=None):
"""Internal clone helper."""
if not base:
if self.__explicit_session:
base = self._clone_base(self.__session)
else:
base = self._clone_base(None)
values_to_clone = ("spec", "projection", "skip", ... |
java | protected String generateCreateIndexSql(final CreateSpatialIndexStatement statement,
final Database database) {
final StringBuilder sql = new StringBuilder();
sql.append("CREATE INDEX ");
final String schemaName = statement.getTableSchemaName();
final String catalogName = statement.getT... |
python | def list_public_ips(kwargs=None, call=None):
'''
List all available public IPs.
CLI Example:
.. code-block:: bash
salt-cloud -f list_public_ips <provider>
To list unavailable (assigned) IPs, use:
CLI Example:
.. code-block:: bash
salt-cloud -f list_public_ips <provider> ... |
java | protected void initializeExceptionHandler() {
// Initialize the default uncaught exception handler for all other threads
Thread.setDefaultUncaughtExceptionHandler(getDefaultUncaughtExceptionHandler());
// Initialize the uncaught exception handler for JavaFX Application Thread
JRebirth.... |
java | public static Expression sanitizedContentOrdainerFunctionForInternalBlocks(
SanitizedContentKind kind) {
return symbolWithNamespace(
NodeContentKinds.getJsImportForOrdainersFunctions(kind),
NodeContentKinds.toJsSanitizedContentOrdainerForInternalBlocks(kind));
} |
java | protected List<AbstractColumn> getVisibleColumns() {
List<AbstractColumn> visibleColums = new ArrayList<AbstractColumn>(getReport().getColumns());
for (DJGroup group : getReport().getColumnsGroups()) {
if (group.getLayout().isHideColumn()) {
visibleColums.remove(group.getColumnToGroupBy());
}
}
return... |
java | @Override
public DMatrixRMaj getR(DMatrixRMaj R, boolean compact) {
if( compact ) {
R = UtilDecompositons_DDRM.checkZerosLT(R,minLength,numCols);
} else {
R = UtilDecompositons_DDRM.checkZerosLT(R,numRows,numCols);
}
for( int j = 0; j < numCols; j++ ) {
... |
java | @Override
public ValueRange range(ChronoField field) {
switch (field) {
case DAY_OF_YEAR:
return DOY_RANGE;
case ALIGNED_WEEK_OF_MONTH:
return ALIGNED_WOM_RANGE;
case ALIGNED_WEEK_OF_YEAR:
return ALIGNED_WOY_RANGE;
... |
python | def re_symlink(input_file, soft_link_name, log=None):
"""
Helper function: relinks soft symbolic link if necessary
"""
input_file = os.fspath(input_file)
soft_link_name = os.fspath(soft_link_name)
if log is None:
prdebug = partial(print, file=sys.stderr)
else:
prdebug = log.d... |
python | def edit_matching_entry(program, arguments):
"""Edit the matching entry."""
entry = program.select_entry(*arguments)
entry.context.execute("pass", "edit", entry.name) |
java | public boolean process( List<AssociatedPair> points , FastQueue<DMatrixRMaj> solutions ) {
if( points.size() != 7 )
throw new IllegalArgumentException("Must be exactly 7 points. Not "+points.size()+" you gelatinous piece of pond scum.");
// reset data structures
solutions.reset();
// must normalize for whe... |
java | public static List<ForwardedHeader> fromString(String input) {
if (input == null || input.trim().isEmpty()) {
return emptyList();
}
StringBuilder buffer = new StringBuilder();
List<ForwardedHeader> results = new ArrayList<>();
int i = 0;
while (i < input.len... |
java | public static Variable[] getDeclaredVariables(Class<?> type) {
if (!isGeneratedClass(type))
return new Variable[0];
if (type.isInterface())
return getVariables(type);
return getVariables(getNewInstance(type));
} |
java | public static base_responses update(nitro_service client, systemgroup resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
systemgroup updateresources[] = new systemgroup[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] =... |
python | def update(self, portfolio, date, perfs=None):
'''
Actualizes the portfolio universe with the alog state
'''
# Make the manager aware of current simulation
self.portfolio = portfolio
self.perfs = perfs
self.date = date |
python | def _estimate_label_shape(self):
"""Helper function to estimate label shape"""
max_count = 0
self.reset()
try:
while True:
label, _ = self.next_sample()
label = self._parse_label(label)
max_count = max(max_count, label.shape[0])... |
python | def info(name, root=None):
'''
Return user information
name
User to get the information
root
Directory to chroot into
CLI Example:
.. code-block:: bash
salt '*' user.info root
'''
# If root is provided, we use a less portable solution that
# depends on an... |
java | public static MojoModel readFrom(MojoReaderBackend reader, final boolean readModelDescriptor) throws IOException {
try {
Map<String, Object> info = parseModelInfo(reader);
if (! info.containsKey("algorithm"))
throw new IllegalStateException("Unable to find information about the model's algorithm... |
python | def draw_image(self, ax, image):
"""Process a matplotlib image object and call renderer.draw_image"""
self.renderer.draw_image(imdata=utils.image_to_base64(image),
extent=image.get_extent(),
coordinates="data",
... |
java | public static Object stringToValue(String string) {
if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE;
}
if ("false".equalsIgnoreCase(string)) {
return Boolean.FALSE;
}
if ("null".equalsIgnoreCase(string)) {
return JSONObject.NULL;
... |
python | def parameter_names_flat(self, include_fixed=False):
"""
Return the flattened parameter names for all subsequent parameters
of this parameter. We do not include the name for self here!
If you want the names for fixed parameters as well in this list,
set include_fixed to True.
... |
java | public void marshall(GetRegexPatternSetRequest getRegexPatternSetRequest, ProtocolMarshaller protocolMarshaller) {
if (getRegexPatternSetRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getR... |
java | @Override
public int compareTo(YearQuarter other) {
int cmp = (year - other.year);
if (cmp == 0) {
cmp = quarter.compareTo(other.quarter);
}
return cmp;
} |
python | def make_srcmap_manifest(self, modelkey, components, data):
"""Build a yaml file that specfies how to make the srcmap files for a particular model
Parameters
----------
modelkey : str
Key used to identify this particular model
components : list
The binni... |
java | private static List<ProjectDefinition> collectProjects(ProjectDefinition def, List<ProjectDefinition> collected) {
collected.add(def);
for (ProjectDefinition child : def.getSubProjects()) {
collectProjects(child, collected);
}
return collected;
} |
python | def randomize(length=6, choices=None):
"""Returns a random string of the given length."""
if type(choices) == str:
choices = list(choices)
choices = choices or ascii_lowercase
return "".join(choice(choices) for _ in range(length)) |
java | public static Properties fileToProperties(String fileName, Configuration conf)
throws IOException, ConfigurationException {
PropertiesConfiguration propsConfig = new PropertiesConfiguration();
Path filePath = new Path(fileName);
URI fileURI = filePath.toUri();
if (fileURI.getScheme() == null && ... |
java | public OvhOperation serviceName_output_elasticsearch_alias_aliasId_PUT(String serviceName, String aliasId, String description, String optionId) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/output/elasticsearch/alias/{aliasId}";
StringBuilder sb = path(qPath, serviceName, aliasId);
HashMap<String... |
java | public Observable<String> deleteAsync(String listId) {
return deleteWithServiceResponseAsync(listId).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
} |
python | def create_job(batch_service_client, job_id, pool_id):
"""Creates a job with the specified ID, associated with the specified pool.
:param batch_service_client: A Batch service client.
:type batch_service_client: `azure.batch.BatchServiceClient`
:param str job_id: The ID for the job.
:param str pool... |
python | def foreignKeys(self, *a, **kw): # nopep8
"""Executes the SQLForeignKeys function and creates a result set
of column names that are foreign keys in the specified table (columns
in the specified table that refer to primary keys in other tables)
or foreign keys in other tables that refer ... |
python | def get_owner_ids_value(self, obj):
"""Extract owners' ids."""
return [
user.pk
for user in get_users_with_permission(obj, get_full_perm('owner', obj))
] |
python | def need_deployment():
'''
Salt thin needs to be deployed - prep the target directory and emit the
delimiter and exit code that signals a required deployment.
'''
if os.path.exists(OPTIONS.saltdir):
shutil.rmtree(OPTIONS.saltdir)
old_umask = os.umask(0o077) # pylint: disable=blacklisted... |
java | public void put(String id, StringWrapper toInsert,Object value)
{
MyWrapper wrapper = asMyWrapper(toInsert);
Token[] tokens = wrapper.getTokens();
for (int i=0; i<tokens.length; i++) {
ArrayList stringsWithToken = (ArrayList) index.get(tokens[i]);
if (stringsWithToken==null) index.put( tokens[i], (stri... |
python | def set(self, val, force_set=False):
"""
Sets an input with a specified value; if force_set=True, will set through javascript if webdriver fails
NOTE: if val is None, this function will interpret this to be an empty string
@type val: str
@param val: string to se... |
java | public void setCardinality(double cardinality)
{
if (cardinality < 0 || Double.isNaN(cardinality))
throw new IllegalArgumentException("Cardinality must be a positive integer or infinity, not " + cardinality);
this.cardinality = Math.ceil(cardinality);
fixCache();
} |
java | public void assign(AbstractIntDoubleMap other) {
if (!(other instanceof OpenIntDoubleHashMap)) {
super.assign(other);
return;
}
OpenIntDoubleHashMap source = (OpenIntDoubleHashMap) other;
OpenIntDoubleHashMap copy = (OpenIntDoubleHashMap) source.copy();
this.values = copy.values;
this.table = copy.table;
thi... |
java | protected BaseTile getBaseTile (int tx, int ty)
{
SceneBlock block = getBlock(tx, ty);
return (block == null) ? null : block.getBaseTile(tx, ty);
} |
python | def getCycleData(self, attri, fname, numtype='cycNum'):
"""
In this method a column of data for the associated cycle
attribute is returned.
Parameters
----------
attri : string
The name of the attribute we are looking for.
fname : string
T... |
python | def list_all(self):
"""All items"""
return list(set(
item for items in self._routes.values() for item in items
)) |
java | public void append(final Event... events) {
if (events != null && events.length > 0) {
this.events.addAll(EscSpiUtils.asList(events));
}
} |
java | protected String toLocaleString(Locale locale) {
String language = locale.getLanguage();
if(language.isEmpty()) return "";
String country = locale.getCountry();
if(country.isEmpty()) return language;
String variant = locale.getVariant();
if(variant.isEmpty()) {
return language + '-' + country;
} else... |
java | public void setParent(AstNode parent) {
if (parent == this.parent) {
return;
}
// Convert position back to absolute.
if (this.parent != null) {
setRelative(-this.parent.getAbsolutePosition());
}
this.parent = parent;
if (parent != null) {... |
java | public static String getCacheName(Method method, String methodCacheName, CacheDefaults cacheDefaultsAnnotation, boolean generate) {
assertNotNull(method, "method parameter must not be null");
assertNotNull(methodCacheName, "methodCacheName parameter must not be null");
String cacheName = methodCacheN... |
java | private void actualRefresh(final ClientMapInfo mapInfo) {
if (null == mapInfo) {
Log.logError("Cannot find map with id " + id);
return;
}
this.mapInfo = mapInfo;
srid = 0;
try {
int pos = mapInfo.getCrs().indexOf(":");
if (pos >= 0) {
srid = Integer.parseInt(mapInfo.getCrs().substring(pos + 1)... |
java | public EClass getIfcApprovalActorRelationship() {
if (ifcApprovalActorRelationshipEClass == null) {
ifcApprovalActorRelationshipEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(25);
}
return ifcApprovalActorRelationshipEClass;
} |
java | public void untag(Class<?> tagClass) {
Iterator<Tag<?>> tagIter = _tags.iterator();
while (tagIter.hasNext()) {
Tag<?> tag = tagIter.next();
if (tagClass.isInstance(tag)) {
tagIter.remove();
}
}
} |
java | public ReadRecordStatus readRecord(byte[] hostBytes, int processed) throws IOException {
int bytesRead = 0;
if (getBytesPrefetched() == 0) {
bytesRead = readFully(hostBytes, 0, RDW_LEN);
if (bytesRead < RDW_LEN) {
throw new IOException(
"No... |
python | def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False,
quote_strings=False, max_seq_items=None):
"""
This function is the sanctioned way of converting objects
to a unicode representation.
properly handles nested sequences containing unicode strings
(unicode(... |
python | def is_owner(self, user):
"""
Checks if user is the owner of object
Parameters
----------
user: get_user_model() instance
Returns
-------
bool
Author
------
Himanshu Shankar (https://himanshus.com)
"""
if user.is_... |
python | def setQuickColor( self, color ):
"""
Sets the quick color for the palette to the given color.
:param color | <QColor>
"""
colorset = XPaletteColorSet()
colorset.setPalette(QPalette(color))
self.setColorSet(colorset) |
python | def cli(env, billing_id, datacenter):
"""Adds a load balancer given the id returned from create-options."""
mgr = SoftLayer.LoadBalancerManager(env.client)
if not formatting.confirm("This action will incur charges on your "
"account. Continue?"):
raise exceptions.CLIAb... |
python | def _validated(self, value):
"""Format the value or raise a :exc:`ValidationError` if an error occurs."""
if value is None:
return None
if isinstance(value, bson.ObjectId):
return value
try:
return bson.ObjectId(value)
except (ValueError, Attri... |
python | def generate_proxy(
prefix, base_url='', verify_ssl=True, middleware=None,
append_middleware=None, cert=None, timeout=None):
"""Generate a ProxyClass based view that uses the passed base_url."""
middleware = list(middleware or HttpProxy.proxy_middleware)
middleware += list(append_middleware ... |
java | static void dataUri( CssFormatter formatter, byte[] bytes, String urlStr, String type ) {
if( type == null ) {
switch( urlStr.substring( urlStr.lastIndexOf( '.' ) + 1 ) ) {
case "gif":
type = "image/gif;base64";
break;
case "pn... |
python | def _handle_response(response, **kwargs) -> XMLResponse:
"""Requests HTTP Response handler. Attaches .html property to
class:`requests.Response <requests.Response>` objects.
"""
if not response.encoding:
response.encoding = DEFAULT_ENCODING
return response |
python | def _http_request(url,
headers=None,
data=None):
'''
Make the HTTP request and return the body as python object.
'''
if not headers:
headers = _get_headers()
session = requests.session()
log.debug('Querying %s', url)
req = session.post(url,
... |
java | public static Predicate<MonetaryAmount> filterByExcludingCurrency(
CurrencyUnit... currencies) {
if (Objects.isNull(currencies) || currencies.length == 0) {
return m -> true;
}
return isCurrency(currencies).negate();
} |
python | def floating_point(
element_name, # type: Text
attribute=None, # type: Optional[Text]
required=True, # type: bool
alias=None, # type: Optional[Text]
default=0.0, # type: Optional[float]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
... |
python | def ipv6_acl_ipv6_access_list_standard_seq_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:brocade.com:mgmt:brocade-ipv6-access-list")
ipv6 = ET.SubElement(ipv6_acl, "ipv6")
access_li... |
java | public void pressMenuItem(int index) {
if(config.commandLogging){
Log.d(config.commandLoggingTag, "pressMenuItem("+index+")");
}
presser.pressMenuItem(index);
} |
java | public static void encodeDesc(Float value, byte[] dst, int dstOffset) {
if (value == null) {
DataEncoder.encode(~0x7fffffff, dst, dstOffset);
} else {
encodeDesc(value.floatValue(), dst, dstOffset);
}
} |
python | def insertComponent(self, index, comp):
"""Inserts new component *comp* at index"""
# new component needs to be wrapped
if self.columnCountForRow(index.row()) == 0:
self.beginInsertRows(QtCore.QModelIndex(), index.row(), index.row())
self._stim.insertComponent(comp, index... |
python | def create_token(key, payload):
"""Auth token generator
payload should be a json encodable data structure
"""
token = hmac.new(key)
token.update(json.dumps(payload))
return token.hexdigest() |
java | public static void insertSort(int[] arrays) {
for (int i = 1; i < arrays.length; i++) {
int currentNumber = arrays[i];
int j = i - 1;
while (j >= 0 && arrays[j] > currentNumber) {
arrays[j + 1] = arrays[j--];
}
arrays[j + 1] = currentNu... |
java | public Object[] getAnnotations() {
if (annotations == null) {
try {
annotations = getCtClass().getAvailableAnnotations();
} catch (Exception | Error e) {
return new Object[0];
}
}
return annotations;
} |
python | def get_short_lambda_body_text(lambda_func):
"""Return the source of a (short) lambda function.
If it's impossible to obtain, returns None.
"""
try:
source_lines, _ = inspect.getsourcelines(lambda_func)
except (IOError, TypeError):
return None
# skip `def`-ed functions and long ... |
java | public Container getTargetScreen(Container component, Class<?> targetClass, boolean bComponent)
{
Container container = null;
if (bComponent)
if (component == this)
if (m_parent instanceof Container)
{
bComponent = false;
container = (Conta... |
python | def pack_data(abi_types, values) -> bytes:
"""Normalize data and pack them into a byte array"""
if len(abi_types) != len(values):
raise ValueError(
"Length mismatch between provided abi types and values. Got "
"{0} types and {1} values.".format(len(abi_types), len(values)),
... |
java | public static policymap[] get(nitro_service service) throws Exception{
policymap obj = new policymap();
policymap[] response = (policymap[])obj.get_resources(service);
return response;
} |
java | public void insertRecord(long recordPointer, long keyPrefix, boolean prefixIsNull) {
if (!hasSpaceForAnotherRecord()) {
throw new IllegalStateException("There is no space for new record");
}
if (prefixIsNull && radixSortSupport != null) {
// Swap forward a non-null record to make room for this o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.