query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
func (q *segmentQueue) enqueue(s *segment) bool {
q.mu.Lock()
r := q.used < q.limit
if r {
q.list.PushBack(s)
| q.used += s.data.Size() + header.TCPMinimumSize
}
q.mu.Unlock()
return r
} | csn_ccr |
func (s *TapeArchive) SetRetrievedTo(v string) *TapeArchive {
| s.RetrievedTo = &v
return s
} | csn_ccr |
Remove the specified file
@param {string} filePath the relative path (from the project root) to remove
@return {RSVP.Promise} | function (filePath) {
var projectRoot = this.project.root
var fullPath = resolve(projectRoot, filePath)
return RSVP.denodeify(unlink)(fullPath)
} | csn |
how to merge multi yaml file into csv in python | def csv2yaml(in_file, out_file=None):
"""Convert a CSV SampleSheet to YAML run_info format.
"""
if out_file is None:
out_file = "%s.yaml" % os.path.splitext(in_file)[0]
barcode_ids = _generate_barcode_ids(_read_input_csv(in_file))
lanes = _organize_lanes(_read_input_csv(in_file), barcode_ids... | cosqa |
// RFC Section 4.15 - Discriminated Union
// RFC Section 4.16 - Void
// RFC Section 4.17 - Constant
// RFC Section 4.18 - Typedef
// RFC Section 4.19 - Optional data
// RFC Sections 4.15 though 4.19 only apply to the data specification language
// which is not implemented by this package. In the case of discriminated
... | func (enc *Encoder) encodeMap(v reflect.Value) (int, error) {
// Number of elements.
n, err := enc.EncodeUint(uint32(v.Len()))
if err != nil {
return n, err
}
// Encode each key and value according to their type.
for _, key := range v.MapKeys() {
n2, err := enc.encode(key)
n += n2
if err != nil {
retu... | csn |
def contains_pt(self, pt):
"""Containment test."""
obj1, obj2 = self.objects
| return obj2.contains_pt(pt) and np.logical_not(obj1.contains_pt(pt)) | csn_ccr |
def get_wsgi_requests(request):
'''
For the given batch request, extract the individual requests and create
WSGIRequest object for each.
'''
valid_http_methods = ["get", "post", "put", "patch", "delete", "head", "options", "connect", "trace"]
requests = json.loads(request.body)
if t... | mutate the current request with the respective parameters, but mutation is ghost in the dark,
# so lets avoid. Construct the new WSGI request object for each request.
def construct_wsgi_from_data(data):
'''
Given the data in the format of url, method, body and headers, construct a new
... | csn_ccr |
// checkPermission ensures that the logged in user holds the given permission on an entity. | func (api *BaseAPI) checkPermission(tag names.Tag, perm permission.Access) error {
allowed, err := api.Authorizer.HasPermission(perm, tag)
if err != nil {
return errors.Trace(err)
}
if !allowed {
return common.ErrPerm
}
return nil
} | csn |
protected function parseResponseIntoArray($response)
{
if (!$response->isContentType('json')) {
parse_str($response->getBody(true), $array);
| return $array;
}
return $response->json();
} | csn_ccr |
Preload all the index properties and return the
property requested
@param string $propertyUri
@return Ambigous <NULL, mixed> | private function getOneCached($propertyUri)
{
if (is_null($this->cached)) {
$props = array(static::PROPERTY_INDEX_IDENTIFIER, static::PROPERTY_INDEX_TOKENIZER, static::PROPERTY_INDEX_FUZZY_MATCHING, static::PROPERTY_DEFAULT_SEARCH);
$this->cached = $this->getPropertiesValues($props);... | csn |
private int lastInGroup(int groupIndex) {
if (this.pointCoordinates == null) {
throw new IndexOutOfBoundsException();
}
final int count = getGroupCount();
if (groupIndex < 0) {
throw new IndexOutOfBoundsException(groupIndex + "<0"); //$NON-NLS-1$
}
if (groupIndex >= count) {
throw new | IndexOutOfBoundsException(groupIndex + ">=" + count); //$NON-NLS-1$
}
if (this.partIndexes != null && groupIndex < this.partIndexes.length) {
return this.partIndexes[groupIndex] - 2;
}
return this.pointCoordinates.length - 2;
} | csn_ccr |
function getDetails(addonPath) {
return readManifest(addonPath).then(function(doc) {
var em = getNamespaceId(doc, 'http://www.mozilla.org/2004/em-rdf#');
var rdf = getNamespaceId(
doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
var description = doc[rdf + 'RDF'][rdf + 'Description'][0];
... | function getNodeText(node, name) {
return node[name] && node[name][0] || '';
}
function getNamespaceId(doc, url) {
var keys = Object.keys(doc);
if (keys.length !== 1) {
throw new AddonFormatError('Malformed manifest for add-on ' + addonPath);
}
var namespaces = doc[keys[0]].$;
var ... | csn_ccr |
public Coordinate tileTopLeft(int tx, int ty, int zoomLevel) {
int px = tx * tileSize;
int py = ty * tileSize;
| Coordinate result = pixelsToMeters(px, py, zoomLevel);
return result;
} | csn_ccr |
Converts Doctrine mapping type name to a migration column method name | public static function toMigrationMethodName($type, $columnName)
{
$typeMap = self::getDoctrineTypeMap();
if (!in_array($type, $typeMap)) {
throw new SystemException(sprintf('Unknown column type: %s', $type));
}
// Some Doctrine types map to multiple migration types, fo... | csn |
def GetInstance(self, InstanceName, LocalOnly=None, IncludeQualifiers=None,
IncludeClassOrigin=None, PropertyList=None, **extra):
# pylint: disable=invalid-name,line-too-long
"""
Retrieve an instance.
This method performs the GetInstance operation
(see :term:... | **extra)
try:
stats = self.statistics.start_timer(method_name)
# Strip off host and namespace to make this a "local" object
namespace = self._iparam_namespace_from_objectname(
InstanceName, 'InstanceName')
instancename = self._ipa... | csn_ccr |
// Add attaches a new destination to the Output. Any data subsequently written
// to the output will be written to the new destination in addition to all the others.
// This method is thread-safe. | func (o *Output) Add(dst io.Writer) {
o.Lock()
defer o.Unlock()
o.dests = append(o.dests, dst)
} | csn |
python print format string fixed width | def indented_show(text, howmany=1):
"""Print a formatted indented text.
"""
print(StrTemplate.pad_indent(text=text, howmany=howmany)) | cosqa |
func (c *cluster) RemoveServer(ctx context.Context, serverID ServerID) error {
req, err := c.conn.NewRequest("POST", "_admin/cluster/removeServer")
if err != nil {
return WithStack(err)
}
if _, err := req.SetBody(serverID); err != nil {
return WithStack(err)
} |
applyContextSettings(ctx, req)
resp, err := c.conn.Do(ctx, req)
if err != nil {
return WithStack(err)
}
if err := resp.CheckStatus(200, 202); err != nil {
return WithStack(err)
}
return nil
} | csn_ccr |
public void setStartRule(int month, int dayOfMonth, int time) {
if (isFrozen()) {
throw new UnsupportedOperationException("Attempt to modify a frozen SimpleTimeZone instance.");
}
| getSTZInfo().setStart(month, -1, -1, time, dayOfMonth, false);
setStartRule(month, dayOfMonth, 0, time, WALL_TIME);
} | csn_ccr |
Extra can be a number, shortcut for increasing-calling-decreasing | function indent(extra) {
if (!this.multiline) {
return "";
}
var chr = this.indentChar;
if (this.HTML) {
chr = chr.replace(/\t/g, " ").replace(/ /g, " ");
}
return new Array(this.depth + (extra || 0)).join(chr);
} | csn |
Parses the method arguments pattern and returns the corresponding constraints array
@param string $methodArgumentsPattern The arguments pattern defined in the pointcut expression
@return array The corresponding constraints array | protected function getArgumentConstraintsFromMethodArgumentsPattern(string $methodArgumentsPattern): array
{
$matches = [];
$argumentConstraints = [];
preg_match_all(self::PATTERN_MATCHRUNTIMEEVALUATIONSDEFINITION, $methodArgumentsPattern, $matches);
$matchesCount = count($matches[... | csn |
public static void destroyAllWebSessions ()
{
// destroy all session web scopes (make a copy, because we're invalidating
// the sessions!)
for (final ISessionWebScope aSessionScope : getAllSessionWebScopes ())
{
// Unfortunately we need a special handling here
if (aSessionScope.selfDestruc... | {
// Remove from map
ScopeSessionManager.getInstance ().onScopeEnd (aSessionScope);
}
// Else the destruction was already started!
}
} | csn_ccr |
Recently Chef learned about Longest Increasing Subsequence. To be precise, he means longest strictly increasing subsequence, when he talks of longest increasing subsequence. To check his understanding, he took his favorite n-digit number and for each of its n digits, he computed the length of the longest increasing su... | m=int(input())
while m:
m-=1
n=int(input())
t=[i for i in input().split()]
print(''.join(t)) | apps |
Decodes a BigDecimal.
@param src source of encoded data
@param srcOffset offset into encoded data
@param valueRef decoded BigDecimal is stored in element 0, which may be null
@return amount of bytes read from source
@throws CorruptEncodingException if source data is corrupt
@since 1.2 | public static int decode(byte[] src, int srcOffset, BigDecimal[] valueRef)
throws CorruptEncodingException
{
try {
final int originalOffset = srcOffset;
int b = src[srcOffset++] & 0xff;
if (b >= 0xf8) {
valueRef[0] = null;
... | csn |
public function cleanEmail($email)
{
$response = $this->query($this->prepareUri('clean/email'), [$email]);
$result = $this->populate(new Email, $response);
if (!$result instanceof Email) {
| throw new RuntimeException('Unexpected populate result: ' . get_class($result). '. Expected: ' . Email::class);
}
return $result;
} | csn_ccr |
Set the plural definition.
@param int $count
@param string $rule
@return self | public function setPluralForms($count, $rule)
{
if (preg_match('/[a-z]/i', str_replace('n', '', $rule))) {
throw new \InvalidArgumentException('Invalid Plural form: ' . $rule);
}
$this->setHeader(self::HEADER_PLURAL, "nplurals={$count}; plural={$rule};");
return $this;
... | csn |
Marks a given list of statements for insertion into the current document.
Inserted statements can have an id if they should update an existing
statement, or use an empty string as id if they should be added. The
method removes duplicates and avoids unnecessary modifications by
checking the current content of the given ... | protected void markStatementsForInsertion(
StatementDocument currentDocument, List<Statement> addStatements) {
for (Statement statement : addStatements) {
addStatement(statement, true);
}
for (StatementGroup sg : currentDocument.getStatementGroups()) {
if (this.toKeep.containsKey(sg.getProperty())) {
... | csn |
def summary(self, stdout=True, plot=False):
'''
Displays diagnostics to the user
Args:
stdout (bool): print results to the console
plot (bool): use Seaborn to plot results
'''
if stdout:
print('Collinearity summary:')
print(pd.conc... | print('Validity summary:')
print(self.results['Variances'])
if plot:
verify_dependencies('seaborn')
for key, result in self.results.items():
if key == 'CorrelationMatrix':
ax = plt.axes()
sns.heatmap(result, ... | csn_ccr |
Gets the additionalTermsSource value for this ProductMarketplaceInfo.
@return additionalTermsSource * Specifies the source of the {@link #additionalTerms} value.
To revert an overridden value to its default, set this field to {@link
ValueSourceType#PARENT}. | public com.google.api.ads.admanager.axis.v201808.ValueSourceType getAdditionalTermsSource() {
return additionalTermsSource;
} | csn |
func (w *window) Reset() {
w.bucketLock.Lock()
w.buckets.Do(func(x interface{}) {
| x.(*bucket).Reset()
})
w.bucketLock.Unlock()
} | csn_ccr |
public function addEntityReflection(EntityReflectionInterface $entityReflection)
{
// At the moment slug is not configurable otherwise
$slug = $entityReflection->getSlug();
if (isset($this->entitiesBySlug[$slug])) {
| throw new DomainErrorException('Two entities are registered with the same "'.$slug.'" slug!');
}
$this->entitiesBySlug[$slug] = $entityReflection;
} | csn_ccr |
def match_route(self, url):
# type: (str) -> MatchResult
"""Match the url against known routes.
This method takes a concrete route "/foo/bar", and
matches it against a set of routes. These routes can
use param substitution corresponding to API gateway patterns.
For exam... | if len(parts) == len(url_parts):
for i, j in zip(parts, url_parts):
if j.startswith('{') and j.endswith('}'):
captured[j[1:-1]] = i
continue
if i != j:
break
else:
... | csn_ccr |
private function determineMapFor(int $index, int $parentId, array $inverseList): ?int
{
if (!isset($inverseList[$parentId])) {
throw new \InvalidArgumentException(
'Page id ' . $parentId . ' has not been mapped'
);
}
| // Lookup all children of parent page in main language.
$mainSiblings = $this->database->getPagesByPidList([$inverseList[$parentId]]);
return isset($mainSiblings[$index]) ? (int) $mainSiblings[$index]['id'] : null;
} | csn_ccr |
Logical conjunction of two boolean operators.
@param left left operator
@param right right operator
@return result of logical conjunction
@since 1.0 | public static Boolean and(Boolean left, Boolean right) {
return left && Boolean.TRUE.equals(right);
} | csn |
func initiatorEncHandshake(conn io.ReadWriter, prv *ecdsa.PrivateKey, remote *ecdsa.PublicKey) (s secrets, err error) {
h := &encHandshake{initiator: true, remote: ecies.ImportECDSAPublic(remote)}
authMsg, err := h.makeAuthMsg(prv)
if err != nil {
return s, err
}
authPacket, err := sealEIP8(authMsg, h)
if err !... | authRespMsg := new(authRespV4)
authRespPacket, err := readHandshakeMsg(authRespMsg, encAuthRespLen, prv, conn)
if err != nil {
return s, err
}
if err := h.handleAuthResp(authRespMsg); err != nil {
return s, err
}
return h.secrets(authPacket, authRespPacket)
} | csn_ccr |
def charge_balance(model):
"""Calculate the overall charge for all reactions in the model.
Yield (reaction, charge) pairs.
Args:
model: :class:`psamm.datasource.native.NativeModel`.
"""
compound_charge = {}
for compound in model.compounds:
if compound.charge is not None:
| compound_charge[compound.id] = compound.charge
for reaction in model.reactions:
charge = reaction_charge(reaction.equation, compound_charge)
yield reaction, charge | csn_ccr |
Match code lines prefixed with a variety of keywords. | def match(self, context, line):
"""Match code lines prefixed with a variety of keywords."""
return line.kind == 'code' and line.partitioned[0] in self._both | csn |
func (s *StanServer) processMsg(c *channel) {
ss := c.ss
// Since we iterate through them all.
ss.RLock()
// Walk the plain subscribers and deliver to each one
for _, sub := range ss.psubs {
s.sendAvailableMessages(c, sub)
} |
// Check the queue subscribers
for _, qs := range ss.qsubs {
s.sendAvailableMessagesToQueue(c, qs)
}
ss.RUnlock()
} | csn_ccr |
// SetCloudWatchLoggingOption sets the CloudWatchLoggingOption field's value. | func (s *AddApplicationCloudWatchLoggingOptionInput) SetCloudWatchLoggingOption(v *CloudWatchLoggingOption) *AddApplicationCloudWatchLoggingOptionInput {
s.CloudWatchLoggingOption = v
return s
} | csn |
json paramfile in python code | def load_parameters(self, source):
"""For JSON, the source it the file path"""
with open(source) as parameters_source:
return json.loads(parameters_source.read()) | cosqa |
function() {
var connectionAncestor;
if (this.graph) {
var cells = [
this,
this.getSourceElement(), // null if source is a point
| this.getTargetElement() // null if target is a point
].filter(function(item) {
return !!item;
});
connectionAncestor = this.graph.getCommonAncestor.apply(this.graph, cells);
}
return connectionAncestor || null;
} | csn_ccr |
how to add arrows to plot in python | def add_arrow(self, x1, y1, x2, y2, **kws):
"""add arrow to plot"""
self.panel.add_arrow(x1, y1, x2, y2, **kws) | cosqa |
Display a form to edit Blog settings.
@param Request $request
@param BasePage $blog
@Route("/{id}/settings", name="victoire_blog_settings")
@Method(methods={"GET", "POST"})
@ParamConverter("blog", class="VictoirePageBundle:BasePage")
@throws \InvalidArgumentException
@return Response | public function settingsAction(Request $request, BasePage $blog)
{
$form = $this->getSettingsForm($blog);
$form->handleRequest($request);
if ($request->isMethod('POST')) {
if ($form->isValid()) {
$this->getDoctrine()->getManager()->flush();
$form ... | csn |
// NewDbPermission is a helper method to create a tabletmanagerdatapb.DbPermission | func NewDbPermission(fields []*querypb.Field, values []sqltypes.Value) *tabletmanagerdatapb.DbPermission {
up := &tabletmanagerdatapb.DbPermission{
Privileges: make(map[string]string),
}
for i, field := range fields {
switch field.Name {
case "Host":
up.Host = values[i].ToString()
case "Db":
up.Db = va... | csn |
public function clean(string $key = null): ConfigInterface
{
if (null !== $key) {
unset($this->_config[$key]);
| } else {
$this->_config = [];
}
return $this;
} | csn_ccr |
Given a request, an email and optionally some additional data, ensure that
a user with the email address exists, and authenticate & login them right
away if the user is active.
Returns a tuple consisting of ``(user, created)`` upon success or ``(None,
None)`` when authentication fails. | def email_login(request, *, email, **kwargs):
"""
Given a request, an email and optionally some additional data, ensure that
a user with the email address exists, and authenticate & login them right
away if the user is active.
Returns a tuple consisting of ``(user, created)`` upon success or ``(Non... | csn |
// NewVertex builds a new Vertex from a slice of Tags. | func NewVertex(tags core.TagSlice) (*Vertex, error) {
vertex := new(Vertex)
vertex.InitBaseEntityParser()
vertex.Update(map[int]core.TypeParser{
10: core.NewFloatTypeParserToVar(&vertex.Location.X),
20: core.NewFloatTypeParserToVar(&vertex.Location.Y),
30: core.NewFloatTypeParserToVar(&vertex.Location.Z),
4... | csn |
Check the current state.
@param state The state to check.
@return <code>true</code> if it is this state, <code>false</code> else. | public boolean isState(Class<? extends State> state)
{
if (current != null)
{
return current.getClass().equals(state);
}
return false;
} | csn |
func (v Version) IncMajor() Version {
vNext := v
vNext.metadata = ""
vNext.pre = ""
vNext.patch = 0
vNext.minor = 0
vNext.major = | v.major + 1
vNext.original = v.originalVPrefix() + "" + vNext.String()
return vNext
} | csn_ccr |
func (l Links) CurrentPage() (int, error) {
switch {
case l.Previous == "" && l.Next != "":
return 1, nil |
case l.Previous != "":
prevPage, err := pageForURL(l.Previous)
if err != nil {
return 0, err
}
return prevPage + 1, nil
}
return 0, nil
} | csn_ccr |
how to add noise to sound in python | def synthesize(self, duration):
"""
Synthesize white noise
Args:
duration (numpy.timedelta64): The duration of the synthesized sound
"""
sr = self.samplerate.samples_per_second
seconds = duration / Seconds(1)
samples = np.random.uniform(low=-1., high=... | cosqa |
Remove current route data.
@return bool
@throws \Zend\Session\Exception\InvalidArgumentException | public function removeData()
{
$session = $this->getSession();
/** @noinspection PhpUndefinedFieldInspection */
if ($session->data !== null) {
unset($session->data);
return true;
}
return false;
} | csn |
Wrapper for starting a router and register it.
Args:
router_class: The router class to instantiate.
router_name: The name to give to the router.
Returns:
A handle to newly started router actor. | def start_router(router_class, router_name):
"""Wrapper for starting a router and register it.
Args:
router_class: The router class to instantiate.
router_name: The name to give to the router.
Returns:
A handle to newly started router actor.
"""
handle = router_class.remote... | csn |
Returns snapshot data from a D-Bus response.
A snapshot D-Bus response is a dbus.Struct containing the
information related to a snapshot:
[id, type, pre_snapshot, timestamp, user, description,
cleanup_algorithm, userdata]
id: dbus.UInt32
type: dbus.UInt16
pre_snapshot: dbus.UInt32
ti... | def _snapshot_to_data(snapshot):
'''
Returns snapshot data from a D-Bus response.
A snapshot D-Bus response is a dbus.Struct containing the
information related to a snapshot:
[id, type, pre_snapshot, timestamp, user, description,
cleanup_algorithm, userdata]
id: dbus.UInt32
type: dbu... | csn |
def validateStringInput(input_key,input_data, read=False):
"""
To check if a string has the required format. This is only used for POST APIs.
"""
log = clog.error_log
func = None
if '*' in input_data or '%' in input_data:
func = validationFunctionWildcard.get(input_key)
if func i... | func = reading_lfn_check
else:
func = namestr
try:
func(input_data)
except AssertionError as ae:
serverLog = str(ae) + " key-value pair (%s, %s) cannot pass input checking" %(input_key, input_data)
#print serverLog
dbsExceptionHandler("dbsException-in... | csn_ccr |
c++ calll python build | def cpp_prog_builder(build_context, target):
"""Build a C++ binary executable"""
yprint(build_context.conf, 'Build CppProg', target)
workspace_dir = build_context.get_workspace('CppProg', target.name)
build_cpp(build_context, target, target.compiler_config, workspace_dir) | cosqa |
Create an association between a sex-specific strain id
and each of the phenotypes.
Here, we create a genotype from the strain,
and a sex-specific genotype.
Each of those genotypes are created as anonymous nodes.
The evidence code is hardcoded to be:
ECO:experimental_... | def _add_g2p_assoc(self, graph, strain_id, sex, assay_id, phenotypes, comment):
"""
Create an association between a sex-specific strain id
and each of the phenotypes.
Here, we create a genotype from the strain,
and a sex-specific genotype.
Each of those genotypes are crea... | csn |
def _to_enos_networks(networks):
"""Transform the networks returned by deploy5k.
Args:
networks (dict): networks returned by
| :py:func:`enoslib.infra.provider.Provider.init`
"""
nets = []
for roles, network in networks:
nets.append(network.to_enos(roles))
logger.debug(nets)
return nets | csn_ccr |
public static String getTypeValue(Class<? extends WindupFrame> clazz)
{
TypeValue typeValueAnnotation = clazz.getAnnotation(TypeValue.class);
if (typeValueAnnotation == null)
| throw new IllegalArgumentException("Class " + clazz.getCanonicalName() + " lacks a @TypeValue annotation");
return typeValueAnnotation.value();
} | csn_ccr |
def uri_to_kwargs(uri):
"""Return a URI as kwargs for connecting to PostgreSQL with psycopg2,
applying default values for non-specified areas of the URI.
:param str uri: The connection URI
:rtype: dict
"""
parsed = urlparse(uri)
default_user = get_current_user()
password = unquote(pars... | = parse_qs(parsed.query)
if 'host' in values:
kwargs['host'] = values['host'][0]
for k in [k for k in values if k in KEYWORDS]:
kwargs[k] = values[k][0] if len(values[k]) == 1 else values[k]
try:
if kwargs[k].isdigit():
kwargs[k] = int(kwargs[k])
exce... | csn_ccr |
def duration_to_timedelta(obj):
"""Converts duration to timedelta
>>> duration_to_timedelta("10m")
>>> datetime.timedelta(0, 600)
"""
matches = DURATION_PATTERN.search(obj)
matches | = matches.groupdict(default="0")
matches = {k: int(v) for k, v in matches.items()}
return timedelta(**matches) | csn_ccr |
index of in python list | def binSearch(arr, val):
"""
Function for running binary search on a sorted list.
:param arr: (list) a sorted list of integers to search
:param val: (int) a integer to search for in the sorted array
:returns: (int) the index of the element if it is found and -1 otherwise.
"""
i = bisect_left(arr, val)
... | cosqa |
Run and skip pending operations
@param resultConsumer consumer for result of operations | private void processOperations(
final Consumer<WorkflowSystem.OperationResult<DAT, RES, OP>> resultConsumer
)
{
int origPendingCount = pending.size();
//operations which match runnable conditions
List<OP> shouldrun = pending.stream()
.filt... | csn |
public void recordAsyncOpTimeNs(SocketDestination dest, long opTimeNs) {
if(dest != null) {
getOrCreateNodeStats(dest).recordAsyncOpTimeNs(null, opTimeNs); |
recordAsyncOpTimeNs(null, opTimeNs);
} else {
this.asynOpTimeRequestCounter.addRequest(opTimeNs);
}
} | csn_ccr |
python how to check if environment defined | def _pip_exists(self):
"""Returns True if pip exists inside the virtual environment. Can be
used as a naive way to verify that the environment is installed."""
return os.path.isfile(os.path.join(self.path, 'bin', 'pip')) | cosqa |
private void updateLastMapLocalityLevel(JobInProgress job,
Task mapTaskLaunched, TaskTrackerStatus tracker) {
JobInfo info = infos.get(job);
| LocalityLevel localityLevel = localManager.taskToLocalityLevel(
job, mapTaskLaunched, tracker);
info.lastMapLocalityLevel = localityLevel;
info.timeWaitedForLocalMap = 0;
} | csn_ccr |
Tell the writer the destination to write to.
@param destination destination to write to
@return this {@link DataWriterBuilder} instance | public DataWriterBuilder<S, D> writeTo(Destination destination) {
this.destination = destination;
log.debug("For destination: {}", destination);
return this;
} | csn |
def title(self):
"""
get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the | default
value from stud.ip is used.
"""
tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title
return secure_filename(tmp) | csn_ccr |
// ValidateEvent validates the event type given it's category | func ValidateEvent(eventCategory EventCategory, event Event) bool {
valid := false
switch eventCategory {
case EventCategoryDefined:
valid = int(event) >= 0 && event < EventDefinedLast
case EventCategoryUndefined:
valid = int(event) >= 0 && event < EventUndefinedLast
case EventCategoryStarted:
valid = int(ev... | csn |
def _write_pidfile(self):
"""Write the pid file out with the process number in the pid file"""
LOGGER.debug('Writing pidfile: %s', self.pidfile_path)
| with open(self.pidfile_path, "w") as handle:
handle.write(str(os.getpid())) | csn_ccr |
Register the GAE queue connector.
@param \Illuminate\Queue\QueueManager $manager
@return void | protected function registerGaeConnector($manager)
{
$app = $this->app;
$manager->addConnector('gae', function () use ($app) {
return new GaeConnector($app['encrypter'], $app['request']);
});
} | csn |
public function getRecordStatusAction(Request $request, $databox_id, $record_id)
{
$record = $this->findDataboxById($databox_id)->get_record($record_id);
| $ret = ["status" => $this->listRecordStatus($record)];
return Result::create($request, $ret)->createResponse();
} | csn_ccr |
def built_datetime(self):
"""Return the built time as a datetime object"""
from datetime import datetime
try:
| return datetime.fromtimestamp(self.state.build_done)
except TypeError:
# build_done is null
return None | csn_ccr |
Show the form for entering the project role.
@param string $defaultRole
@param \Symfony\Component\Console\Input\InputInterface $input
@return string | private function showProjectRoleForm($defaultRole, InputInterface $input)
{
/** @var \Platformsh\Cli\Service\QuestionHelper $questionHelper */
$questionHelper = $this->getService('question_helper');
$this->stdErr->writeln("The user's project role can be " . $this->describeRoles(ProjectAcces... | csn |
protected void createGenericLoginSuccessEndState(final Flow flow) {
val state = createEndState(flow, CasWebflowConstants.STATE_ID_VIEW_GENERIC_LOGIN_SUCCESS, CasWebflowConstants.VIEW_ID_GENERIC_SUCCESS);
| state.getEntryActionList().add(createEvaluateAction("genericSuccessViewAction"));
} | csn_ccr |
public function beforeSend(Server $server)
{
// Check to make sure we have a query_port because it is required
if (!isset($this->options[Server::SERVER_OPTIONS_QUERY_PORT])
|| empty($this->options[Server::SERVER_OPTIONS_QUERY_PORT])
) {
throw new Exception(__METHOD__... |
// Let's loop the packets and set the proper pieces
foreach ($this->packets as $packet_type => $packet) {
// Update with the client port for the server
$this->packets[$packet_type] = sprintf($packet, $server->portClient());
}
} | csn_ccr |
used by the bytecode builded
@param pc pageContext
@param className
@param bundleName
@param bundleVersion
@return
@throws BundleException
@throws ClassException | public static Object invokeBIF(PageContext pc, Object[] args, String className, String bundleName, String bundleVersion) throws PageException {
try {
Class<?> clazz = ClassUtil.loadClassByBundle(className, bundleName, bundleVersion, pc.getConfig().getIdentification());
BIF bif;
if (Reflector.isInstaneOf... | csn |
public TSIGRecord
generate(Message m, byte [] b, int error, TSIGRecord old) {
Date timeSigned;
if (error != Rcode.BADTIME)
timeSigned = new Date();
else
timeSigned = old.getTimeSigned();
int fudge;
HMAC hmac = null;
if (error == Rcode.NOERROR || error == Rcode.BADTIME)
hmac = new HMAC(digest, digestBlockLen... | hmac.update(out.toByteArray());
byte [] signature;
if (hmac != null)
signature = hmac.sign();
else
signature = new byte[0];
byte [] other = null;
if (error == Rcode.BADTIME) {
out = new DNSOutput();
time = new Date().getTime() / 1000;
timeHigh = (int) (time >> 32);
timeLow = (time & 0xFFFFFFFFL);
... | csn_ccr |
Changes specified reservation to a new amount.
<b>Flags can be either of these</b>:<br>
{@link KlarnaFlags::NEW_AMOUNT}<br>
{@link KlarnaFlags::ADD_AMOUNT}<br>
@param string $rno Reservation number.
@param int $amount Amount including VAT.
@param int $flags Options which affect the behaviour.
@throws Klar... | public function changeReservation(
$rno, $amount, $flags = KlarnaFlags::NEW_AMOUNT
) {
$this->_checkRNO($rno);
$this->_checkAmount($amount);
$this->_checkInt($flags, 'flags');
$digestSecret = self::digest(
$this->colon($this->_eid, $rno, $amount, $this->_secret)
... | csn |
def clone(self):
"""Duplicate a Pangler.
Returns a copy of this Pangler, with all the same state. Both will be
bound to the same instance and have the same `id`, but new hooks will
not be shared.
"""
| p = type(self)(self.id)
p.hooks = list(self.hooks)
p.instance = self.instance
return p | csn_ccr |
def configure(self, voltage_range=RANGE_32V, gain=GAIN_AUTO,
bus_adc=ADC_12BIT, shunt_adc=ADC_12BIT):
""" Configures and calibrates how the INA219 will take measurements.
Arguments:
voltage_range -- The full scale voltage range, this is either 16V
or 32V represente... | if self._max_expected_amps is not None:
if gain == self.GAIN_AUTO:
self._auto_gain_enabled = True
self._gain = self._determine_gain(self._max_expected_amps)
else:
self._gain = gain
else:
if gain != self.GAIN_AUTO:
... | csn_ccr |
public ThreadContextDescriptor deserializeThreadContext(Map<String, String> execProps) throws IOException, ClassNotFoundException | {
return threadContextBytes == null ? null : ThreadContextDeserializer.deserialize(threadContextBytes, execProps);
} | csn_ccr |
Determine if the given attributes were changed.
@param array $changes An array attributes was change.
@param array|string|null $attributes Optional, the attribute(s) for determine.
@return bool | protected function has_changes( array $changes, $attributes = null ) {
if ( empty( $attributes ) ) {
return count( $changes ) > 0;
}
foreach ( (array) $attributes as $attribute ) {
if ( array_key_exists( $attribute, $changes ) ) {
return true;
}
}
return false;
} | csn |
Method to get an array of nodes from a given node to its root.
@param integer $pk Primary key of the node for which to get the path.
@param boolean $allFields Get all fields.
@return mixed An array of node objects including the start node.
@since 2.0 | public function getPath($pk = null, $allFields = false)
{
$k = $this->getKeyName();
$pk = $pk === null ? $this->$k : $pk;
// Get the path from the node to the root.
$query = $this->db->getQuery(true)
->select('p.' . $k . ', p.parent_id, p.level, p.lft, p.rgt')
... | csn |
Set Values to the class members
@param Response $response | private function setParams(Response $response)
{
$this->protocol = $response->getProtocolVersion();
$this->statusCode = (int) $response->getStatusCode();
$this->headers = $response->getHeaders();
$this->body = json_decode($response->getBody()->getContents());
$this->extractBo... | csn |
func (b *Bucket) SetRaw(k string, exp int, v []byte) error { |
return b.Write(k, 0, exp, v, Raw)
} | csn_ccr |
python time struct from timestamp | def utcfromtimestamp(cls, timestamp):
"""Returns a datetime object of a given timestamp (in UTC)."""
obj = datetime.datetime.utcfromtimestamp(timestamp)
obj = pytz.utc.localize(obj)
return cls(obj) | cosqa |
Animate the art exiting the screen
@param string $direction top|bottom|right|left | public function exitTo($direction)
{
$this->setupKeyframes();
$this->animate($this->keyframes->exitTo($this->getLines(), $direction));
} | csn |
protected void ensureParentage(AbstractNode child) throws IllegalStateException {
if (child.parent == this) return;
| throw new IllegalStateException(String.format(
"Can't disown child of type %s - it isn't my child (I'm a %s)",
child.getClass().getName(), this.getClass().getName()));
} | csn_ccr |
Contains the logic to render a report and its children.
@param common_report_Report $report A report to be rendered.
@param array $childRenderedReports An array of strings containing the separate rendering of $report's child reports.
@param integer $nesting The current nesting level (root = 0).
@return string The HTML... | private static function renderReport(common_report_Report $report, array $childRenderedReports = array(), $nesting = 0, $leaf = false) {
switch ($report->getType()) {
case common_report_Report::TYPE_SUCCESS:
$typeClass = 'success';
break;
... | csn |
@RequestMapping(value = "/api/scripts", method = RequestMethod.POST)
public
@ResponseBody
Script addScript(Model model,
@RequestParam(required = true) String name,
| @RequestParam(required = true) String script) throws Exception {
return ScriptService.getInstance().addScript(name, script);
} | csn_ccr |
public function countDealerShedulesVersions(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collDealerShedulesVersionsPartial && !$this->isNew();
if (null === $this->collDealerShedulesVersions || null !== $criteria || $partial) {
if ($th... | }
$query = ChildDealerShedulesVersionQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterByDealerShedules($this)
->count($con);
}
return count($this->collDe... | csn_ccr |
Get all session values | public static function wrapped_session_all($session_object)
{
global $TSUGI_SESSION_OBJECT;
if ( $session_object === null && isset($TSUGI_SESSION_OBJECT) ) $session_object = $TSUGI_SESSION_OBJECT;
if ( is_object($session_object) ) {
return $session_object->all();
}
... | csn |
how to tell if running 64 bit python | def check64bit(current_system="python"):
"""checks if you are on a 64 bit platform"""
if current_system == "python":
return sys.maxsize > 2147483647
elif current_system == "os":
import platform
pm = platform.machine()
if pm != ".." and pm.endswith('64'): # recent Python (not... | cosqa |
public synchronized void closeImmediatedly() {
close();
Iterator iterator = this.connectionsInUse.iterator();
while (iterator.hasNext()) {
PooledConnection connection = (PooledConnection) iterator.next();
SessionConnectionWrapper sessionWrapper =
(Sessi... | connection);
closeSessionWrapper(
sessionWrapper,
"Error closing session wrapper. Connection pool was shutdown immediatedly.");
}
} | csn_ccr |
// SetPortStates sets the PortStates field's value. | func (s *GetInstancePortStatesOutput) SetPortStates(v []*InstancePortState) *GetInstancePortStatesOutput {
s.PortStates = v
return s
} | csn |
how to stop pdb python | def do_quit(self, arg):
"""
quit || exit || q
Stop and quit the current debugging session
"""
for name, fh in self._backup:
setattr(sys, name, fh)
self.console.writeline('*** Aborting program ***\n')
self.console.flush()
self.console.close()
... | cosqa |
// numBits counts the number of zero and one bits in the byte. | func numBits(b byte) (zeros, ones int) {
ones = int(oneBitsLUT[b])
zeros = 8 - ones
return
} | csn |
func (f Firewall) getDefaultIngressRules(apiPort int) []network.IngressRule {
return []network.IngressRule{
{
PortRange: corenetwork.PortRange{
FromPort: 22,
ToPort: 22,
Protocol: "tcp",
},
SourceCIDRs: []string{
"0.0.0.0/0",
},
},
{
PortRange: corenetwork.PortRange{
FromPort... | ToPort: 3389,
Protocol: "tcp",
},
SourceCIDRs: []string{
"0.0.0.0/0",
},
},
{
PortRange: corenetwork.PortRange{
FromPort: apiPort,
ToPort: apiPort,
Protocol: "tcp",
},
SourceCIDRs: []string{
"0.0.0.0/0",
},
},
{
PortRange: corenetwork.PortRange{
FromPort:... | csn_ccr |
func (m *MockLambdaAPI) GetFunctionRequest(arg0 *lambda.GetFunctionInput) (*request.Request, *lambda.GetFunctionOutput) {
ret := m.ctrl.Call(m, "GetFunctionRequest", arg0)
ret0, | _ := ret[0].(*request.Request)
ret1, _ := ret[1].(*lambda.GetFunctionOutput)
return ret0, ret1
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.