query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
// CursorRight move to right on the current line. | func (b *Buffer) CursorRight(count int) {
l := b.Document().GetCursorRightPosition(count)
b.cursorPosition += l
return
} | csn |
def _build_lv_grid_dict(network):
"""Creates dict of LV grids
LV grid ids are used as keys, LV grid references as values.
Parameters
----------
network: :class:`~.grid.network.Network`
The eDisGo container object
Returns
-------
:obj:`dict`
| Format: {:obj:`int`: :class:`~.grid.grids.LVGrid`}
"""
lv_grid_dict = {}
for lv_grid in network.mv_grid.lv_grids:
lv_grid_dict[lv_grid.id] = lv_grid
return lv_grid_dict | csn_ccr |
func (in *Secret) DeepCopy() *Secret {
if in == nil {
return nil
}
out | := new(Secret)
in.DeepCopyInto(out)
return out
} | csn_ccr |
def restore_original_new_method(klass)
klass.define_singleton_method :new do |*args, &block|
| Throttling.original_new_method(klass).bind(klass).call *args, &block
end
end | csn_ccr |
// FilesHandler returns a handler that serves the concatentation of the
// specified files. The files are specified by slash separated paths relative
// to the static server's Dir field. | func (ss *StaticServer) FilesHandler(fileNames ...string) http.Handler {
// todo: cache concatenated files on disk and serve from there.
mimeType := ss.mimeType(fileNames[0])
var buf []byte
var openErr error
for _, fileName := range fileNames {
p, err := ioutil.ReadFile(ss.resolve(fileName))
if err != nil {... | csn |
Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`. | def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment:
"Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`."
x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8))
x = x.view(shape[1], shape[0], -1)
return ImageSegment(x.permu... | csn |
R"""
Degenerate log-likelihood.
.. math::
f(x \mid k) = \left\{ \begin{matrix} 1 \text{ if } x = k \\ 0 \text{ if } x \ne k\end{matrix} \right.
:Parameters:
- `x` : Input value.
- `k` : Degenerate value. | def degenerate_like(x, k):
R"""
Degenerate log-likelihood.
.. math::
f(x \mid k) = \left\{ \begin{matrix} 1 \text{ if } x = k \\ 0 \text{ if } x \ne k\end{matrix} \right.
:Parameters:
- `x` : Input value.
- `k` : Degenerate value.
"""
x = np.atleast_1d(x)
return sum(np... | csn |
An iterator returning file_paths in a directory
containing CONLL-formatted files. | def dataset_path_iterator(file_path: str) -> Iterator[str]:
"""
An iterator returning file_paths in a directory
containing CONLL-formatted files.
"""
logger.info("Reading CONLL sentences from dataset files at: %s", file_path)
for root, _, files in list(os.walk(file_path))... | csn |
Set the property's display layout.
@param string $display The layout for the tickable elements.
@throws InvalidArgumentException If the given layout is invalid.
@throws OutOfBoundsException If the given layout is unsupported.
@return self | public function setDisplay($display)
{
if ($display === null) {
$this->display = null;
return $this;
}
if (!is_string($display)) {
throw new InvalidArgumentException(sprintf(
'Layout must be a string, received %s',
(is_obj... | csn |
// removeStateFiles goes through the list of files and removes any that appear
// to be statefiles to avoid .leash.state.leash.state.leash.state from appearing
// when you use an overly permissive glob | func removeStateFiles(files []string, conf Config) []string {
newFiles := []string{}
for _, file := range files {
if file == conf.Options.StateFile {
logrus.WithFields(logrus.Fields{
"file": file,
}).Debug("skipping tailing file because it is named the same as the statefile flag")
continue
}
if str... | csn |
def _delim_accum(control_files, filename_template, keys=None,
exclude_keys=None, separator=DEFAULT_SEP, missing_action='fail'):
"""
Accumulator for delimited files
Combines each file with values from JSON dictionary in same directory
:param iterable control_files: Iterable of control files
... | f))
with open(f) as fp:
reader = csv.DictReader(fp, delimiter=separator)
for row in reader:
row_dict = collections.OrderedDict(
itertools.chain(((k, row[k]) for k in reader.fieldnames),
((k, v) for k, v... | csn_ccr |
public AggregatedStats getAggregatedStats(long id, GameMode gameMode, Season season) {
| return client.sendRpcAndWait(SERVICE, "getAggregatedStats", id, gameMode, season.numeric);
} | csn_ccr |
remove last object from python list without deleting list | def pop(self, index=-1):
"""Remove and return the item at index."""
value = self._list.pop(index)
del self._dict[value]
return value | cosqa |
public function export($axml)
{
$category = PermissionKeyCategory::getByID($this->pkCategoryID)->getPermissionKeyCategoryHandle();
$pkey = $axml->addChild('permissionkey');
$pkey->addAttribute('handle', $this->getPermissionKeyHandle());
$pkey->addAttribute('name', $this->getPermissio... | $pkey->addAttribute('description', $this->getPermissionKeyDescription());
$pkey->addAttribute('package', $this->getPackageHandle());
$pkey->addAttribute('category', $category);
$this->exportAccess($pkey);
return $pkey;
} | csn_ccr |
func (k *SimpleFS) SimpleFSGetUserQuotaUsage(ctx context.Context) (
res keybase1.SimpleFSQuotaUsage, err error) {
ctx = k.makeContext(ctx)
status, _, err := k.config.KBFSOps().Status(ctx)
if err != nil {
return keybase1.SimpleFSQuotaUsage{}, err
}
res.UsageBytes = status.UsageBytes
res.ArchiveBytes = status.Ar... | status.LimitBytes
res.GitUsageBytes = status.GitUsageBytes
res.GitArchiveBytes = status.GitArchiveBytes
res.GitLimitBytes = status.GitLimitBytes
return res, nil
} | csn_ccr |
Tests a string and returns true if the string counts as a reserved token in the Java language.
@param value the {@code String} to be tested.
@return {@code true} if the {@code String} is a reserved token; {@code false} otherwise. | private boolean isToken(String value) {
int len = value.length();
for (int i = 0; i < len; i++) {
char c = value.charAt(i);
if (c < 0x20 || c >= 0x7f || TSPECIALS.indexOf(c) != -1) {
return false;
}
}
return true;
} | csn |
Given an array of numbers (in string format), you must return a string. The numbers correspond to the letters of the alphabet in reverse order: a=26, z=1 etc. You should also account for `'!'`, `'?'` and `' '` that are represented by '27', '28' and '29' respectively.
All inputs will be valid. | def switcher(arr):
d = {str(i): chr(123-i) for i in range(1,27)}
d.update({'27':'!'})
d.update({'28':'?'})
d.update({'29':' '})
d.update({'0':''})
return ''.join([d[str(i)] for i in arr]) | apps |
def get_token(self, url):
"""
Retrieves a temporary access token
"""
# A hack to avoid url-encoding the url, since the authorization service
# doesn't work with correctly encoded | urls
parsed_url = urlparse.urlsplit(url)
parsed_url = parsed_url._replace(path='/authorization/api')
self.url = urlparse.urlunsplit(parsed_url)
response = self.request(method='GET', url='/v1/token?url=' + url)
return response.result.text | csn_ccr |
Generate an ordered list of items.
@param array $list
@param array $attributes
@return string | public static function ol($list, $attributes = array())
{
$html = self::getInstance()->html;
$args = func_get_args();
return call_user_func_array(array($html, __FUNCTION__), $args);
} | csn |
public function setTemplate($template)
{
if (!($template instanceof KTemplateInterface))
{
if (is_string($template) && strpos($template, '.') === false)
{
$identifier = $this->getIdentifier()->toArray();
| $identifier['path'] = array('template');
$identifier['name'] = $template;
$identifier = $this->getIdentifier($identifier);
}
else $identifier = $this->getIdentifier($template);
$template = $identifier;
}
$this->_template... | csn_ccr |
public Bbox getBounds() {
double w = getViewSpaceWidth();
double h = getViewSpaceHeight();
double x = viewState.getX() - w / | 2;
double y = viewState.getY() - h / 2;
return new Bbox(x, y, w, h);
} | csn_ccr |
Choose what relationships to return with query.
@param mixed $relationships
@return $this | public function with($relationships)
{
$this->requiredRelationships = [];
if ($relationships == 'all') {
$this->requiredRelationships = $this->relationships;
} elseif (is_array($relationships)) {
$this->requiredRelationships = array_filter($relationships, function ($... | csn |
public static function getPrivateProperty(\ReflectionClass $reflectionClass, $property)
{
if (!$reflectionClass->hasProperty($property) && | $reflectionClass->getParentClass()) {
return static::getPrivateProperty($reflectionClass->getParentClass(), $property);
}
return $reflectionClass->getProperty($property);
} | csn_ccr |
Patch on ngModelOptions, since it doesn't like waiting for its value. | function(args) {
if (args.form.ngModelOptions && Object.keys(args.form.ngModelOptions).length > 0) {
args.fieldFrag.firstChild.setAttribute('ng-model-options', JSON.stringify(args.form.ngModelOptions));
}
} | csn |
returns if a value is an instance of native type
@param ctx.{*} ctx.val ctx.value to check if is native
@return {Boolean} ctx.true if val is native, else false | function isNative (val) {
if (isPrimitive(val)) {
return true
}
return natives.some(function (Class) {
return val === Class || directInstanceOf(val, Class)
})
} | csn |
GENERIC!!! HELPER FUNCION FOR REPLACEMENT
update the var: DYNAMIC REPLACEMENT of VAR.
Every task must have matching command data and task result
@param task
the task
@param replaceVarKey
the replace var key
@param replaceVarValue
the replace var value | public void updateRequestByAddingReplaceVarPair(
ParallelTask task, String replaceVarKey, String replaceVarValue) {
Map<String, NodeReqResponse> taskResult = task.getParallelTaskResult();
for (Entry<String, NodeReqResponse> entry : taskResult.entrySet()) {
NodeReqResponse nodeR... | csn |
// nodeConditionsLastObservedAt merges the input with the previous observation to determine when a condition was most recently met. | func nodeConditionsLastObservedAt(nodeConditions []v1.NodeConditionType, lastObservedAt nodeConditionsObservedAt, now time.Time) nodeConditionsObservedAt {
results := nodeConditionsObservedAt{}
// the input conditions were observed "now"
for i := range nodeConditions {
results[nodeConditions[i]] = now
}
// the c... | csn |
// SafeRestart jenkins, restart will be done when there are no jobs running | func (j *Jenkins) SafeRestart() error {
_, err := j.Requester.Post("/safeRestart", strings.NewReader(""), struct{}{}, map[string]string{})
return err
} | csn |
func (s *LoggingConfiguration) SetRedactedFields(v | []*FieldToMatch) *LoggingConfiguration {
s.RedactedFields = v
return s
} | csn_ccr |
OpenCV Gaussian filter
Still propagates NaN values | def gauss_fltr_opencv(dem, size=3, sigma=1):
"""OpenCV Gaussian filter
Still propagates NaN values
"""
import cv2
dem = malib.checkma(dem)
dem_cv = cv2.GaussianBlur(dem.filled(np.nan), (size, size), sigma)
out = np.ma.fix_invalid(dem_cv)
out.set_fill_value(dem.fill_value)
return out | csn |
func NewManagedConn(
network string,
address string,
handle resource_pool.ManagedHandle,
pool ConnectionPool,
options ConnectionOptions) ManagedConn {
addr := NetworkAddress{
Network: network,
Address: address,
}
|
return &managedConnImpl{
addr: addr,
handle: handle,
pool: pool,
options: options,
}
} | csn_ccr |
// shExpMatch returns true if the string matches the specified shell expression. | func shExpMatch(str, shexp string) bool {
shexp = strings.Replace(shexp, ".", "\\.", -1)
shexp = strings.Replace(shexp, "?", ".?", -1)
shexp = strings.Replace(shexp, "*", ".*", -1)
matched, err := regexp.MatchString("^"+shexp+"$", str)
return err == nil && matched
} | csn |
Auto generates pretty label_columns from list of columns | def _gen_labels_columns(self, list_columns):
"""
Auto generates pretty label_columns from list of columns
"""
for col in list_columns:
if not self.label_columns.get(col):
self.label_columns[col] = self._prettify_column(col) | csn |
x = np.arange(12)
x.size
np.zeros((2, 3, 4))
np.ones((2, 3, 4))
np.random.normal(0, 1, size=(3, 4))
np.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
x = np.array([1, 2, 4, 8])
y = np.array([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
np.exp(x)
X = np.arange(12).reshape(3, 4)
Y = np.array([[2, 1, 4, 3], [1, 2, 3... | x = torch.arange(12)
x.numel()
torch.zeros((2, 3, 4))
torch.ones((2, 3, 4))
torch.randn(3, 4)
torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
torch.exp(x)
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
... | codetrans_dl |
// Put stores a chunk in localstore, and delivers to all requestor peers using the fetcher stored in
// the fetchers cache | func (n *NetStore) Put(ctx context.Context, ch Chunk) error {
n.mu.Lock()
defer n.mu.Unlock()
// put to the chunk to the store, there should be no error
err := n.store.Put(ctx, ch)
if err != nil {
return err
}
// if chunk is now put in the store, check if there was an active fetcher and call deliver on it
/... | csn |
function searchFilter(mock) {
if (!vm.searchUrl || !mock.expression) {
return true;
}
| return vm.searchUrl.match(mock.expression);
} | csn_ccr |
public void removeEjbBindings()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "removeEjbBindings called");
// Just loop through the values, not the keys, as the simple-binding-name
| // key may have a # in front of it when the bean was not simple, and that
// won't match what is in the ServerContextBindingMap. d457053.1
for (String bindingName : ivEjbContextBindingMap.values())
{
removeFromServerContextBindingMap(bindingName, true);
}
... | csn_ccr |
func (s *ListBackupsInput) SetTimeRangeUpperBound(v time.Time) *ListBackupsInput {
| s.TimeRangeUpperBound = &v
return s
} | csn_ccr |
def check(text):
"""Advice on sudden vs suddenly."""
err = "misc.suddenly"
msg = u"Suddenly is nondescript, slows the action, and warns your reader."
regex = "Suddenly,"
return existence_check(text, | [regex], err, msg, max_errors=3,
require_padding=False, offset=-1, ignore_case=False) | csn_ccr |
how to see array size in python | def bytesize(arr):
"""
Returns the memory byte size of a Numpy array as an integer.
"""
byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize
return byte_size | cosqa |
protected static String orRegex(Iterable<String> elements) {
final StringBuilder regex = new StringBuilder();
for (final String element : elements) {
if (regex.length() > 0) {
regex.append("|"); //$NON-NLS-1$
| }
regex.append("(?:"); //$NON-NLS-1$
regex.append(quoteRegex(element));
regex.append(")"); //$NON-NLS-1$
}
return regex.toString();
} | csn_ccr |
Get recent events
Args:
filters (string set): 'ARM', 'DISARM', 'FIRE', 'INTRUSION',
'TECHNICAL', 'SOS', 'WARNING', 'LOCK',
'UNLOCK'
pagesize (int): Number of events to display
offset (int): Skip pagesize * o... | def get_history(self, filters=(), pagesize=15, offset=0):
""" Get recent events
Args:
filters (string set): 'ARM', 'DISARM', 'FIRE', 'INTRUSION',
'TECHNICAL', 'SOS', 'WARNING', 'LOCK',
'UNLOCK'
pagesize (int): N... | csn |
public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, Connection con, Map<String, Object> _parameters) throws JRException {
log.info("generating JasperPrint");
JasperPrint jp;
if (_parameters == null)
_parameters = new HashMap<String, Object>()... | dr);
JRPropertiesUtil.getInstance(DefaultJasperReportsContext.getInstance()).setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());
//JRProperties.setProperty(JRCompiler.COMPILER_PREFIX, DJCompilerFactory.getCompilerClassName());
JasperReport jr = JasperCompileManage... | csn_ccr |
Returns all unused splits in the account. Used for the calculation of avg.price.
The split that has been partially used will have its quantity reduced to available
quantity only. | def get_available_splits_for_account(self, account: Account) -> List[Split]:
""" Returns all unused splits in the account. Used for the calculation of avg.price.
The split that has been partially used will have its quantity reduced to available
quantity only. """
available_splits = []
... | csn |
// GetManifest wraps methods.GetManifest | func (l *Lease) GetManifest(ctx context.Context) error {
req := types.HttpNfcLeaseGetManifest{
This: l.Reference(),
}
_, err := methods.HttpNfcLeaseGetManifest(ctx, l.c, &req)
if err != nil {
return err
}
return nil
} | csn |
def GetDisplayNameForPathSpec(
cls, path_spec, mount_path=None, text_prepend=None):
"""Retrieves the display name of a path specification.
Args:
path_spec (dfvfs.PathSpec): path specification.
mount_path (Optional[str]): path where the file system that is used
by the path specificat... | and path_spec.type_indicator in (
dfvfs_definitions.TYPE_INDICATOR_BZIP2,
dfvfs_definitions.TYPE_INDICATOR_GZIP):
parent_path_spec = parent_path_spec.parent
if parent_path_spec and parent_path_spec.type_indicator == (
dfvfs_definitions.TYPE_INDICATOR_VSHADOW):
store_index = get... | csn_ccr |
def list_resource_groups(access_token, subscription_id):
'''List the resource groups in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response.
'''
endpoint = ''.join([get_rm_endpoin... | '/subscriptions/', subscription_id,
'/resourceGroups/',
'?api-version=', RESOURCE_API])
return do_get(endpoint, access_token) | csn_ccr |
Return a list of integers that are list-index references to the
original list of dictionaries."
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "order": 2},
... {"name": "Larry", "age": 18, "order": 3},
... {"name... | def returnIndexList(self, limit=False):
'''Return a list of integers that are list-index references to the
original list of dictionaries."
Example of use:
>>> test = [
... {"name": "Jim", "age": 18, "income": 93000, "order": 2},
... {"name": "Larry", "age": 18, ... | csn |
private <T> void addIndex(Map<T, List<HttpCookie>> indexStore,
T index,
HttpCookie cookie)
{
// Android-changed : "index" can be null. We only use the URI based
// index on Android and we want to support null URIs. The underlying
| // store is a HashMap which will support null keys anyway.
List<HttpCookie> cookies = indexStore.get(index);
if (cookies != null) {
// there may already have the same cookie, so remove it first
cookies.remove(cookie);
cookies.add(cookie);
} else {
... | csn_ccr |
public function mirror($local_path, $remote_path)
{
if ( ! $this->_is_conn())
{
return false;
}
// Open the local file path
if ($fp = @opendir($local_path))
{
// Attempt to open the remote file path.
if ( ! $this->change_dir($remote_path, true))
{
// If it doesn't exist we'll attempt to cr... |
elseif (substr($file, 0, 1) != ".")
{
// Get the file extension so we can se the upload type
$ext = pathinfo($file, PATHINFO_EXTENSION);
$mode = $this->_settype($ext);
$this->upload($local_path.$file, $remote_path.$file, $mode);
}
}
return true;
}
return false;
} | csn_ccr |
Run random prompt.
@param string $name
@param array $options
@param string $default
@return string | protected function runRandom($name, array $options, $default = 'SomeRandomString')
{
$value = $this->command->ask($this->generatePrompt($name, $options['prompt']), $default);
if ($value === 'SomeRandomString')
{
$value = $this->getRandomKey(config('app.cipher'));
}
... | csn |
Prepare request to node's API route
:param Node node: the RAML node object | def prepare_request(node):
"""
Prepare request to node's API route
:param Node node: the RAML node object
"""
if node.resource.method not in AVAILABLE_METHODS:
raise UnsupportedHTTPMethodError(node.resource.method)
def request(data=None, json=None, **kwargs):
"""
... | csn |
Execute all Rules in the RuleSet.
@param Context $context Context with which to execute each Rule | public function executeRules(Context $context)
{
foreach ($this->rules as $rule) {
$rule->execute($context);
}
} | csn |
def display_index(config):
"""Open index in web browser.
Parameters
----------
config : Config
Configuration settings.
Raises
------
FileNotFoundError
If index file doesn't exist.
"""
browser = config["web browser"].lower()
data_dir = Path(config["data dir"])
... | b = webbrowser.get()
index_file = data_dir.joinpath("index.html")
if not index_file.exists():
logger.error("File doesn't exist: %s", index_file.as_posix())
raise FileNotFoundError("Index file doesn't exist")
else:
logger.info("Opening %s in '%s'", index_file.as_posix(), b.name)... | csn_ccr |
how to write a list as tab delimit into a file, line by line, python | def write_tsv_line_from_list(linelist, outfp):
"""Utility method to convert list to tsv line with carriage return"""
line = '\t'.join(linelist)
outfp.write(line)
outfp.write('\n') | cosqa |
how to make sprites move up and down in python | def move_back(self, dt):
""" If called after an update, the sprite can move back
"""
self._position = self._old_position
self.rect.topleft = self._position
self.feet.midbottom = self.rect.midbottom | cosqa |
def readBatchTupleQuotes(self, symbols, start, end):
'''
read batch quotes as tuple to save memory
'''
if end is None:
end=sys.maxint
ret={}
session=self.getReadSession()()
try:
symbolChunks=splitListEqually(symbols, 100)
... | Quote.time < int(end)))
for row in rows:
if row.time not in ret:
ret[row.time]={}
ret[row.time][row.symbol]=self.__sqlToTupleQuote(row)
finally:
self.getRe... | csn_ccr |
Discard padding bytes using the unpacked length attribute. | def unpack(self, buff, offset=0):
"""Discard padding bytes using the unpacked length attribute."""
begin = offset
for name, value in list(self.get_class_attributes())[:-1]:
size = self._unpack_attribute(name, value, buff, begin)
begin += size
self._unpack_attribut... | csn |
Gets the value of the genericApplicationPropertyOfRoofSurface property.
<p>
This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a <CODE>set</CODE> method for the genericAppli... | public List<JAXBElement<Object>> get_GenericApplicationPropertyOfRoofSurface() {
if (_GenericApplicationPropertyOfRoofSurface == null) {
_GenericApplicationPropertyOfRoofSurface = new ArrayList<JAXBElement<Object>>();
}
return this._GenericApplicationPropertyOfRoofSurface;
} | csn |
Create the main menu using the admin config.
@param mixed $options The main menu widget ID or config.
@throws InvalidArgumentException If the admin config is missing, invalid, or malformed.
@return array | protected function createMainMenu($options = null)
{
$mainMenuConfig = $this->adminConfig('main_menu');
if (!isset($mainMenuConfig['items'])) {
throw new InvalidArgumentException(
'Missing "admin.main_menu.items"'
);
}
$mainMenuIdent = $this-... | csn |
public function actionUpdate($id)
{
$model = $this->findModel($id);
if (!\Yii::$app->user->can('update', ['model' => $model]))
throw new ForbiddenHttpException(Module::t('metaTag', 'Access denied.'));
if ($model->load(\Yii::$app->request->post()) && $model->save()) {
... | return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
} | csn_ccr |
func FormatPod(pod *Pod) string {
// Use underscore as the delimiter because it is not allowed in pod name
// (DNS subdomain format), while allowed | in the container name format.
return fmt.Sprintf("%s_%s(%s)", pod.Name, pod.Namespace, pod.ID)
} | csn_ccr |
def get_full_pipe(sol, base=()):
"""
Returns the full pipe of a dispatch run.
:param sol:
A Solution object.
:type sol: schedula.utils.Solution
:param base:
Base node id.
:type base: tuple[str]
:return:
Full pipe of a dispatch run.
:rtype: DspPipe
"""
... | n_id = node_id[i:]
n, path = d.get_node(n, node_attr=None)
if n['type'] == 'function' and 'function' in n:
try:
sub_sol = s.workflow.node[path[-1]]['solution']
sp = get_full_pipe(sub_sol, base=node_id)
if sp:
p['sub_... | csn_ccr |
// SetChunk sets a limited range of the underlying BGZF file to read, after
// seeking to the start of the given chunk. It may be used to iterate over
// a defined genomic interval. | func (br *Reader) SetChunk(c *bgzf.Chunk) error {
if c != nil {
err := br.r.Seek(c.Begin)
if err != nil {
return err
}
}
br.c = c
return nil
} | csn |
func WithConfirms(confirm chan struct{}, msg Msg) Msg {
switch m := msg.(type) {
case | *Base:
m.confirm = confirm
}
return msg
} | csn_ccr |
Collapse an iterable of intervals sorted by start coord. | def _collapse(intervals):
"""
Collapse an iterable of intervals sorted by start coord.
"""
span = None
for start, stop in intervals:
if span is None:
span = _Interval(start, stop)
elif start <= span.stop < stop:
span = _Interval(span.start, stop)
... | csn |
This method should be invoked by the user of the PatternFinder. Invoke it
for each value in your dataset. Repeated values are handled correctly but
if available it is more effecient to handle only the distinct values and
their corresponding distinct counts.
@param row
the row containing the value
@param value
the stri... | public void run(R row, String value, int distinctCount) {
final List<Token> tokens;
boolean match = false;
try {
tokens = _tokenizer.tokenize(value);
} catch (RuntimeException e) {
throw new IllegalStateException("Error occurred while tokenizing value: " + value, ... | csn |
Considers the given name to be a property name. If the concrete syntax of the
processed feature matches a feature call or assignment, a prefix is added to the
name and that one is used as a variant that should be processed. | protected void processAsPropertyNames(QualifiedName name, NameAcceptor acceptor) {
String nameAsPropertyName = tryGetAsPropertyName(name.toString());
if (nameAsPropertyName != null) {
if (featureCall == null || featureCall instanceof XAssignment) {
String aliasedSetter = "set" + nameAsPropertyName;
accep... | csn |
func httpClientForRootCAs(rootCAs string) (*http.Client, error) {
tlsConfig := tls.Config{RootCAs: x509.NewCertPool()}
rootCABytes, err := ioutil.ReadFile(rootCAs)
if err != nil {
return nil, fmt.Errorf("failed to read root-ca: %v", err)
}
if !tlsConfig.RootCAs.AppendCertsFromPEM(rootCABytes) {
return nil, fmt... | http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}, nil
} | csn_ccr |
func (pool *Pool) TTL(ttl time.Duration) *Pool {
pool.conf.TTL = ttl |
return &Pool{redis: pool.redis, conf: pool.conf}
} | csn_ccr |
def as_dict(self):
"Get the WorkResult as a dict."
return {
'output': self.output,
'test_outcome': self.test_outcome,
| 'worker_outcome': self.worker_outcome,
'diff': self.diff,
} | csn_ccr |
def simulate(self, steps, initial_lr):
"""
Simulates the learning rate scheduler.
Parameters
----------
steps: int
Number of steps to simulate
initial_lr: float
Initial learning rate
Returns
-------
lrs: numpy ndarray
... | """
test = torch.ones(1, requires_grad=True)
opt = torch.optim.SGD([{'params': test, 'lr': initial_lr}])
policy_cls = self._get_policy_cls()
sch = policy_cls(opt, **self.kwargs)
if hasattr(sch, 'batch_step') and callable(sch.batch_step):
step = sch.batch_step
... | csn_ccr |
def plot(what, calc_id=-1, other_id=None, webapi=False):
"""
Generic plotter for local and remote calculations.
"""
if '?' not in what:
raise SystemExit('Missing ? in %r' % what)
prefix, rest = what.split('?', 1)
assert prefix in 'source_geom hcurves hmaps uhs', prefix
if prefix in '... | = [WebExtractor(calc_id)]
if other_id:
xs.append(WebExtractor(other_id))
else:
xs = [Extractor(calc_id)]
if other_id:
xs.append(Extractor(other_id))
make_figure = globals()['make_figure_' + prefix]
plt = make_figure(xs, what)
plt.show() | csn_ccr |
private function _validateInput($input, $base, $checkDomain = false)
{
if (!array_key_exists($base, self::$allowedBases)) {
throw new InvalidArgumentException(sprintf(
'Type must be one of "%s".',
implode(', ', array_keys(self::$allowedBases))
));
... | 'Input data "%s" does not match pattern "%s".',
$input,
self::$allowedBases[$base]
));
}
if ($checkDomain) {
$compare = gmp_init($input, $base);
if (gmp_cmp($this->minValue, $compare) > 0 || gmp_cmp($compare, $this->maxValue)... | csn_ccr |
def selenium(self):
"""Get the instance of webdriver, it starts the browser if the
webdriver is not yet instantied
:return: a `selenium instance <http://selenium-python.readthedocs.org/
api.html#module-selenium.webdriver.remote.webdriver>`
| """
if not self._web_driver:
self._web_driver = self._start_driver()
return self._web_driver | csn_ccr |
def _get_color_definitions(data):
"""Returns the list of custom color definitions for the TikZ file.
"""
definitions = []
fmt = "\\definecolor{{{}}}{{rgb}}{{" + | ",".join(3 * [data["float format"]]) + "}}"
for name, rgb in data["custom colors"].items():
definitions.append(fmt.format(name, rgb[0], rgb[1], rgb[2]))
return definitions | csn_ccr |
// NewAllocDir initializes the AllocDir struct with allocDir as base path for
// the allocation directory. | func NewAllocDir(logger hclog.Logger, allocDir string) *AllocDir {
logger = logger.Named("alloc_dir")
return &AllocDir{
AllocDir: allocDir,
SharedDir: filepath.Join(allocDir, SharedAllocName),
TaskDirs: make(map[string]*TaskDir),
logger: logger,
}
} | csn |
def create(*args)
arguments(args, required: [:user, :repo]) do
permit VALID_LABEL_INPUTS
assert_required VALID_LABEL_INPUTS
end
|
post_request("/repos/#{arguments.user}/#{arguments.repo}/labels", arguments.params)
end | csn_ccr |
def detect_type(err, install_rdf=None, xpi_package=None):
"""Determines the type of add-on being validated based on
install.rdf, file extension, and other properties."""
# The types in the install.rdf don't pair up 1:1 with the type
# system that we're using for expectations and the like. This is
#... |
if type_ in translated_types:
err.save_resource('is_multipackage', type_ == '32', pushable=True)
# Make sure we translate back to the normalized version
return translated_types[type_]
else:
err.error(('typedetection',
'detect_type',... | csn_ccr |
Return a new context dict based on original context.
The new context will be a copy of the original, and some mutable
members (such as script and css files) will also be copied to
prevent polluting shared context. | def __fix_context(context):
"""Return a new context dict based on original context.
The new context will be a copy of the original, and some mutable
members (such as script and css files) will also be copied to
prevent polluting shared context.
"""
COPY_LISTS = ('script_files', 'css_files',)
... | csn |
public static function trashedStatus(array $options = [], $withIcon = true)
{
$trans = Arr::get($options, 'trans', 'core::statuses.trashed');
$icon = Arr::get($options, 'icon', 'fa fa-fw fa-trash-o');
$attributes = [
'class' => Arr::get($options, 'class', 'label label-... | ];
return $withIcon
? static::generateWithIcon(ucfirst(trans($trans)), $icon, $attributes)
: static::generate(ucfirst(trans($trans)), $attributes);
} | csn_ccr |
Counts a single page of the specified gender. If this is the first page
of that gender on this site, a suitable key is added to the list of the
site's genders.
@param gender
the gender to count
@param siteRecord
the site record to count it for | private void countGender(EntityIdValue gender, SiteRecord siteRecord) {
Integer curValue = siteRecord.genderCounts.get(gender);
if (curValue == null) {
siteRecord.genderCounts.put(gender, 1);
} else {
siteRecord.genderCounts.put(gender, curValue + 1);
}
} | csn |
def loads(s, model):
"""
Deserialize PENMAN graphs from a string
Args:
s (str): serialized PENMAN graphs
model: Xmrs subclass instantiated from | decoded triples
Returns:
a list of objects (of class *model*)
"""
graphs = penman.loads(s, cls=XMRSCodec)
xs = [model.from_triples(g.triples()) for g in graphs]
return xs | csn_ccr |
Render a given position for category.
If some position is not defined for first category, position from its parent
category is used unless nofallback is specified.
Syntax::
{% position POSITION_NAME for CATEGORY [nofallback] %}{% endposition %}
{% position POSITION_NAME for CATEGORY using ... | def position(parser, token):
"""
Render a given position for category.
If some position is not defined for first category, position from its parent
category is used unless nofallback is specified.
Syntax::
{% position POSITION_NAME for CATEGORY [nofallback] %}{% endposition %}
{% p... | csn |
Sets the elevation of the shadow, which should be visualized by the view.
@param elevation
The elevation of the shadow, which should be set, in dp as an {@link Integer} value.
The elevation must be at least 0 and at maximum 16 | public final void setShadowElevation(final int elevation) {
Condition.INSTANCE.ensureAtLeast(elevation, 0, "The elevation must be at least 0");
Condition.INSTANCE.ensureAtMaximum(elevation, ElevationUtil.MAX_ELEVATION,
"The elevation must be at maximum " + ElevationUtil.MAX_ELEVATION);
... | csn |
A specialized version of `_.forEachRight` for arrays without support for
callback shorthands or `this` binding.
@private
@param {Array} array The array to iterate over.
@param {Function} callback The function called per iteration.
@returns {Array} Returns `array`. | function arrayEachRight(array, callback) {
var length = array ? array.length : 0;
while (length--) {
if (callback(array[length], length, array) === false) {
break;
}
}
return array;
} | csn |
def save_script_rc(script_path="scripts/scriptrc", **env_vars):
"""
Write an rc file in the charm-delivered directory containing
exported environment variables provided by env_vars. Any charm scripts run
outside the juju hook environment can source this scriptrc to obtain
updated config information ... | os.mkdir(os.path.dirname(juju_rc_path))
with open(juju_rc_path, 'wt') as rc_script:
rc_script.write(
"#!/bin/bash\n")
[rc_script.write('export %s=%s\n' % (u, p))
for u, p in six.iteritems(env_vars) if u != "script_path"] | csn_ccr |
Helper to render a list of dictionaries as an HTML display object. | def _render_table(data, fields=None):
""" Helper to render a list of dictionaries as an HTML display object. """
return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields)) | csn |
Alters the identifiers that have been provided to the definition.
This is an advanced method and should not be used unless really needed.
It allows the developer to slightly alter the definition without having to re-establish the cache.
It will cause more processing as the definition will need to clear and reprepare s... | public function set_identifiers(array $identifiers) {
if ($this->definition->set_identifiers($identifiers)) {
// As static acceleration uses input keys and not parsed keys
// it much be cleared when the identifier set is changed.
$this->staticaccelerationarray = array();
... | csn |
Returns an instance of MarantzDenonTelnet that can handle telnet commands to the given IP.
@constructor
@param {string} ip Address of the AVR. | function(ip) {
this.connectionparams = {
host: ip,
port: 23,
timeout: 1000, // The RESPONSE should be sent within 200ms of receiving the request COMMAND. (plus network delay)
sendTimeout: 1200,
negotiationMandatory: false,
ors: '\r', // Set outbound record separator
... | csn |
async def send_request(self, method, args=()):
'''Send an RPC request over the network.'''
message, | event = self.connection.send_request(Request(method, args))
return await self._send_concurrent(message, event, 1) | csn_ccr |
public function findAllByUserId( $userId )
{
$platform = $this->getDbAdapter()
->getPlatform();
/* @var $from \Zork\Db\Sql\TableIdentifier */
$from = $this->getTableInSchema( 'user_right_x_user' );
if ( $from instanceof TableIdentifier )
{
... | new Expression( $platform->quoteIdentifier( 'id' ) . ' IN (
SELECT ' . $platform->quoteIdentifier( 'rightId' ) . '
FROM ' . $platform->quoteIdentifierChain( $from ) . '
WHERE ' . $platform->quoteIdentifier( 'userId' ) . ' = ?
)', $userId ),
)... | csn_ccr |
// Reset - reset internal state | func (a *DictAcceptor) Reset(p int) {
a.p = p
a.final = false
a.offset = 0
a.valid = true
} | csn |
def run_py(self, cmd, cwd=os.curdir):
"""Run a python command in the enviornment context.
:param cmd: A command to run in the environment - runs with `python -c`
:type cmd: str or list
:param str cwd: The working directory in which to execute the command, defaults to :data:`os.curdir`
... |
:rtype: :class:`~subprocess.Popen`
"""
c = None
if isinstance(cmd, six.string_types):
script = vistir.cmdparse.Script.parse("{0} -c {1}".format(self.python, cmd))
else:
script = vistir.cmdparse.Script.parse([self.python, "-c"] + list(cmd))
with s... | csn_ccr |
def _transform_params(self, **params):
"""Applies all transforms to the given params.
Parameters
----------
\**params :
Key, value pairs of parameters to apply the transforms to.
Returns
-------
dict
A dictionary of the transformed parame... | params = transforms.apply_transforms(params,
self.waveform_transforms,
inverse=False)
# apply boundary conditions
params = self.prior_distribution.apply_boundary_conditions(**params)
return p... | csn_ccr |
public function getAuctionApi()
{
if (!$this->apis->has('auction')) {
| $this->apis->set('auction', new Auction($this));
}
return $this->apis->get('auction');
} | csn_ccr |
Edits a language
@param {stdClass} $data Data passed from ActionScript
@return {array} Returns a standard response array | public function editLanguage($data) {
$response=CodeBank_ClientAPI::responseBase();
try {
if(SnippetLanguage::get()->filter('Name:nocase', Convert::raw2sql($data->language))->Count()>0) {
$response['status']='EROR';
$response['message']=_t('CodeBankAP... | csn |
Gets the metadata for the distribute alterations rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.* | def get_distribute_alterations_metadata(self):
"""Gets the metadata for the distribute alterations rights flag.
return: (osid.Metadata) - metadata for the distribution rights
fields
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented fr... | csn |
public static function withLanguage(\Closure $callback, $config = [])
{
if (\App::runningUnitTests()) {
$locale = \App::getLocale();
} else {
$locale = request()->segment(1);
}
if (strlen($locale) | <= 2) {
Route::group(['prefix' => $locale, 'middleware' => 'lang'], function () use ($callback) {
$callback();
});
}
} | csn_ccr |
def max_sequence_depth(comma_sequence, current_depth)
# Sequence contains interpolation; assume a depth of 1
return current_depth + 1 unless comma_sequence
| comma_sequence.members.map { |sequence| sequence_depth(sequence, current_depth) }.max
end | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.