query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
Main body of `vertex_enumeration_gen`. Parameters ---------- labelings_bits_tup : tuple(ndarray(np.uint64, ndim=1)) Tuple of ndarrays of integers representing labelings of the vertices of the best response polytopes. equations_tup : tuple(ndarray(float, ndim=2)) Tuple of ndarra...
def _vertex_enumeration_gen(labelings_bits_tup, equations_tup, trans_recips): """ Main body of `vertex_enumeration_gen`. Parameters ---------- labelings_bits_tup : tuple(ndarray(np.uint64, ndim=1)) Tuple of ndarrays of integers representing labelings of the vertices of the best resp...
csn
Remove the entry data of this field from the database. @param integer|array $entry_id the ID of the entry, or an array of entry ID's to delete. @param array $data (optional) The entry data provided for fields to do additional cleanup This is an optional argument and defaults to null. @throws DatabaseException @return ...
public function entryDataCleanup($entry_id, $data = null) { $where = is_array($entry_id) ? " `entry_id` IN (" . implode(',', $entry_id) . ") " : " `entry_id` = '$entry_id' "; Symphony::Database()->delete('tbl_entries_data_' . $this->get('id'), $where); return true; ...
csn
// SetCustomHeaders sets the CustomHeaders field's value.
func (s *Origin) SetCustomHeaders(v *CustomHeaders) *Origin { s.CustomHeaders = v return s }
csn
func decodeValue(dv, sv reflect.Value, blank bool) error {
return valueDecoder(dv, sv, blank)(dv, sv) }
csn_ccr
public static function shorten($text, $maxlength = 140, $end = '[...]') { $maxlength++; if (mb_strlen($text) > $maxlength) { $subex = mb_substr($text, 0, $maxlength - 5); $exwords = explode(' ', $subex); $excut = - (mb_strlen($exwords[count($exwords)-1])); ...
{ $text = mb_substr($subex, 0, $excut); } else { $text = $subex; } $text .= $end; } return $text; }
csn_ccr
python remove html markups
def do_striptags(value): """Strip SGML/XML tags and replace adjacent whitespace by one space. """ if hasattr(value, '__html__'): value = value.__html__() return Markup(unicode(value)).striptags()
cosqa
Adds a new user to the database @return JsonModel
public function addNewUserAction() { $container = new Container('meliscore'); $response = []; $this->getEventManager()->trigger('meliscore_tooluser_savenew_start', $this, $response); $melisMelisCoreConfig = $this->serviceLocator->get('MelisCoreConfig'); $appConfigForm = $mel...
csn
public function store($record) { $params['index'] = $this->getName(); $params['type'] = $record['type']; $params['id'] = $record['id'];
$params['body'] = $record['data']; self::getClient()->index($params); }
csn_ccr
List media for a given series or collection @param crunchyroll.models.Series series the series to search for @param str sort choose the ordering of the results, only META.SORT_DESC ...
def list_media(self, series, sort=META.SORT_DESC, limit=META.MAX_MEDIA, offset=0): """List media for a given series or collection @param crunchyroll.models.Series series the series to search for @param str sort choose the ordering of the ...
csn
function polygonMakeCCW(polygon){ var br = 0, v = polygon; // find bottom right point for (var i = 1; i < polygon.length; ++i) { if (v[i][1] < v[br][1] || (v[i][1] === v[br][1] && v[i][0] > v[br][0])) { br = i; } }
// reverse poly if clockwise if (!isLeft(polygonAt(polygon, br - 1), polygonAt(polygon, br), polygonAt(polygon, br + 1))) { polygonReverse(polygon); return true; } else { return false; } }
csn_ccr
def from_json(payload): """ Build a ``Place`` instance from the specified JSON object. @param payload: JSON representation of a place:: { "area_id": string, "address": { component_type: string, ... ...
"longitude": decimal, } where: * ``accuracy`` (optional): accuracy of the place's position in meters. * ``altitude`` (optional): altitude in meters of the place. * ``latitude`` (required): latitude-angular dis...
csn_ccr
Resume a paused windows service @param [String] service_name name of the service to resume @param optional [Integer] :timeout the minumum number of seconds to wait before timing out
def resume(service_name, timeout: DEFAULT_TIMEOUT) Puppet.debug _("Resuming the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout } valid_initial_states = [ SERVICE_PAUSE_PENDING, SERVICE_PAUSED, SERVICE_CONTINUE_PENDING ...
csn
You are given a permutation $p_1, p_2, \dots, p_n$. Recall that sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once. Find three indices $i$, $j$ and $k$ such that: $1 \le i < j < k \le n$; $p_i < p_j$ and $p_j > p_k$. Or say that there are no such indices. --...
import sys import math #from queue import * import random #sys.setrecursionlimit(int(1e6)) input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): return(int(input())) def inara(): return(list(map(int,input().split()))) def insr(): s = input() return(list...
apps
// NameFromKey is returns the name for this key
func (g *GPG) NameFromKey(ctx context.Context, id string) string { ent := g.findEntity(id) if ent == nil || ent.Identities == nil { return "" } for name, id := range ent.Identities { if id.UserId == nil { return name } return id.UserId.Name } return "" }
csn
python verify text field in alert window
def check_alert(self, text): """ Assert an alert is showing with the given text. """ try: alert = Alert(world.browser) if alert.text != text: raise AssertionError( "Alert text expected to be {!r}, got {!r}.".format( text, alert.text)) ...
cosqa
@Benchmark public ExampleInterface baseline() { return new ExampleInterface() { public boolean method(boolean arg) { return false; } public byte method(byte arg) { return 0; } public short method(short arg) { ...
public Object method(Object arg) { return null; } public boolean[] method(boolean arg1, boolean arg2, boolean arg3) { return null; } public byte[] method(byte arg1, byte arg2, byte arg3) { return null; } ...
csn_ccr
Writes an array of bytes. This method will block until all the bytes are actually written. @param b the data to be written @param off the start offset of the data @param len the number of bytes to write @exception IOException if an I/O error has occurred
public void write(byte[] b, int off, int len) throws IOException { //PK89810, If WCCustomProperties.FINISH_RESPONSE_ON_CLOSE is set and stream is already obtained and closed. // User will not be allowed to write more data if the above case is met, outputstreamClosed will be true and default is false. if (!(WCCu...
csn
private void upgradeLeafBlock(ReadStream is, TableEntry10 table, TableUpgrade upgradeTable, Page10 page) throws IOException { TempBuffer tBuf = TempBuffer.create(); byte []buffer = tBuf.buffer(); ...
switch (code) { case INSERT: rowInsert(table.row(), upgradeTable, buffer, rowOffset); rowOffset += rowLen; break; case REMOVE: rowOffset += keyLen + STATE_LENGTH; break; default: System.out.println("UNKNOWN: " + Integ...
csn_ccr
Returns true, if a given byte sequence is found at the given offset within the given file. @param array $bytes @param int $offset @param array $mask @return bool
protected function checkForBytes(array $bytes, int $offset = 0, array $mask = []): bool { if (empty($bytes) || empty($this->byteCache)) { return false; } // make sure we have nummeric indices $bytes = array_values($bytes); foreach ($bytes as $i => $byte) { ...
csn
protected function expandType(ClassReflection $class, $type) { $typeWithoutNull = TypeHandling::stripNullableType($type); $isNullable = $typeWithoutNull !== $type; // expand "SomeType<SomeElementType>" to "\SomeTypeNamespace\SomeType<\ElementTypeNamespace\ElementType>" if (strpos($ty...
// and then we try to find "use" statements for the class. $className = $class->getName(); if (!isset($this->useStatementsForClassCache[$className])) { $this->useStatementsForClassCache[$className] = $this->getDoctrinePhpParser()->parseClass($class); } $useStatementsFo...
csn_ccr
public function readByteOrder() : void { $byteOrder = $this->readUnsignedChar(); if ($byteOrder !== WKBTools::BIG_ENDIAN && $byteOrder !== WKBTools::LITTLE_ENDIAN) { throw GeometryIOException::invalidWKB('unknown
byte order: ' . $byteOrder); } $this->invert = ($byteOrder !== $this->machineByteOrder); }
csn_ccr
func scanTo(buf []byte, i int, stop byte) (int, []byte) { start := i for { // reached the end of buf? if i >= len(buf) { break } // Reached unescaped stop value?
if buf[i] == stop && (i == 0 || buf[i-1] != '\\') { break } i++ } return i, buf[start:i] }
csn_ccr
function chmod(p, mode) { mode = mode || 0777; if (!fs.existsSync(p)) {
return true; } return fs.chmodSync(p, mode); }
csn_ccr
python check if two paths are equal
def samefile(a: str, b: str) -> bool: """Check if two pathes represent the same file.""" try: return os.path.samefile(a, b) except OSError: return os.path.normpath(a) == os.path.normpath(b)
cosqa
protected function write($data, $log_type) { return file_put_contents($this->getLogPath($log_type) .date('Y_m_d').'.log', "\n\n".\date('Y/m/d H:i:s')
."\t".$this->agent_str ."\n".$data, \FILE_APPEND); }
csn_ccr
def done(self, msg_handle): """acknowledge completion of message""" self.sqs_client.delete_message(
QueueUrl=self.queue_url, ReceiptHandle=msg_handle.handle, )
csn_ccr
Get a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, a list of element names in order, comma separated :...
def set_data_value(datastore, path, data): ''' Get a data entry in a datastore :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :param path: The device path to set the value at, ...
csn
Sorting function, uses the score of a object to determine the order of the array @param $a @param $b @return int @author Tim Perry
protected function sortByScore($a, $b) { if ($a->score == $b->score) { return 0; } return ($a->score > $b->score) ? -1 : 1; }
csn
def path_ok(match_tuple: MatchTuple) -> bool: """Check if a file in this repository exists.""" relative_path
= match_tuple.link.split("#")[0] full_path = os.path.join(os.path.dirname(str(match_tuple.source)), relative_path) return os.path.exists(full_path)
csn_ccr
def get_connection_id(self, conn_or_int_id): """Get the connection id. Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if ...
table = self._int_connections elif isinstance(key, int): table = self._connections else: raise ArgumentError("You must supply either an int connection id or a string internal id to _get_connection_state", id=key) try: data = table[key] except KeyErr...
csn_ccr
def get_environment_requirements_list(): """ Take the requirements list from the current running environment :return: string """ requirement_list = [] requirements = check_output([sys.executable, '-m', 'pip', 'freeze']) for
requirement in requirements.split(): requirement_list.append(requirement.decode("utf-8")) return requirement_list
csn_ccr
public function append($middleware, $priority = 0): Server { return $this->appendOnCondition( $middleware,
$this->buildAlwaysTrue(), $priority ); }
csn_ccr
Obtains all relevant attributes from the activity's theme.
private void obtainStyledAttributes() { obtainUseSplitScreen(); obtainNavigationWidth(); obtainNavigationVisibility(); obtainOverrideNavigationIcon(); obtainShowButtonBar(); obtainNextButtonText(); obtainBackButtonText(); obtainFinishButtonText(); ...
csn
def allocate(n, dtype=numpy.float32): """ allocate context-portable pinned host memory """ return drv.pagelocked_empty(int(n),
dtype, order='C', mem_flags=drv.host_alloc_flags.PORTABLE)
csn_ccr
Parse the token stream into a nice dictionary data structure.
def _parse(self): """Parse the token stream into a nice dictionary data structure.""" while self._cur_token['type'] in (TT.ws, TT.lbreak): self._skip_whitespace() self._skip_newlines() self._data = self._parse_value() return self._data
csn
Instantiates a new ViewResponse @param TemplateEngineInterface $template @param string $view @param array $viewdata @param int $status @param array $headers @return \static @throws InvalidArgumentException
public static function create($template = null, $view = '', $viewdata = [], $status = 200, $headers = array()) { if (!$template instanceof TemplateEngineInterface) { throw new InvalidArgumentException('The first argument of ViewResponse::create must be an instance of Laasti\Response\Engines\Temp...
csn
function(models, options) { if(!models) return false; this.remove(models, options); var singular = !_.isArray(models); models = singular
? [models] : _.clone(models); return this._callAdapter('removeFromIndex', options, models); }
csn_ccr
Internal generate log message. @param string $type @param string $message @param string $trace @param string $groupIdentifier @return boolean
private static function log($type, $message, $trace, $groupIdentifier) { $hashArray = static::getHashArray($message, $groupIdentifier); $file = 'unknown'; $line = 'unknown'; $fn = 'unknown'; $fnArgs = []; if (isset($trace[0])) { $file = !...
csn
Return the nominal diameter of the entrance tank drain pipe. Depth at the end of the flocculator is used for headloss and length calculation inputs in the diam_pipe calculation. Parameters ---------- q_plant: float Plant flow rate T: float Design temperature depth_end: flo...
def drain_OD(q_plant, T, depth_end, SDR): """Return the nominal diameter of the entrance tank drain pipe. Depth at the end of the flocculator is used for headloss and length calculation inputs in the diam_pipe calculation. Parameters ---------- q_plant: float Plant flow rate T: flo...
csn
python numpy make empty array
def _create_empty_array(self, frames, always_2d, dtype): """Create an empty array with appropriate shape.""" import numpy as np if always_2d or self.channels > 1: shape = frames, self.channels else: shape = frames, return np.empty(shape, dtype, order='C')
cosqa
private static DataNode marshalObject(Map<String, AbstractDataMarshaller<?>> marshallerMap, Object object) { //can't be null here because it is not resolved: meaning, it is an instance of an unknown class final Class<?> clazz = object.getClass(); final AbstractDataMarshaller<Object> serializer ...
(AbstractDataMarshaller<Object>) marshallerMap.get(clazz.getCanonicalName()); if (serializer != null) { final DataNode node = serializer.marshal(object); node.setObject(META_CLASS_NAME, serializer.getDataClassName()); return node; } return null; //no marshall...
csn_ccr
Report irregularity to a delivery execution @todo remove this method to separate service @param DeliveryExecution $deliveryExecution @param array $reason @return bool
public function reportExecution(DeliveryExecution $deliveryExecution, $reason) { $deliveryLog = $this->getDeliveryLogService(); $data = [ 'reason' => $reason, 'timestamp' => microtime(true), 'itemId' => $this->getCurrentItemId($deliveryExecution), 'con...
csn
helper function to load mapratings for current map @param Map $map
private function loadRatings(Map $map) { try { $this->mapRatingsService->load($map); } catch (PropelException $e) { $this->logger->error("error loading map ratings", ["exception" => $e]); } }
csn
Pads vocabulary to a multiple of 'pad' tokens. :param vocab: list with vocabulary :param pad: integer
def pad_vocabulary(self, vocab, pad): """ Pads vocabulary to a multiple of 'pad' tokens. :param vocab: list with vocabulary :param pad: integer """ vocab_size = len(vocab) padded_vocab_size = (vocab_size + pad - 1) // pad * pad for i in range(0, padded_vo...
csn
Check if the Role is applied to Private Zone. @param bool $strict If true, only roles with nb_site_map_role_zone= 'P' are valid. If false, 'P' and 'B' values are true. @return bool Return true if the Role applies to Private Zone.
public function isForPrivateZone(bool $strict = false) { if (!method_exists($this, 'getZone')) { throw new ENabuCoreException(ENabuCoreException::ERROR_FEATURE_NOT_IMPLEMENTED); } $zone = $this->getZone(); return ($zone === CNabuSite::ZONE_PRIVATE || (!$strict && $zone ...
csn
// masterGTIDSet is part of the Flavor interface.
func (mysqlFlavor) masterGTIDSet(c *Conn) (GTIDSet, error) { qr, err := c.ExecuteFetch("SELECT @@GLOBAL.gtid_executed", 1, false) if err != nil { return nil, err } if len(qr.Rows) != 1 || len(qr.Rows[0]) != 1 { return nil, vterrors.Errorf(vtrpc.Code_INTERNAL, "unexpected result format for gtid_executed: %#v", q...
csn
// Send sends a seek request to the deliver server
func (c *DeliverConnection) Send(seekInfo *ab.SeekInfo) error { if c.Closed() { return errors.New("connection is closed") } logger.Debugf("Sending %#v", seekInfo) env, err := c.createSignedEnvelope(seekInfo) if err != nil { return err } return c.deliverStream().Send(env) }
csn
func SubSpan(path, key string, i, j int) (string, error) { si, ok := segIndexByKey(path, key) if !ok { return "", ErrKeySegNotFound } if i >= 0 { i++ } if
j > 0 { j++ } s, err := Span(path[si:], i, j) if err != nil { return "", err } return s, nil }
csn_ccr
def freeze(bin_env=None, user=None, cwd=None, use_vt=False, env_vars=None, **kwargs): ''' Return a list of installed packages either globally or in the specified virtualenv bin_env Path to pip (or to a virtualenv). This can be used to speci...
'included in the output of pip.freeze', cur_version, min_version ) else: cmd.append('--all') cmd_kwargs = dict(runas=user, cwd=cwd, use_vt=use_vt, python_shell=False) if kwargs: cmd_kwargs.update(**kwargs) if bin_env and os.path.isdir(bin_env): cmd_kwargs['env'] =...
csn_ccr
public static function addTag(string $string, string $tag): string { $lastPoint = strrpos($string, '.');
return ($tag ? substr_replace($string, sprintf('.%s.', $tag), $lastPoint, 1) : $string); }
csn_ccr
Search for the value in the float array and return the index of the first occurrence from the beginning of the array. @param floatArray array that we are searching in. @param value value that is being searched in the array. @param occurrence number of times we have seen the value before returning the index. @return t...
public static int search(float[] floatArray, float value, int occurrence) { if(occurrence <= 0 || occurrence > floatArray.length) { throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than " + "the array length: " + occurrence); } ...
csn
function() { var layerEl = this.container && this.container.layer ? this.container.layer.el : document.body; var obj = this.el; var curleft = 0, curtop = 0; if (obj.offsetParent) { do {
curleft += obj.offsetLeft; curtop += obj.offsetTop; obj = obj.offsetParent; } while ( !!obj && obj != layerEl); } return [curleft+15,curtop+15]; }
csn_ccr
Tests if the decorated method has a sufficient number of parameters. :param method: The method to be tested :param needed_args: The name (for description only) of the needed arguments, without "self". :return: Nothing :raise TypeError: Invalid number of parameter
def validate_method_arity(method, *needed_args): # type: (Callable, *str) -> None """ Tests if the decorated method has a sufficient number of parameters. :param method: The method to be tested :param needed_args: The name (for description only) of the needed arguments, with...
csn
protected function sigquit() { if (Daemon::$config->logsignals->value) { $this->log('Caught SIGQUIT.');
} $this->signalToChildren(SIGQUIT); $this->shutdown(SIGQUIT); }
csn_ccr
@Override public long numParams(boolean backwards) { int length = 0; for (int i = 0; i < layers.length; i++)
length += layers[i].numParams(backwards); return length; }
csn_ccr
how to do things after a set amount of time in python
def seconds(num): """ Pause for this many seconds """ now = pytime.time() end = now + num until(end)
cosqa
def try_int(o:Any)->Any: "Try to convert `o` to int, default to `o` if not possible." # NB: single-item rank-1 array/tensor can be converted to int, but we don't want to do this if isinstance(o, (np.ndarray,Tensor)): return o if o.ndim else
int(o) if isinstance(o, collections.Sized) or getattr(o,'__array_interface__',False): return o try: return int(o) except: return o
csn_ccr
function(reaped) { childCount += 1; if (reaped) { self.options.log.trace1('Incrementing reapCount', {current: reapCount});
reapCount += 1; } if (childCount >= children.length) { cbWrapper(function() { callback(null, reapCount); }); } }
csn_ccr
// SeedHash retrieves the seed hash of a block.
func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) { block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) if block == nil { return "", fmt.Errorf("block #%d not found", number) } return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil }
csn
function getRowspanNum(data = [], child = []) { let childs = []; for (let i = 0; i < data.length; i += 1) { if (!data[i].children) { childs.push(data[i]); } else if (data[i].children && data[i].children.length
> 0) { childs = childs.concat(getRowspanNum(data[i].children, child)); } } return childs; }
csn_ccr
func Sequence(meta SequenceMeta, r ...Renderable) *SequenceRenderer { if meta.Tag == "" { meta.Tag = "div" } s := SequenceRenderer{ Publisher:
pub.Identity(), SequenceMeta: &meta, } s.Add(r...) return &s }
csn_ccr
func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) {
return newServicePrincipalTokenFromMSI(msiEndpoint, resource, nil, callbacks...) }
csn_ccr
public function createAssoc(array $properties, array $mapping) { $values = (array) $properties[$mapping['property']]; if (!isset($properties[$mapping['assoc']])) { return $values; } $keys = (array) $properties[$mapping['assoc']]; $nulls = (array)
($properties[$mapping['assocNulls']] ?? []); // make sure we start with first value reset($values); $result = []; foreach ($keys as $key) { if (in_array($key, $nulls)) { $result[$key] = null; } else { $result[$key] = current($valu...
csn_ccr
how can i combine all the elements in a list in python
def combinations(l): """Pure-Python implementation of itertools.combinations(l, 2).""" result = [] for x in xrange(len(l) - 1): ls = l[x + 1:] for y in ls: result.append((l[x], y)) return result
cosqa
public function get($abstract) { /** * @todo validate that $abstract is a string */ if (!isset($this->definitions[$abstract])) {
$this->definitions[$abstract] = new Definition($this); } return $this->definitions[$abstract]; }
csn_ccr
private EditableValueData createEditableCopy(ValueData oldValue) throws RepositoryException, IllegalStateException, IOException { if (oldValue.isByteArray()) { // bytes, make a copy of real data byte[] oldBytes = oldValue.getAsByteArray(); byte[] newBytes = new byte[oldBy...
} catch (IOException e) { throw new RepositoryException(e); } } else { // edited BLOB file, make a copy try { return new EditableValueData(oldValue.getAsStream(), oldValue.getOrderNumber(), spoolConfig); } ...
csn_ccr
// Deserialize takes some Flatbuffer serialized bytes and deserialize's them // as meminfo.Info.
func Deserialize(p []byte) *mem.Info { infoFlat := structs.GetRootAsInfo(p, 0) info := &mem.Info{} info.Timestamp = infoFlat.Timestamp() info.Active = infoFlat.Active() info.ActiveAnon = infoFlat.ActiveAnon() info.ActiveFile = infoFlat.ActiveFile() info.AnonHugePages = infoFlat.AnonHugePages() info.AnonPages = ...
csn
Formats the given text to fit into the maximum line length and outputs it to the console window @param string $text Text to output @param array $arguments Optional arguments to use for sprintf @param integer $leftPadding The number of spaces to use for indentation @return void @see outputLine()
public function outputFormatted(string $text = '', array $arguments = [], int $leftPadding = 0): void { $lines = explode(PHP_EOL, $text); foreach ($lines as $line) { $formattedText = str_repeat(' ', $leftPadding) . wordwrap($line, $this->getMaximumLineLength() - $leftPadding, PHP_EOL . s...
csn
def find(node, nbk) node_type = get_node_type node case node_type when :blank BLANK_NODE when :branch return node.last if nbk.empty? sub_node = decode_to_node node[nbk[0]] find sub_node, nbk[1..-1] when :leaf node_key = NibbleKey.decode(node[0]).te...
if node_key.prefix?(nbk) sub_node = decode_to_node node[1] find sub_node, nbk[node_key.size..-1] else BLANK_NODE end else raise InvalidNodeType, "node type must be in #{NODE_TYPES}, given: #{node_type}" end end
csn_ccr
// Attach attaches a policy to a team
func (p *PoliciesClient) Attach(ctx context.Context, org, policy, team *identity.ID) error { attachment := primitive.PolicyAttachment{ OrgID: org, OwnerID: team, PolicyID: policy, } ID, err := identity.NewMutable(&attachment) if err != nil { return err } env := envelope.PolicyAttachment{ ID: ...
csn
Wait to get the status of a fault log write
private void blockFaultLogWriteStatus(SettableFuture<Boolean> written) { boolean logWritten = false; if (written != null) { try { logWritten = written.get(); } catch (InterruptedException e) { } catch (ExecutionException e) { if (tmLog...
csn
private void configureAnalysisFeatures() { for (AnalysisFeatureSetting setting : analysisOptions.analysisFeatureSettingList) { setting.configure(AnalysisContext.currentAnalysisContext());
} AnalysisContext.currentAnalysisContext().setBoolProperty(AnalysisFeatures.MERGE_SIMILAR_WARNINGS, analysisOptions.mergeSimilarWarnings); }
csn_ccr
python hsv to rgb code
def hsv2rgb_spectrum(hsv): """Generates RGB values from HSV values in line with a typical light spectrum.""" h, s, v = hsv return hsv2rgb_raw(((h * 192) >> 8, s, v))
cosqa
public static WriteChannelConfiguration of(TableId destinationTable,
FormatOptions format) { return newBuilder(destinationTable).setFormatOptions(format).build(); }
csn_ccr
public function indexAction() { $em = $this->getDoctrine()->getManager(); $paymentServiceProviders = $em->getRepository('EcommerceBundle:PaymentServiceProvider')->findAll();
return array( 'paymentServiceProviders' => $paymentServiceProviders, ); }
csn_ccr
// ClusterNamesByVersion returns a slice of all cluster names which match a given cluster version
func (m Map) ClusterNamesByVersion(matchingVersion string) []string { var ret []string for name, cluster := range m.nameMap { if matchingVersion == cluster.CurrentNodeVersion { ret = append(ret, name) } } return ret }
csn
Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, suggest them, sorted by how often the type is referenced, starting with Interfaces.
def get_suggested_type_names(schema, output_type, field_name): """Go through all of the implementations of type, as well as the interfaces that they implement. If any of those types include the provided field, suggest them, sorted by how often the type is referenced, starting with Interfaces.""" ...
csn
async def exist(self, key, param=None): """see if specific identity exists"""
identity = self._gen_identity(key, param) return await self.client.exists(identity)
csn_ccr
function mask( obj ){ if ( Object.create ){ var T = function Masked(){}; T.prototype = obj;
return new T(); }else{ return Object.create( obj ); } }
csn_ccr
Applies the maximum height and width to the dimension. @param dim the dimension to be limited
private void applyMax(Dimension dim) { if (getMaxHeight() > 0) { dim.height = Math.min(dim.height, getMaxHeight()); } if (getMaxWidth() > 0) { dim.width = Math.min(dim.width, getMaxWidth()); } }
csn
python go to parent directory
def go_to_parent_directory(self): """Go to parent directory""" self.chdir(osp.abspath(osp.join(getcwd_or_home(), os.pardir)))
cosqa
public static java.lang.Long toLong(Object arg) throws NoSuchMethodException { if (arg instanceof java.lang.Integer) return boxToLong((long)unboxToInt(arg)); if (arg instanceof java.lang.Double) return boxToLong((long)unboxToDouble(arg)); if (arg instanceof java.lang.Float) return boxToLong((lon...
if (arg instanceof java.lang.Long) return (java.lang.Long)arg; if (arg instanceof java.lang.Character) return boxToLong((long)unboxToChar(arg)); if (arg instanceof java.lang.Byte) return boxToLong((long)unboxToByte(arg)); if (arg instanceof java.lang.Short) return boxToLong((long)unboxT...
csn_ccr
public function makeSureMenusExist() { $locales = array_unique($this->getLocales()); $required = array(); foreach ($this->menuNames as $name) { $required[$name] = $locales; } $menuObjects = $this->em->getRepository($this->menuEntityClass)->findAll(); fo...
$index = array_search($menu->getLocale(), $required[$menu->getName()]); if ($index !== false) { unset($required[$menu->getName()][$index]); } } } foreach ($required as $name => $locales) { foreach ($locales as $locale...
csn_ccr
public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) { global $DB; if ($instanceid != 0) { debugging('context_system::instance(): invalid $id parameter detected, should be 0'); } if (defined('SYSCONTEXTID') and $cache) { // dangerous: de...
} if (defined('SYSCONTEXTID')) { // this would happen only in unittest on sites that went through weird 1.7 upgrade $record->id = SYSCONTEXTID; $DB->import_record('context', $record); $DB->get_manager()->reset_sequence('co...
csn_ccr
Produce a list of slices given the boolean array b. Start and stop in each slice describe the True sections in b.
def slicelist(b): """Produce a list of slices given the boolean array b. Start and stop in each slice describe the True sections in b.""" slicelst = [] started = False for i, e in enumerate(b): if e and not started: start = i started = True elif not e and st...
csn
func (s *GeoLocationDetails) SetSubdivisionName(v string) *GeoLocationDetails {
s.SubdivisionName = &v return s }
csn_ccr
reates a the summary of MonetaryAmounts. @param currencyUnit the target {@link javax.money.CurrencyUnit} @param provider the rate provider @return the MonetarySummaryStatistics @deprecated Use #summarizingMonetary(CurrencyUnit) instead of.
@Deprecated public static Collector<MonetaryAmount, MonetarySummaryStatistics, MonetarySummaryStatistics> summarizingMonetary( CurrencyUnit currencyUnit, ExchangeRateProvider provider){ // TODO implement method here return summarizingMonetary(currencyUnit); }
csn
func (s *EventSourceMappingConfiguration) SetStateTransitionReason(v
string) *EventSourceMappingConfiguration { s.StateTransitionReason = &v return s }
csn_ccr
// ClearAllTlfBlocks implements the DiskBlockCache interface for // DiskBlockCacheLocal.
func (cache *DiskBlockCacheLocal) ClearAllTlfBlocks( ctx context.Context, tlfID tlf.ID) (err error) { defer func() { cache.log.CDebugf(ctx, "Finished clearing blocks from %s: %+v", tlfID, err) }() // Delete the blocks in batches, so we don't keep the lock for too // long. for { cache.log.CDebugf(ctx, "Del...
csn
private function createDeleteForm($featureId, $id) { return $this->createFormBuilder(array('featureId' => $featureId, 'id' => $id)) ->add('featureId',
'hidden') ->add('id', 'hidden') ->getForm(); }
csn_ccr
HTTP POST routing. @param uriTemplate the specified request URI template @param handler the specified handler @return router
public static Router post(final String uriTemplate, final ContextHandler handler) { return route().post(uriTemplate, handler); }
csn
private function copy_feedback_files(context $context, string $filearea, int $itemid) { if ($this->feedbackfiles) { $filestocopycontextid = $this->feedbackfiles['contextid']; $filestocopycomponent = $this->feedbackfiles['component']; $filestocopyfilearea = $this->feedbackfile...
$destination = [ 'contextid' => $context->id, 'component' => GRADE_FILE_COMPONENT, 'filearea' => $filearea, 'itemid' => $itemid ]; $fs->create_file_from_storedfile($destinati...
csn_ccr
Properly formats a title string. @param string $string @return string
public function title($string) { $string = explode(' ', $string); foreach ($string as $key => $value) { if (!empty($value) && mb_strtoupper($value) == $value) { $string[$key] = mb_strtolower($value); } } return TextFormatter::titleCase(implode...
csn
// WithTimeout adds the timeout to the delete service ID params
func (o *DeleteServiceIDParams) WithTimeout(timeout time.Duration) *DeleteServiceIDParams { o.SetTimeout(timeout) return o }
csn
def auto_param_specs(self): """ Parameter pecs in the sub-study class that are not explicitly provided
in the name map """ for spec in self.study_class.parameter_specs(): if spec.name not in self._name_map: yield spec
csn_ccr
Sets element html content as a typical action of a modal form call @param string $element The element specifier; typically starting with '#' @param string $html The html string
protected function SetJSHtml($element, $html) { $jsElement = Str::ToJavascript($element, false); $jsHtml = Str::ToJavascript($html, false); echo "<script>$($jsElement).html($jsHtml);</script>"; }
csn
Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on connect, return all tables, with schema prefixes
def tables(self): """ Get a listing of all tables - if schema specified on connect, return unqualifed table names in that schema - in no schema specified on connect, return all tables, with schema prefixes """ if self.schema: return...
csn
Add the given values to this adder. @param values the values to add. @return {@code this} adder, for command chaining
public DoubleAdder add(final double[] values) { for (int i = values.length; --i >= 0;) { add(values[i]); } return this; }
csn
public function actionDataBlocks() { $favs = Yii::$app->adminuser->identity->setting->get("blockfav", []); $groups = []; foreach (BlockGroup::find()->with(['blocks'])->all() as $blockGroup) { $blocks = []; $groupPosition = null; foreach ($blockGroup->block...
'groupPosition' => $groupPosition, 'group' => $group, 'blocks' => $blocks, ]; } if (!empty($favs)) { $favblocks = []; foreach ($favs as $fav) { $favblocks[] = $fav; } array_un...
csn_ccr
function log(msg, color) { if (typeof(msg) === 'object') { for (var item in msg) { if (msg.hasOwnProperty(item)) { if(color && color in $.util.colors) {
$.util.log($.util.colors[color](msg[item])); } $.util.log($.util.colors.lightgreen(msg[item])); } } } else { $.util.log($.util.colors.green(msg)); } }
csn_ccr