query
large_stringlengths
4
15k
positive
large_stringlengths
5
373k
source
stringclasses
7 values
Creates a floating-point symbol. :param name: The name of the symbol :param sort: The sort of the floating point :param explicit_name: If False, an identifier is appended to the name to ensure uniqueness. :return: An FP AST.
def FPS(name, sort, explicit_name=None): """ Creates a floating-point symbol. :param name: The name of the symbol :param sort: The sort of the floating point :param explicit_name: If False, an identifier is appended to the name to ensure uniqueness. :return: ...
csn
Create a WorkClassLoader @param cb The class bundle @return The class loader
static WorkClassLoader createWorkClassLoader(final ClassBundle cb) { return AccessController.doPrivileged(new PrivilegedAction<WorkClassLoader>() { public WorkClassLoader run() { return new WorkClassLoader(cb); } }); }
csn
The CSV package has no resources, so we just need to resolve the URLs to them. Usually, the CSV package is built from a file system ackage on a publically acessible server.
def _load_resource(self, source_r, abs_path=False): """The CSV package has no resources, so we just need to resolve the URLs to them. Usually, the CSV package is built from a file system ackage on a publically acessible server. """ from itertools import islice from metapack.exc impo...
csn
Returns the Java name for a proto field.
public static String getFieldName( Descriptors.FieldDescriptor field, boolean capitializeFirstLetter) { String fieldName = field.getName(); if (SPECIAL_CASES.containsKey(fieldName)) { String output = SPECIAL_CASES.get(fieldName); if (capitializeFirstLetter) { return output; } els...
csn
Checks whether the given file has one of the given extension. @param file the file @param extensions the extensions @return {@literal true} if the file has one of the given extension, {@literal false} otherwise
public static boolean hasExtension(File file, String... extensions) { String extension = FilenameUtils.getExtension(file.getName()); for (String s : extensions) { if (extension.equalsIgnoreCase(s) || ("." + extension).equalsIgnoreCase(s)) { return true; } ...
csn
Get all available entities @return string[]
public static function getAllEntities() { $entities = cleanscandir(pathOf(CONFDIR.ENTITY_DESCRIPTOR_CONFIG_PATH)); foreach( $entities as $i => &$filename ) { $pi = pathinfo($filename); if( $pi['extension'] != 'yaml' ) { unset($entities[$i]); continue; } $filename = $pi['filename']; } return ...
csn
Get a relation by name for this entity. Ignore cache if cachable is false. @param valuesClass Class type of T. @param name Name of the relation attribute. @param cachable False if should not be cached. @return The related asset.
<T extends Entity> T getRelation(Class<T> valuesClass, String name, boolean cachable) { return instance.getRelation(this, valuesClass, name, cachable); }
csn
Build the Steam login URL @param string $return A custom return to URL @return string
public function url($return = null, $altRealm = null) { $useHttps = !empty($_SERVER['HTTPS']) || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'); if (!is_null($return)) { if (!$this->validateUrl($return)) { throw new Exception...
csn
Resolve node parenthesis. @param NodeContract $node
public function resolveParenthesis(NodeContract $node) { foreach ($node->getChildren() as $child) { $this->resolveParenthesis($child); } if (!$node instanceof Nodes\TextNode) { return; } $value = ''; $positions = []; foreach ($this->...
csn
comfort method for getting a console error stream @return \stubbles\streams\OutputStream
public static function forError(): OutputStream { if (null === self::$err) { self::$err = self::create('php://stderr'); } return self::$err; }
csn
Sets the resources for this operator. This overrides the default minimum and preferred resources. @param resources The resources for this operator. @return The operator with set minimum and preferred resources.
private O setResources(ResourceSpec resources) { Preconditions.checkNotNull(resources, "The resources must be not null."); Preconditions.checkArgument(resources.isValid(), "The values in resources must be not less than 0."); this.minResources = resources; this.preferredResources = resources; @SuppressWarnin...
csn
Catalogue also class interface when using add @param string $name @param string $class
protected function addInterface(string $name, string $class) { if (!$this->hasInterface($name)) { $this->interfaces[$name] = $class; return; } $interfaces = $this->getInterface($name); if (!is_array($interfaces)) { $interfaces = [$interfaces]; ...
csn
Delete a feed post comment @param string|int $channelIdentifier @param string $postId @param string $accessToken @param string|int $commentId @throws InvalidIdentifierException @throws InvalidTypeException @return array|json
public function deleteFeedComment($channelIdentifier, $postId, $commentId, $accessToken) { if ($this->apiVersionIsGreaterThanV3() && !is_numeric($channelIdentifier)) { throw new InvalidIdentifierException('channel'); } return $this->delete(sprintf('feed/%s/posts/%s/comments/%s',...
csn
Calls sibling with exception expectation.
def run(self) -> None: '''Calls sibling with exception expectation.''' with self.context.assertRaises(self.error.__class__) as error: super().run() self.exception = error.exception
csn
Trackes the list of prefixes as defined. @param string[]|string $prefixes list of prefixes
public function trackDefinedPrefixes( $prefixes ) { if ( !is_array( $prefixes ) ) { $prefixes = $this->matchPrefixes( $prefixes ); } $this->definedPrefixes = array_merge( $this->definedPrefixes, $prefixes ); }
csn
Converts the given AudioBuffer into an audio packet, ready for streaming along the underlying output stream. Unlike the raw audio packets used by this audio recorder, AudioBuffers require floating point samples and are split into isolated planes of channel-specific data. @private @param {AudioBuffer} audioBuffer The W...
function toSampleArray(audioBuffer) { // Track overall amount of data read var inSamples = audioBuffer.length; readSamples += inSamples; // Calculate the total number of samples that should be written as of // the audio data just received and adjust the size of the output ...
csn
Draws the base sausage within which all the other decorations are added.
protected void drawBase (Graphics2D gfx, int x, int y) { gfx.fillRoundRect( x, y, _size.width - 1, _size.height - 1, _dia, _dia); }
csn
// NewProcessor creates a Processor. // // "highQuality" indicates if the Processor return a NRGBA64 Image or an Image with the same quality as the given Image.
func NewProcessor(gamma float64, highQuality bool) *Processor { prc := new(Processor) gammaInv := 1 / gamma for i := range prc.vals { prc.vals[i] = uint16(math.Pow(float64(i)/65535, gammaInv)*65535 + 0.5) } if highQuality { prc.newDrawable = func(p image.Image) draw.Image { return image.NewNRGBA64(p.Bounds(...
csn
// NewDuration returns returns an 'enum' value of type duration given its // string representation
func NewDuration(s string) (duration, error) { var e duration err := e.FromString(s) if err != nil { return 0, err } return e, nil }
csn
// ParseFile parses the given .mss file. // Can be called multiple times to parse a style split into multiple files.
func (d *Decoder) ParseFile(filename string) error { d.filename = filename defer func() { d.filename = "" }() r, err := os.Open(filename) if err != nil { return err } defer r.Close() content, err := ioutil.ReadAll(r) if err != nil { return err } return d.ParseString(string(content)) }
csn
// AddSessionName appends Session Name field to Session.
func (s Session) AddSessionName(name string) Session { return s.appendString(TypeSessionName, name) }
csn
// restRemoveVirtualHost removes a vhost name from provided service and endpoint. Parameters are defined in path.
func restRemoveVirtualHost(w *rest.ResponseWriter, r *rest.Request, ctx *requestContext) { serviceid, application, vhost, err := getVHostContext(r) if err != nil { restServerError(w, err) return } glog.V(2).Info("Removing vhost %d from service (%s)", vhost, serviceid) facade := ctx.getFacade() dataCtx := ct...
csn
Validates that a library class name exists. @param string $subClass @param string $path @throws InvalidConfigurationException
private function validateLibClassExists($subClass, $path) { $class = Utility::getLibraryClass($subClass); if (false === class_exists($class)) { throw new InvalidConfigurationException(sprintf('The library class "%s" was not found for "%s" - was the library installed?', $class, $path)); ...
csn
Makes sure we've properly handled the POST body, such as ensuring that CURLOPT_INFILESIZE is set if CURLOPT_READFUNCTION is set. @param Request $request Request to set cURL option to. @param resource $curlHandle cURL handle associated with the request.
public static function validateCurlPOSTBody(Request $request, $curlHandle = null) { $readFunction = $request->getCurlOption(CURLOPT_READFUNCTION); if (is_null($readFunction)) { return; } // Guzzle 4 sometimes sets the post body in CURLOPT_POSTFIELDS even if ...
csn
Returns information if given url address is valid @param string $url The url to validate / verify @param bool $requireProtocol (optional) If is set to true, the protocol is required to be passed in the url. Otherwise - not. @return bool
public static function isValidUrl($url, $requireProtocol = false) { /* * Not a string? * Nothing to do */ if (!is_string($url)) { return false; } $pattern = self::getUrlPattern($requireProtocol); return (bool)preg_match($pattern, $url)...
csn
// GetMetrics - Retrieve current values of run-time metrics. // Returns - metrics - Current values for run-time metrics.
func (c *Performance) GetMetrics() ([]*PerformanceMetric, error) { resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Performance.getMetrics"}) if err != nil { return nil, err } var chromeData struct { Result struct { Metrics []*P...
csn
Invoke a POST request to the Para API. @param resourcePath the subpath after '/v1/', should not start with '/' @param entity request body @return a {@link Response} object
public Response invokePost(String resourcePath, Entity<?> entity) { logger.debug("POST {}, entity: {}", getFullPath(resourcePath), entity); return invokeSignedRequest(getApiClient(), accessKey, key(true), POST, getEndpoint(), getFullPath(resourcePath), null, null, entity); }
csn
// Apply command adds hostnames to the hosts file from JSON
func Apply(c *cli.Context) { if len(c.Args()) != 1 { MaybeError(c, "Usage should be apply [filename]") } filename := c.Args()[0] jsonbytes, err := ioutil.ReadFile(filename) if err != nil { MaybeError(c, fmt.Sprintf("Unable to read %s: %s", filename, err)) } hostfile := AlwaysLoadHostFile(c) err = hostfile...
csn
Retrieve the lock object for a given key @param key the key for the lock @return the object that will be used as a lock
private Object retrieveLock(String key) { Object lock = this.lockMap.get(key); if(lock == null) { lock = key; this.lockMap.put(key, lock); } return lock; }
csn
Fetches a resource. @param msg the HTTP message that will be sent to the server @throws IOException Signals that an I/O exception has occurred.
private void fetchResource(HttpMessage msg) throws IOException { if (parent.getHttpSender() == null) { return; } try { parent.getHttpSender().sendAndReceive(msg); } catch (ConnectException e) { log.debug("Failed to connect to: " + msg.getRequestHeader().getURI(), e); throw e; } catch (SocketTim...
csn
Interprets positional and keyword arguments related to framers. :param args: A tuple of positional arguments. The first such argument will be interpreted as a framer object, and the second will be interpreted as a framer state. :pa...
def _interpret_framer(self, args, kwargs): """ Interprets positional and keyword arguments related to framers. :param args: A tuple of positional arguments. The first such argument will be interpreted as a framer object, and the second will be ...
csn
Appends url path. @param string $urlPath url path to append
public function appendUrlPath($urlPath) { Validate::isString($urlPath, 'urlPath'); $newUrlPath = parse_url($this->_url, PHP_URL_PATH).$urlPath; $this->_url->setPath($newUrlPath); }
csn
Updates RT filters for each peer. Should be called if a new RT Nlri's have changed based on the setting. Currently only used by `Processor` to update the RT filters after it has processed a RT destination. If RT filter has changed for a peer we call RT filter change handler.
def update_rtfilters(self): """Updates RT filters for each peer. Should be called if a new RT Nlri's have changed based on the setting. Currently only used by `Processor` to update the RT filters after it has processed a RT destination. If RT filter has changed for a peer we cal...
csn
Clips the current image by modifying it in-place @method clip @param {int} x Starting x-coordinate @param {int} y Starting y-coordinate @param {int} width Width of area relative to starting coordinate @param {int} height Height of area relative to starting coordinate
function (x, y, width, height) { var image; width = Math.min(width, this.getWidth() - x); height = Math.min(height, this.getHeight() - y); if ((width < 0) || (height < 0)) { throw new Error('Width and height cannot be negative.'); } image = new PNG({ width: width, height: height }); this._ima...
csn
Zrzuca namespace do tabeli @return string
public function toArray() { return (isset($_SESSION[$this->_namespace]) && is_array($_SESSION[$this->_namespace])) ? $_SESSION[$this->_namespace] : []; }
csn
Create and return a default ID field that is Auto generated
def _create_id_field(new_class): """Create and return a default ID field that is Auto generated""" id_field = Auto(identifier=True) setattr(new_class, 'id', id_field) id_field.__set_name__(new_class, 'id') # Ensure ID field is updated properly in Meta attribute new_clas...
csn
Returns the number of elements matched by the selector @method getNumberOfElements @param {string} selector Selector expression to find the elements @param {integer} expected Expected number of matched elements @param {string} uuid Unique hash of that fn call @chainable
function (selector, expected, hash) { this.actionQueue.push(this.webdriverClient.elements.bind(this.webdriverClient, selector)); this.actionQueue.push(this._getNumberOfElementsCb.bind(this, selector, hash, expected)); return this; }
csn
Remove a previously frozen list of extensions.
def unfreeze_extensions(self): """Remove a previously frozen list of extensions.""" output_path = os.path.join(_registry_folder(), 'frozen_extensions.json') if not os.path.isfile(output_path): raise ExternalError("There is no frozen extension list") os.remove(output_path) ...
csn
Query the info for a specific value @param string $info_name @return mixed
public function getInfo($info_name) { $value = null; if($info_name == 'provider') $value = $this->provider; else if(property_exists($this->profile, $info_name)) $value = $this->profile->$info_name; return $value; }
csn
Formats a string and puts the result into a StringBuffer. Allows for standard Java backslash escapes and a customized behavior for % escapes in the form of a PrintfSpec. @param buf the buffer to append the result to @param formatString the string to format @param printfSpec the specialization for printf
public static void printf(StringBuffer buf, String formatString, PrintfSpec printfSpec) { for (int i = 0; i < formatString.length(); ++i) { char c = formatString.charAt(i); if ((c == '%') && (i + 1 < formatString.length())) { ++i; char code = formatSt...
csn
// NewCmdCreateNamespace is a macro command to create a new namespace
func NewCmdCreateNamespace(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { options := &NamespaceOpts{ CreateSubcommandOptions: NewCreateSubcommandOptions(ioStreams), } cmd := &cobra.Command{ Use: "namespace NAME [--dry-run]", DisableFlagsInUseLine: true, Aliases:...
csn
Compute the SARI score for a single prediction and one or more targets. Args: source_ids: a list / np.array of SentencePiece IDs prediction_ids: a list / np.array of SentencePiece IDs list_of_targets: a list of target ID lists / np.arrays max_gram_size: int. largest n-gram size we care about (e.g. 3 ...
def get_sari_score(source_ids, prediction_ids, list_of_targets, max_gram_size=4, beta_for_deletion=0): """Compute the SARI score for a single prediction and one or more targets. Args: source_ids: a list / np.array of SentencePiece IDs prediction_ids: a list / np.array of SentencePiece ID...
csn
generate a message for loglevel WARN @param pObject the message Object
public final void warn(Object pObject) { getLogger().log(FQCN, Level.WARN, pObject, null); }
csn
Sets the caseValue value for this ProductPartition. @param caseValue * Dimension value with which this product partition is refining its parent. Undefined for the root partition.
public void setCaseValue(com.google.api.ads.adwords.axis.v201809.cm.ProductDimension caseValue) { this.caseValue = caseValue; }
csn
// NewEventsController creates a work_item_events controller.
func NewEventsController(service *goa.Service, db application.DB, config EventsControllerConfig) *EventsController { return &EventsController{ Controller: service.NewController("EventsController"), db: db, config: config} }
csn
define the outlines in the doc, empty for now
function o_outlines( $id, $action, $options = '' ) { if ( $action != 'new' ) { $o =& $this->objects[$id]; } switch ( $action ) { case 'new': $this->objects[$id] = array( 't' => 'outlines', 'info' => array( 'outlines' => array() ) ); ...
csn
Retrieve page uuid from legacy moduleid.
def get_module_uuid(plpy, moduleid): """Retrieve page uuid from legacy moduleid.""" plan = plpy.prepare("SELECT uuid FROM modules WHERE moduleid = $1;", ('text',)) result = plpy.execute(plan, (moduleid,), 1) if result: return result[0]['uuid']
csn
Only a getter on purpose. See the tests.
def background(self): """Only a getter on purpose. See the tests.""" if self._background is None: self._background = GSBackgroundLayer() self._background._foreground = self return self._background
csn
Export groups to configuration file. @param groupsConfig The export media (must not be <code>null</code>). @param groups The groups to export (must not be <code>null</code>). @throws LionEngineException If unable to write to media.
public static void exports(Media groupsConfig, Iterable<TileGroup> groups) { Check.notNull(groupsConfig); Check.notNull(groups); final Xml nodeGroups = new Xml(NODE_GROUPS); nodeGroups.writeString(Constant.XML_HEADER, Constant.ENGINE_WEBSITE); for (final TileGroup g...
csn
Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
def resume(profile_process='worker'): """ Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ ...
csn
Returns the index of the first appearance of the given range of the target in the given range of the source, source, starting at the given index, using the given comparator for characters. Returns -1 if the target string is not found. @param source The source string @param sourceOffset The source offset @param sourceC...
private static int indexOf( String source, int sourceOffset, int sourceCount, String target, int targetOffset, int targetCount, int startIndex, IntBinaryOperator comparator) { int fromIndex = startIndex; // Adapted from String#indexOf if (fromIndex >...
csn
parse outputs into normalized struct @param array $outputs [address => value, ] or [[address, value], ] or [['address' => address, 'value' => value], ] @return array [['address' => address, 'value' => value], ]
public static function normalizeOutputsStruct(array $outputs) { $result = []; foreach ($outputs as $k => $v) { if (is_numeric($k)) { if (!is_array($v)) { throw new \InvalidArgumentException("outputs should be [address => value, ] or [[address, value], ] o...
csn
// Sign sends a signature request to the remote CFSSL server, // receiving a signed certificate or an error in response. // It takes the serialized JSON request to send.
func (srv *server) Sign(jsonData []byte) ([]byte, error) { return srv.request(jsonData, "sign") }
csn
// connectTLS returns a tls.Conn that has already completed the Handshake
func (d *Dialer) connectTLS(ctx context.Context, conn net.Conn) (tlsConn *tls.Conn, err error) { tlsConn = tls.Client(conn, d.TLS) errch := make(chan error) go func() { defer close(errch) errch <- tlsConn.Handshake() }() select { case <-ctx.Done(): conn.Close() tlsConn.Close() <-errch // ignore possib...
csn
Pick a random image file from a directory.
def get_random_image(img_dir): """Pick a random image file from a directory.""" images, current_wall = get_image_dir(img_dir) if len(images) > 2 and current_wall in images: images.remove(current_wall) elif not images: logging.error("No images found in directory.") sys.exit(1) ...
csn
Returns the ID the form's state is stored by in the session @param \Symfony\Component\Form\FormInterface $form @return mixed
public function getFormId(FormInterface $form) { if (is_object($form->getData())) { $ret = preg_replace('/\W/', '_', get_class($form->getData())); } else { if ($form->getName()) { return (string)$form->getName(); } else { return pre...
csn
Initializes filtering by applying all active filters through the related filter types. @param ContextInterface $context
protected function initializeFiltering(ContextInterface $context) { $activeFilters = $context->getActiveFilters(); foreach ($activeFilters as $activeFilter) { $filterName = $activeFilter->getFilterName(); if ($this->table->hasFilter($filterName)) { $this->tab...
csn
// loadConfig decodes data as a KubeProxyConfiguration object.
func (o *Options) loadConfig(data []byte) (*kubeproxyconfig.KubeProxyConfiguration, error) { configObj, gvk, err := o.codecs.UniversalDecoder().Decode(data, nil, nil) if err != nil { return nil, err } proxyConfig, ok := configObj.(*kubeproxyconfig.KubeProxyConfiguration) if !ok { return nil, fmt.Errorf("got un...
csn
// maxRevision returns the max revision number of the given list of histories
func maxRevision(histories []*apps.ControllerRevision) int64 { max := int64(0) for _, history := range histories { if history.Revision > max { max = history.Revision } } return max }
csn
Asynchronously writes a file as UTF-8 encoded text. @param {!File} file File to write @param {!string} text @param {boolean=} allowBlindWrite Indicates whether or not CONTENTS_MODIFIED errors---which can be triggered if the actual file contents differ from the FileSystem's last-known contents---should be ignored. @retu...
function writeText(file, text, allowBlindWrite) { var result = new $.Deferred(), options = {}; if (allowBlindWrite) { options.blind = true; } file.write(text, options, function (err) { if (!err) { result.resolve(); } else ...
csn
Get Revision DB Info @param integer $siteId Site Id @param string $name Page Name @param string $revisionId Revision Id @return null|array Database Result Set
public function getRevisionDbInfo($siteId, $name, $revisionId) { /** @var \Doctrine\ORM\QueryBuilder $queryBuilder */ $queryBuilder = $this->_em->createQueryBuilder() ->select( 'container,' . 'publishedRevision.revisionId,' . 'revision,' ...
csn
// errNoManager returns error describing why manager commands can't be used. // Call with read lock.
func (c *Cluster) errNoManager(st nodeState) error { if st.swarmNode == nil { if errors.Cause(st.err) == errSwarmLocked { return errSwarmLocked } if st.err == errSwarmCertificatesExpired { return errSwarmCertificatesExpired } return errors.WithStack(notAvailableError("This node is not a swarm manager. ...
csn
Handles an incoming packet. @param Packet $packet
private function handlePacket(Packet $packet) { switch ($packet->getPacketType()) { case Packet::TYPE_PUBLISH: /* @var PublishRequestPacket $packet */ $message = new DefaultMessage( $packet->getTopic(), $packet->getPayload()...
csn
Reads the first part of the file to get some essential metadata # Returns return (dict): the metadata in the header
def process_header(self, data): """ Reads the first part of the file to get some essential metadata # Returns return (dict): the metadata in the header """ metadata = { "datacolumns": data.read_chunk("I"), "firstyear": data.read_chunk("I"), ...
csn
Determine the loader based on the classname of the object @param object $source @return LoaderInterface @throws NoLoaderException
protected function determineLoaderFromClass($source): LoaderInterface { foreach ($this->loaders as $key => $loader) { if (class_exists($key) && is_a($source, $key)) { return $loader; } } $desc = get_class($source) . ' ' . gettype($source); thr...
csn
Read the device database and load.
async def load(self, mem_addr=0x0000, rec_count=0, retry=0): """Read the device database and load.""" if self._version == ALDBVersion.Null: self._status = ALDBStatus.LOADED _LOGGER.debug('Device has no ALDB') else: self._status = ALDBStatus.LOADING ...
csn
Create a Wagon archive and returns its path. Package name and version are extracted from the setup.py file of the `source` or from the PACKAGE_NAME==PACKAGE_VERSION if the source is a PyPI package. Supported `python_versions` must be in the format e.g [33, 27, 2, 3].. `force` will remove any exce...
def create(source, requirement_files=None, force=False, keep_wheels=False, archive_destination_dir='.', python_versions=None, validate_archive=False, wheel_args='', archive_format='zip', build_tag=''): """Create a Wag...
csn
Decompose a url into a prefix, path, and suffix @param $path_or_url @return array
private function decomposeUrl($path_or_url) { $result = array(); if (filter_var($path_or_url, FILTER_VALIDATE_URL)) { $url_parts = parse_url($path_or_url); $result['prefix'] = $url_parts['scheme'] . "://" . $url_parts['host']; $result['path'] = $url_parts['path']...
csn
Returns the classname of the given Route option @param string $type HTTP Request Type @param string $name Route name @return string Route class name
public function getRoute(string $type, string $name): string{ return $this->routes[$name][$type]; }
csn
This is used only if websocket fails
def toggle_sensor(request, sensorname): """ This is used only if websocket fails """ if service.read_only: service.logger.warning("Could not perform operation: read only mode enabled") raise Http404 source = request.GET.get('source', 'main') sensor = service.system.namespace[sens...
csn
Clear chat. @param string $chatId @param array $chat @return \EntWeChat\Support\Collection
public function clear($chatId, array $chat) { $params = [ 'chatid' => $chatId, 'chat' => $chat, ]; return $this->parseJSON('json', [self::API_CLEAR_NOTIFY, $params]); }
csn
A method to determine absolute path for a given relative path to the directory where this setup.py script is located
def abspath(*path): """A method to determine absolute path for a given relative path to the directory where this setup.py script is located""" setup_dir = os.path.dirname(os.path.abspath(__file__)) return os.path.join(setup_dir, *path)
csn
Returns a ZipInputStream opened with a given charset.
static ZipInputStream createZipInputStream(InputStream inStream, Charset charset) { if (charset == null) return new ZipInputStream(inStream); try { Constructor<ZipInputStream> constructor = ZipInputStream.class.getConstructor(new Class[] { InputStream.class, Charset.class }); return (ZipInput...
csn
Generates one or more streams for each name, value pair
def make_streams(name, value, boundary, encoding): """Generates one or more streams for each name, value pair""" filename = None mime = None # user passed in a special dict. if isinstance(value, collections.Mapping) and "name" in value and "value" in value: filename = value["name"] ...
csn
Get a page of indicators matching the provided filters. :param int from_time: start of time window in milliseconds since epoch (defaults to 7 days ago) :param int to_time: end of time window in milliseconds since epoch (defaults to current time) :param int page_number: the page number :...
def get_indicators_page(self, from_time=None, to_time=None, page_number=None, page_size=None, enclave_ids=None, included_tag_ids=None, excluded_tag_ids=None): """ Get a page of indicators matching the provided filters. :param int from_time: start of time window in mi...
csn
Try to decrypt a YubiKey OTP. Returns a string starting with either 'OK' or 'ERR' : 'OK counter=ab12 low=dd34 high=2a use=0a' 'ERR Unknown public_id' on YubiHSM errors (or bad OTP), only 'ERR' is returned.
def decrypt_yubikey_otp(self, from_key): """ Try to decrypt a YubiKey OTP. Returns a string starting with either 'OK' or 'ERR' : 'OK counter=ab12 low=dd34 high=2a use=0a' 'ERR Unknown public_id' on YubiHSM errors (or bad OTP), only 'ERR' is returned. """ ...
csn
Returns true if the caller and callee have declared the same @ PersistneceContext in their components.
private static final boolean parentHasSameExPc(JPAPuId parentPuIds[], JPAPuId puId) { for (JPAPuId parentPuId : parentPuIds) { if (parentPuId.equals(puId)) { return true; } } return false; }
csn
Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule's arguments are validated against this schema: {'isvalid_orcid...
def _validate_isvalid_orcid(self, isvalid_orcid, field, value): """Checks for valid ORCID if given. Args: isvalid_orcid (`bool`): flag from schema indicating ORCID to be checked. field (`str`): 'author' value (`dict`): dictionary of author metadata. The rule...
csn
Initialize the defined network and restore from files is so specified.
def _initialize_model(self): """ Initialize the defined network and restore from files is so specified. """ # Initialize all variables first self.sess.run(tf.local_variables_initializer()) self.sess.run(tf.global_variables_initializer()) if self.flags['RESTORE_META'] == 1: ...
csn
// Set inserts a key, possibly overwriting and existing entry
func (p *Pubring) Set(pk *PublicKey) error { p.Lock() defer p.Unlock() p.insert(pubKRToPB(pk)) return nil }
csn
Writes newline-terminated formatted string to reporter output stream. @private @param {string} format - `printf`-like format string @param {...*} [varArgs] - Format string arguments
function println(format, varArgs) { var vargs = Array.from(arguments); vargs[0] += '\n'; process.stdout.write(sprintf.apply(null, vargs)); }
csn
Return the query for the gql call node
def node_query(self, node): """ Return the query for the gql call node """ if isinstance(node, ast.Call): assert node.args arg = node.args[0] if not isinstance(arg, ast.Str): return else: raise TypeError(type(node))...
csn
Sets the Components. :param requisite: Set only requisite Components. :type requisite: bool
def __set_components(self, requisite=True): """ Sets the Components. :param requisite: Set only requisite Components. :type requisite: bool """ components = self.__components_manager.list_components() candidate_components = \ getattr(set(components),...
csn
Declarative Services method for setting the recovery auth data service reference @param ref reference to the service
protected void setRecoveryAuthData(ServiceReference<?> ref) { // com.ibm.websphere.security.auth.data.AuthData if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(this, tc, "setRecoveryAuthData", ref); lock.writeLock().lock(); try { recoveryAuthDataR...
csn
Sets the metadata of the Key field. @param keyMetadata the key metadata.
public void setKeyMetadata(KeyMetadata keyMetadata) { if (this.keyMetadata != null) { String format = "Class %s has two fields, %s and %s marked with %s annotation. Only one " + "field can be marked as Key. "; String message = String.format(format, entityClass.getName(), this.keyMetadata.getNa...
csn
Returns error code from given error message. @param string $errorMessage error message @return int error code
public static function getCodeByMessage(string $errorMessage): int { $code = array_search($errorMessage, self::MESSAGES); if ($code === false) { $code = self::UNKNOWN_ERROR; } return (int)$code; }
csn
Sets the custom date format to use for formatting Calendar objects to displayable strings. @param dateFormat The new DateFormat, or null to use the default format. @param numbersDateFormat The DateFormat for formatting the secondary date when both FLAG_NUMBERS and FLAG_WEEKDAY_NAMES are set, or null to use the default ...
public void setDateFormat(java.text.DateFormat dateFormat, java.text.DateFormat numbersDateFormat) { this.customDateFormat = dateFormat; this.secondaryDateFormat = numbersDateFormat; // update the spinner with the new date format: // the only spinner item that will be affected is the mo...
csn
Parse the condition type and its arguments from an options array. @param array $options @return array
protected function parseConditionOptions( $options ) { $type = $options[0]; $arguments = array_values( array_slice( $options, 1 ) ); if ( $this->isNegatedCondition( $type ) ) { return $this->parseNegatedCondition( $type, $arguments ); } if ( ! $this->conditionTypeRegistered( $type ) ) { if ( is_callab...
csn
Get the value of a persistent config key from the registry If no default is specified and the key is not found ArgumentError is raised. Args: key (string): The key name to fetch default (string): an optional value to be returned if key cannot be found Returns: ...
def get_config(self, key, default=MISSING): """Get the value of a persistent config key from the registry If no default is specified and the key is not found ArgumentError is raised. Args: key (string): The key name to fetch default (string): an optional value to be ret...
csn
// ClientHandler is the handler which serves the javascript client-side. // It can be used as an alternative of a custom http route to register the client-side javascript code, // Use the Server's `ClientSource` field instead to serve the custom code if you changed the default prefix for custom websocket events.
func ClientHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/javascript") _, err := w.Write(ClientSource) if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError) } }
csn
Preprocess data locally.
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint): """Preprocess data locally.""" import apache_beam as beam from google.datalab.utils import LambdaJob from . import _preprocess if checkpoint is None: checkpoint = _util._DEFAULT_CHECKPOINT_GSURL job_id = ('preprocess-im...
csn
Perform special logic to provide a field's default value for caching.
def _get_default_value_to_cache(self, xblock): """ Perform special logic to provide a field's default value for caching. """ try: # pylint: disable=protected-access return self.from_json(xblock._field_data.default(xblock, self.name)) except KeyError: ...
csn
Returns geocoding data for either a list of addresses or a single address represented as a string. Provides a single point of access for end users.
def geocode(self, address_data, **kwargs): """ Returns geocoding data for either a list of addresses or a single address represented as a string. Provides a single point of access for end users. """ if isinstance(address_data, list): return self.batch_geocode...
csn
Returns a VimInstanceAgent with which requests regarding VimInstances can be sent to the NFVO. @return a VimInstanceAgent
public synchronized VimInstanceAgent getVimInstanceAgent() { if (this.vimInstanceAgent == null) { if (isService) { this.vimInstanceAgent = new VimInstanceAgent( this.serviceName, this.projectId, this.sslEnabled, this.nfvoIp, ...
csn
Disconnects from a broker. @return ExtendedPromiseInterface
public function disconnect() { if (!$this->isConnected || $this->isDisconnecting) { return new RejectedPromise(new \LogicException('The client is not connected.')); } $this->isDisconnecting = true; $deferred = new Deferred(); $this->startFlow(new OutgoingDiscon...
csn
This function calculates the steps forward or backward that need to skip the virtual history states. @private
function calcStepsToRealHistory(sCurrentHash, bForward){ var iIndex = jQuery.inArray(sCurrentHash, hashHistory), i; if (iIndex !== -1) { if (bForward) { for (i = iIndex ; i < hashHistory.length ; i++) { if (!isVirtualHash(hashHistory[i])) { return i - iIndex; } } } else {...
csn
Driver-specific configuration of database connection @param array $dsn DSN for DB connections @param PDO $dbh Connection handler
protected function conn_configure($dsn, $dbh) { $init_queries = array( "ALTER SESSION SET nls_date_format = 'YYYY-MM-DD'", "ALTER SESSION SET nls_timestamp_format = 'YYYY-MM-DD HH24:MI:SS'", ); foreach ($init_queries as $query) { $stmt = oci_parse($dbh, $...
csn
Generate a secure hash from a password and a random salt. Uses the PHP {@link http://php.net/manual/en/function.crypt.php crypt()} built-in function with the Blowfish hash option. @param string $password The password to be hashed. @param int $cost Cost parameter used by the Blowfish hash algorithm. The higher the val...
public static function hashPassword($password,$cost=13) { self::checkBlowfish(); $salt=self::generateSalt($cost); $hash=crypt($password,$salt); if(!is_string($hash) || (function_exists('mb_strlen') ? mb_strlen($hash, '8bit') : strlen($hash))<32) throw new CException(Yii::t('yii','Internal error while gener...
csn
// RenderHTML renders the Category struct and its children as HTML into a buffer. // If maxDepth is negative, skip the labels to render the HTML as flat rather than nested.
func (c Category) RenderHTML(buffer *bytes.Buffer, depth int, maxDepth int) { // Check to see if this category is a leaf. // A leaf category has no other categories as it's children. isLeafCategory := true for _, child := range c.children { if _, ok := child.(*Category); ok { isLeafCategory = false break ...
csn
Detach an handler from an event. @param string $eventName @param callable $handler
public function detach($eventName, callable $handler) { if (isset($this->events[$eventName])) { $this->events[$eventName]->remove($handler); if (0 == count($this->events[$eventName])) { unset($this->events[$eventName]); } } }
csn