language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public Object asConstantPoolValue() {
StringBuilder stringBuilder = new StringBuilder().append('(');
for (TypeDescription parameterType : getParameterTypes()) {
stringBuilder.append(parameterType.getDescriptor());
}
String descriptor = stringBuilder.append... |
java | public static LocalizationContext getLocalizationContext(PageContext pc,
String basename) {
LocalizationContext locCtxt = null;
ResourceBundle bundle = null;
if ((basename == null) || basename.equals("")) {
return new Loca... |
java | public static Map<String, Method> getClassWriteMethods(Class<?> clazz) {
Map<String, Method> writeMethods = classWriteMethods.get(clazz);
if (writeMethods == null) {
cacheReadWriteMethodsAndBoxField(clazz);
return classWriteMethods.get(clazz);
} else
return writeMethods;
} |
python | def getProfileInfo(exp):
"""
Prints profiling information.
Parameters:
----------------------------
@param reset (bool)
If set to True, the profiling will be reset.
"""
totalTime = 0.000001
for region in exp.network.regions.values():
timer = region.getComputeTimer()
totalTime += ... |
python | def optimize(objective_function, domain,
stopping_condition, parameters=None,
position_update=functions.std_position,
velocity_update=functions.std_velocity,
parameter_update=functions.std_parameter_update,
measurements=(),
measurer=dictionar... |
java | public final <K> Ix<T> distinct(IxFunction<? super T, K> keySelector) {
return new IxDistinct<T, K>(this, nullCheck(keySelector, "keySelector is null"));
} |
python | def ReceiveMessages(self, client_id, messages):
"""Receives and processes the messages from the source.
For each message we update the request object, and place the
response in that request's queue. If the request is complete, we
send a message to the worker.
Args:
client_id: The client whic... |
java | @Override
public final Choice2<A, B> converge(Function<? super C, ? extends CoProduct2<A, B, ?>> convergenceFn) {
return match(Choice2::a, Choice2::b, convergenceFn.andThen(cp2 -> cp2.match(Choice2::a, Choice2::b)));
} |
java | public static boolean sendRequestedBlobs(HttpServerExchange exchange) {
ByteBuffer buffer = null;
String type = null;
String etag = null;
String quotedEtag = null;
if ("css".equals(exchange.getQueryString())) {
buffer = Blobs.FILE_CSS_BUFFER.duplicate();
t... |
java | public Iterable<DContact> queryByCreatedBy(Object parent, java.lang.String createdBy) {
return queryByField(parent, DContactMapper.Field.CREATEDBY.getFieldName(), createdBy);
} |
java | public InstanceResizePolicy withInstancesToTerminate(String... instancesToTerminate) {
if (this.instancesToTerminate == null) {
setInstancesToTerminate(new com.amazonaws.internal.SdkInternalList<String>(instancesToTerminate.length));
}
for (String ele : instancesToTerminate) {
... |
python | def _importSNPs_dbSNPSNP(setName, species, genomeSource, snpsFile) :
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based"
snpData = VCFFile(snpsFile, gziped = True, stream = True)
dbSNPSNP.dropIndex(('start', 'chromosomeNumber', 'setName'))
conf.db.be... |
java | public ResultList<TVInfo> getTVSimilar(int tvID, Integer page, String language) throws MovieDbException {
return tmdbTv.getTVSimilar(tvID, page, language);
} |
java | public float getBoundsHeight(){
if (mSceneObject != null) {
GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();
return v.maxCorner.y - v.minCorner.y;
}
return 0f;
} |
java | public String getPathName()
{
if( pathName_ == null)
{
StringBuilder pathName = new StringBuilder();
IVarDef parent = getParent();
if( parent != null)
{
pathName
.append( parent.getPathName())
.append( '.');
}
String name = getName();
... |
java | public void removeExtension() {
deleteRelationships();
geoPackage.deleteTable(StyleTable.TABLE_NAME);
geoPackage.deleteTable(IconTable.TABLE_NAME);
try {
if (extensionsDao.isTableExists()) {
extensionsDao.deleteByExtension(EXTENSION_NAME);
}
} catch (SQLException e) {
throw new GeoPackageExce... |
java | public boolean getForecast(JsonObject forecast) {
this.forecast = forecast;
try {
this.currently = forecast.get("currently").asObject();
} catch (NullPointerException e) {
this.currently = null;
}
try {
this.minutely = forecast.get("minutely").asObject();
} catch (NullPointerException e) {
this.... |
python | def FromJsonString(self, value):
"""Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
... |
python | def is_binary_address(value: Any) -> bool:
"""
Checks if the given string is an address in raw bytes form.
"""
if not is_bytes(value):
return False
elif len(value) != 20:
return False
else:
return True |
python | async def stor(self, sops, splices=None):
'''
Execute a series of storage operations.
Overrides implementation in layer.py to avoid unnecessary async calls.
'''
for oper in sops:
func = self._stor_funcs.get(oper[0])
if func is None: # pragma: no cover
... |
python | def list(self, options=None, **kwds):
"""
Endpoint: /photos[/<options>]/list.json
Returns a list of Photo objects.
The options parameter can be used to narrow down the list.
Eg: options={"album": <album_id>}
"""
option_string = self._build_option_string(options)
... |
java | public void loadDefaultImports() {
/** Note: the resolver looks through these in reverse order, per
* precedence rules... so for max efficiency put the most common ones
* later. */
this.importClass("bsh.EvalError");
this.importClass("bsh.Interpreter");
this.importClass(... |
java | public String summarize()
{
return String.format(SUMMARY_FORMAT,
ticket,
action,
(client != null ? client.getServiceNumber() : 0),
(client != null ? client.getNumber() : 0),
(client != null ? client.getClientId() : 0),
... |
python | def midi_event(self, event_type, channel, param1, param2=None):
"""Convert and return the paraters as a MIDI event in bytes."""
assert event_type < 0x80 and event_type >= 0
assert channel < 16 and channel >= 0
tc = a2b_hex('%x%x' % (event_type, channel))
if param2 is None:
... |
python | def delete_tmpl(args):
"""Delete template.
Argument:
args: arguments object
"""
if args.__dict__.get('template'):
template = args.template
password = get_password(args)
token = connect.get_token(args.username, password, args.server)
processing.delete_template(args.server, ... |
python | def _ParseDateTimeValue(self, parser_mediator, date_time_value):
"""Parses a date time value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
date_time_value (str): date time value
(CSSM_DB_ATTRIBUTE_... |
python | def _track_stack_pointers(self):
"""
For each instruction, track its stack pointer offset and stack base pointer offset.
:return: None
"""
regs = {self.project.arch.sp_offset}
if hasattr(self.project.arch, 'bp_offset') and self.project.arch.bp_offset is not None:
... |
python | def names(self):
"""
Returns the player's name and real name.
Returns two empty strings if the player is unknown.
AI real name is always an empty string.
"""
if self.name == self.UNKNOWN_HUMAN_PLAYER:
return "", ""
if not self.is_ai and " " in self.name:
return "", self.name
return self.name, "" |
java | public AbstractDockerCommand withParam(String name, String value) {
parameters.put(name, value);
return this;
} |
python | def callable_check(func, arg_count=1, arg_value=None, allow_none=False):
"""Check whether func is callable, with the given number of positional arguments. Returns True if check
succeeded, False otherwise."""
if func is None:
if not allow_none:
raise ValueError('cal... |
java | static void assertEquals(String message, Object comparison1, Object comparison2)
{
if(comparison1 == comparison2)
{
return;
}
if(comparison1.equals(comparison2))
{
return;
}
System.err.println(message);
} |
java | public String getBody() {
JsonObject wrapper = new JsonObject();
wrapper.add(Ref.getTypeFromRef(ref), obj);
return gsonBuilder.create().toJson(wrapper);
} |
java | public static int cuGraphAddDependencies(CUgraph hGraph, CUgraphNode from[], CUgraphNode to[], long numDependencies)
{
return checkResult(cuGraphAddDependenciesNative(hGraph, from, to, numDependencies));
} |
java | @Override
public void onDialogRequestEricsson(MAPDialog mapDialog, AddressString destReference, AddressString origReference,
AddressString arg3, AddressString arg4) {
if (logger.isDebugEnabled()) {
logger.debug(String.format("onDialogRequest for DialogId=%d DestinationReference=%s Or... |
python | def _is_valid(self, value):
"""Return True if the input value is valid for insertion into the
inner list.
Args:
value: An object about to be inserted.
"""
# Entities have an istypeof method that can perform more sophisticated
# type checking.
if hasa... |
java | @Override
public RoundedMoney add(MonetaryAmount amount) {
MoneyUtils.checkAmountParameter(amount, currency);
if (amount.isZero()) {
return this;
}
return new RoundedMoney(number.add(amount.getNumber().numberValue(BigDecimal.class)), currency,
rounding).wi... |
java | private void flagSFSBRemoveMethods(BeanMetaData bmd, final Method[] allMethodsOfEJB, Map<Method, ArrayList<EJBMethodInfoImpl>> methodInfoMap) throws EJBConfigurationException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
String ejbName = bmd.enterpriseBeanName;
if (isTraceOn... |
java | @NotNull
public Stream<T> filterIndexed(int from, int step,
@NotNull IndexedPredicate<? super T> predicate) {
return new Stream<T>(params, new ObjFilterIndexed<T>(
new IndexedIterator<T>(from, step, iterator),
predicate));
} |
python | def add_options(parser):
"""
Add optional arguments to the parser
"""
partial_action = common.partial_append_action
file_mods = parser.add_argument_group("Sequence File Modification")
file_mods.add_argument('--line-wrap', dest='line_wrap', metavar='N',
type=int, help='Adjust line wrap fo... |
python | def ihs(h, pos, map_pos=None, min_ehh=0.05, min_maf=0.05, include_edges=False,
gap_scale=20000, max_gap=200000, is_accessible=None, use_threads=True):
"""Compute the unstandardized integrated haplotype score (IHS) for each
variant, comparing integrated haplotype homozygosity between the
reference (0... |
python | def _make_nodes(self, cwd=None):
"""
Cast generated nodes to be Arcana nodes
"""
for i, node in NipypeMapNode._make_nodes(self, cwd=cwd):
# "Cast" NiPype node to a Arcana Node and set Arcana Node
# parameters
node.__class__ = self.node_cls
... |
java | protected String normalizeName(String originalName) {
if (originalName == null || originalName.endsWith(".js")) {
return originalName;
}
return originalName + ".js";
} |
java | public void marshall(CopySnapshotRequest copySnapshotRequest, ProtocolMarshaller protocolMarshaller) {
if (copySnapshotRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(copySnapshotRequest.ge... |
java | public static <T> Observable.Transformer<T, T> applyCustomSchedulers(final Handler subscribeHandler) {
return new Observable.Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> observable) {
return observable.subscribeOn(HandlerScheduler.from(subscribe... |
java | public static Session getSession(final ServerSetup setup, Properties mailProps) {
Properties props = setup.configureJavaMailSessionProperties(mailProps, false);
log.debug("Mail session properties are {}", props);
return Session.getInstance(props, null);
} |
java | @Override
public Request<DescribeDhcpOptionsRequest> getDryRunRequest() {
Request<DescribeDhcpOptionsRequest> request = new DescribeDhcpOptionsRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
python | def post_create(self, tags, file_=None, rating=None, source=None,
rating_locked=None, note_locked=None, parent_id=None,
md5=None):
"""Function to create a new post (Requires login).
There are only two mandatory fields: you need to supply the
'tags', and y... |
python | def is_pigalle(obj: Any) -> bool:
""" Return true if the passed object as argument is a class or an
instance of class being to the Pigalle framework.
# Arguments
obj: The class or object to test.
# Returns:
bool:
* True if class or object is Piga... |
python | def writejar(self, jar):
"""Schedules all entries from the given ``jar``'s to be added to this jar save for the manifest.
:param string jar: the path to the pre-existing jar to graft into this jar
"""
if not jar or not isinstance(jar, string_types):
raise ValueError('The jar path must be a non-em... |
java | public static String messageAliasTableLocked(String lockOwner) {
return Messages.get().key(Messages.GUI_ALIASES_TABLE_LOCKED_1, lockOwner);
} |
python | def get_attribute(self, app=None, key=None):
"""Returns an application attribute
:param app: application id
:param key: attribute key or None to retrieve all values for the
given application
:returns: attribute value if key was specified, or an array of tuples
(k... |
python | def _add_value(self, skey, vtyp, key, val, _deser, null_allowed):
"""
Main method for adding a value to the instance. Does all the
checking on type of value and if among allowed values.
:param skey: string version of the key
:param vtyp: Type of value
:param key... |
python | def request_io(self, iocb):
"""Called by a client to start processing a request."""
if _debug: IOController._debug("request_io %r", iocb)
# check that the parameter is an IOCB
if not isinstance(iocb, IOCB):
raise TypeError("IOCB expected")
# bind the iocb to this co... |
python | def get_user_group(self, user=None, group=None):
"""
Get the user and group information.
Parameters
----------
user : str
User name or user id (default is the `os.getuid()`).
group : str
Group name or group id (default is the group of `user`).
... |
java | private int getPacketSize(Format codecFormat, int milliseconds) throws IllegalArgumentException {
String encoding = codecFormat.getEncoding();
if (encoding.equalsIgnoreCase(AudioFormat.GSM) ||
encoding.equalsIgnoreCase(AudioFormat.GSM_RTP)) {
return milliseconds * 4; // 1 byt... |
python | def max(self):
"""Return the maximum value in this histogram.
If there are no values in the histogram at all, return 600.
Returns:
int: The maximum value in the histogram.
"""
if len(self._data) == 0:
return 600
return next(iter(reversed(sorted(s... |
python | def ls(system, user, local, include_missing):
"""List configuration files detected (and/or examined paths)."""
# default action is to list *all* auto-detected files
if not (system or user or local):
system = user = local = True
for path in get_configfile_paths(system=system, user=user, local=l... |
python | def subvolume_create(name, dest=None, qgroupids=None):
'''
Create subvolume `name` in `dest`.
Return True if the subvolume is created, False is the subvolume is
already there.
name
Name of the new subvolume
dest
If not given, the subvolume will be created in the current
... |
python | def readDate(self):
"""
Read date from the stream.
The timezone is ignored as the date is always in UTC.
"""
ref = self.readInteger(False)
if ref & REFERENCE_BIT == 0:
return self.context.getObject(ref >> 1)
ms = self.stream.read_double()
re... |
java | public static List<CommerceNotificationQueueEntry> findBySent(
boolean sent, int start, int end,
OrderByComparator<CommerceNotificationQueueEntry> orderByComparator) {
return getPersistence().findBySent(sent, start, end, orderByComparator);
} |
python | def save_gradebook_column(self, gradebook_column_form, *args, **kwargs):
"""Pass through to provider GradebookColumnAdminSession.update_gradebook_column"""
# Implemented from kitosid template for -
# osid.resource.ResourceAdminSession.update_resource
if gradebook_column_form.is_for_updat... |
java | void notifyAsynchDeletionEnd(AsynchDeletionThread thread)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "notifyAsynchDeletionEnd", thread);
// Under the ADT lock, we'll notify any waiters and set the running
// flag to false
synchroni... |
java | public static String guessMimeTypeFromExtension(String extension) {
if (extension == null || extension.isEmpty()) {
return null;
}
return extensionToMimeTypeMap.get(extension);
} |
python | def lift(data, addr, arch, max_bytes=None, max_inst=None, bytes_offset=0, opt_level=1, traceflags=0,
strict_block_end=True, inner=False, skip_stmts=False, collect_data_refs=False):
"""
Recursively lifts blocks using the registered lifters and postprocessors. Tries each lifter in the order in
which ... |
java | private void initializeStaticPolicy(List<ProGradePolicyEntry> grantEntriesList) throws Exception {
// grant codeBase "file:${{java.ext.dirs}}/*" {
// permission java.security.AllPermission;
// };
ProGradePolicyEntry p1 = new ProGradePolicyEntry(true, debug);
Certificate[] certif... |
java | public ModifiableDBIDs determineIDs(DBIDs superSetIDs, HyperBoundingBox interval, double d_min, double d_max) {
StringBuilder msg = LOG.isDebugging() ? new StringBuilder() : null;
if(msg != null) {
msg.append("interval ").append(interval);
}
ModifiableDBIDs childIDs = DBIDUtil.newHashSet(superSet... |
java | static IOException ioeToSocketException(IOException ioe) {
if (ioe.getClass().equals(IOException.class)) {
// "se" could be a new class in stead of SocketException.
IOException se = new SocketException("Original Exception : " + ioe);
se.initCause(ioe);
/* Change the stacktrace so that origin... |
java | public void setInputChannels(java.util.Collection<Integer> inputChannels) {
if (inputChannels == null) {
this.inputChannels = null;
return;
}
this.inputChannels = new java.util.ArrayList<Integer>(inputChannels);
} |
python | def rewrap(s, width=COLS):
""" Join all lines from input string and wrap it at specified width """
s = ' '.join([l.strip() for l in s.strip().split('\n')])
return '\n'.join(textwrap.wrap(s, width)) |
java | private void startConnecting()
{
// Open the connecting socket.
try {
boolean rc = open();
// Connect may succeed in synchronous manner.
if (rc) {
handle = ioObject.addFd(fd);
connectEvent();
}
// Connect... |
java | public boolean contains(BoundingBox boundingBox) {
return getMinLongitude() <= boundingBox.getMinLongitude()
&& getMaxLongitude() >= boundingBox.getMaxLongitude()
&& getMinLatitude() <= boundingBox.getMinLatitude()
&& getMaxLatitude() >= boundingBox.getMaxLatitude();
} |
java | public static CmsSubscriptionReadMode modeForName(String modeName) {
if (MODE_NAME_ALL.equals(modeName)) {
return ALL;
} else if (MODE_NAME_VISITED.equals(modeName)) {
return VISITED;
}
return UNVISITED;
} |
java | @Nullable
public static <DATATYPE> Class <DATATYPE> getClassFromNameSafe (@Nonnull final String sName)
{
try
{
return getClassFromName (sName);
}
catch (final ClassNotFoundException e)
{
return null;
}
} |
python | def _get_from_cache(self, sector, scale, eft, basis):
"""Try to load a set of Wilson coefficients from the cache, else return
None."""
try:
return self._cache[eft][scale][basis][sector]
except KeyError:
return None |
python | def forecast(place, series=True):
"""NOAA weather forecast for a location"""
lat, lon = place
url = "http://graphical.weather.gov/xml/SOAP_server/ndfdXMLclient.php?" + \
"whichClient=NDFDgen&" + "lat=%s&lon=%s&" % (lat, lon) + \
"Unit=e&temp=temp&wspd=wspd&sky=sky&wx=wx&rh=rh&" + \
... |
python | def filterVariantAnnotation(self, vann):
"""
Returns true when an annotation should be included.
"""
# TODO reintroduce feature ID search
ret = False
if len(self._effects) != 0 and not vann.transcript_effects:
return False
elif len(self._effects) == 0:... |
python | def create_namespaced_daemon_set(self, namespace, body, **kwargs):
"""
create a DaemonSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_daemon_set(namespace, body, async... |
java | public DetectFacesRequest withAttributes(Attribute... attributes) {
java.util.ArrayList<String> attributesCopy = new java.util.ArrayList<String>(attributes.length);
for (Attribute value : attributes) {
attributesCopy.add(value.toString());
}
if (getAttributes() == null) {
... |
python | def set_unit(self, unit):
"""Set the GPS step scale
"""
# accept all core time units
if unit is None or (isinstance(unit, units.NamedUnit) and
unit.physical_type == 'time'):
self._unit = unit
return
# convert float to custom uni... |
python | def system_info(self):
"""Return system information."""
res = self.client.service.SystemInfo()
res = {ustr(x[0]): x[1] for x in res[0]}
to_str = lambda arr: '.'.join([ustr(x) for x in arr[0]])
res['OSVersion'] = to_str(res['OSVersion'])
res['RuntimeVersion'] = to_str(res... |
python | def start_consuming(self, to_tuple=False, auto_decode=True):
"""Start consuming messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChanne... |
java | @Override
public EEnum getIfcSequenceEnum() {
if (ifcSequenceEnumEEnum == null) {
ifcSequenceEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(1061);
}
return ifcSequenceEnumEEnum;
} |
java | private Map<String,Object> getMap()
{
if (m_data == null)
m_data = new HashMap<String,Object>();
return (Map<String, Object>)m_data;
} |
python | def prompt(self, for_=None, error_type=None, card_type=None, attempt=None,
**kwargs):
"""
Create a <Prompt> element
:param for_: Name of the credit card data element
:param error_type: Type of error
:param card_type: Type of the credit card
:param attempt:... |
java | public Matrix3x2f translate(Vector2fc offset, Matrix3x2f dest) {
return translate(offset.x(), offset.y(), dest);
} |
python | def _check_config():
"""Create config files as necessary."""
config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
verfile = config.CONFIG_DIR / '.version'
uptodate = verfile.is_file() and verfile.read_text() == __version__
if not uptodate:
verfile.write_text(__version__)
if not (uptodate... |
java | public int nnz() {
int sum = 0;
for (int i = 0; i < N; i++)
sum += rows[i].nnz();
return sum;
} |
python | def get_rlzs_by_gsim_grp(self, sm_lt_path=None, trts=None):
"""
:returns: a dictionary src_group_id -> gsim -> rlzs
"""
self.rlzs_assoc = self.get_rlzs_assoc(sm_lt_path, trts)
dic = {grp.id: self.rlzs_assoc.get_rlzs_by_gsim(grp.id)
for sm in self.source_models for ... |
java | private ZapMenuItem getMenuToolsFilter() {
if (menuToolsFilter == null) {
menuToolsFilter = new ZapMenuItem("menu.tools.filter");
menuToolsFilter.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
FilterDialog... |
python | def search_by(lookup, tgt_type='compound', minion_id=None):
'''
Search a dictionary of target strings for matching targets
This is the inverse of :py:func:`match.filter_by
<salt.modules.match.filter_by>` and allows matching values instead of
matching keys. A minion can be matched by multiple entrie... |
python | def get_by_page(query, page, page_size):
"""
Осуществляет пагинацию
:param query: запрос
:param page: номер страницы
:param page_size: количество объектов на странице
:return:
"""
pager = Paginator(query, page_size)
try:
models = pager.page(page)
except PageNotAnInteger:... |
python | def _init_health_checker(self):
"""
start the health checker stub and start a thread to ping it every 30 seconds
:return: None
"""
stub = Health_pb2_grpc.HealthStub(channel=self._channel)
self._health_check = stub.Check
health_check_thread = threading.Thread(targe... |
java | public void setExtension(boolean newExtension)
{
boolean oldExtension = extension;
extension = newExtension;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, XtypePackage.XIMPORT_DECLARATION__EXTENSION, oldExtension, extension));
} |
python | def pack_small_tensors(tower_grads, max_bytes=0):
"""Concatenate gradients together more intelligently.
Does binpacking
Args:
tower_grads: List of lists of (gradient, variable) tuples.
max_bytes: Int giving max number of bytes in a tensor that
may be considered small.
"""
assert max_bytes >... |
python | def arp_ip(opcode, src_mac, src_ip, dst_mac, dst_ip):
"""A convenient wrapper for IPv4 ARP for Ethernet.
This is an equivalent of the following code.
arp(ARP_HW_TYPE_ETHERNET, ether.ETH_TYPE_IP, \
6, 4, opcode, src_mac, src_ip, dst_mac, dst_ip)
"""
return arp(ARP_HW_TYPE_ETHERNE... |
python | def overlap(self, x, j=None):
"""Checks how many ellipsoid(s) `x` falls within, skipping the `j`-th
ellipsoid."""
q = len(self.within(x, j=j))
return q |
java | @RequestMapping(value = "api/servergroup/{id}", method = RequestMethod.DELETE)
public
@ResponseBody
List<ServerGroup> deleteServerGroup(Model model,
@PathVariable int id,
@RequestParam(value = "profileId", required = f... |
java | @Override
public void addRow(final KeyValue row) {
if (this.key == null) {
throw new IllegalStateException("setRow was never called on " + this);
}
final byte[] key = row.key();
if (Bytes.memcmp(this.key, key, Const.SALT_WIDTH(),
key.length - Const.SALT_WIDTH()) != 0) {
throw new... |
java | private void createChameleonMarkerFile(Path parent) throws IOException {
final Path chameleon = parent.resolve("chameleonrunner");
Files.write(chameleon, "Chameleon Runner was there".getBytes());
} |
python | def addNoiseToVector(inputVector, noiseLevel, vectorType):
"""
Add noise to SDRs
@param inputVector (array) binary vector to be corrupted
@param noiseLevel (float) amount of noise to be applied on the vector.
@param vectorType (string) "sparse" or "dense"
"""
if vectorType == 'sparse':
corruptSparse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.