language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private ThreadContextDescriptor captureThreadContext(Executor executor) {
WSManagedExecutorService managedExecutor = defaultExecutor instanceof WSManagedExecutorService //
? (WSManagedExecutorService) defaultExecutor //
: executor != defaultExecutor && executor in... |
python | def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller
is responsibile for closing the stream. Bad things happen
if you dont close the stream
"""
class flo:
def __init__(self, this, sink, upstream, repo_pa... |
java | public static CurrencyPair fromLunoPair(String lunoPair) {
return new CurrencyPair(
fromLunoCurrency(lunoPair.substring(0, 3)), fromLunoCurrency(lunoPair.substring(3)));
} |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case XtextPackage.PARAMETER__NAME:
setName(NAME_EDEFAULT);
return;
}
super.eUnset(featureID);
} |
python | def libvlc_video_set_marquee_int(p_mi, option, i_val):
'''Enable, disable or set an integer marquee option
Setting libvlc_marquee_Enable has the side effect of enabling (arg !0)
or disabling (arg 0) the marq filter.
@param p_mi: libvlc media player.
@param option: marq option to set See libvlc_video... |
python | def sql_get_oids(self, where=None):
'''
Query source database for a distinct list of oids.
'''
table = self.lconfig.get('table')
db = self.lconfig.get('db_schema_name') or self.lconfig.get('db')
_oid = self.lconfig.get('_oid')
if is_array(_oid):
_oid =... |
java | void sendDeltaWorkFailed()
{
failed.incrementAndGet();
if (trace)
log.tracef("sendDeltaWorkFailed: %s", workManagers);
if (own != null && transport != null && transport.isInitialized())
{
for (Address address : workManagers)
{
if (!own.equals(address))... |
java | protected boolean isNotSameAsOwner(MultistepExprHolder head, ElemTemplateElement ete)
{
MultistepExprHolder next = head;
while(null != next)
{
ElemTemplateElement elemOwner = getElemFromExpression(next.m_exprOwner.getExpression());
if(elemOwner == ete)
return false;
next = next.m_next;
}
... |
python | def delete_assets(self, service_id, url=None, all=False):
"""Delete CDN assets
Arguments:
service_id: The ID of the service to delete from.
url: The URL at which to delete assets
all: When True, delete all assets associated with the service_id.
You cannot specifiy both ... |
python | def polish(commit_indexes=None, urls=None):
'''
Apply certain behaviors to commits or URLs that need polishing before they are ready for screenshots
For example, if you have 10 commits in a row where static file links were broken, you could re-write the html
in memory as it is interpreted.
Keyword... |
python | def _set_env(self, env):
""" Set environment for each callback in callbackList """
for callback in self.callbacks:
if callable(getattr(callback, '_set_env', None)):
callback._set_env(env) |
java | protected void setTargetClass(Class targetClass) {
this.targetClass = targetClass;
this.readAccessors.clear();
this.writeAccessors.clear();
introspectMethods(targetClass, new HashSet());
if (isFieldAccessEnabled()) {
introspectFields(targetClass, new HashSet());
}
} |
python | def construct_format(f, type_map=CONSTRUCT_CODE):
"""
Formats for Construct.
"""
formatted = ""
if type_map.get(f.type_id, None):
return "'{identifier}' / {type_id}".format(type_id=type_map.get(f.type_id),
identifier=f.identifier)
elif f.type_id == 'string' a... |
java | private boolean matchString(final ByteBuffer bbuf) throws IOException {
if (this.isBetween) {
final String buffer = new String(bbuf.array());
if (buffer.contains(getContent())) {
return true;
}
return false;
}
final int read = getContent().length();
for (int j = 0; j < read; j++) {
if ((bbuf.... |
python | def _load_info(self):
"""Loads metadata about this table."""
if self._info is None:
try:
self._info = self._api.tables_get(self._name_parts)
except Exception as e:
raise e |
java | public double[] get(double[] target) {
if ((target == null) || (target.length != 6)) {
target = new double[6];
}
target[0] = m00;
target[1] = m01;
target[2] = m02;
target[3] = m10;
target[4] = m11;
target[5] = m12;
return target;
... |
python | def _do_taxons(self, taxon_str):
"""Taxon"""
taxons = self._get_list(taxon_str)
taxons_str = [v.split(':')[1] for v in taxons] # strip "taxon:"
taxons_int = [int(s) for s in taxons_str if s]
return taxons_int |
python | def set_user_permission(rid, uid, action='full'):
""" Sets users permission on a given resource. The resource will be created
if it doesn't exist. Actions are: read, write, update, delete, full.
:param uid: user id
:type uid: str
:param rid: resource ID
:type rid: str
... |
python | def check_valid_solution(solution, graph):
"""Check that the solution is valid: every path is visited exactly once."""
expected = Counter(
i for (i, _) in graph.iter_starts_with_index()
if i < graph.get_disjoint(i)
)
actual = Counter(
min(i, graph.get_disjoint(i))
for i i... |
python | def zip(self, destination_path, files):
"""
Takes array of files and downloads a compressed ZIP archive
to provided path
*returns* [requests.response]
```python
from filestack import Client
client = Client("<API_KEY>")
client.zip('/path/to/file/destinat... |
python | def setup(self):
"""Setup."""
self.normalize = self.config['normalize'].upper()
self.convert_encoding = self.config['convert_encoding'].lower()
self.errors = self.config['errors'].lower()
if self.convert_encoding:
self.convert_encoding = codecs.lookup(
... |
python | def input(self, prompt, default=None, show_default=True):
"""Provide a command prompt."""
return click.prompt(prompt, default=default, show_default=show_default) |
java | public long getEstimateSplitSize(String[] blocks)
{
String parts[] = null, lastParts[] = null;
long totalSize = 0;
for (String block : blocks) {
lastParts = parts;
parts = block.split("\t");
if ((lastParts != null) && (parts.length >= 3) && (lastParts.length >= 3)) {
// If same shard, simp... |
java | protected final void beanUpdate(Object bean, Object identifier, Object value) {
LOGGER.trace("Update bean \"" + bean + "\" property \"" + identifier + "\"");
String propertyName = identifier.toString();
Class beanType = bean.getClass();
Class propType = PROPERTY_CACHE.getPropertyType(b... |
java | public void setStandardsSubscriptionRequests(java.util.Collection<StandardsSubscriptionRequest> standardsSubscriptionRequests) {
if (standardsSubscriptionRequests == null) {
this.standardsSubscriptionRequests = null;
return;
}
this.standardsSubscriptionRequests = new jav... |
python | def _indices(self, indices):
"""Turn all string indices into int indices, preserving ellipsis."""
if isinstance(indices, tuple):
out = []
dim = 0
for i, index in enumerate(indices):
if index is Ellipsis:
out.append(index)
dim = len(self.shape) - len(indices) + i
... |
java | @SuppressWarnings("deprecation")
public CmsResource createFolder(String targetFolder, String folderName) throws Exception {
if (m_cms.existsResource(targetFolder + folderName)) {
m_shell.getOut().println(
getMessages().key(Messages.GUI_SHELL_FOLDER_ALREADY_EXISTS_1, targetFolder... |
java | public static float calculate(Map<String, Integer> features1, Map<String, Integer> features2) {
TreeSet<String> keys = new TreeSet<String>(features1.keySet());
keys.addAll(features2.keySet());
float sum = 0.0f;
for (String key : keys) {
Integer c1 = features1.get(key);
... |
java | public static ConfigurationException invalidConfiguration(Throwable cause, String message, Object... args) {
throw new ConfigurationException(cause, message, args);
} |
python | def require_attribute(self, attribute: str, typ: Type = _Any) -> None:
"""Require an attribute on the node to exist.
If `typ` is given, the attribute must have this type.
Args:
attribute: The name of the attribute / mapping key.
typ: The type the attribute must have.
... |
python | def set_salt_view():
'''
Helper function that sets the salt design
document. Uses get_valid_salt_views and some hardcoded values.
'''
options = _get_options(ret=None)
# Create the new object that we will shove in as the design doc.
new_doc = {}
new_doc['views'] = get_valid_salt_views()... |
python | def coordinate_reproject(x, y, s_crs, t_crs):
"""
reproject a coordinate from one CRS to another
Parameters
----------
x: int or float
the X coordinate component
y: int or float
the Y coordinate component
s_crs: int, str or :osgeo:class:`osr.SpatialReference`
the... |
python | def __set_missense_status(self, hgvs_string):
"""Sets the self.is_missense flag."""
# set missense status
if re.search('^[A-Z?]\d+[A-Z?]$', hgvs_string):
self.is_missense = True
self.is_non_silent = True
else:
self.is_missense = False |
java | public void setOverlayPainter(Painter<? super JXMapViewer> overlay)
{
Painter<? super JXMapViewer> old = getOverlayPainter();
this.overlay = overlay;
PropertyChangeListener listener = new PropertyChangeListener()
{
@Override
public void propertyChange... |
python | def isInstalledBuild(self):
"""
Determines if the Engine is an Installed Build
"""
sentinelFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'InstalledBuild.txt')
return os.path.exists(sentinelFile) |
python | def plot_posterior(
data,
var_names=None,
coords=None,
figsize=None,
textsize=None,
credible_interval=0.94,
round_to=1,
point_estimate="mean",
rope=None,
ref_val=None,
kind="kde",
bw=4.5,
bins=None,
ax=None,
**kwargs
):
"""Plot Posterior densities in the s... |
python | def create_cache_database(self):
""" Create a new SQLite3 database for use with Cache objects
:raises: IOError if there is a problem creating the database file
"""
conn = sqlite3.connect(self.database)
conn.text_factory = str
c = conn.cursor()
c.execute("""CR... |
java | public void initializeDefaultPreferences() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.P_DEFAULT_ROOT_FOLDER, PreferencesUtil.getDefaultRootFolder());
store.setDefault(PreferenceConstants.P_MAVEN_HOME, PreferencesUtil.getMavenHome());
store.setDef... |
java | public void marshall(DescribeUsersRequest describeUsersRequest, ProtocolMarshaller protocolMarshaller) {
if (describeUsersRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeUsersReques... |
python | def load_file(self, sequence):
"""Load data from an "external" data file an pass it to
the given |IOSequence|."""
try:
if sequence.filetype_ext == 'npy':
sequence.series = sequence.adjust_series(
*self._load_npy(sequence))
elif sequence... |
java | public static String formatDate(java.util.Date pDate, String format) {
if (pDate == null) {
pDate = new java.util.Date();
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(pDate);
} |
python | def ask(question, default=None):
"""
@question: str
@default: Any value which can be converted to string.
Asks a user for a input.
If default parameter is passed it will be appended to the end of the message in square brackets.
"""
question = str(question)
if default:
question ... |
java | public void layoutContainer (Container parent)
{
Insets insets = parent.getInsets();
int pcount = parent.getComponentCount();
for (int ii = 0; ii < pcount; ii++) {
Component comp = parent.getComponent(ii);
if (!comp.isVisible()) {
continue;
... |
python | def check_requires_python(requires_python):
# type: (Optional[str]) -> bool
"""
Check if the python version in use match the `requires_python` specifier.
Returns `True` if the version of python in use matches the requirement.
Returns `False` if the version of python in use does not matches the
... |
python | def lenet5(images, labels):
"""Creates a multi layer convolutional network.
The architecture is similar to that defined in LeNet 5.
Please change this to experiment with architectures.
Args:
images: The input images.
labels: The labels as dense one-hot vectors.
Returns:
A softmax result.
"""
... |
python | def concat(*cols):
"""
Concatenates multiple input columns together into a single column.
The function works with strings, binary and compatible array columns.
>>> df = spark.createDataFrame([('abcd','123')], ['s', 'd'])
>>> df.select(concat(df.s, df.d).alias('s')).collect()
[Row(s=u'abcd123')]... |
java | public Quaternionf set(AxisAngle4f axisAngle) {
return setAngleAxis(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z);
} |
python | def _patch_argument_parser(self):
"""
Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and
all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser
figure out which subpars... |
java | private static String getActionString(int action) {
switch (action) {
case Constraint.RESTRICT :
return Tokens.T_RESTRICT;
case Constraint.CASCADE :
return Tokens.T_CASCADE;
case Constraint.SET_DEFAULT :
return Tokens.T_SET ... |
python | def append_tag(self, field_number, wire_type):
"""Appends a tag containing field number and wire type information."""
self._stream.append_var_uint32(wire_format.pack_tag(field_number, wire_type)) |
python | def color_(self, i=None):
"""
Get a color from the palette
"""
global palette, color_num
if i is not None:
color_num = i
if color_num == len(palette) - 1:
color_num = 0
res = palette[color_num]
color_num += 1
return res |
java | public static String toStringType(int type, String defaultValue) {
switch (type) {
case Types.ARRAY:
return "CF_SQL_ARRAY";
case Types.BIGINT:
return "CF_SQL_BIGINT";
case Types.BINARY:
return "CF_SQL_BINARY";
case Types.BIT:
return "CF_SQL_BIT";
case Types.BOOLEAN:
return "CF_SQL_BOOLEAN... |
python | def sort_link(context, text, sort_field, visible_name=None):
"""Usage: {% sort_link "text" "field_name" %}
Usage: {% sort_link "text" "field_name" "Visible name" %}
"""
sorted_fields = False
ascending = None
class_attrib = 'sortable'
orig_sort_field = sort_field
if context.get('current_s... |
java | public static MachineTime<TimeUnit> ofPosixSeconds(BigDecimal seconds) {
BigDecimal secs = seconds.setScale(0, RoundingMode.FLOOR);
int fraction =
seconds.subtract(secs)
.multiply(BigDecimal.valueOf(MRD))
.setScale(0, RoundingMode.DOWN)
.intValueExact();
... |
java | public List<JAXBElement<Object>> get_GenericApplicationPropertyOfPlantCover() {
if (_GenericApplicationPropertyOfPlantCover == null) {
_GenericApplicationPropertyOfPlantCover = new ArrayList<JAXBElement<Object>>();
}
return this._GenericApplicationPropertyOfPlantCover;
} |
python | def register_templatetags():
""" Register templatetags defined in settings as basic templatetags """
from turboengine.conf import settings
from google.appengine.ext.webapp import template
for python_file in settings.TEMPLATE_PATH:
template.register_template_library(python_file) |
python | def three_dim_props(event):
"""
Get information for a pick event on a 3D artist.
Parameters
-----------
event : PickEvent
The pick event to process
Returns
--------
A dict with keys:
`x`: The estimated x-value of the click on the artist
`y`: The estimated y-valu... |
python | def run():
print("Environment", os.environ)
try:
os.environ["SELENIUM"]
except KeyError:
print("Please set the environment variable SELENIUM to Selenium URL")
sys.exit(1)
driver = WhatsAPIDriver(client='remote', command_executor=os.environ["SELENIUM"])
print("Waiting for QR"... |
python | def search(self, filterstr, attrlist):
"""Query the configured LDAP server."""
return self._paged_search_ext_s(self.settings.BASE, ldap.SCOPE_SUBTREE, filterstr=filterstr,
attrlist=attrlist, page_size=self.settings.PAGE_SIZE) |
java | public static boolean applyFilters(Object event, Set<EventFilter> filters, StatsTimer filterStats,
String invokerDesc, Logger logger) {
if (filters.isEmpty()) {
return true;
}
Stopwatch filterStart = filterStats.start();
try {
... |
java | public static MutableFst importFst(File fileToFst, Semiring semiring) {
Preconditions.checkArgument(fileToFst.exists(), "File to the fst.txt openfst output doesnt exist", fileToFst);
Preconditions.checkArgument(fileToFst.getName().endsWith(FST_TXT), "fst.txt path must end in .fst.txt", fileToFst);
String ba... |
java | public void getMFInstruments(KiteConnect kiteConnect) throws KiteException, IOException {
List<MFInstrument> mfList = kiteConnect.getMFInstruments();
System.out.println("size of mf instrument list: "+mfList.size());
} |
java | public void printHead(final OutputStream output) throws IOException {
final String eol = "\r\n";
final Writer writer = new Utf8OutputStreamContent(output);
for (final String line : this.head()) {
writer.append(line);
writer.append(eol);
}
writer.append(eol... |
python | def _getAnnotationAnalysis(self, varFile):
"""
Assembles metadata within the VCF header into a GA4GH Analysis object.
:return: protocol.Analysis
"""
header = varFile.header
analysis = protocol.Analysis()
formats = header.formats.items()
infos = header.inf... |
java | static String requestURI(HttpServletRequest request)
{
String uri = request.getRequestURI();
if (uri != null)
{
String contextPath = request.getContextPath();
int length = contextPath == null ? 0 : contextPath.length();
if (length > 0)
{
uri = uri.sub... |
java | public void configure() throws IOException {
// Read config file
sConfig = new Properties();
String configFile = DEFAULT_CONFIG_FILE;
if (System.getProperty("selenuim_config")!=null){
configFile = System.getProperty("selenuim_config");
}
sConfig.load(new FileReader(configFile));
// Prepare capabilitie... |
java | public void add (T element)
{
DependencyNode<T> node = new DependencyNode<T>(element);
_nodes.put(element, node);
_orphans.add(element);
} |
java | public static <T extends ISized & IChild<U>, U extends ISized> IntSupplier middleAligned(T owner, int offset)
{
return () -> {
U parent = owner.getParent();
if (owner.getParent() == null)
return 0;
return (int) (Math.ceil(((float) parent.size().height() - Padding.of(parent).vertical() - owner.size().hei... |
python | def new_action(project_id):
"""Add action."""
project = get_data_or_404('project', project_id)
if project['owner_id'] != get_current_user_id():
return jsonify(message='forbidden'), 403
form = NewActionForm()
if not form.validate_on_submit():
return jsonify(errors=form.errors), 400... |
python | def format_file_url_params(file_urls):
'''
Utility method for formatting file URL parameters for transmission
'''
file_urls_payload = {}
if file_urls:
for idx, fileurl in enumerate(file_urls):
file_urls_payload["file_url[" + str(idx) + "]"] = fileu... |
python | def _StopProfiling(self):
"""Stops profiling."""
if self._guppy_memory_profiler:
self._guppy_memory_profiler.Sample()
self._guppy_memory_profiler.Stop()
self._guppy_memory_profiler = None
if self._memory_profiler:
self._memory_profiler.Stop()
self._memory_profiler = None
... |
java | public void serialize(final DataOutput output) throws TTIOException {
try {
output.writeLong(dataKey);
output.writeBoolean(eof);
output.writeInt(val.length);
output.write(val);
} catch (final IOException exc) {
throw new TTIOException(exc);
... |
java | protected SortedMap<String, String> getProperties(ITextNode[]nodes, String language, Status[] status) {
TreeMap<String, String> map = new TreeMap<>();
for (ITextNode node : nodes) {
IValueNode valueNode = node.getValueNode(language);
if (valueNode != null) {
if (status == null || TremaCoreUt... |
java | public HostVsanInternalSystemVsanObjectOperationResult[] upgradeVsanObjects(String[] uuids, int newVersion) throws RuntimeFault, VsanFault, RemoteException {
return getVimService().upgradeVsanObjects(getMOR(), uuids, newVersion);
} |
java | public String deleteAbucoinsOrder(String orderID) throws IOException {
String resp =
abucoinsAuthenticated.deleteOrder(
orderID,
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getExchangeSpecification().getPassword(),
t... |
python | def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation
of dihedral (torsion) angles of alpha carbon backbone
Parameters
----------
traj : mdtraj.Trajectory
A molecular dynamics trajectory to featurize.
Returns
... |
java | @Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case LogPackage.LOG_ACTION:
return (EObject) createLogAction();
case LogPackage.SERVER_LOG:
return (EObject) createServerLog();
case LogPackage.PROJECT_RELATED:
return (EObject) createProjectRelated();
case... |
python | def forward(self, tokens, mask=None):
"""
Args:
tokens (:class:`torch.FloatTensor` [batch_size, num_tokens, input_dim]): Sequence
matrix to encode.
mask (:class:`torch.FloatTensor`): Broadcastable matrix to `tokens` used as a mask.
Returns:
(:c... |
java | @Override
public void configure() throws Exception {
LOG.debug("Started REST data stream source at port {}.", port);
from("netty4-http:http://0.0.0.0:" + port + "/?matchOnUriPrefix=true&httpMethodRestrict=OPTIONS,GET,POST,PUT,DELETE").
choice().
when(header(HTTP_... |
java | public void updateChannelConfiguration(UpdateChannelConfiguration updateChannelConfiguration, Orderer orderer, byte[]... signers) throws TransactionException, InvalidArgumentException {
checkChannelState();
checkOrderer(orderer);
try {
final long startLastConfigIndex = getLastConf... |
python | def process(self, input_data, ratio, end_of_input=False, verbose=False):
"""Resample the signal in `input_data`.
Parameters
----------
input_data : ndarray
Input data. A single channel is provided as a 1D array of `num_frames` length.
Input data with several chan... |
python | def _tls_hmac_verify(self, hdr, msg, mac):
"""
Provided with the record header, the TLSCompressed.fragment and the
HMAC, return True if the HMAC is correct. If we could not compute the
HMAC because the key was missing, there is no sense in verifying
anything, thus we also return ... |
python | def create_volume(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Create a glusterfs volume
name
Name of the gluster volume
bricks
Bricks to create volume from, in <peer>:<brick path> format. F... |
java | public final T fromJsonTree(JsonElement jsonTree) {
try {
JsonReader jsonReader = new JsonTreeReader(jsonTree);
return read(jsonReader);
} catch (IOException e) {
throw new JsonIOException(e);
}
} |
python | def get_repo_revision():
'''
Returns git revision string somelike `git rev-parse --short HEAD`
does.
Returns an empty string if anything goes wrong, such as missing
.hg files or an unexpected format of internal HG files or no
mercurial repository found.
'''
repopath = _findrepo()
if... |
java | public void addSummary(Record recSummary, BaseField[][] mxKeyFields, BaseField[][] mxDataFields)
{
try {
recSummary.addNew();
// First move the key to see if a record exists
this.setupSummaryKey(mxKeyFields);
boolean bSuccess = recSummary.seek("=");
... |
java | public static <T> Iterable<T> cycle(T... elements) {
return cycle(Lists.newArrayList(elements));
} |
java | public void loadModel(String modelfile) throws IOException,
ClassNotFoundException {
ObjectInputStream instream = new ObjectInputStream(new GZIPInputStream(
new FileInputStream(modelfile)));
factory = (AlphabetFactory) instream.readObject();
models = (Linear[]) instream.readObject();
instream.close... |
python | def consolidateBy(requestContext, seriesList, consolidationFunc):
"""
Takes one metric or a wildcard seriesList and a consolidation function
name.
Valid function names are 'sum', 'average', 'min', and 'max'.
When a graph is drawn where width of the graph size in pixels is smaller
than the numb... |
java | public void writeUTCDate(long time)
throws IOException
{
if (SIZE < _offset + 32)
flushBuffer();
int offset = _offset;
byte[] buffer = _buffer;
if (time % 60000L == 0) {
// compact date ::= x65 b3 b2 b1 b0
long minutes = time / 60000L;
... |
java | static Command parse(String s) {
@Cleanup
Scanner scanner = new Scanner(s);
String component = scanner.findInLine(SCANNER_PATTERN);
String command = scanner.findInLine(SCANNER_PATTERN);
ArrayList<String> args = new ArrayList<>();
String arg;
while ((arg = scanner.... |
python | def bulk_query(self, query, *multiparams):
"""Bulk insert or update."""
with self.get_connection() as conn:
conn.bulk_query(query, *multiparams) |
python | def discard_event(event: events.Event, bot_id: str = None) -> bool:
"""
Check if the incoming event needs to be discarded
Args:
event: Incoming :class:`slack.events.Event`
bot_id: Id of connected bot
Returns:
boolean
"""
if event["type"] in SKIP_EVENTS:
return T... |
python | def build_url(self):
"""Build the url path based on the filter options."""
if not self.api_filters:
return self.url
# Reduce complex objects to simpler strings
for k, v in self.api_filters.items():
if isinstance(v, datetime): # datetime > UNIX timestamp
... |
java | private static Key keyForCode(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_0: return Key.K0;
case KeyEvent.KEYCODE_1: return Key.K1;
case KeyEvent.KEYCODE_2: return Key.K2;
case KeyEvent.KEYCODE_3: return Key.K3;
case KeyEvent.KEYCODE_4: return Key.K4;
case KeyEvent.KEYCODE_5: ret... |
python | def format_field_names(obj, format_type=None):
"""
Takes a dict and returns it with formatted keys as set in `format_type`
or `JSON_API_FORMAT_FIELD_NAMES`
:format_type: Either 'dasherize', 'camelize', 'capitalize' or 'underscore'
"""
if format_type is None:
format_type = json_api_setti... |
java | public IfcColumnTypeEnum createIfcColumnTypeEnumFromString(EDataType eDataType, String initialValue) {
IfcColumnTypeEnum result = IfcColumnTypeEnum.get(initialValue);
if (result == null)
throw new IllegalArgumentException(
"The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.get... |
java | public MessageDataDesc getMessageDataDesc(String strKey)
{
if (m_messageDataDesc == null)
return null;
return m_messageDataDesc.getMessageDataDesc(strKey);
} |
python | def css(self, path):
"""
Link/embed CSS file.
"""
if self.settings.embed_content:
content = codecs.open(path, 'r', encoding='utf8').read()
tag = Style(content, type="text/css")
else:
tag = Link(href=path, rel="stylesheet", type_="text/css")
... |
python | def do_ams_put(endpoint, path, body, access_token, rformat="json", ds_min_version="3.0;NetFx"):
'''Do a AMS HTTP PUT request and return JSON.
Args:
endpoint (str): Azure Media Services Initial Endpoint.
path (str): Azure Media Services Endpoint Path.
body (str): Azure Media Services Con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.