query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
func (b UpdateMap) Put(ns, coll, key string, value []byte, version *version.Height) {
b.PutValAndMetadata(ns, coll, key, value, nil, version) }
csn_ccr
python make an array of datetime
def get_dt_list(fn_list): """Get list of datetime objects, extracted from a filename """ dt_list = np.array([fn_getdatetime(fn) for fn in fn_list]) return dt_list
cosqa
function _shouldGetFromCache(fileInfo) { var result = new $.Deferred(), isChanged = _changedDocumentTracker.isPathChanged(fileInfo.fullPath); if (isChanged && fileInfo.JSUtils) { // See if it's dirty and in the working set first var doc = DocumentManager.getOpenDocum...
if (!err) { result.resolve(fileInfo.JSUtils.timestamp.getTime() === stat.mtime.getTime()); } else { result.reject(err); } }); } } else { // Use the cache if the file d...
csn_ccr
def _setConfig(self, num, value, device, message): """ Low level method used for all set config commands. :Parameters: num : `int` Number that indicates the config option to get from the hardware. value : `int` The value to set in the hardware device....
result = self._serial.read(size=1) result = ord(result) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_info=True) raise e except TypeError as e: result = None if result is not None and message: ...
csn_ccr
Creates a flash element. @param string $src The swf file source @param null|int $width Width attribute @param null|int $height Height attribute @return string
public static function flash($src, $width = null, $height = null) { $code = self::element('object', [ 'width' => $width ?: 600, 'height' => $height ?: 400, 'classid' => 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000', 'codebase' => 'http://download.macromedia.com...
csn
python random sample based on pmf
def SampleSum(dists, n): """Draws a sample of sums from a list of distributions. dists: sequence of Pmf or Cdf objects n: sample size returns: new Pmf of sums """ pmf = MakePmfFromList(RandomSum(dists) for i in xrange(n)) return pmf
cosqa
def render(self, data, accepted_media_type=None, renderer_context=None): """ Render `data` into JSON, returning a bytestring. """ if data is None: return bytes() renderer_context = renderer_context or {} indent = self.get_indent(accepted_media_type, renderer_...
# and may (or may not) be unicode. # On python 3.x json.dumps() returns unicode strings. if isinstance(ret, six.text_type): # We always fully escape \u2028 and \u2029 to ensure we output JSON # that is a strict javascript subset. If bytes were returned # by json.du...
csn_ccr
public final FFDCLogger append(String info) { lines.add(new
StringBuffer().append(info).append(AdapterUtil.EOLN).toString()); return this; }
csn_ccr
Display a list of resume. @return Response
public function index(ResumeRequest $request) { $view = $this->response->theme->listView(); if ($this->response->typeIs('json')) { $function = camel_case('get-' . $view); return $this->repository ->setPresenter(\Litecms\Career\Repositories\Presenter\ResumePre...
csn
python invert a dict
def inverted_dict(d): """Return a dict with swapped keys and values >>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0} True """ return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d)))
cosqa
Induce a sub-graph from all of the upstream causal entities of the nodes in the nbunch. :type graph: pybel.BELGraph :rtype: pybel.BELGraph
def get_upstream_causal_subgraph(graph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]): """Induce a sub-graph from all of the upstream causal entities of the nodes in the nbunch. :type graph: pybel.BELGraph :rtype: pybel.BELGraph """ return get_subgraph_by_edge_filter(graph, build_upstream_edge_p...
csn
public void clearResponseSettings(int pathId, String clientUUID) throws Exception { logger.info("clearing response settings"); this.setResponseEnabled(pathId, false, clientUUID);
OverrideService.getInstance().disableAllOverrides(pathId, clientUUID, Constants.OVERRIDE_TYPE_RESPONSE); EditService.getInstance().updateRepeatNumber(Constants.OVERRIDE_TYPE_RESPONSE, pathId, clientUUID); }
csn_ccr
public function load(IPost $post) { $this->template->set('title', $post->getTitle()); $this->template->set('meta_title', $post->metaTitle());
$this->template->set('meta_keywords', $post->metaKeywords()); $this->template->set('meta_description', $post->metaDescription()); }
csn_ccr
protected function handle(Connection $connection, $request) { $this->loadSession($connection);
return $this->Kernel->handle($request); }
csn_ccr
func NewTfaChangeBackupPhoneType(Description string) *TfaChangeBackupPhoneType { s :=
new(TfaChangeBackupPhoneType) s.Description = Description return s }
csn_ccr
Log a message in the syslog. @param string $pMessage @return null|string
public static function log($pMessage) { if (is_array($pMessage) or is_object($pMessage)) { $message = json_encode($pMessage); } else { $message = (string)$pMessage; } $logId = mt_rand(); if (Agl::isInitialized()) { $message = '[agl_' . $l...
csn
public function listServiceTypeData() { if (!isset($this->serviceTypesData)) { $this->serviceTypesData
= $this->environment->getStorage()->retrieve('service_tag_types'); } return $this->serviceTypesData; }
csn_ccr
public static responderpolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{ responderpolicylabel_policybinding_binding obj = new responderpolicylabel_policybinding_binding(); obj.set_labelname(labelname);
responderpolicylabel_policybinding_binding response[] = (responderpolicylabel_policybinding_binding[]) obj.get_resources(service); return response; }
csn_ccr
def save_mets(self): """ Write out the current state of the METS file. """ log.info("Saving mets '%s'" % self.mets_target) if self.automatic_backup:
WorkspaceBackupManager(self).add() with open(self.mets_target, 'wb') as f: f.write(self.mets.to_xml(xmllint=True))
csn_ccr
creates keys with detailed regis. information
def data_filler_detailed_registration(self, number_of_rows, pipe): '''creates keys with detailed regis. information ''' try: for i in range(number_of_rows): pipe.hmset('detailed_registration:%s' % i, { 'id': rnd_id_generator(self), ...
csn
Return whether the batch of requests in the PRE-PREPARE can proceed to the PREPARE step. :param ppReq: any object with identifier and requestId attributes
def canPrepare(self, ppReq) -> (bool, str): """ Return whether the batch of requests in the PRE-PREPARE can proceed to the PREPARE step. :param ppReq: any object with identifier and requestId attributes """ if self.has_sent_prepare(ppReq): return False, 'has ...
csn
Flatten results from a sequence of parslets. @api private
def flatten_sequence(list) foldl(list.compact) { |r, e| # and then merge flat elements merge_fold(r, e) } end
csn
Gets the sequence of SQL statements that need to be performed in order to bring the given class mappings in-synch with the relational schema. @param ClassMetadata[] $classes The classes to consider. @param bool $saveMode If TRUE, only generates SQL for a partial update that does not include SQL for droppin...
public function getUpdateSchemaSql(array $classes, $saveMode = false) { $sm = $this->em->getConnection()->getSchemaManager(); $fromSchema = $sm->createSchema(); $toSchema = $this->getSchemaFromMetadata($classes); $comparator = new Comparator(); $schemaDiff = $comparator->...
csn
function() { var C = this; var l = arguments.length; if (l > 0) { var args = new Array(l); for (var i = 0; i < l; i++) { args[i] = arguments[i];
} this._initProperties(args); } return new C(); }
csn_ccr
public function primary($columns, $name = null) { $this->addCachePrimary($columns);
return parent::primary($columns, $name); }
csn_ccr
def can_refresh?(other) mrrt? && (authority == other.authority) &&
(user_info == other.user_info) && (client_id == other.client_id) end
csn_ccr
public Set<Auth> createAuthsFromString(String authInfo) { if ("".equals(authInfo) || authInfo == null) return Collections.emptySet(); String[] parts = authInfo.split(","); final Set<Auth> auths = new HashSet<Auth>(); try { for (String auth : parts) { StringTokenizer tokenizer = new St...
(NoSuchElementException e) { final StringBuilder b = new StringBuilder(); for (String auth : parts) { b.append(auth); } throw new IllegalArgumentException( "Auth configuration is configured wrongly:" + b.toString(), e); } }
csn_ccr
def name(self): """The final path component, if any.""" parts = self._parts
if len(parts) == (1 if (self._drv or self._root) else 0): return '' return parts[-1]
csn_ccr
Writes data to some existing byte array starting from specific offset @param target byte array destination @param targetOffset destination offset to start @return length of source (written) data @throws IOException
public int toByteArray(byte[] target, int targetOffset) throws IOException { long length = length(); if ((long)targetOffset + length > Integer.MAX_VALUE) { throw new IOException("Unable to write - too big data"); } if (target.length < targetOffset + length) { thro...
csn
// RegisterStorage registers a new storage backend with the registry.
func RegisterStorage(id StorageBackend, name string, loader StorageLoader) { storageRegistry[id] = loader storageNameToBackendMap[name] = id storageBackendToNameMap[id] = name }
csn
Returns all defined permissions not related to junction tables. Excludes permissions related to applications & plugins that are disabled. @param string $LimitToSuffix An optional suffix to limit the permission names to. @return DataSet
public function GetPermissions($RoleID, $LimitToSuffix = '') { //$Namespaces = $this->GetAllowedPermissionNamespaces(); //$NamespaceCount = count($Namespaces); $Result = array(); $GlobalPermissions = $this->GetGlobalPermissions($RoleID, $LimitToSuffix); $Result[] = $GlobalPer...
csn
Returns a shape based on `self` with at least the given rank. Args: rank: An integer. Returns: A shape that is at least as specific as `self` with at least the given rank. Raises: ValueError: If `self` does not represent a shape with at least the given ...
def with_rank_at_least(self, rank): """Returns a shape based on `self` with at least the given rank. Args: rank: An integer. Returns: A shape that is at least as specific as `self` with at least the given rank. Raises: ValueError: If `self` does...
csn
Copy one Gradient into another. @param g the Gradient to copy into
public void copyTo(Gradient g) { g.numKnots = numKnots; g.map = (int[])map.clone(); g.xKnots = (int[])xKnots.clone(); g.yKnots = (int[])yKnots.clone(); g.knotTypes = (byte[])knotTypes.clone(); }
csn
Update the listener to listen for changes to no records. @param strKeyName The (optional) key area the query is being of. @param objKeyData The (optional) reference value of the key area.
public void clearBookmarkFilters(String strKeyName, Object objKeyData) { Map<String,Object> properties = new Hashtable<String,Object>(); properties.put(GridRecordMessageFilter.ADD_BOOKMARK, GridRecordMessageFilter.CLEAR_BOOKMARKS); if (objKeyData != null) { properties.put...
csn
def init_repo(path): """clone the gh-pages repo if we haven't already.""" sh("git clone %s %s"%(pages_repo, path))
here = os.getcwd() cd(path) sh('git checkout gh-pages') cd(here)
csn_ccr
Returns configured REDIS dictionary from REDIS_URL.
def config(env=DEFAULT_ENV, default=None, **overrides): """Returns configured REDIS dictionary from REDIS_URL.""" config = {} s = os.environ.get(env, default) if s: config = parse(s) overrides = dict([(k.upper(), v) for k, v in overrides.items()]) config.update(overrides) retur...
csn
def from_yaml(cls, yaml_str=None, str_or_buffer=None): """ Create a SegmentedRegressionModel instance from a saved YAML configuration. Arguments are mutally exclusive. Parameters ---------- yaml_str : str, optional A YAML string from which to load model. ...
default_ytransform = cfg['default_config']['ytransform'] seg = cls( cfg['segmentation_col'], cfg['fit_filters'], cfg['predict_filters'], default_model_expr, YTRANSFORM_MAPPING[default_ytransform], cfg['min_segment_size'], cfg['name']) if "models" not in...
csn_ccr
func (s *DescribeAlgorithmOutput) SetAlgorithmStatusDetails(v *AlgorithmStatusDetails)
*DescribeAlgorithmOutput { s.AlgorithmStatusDetails = v return s }
csn_ccr
def play_NoteContainer(self, nc, channel=1, velocity=100): """Play the Notes in the NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel': channel, 'velocity': velocity}) if nc is None:
return True for note in nc: if not self.play_Note(note, channel, velocity): return False return True
csn_ccr
Encodes this MarketHistoryList instance to a JSON string. :param MarketHistoryList history_list: The history instance to serialize. :rtype: str
def encode_to_json(history_list): """ Encodes this MarketHistoryList instance to a JSON string. :param MarketHistoryList history_list: The history instance to serialize. :rtype: str """ rowsets = [] for items_in_region_list in history_list._history.values(): region_id = items_in_reg...
csn
func getIntelRdtParamString(path, file string) (string, error) { contents, err := ioutil.ReadFile(filepath.Join(path, file)) if err != nil {
return "", err } return strings.TrimSpace(string(contents)), nil }
csn_ccr
func (r rsStream) Join(dst io.Writer, shards []io.Reader, outSize int64) error { // Do we have enough shards? if len(shards) < r.r.DataShards { return ErrTooFewShards } // Trim off parity shards if any shards = shards[:r.r.DataShards] for i := range shards { if shards[i] == nil { return StreamReadError{Er...
// Copy data to dst n, err := io.CopyN(dst, src, outSize) if err == io.EOF { return ErrShortData } if err != nil { return err } if n != outSize { return ErrShortData } return nil }
csn_ccr
def make_data_iter_plan(self): "make a random data iteration plan" # truncate each bucket into multiple of batch-size bucket_n_batches = [] for i in range(len(self.data)): bucket_n_batches.append(np.floor((self.data[i]) / self.batch_size)) self.data[i] = self.data...
self.bucket_idx_all = bucket_idx_all self.bucket_curr_idx = [0 for x in self.data] self.data_buffer = [] self.label_buffer = [] for i_bucket in range(len(self.data)): if not self.model_parallel: data = np.zeros((self.batch_size, self.buckets[i_bucket])) ...
csn_ccr
func (api *Client) Debugf(format string, v ...interface{})
{ if api.debug { api.log.Output(2, fmt.Sprintf(format, v...)) } }
csn_ccr
def ensure_not_in_dest dest_pathname = Pathname.new(dest) Pathname.new(source).ascend do |path| if path == dest_pathname raise( Errors::FatalException,
"Destination directory cannot be or contain the Source directory." ) end end end
csn_ccr
// State returns the state of the stream.
func (s *Stream) State() State { s.l.Lock() defer s.l.Unlock() return s.state }
csn
protected function setEnabled(array $enabled) { $enabled = array_values(array_unique($enabled));
$this->config->set('extensions_enabled', json_encode($enabled)); }
csn_ccr
func (c *OpenChannel) ApplyChanStatus(status ChannelStatus) error { c.Lock()
defer c.Unlock() return c.putChanStatus(status) }
csn_ccr
def init(name, runtime): """Create a new Django app.""" runtime = click.unstyle(runtime) stdout.write( style.format_command( 'Initializing', '%s %s %s' % (name, style.gray('@'), style.green(runtime)) ) ) config = Config(os.getcwd())
config.set('runtime', runtime) config.save() generate.main(['init', name], standalone_mode=False) run.main(['python', 'manage.py', 'migrate'])
csn_ccr
def _EnforceProcessMemoryLimit(self, memory_limit): """Enforces a process memory limit. Args: memory_limit (int): maximum number of bytes the process is allowed to allocate, where 0 represents no limit and None a default of 4 GiB. """ # Resource is not supported on Windows.
if resource: if memory_limit is None: memory_limit = 4 * 1024 * 1024 * 1024 elif memory_limit == 0: memory_limit = resource.RLIM_INFINITY resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))
csn_ccr
Given an array nums of 0s and 1s and an integer k, return True if all 1's are at least k places away from each other, otherwise return False.   Example 1: Input: nums = [1,0,0,0,1,0,0,1], k = 2 Output: true Explanation: Each of the 1s are at least 2 places away from each other. Example 2: Input: nums = [1,0,0,1,0,1]...
class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: if nums.count(0) == len(nums): return True idx = nums.index(1) ctr = 0 for num in nums[idx+1:]: if num == 1: if ctr < k: return False...
apps
Checks if the system is in uefi boot mode. :return: 'True' if the boot mode is uefi else 'False'
def _is_boot_mode_uefi(self): """Checks if the system is in uefi boot mode. :return: 'True' if the boot mode is uefi else 'False' """ boot_mode = self.get_current_boot_mode() return (boot_mode == BOOT_MODE_MAP.get(sys_cons.BIOS_BOOT_MODE_UEFI))
csn
Open an help message in the user's browser :param message: An optional message object to display in the dialog. :type message: Message.Message
def show_help(message=None): """Open an help message in the user's browser :param message: An optional message object to display in the dialog. :type message: Message.Message """ help_path = mktemp('.html') with open(help_path, 'wb+') as f: help_html = get_help_html(message) f....
csn
If this tree is an identifier or a field or a parameterized type, return its name, otherwise return null.
public static Name name(JCTree tree) { switch (tree.getTag()) { case IDENT: return ((JCIdent) tree).name; case SELECT: return ((JCFieldAccess) tree).name; case TYPEAPPLY: return name(((JCTypeApply) tree).clazz); default: return null...
csn
private static void parseErrorPages(final ErrorPageType errorPageType, final WebApp webApp) { final WebAppErrorPage errorPage = new WebAppErrorPage(); if (errorPageType.getErrorCode() != null) { errorPage.setErrorCode(errorPageType.getErrorCode().getValue().toString()); } if (errorPageType.getExceptionT...
{ errorPage.setLocation(errorPageType.getLocation().getValue()); } if (errorPage.getErrorCode() == null && errorPage.getExceptionType() == null) { errorPage.setExceptionType(ErrorPageModel.ERROR_PAGE); } webApp.addErrorPage(errorPage); }
csn_ccr
protected function addConsumer(ArrayNodeDefinition $node) { $consumerChildren = $node ->children() ->arrayNode('consumer') ->addDefaultsIfNotSet() ->children(); $general = $consumerChildren
->arrayNode('general'); $this->addGeneralConsumerConfiguration($general); $individualPrototype = $consumerChildren ->arrayNode('individual') ->useAttributeAsKey('consumer') ->prototype('array'); ...
csn_ccr
protected function hydrateResponseFromCurl(Response $response, Curl $curl) { $headerSize = $curl->getInfo(CURLINFO_HEADER_SIZE); $rawContent = $this->multiCurl->getContent($curl); $response->setStatusCode($curl->getInfo(CURLINFO_HTTP_CODE))
->setContent(substr($rawContent, $headerSize)); $this->parseResponseHeaders($response, substr($rawContent, 0, $headerSize)); return $this; }
csn_ccr
def unsubscribe(self, socket_id, channel): """Unsubscribes a socket from a channel.""" con = self._get_connection(socket_id, create=False)
if con is not None: con.subscriptions.discard(channel) try: self.subscriptions[channel].discard(socket_id) except KeyError: pass
csn_ccr
function stop(next) { if (phantomProcess) { seleniumServerProcess.on('close', function (code, signal) { // this should really resolve both callbacks rather than guessing phantom wrapper will terminate instantly if (typeof next === 'function' && !seleniumServerProcess ) { ...
end cleanly, can do killall -9 java if getting startup errors phantomProcess.kill('SIGTERM'); started = false; starting = false; } if (seleniumServerProcess) { seleniumServerProcess.on('close', function (code, signal) { if (typeof next === 'function' ) { ...
csn_ccr
public static void killProcess(String pid) { synchronized (lock) { LOG.info("Begin to kill process " + pid); WorkerShutdown shutdownHandle = getProcessHandle(pid); if (shutdownHandle != null) {
shutdownHandle.shutdown(); } processMap.remove(pid); LOG.info("Successfully killed process " + pid); } }
csn_ccr
def detect_intent_with_model_selection(project_id, session_id, audio_file_path, language_code): """Returns the result of detect intent with model selection on an audio file as input Using the same `session_id` between requests allows continuation of the conversaio...
language_code=language_code, sample_rate_hertz=sample_rate_hertz, model=model) query_input = dialogflow.types.QueryInput(audio_config=audio_config) response = session_client.detect_intent( session=session_path, query_input=query_input, input_audio=input_audio) print('=' * ...
csn_ccr
func (s *Schema) Register(t GraphQLType) { typeInfo := t.GraphQLTypeInfo() s.registeredTypes[t.GraphQLTypeInfo().Name] = typeInfo // TODO(tmc): collision handling for
name, fieldSpec := range typeInfo.Fields { if fieldSpec.IsRoot { s.rootFields[name] = fieldSpec } } }
csn_ccr
Start a queue consumer This method asks the server to start a "consumer", which is a transient request for messages from a specific queue. Consumers last as long as the channel they were created on, or until the client cancels them. RULE: The server SHOULD support ...
def basic_consume(self, queue='', consumer_tag='', no_local=False, no_ack=False, exclusive=False, nowait=False, callback=None, arguments=None, on_cancel=None): """Start a queue consumer This method asks the server to start a "consumer", which is a tra...
csn
Raw linear combination.
def _lincomb(self, a, x1, b, x2, out): """Raw linear combination.""" self.tspace._lincomb(a, x1.tensor, b, x2.tensor, out.tensor)
csn
Stop metrics & send finish metric event. @param {Context} ctx @param {Error} error @private
function metricFinish(ctx, error) { if (ctx.startHrTime) { let diff = process.hrtime(ctx.startHrTime); ctx.duration = (diff[0] * 1e3) + (diff[1] / 1e6); // milliseconds } ctx.stopTime = ctx.startTime + ctx.duration; if (ctx.metrics) { const payload = generateMetricPayload(ctx); payload.endTime = ctx.stopTi...
csn
def tail(file_path, lines=10, encoding="utf-8", printed=True, errors='strict'): """ A really silly way to get the last N lines, defaults to 10. :param file_path: Path to file to read :param lines: Number of lines to read in :param encoding: defaults to utf-8 to decode as, will fail on bin...
if python_version >= (2, 7): data.append(line.decode(encoding, errors=errors)) else: data.append(line.decode(encoding)) if len(data) > lines: data.popleft() if printed: print("".join(data)) else: return data
csn_ccr
def run_operation_with_response( self, sock_info, operation, set_slave_okay, listeners, exhaust, unpack_res): """Run a _Query or _GetMore operation and return a Response object. This method is used only to run _Query/_G...
/ getMore / explain command response # format. if use_cmd: res = docs[0] elif operation.name == "explain": res = docs[0] if docs else {} else: res = {"cursor": {"id": reply.cursor_id, "ns":...
csn_ccr
Returns a filename that is safer to use on the filesystem. The filename will not contain a slash (nor the path separator for the current platform, if different), it will not start with a dot, and it will have the expected extension. No guarantees that makes it "safe enough". No...
def filename_sanitized(self, extension, default_filename='file'): """Returns a filename that is safer to use on the filesystem. The filename will not contain a slash (nor the path separator for the current platform, if different), it will not start with a dot, and it will have the expec...
csn
To pull session data @param string $name @param string $value @return mixed
public function pull($name, $value = '') { $value = $this->get($name, $value); $this->delete($name); return $value; }
csn
public void join() { try { UnicastRemoteObject.unexportObject(registry, true); /* * NOTE: javaRunner.waitForExit() works for Equinox and Felix, but not for Knopflerfish,
* need to investigate why. OTOH, it may be better to kill the process as we're doing * now, just to be on the safe side. */ javaRunner.shutdown(); } catch (NoSuchObjectException exc) { throw new TestContainerException(exc); } }
csn_ccr
public function active() { $stats = $this->root()->stats(); return
$this->root()->focused() ? $stats['focused'] : $stats['normal']; }
csn_ccr
function(p) { var self = this; if (!p) return; if (!p.parent) return; //console.log("zoom out p.value = " + p.parent.value);
//console.log("zoom out p.name = " + p.parent.name); //console.log(p.parent); self.updateExplanation(p.parent.sum, p.parent.name); self.zoom(p.parent, p); }
csn_ccr
public void fill(View view) { validateNotNullableView(view); try { if(view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for(int i = 0; i < viewGroup.getChildCount(); i++) { View child = viewGroup.getChildAt(i); ...
null) { fillView(view); } else if(mIds.contains(view.getId())) { fillView(view); } } } catch (Exception e) { e.printStackTrace(); } finally { mFaker = null; } }
csn_ccr
def flat_map(&block) raise Erlang::ImproperListError if improper? return enum_for(:flat_map) unless block_given? return self if empty? out = tail = Erlang::Cons.allocate list = self until list.empty? head_list = Erlang::List.from_enum(yield(list.head)) if head_list.em...
tail.instance_variable_set(:@tail, head_list.tail + new_node) tail.immutable! list = list.tail tail = new_node end end if not tail.immutable? tail.instance_variable_set(:@tail, Erlang::Nil) tail.immutable! end if out === tail and not...
csn_ccr
func (t *DatacentersTable) fetch(c context.Context) error { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, name, description, state FROM datacenters `) if err != nil { return errors.Annotate(err, "failed to select datacenters").Err() } defer rows.Close() for rows.Next() { dc := &Datac...
if err := rows.Scan(&dc.Id, &dc.Name, &dc.Description, &dc.State); err != nil { return errors.Annotate(err, "failed to scan datacenter").Err() } t.current = append(t.current, dc) } return nil }
csn_ccr
Return information about failed tasks.
def error_info(): """Return information about failed tasks.""" worker = global_worker worker.check_connected() return (global_state.error_messages(driver_id=worker.task_driver_id) + global_state.error_messages(driver_id=DriverID.nil()))
csn
protected function createSortTransformFunction() { $propertyMap = $this->propertyMap; $propertyExtractor = $this->getPropertyExtractor(); $valueChecker = $this->getValueChecker(); return function($a, $b) use ($propertyMap, $propertyExtractor, $valueChecker){ foreach($pr...
$cmp ComparatorInterface */ $valueChecker($valueA, $valueB, $cmp); $result = $cmp->compare($valueA, $valueB); if($result != 0){ return $result * $property['direction']; } } return 0; }; }
csn_ccr
Overwrites the original method to filter the language extension from basename
def process(name) self.ext = File.extname(name) self.basename = name[0 .. -self.ext.length-1]. sub(Localization::LANG_END_RE, '') end
csn
function introspect (text) { return new Promise(function (resolve, reject) { try { var astDocument = parse(text) var schema = buildASTSchema(astDocument) graphql(schema, graphqlviz.query) .then(function (data) { resolve(data) })
.catch(function (e) { reject('Fatal error, exiting.') fatal(e, text) }) } catch (e) { reject('Fatal error, exiting.') fatal(e, text) } }) }
csn_ccr
Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR CreateApplication request body :rtype: dict
def _create_application_request(app_metadata, template): """ Construct the request body to create application. :param app_metadata: Object containing app metadata :type app_metadata: ApplicationMetadata :param template: A packaged YAML or JSON SAM template :type template: str :return: SAR C...
csn
public function quickResetCache() { $tables = [ 'groupex_form_cache', 'groupex_form_cache__field_gfc_created', 'groupex_form_cache__field_gfc_options', 'groupex_form_cache__field_gfc_response', ]; foreach
($tables as $table) { db_truncate($table)->execute(); } $this->logger->info('GroupEx Pro Form Cache has been quickly erased using "TRUNCATE".'); }
csn_ccr
Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
def serialize(self): """Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed. """ converted_dict = { 'success': self.success, ...
csn
private ByteBuffer _read(long offset, long length, ByteBuffer buffer) throws IOException { if (offset + length > this.length) { throw new IllegalArgumentException("Piece#" + this.index + " overrun (" + offset + " + " + length + " > " + this.length + ") !"); } // TODO: remo...
int when large ByteBuffer support is // implemented in Java. int position = buffer.position(); byte[] bytes = this.pieceStorage.readPiecePart(this.index, (int)offset, (int)length); buffer.put(bytes); buffer.rewind(); buffer.limit(bytes.length + position); return buffer; }
csn_ccr
Returns friendly error message explaining how to fix permissions @param string $path to the directory missing permissions @return string Error message
public static function getErrorMessageMissingPermissions($path) { $message = "Please check that the web server has enough permission to write to these files/directories:<br />"; if (SettingsServer::isWindows()) { $message .= "On Windows, check that the folder is not read only and is wri...
csn
Chef is frustrated in this lockown. So to overcome this he plans to travel various mountains. He is very strange so he sets some conditions for $each$ Type 2 query(mentioned below) (i.e. $1$ $i$) : - Let Chef has travelled till $ith$ mountain from left to right. - He does not like to travel the mountain with the heigh...
# cook your dish here from bisect import bisect_left def BinarySearch(a, x): i = bisect_left(a, x) if i != len(a) and a[i] == x: return i else: return -1 for _t in range(int(input())): _n, q = list(map(int, input().split())) mounts = list(map(int, input().split())) for _q in range(q): query = list(...
apps
Method which kick start the consumer process thread
def start channel.prefetch(10) queue.subscribe(manual_ack: true, exclusive: false) do |delivery_info, metadata, payload| begin body = JSON.parse(payload).with_indifferent_access status = run(body) rescue => e status = :error end if status == :ok...
csn
Read discrete trajectory from ascii file. The ascii file containing a single column with integer entries is read into an array of integers. Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the ...
def read_discrete_trajectory(filename): """Read discrete trajectory from ascii file. The ascii file containing a single column with integer entries is read into an array of integers. Parameters ---------- filename : str The filename of the discrete state trajectory file. The fi...
csn
def _check_valid_udunits(self, ds, variable_name): ''' Checks that the variable's units are contained in UDUnits :param netCDF4.Dataset ds: An open netCDF dataset :param str variable_name: Name of the variable to be checked ''' variable = ds.variables[variable_name] ...
std_name_units_dimensionless = cfutil.is_dimensionless_standard_name(self._std_names._root, standard_name) # If the variable is supposed to be dimensionless, it automatically passes should_be_dimensionless = (variable.dtype.char == 'S' or ...
csn_ccr
func (s *ShapeIndexCell) numEdges() int { var e int for _, cs := range s.shapes {
e += cs.numEdges() } return e }
csn_ccr
create a function to generate random letters in python
def random_letters(n): """ Generate a random string from a-zA-Z :param n: length of the string :return: the random string """ return ''.join(random.SystemRandom().choice(string.ascii_letters) for _ in range(n))
cosqa
func NewEndpointsInformer(client kubernetes.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredEndpointsInformer(client, namespace, resyncPeriod, indexers, nil) }
csn_ccr
Write data blocks to unencrypted services. This method sends a Write Without Encryption command to the tag. The data blocks to overwrite are indicated by a sequence of :class:`~nfc.tag.tt3.BlockCode` objects in the parameter *block_list*. Each block code must reference one of the ...
def write_without_encryption(self, service_list, block_list, data): """Write data blocks to unencrypted services. This method sends a Write Without Encryption command to the tag. The data blocks to overwrite are indicated by a sequence of :class:`~nfc.tag.tt3.BlockCode` objects in the p...
csn
function _in_list(in_item, list, comparator){ var retval = false; for(var li = 0; li < list.length; li++ ){ var list_item = list[li]; if( comparator ){ var comp_op = comparator(in_item, list_item); if( comp_op && comp_op == true ){
retval = true; } }else{ if( in_item == list_item ){ retval = true; } } } return retval; }
csn_ccr
python change plural to singular
def singularize(word): """ Return the singular form of a word, the reverse of :func:`pluralize`. Examples:: >>> singularize("posts") "post" >>> singularize("octopi") "octopus" >>> singularize("sheep") "sheep" >>> singularize("word") "word" ...
cosqa
public boolean startSession() { synchronized (sharedLock) { SessionData session = loadSession(); if (isSessionActive(session)) { sharedLock.notifyAll(); return false;
} else { clearAll(); } sharedLock.notifyAll(); } return true; }
csn_ccr
func (k *KBPKIClient) CreateTeamTLF( ctx context.Context, teamID keybase1.TeamID, tlfID tlf.ID) error {
return k.serviceOwner.KeybaseService().CreateTeamTLF(ctx, teamID, tlfID) }
csn_ccr
Copy a file to a given path from a given path, if it does not exist. After copying it, verify it integrity by checking the SHA-256 hash. Parameters ---------- path: str The (destination) path of the file on the local filesystem source_path: str The path from which to copy the file ...
def copy_and_verify(path, source_path, sha256): """ Copy a file to a given path from a given path, if it does not exist. After copying it, verify it integrity by checking the SHA-256 hash. Parameters ---------- path: str The (destination) path of the file on the local filesystem sou...
csn
func (scope *Scope) Raw(sql string) *Scope {
scope.SQL = strings.Replace(sql, "$$$", "?", -1) return scope }
csn_ccr
Delete an Arctic Library, and all associated collections in the MongoDB. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library'
def delete_library(self, library): """ Delete an Arctic Library, and all associated collections in the MongoDB. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' """ lib = ArcticLibraryBinding(self, librar...
csn
Print bug in one-line format. @param bugInstance the bug to print
protected void printBug(BugInstance bugInstance) { if (showRank) { int rank = BugRanker.findRank(bugInstance); outputStream.printf("%2d ", rank); } switch (bugInstance.getPriority()) { case Priorities.EXP_PRIORITY: outputStream.print("E "); ...
csn