query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
function(nodemon) {
nodemon.on('log', function(event) {
console.log(event.colour);
});
// opens browser on initial server start
nodemon.on('config:update', function() {
// Delay before server listens on port
setTimeout(function()... | nodemon.on('restart', function() {
// Delay before server listens on port
setTimeout(function() {
require('fs').writeFileSync('.rebooted', 'rebooted');
}, 3000);
});
} | csn_ccr |
func (diff *differ) Diff(out io.Writer, a io.ReadSeeker, b io.ReadSeeker) error {
var src, dst []byte
var err error
if src, err = ioutil.ReadAll(a); err != nil {
return err
}
if dst, err = ioutil.ReadAll(b); err != nil {
return err
| }
patch := diff.dmp.PatchMake(string(src), string(dst))
diffText := strings.Replace(diff.dmp.PatchToText(patch), "%0A", "", -1)
_, err = fmt.Fprint(out, diffText)
return err
} | csn_ccr |
func (m *Source) Open(tableName string) (schema.Conn, error) {
tableName = strings.ToLower(tableName)
if ds, ok := m.tables[tableName]; ok {
return &Table{StaticDataSource: ds}, nil
}
err := m.loadTable(tableName)
if err != nil {
u.Errorf("could not | load table %q err=%v", tableName, err)
return nil, err
}
ds := m.tables[tableName]
return &Table{StaticDataSource: ds}, nil
} | csn_ccr |
public function unRegister()
{
if (isset(static::$handlers[$this->handlerId])) {
if (!is_null($this->getKey())) {
static::$keys[$this->getKey()]--;
}
| unset(static::$handlers[$this->handlerId]);
return true;
}
return false;
} | csn_ccr |
// AutoID returns the auto id of this hprose client.
// If the id is not initialized, it be initialized and returned. | func (client *BaseClient) AutoID() (string, error) {
client.topicManager.locker.RLock()
if client.id != "" {
client.topicManager.locker.RUnlock()
return client.id, nil
}
client.topicManager.locker.RUnlock()
client.topicManager.locker.Lock()
defer client.topicManager.locker.Unlock()
if client.id != "" {
ret... | csn |
function (x, y) {
var a = this.val,
_x = x,
_y = typeof(y) === "undefined" ? _x : y;
a[0] *= _x;
a[1] *= _x; |
a[3] *= _y;
a[4] *= _y;
return this;
} | csn_ccr |
def query_one(self, sql, params=None):
"""Grab just one record
"""
| r = self.engine.execute(sql, params)
return r.fetchone() | csn_ccr |
def event_strips_for_month(shown_date, first_day_of_week=0, find_options = {})
if first_day_of_week.is_a?(Hash)
find_options.merge!(first_day_of_week)
first_day_of_week = 0
end
strip_start, strip_end | = get_start_and_end_dates(shown_date, first_day_of_week)
events = events_for_date_range(strip_start, strip_end, find_options)
event_strips = create_event_strips(strip_start, strip_end, events)
event_strips
end | csn_ccr |
protected function request($url)
{
$response = null;
try {
$response = $this->getHttpClient()
->get($url)
| ->send();
} catch (ClientErrorResponseException $e) {
return Json::encode([
'error' => $e->getMessage()
]);
}
return $response->json();
} | csn_ccr |
Given two objects, merge src into dst. - If a property in src has a truthy value in ignoreMap then skip merging it. - If a property exists in src and not in dst, the property is added to dst. - If an array property exists in src and in dst, the src elements are added to dst. - If an array property exists in dst and a n... | function merge(dst, src, ignoreMap)
{
if (isObject( dst ) && isObject( src ))
{
for (var prop in src)
{
if (!ignoreMap || !ignoreMap[ prop ])
{
var adding = src[ prop ];
if (prop in dst)
{
var existing = dst[ prop ];
if (isArray( existing ))
... | csn |
def handle(self, **options):
"""Exported "eighth_activity_permissions" table in CSV format."""
perm_map = {}
with open('eighth_activity_permissions.csv', 'r') as absperms:
perms = csv.reader(absperms)
for row in perms:
aid, uid = row
try:
... | self.stdout.write("Activity {} doesn't exist".format(aid))
else:
self.stdout.write("{}: {}".format(aid, EighthActivity.objects.get(id=aid)))
grp, _ = Group.objects.get_or_create(name="{} -- Permissions".format("{}".format(act)[:55]))
users = perm_map[aid]
... | csn_ccr |
func If(condition bool, condTrue Cond, condFalse ...Cond) Cond {
var c = condIf{
condition: condition,
condTrue: condTrue, |
}
if len(condFalse) > 0 {
c.condFalse = condFalse[0]
}
return c
} | csn_ccr |
private static function extractEnclosedFieldContent()
{
if ((self::$line[0] ?? '') === self::$enclosure) {
self::$line = substr(self::$line, 1);
}
$content = '';
while (false !== self::$line) {
list($buffer, $remainder) = explode(self::$enclosure, self::$line... | {
return $content;
}
return rtrim($content, "\r\n");
}
$char = self::$line[0] ?? '';
if ($char === self::$delimiter) {
self::$line = substr(self::$line, 1);
return $content;
}
if ($char === self::$enclosure) {
... | csn_ccr |
def unitary(val: Any,
default: TDefault = RaiseTypeErrorIfNotProvided
) -> Union[np.ndarray, TDefault]:
"""Returns a unitary matrix describing the given value.
Args:
val: The value to describe with a unitary matrix.
default: Determines the fallback behavior when `val` do... | # Fallback to decomposition for gates and operations
if isinstance(val, (Gate, Operation)):
decomposed_unitary = _decompose_and_get_unitary(val)
if decomposed_unitary is not None:
return decomposed_unitary
if default is not RaiseTypeErrorIfNotProvided:
return default
... | csn_ccr |
Sets the DST start rule to a fixed date within a month.
@param month The month in which this rule occurs (0-based).
@param dayOfMonth The date in that month (1-based).
@param time The time of that day (number of millis after midnight)
when DST takes effect in local wall time, which is
standard time... | 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, ... | csn |
Generates M random trajectories of length N each with time step dt | def generate_trajs(self, M, N, start=None, stop=None, dt=1):
""" Generates M random trajectories of length N each with time step dt """
from msmtools.generation import generate_trajs
return generate_trajs(self._P, M, N, start=start, stop=stop, dt=dt) | csn |
Returns the Device for the given \Wurfl\Request_GenericRequest
@param Request\GenericRequest $request
@return \Wurfl\CustomDevice | private function getDeviceForRequest(Request\GenericRequest $request)
{
Handlers\Utils::reset();
$deviceId = $this->deviceIdForRequest($request);
return $this->getWrappedDevice($deviceId, $request);
} | csn |
Computes a join on two tables | def join(expr1, expr2, d1_keys, d2_keys, keys_type, d1_vals, df1_vals_ty, d2_vals, df2_vals_ty):
"""
Computes a join on two tables
"""
weld_obj = WeldObject(encoder_, decoder_)
df1_var = weld_obj.update(expr1)
if isinstance(expr1, WeldObject):
df1_var = expr1.obj_id
weld_obj.... | csn |
public function setButtonSubmit($submitButton)
{
if (\is_string($submitButton)) {
$this->submitButton = CmsButton::getInstance($submitButton);
} elseif ($submitButton instanceof CmsButton) {
$this->submitButton = $submitButton;
} else {
| throw new InvalidArgumentException('setButtonSubmit parameter type must be String or CmsButton.');
}
return $this;
} | csn_ccr |
public BooleanProperty isCurvedProperty() {
if (this.isCurved == null) {
this.isCurved = new ReadOnlyBooleanWrapper(this, MathFXAttributeNames.IS_CURVED, false);
this.isCurved.bind(Bindings.createBooleanBinding(() -> {
for (final PathElementType type : innerTypesProperty()) {
| if (type == PathElementType.CURVE_TO || type == PathElementType.QUAD_TO) {
return true;
}
}
return false;
},
innerTypesProperty()));
}
return this.isCurved;
} | csn_ccr |
def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
firs... | An object or changeset key for the collation to be performed on.
second_axis : {'create','modify','delete'}
An action key to be added to the first_axis key.
"""
if first_axis not in collation:
collation[first_axis] = {}
collation[first_axis]["create"] = 0
collation[first_... | csn_ccr |
Returns true if the bundle is a valid bundle
@param requestedPath
the requested path
@return true if the bundle is a valid bundle | protected BundleHashcodeType isValidBundle(String requestedPath) {
BundleHashcodeType bundleHashcodeType = BundleHashcodeType.VALID_HASHCODE;
if (!jawrConfig.isDebugModeOn()) {
bundleHashcodeType = bundlesHandler.getBundleHashcodeType(requestedPath);
}
return bundleHashcodeType;
} | csn |
def U(data, bits=None, endian=None, target=None):
"""
Unpack an unsigned pointer for a given target.
Args:
data(bytes): The data to unpack.
bits(:class:`pwnypack.target.Target.Bits`): Override the default
word size. If ``None`` it will look at the word size of
``targ... | byte order. If ``None``, it will look at the byte order of
the ``target`` argument.
target(:class:`~pwnypack.target.Target`): Override the default byte
order. If ``None``, it will look at the byte order of
the global :data:`~pwnypack.target.target`.
Returns:
... | csn_ccr |
func (s *SVG) Polyline(str string, args map[string]interface{}) {
polylineStr := fmt.Sprintf("<polyline points='%s' %s | />", str, s.WriteArgs(args))
s.svgString += polylineStr
} | csn_ccr |
protected function initNamespace()
{
$namespaces = $this->config->get('namespaces', null);
if ($namespaces !== null) {
foreach ($namespaces as $namespace => $path) {
| $this->loader->registerNamespaces([$namespace => $path], true);
}
$this->loader->register();
$this->di->set('loader', $this->loader);
}
} | csn_ccr |
// Shared function between CreateContainer and ExecProcess, because those expect
// the console to be properly setup after the process has been started. | func (a *agentGRPC) postExecProcess(ctr *container, proc *process) error {
if ctr == nil {
return grpcStatus.Error(codes.InvalidArgument, "Container cannot be nil")
}
if proc == nil {
return grpcStatus.Error(codes.InvalidArgument, "Process cannot be nil")
}
defer proc.closePostStartFDs()
// Setup terminal ... | csn |
// GetJournalManager returns the JournalManager tied to a particular
// config. | func GetJournalManager(config Config) (*JournalManager, error) {
bserver := config.BlockServer()
jbserver, ok := bserver.(journalBlockServer)
if !ok {
return nil, errors.New("Write journal not enabled")
}
return jbserver.jManager, nil
} | csn |
turn string into int in python | def try_cast_int(s):
"""(str) -> int
All the digits in a given string are concatenated and converted into a single number.
"""
try:
temp = re.findall('\d', str(s))
temp = ''.join(temp)
return int(temp)
except:
return s | cosqa |
def tenant_quota_usages(request, tenant_id=None, targets=None):
"""Get our quotas and construct our usage object.
:param tenant_id: Target tenant ID. If no tenant_id is provided,
a the request.user.project_id is assumed to be used.
:param targets: A tuple of quota names to be retrieved.
If ... | usages = QuotaUsage()
futurist_utils.call_functions_parallel(
(_get_tenant_compute_usages,
[request, usages, disabled_quotas, tenant_id]),
(_get_tenant_network_usages,
[request, usages, disabled_quotas, tenant_id]),
(_get_tenant_volume_usages,
[request, usages,... | csn_ccr |
Checks whether the scl string is the equals relation. | private static boolean equals_(String scl) {
// Valid for all
if (scl.charAt(0) == 'T' && scl.charAt(1) == '*'
&& scl.charAt(2) == 'F' && scl.charAt(3) == '*'
&& scl.charAt(4) == '*' && scl.charAt(5) == 'F'
&& scl.charAt(6) == 'F' && scl.charAt(7) == 'F'
&& scl.charAt(8) == '*')
return true;
r... | csn |
Add a new product class | protected function addProductClass()
{
if (!$this->isError()) {
$id = $this->product_class->add($this->getSubmitted());
if (empty($id)) {
$this->errorAndExit($this->text('Unexpected result'));
}
$this->line($id);
}
} | csn |
python select files by pattern | def match_files(files, pattern: Pattern):
"""Yields file name if matches a regular expression pattern."""
for name in files:
if re.match(pattern, name):
yield name | cosqa |
def run(*args)
optparse(*args)
options = {
:env => :production,
:host => @host,
:port => @port
| }
options.merge!(:server => @handler) if @handler
App.run!(options)
end | csn_ccr |
public function getRepository()
{
if (!$this->_repository instanceof AnDomainRepositoryAbstract) {
if (!$this->_repository instanceof AnServiceIdentifier) {
$this->setRepository($this->_repository);
}
| $this->_repository = AnDomain::getRepository($this->_repository);
}
return $this->_repository;
} | csn_ccr |
func decodeRowKey(v string) (*rowKey, error) {
keyParts := strings.SplitN(v, "~", 3)
if len(keyParts) != 3 {
return nil, errMalformedRowKey
}
hashEnc, idxEnc, countEnc := keyParts[0], keyParts[1], keyParts[2]
if base64.URLEncoding.DecodedLen(len(hashEnc)) < sha256.Size {
return nil, errMalformedRowKey
}
//... |
// Decode index.
rk.index, err = readHexInt64(idxEnc)
if err != nil {
return nil, err
}
// If a count is available, decode that as well.
rk.count, err = readHexInt64(countEnc)
if err != nil {
return nil, err
}
return &rk, nil
} | csn_ccr |
def proxy_callback(request):
"""Handles CAS 2.0+ XML-based proxy callback call.
Stores the proxy granting ticket in the database for
future use.
NB: Use created and set it in python in case database
has issues with setting up the default timestamp value
"""
pgtIou = request.GET.get('pgtIou... | request.session['pgt-TICKET'] = pgtIou
return HttpResponse('PGT ticket is: {ticket}'.format(ticket=pgtIou), content_type="text/plain")
except Exception as e:
logger.warning('PGT storage failed. {message}'.format(
message=e
))
return HttpResponse('PGT storage failed... | csn_ccr |
Checks if is the main id, or it is a secondary id.
@param id
Current id.
@param resource
Current resource.
@param lastElement
Last element of the URL.
@return true if is the main id, false otherwise. | private Boolean isMainId(String id, String resource, String lastElement) {
Boolean isMainId = false;
if (id == null) {
if (!utils.singularize(utils.cleanURL(lastElement)).equals(resource) && resource == null) {
isMainId = true;
}
}
return isMainId;
} | csn |
replace comments with a space python | def _comment(string):
"""return string as a comment"""
lines = [line.strip() for line in string.splitlines()]
return "# " + ("%s# " % linesep).join(lines) | cosqa |
public final static void replaceMonomer(HELM2Notation helm2notation, String polymerType, String existingMonomerID,
String newMonomerID) throws NotationException, MonomerException,
ChemistryException, CTKException, IOException, JDOMException {
validateMonomerReplacement(polymerType, existingMonomerID, newMo... | j = 0; j < helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements()
.size(); j++) {
MonomerNotation monomerNotation = replaceMonomerNotation(
helm2notation.getListOfPolymers().get(i).getPolymerElements().getListOfElements().get(j),
existingMonomerID, newMonomerID);... | csn_ccr |
def _read_para_via_rvs(self, code, cbit, clen, *, desc, length, version):
"""Read HIP VIA_RVS parameter.
Structure of HIP VIA_RVS parameter [RFC 6028]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1... | .
. . .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Address ... | csn_ccr |
func (s *PutConfigRuleInput) SetConfigRule(v | *ConfigRule) *PutConfigRuleInput {
s.ConfigRule = v
return s
} | csn_ccr |
private void waitUntilFlowPreparationFinish() throws InterruptedException {
final Duration SLEEP_INTERVAL = Duration.ofSeconds(5);
while (this.preparingFlowCount.intValue() != | 0) {
logger.info(this.preparingFlowCount + " flow(s) is/are still being setup before complete "
+ "deactivation.");
Thread.sleep(SLEEP_INTERVAL.toMillis());
}
} | csn_ccr |
// CopyMatMN copies src into dst. This Reshapes dst
// to the same size as src.
//
// If dst or src is nil, this is a no-op | func CopyMatMN(dst, src *MatMxN) {
if dst == nil || src == nil {
return
}
dst.Reshape(src.m, src.n)
copy(dst.dat, src.dat)
} | csn |
Creates a new RDS from the snapshot | def create_tmp_rds_from_snapshot
unless @new_instance
update_status "Waiting for snapshot #{@snapshot_id}"
@snapshot.wait_for { ready? }
update_status "Booting new RDS #{@new_rds_id} from snapshot #{@snapshot.id}"
@rds.restore_db_instance_from_db_snapshot(@snapshot.id,
@n... | csn |
Check if the data file is already extracted. | def is_extracted(self, file_path):
"""
Check if the data file is already extracted.
"""
if os.path.isdir(file_path):
self.chatbot.logger.info('File is already extracted')
return True
return False | csn |
function Adapter() {
expect(this).to.be.an(
'object',
'The Adapter\'s constructor can be only invoked from specialized' +
'classes\' constructors'
);
expect(this.constructor).to.be.a(
'function',
'The Adapter\'s constructor can be only invoked from specialized' +
'classes\' constructors'
... | cannot be directly initialized'
);
expect(this).to.be.instanceof(
Adapter,
'The Adapter\'s constructor can be only invoked from specialized' +
'classes\' constructors'
);
} | csn_ccr |
public String getObjectImage(int groupID, int objectID) {
if (groupID >= 0 && groupID < objectGroups.size()) {
ObjectGroup grp = (ObjectGroup) objectGroups.get(groupID);
if (objectID >= 0 && objectID < grp.objects.size()) {
GroupObject object | = (GroupObject) grp.objects.get(objectID);
if (object == null) {
return null;
}
return object.image;
}
}
return null;
} | csn_ccr |
function formatUrl(p, callback) {
// Are we signing the request?
var sign;
// OAuth1
// Remove the token from the query before signing
if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) {
// OAUTH SIGNING PROXY
sign = p.query.access_token;
// R... | circumventing services without Access-Control Headers
if (p.proxy) {
// Use the proxy as a path
path = _this.qs(p.oauth_proxy, {
path: path,
access_token: sign || '',
// This will prompt the request to be signed as though it is OAuth1
then: p.proxy_response_type || (p.method.toLowerCase... | csn_ccr |
// Read reads into the passed byte slice and returns the bytes read. | func (body *Body) Read(b []byte) (n int, err error) {
if !body.IsOpen() {
return 0, fmt.Errorf("ERROR: Body has been closed")
}
if len(body.b) == 0 {
return 0, io.EOF
}
n = copy(b, body.b)
body.b = body.b[n:]
return n, nil
} | csn |
Drops a table. Use caution! | def drop_table(self, tablename: str) -> int:
"""Drops a table. Use caution!"""
sql = "DROP TABLE IF EXISTS {}".format(tablename)
log.info("Dropping table " + tablename + " (ignore any warning here)")
return self.db_exec_literal(sql) | csn |
public List< T> getAllByHql(String secondHalfOfHql, Object paramValue1, Type paramType1, Object paramValue2, Type | paramType2) {
return getAllByHql(secondHalfOfHql, new Object[] {paramValue1, paramValue2}, new Type[]{paramType2, paramType2}, null, null);
} | csn_ccr |
// TokenAccessor returns the standardized token accessor for the given secret.
// If the secret is nil or does not contain an accessor, this returns the empty
// string. | func (s *Secret) TokenAccessor() (string, error) {
if s == nil {
return "", nil
}
if s.Auth != nil && len(s.Auth.Accessor) > 0 {
return s.Auth.Accessor, nil
}
if s.Data == nil || s.Data["accessor"] == nil {
return "", nil
}
accessor, ok := s.Data["accessor"].(string)
if !ok {
return "", fmt.Errorf("t... | csn |
Converts and return the underlying S3 object as a json string.
@throws SdkClientException if failed in JSON conversion. | String toJsonString() {
try {
return from(s3obj.getObjectContent());
} catch (Exception e) {
throw new SdkClientException("Error parsing JSON: " + e.getMessage());
}
} | csn |
def update_handler_result(self, ddoc_id, handler_name, doc_id=None, data=None, **params):
"""
Creates or updates a document from the specified database based on the
update handler function provided. Update handlers are used, for
example, to provide server-side modification timestamps, a... | data={'month': 'July'})
For more details, see the `update handlers documentation
<https://console.bluemix.net/docs/services/Cloudant/api/design_documents.html#update-handlers>`_.
:param str ddoc_id: Design document id used to get result.
:param str handler_name: Name used in p... | csn_ccr |
def _summary(tag, hparams_plugin_data):
"""Returns a summary holding the given HParamsPluginData message.
Helper function.
Args:
tag: string. The tag to use.
hparams_plugin_data: The HParamsPluginData message to use.
"""
summary | = tf.compat.v1.Summary()
summary.value.add(
tag=tag,
metadata=metadata.create_summary_metadata(hparams_plugin_data))
return summary | csn_ccr |
function(element, child){
if(_.isString(child))
element.innerHTML | += child;
else if (_.isElement(child))
element.appendChild(child);
} | csn_ccr |
Return the cache file path.
@param string $pKey
@return string | private function _getFilePath($pKey)
{
$keyArr = explode(static::SECTION_DELIMITER, $pKey, 2);
$fileName = $keyArr[0];
if (! isset($this->_paths[$fileName])) {
$encodedFileName = md5($fileName);
$this->_paths[$fileName] = $this->_dir
... | csn |
Generate a MDP example based on a simple forest management scenario.
This function is used to generate a transition probability
(``A`` × ``S`` × ``S``) array ``P`` and a reward (``S`` × ``A``) matrix
``R`` that model the following problem. A forest is managed by two actions:
'Wait' and 'Cut'. An action... | def forest(S=3, r1=4, r2=2, p=0.1, is_sparse=False):
"""Generate a MDP example based on a simple forest management scenario.
This function is used to generate a transition probability
(``A`` × ``S`` × ``S``) array ``P`` and a reward (``S`` × ``A``) matrix
``R`` that model the following problem. A fores... | csn |
protected void configureYahooClient(final Collection<BaseClient> properties) {
val yahoo = pac4jProperties.getYahoo();
if (StringUtils.isNotBlank(yahoo.getId()) && StringUtils.isNotBlank(yahoo.getSecret())) {
val client = new YahooClient(yahoo.getId(), yahoo.getSecret());
configu... | LOGGER.debug("Created client [{}] with identifier [{}]", client.getName(), client.getKey());
properties.add(client);
}
} | csn_ccr |
public static boolean matchConsumes(InternalRoute route, InternalRequest<?> request) {
if (route.getConsumes().contains(WILDCARD)) {
return true;
| }
return route.getConsumes().contains(request.getContentType());
} | csn_ccr |
Opens a WritableGridFileChannel for writing to the file denoted by pathname.
@param pathname the file to write to
@param append if true, the bytes written to the channel will be appended to the end of the file
@param chunkSize the size of the file's chunks. This parameter is honored only when the file at pathname does
... | public WritableGridFileChannel getWritableChannel(String pathname, boolean append, int chunkSize) throws IOException {
GridFile file = (GridFile) getFile(pathname, chunkSize);
checkIsNotDirectory(file);
createIfNeeded(file);
return new WritableGridFileChannel(file, data, append);
} | csn |
Finds an address by id.
@param string|int $address_id
The address id.
@return null|array
The found address. | public static function findAddress($address_id) {
$found_address = NULL;
$user = \Drupal::service('acm.commerce_user_manager')->getAccount();
$addresses = $user->getAddresses();
$extra_keys = [
'customer_id',
'customer_address_id',
'region_id',
'default_billing',
'default_... | csn |
func (c *Clientset) Image() imageinternalversion.ImageInterface | {
return &fakeimageinternalversion.FakeImage{Fake: &c.Fake}
} | csn_ccr |
func (e *TokensController) Run(workers int, stopCh <-chan struct{}) {
// Shut down queues
defer utilruntime.HandleCrash()
defer e.syncServiceAccountQueue.ShutDown()
defer e.syncSecretQueue.ShutDown()
if !controller.WaitForCacheSync("tokens", stopCh, e.serviceAccountSynced, e.secretSynced) {
return
}
klog.V(5... | 0; i < workers; i++ {
go wait.Until(e.syncServiceAccount, 0, stopCh)
go wait.Until(e.syncSecret, 0, stopCh)
}
<-stopCh
klog.V(1).Infof("Shutting down")
} | csn_ccr |
// FindRestartingPods inspects all Pods to see if they've restarted more than the threshold. logsCommandName is the name of
// the command that should be invoked to see pod logs. securityPolicyCommandPattern is a format string accepting two replacement
// variables for fmt.Sprintf - 1, the namespace of the current pod,... | func FindRestartingPods(g osgraph.Graph, f osgraph.Namer, logsCommandName, securityPolicyCommandPattern string) []osgraph.Marker {
markers := []osgraph.Marker{}
for _, uncastPodNode := range g.NodesByKind(kubegraph.PodNodeKind) {
podNode := uncastPodNode.(*kubegraph.PodNode)
pod, ok := podNode.Object().(*corev1.... | csn |
def _set_object_view(self, session):
"""Sets the underlying object views to match current view"""
for obj_name in self._object_views:
if self._object_views[obj_name] == PLENARY:
try:
getattr(session, 'use_plenary_' + obj_name + '_view')()
e... | else:
try:
getattr(session, 'use_comparative_' + obj_name + '_view')()
except AttributeError:
pass | csn_ccr |
add service to services.yml
@param string $id id of new service
@param string $parent parent for service
@param array $calls methodCalls to add
@param string $tag tag name or empty if no tag needed
@param array $arguments service arguments
@param string $factoryService fa... | protected function addService(
$id,
$parent = null,
array $calls = [],
$tag = null,
array $arguments = [],
$factoryService = null,
$factoryMethod = null,
$className = null
) {
$service = [];
$service['public'] = true;
// classn... | csn |
decreasing the contrast of an image using python | def lighting(im, b, c):
""" Adjust image balance and contrast """
if b==0 and c==1: return im
mu = np.average(im)
return np.clip((im-mu)*c+mu+b,0.,1.).astype(np.float32) | cosqa |
public function getTrackingData()
{
return [
'product' => $this->getCurrentProduct(),
'category' => $this->getCategory(),
'store' => $this->getStoreData(),
'search' | => $this->getSearchData(),
'exchangeRate' => $this->getExchangeRate(),
'slug' => $this->getStoreSlug(),
];
} | csn_ccr |
Check that hdrgo set is a set of GO IDs. | def _chk_hdrgoids(hdrgos):
"""Check that hdrgo set is a set of GO IDs."""
goid = next(iter(hdrgos))
if isinstance(goid, str) and goid[:3] == "GO:":
return
assert False, "HDRGOS DO NOT CONTAIN GO IDs: {E}".format(E=goid) | csn |
function( context, target ) {
var method = target ? 'qsa' : 'tag'
var target = target || 'em'
var $target = $[ method ]( target, context )
$target
.forEach(function( elem ) {
var $elem = Han( elem )
if ( Locale.support.textemphasis ) {
$elem
.avoid( 'rt, h-char' )
... | .groupify({ western: true })
.charify({
hanzi: true,
biaodian: true,
punct: true,
latin: true,
ellinika: true,
kirillica: true
})
}
})
} | csn_ccr |
how to get number of objects in document in python | def get_size(objects):
"""Compute the total size of all elements in objects."""
res = 0
for o in objects:
try:
res += _getsizeof(o)
except AttributeError:
print("IGNORING: type=%s; o=%s" % (str(type(o)), str(o)))
return res | cosqa |
public static int getNextAvailablePort(int fromPort, int toPort) {
if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort) {
throw new IllegalArgumentException(format("Invalid port | range: %d ~ %d", fromPort, toPort));
}
int nextPort = fromPort;
//noinspection StatementWithEmptyBody
while (!isPortAvailable(nextPort++)) { /* Empty */ }
return nextPort;
} | csn_ccr |
public static function delete($id, $additionalAttributes, $table, $idAttribute = 'id', $limit = 1)
{
//force disable limit because they wont work with postgreqsql
$limit = null;
$queryValues = [$id];
$additional = [];
foreach ($additionalAttributes as $key => $value) {
... | $query = sprintf(
'DELETE FROM %s
WHERE "%s" = ?
%s
%s',
$tableName,
$idAttribute,
implode("\n", $additional),
(
$limit === null
? ''
: 'LIMIT ' . $limit
... | csn_ccr |
Starts a new thread to process the request, adding the client address
in its name. | def process_request(self, request, client_address):
"""
Starts a new thread to process the request, adding the client address
in its name.
"""
thread = threading.Thread(
name="RemoteShell-{0}-Client-{1}".format(
self.server_address[1], client_address[:... | csn |
public function createFilesDocuments(Drop $drop, User $user, array $files)
{
$documents = [];
$documentEntities = [];
$currentDate = new \DateTime();
$dropzone = $drop->getDropzone();
$this->om->startFlushSuite();
foreach ($files as $file) {
$document = n... | $documents[] = $this->serializeDocument($document);
}
$this->om->endFlushSuite();
//tracking for each document, after flush
foreach ($documentEntities as $entity) {
$this->eventDispatcher->dispatch('log', new LogDocumentCreateEvent($drop->getDropzone(), $drop, $ent... | csn_ccr |
r"""Check multi line docstring summary is separated with empty line.
OpenStack HACKING guide recommendation for docstring:
Docstring should start with a one-line summary, less than 80 characters.
Okay: def foo():\n a = '''\nnot\na docstring\n'''
Okay: '''foobar\n\nfoo\nbar\n'''
H405: def foo():... | def hacking_docstring_summary(physical_line, previous_logical, tokens):
r"""Check multi line docstring summary is separated with empty line.
OpenStack HACKING guide recommendation for docstring:
Docstring should start with a one-line summary, less than 80 characters.
Okay: def foo():\n a = '''\nnot... | csn |
Guess the MIME type of a given file, first by checking the extension then by falling back to magic.
@param string $file_path Relative or absolute path to an existing file.
@param string $reference_name Use this name for detection based on the extension.
@param string $default Default MIME type.
@return string|null Th... | public static function guessType($file_path, $reference_name = null, $default = 'application/octet-stream') {
if (!$reference_name) {
$reference_name = basename($file_path);
}
$extension = pathinfo($reference_name, PATHINFO_EXTENSION);
if ($extension and $mime_type = static::getTypeForExtension($extension))... | csn |
function getPost($postId, array $fields = array())
{
if (empty($fields)) {
$params = array(1, $this->username, $this->password, $postId);
} else {
| $params = array(1, $this->username, $this->password, $postId, $fields);
}
return $this->sendRequest('wp.getPost', $params);
} | csn_ccr |
protected FtpMessage createDir(CommandType ftpCommand) {
try {
sftp.mkdir(ftpCommand.getArguments());
return FtpMessage.result(FTPReply.PATHNAME_CREATED, "Pathname created", true);
| } catch (SftpException e) {
throw new CitrusRuntimeException("Failed to execute ftp command", e);
}
} | csn_ccr |
public function parse($url) {
// iterate all rules
$hit = false;
foreach ($this->_routes as $rule => $new_class) {
$regex = trim($rule, '/');
// rebuild route to a preg pattern
if (preg_match($regex, $url, $parameters)) {
$class = preg_replace($regex, $new_class, $url);
$class = str_replace('/... | $class = call_user_func($this->_fallback, $url);
}
$class_shards = explode('\\', $class);
$class_shards[count($class_shards)-1] = ucfirst(strtolower($class_shards[count($class_shards)-1]));
$class = implode('\\', $class_shards);
return [
'controller' => $class,
'parameters' => isset($parameters) ?... | csn_ccr |
This function returns the SHA-1 hash
of the file passed into it | def hash_file(filename):
""""This function returns the SHA-1 hash
of the file passed into it"""
# make a hash object
h = hashlib.sha1()
# open file for reading in binary mode
with open(filename,'rb') as file:
# loop till the end of the file
chunk = 0
while chunk != b'':
... | csn |
// NewLeastSquaresFunction creates a new least squares function based
// on a set of points. | func NewLeastSquaresFunction(points Points) *LeastSquaresFunction {
lsf := new(LeastSquaresFunction)
if points != nil {
lsf.AppendPoints(points)
}
return lsf
} | csn |
Returns the sum of all instances durations as expressed in seconds. | public function getTotalTimestampInterval(): float
{
$retval = 0;
foreach ($this->intervals as $interval) {
$retval += $interval->getTimestampInterval();
}
return $retval;
} | csn |
def _insert_line(self, count=1):
"""
Inserts lines at line with cursor. Lines displayed below cursor move
down. Lines moved past the bottom margin are lost.
"""
trimmed = self.display[:self.y+1] + \
| [u" " * self.size[1]] * count + \
self.display[self.y+1:self.y+count+1]
self.display = trimmed[:self.size[0]] | csn_ccr |
Convert from a base64 string to a bitArray | function(str, _url) {
str = str.replace(/\s|=/g,'');
var out = [], i, bits=0, c = sjcl.codec.base64._chars, ta=0, x;
if (_url) {
c = c.substr(0,62) + '-_';
}
for (i=0; i<str.length; i++) {
x = c.indexOf(str.charAt(i));
if (x < 0) {
throw new sjcl.exception.invalid("this isn... | csn |
//getRing loads a ring from disk | func (s *Server) getRing(path string) (ring.Ring, error) {
r, _, err := ring.RingOrBuilder(path)
return r, err
} | csn |
A bootstrap for the handleRequest method
@todo setDataModel and setRequest are redundantly called in parent::handleRequest() - sort this out
@param HTTPRequest $request | protected function beforeHandleRequest(HTTPRequest $request)
{
//Set up the internal dependencies (request, response)
$this->setRequest($request);
//Push the current controller to protect against weird session issues
$this->pushCurrent();
$this->setResponse(new HTTPResponse()... | csn |
public static function equals(string $string1, string $string2, bool $caseSensitive = true)
{
if ($caseSensitive) {
| return $string1 === $string2;
}
return strtolower($string1) === strtolower($string2);
} | csn_ccr |
Rollback the transacion. Force a backout record to the log.
@param reUse Indicates whether the transaction is terminated or can be reused for another logical unit of work.
@param transaction the external Transaction.
@throws ObjectManagerException | protected void backout(boolean reUse,
Transaction transaction)
throws ObjectManagerException {
final String methodName = "backout";
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this, cclass, methodName, new Object[] {... | csn |
public function addSubController($pTriggerUrl, $pControllerClass = '')
{
$this->normalizeUrl($pTriggerUrl);
$base = $this->triggerUrl;
if ($base == '/') $base = '';
| $controller = new Server($base . $pTriggerUrl, $pControllerClass, $this);
$this->controllers[] = $controller;
return $controller;
} | csn_ccr |
Check if one or more subjects are allowed to perform action level on object.
If a subject holds permissions for one action level on object, all lower action
levels are also allowed. Any included subject that is unknown to this MN is treated
as a subject without permissions.
Returns:
bool
... | def is_allowed(request, level, pid):
"""Check if one or more subjects are allowed to perform action level on object.
If a subject holds permissions for one action level on object, all lower action
levels are also allowed. Any included subject that is unknown to this MN is treated
as a subject without p... | csn |
// Fixes the first args many segments as the prefix of a new KeyFormat by using the args to generate a key that becomes
// that prefix. Any remaining unassigned segments become the layout of the new KeyFormat. | func (kf *KeyFormat) Fix(args ...interface{}) (*KeyFormat, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return NewKeyFormat(string(key), kf.layout[len(args):]...)
} | csn |
Gets a date time instance by a given data and timezone.
@param \DateTime|\DateTimeInterface|string|int $data Value representing date
@param string|null $timezone Timezone of the date
@return \DateTime | public function getDatetime($data, $timezone = null)
{
if ($data instanceof \DateTime) {
return $data;
}
if ($data instanceof \DateTimeImmutable) {
return \DateTime::createFromFormat(\DateTime::ATOM, $data->format(\DateTime::ATOM));
}
// the format m... | csn |
def tai(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
jd=None):
"""Build a `Time` from a TAI calendar date.
Supply the International Atomic Time (TAI) as a proleptic
Gregorian calendar date:
>>> t = ts.tai(2014, 1, 18, 1, 35, 37.5)
>>> t.tai
... | tai = jd
else:
tai = julian_date(
_to_array(year), _to_array(month), _to_array(day),
_to_array(hour), _to_array(minute), _to_array(second),
)
return self.tai_jd(tai) | csn_ccr |
public function Upgrade171to172()
{
$this->_batch->addTask('Db_CreateNewTables');
$this->_batch->addTask('Db_AddPatches', 58);
$this->_batch->addTask('Echo', $this->_('Make sure to read the changelog as it contains important instructions'));
| $this->_batch->addTask('Echo', $this->_('Check the Code compatibility report for any issues with project specific code!'));
return true;
} | csn_ccr |
One step of the first-best-admissible tabu search algorithm.
All possible moves are inspected in random order, and either the first admissible improvement,
if any, or, else, the best admissible move, is applied to the current solution.
@throws IncompatibleTabuMemoryException if the applied tabu memory is not compatibl... | @Override
protected void searchStep() {
// get list of possible moves
List<? extends Move<? super SolutionType>> moves = getNeighbourhood().getAllMoves(getCurrentSolution());
// shuffle moves
Collections.shuffle(moves);
// find best admissible move, or first admissible improv... | csn |
protected function afterDispatch(string $eventName, $event)
{
$this->postDispatch($eventName, | $event instanceof Event ? $event : new LegacyEventProxy($event));
} | csn_ccr |
func New(addr string, reqHeaders, respHeaders []string) (*Trace, error) {
if _, err := newWriter(addr); err | != nil {
return nil, err
}
return &Trace{
ReqHeaders: reqHeaders,
RespHeaders: respHeaders,
Addr: addr,
}, nil
} | csn_ccr |
func (s *LifecycleRule) SetNoncurrentVersionTransitions(v []*NoncurrentVersionTransition) | *LifecycleRule {
s.NoncurrentVersionTransitions = v
return s
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.