query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
func (m *GormAreaRepository) Root(ctx context.Context, spaceID uuid.UUID) (*Area, error) {
defer goa.MeasureSince([]string{"goa", "db", "Area", "root"}, time.Now())
var rootArea []Area
rootArea, err := m.Query(FilterBySpaceID(spaceID), func(db *gorm.DB) *gorm.DB {
return db.Where("space_id = ? AND nlevel(path)=1"... | len(rootArea) != 1 {
return nil, errors.NewInternalError(ctx, errs.Errorf("single Root area not found for space %s", spaceID))
}
if err != nil {
return nil, err
}
return &rootArea[0], nil
} | csn_ccr |
public static JsonInputValidator getValidator(Class<?> clazz) {
if (clazz.equals(Scope.class)) {
return ScopeValidator.getInstance();
}
if | (clazz.equals(ApplicationInfo.class)) {
return ApplicationInfoValidator.getInstance();
}
return null;
} | csn_ccr |
Remove the specified object of the array.
@param object The object to add at the end of the array. | int remove(T object) {
int positionOfRemove = mObjects.indexOf(object);
if (positionOfRemove >= 0) {
T objectRemoved = removeAt(positionOfRemove);
if (objectRemoved != null) {
return positionOfRemove;
}
}
return -1;
} | csn |
public long readUnconsumedDecData() {
long totalBytesRead = 0L;
// Determine if data is left over from a former read request.
if (unconsumedDecData != null) {
// Left over data exists. Is there enough to satisfy the request?
if (getBuffer() == null) {
// ... | decryptedNetBuffers = unconsumedDecData;
// Set left over buffers to null to note that they are no longer in use.
unconsumedDecData = null;
if ((decryptedNetLimitInfo == null)
|| (decryptedNetLimitInfo.length != decryptedNetBuffers.length)) {
... | csn_ccr |
public function filterByFuzzyUserName($username)
{
$this->query->andWhere(
$this->query->expr()->like('u.uName', ':uName')
| );
$this->query->setParameter('uName', $username . '%');
} | csn_ccr |
def retry_count(self):
"""
Amount of retried test cases in this list.
:return: integer
"""
| retries = len([i for i, result in enumerate(self.data) if result.retries_left > 0])
return retries | csn_ccr |
public static List<HostAddress> parse(String spec, HaMode haMode) {
if (spec == null) {
throw new IllegalArgumentException("Invalid connection URL, host address must not be empty ");
}
if ("".equals(spec)) {
return new ArrayList<>(0);
}
String[] tokens = spec.trim().split(",");
int s... | + "Using end-point permit auto-discovery of new replicas");
}
}
for (String token : tokens) {
if (token.startsWith("address=")) {
arr.add(parseParameterHostAddress(token));
} else {
arr.add(parseSimpleHostAddress(token));
}
}
if (haMode == HaMode.REPLICAT... | csn_ccr |
private boolean add(DBIDRef cur, DBIDRef cand, double distance) {
KNNHeap neighbors = store.get(cur);
if(neighbors.contains(cand)) {
return false;
}
| double newKDistance = neighbors.insert(distance, cand);
return (distance <= newKDistance);
} | csn_ccr |
Returns a collection of uploaded files from a multi-part port request.
@param encoding specifies the character encoding to be used when reading the headers of individual part.
When not specified, or null, the request encoding is used. If that is also not specified, or null,
the platform default encoding is used.
@para... | protected Iterator<FormItem> uploadedFiles(String encoding, long maxFileSize) {
List<FormItem> fileItems = new ArrayList<>();
for(FormItem item : multipartFormItems(encoding, maxFileSize)) {
if (item.isFile()) {
fileItems.add(item);
}
}
return file... | csn |
public static String getConstantName(Object value, Class c) {
for (Field f : c.getDeclaredFields()) {
int mod = f.getModifiers();
if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && Modifier.isFinal(mod)) {
try {
if (f.get(null).equals(value)) {
... | }
} catch (IllegalAccessException e) {
return String.valueOf(value);
}
}
}
return String.valueOf(value);
} | csn_ccr |
private function resetDynamicSettings()
{
// Ensure to reset services that need to be.
foreach ($this->resettableServiceIds as $serviceId) {
if (!$this->container->initialized($serviceId)) {
continue;
}
$this->container->set($serviceId, null);
... | $service = $this->container->get($serviceId);
foreach ($methodCalls as $callConfig) {
list($method, $expression) = $callConfig;
$argument = $this->expressionLanguage->evaluate($expression, ['container' => $this->container]);
call_user_func_array([$service, $m... | csn_ccr |
private List<InetAddress> findAddresses() throws HarvestException {
// Stores found addresses
List<InetAddress> found = new ArrayList<InetAddress>(3);
// Retrieve list of available network interfaces
Enumeration<NetworkInterface> interfaces = getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
... | Enumeration<InetAddress> addresses = iface.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
// loopback addresses are discarded
if (address.isLoopbackAddress()) {
continue;
}
// Ignore IPv6 addresses for now
if (address instan... | csn_ccr |
private function addLog($string)
{
$currentTime = round(microtime(true) * 1000);
$this->log .= date('d-m-Y H:i:s - ') . str_pad($string, 50, " ", |
STR_PAD_RIGHT) . "\t" . ($currentTime - $this->lastLog) . 'ms since last log. ' . "\t" . ($currentTime - $this->loggingStart) . 'ms since start.' . PHP_EOL;
$this->lastLog = round(microtime(true) * 1000);
} | csn_ccr |
Create decoration, rely to given client
@param string $method
@param string $url
@param array $headers
@return AbstractRequest | public function createRequest($method, $url = '', array $headers = [])
{
return $this->client->createRequest($method, $url, $headers);
} | csn |
Prepare a capstone disassembler instance for a given target and syntax.
Args:
syntax(AsmSyntax): The assembler syntax (Intel or AT&T).
target(~pwnypack.target.Target): The target to create a disassembler
instance for. The global target is used if this argument is
``None``.
... | def prepare_capstone(syntax=AsmSyntax.att, target=None):
"""
Prepare a capstone disassembler instance for a given target and syntax.
Args:
syntax(AsmSyntax): The assembler syntax (Intel or AT&T).
target(~pwnypack.target.Target): The target to create a disassembler
instance for. ... | csn |
public static SeleniumAssert assertThat(CommonG commong, List<WebElement> actual) {
| return new SeleniumAssert(commong, actual);
} | csn_ccr |
public function getFileContents()
{
$result = null;
$fsl = $this->getFile()->getFileStorageLocationObject();
if ($fsl !== null) {
$app = Application::getFacadeApplication();
$cf = $app->make('helper/concrete/file');
try {
$result = $fsl->ge... | if ($result === false) {
$result = null;
}
} catch (FileNotFoundException $x) {
}
}
return $result;
} | csn_ccr |
Calls the service method defined with the arguments provided | def call(self, method, *args):
""" Calls the service method defined with the arguments provided """
try:
response = getattr(self.client.service, method)(*args)
except (URLError, SSLError) as e:
log.exception('Failed to connect to responsys service')
raise Conn... | csn |
Read requirements.txt. | def get_requires():
"""Read requirements.txt."""
requirements = open("requirements.txt", "r").read()
return list(filter(lambda x: x != "", requirements.split())) | csn |
public static WidgetLib init(GVRContext gvrContext, String customPropertiesAsset)
throws InterruptedException, JSONException, NoSuchMethodException {
| if (mInstance == null) {
// Constructor sets mInstance to ensure the initialization order
new WidgetLib(gvrContext, customPropertiesAsset);
}
return mInstance.get();
} | csn_ccr |
Get the table lines size
@return int | public function getTableLineSize()
{
if ($this->column_size===0 && $this->line_size===0 && $this->cell_size===0) {
$this->_parseTableSizes();
}
return $this->line_size;
} | csn |
A rectangle can be split up into a grid of 1x1 squares, the amount of which being equal to the product of the two dimensions of the rectangle. Depending on the size of the rectangle, that grid of 1x1 squares can also be split up into larger squares, for example a 3x2 rectangle has a total of 8 squares, as there are 6 d... | def findSquares(x,y):
return sum( (x-i) * (y-i) for i in range(y) ) | apps |
// Get returns the stored entity with the given id, or nil if none was found.
// The contents of the returned entity MUST not be changed. | func (a *multiwatcherStore) Get(id multiwatcher.EntityId) multiwatcher.EntityInfo {
e, ok := a.entities[id]
if !ok {
return nil
}
return e.Value.(*entityEntry).info
} | csn |
Return a dictionary representation for a matrix row
:param row_idx: which row
:return: a dict of feature keys/values, not including ones which are the default value | def get_row_dict(self, row_idx):
""" Return a dictionary representation for a matrix row
:param row_idx: which row
:return: a dict of feature keys/values, not including ones which are the default value
"""
try:
row = self._rows[row_idx]
except TypeError:
... | csn |
public static String getCharset(HttpEntity entity) {
final String guess = EntityUtils.getContentCharSet(entity);
| return guess == null ? HTTP.DEFAULT_CONTENT_CHARSET : guess;
} | csn_ccr |
public function get($code)
{
$result = $this->getConnection()->table('oauth_auth_codes')
->where('oauth_auth_codes.id', $code)
->where('oauth_auth_codes.expire_time', '>=', time())
->first();
if (is_null($result)) {
| return;
}
return (new AuthCodeEntity($this->getServer()))
->setId($result->id)
->setRedirectUri($result->redirect_uri)
->setExpireTime((int) $result->expire_time);
} | csn_ccr |
On MySQL, as PROJECTS.KEE is not unique, if the same project is provisioned multiple times, then it will be duplicated in the database.
So, after creating a project, we commit, and we search in the db if their are some duplications and we remove them.
SONAR-6332 | private void removeDuplicatedProjects(DbSession session, String projectKey) {
List<ComponentDto> duplicated = dbClient.componentDao().selectComponentsHavingSameKeyOrderedById(session, projectKey);
for (int i = 1; i < duplicated.size(); i++) {
dbClient.componentDao().delete(session, duplicated.get(i).getId... | csn |
Clean up content capture and display main template
@return null | public static function shutdown()
{
global $PPHP;
$req = grab('request');
if (!$req['binary']) {
$body = ob_get_contents();
ob_end_clean();
try {
array_merge_assoc(
self::$_stash,
array(
... | csn |
// SetCookieExpire allows you set cookie expire time | func (app *App) SetCookieExpire(d time.Duration) {
if d != 0 {
app.cookieExpire = d
}
} | csn |
// SetHttpRoute sets the HttpRoute field's value. | func (s *RouteSpec) SetHttpRoute(v *HttpRoute) *RouteSpec {
s.HttpRoute = v
return s
} | csn |
public function mapLinkTypeCodeToLinkTypeId($linkTypeCode)
{
// query weather or not the link type code has been mapped
if (isset($this->linkTypes[$linkTypeCode])) {
return $this->linkTypes[$linkTypeCode][MemberNames::LINK_TYPE_ID];
}
// throw an exception if the link t... | throw new MapLinkTypeCodeToIdException(
$this->appendExceptionSuffix(
sprintf('Found not mapped link type code %s', $linkTypeCode)
)
);
} | csn_ccr |
func (s *Signatory) verifySignature(block *clearsign.Block) (*openpgp.Entity, error) {
return openpgp.CheckDetachedSignature(
s.KeyRing,
| bytes.NewBuffer(block.Bytes),
block.ArmoredSignature.Body,
)
} | csn_ccr |
def delete
Sidekiq.redis do |conn|
conn.multi do
conn.del(status_key)
conn.zrem(self.class.kill_key, self.jid)
| conn.zrem(self.class.statuses_key, self.jid)
end
end
end | csn_ccr |
def _GetDirectory(self):
"""Retrieves the directory.
Returns:
LVMDirectory: a directory or None if not available.
"""
| if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY:
return None
return LVMDirectory(self._file_system, self.path_spec) | csn_ccr |
public function addAccountLinkButton($url)
{
$this->add(new | Button(Button::TYPE_ACCOUNT_LINK, null, $url));
return $this;
} | csn_ccr |
func (em *eventMetadata) writeCountedArray(name string, count uint16, inType inType, outType outType, tags uint32) | {
em.writeFieldInner(name, inType|inTypeCountedArray, outType, tags, count)
} | csn_ccr |
def verbose(self_,msg,*args,**kw):
"""
Print msg merged with args as a verbose message.
See Python's logging module for details of message | formatting.
"""
self_.__db_print(VERBOSE,msg,*args,**kw) | csn_ccr |
Unserializes a value.
@param mixed $serialized The serialized value.
@return string The unserialized value.
@throws UnserializationFailedException If the value cannot be unserialized. | public static function unserialize($serialized)
{
if (!is_string($serialized)) {
throw UnserializationFailedException::forValue($serialized);
}
$errorMessage = null;
$errorCode = 0;
set_error_handler(function ($errno, $errstr) use (&$errorMessage, &$errorCode) {... | csn |
Loads a context from the annotations config and inject all objects in the Map
@param extraBeans Extra beans for being injected
@param config Configuration class
@return ApplicationContext generated | public static ApplicationContext contextMergedBeans(Map<String, ?> extraBeans, Class<?> config) {
final DefaultListableBeanFactory parentBeanFactory = buildListableBeanFactory(extraBeans);
//loads the annotation classes and add definitions in the context
GenericApplicationContext parent... | csn |
// Dial opens a network connection. | func (t *Transport) Dial(addr string, timeout time.Duration) (net.Conn, error) {
dialer := &net.Dialer{Timeout: timeout}
var err error
var conn net.Conn
if t.remoteEncrypted {
conf := &tls.Config{
InsecureSkipVerify: t.skipVerify,
}
fmt.Println("doing a TLS dial")
conn, err = tls.DialWithDialer(dialer, ... | csn |
// boxSearcher builds a searcher for the described bounding box
// if the desired box crosses the dateline, it is automatically split into
// two boxes joined through a disjunction searcher | func boxSearcher(indexReader index.IndexReader,
topLeftLon, topLeftLat, bottomRightLon, bottomRightLat float64,
field string, boost float64, options search.SearcherOptions) (
search.Searcher, error) {
if bottomRightLon < topLeftLon {
// cross date line, rewrite as two parts
leftSearcher, err := NewGeoBoundingB... | csn |
public function getValue(): string
{
if (!$this->validated && $this->defaultValue !== null) {
| return $this->defaultValue;
}
if ($this->value === null) {
return '';
}
return $this->value;
} | csn_ccr |
protected static function convert_hyphenation_exception_to_pattern( $exception ) {
$f = Strings::functions( $exception );
if ( empty( $f ) ) {
return null; // unknown encoding, abort.
}
// Set the word_pattern - this method keeps any contextually important capitalization.
$lowercase_hyphened_word_parts =... | for ( $i = 0; $i < $lowercase_hyphened_word_length; $i++ ) {
if ( '-' === $lowercase_hyphened_word_parts[ $i ] ) {
$word_pattern[ $index ] = 9;
} else {
$index++;
}
}
return $word_pattern;
} | csn_ccr |
Create the include path information
@param Infoset $info | protected function includePathInfo(Infoset $info) {
$list = $this->createList();
$list->setTitle('Include path');
$include = explode(PATH_SEPARATOR, get_include_path());
foreach ($include as $path) {
$list[] = $path;
}
$info[] = $list;
} | csn |
Create all default tiles, as defined above. | def _create_default_tiles(self):
"""Create all default tiles, as defined above."""
for value, background, text in self.DEFAULT_TILES:
self.tiles[value] = self._make_tile(value, background, text) | csn |
def private_config_file(self):
"""
Returns the private-config file for this IOU VM.
:returns: path to config file. None if the file doesn't exist
"""
| path = os.path.join(self.working_dir, 'private-config.cfg')
if os.path.exists(path):
return path
else:
return None | csn_ccr |
def refresh(self):
"""
Explicitly refresh one or more index, making all operations
performed since the last refresh available for search.
| """
self._changed = False
self.es.indices.refresh(index=self.index) | csn_ccr |
Gives the return type of an ExpressionTree that represents a method select.
<p>TODO(eaftan): Are there other places this could be used? | public static Type getReturnType(ExpressionTree expressionTree) {
if (expressionTree instanceof JCFieldAccess) {
JCFieldAccess methodCall = (JCFieldAccess) expressionTree;
return methodCall.type.getReturnType();
} else if (expressionTree instanceof JCIdent) {
JCIdent methodCall = (JCIdent) exp... | csn |
static function Delete($dir)
{
$files = self::GetFileSystemEntries($dir);
foreach($files as $file)
{
$path = Path::Combine($dir, $file);
switch(self::GetFileSystemEntryType($path))
{
case FileSystemEntryType::File():
... | break;
case FileSystemEntryType::Folder():
self::Delete($path);
break;
}
}
rmdir($dir);
} | csn_ccr |
public function collect($data)
{
$this->_map = $this->objectToArray($data); |
$this->_baseContents = &$this->_map;
return $this;
} | csn_ccr |
def acp_users_delete():
"""Delete or undelete an user account."""
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = UserDeleteForm()
if not form.validate():
re... | return error("User does not exist.", 404)
else:
for p in PERMISSIONS:
setattr(user, p, False)
user.active = direction == 'undel'
write_user(user)
return redirect(url_for('acp_users') + '?status={_del}eted'.format(
_del=direction)) | csn_ccr |
how to cast a variable as a float in python | def _tofloat(obj):
"""Convert to float if object is a float string."""
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj | cosqa |
Create singleton from class | def singleton(klass):
"""
Create singleton from class
"""
instances = {}
def getinstance(*args, **kwargs):
if klass not in instances:
instances[klass] = klass(*args, **kwargs)
return instances[klass]
return wraps(klass)(getinstance) | csn |
// clientConfig is used to generate a new client configuration struct for
// initializing a Nomad client. | func (a *Agent) clientConfig() (*clientconfig.Config, error) {
c, err := convertClientConfig(a.config)
if err != nil {
return nil, err
}
if err := a.finalizeClientConfig(c); err != nil {
return nil, err
}
return c, nil
} | csn |
using static variables in a python rest api | def home():
"""Temporary helper function to link to the API routes"""
return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \
HTTPStatus.OK | cosqa |
def _apply_summaries(self):
"""Add all summary rows and columns."""
def as_frame(r):
if isinstance(r, pd.Series):
return r.to_frame()
else:
return r
df = self.data
if df.index.nlevels > 1:
raise ValueError(
... | pd.concat([agg.apply(_df)
for agg in self._cleaned_summary_rows], axis=1).T
df = pd.concat([df, as_frame(rows)], axis=0)
if self.summary_cols:
cols = pd.concat([agg.apply(_df)
for agg in self._cleaned_summary_cols], axis=1)
... | csn_ccr |
Write an array to an output stream.
@param arr the array to write
@param outputStream the output stream to write to | public static void writeArrayToOutputStream(INDArray arr, OutputStream outputStream) {
ByteBuffer buffer = BinarySerde.toByteBuffer(arr);
try (WritableByteChannel channel = Channels.newChannel(outputStream)) {
channel.write(buffer);
} catch (IOException e) {
e.printStackT... | csn |
Dictionary with the AE partial waves indexed by state. | def ae_partial_waves(self):
"""Dictionary with the AE partial waves indexed by state."""
ae_partial_waves = OrderedDict()
for mesh, values, attrib in self._parse_all_radfuncs("ae_partial_wave"):
state = attrib["state"]
#val_state = self.valence_states[state]
a... | csn |
def download(self, path=''):
"""Download the data for this asset.
:param path: (optional), path where the file should be saved
to, default is the filename provided in the headers and will be
written in the current directory.
it can take a file-like object as well
... | }
resp = self._get(self._api, allow_redirects=False, stream=True,
headers=headers)
if resp.status_code == 302:
# Amazon S3 will reject the redirected request unless we omit
# certain request headers
headers.update({
'Cont... | csn_ccr |
def brightness(frames):
"""parse a brightness message"""
reader = MessageReader(frames)
res = reader.string("command").uint32("brightness").assert_end().get()
if res.command != "brightness":
| raise MessageParserError("Command is not 'brightness'")
return (res.brightness/1000,) | csn_ccr |
Delete outdated sessions for users that are no longer logged-in
@return bool sessions are deleted | private function deleteOldSessions()
{
// 2% chance of kicking idle sessions
if (mt_rand(0, 49)) {
return false;
}
$sessions = new UsersSessionEntityRepository();
$sessions->setOnlyOutdated();
$sessions->deleteObjectCollection();
return true;
... | csn |
// Appending logs to stdout. | func (s *Stdout) Append(log Log) {
msg := fmt.Sprintf(" {cyan}%s {default}%s {%s}%s[%s] ▶ %s",
log.Logger.Name,
log.Time.Format(s.DateFormat),
log.Level.color,
log.Level.icon,
log.Level.Name[:4],
log.Message)
color.Print(msg).InFormat()
} | csn |
func RegisterSimpleStringEnum(typeName string, typePrefix string, valueMap map[string]int32) {
if _, ok := simpleStringValueMaps[typeName]; ok {
panic("jsonpb: duplicate enum registered: " + typeName)
}
m := make(map[string]int32)
for key, value := range valueMap | {
m[strings.TrimPrefix(strings.ToLower(key), fmt.Sprintf("%s_", strings.ToLower(typePrefix)))] = value
}
simpleStringValueMaps[typeName] = m
} | csn_ccr |
Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform. | def _fit(self, col):
"""Create a map of the empirical probability for each category.
Args:
col(pandas.DataFrame): Data to transform.
"""
column = col[self.col_name].replace({np.nan: np.inf})
frequencies = column.groupby(column).count().rename({np.inf: None}).to_dict... | csn |
private static List<Object> convertRepeatedFieldToList(Group g, int fieldIndex, boolean binaryAsString)
{
Type t = g.getType().getFields().get(fieldIndex);
assert t.getRepetition().equals(Type.Repetition.REPEATED);
int repeated = g.getFieldRepetitionCount(fieldIndex);
List<Object> vals = new ArrayLis... | if (t.isPrimitive()) {
vals.add(convertPrimitiveField(g, fieldIndex, i, binaryAsString));
} else {
vals.add(g.getGroup(fieldIndex, i));
}
}
return vals;
} | csn_ccr |
function restartOnProcess( index ) {
log( 'Attempting to restart ' + index + '...' );
// generate delegate function to pass with proper contexts.
var startRequest = (function(context, index) {
return function(cb) {
startForeverWithIndex.call(context, index, cb);
};
}(this, index));
done = th... | log(forever.format(true,[process]));
forever.restart(index, false);
done();
}
else {
log(index + ' not found in list of processes in forever. Starting new instance...');
startRequest(done);
}
});
} | csn_ccr |
def copy(self, folder):
""" Copy the message to a given folder
:param folder: Folder object or Folder id or Well-known name to
copy this message to
:type folder: str or mailbox.Folder
:returns: the copied message
:rtype: Message
"""
if self.object_id is ... |
raise RuntimeError('Must Provide a valid folder_id')
data = {self._cc('destinationId'): folder_id}
response = self.con.post(url, data=data)
if not response:
return None
message = response.json()
# Everything received from cloud must be passed as self.... | csn_ccr |
def _init_sub_groups(self, parent):
"""
Initialise sub-groups, and create any that do not already exist.
"""
if self._sub_groups:
for sub_group in self._sub_groups:
for component in split_path_components(sub_group):
fp = os.path.join(paren... | parent.children.append(node)
else:
node = parent.create_cgroup(component)
parent = node
self._init_children(node)
else:
self._init_children(parent) | csn_ccr |
public function listContent()
{
$filesList = array();
$numFiles = $this->archive->numFiles;
for ($i = 0; $i < $numFiles; $i++) {
$statIndex = $this->archive->statIndex($i);
$filesList[] = (object) array(
'filename' => $statIndex['name'],
... | 'comment' => ($comment = $this->archive->getCommentIndex
($statIndex['index']) !== false) ? $comment : null,
'folder' => in_array(substr($statIndex['name'], -1),
array('/', '\\')),
'index' => $statIndex['index'],
'status' => 'ok',
... | csn_ccr |
def iter_sources(self):
"""Iterates over all source names and IDs."""
for | src_id in xrange(self.get_source_count()):
yield src_id, self.get_source_name(src_id) | csn_ccr |
def add(self, properties):
"""
Add a faked resource to this manager.
For URI-based lookup, the resource is also added to the faked HMC.
Parameters:
properties (dict):
Resource properties. If the URI property (e.g. 'object-uri') or the
| object ID property (e.g. 'object-id') are not specified, they
will be auto-generated.
Returns:
FakedBaseResource: The faked resource object.
"""
resource = self.resource_class(self, properties)
self._resources[resource.oid] = resource
self._hmc.... | csn_ccr |
private static PrintStream openStream(File out) throws IOException {
OutputStream os = new | FileOutputStream(out);
os = out.getName().endsWith(GZIP_POSTFIX) ? new GZIPOutputStream(os) : os;
return new PrintStream(os);
} | csn_ccr |
python logger is enabled for | def logger(message, level=10):
"""Handle logging."""
logging.getLogger(__name__).log(level, str(message)) | cosqa |
public function sendVenueReply(bool $quoteOriginal = false): SendVenue
{
$m = $this->bot->sendVenue();
| $this->setReplyMarkup($m, $quoteOriginal);
return $m;
} | csn_ccr |
Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return: | async def load_message_field(obj, msg, field, field_archiver=None):
"""
Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return:
... | csn |
New record with same keys or renamed keys if key found in key_map. | def rename_keys(record: Mapping, key_map: Mapping) -> dict:
"""New record with same keys or renamed keys if key found in key_map."""
new_record = dict()
for k, v in record.items():
key = key_map[k] if k in key_map else k
new_record[key] = v
return new_record | csn |
public function setText(string $text): void
{
$this->text = $text;
if ( ! is_null($this->encode)) {
$text = $this->encode->convert($text);
| // remember the conversion
$this->convertedText = $text;
}
} | csn_ccr |
function(context, childPkg){
var curAddress = childPkg.origFileUrl;
var parentAddress = utils.path.parentNodeModuleAddress(childPkg.origFileUrl);
while(parentAddress) {
var packageAddress = parentAddress+"/"+childPkg.name+"/package.json";
var parentPkg = context.paths[packageAddress];
if(parentPkg && Sem... |
return parentPkg.fileUrl;
} else {
return curAddress;
}
}
parentAddress = utils.path.parentNodeModuleAddress(packageAddress);
curAddress = packageAddress;
}
return curAddress;
} | csn_ccr |
Replies the isCurved property.
@return the isCurved property. | 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 == PathElementTy... | csn |
// reloadHTTPServer shuts down the existing HTTP server and restarts it. This
// is helpful when reloading the agent configuration. | func (c *Command) reloadHTTPServer() error {
c.agent.logger.Info("reloading HTTP server with new TLS configuration")
c.httpServer.Shutdown()
http, err := NewHTTPServer(c.agent, c.agent.config)
if err != nil {
return err
}
c.httpServer = http
return nil
} | csn |
Renders the Dompdf instance.
@param \CakePdf\Pdf\CakePdf $Pdf The CakePdf instance that supplies the content to render.
@param \Dompdf\Dompdf $DomPDF The Dompdf instance to render.
@return \Dompdf\Dompdf | protected function _render($Pdf, $DomPDF)
{
$DomPDF->loadHtml($Pdf->html());
$DomPDF->render();
return $DomPDF;
} | csn |
private function validateUnderlyingObjectType($object)
{
if (count($this->mustBeInstanceOf) == 0) {
return true;
}
foreach ($this->mustBeInstanceOf as $instance) {
if ($object instanceof $instance) { //|| $object->asa($instance) !== null
| return true;
}
}
Yii::error('Got invalid underlying object type! (' . $object->className() . ')');
return false;
} | csn_ccr |
Store all content of the given ListField in a redis set.
Use scripting if available to avoid retrieving all values locally from
the list before sending them back to the set | def _list_to_set(self, list_key, set_key):
"""
Store all content of the given ListField in a redis set.
Use scripting if available to avoid retrieving all values locally from
the list before sending them back to the set
"""
if self.cls.database.support_scripting():
... | csn |
public BooleanConditionBuilder must(ConditionBuilder... conditionBuilders) {
if (must == null) {
must = new ArrayList<>(conditionBuilders.length);
}
for | (ConditionBuilder conditionBuilder : conditionBuilders) {
must.add(conditionBuilder.build());
}
return this;
} | csn_ccr |
public function style($style)
{
if (is_string($style)) {
$this->attributes['style'] = $style;
return $this;
}
if (is_array($style)) {
$html = [];
foreach ($style as $name => $value) | {
$html[] = "$name:$value";
}
$this->attributes['style'] = implode(';', $html);
}
return $this;
} | csn_ccr |
// IndirectPtr implements the BlockWithPtrs interface for FileBlock. | func (fb *FileBlock) IndirectPtr(i int) (BlockInfo, Offset) {
if !fb.IsInd {
panic("IndirectPtr called on a direct file block")
}
iptr := fb.IPtrs[i]
return iptr.BlockInfo, iptr.Off
} | csn |
protected function getDevices() {
if (!$this->_devices) {
$this->_devices | = new DeviceList($this->version, $this->solution['sid']);
}
return $this->_devices;
} | csn_ccr |
def setup_path():
"""Sets up the python include paths to include src"""
import os.path; import sys
| if sys.argv[0]:
top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
sys.path = [os.path.join(top_dir, "src")] + sys.path
pass
return | csn_ccr |
Create the given resource.
Args:
resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on success.
Raises:
re... | def create(self, resource):
"""Create the given resource.
Args:
resource (intern.resource.boss.BossResource): Create a data model object with attributes matching those of the resource.
Returns:
(intern.resource.boss.BossResource): Returns resource of type requested on s... | csn |
public function addAppends($appends)
{
if (is_string($appends)) {
$appends = func_get_args();
}
$this->appends | = array_merge($this->appends, $appends);
return $this;
} | csn_ccr |
Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.
To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is... | N=int(input())
M=len(input())
O=10**9+7
D=[pow(-~O//2,M,O)]+[0]*N
for _ in'_'*N:D=[D[0]+D[1]]+[(i+2*j)%O for i,j in zip(D[2:]+[0],D[:-1])]
print(D[M]) | apps |
def accept(self):
'''
Acts as `Field.accepts` but returns result of every child field
as value in parent `python_data`.
'''
| result = FieldSet.accept(self)
self.clean_value = result[self.name]
return self.clean_value | csn_ccr |
Retrieve the searchlog for the specified search jobs. | def searchlog(self, argv):
"""Retrieve the searchlog for the specified search jobs."""
opts = cmdline(argv, FLAGS_SEARCHLOG)
self.foreach(opts.args, lambda job:
output(job.searchlog(**opts.kwargs))) | csn |
Loads binary data asynchronously. The returned state instance provides a means to listen for
the arrival of the data.
@param path the path to the binary asset. | public RFuture<ByteBuffer> getBytes (final String path) {
final RPromise<ByteBuffer> result = exec.deferredPromise();
exec.invokeAsync(new Runnable() {
public void run () {
try {
result.succeed(getBytesSync(path));
} catch (Throwable t) {
result.fail(t);
}
... | csn |
getSurvey - Get information on a survey
@param int $surveyId - See survey ID to use
@param bool $includePages - Include page details or not
@return @see Client::sendRequest | public function getSurvey($surveyId, $includePages = false)
{
if ($includePages) {
return $this->sendRequest(
$this->createRequest('GET', sprintf('surveys/%d/details', $surveyId))
);
} else {
return $this->sendRequest(
$this->createRequest('GET', sprintf('surveys/%d', $surveyId))
);
}
} | csn |
protected void cleanUpMenuTree(WebMenuItem root, String menuName){
List<WebMenuItem> subMenu = root.getSubMenu();
List<WebMenuItem> rootBreadcrumbs = root.getBreadcrumbs();
if (subMenu != null && subMenu.size() > 0){
Collections.sort(subMenu);
for (int i = 0; i < subMenu.size(); i++){
WebMenuItem ... | menuItemPaths.get(menuName).put(itemExt.path, item);
}
item.breadcrumbs = new ArrayList<WebMenuItem>();
if (rootBreadcrumbs != null){
item.breadcrumbs.addAll(rootBreadcrumbs);
}
item.breadcrumbs.add(item);
cleanUpMenuTree(item, menuName);
}
}
} | csn_ccr |
def _see_node(self, node_id, fringe, dist, w_wait_in=0):
"""
See a node, updating seen and fringe.
:param node_id:
Node id to see.
:type node_id: str
:param fringe:
Heapq of closest available nodes.
:type fringe: list[(float | int, bool, (str, Di... | raise DispatcherError('Contradictory paths found: '
'negative weights?', sol=self)
elif node_id not in seen or dist < seen[node_id]: # Check min dist.
seen[node_id] = dist # Update dist.
index = self.nodes[node_id]['index'] # Node index.
... | csn_ccr |
Checks that variables, functions, and arguments are not deleted. | private static void checkDelete(NodeTraversal t, Node n) {
if (n.getFirstChild().isName()) {
Var v = t.getScope().getVar(n.getFirstChild().getString());
if (v != null) {
t.report(n, DELETE_VARIABLE);
}
}
} | csn |
function printFileSizesAfterBuild(
webpackStats,
previousSizeMap,
buildFolder,
maxBundleGzipSize,
maxChunkGzipSize
) {
var root = previousSizeMap.root;
var sizes = previousSizeMap.sizes;
var assets = (webpackStats.stats || [webpackStats])
.map(stats =>
stats
.toJson({ all: false, asset... | ? maxBundleGzipSize
: maxChunkGzipSize;
var isLarge = maxRecommendedSize && asset.size > maxRecommendedSize;
if (isLarge && path.extname(asset.name) === '.js') {
suggestBundleSplitting = true;
}
console.log(
' ' +
(isLarge ? chalk.yellow(sizeLabel) : sizeLabel) +
' ... | csn_ccr |
public void addPattern(Pattern pattern) {
if (patterns == null) { |
patterns = new ArrayList<Pattern>();
}
patterns.add(pattern);
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.