comment
stringlengths
16
255
code
stringlengths
52
3.87M
perform this use case
public void apply() { String in = readLineWithMessage("Delete Product with id:"); int id = Integer.parseInt(in); // We don't have a reference to the selected Product. // So first we have to lookup the object, // we do this by a query by example (QBE): // 1. build an example object with matching primary key values: Product example = new Product(); example.setId(id); // 2. build a QueryByIdentity from this sample instance: Query query = new QueryByIdentity(example); try { // start broker transaction broker.beginTransaction(); // lookup the product specified by the QBE Product toBeDeleted = (Product) broker.getObjectByQuery(query); // now ask broker to delete the object broker.delete(toBeDeleted); // commit transaction broker.commitTransaction(); } catch (Throwable t) { // rollback in case of errors broker.abortTransaction(); t.printStackTrace(); } }
// formatFields converts logrus Fields (containing arbitrary types) into a string slice.
func formatFields(fields logrus.Fields) []string { var results []string for k, v := range fields { value, ok := v.(string) if !ok { // convert non-string value into a string value = fmt.Sprint(v) } results = append(results, fmt.Sprintf("%s=%q", k, value)) } return results }
// GetPost チ-ム名と記事番号を指定して記事を取得する
func (p *PostService) GetPost(teamName string, postNumber int) (*PostResponse, error) { var postRes PostResponse postNumberStr := strconv.Itoa(postNumber) postURL := PostURL + "/" + teamName + "/posts" + "/" + postNumberStr res, err := p.client.get(postURL, url.Values{}, &postRes) if err != nil { return nil, err } defer res.Body.Close() return &postRes, nil }
// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int { c.mux.Lock() // Lock so only one goroutine at a time can access the map c.v. defer c.mux.Unlock() return c.v[key] }
// NewStringMap returns a new StringMap
func NewStringMap(name string) *StringMap { v := &StringMap{values: make(map[string]string)} Publish(name, v) return v }
Return a reverse ordering by upper endpoint over ranges. @param <C> range endpoint type @return a reverse ordering by upper endpoint over ranges
public static <C extends Comparable> Ordering<Range<C>> reverseOrderingByUpperEndpoint() { Ordering<Range<C>> orderingByUpperEndpoint = orderingByUpperEndpoint(); return orderingByUpperEndpoint.reverse(); }
almost same as mailflute
protected SqlAnalyzer createSqlAnalyzer(String templateText, boolean blockNullParameter) { final SqlAnalyzer analyzer = new SqlAnalyzer(templateText, blockNullParameter) { @Override protected String filterAtFirst(String sql) { return sql; // keep body } @Override protected EmbeddedVariableNode newEmbeddedVariableNode(String expr, String testValue, String specifiedSql, boolean blockNullParameter, NodeAdviceFactory adviceFactory, boolean replaceOnly, boolean terminalDot, boolean overlookNativeBinding) { return createTemplikeEmbeddedVariableNode(expr, testValue, specifiedSql, blockNullParameter, adviceFactory, replaceOnly, terminalDot, overlookNativeBinding); } }.overlookNativeBinding().switchBindingToReplaceOnlyEmbedded(); // adjust for plain template return analyzer; }
Scans the current installation and picks up all the SilverStripe modules that contain a `docs` folder. @return void
public function populateEntitiesFromInstall() { if ($this->automaticallyPopulated) { // already run return; } foreach (scandir(BASE_PATH) as $key => $entity) { if ($key == "themes") { continue; } $dir = DocumentationHelper::normalizePath(Controller::join_links(BASE_PATH, $entity)); if (is_dir($dir)) { // check to see if it has docs $docs = Controller::join_links($dir, 'docs'); if (is_dir($docs)) { $entities[] = array( 'Path' => $docs, 'Title' => DocumentationHelper::clean_page_name($entity), 'Version' => 'master', 'Branch' => 'master', 'Stable' => true ); } } } Config::inst()->update( 'DocumentationManifest', 'register_entities', $entities ); $this->automaticallyPopulated = true; }
This will get the model. There is no order for the arguments. @params string path to the model @params array data to send to the model @return $this
public function set_cached_model(){ $args = \func_get_args(); $die = 1; foreach ( $args as $a ){ if ( \is_string($a) && \strlen($a) ){ $path = $a; } else if ( \is_array($a) ){ $data = $a; } else if ( \is_int($a) ){ $ttl = $a; } else if ( \is_bool($a) ){ $die = $a; } } if ( !isset($path) ){ $path = $this->path; } else if ( strpos($path, './') === 0 ){ $path = $this->say_dir().substr($path, 1); } if ( !isset($data) ){ $data = $this->data; } if ( !isset($ttl) ){ $ttl = 10; } $this->mvc->set_cached_model($path, $data, $this, $ttl); return $this; }
Send a message to the google chat room specified in the webhook url. .. code-block:: bash salt '*' google_chat.send_message "https://chat.googleapis.com/v1/spaces/example_space/messages?key=example_key" "This is a test message"
def send_message(url, message): ''' ''' headers = {'Content-Type': 'application/json'} data = {'text': message} result = __utils__['http.query'](url, 'POST', data=json.dumps(data), header_dict=headers, decode=True, status=True) if result.get('status', 0) == 200: return True else: return False
// move returns the cell in the direction dir from position r, c. // It returns ok==false if there is no cell in that direction.
func (m *Maze) move(x, y int, dir Dir) (nx, ny int, ok bool) { nx = x + dirs[dir].δx ny = y + dirs[dir].δy ok = 0 <= nx && nx < m.w && 0 <= ny && ny < m.h return }
@param $repository @param $type @param $format @return \PUGX\Badge\Model\Badge
public function createDownloadsBadge($repository, $type, $format) { return $this->createBadgeFromRepository($repository, self::SUBJECT, self::COLOR, $format, $type); }
Returns an array of payment methods @return array
protected function getListPayment() { $id = $this->getParam(0); if (!isset($id)) { $list = $this->payment->getList(); $this->limitArray($list); return $list; } $method = $this->payment->get($id); if (empty($method)) { $this->errorAndExit($this->text('Unexpected result')); } return array($method); }
Marshall the given parameter object.
public void marshall(HierarchyLevel hierarchyLevel, ProtocolMarshaller protocolMarshaller) { if (hierarchyLevel == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(hierarchyLevel.getId(), ID_BINDING); protocolMarshaller.marshall(hierarchyLevel.getArn(), ARN_BINDING); protocolMarshaller.marshall(hierarchyLevel.getName(), NAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Compute E3 pixel. @param a The a value. @param b The b value. @param d The d value. @param e The e value. @param g The g value. @param h The h value. @return The computed value.
private static int computeE3(int a, int b, int d, int e, int g, int h) { if (d == b && e != g || d == h && e != a) { return d; } return e; }
check command line Judge the target platforms. if the command line includes platform names, call grunt cordova_register_platform:<platform>. see '$ cordova compile --help'
function parsePlatforms() { var supportPlatforms = [ { platform: 'android', regexp: /android/ig }, { platform: 'ios', regexp: /ios/ig }, { platform: 'firefoxos', regexp: /firefoxos/ig }, { platform: 'windows8', regexp: /windows8/ig }, { platform: 'browser', regexp: /browser/ig }, { platform: 'amazon-fireos', regexp: /amazon-fireos/ig }, { platform: 'blackberry10', regexp: /blackberry10/ig }, { platform: 'windows', regexp: /windows/ig }, { platform: 'wp8', regexp: /wp8/ig }, ]; var gruntTasks = []; supportPlatforms.forEach(function (checker) { if (null != _cmdline.match(checker.regexp)) { gruntTasks.push('cordova_register_platform:' + checker.platform); } }); return gruntTasks; }
Start the service. This causes a transition to the C{'idle'} state, and then calls L{connect} to attempt an initial conection.
def startService(self): service.Service.startService(self) self._toState('idle') try: self.connect() except NoConsumerError: pass
Sets tenant context data. Must be called after {@link #setTenant}. @param data data to set into context
void setData(Map<String, Object> data) { Objects.requireNonNull(data, "data can't be null"); // @adovbnya DO NOT CHANGE !!!! // allow tenant change only from initial (empty) value or only from super tenant if (this.dataMap.isEmpty()) { this.dataMap = ValueHolder.valueOf(data); } else if (!Objects.equals(this.dataMap.get(), data)) { if (!this.tenant.isPresent()) { throw new IllegalStateException("Tenant doesn't set in context yet"); } if (this.tenant.get().isSuper()) { this.dataMap = ValueHolder.valueOf(data); } else { StackTraceElement[] traces = Thread.currentThread().getStackTrace(); if (!isAllowedToChangeTenant(traces)) { throw new IllegalStateException("Trying to set the data from " + this.dataMap.get() + " to " + data); } } } }
// NewListTask instantiates a new *ListTask instance with the given message.
func NewListTask(msg string) *ListTask { return &ListTask{ msg: msg, ch: make(chan *Update, 1), } }
Build SQL query for a filter @param string $field @param string $type @param string $filter @param mixed $value @return boolean True on success
protected function buildFilter($field, $type, $filter, $value) { if (strlen($field) == 0) throw new \Exception("Empty 'field'"); if (strlen($type) == 0) throw new \Exception("Empty 'type'"); if ($type == Table::TYPE_DATETIME) { if ($filter == Table::FILTER_BETWEEN && is_array($value) && count($value) == 2) { $value = [ $value[0] ? new \DateTime('@' . $value[0]) : null, $value[1] ? new \DateTime('@' . $value[1]) : null, ]; if ($value[0] && $this->getDbTimezone()) $value[0]->setTimezone(new \DateTimeZone($this->getDbTimezone())); if ($value[1] && $this->getDbTimezone()) $value[1]->setTimezone(new \DateTimeZone($this->getDbTimezone())); } else if ($filter != Table::FILTER_BETWEEN && !is_array($value)) { $value = new \DateTime('@' . $value); if ($this->getDbTimezone()) $value->setTimezone(new \DateTimeZone($this->getDbTimezone())); } else { return false; } } else { if ($filter == Table::FILTER_BETWEEN) { if (!is_array($value) || count($value) != 2) return false; } else if (is_array($value)) { return false; } } if (!isset($this->sqlAnds[$field])) $this->sqlAnds[$field] = []; $paramBaseName = 'dt_' . str_replace('.', '_', $field); switch ($filter) { case Table::FILTER_LIKE: $param = ':' . $paramBaseName . '_like'; $this->sqlAnds[$field][] = "$field LIKE $param"; $this->sqlParams[$param] = '%' . $value . '%'; break; case Table::FILTER_EQUAL: $param = ':' . $paramBaseName . '_equal'; $this->sqlAnds[$field][] = "$field = $param"; $this->sqlParams[$param] = $value; break; case Table::FILTER_BETWEEN: $ands = []; if ($value[0] !== null) { $param = ':' . $paramBaseName . '_begin'; $ands[] = "$field >= $param"; $this->sqlParams[$param] = $value[0]; } if ($value[1] !== null) { $param = ':' . $paramBaseName . '_end'; $ands[] = "$field <= $param"; $this->sqlParams[$param] = $value[1]; } $this->sqlAnds[$field][] = join(' AND ', $ands); break; case Table::FILTER_NULL: $this->sqlAnds[$field][] = "$field IS NULL"; break; default: throw new \Exception("Unknown filter: $filter"); } return true; }
Method ignoring GenerateDeployment events if deployment is already done. @param eventContext Event to check
public void blockGenerateDeploymentWhenNeeded(@Observes EventContext<GenerateDeployment> eventContext) { if (!extensionEnabled()) { eventContext.proceed(); } else if (suiteDeploymentGenerated) { // Do nothing with event. debug("Blocking GenerateDeployment event {0}", eventContext.getEvent().toString()); } else { suiteDeploymentGenerated = true; debug("NOT Blocking GenerateDeployment event {0}", eventContext.getEvent().toString()); eventContext.proceed(); } }
// SetProcessName sets the ProcessName field's value.
func (s *AwsSecurityFindingFilters) SetProcessName(v []*StringFilter) *AwsSecurityFindingFilters { s.ProcessName = v return s }
A set operation at the hive level (full path).
async def set(self, full, valu): ''' ''' node = await self._getHiveNode(full) oldv = node.valu node.valu = await self.storNodeValu(full, valu) await node.fire('hive:set', path=full, valu=valu, oldv=oldv) return oldv
This will get a view. @param string $path @param string $mode @param array $data @return string|false
public function get_view(string $path, string $mode = 'html', array $data=null){ if ( !router::is_mode($mode) ){ die("Incorrect mode $path $mode"); } $view = null; if ( $this->has_view($path, $mode) ){ $view = self::$loaded_views[$mode][$path]; } else if ( $info = $this->router->route($path, $mode) ){ $view = new mvc\view($info); $this->add_to_views($path, $mode, $view); } if ( \is_object($view) && $view->check() ){ return \is_array($data) ? $view->get($data) : $view->get(); } return ''; }
Adds an embed field. @param EmbeddedPropMetadata $embed @return self
public function addEmbed(EmbeddedPropMetadata $embed) { $this->validateEmbed($embed); $this->embeds[$embed->getKey()] = $embed; ksort($this->embeds); return $this; }
A simple demo to be used from command line.
def _main(): import sys def log(message): print(message) def print_usage(): log('usage: %s <application key> <application secret> send <number> <message> <from_number>' % sys.argv[0]) log(' %s <application key> <application secret> status <message_id>' % sys.argv[0]) if len(sys.argv) > 4 and sys.argv[3] == 'send': key, secret, number, message = sys.argv[1], sys.argv[2], sys.argv[4], sys.argv[5] client = SinchSMS(key, secret) if len(sys.argv) > 6: log(client.send_message(number, message, sys.argv[6])) else: log(client.send_message(number, message)) elif len(sys.argv) > 3 and sys.argv[3] == 'status': key, secret, message_id = sys.argv[1], sys.argv[2], sys.argv[4] client = SinchSMS(key, secret) log(client.check_status(message_id)) else: print_usage() sys.exit(1) sys.exit(0)
Initializes the sub handlers maps for the given value count.<p> @param count the value count
protected void initHandlers(int count) { if (count == 0) { m_handlers.clear(); } else { while (m_handlers.size() < count) { m_handlers.add(new HashMap<String, CmsAttributeHandler>()); } } m_handlerById.clear(); }
Check for inital comment and patterns that distinguish Rexx from other C-like languages.
def analyse_text(text): if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE): # Header matches MVS Rexx requirements, this is certainly a Rexx # script. return 1.0 elif text.startswith('/*'): # Header matches general Rexx requirements; the source code might # still be any language using C comments such as C++, C# or Java. lowerText = text.lower() result = sum(weight for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS if pattern.search(lowerText)) + 0.01 return min(result, 1.0)
Use this API to add clusternodegroup resources.
public static base_responses add(nitro_service client, clusternodegroup resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { clusternodegroup addresources[] = new clusternodegroup[resources.length]; for (int i=0;i<resources.length;i++){ addresources[i] = new clusternodegroup(); addresources[i].name = resources[i].name; addresources[i].strict = resources[i].strict; } result = add_bulk_request(client, addresources); } return result; }
var RE_full_content = new RegExp('<(' + full_content_tags.join('|') + ')[^>]*>|<\\/(' + full_content_tags.join('|') + ')>', 'g');
function _cleanNodes (nodes) { nodes.forEach(function (tag) { // avoiding circular structure delete tag._parent; // removing temporary tester delete tag.match_closer; // cleaning empty attributes if( tag.attrs && Object.keys(tag.attrs).length === 0 ) delete tag.attrs; // cleaning empty children if( tag._ instanceof Array ) { if( !tag._.length ) delete tag._; else _cleanNodes(tag._); } }); return nodes; }
----------------------------------------------------------------------
public static function splitStringToQRinput($string, QRinput $input, $modeHint, $casesensitive = true) { if(is_null($string) || $string == '\0' || $string == '') { throw new Exception('empty string!!!'); } $split = new QRsplit($string, $input, $modeHint); if(!$casesensitive) $split->toUpper(); return $split->splitString(); }
// ContainerCDNDisable disables CDN access to a container.
func (c *RsConnection) ContainerCDNDisable(container string) error { h := swift.Headers{"X-CDN-Enabled": "false"} _, _, err := c.manage(swift.RequestOpts{ Container: container, Operation: "PUT", ErrorMap: swift.ContainerErrorMap, NoResponse: true, Headers: h, }) return err }
// SetRequesterPays sets the RequesterPays field's value.
func (s *UpdateNFSFileShareInput) SetRequesterPays(v bool) *UpdateNFSFileShareInput { s.RequesterPays = &v return s }
Add HashTable item @param PHPExcel_IComparable $pSource Item to add @throws PHPExcel_Exception
public function add(PHPExcel_IComparable $pSource = null) { $hash = $pSource->getHashCode(); if (!isset($this->items[$hash])) { $this->items[$hash] = $pSource; $this->keyMap[count($this->items) - 1] = $hash; } }
Match a URL to a registered pattern. :param url: URL :return: Matched route :raises kua.RouteError: If there is no match
def match(self, url: str) -> RouteResolved: url = normalize_url(url) parts = self._deconstruct_url(url) return self._match(parts)
Edit form submit
public function editTransversalSubmit(array &$form, FormStateInterface $form_state) { if (!$this->manager->getSiteContext()->isTemporary()) { // @todo Generate a better token (random). $token = drupal_get_token(); $layout = $this->manager->getSiteContext()->getCurrentLayout(); $this->manager->getSiteContext()->setToken($token); // Saving the layout will force it be saved in the temporary storage. $this->manager->getSiteContext()->getStorage()->save($layout); $form_state->setRedirect( current_path(), ['query' => [ContextManager::PARAM_SITE_TOKEN => $token] + drupal_get_query_parameters()] ); } }
// IndexFunc renders a colon separated list enclosed by square brackets. Use for array / slice indexes and definitions.
func (g *Group) IndexFunc(f func(*Group)) *Statement { s := IndexFunc(f) g.items = append(g.items, s) return s }
Adds the members of newArray to the list if they are not already members of the array.
public void union(IntArray newArray) { for (int i = 0; i < newArray._size; i++) { if (! contains(newArray._data[i])) add(newArray._data[i]); } }
// GroupTransactionsIntoBundles groups the given transactions into groups of bundles. // Note that the same bundle can exist in the return slice multiple times, though they // are reattachments of the same transfer.
func GroupTransactionsIntoBundles(txs transaction.Transactions) Bundles { bundles := Bundles{} for i := range txs { tx := &txs[i] if tx.CurrentIndex != 0 { continue } bundle := Bundle{*tx} lastIndex := int(tx.LastIndex) current := tx for x := 1; x <= lastIndex; x++ { // get all txs belonging into this bundle found := false for j := range txs { if current.Bundle != txs[j].Bundle || txs[j].CurrentIndex != current.CurrentIndex+1 || current.TrunkTransaction != txs[j].Hash { continue } found = true bundle = append(bundle, txs[j]) current = &txs[j] break } if !found { break } } bundles = append(bundles, bundle) } return bundles }
// ReadWait sets the amount of time to wait before a websocket read times out. // It should only be used in the constructor - not Goroutine-safe.
func ReadWait(readWait time.Duration) func(*wsConnection) { return func(wsc *wsConnection) { wsc.readWait = readWait } }
Do a full refresh of all devices and automations.
def refresh(self): """""" self.get_devices(refresh=True) self.get_automations(refresh=True)
生成 @author nash.tang <112614251@qq.com>
public function run() { if(Schema::hasTable(strtolower($this->model))) { $tableName = strtolower($this->model); }elseif(Schema::hasTable(strtolower($this->model)."s")) { $tableName = strtolower($this->model."s"); }else{ $tableName = ""; } $module = camel_case($this->module); $model = camel_case($this->model); $templatePath = $this->customTemplate ?: __DIR__."/template/model.blade.php"; $view = View::file($templatePath, [ "group" => $this->group, "module" => $module, "model" => $model, "tableName" => $tableName, "primaryKey" => "id" ]); $filePath = "Models/".ucfirst($model).".php"; if(!is_dir(app_path("Models/"))) { mkdir(app_path("Models/")); } if(!file_exists(app_path($filePath))) { file_put_contents(app_path($filePath), "<?php \n\n" . $view->render()); }else{ if($this->mode == "overwrite") { file_put_contents(app_path($filePath), "<?php \n\n" . $view->render()); } } }
Emit one line of the error message report. By default, error messages are printed to System.err. Subclasses may override. @param line one line of the error report
@Override protected void emitLine(String line) { if (writer == null) { super.emitLine(line); return; } line = line.replaceAll("\t", " "); writer.println(line); }
Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Password.
def __set_revlookup_auth_string(self, username, password): ''' ''' auth = b2handle.utilhandle.create_authentication_string(username, password) self.__revlookup_auth_string = auth
Create a form from an object. @param string|object $entity @return \CmsCommon\Form\FormInterface
public function createForm($entity) { $formSpec = ArrayUtils::iteratorToArray($this->getFormSpecification($entity)); if (!isset($formSpec['options']['merge_input_filter'])) { $formSpec['options']['merge_input_filter'] = true; } return $this->getFormFactory()->createForm($formSpec); }
Paints the barcode. If no exception was thrown a valid barcode is available.
public void paintCode() { int maxErr, lenErr, tot, pad; if ((options & PDF417_USE_RAW_CODEWORDS) != 0) { if (lenCodewords > MAX_DATA_CODEWORDS || lenCodewords < 1 || lenCodewords != codewords[0]) { throw new IllegalArgumentException("Invalid codeword size."); } } else { if (text == null) throw new NullPointerException("Text cannot be null."); if (text.length > ABSOLUTE_MAX_TEXT_SIZE) { throw new IndexOutOfBoundsException("The text is too big."); } segmentList = new SegmentList(); breakString(); //dumpList(); assemble(); segmentList = null; codewords[0] = lenCodewords = cwPtr; } maxErr = maxPossibleErrorLevel(MAX_DATA_CODEWORDS + 2 - lenCodewords); if ((options & PDF417_USE_ERROR_LEVEL) == 0) { if (lenCodewords < 41) errorLevel = 2; else if (lenCodewords < 161) errorLevel = 3; else if (lenCodewords < 321) errorLevel = 4; else errorLevel = 5; } if (errorLevel < 0) errorLevel = 0; else if (errorLevel > maxErr) errorLevel = maxErr; if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) codeRows = 90; lenErr = 2 << errorLevel; boolean fixedColumn = (options & PDF417_FIXED_ROWS) == 0; boolean skipRowColAdjust = false; tot = lenCodewords + lenErr; if ((options & PDF417_FIXED_RECTANGLE) != 0) { tot = codeColumns * codeRows; if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } if (tot < lenCodewords + lenErr) tot = lenCodewords + lenErr; else skipRowColAdjust = true; } else if ((options & (PDF417_FIXED_COLUMNS | PDF417_FIXED_ROWS)) == 0) { double c, b; fixedColumn = true; if (aspectRatio < 0.001) aspectRatio = 0.001f; else if (aspectRatio > 1000) aspectRatio = 1000; b = 73 * aspectRatio - 4; c = (-b + Math.sqrt(b * b + 4 * 17 * aspectRatio * (lenCodewords + lenErr) * yHeight)) / (2 * 17 * aspectRatio); codeColumns = (int)(c + 0.5); if (codeColumns < 1) codeColumns = 1; else if (codeColumns > 30) codeColumns = 30; } if (!skipRowColAdjust) { if (fixedColumn) { codeRows = (tot - 1) / codeColumns + 1; if (codeRows < 3) codeRows = 3; else if (codeRows > 90) { codeRows = 90; codeColumns = (tot - 1) / 90 + 1; } } else { codeColumns = (tot - 1) / codeRows + 1; if (codeColumns > 30) { codeColumns = 30; codeRows = (tot - 1) / 30 + 1; } } tot = codeRows * codeColumns; } if (tot > MAX_DATA_CODEWORDS + 2) { tot = getMaxSquare(); } errorLevel = maxPossibleErrorLevel(tot - lenCodewords); lenErr = 2 << errorLevel; pad = tot - lenErr - lenCodewords; if ((options & PDF417_USE_MACRO) != 0) { // the padding comes before the control block System.arraycopy(codewords, macroIndex, codewords, macroIndex + pad, pad); cwPtr = lenCodewords + pad; while (pad-- != 0) codewords[macroIndex++] = TEXT_MODE; } else { cwPtr = lenCodewords; while (pad-- != 0) codewords[cwPtr++] = TEXT_MODE; } codewords[0] = lenCodewords = cwPtr; calculateErrorCorrection(lenCodewords); lenCodewords = tot; outPaintCode(); }
@param string $eventName @param object $fileReference @param FileMetadata $metadata @return IUploadEvent
public function dispatch($eventName, $fileReference, FileMetadata $metadata) { $event = new UploadEvent($fileReference, $metadata); foreach ($this->listeners[$eventName] as $listener) { call_user_func($listener, $event); } foreach ($this->subscribers as $subscriber) { $events = $subscriber->getSubscribedEvents(); if (!isset($events[$eventName])) { continue; } call_user_func([$subscriber, $events[$eventName]], $event); } return $event; }
// IsAllowedNetwork returns true if the given host (IP or resolvable // hostname) is in the set of allowed networks (CIDR format only).
func IsAllowedNetwork(host string, allowed []string) bool { if hostNoPort, _, err := net.SplitHostPort(host); err == nil { host = hostNoPort } addr, err := net.ResolveIPAddr("ip", host) if err != nil { return false } for _, n := range allowed { result := true if strings.HasPrefix(n, "!") { result = false n = n[1:] } _, cidr, err := net.ParseCIDR(n) if err != nil { continue } if cidr.Contains(addr.IP) { return result } } return false }
Extends a service definition. @param string $name @param callable $callable @param boolean $strict @return callable @throws InvalidArgumentException
public function extend($name, $callable, $strict = true) { if (!$this->services->has($name)) { if ($strict) { throw new InvalidArgumentException(sprintf('Service "%s" is not defined.', $name)); } else { return false; } } $factory = $this->services->get($name); if (!is_object($factory) || !method_exists($factory, '__invoke')) { throw new InvalidArgumentException(sprintf('Service "%s" does not contain an object definition.', $name)); } if (!is_object($callable) || !method_exists($callable, '__invoke')) { throw new InvalidArgumentException('Extension service definition is not a Closure or invokable object.'); } $extended = function($c) use($callable, $factory) { /** @var Closure $factory */ return $callable($factory($c), $c); }; if ($this->factories->contains($factory)) { $this->factories->detach($factory); $this->factories->attach($extended); } $this->services->unlock($name); $this->services->set($name, $extended); return $this->services->get($name); }
Pushes request data to the open http connection @param connection - the open connection of the http call @param request - the parameters to be passed to the endpoint for the service call
private void writeJsonDataRequest(HttpURLConnection connection, Request request) { try (OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream())) { wr.write(request.getJsonPayload().toString()); wr.flush(); } catch (IOException e) { log.error(e); } }
transforms `<div><tag @element/></tag><div>` and `<div><@element/></div>` into valid HTML. and then creates a DOM Element
function createDomElementFromTemplate(html) { //match container markers like <@element/> let containerTags = html.match(rContainerGlobal) || []; for (let containerTag of containerTags) { let [, containerName, attrs = ''] = rContainer.exec(containerTag); let template = `<script type="x" ${ATTR}="${containerName}">${attrs.trim()}</script>`; html = html.split(containerTag).join(template); } //match attribute markers like <span @element></span> let allTags = html.match(rTags) || []; for (let tag of allTags) { let result = rAttr.exec(tag); if (result) { let elName = result[1]; html = html.split(tag).join(tag.replace(`@${elName}`, `${ATTR}="${elName}"`)); } } return $.create(html.trim()); }
Create options for the find query. Note that these are separate from the options for executing the command, which are created in createExecuteOptions(). @return array
private function createQueryOptions() { $options = []; if (isset($this->options['cursorType'])) { if ($this->options['cursorType'] === self::TAILABLE) { $options['tailable'] = true; } if ($this->options['cursorType'] === self::TAILABLE_AWAIT) { $options['tailable'] = true; $options['awaitData'] = true; } } foreach (['allowPartialResults', 'batchSize', 'comment', 'hint', 'limit', 'maxAwaitTimeMS', 'maxScan', 'maxTimeMS', 'noCursorTimeout', 'oplogReplay', 'projection', 'readConcern', 'returnKey', 'showRecordId', 'skip', 'snapshot', 'sort'] as $option) { if (isset($this->options[$option])) { $options[$option] = $this->options[$option]; } } foreach (['collation', 'max', 'min'] as $option) { if (isset($this->options[$option])) { $options[$option] = (object) $this->options[$option]; } } $modifiers = empty($this->options['modifiers']) ? [] : (array) $this->options['modifiers']; if ( ! empty($modifiers)) { $options['modifiers'] = $modifiers; } return $options; }
Adds a column, or array of column names that would be used for an INSERT INTO statement. @param mixed $columns A column name, or array of column names. @return Query Returns this object to allow chaining.
public function columns($columns) { if ( is_null($this->columns) ){ $this->columns = new Element('()', $columns); } else { $this->columns->append($columns); } return $this; }
Before save event. @throws \yii\base\InvalidConfigException
public function beforeSave() { if ($this->file instanceof UploadedFile) { if (true !== $this->owner->isNewRecord) { /** @var ActiveRecord $oldModel */ $oldModel = $this->owner->findOne($this->owner->primaryKey); $behavior = static::getInstance($oldModel, $this->attribute); $behavior->cleanFiles(); } $this->owner->{$this->attribute} = implode('.', array_filter([$this->file->baseName, $this->file->extension]) ); } else { if (true !== $this->owner->isNewRecord && empty($this->owner->{$this->attribute})) { $this->owner->{$this->attribute} = ArrayHelper::getValue($this->owner->oldAttributes, $this->attribute, null); } } }
Retrieve a list of the available P3 project names from a directory. @param directory directory containing P3 files @return list of project names
public static final List<String> listProjectNames(File directory) { List<String> result = new ArrayList<String>(); File[] files = directory.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toUpperCase().endsWith("STR.P3"); } }); if (files != null) { for (File file : files) { String fileName = file.getName(); String prefix = fileName.substring(0, fileName.length() - 6); result.add(prefix); } } Collections.sort(result); return result; }
Searches for a command of the passed-in type and if found removes it from the user's PLF.
private static void removeDirective( String elementId, String attributeName, String type, IPerson person) { Document plf = (Document) person.getAttribute(Constants.PLF); Element node = plf.getElementById(elementId); if (node == null) return; Element editSet = null; try { editSet = getEditSet(node, plf, person, false); } catch (Exception e) { /* * we should never get here since we are calling getEditSet passing * create=false meaning that the only portion of that method that * tosses an exception will not be reached with this call. But if a * runtime exception somehow occurs we will log it so that we don't * lose the information. */ LOG.error(e, e); return; } // if no edit set then the edit can't be there either if (editSet == null) return; Node child = editSet.getFirstChild(); while (child != null) { if (child.getNodeName().equals(type)) { Attr attr = ((Element) child).getAttributeNode(Constants.ATT_NAME); if (attr != null && attr.getValue().equals(attributeName)) { // we found it, remove it editSet.removeChild(child); break; } } child = child.getNextSibling(); } // if that was the last on in the edit set then delete it if (editSet.getFirstChild() == null) node.removeChild(editSet); }
// Geometry retrieves an up-to-date version of the this window's geometry. // It also loads the geometry into the Geom member of Window.
func (w *Window) Geometry() (xrect.Rect, error) { geom, err := RawGeometry(w.X, xproto.Drawable(w.Id)) if err != nil { return nil, err } w.Geom = geom return geom, err }
A mutable builder for a {@link Metadata} object. @param r the resource @return a builder for a {@link Metadata} object
public static Builder builder(final Resource r) { return builder(r.getIdentifier()).interactionModel(r.getInteractionModel()) .container(r.getContainer().orElse(null)) .memberRelation(r.getMemberRelation().orElse(null)) .membershipResource(r.getMembershipResource().orElse(null)) .memberOfRelation(r.getMemberOfRelation().orElse(null)) .insertedContentRelation(r.getInsertedContentRelation().orElse(null)); }
// GenerateWithPrefix generates a string with a given prefix then a given number of randomly selected characters.
func GenerateWithPrefix(prefix string, characters uint8) string { return Prefixed{Prefix: prefix, Len: characters}.Generate() }
Handles help requests.
def _HandleHelp(self, request): """""" help_path = request.path.split("/", 2)[-1] if not help_path: raise werkzeug_exceptions.Forbidden("Error: Invalid help path.") # Proxy remote documentation. return self._RedirectToRemoteHelp(help_path)
Marshall the given parameter object.
public void marshall(EndpointSendConfiguration endpointSendConfiguration, ProtocolMarshaller protocolMarshaller) { if (endpointSendConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(endpointSendConfiguration.getBodyOverride(), BODYOVERRIDE_BINDING); protocolMarshaller.marshall(endpointSendConfiguration.getContext(), CONTEXT_BINDING); protocolMarshaller.marshall(endpointSendConfiguration.getRawContent(), RAWCONTENT_BINDING); protocolMarshaller.marshall(endpointSendConfiguration.getSubstitutions(), SUBSTITUTIONS_BINDING); protocolMarshaller.marshall(endpointSendConfiguration.getTitleOverride(), TITLEOVERRIDE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
// WriteFileFromReader creates and uploads a "file" JSON schema // composed of chunks of r, also uploading the chunks. The returned // BlobRef is of the JSON file schema blob. // The filename is optional.
func WriteFileFromReader(ctx context.Context, bs blobserver.StatReceiver, filename string, r io.Reader) (blob.Ref, error) { return WriteFileFromReaderWithModTime(ctx, bs, filename, time.Time{}, r) }
Run the module setup This method will be called if the ZFTool setup modules command will be executed.
public function runSetup() { if ($this->params->forceIsActive) { $this->createRootCategory() ->createDefaultTypes() ->createDefaultPriorities(); } if ($this->getParams()->createSampleData) { $this->createSampleData(); } }
Return an existing AuthTicket for a given service.
def get_ticket(self, service): """""" return self.auth_tickets \ .filter(expires__gt=datetime.now(timezone.utc), service=service) \ .last()
Determine directory to log import/export reports to
private File determineLogDirectory(final BatchOptions options, String operation) { File logDirectoryParent = options != null ? options.getLogDirectoryParent() : null; if (logDirectoryParent == null) { logDirectoryParent = Files.createTempDir(); } File logDirectory = new File(logDirectoryParent, "data-" + operation + "-reports"); try { logDirectory = logDirectory.getCanonicalFile(); FileUtils.deleteDirectory(logDirectory); } catch (IOException e) { throw new RuntimeException( "Failed to clean data-" + operation + " log directory: " + logDirectory, e); } logDirectory.mkdirs(); return logDirectory; }
Sets the oauth_client attribute
def set_oauth_client(self, consumer_key, consumer_secret): self.oauth_client = oauth1.Client(consumer_key, consumer_secret)
Synchronize and redraw the Pager UI if necessary. @method syncPagerUi @private
function syncPagerUi(page) { var carousel = this, numPages, numVisible; // Don't do anything if the Carousel is not rendered if (!carousel._hasRendered) { return; } numVisible = carousel.get("numVisible"); if (!JS.isNumber(page)) { page = Math.floor(carousel.get("selectedItem") / numVisible); } numPages = Math.ceil(carousel.get("numItems") / numVisible); carousel._pages.num = numPages; carousel._pages.cur = page; if (numPages > carousel.CONFIG.MAX_PAGER_BUTTONS) { carousel._updatePagerMenu(); } else { carousel._updatePagerButtons(); } }
Iterate over all items in the store.
function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { try { var keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; for (var i = 0; i < length; i++) { var key = localStorage.key(i); var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = _deserialize(value); } value = iterator(value, key.substring(keyPrefixLength)); if (value !== void(0)) { resolve(value); return; } } resolve(); } catch (e) { reject(e); } })["catch"](reject); }); executeCallback(promise, callback); return promise; }
Attepmt to parse an ISO8601 formatted duration based on a start datetime. Accepts a ``duration`` and a start ``datetime``. ``duration`` must be an ISO8601 formatted string. Returns a ``datetime.timedelta`` object.
def parse_duration_with_start(start, duration): elements = _parse_duration_string(_clean(duration)) year, month = _year_month_delta_from_elements(elements) end = start.replace( year=start.year + year, month=start.month + month ) del elements['years'] del elements['months'] end += _timedelta_from_elements(elements) return start, end - start
Validate as integer. @param int|string $number The integer to check @param int $min The minimum integer value @param int $max The maximum integer value @return bool
public function isInteger($number, int $min = null, int $max = null): bool { return isset($min) || isset($max) ? filter_var($number, FILTER_VALIDATE_INT, $this->getIntegerOptionsBetween($min, $max)) : filter_var($number, FILTER_VALIDATE_INT); }
@param SerializerInterface|null $serializer @return SerializerInterface
protected static function prepareSerializer(SerializerInterface $serializer = null) { if (null === $serializer) { $serializer = SerializerFactory::create(); } return $serializer; }
Changes group's approval mode :param require_admin_approval: True or False :param thread_id: Group ID to remove people from. See :ref:`intro_threads` :raises: FBchatException if request failed
def changeGroupApprovalMode(self, require_admin_approval, thread_id=None): thread_id, thread_type = self._getThread(thread_id, None) data = {"set_mode": int(require_admin_approval), "thread_fbid": thread_id} j = self._post(self.req_url.APPROVAL_MODE, data, fix_request=True, as_json=True)
SLIDE 5: Bar Chart: Data Series Colors, majorUnits, and valAxisLabelFormatCode ------
function slide5() { var slide = pptx.addNewSlide(); slide.addNotes('API Docs: https://gitbrent.github.io/PptxGenJS/docs/api-charts.html'); slide.addTable( [ [{ text:'Chart Examples: Multi-Color Bars, `catLabelFormatCode`, `valAxisMajorUnit`, `valAxisLabelFormatCode`', options:gOptsTextL },gOptsTextR] ], gOptsTabOpts ); // TOP-LEFT slide.addChart( pptx.charts.BAR, [ { name : 'Labels are Excel Date Values', labels: [37987,38018,38047,38078,38108,38139], values: [20, 30, 10, 25, 15, 5] } ], { x:0.5, y:0.6, w:'45%', h:3, barDir: 'bar', chartColors: ['0077BF','4E9D2D','ECAA00','5FC4E3','DE4216','154384'], catLabelFormatCode: "yyyy-mm", valAxisMajorUnit: 15, valAxisMaxVal: 45, showTitle: true, titleFontSize: 14, titleColor: '0088CC', title: 'Bar Charts Can Be Multi-Color' } ); // TOP-RIGHT // NOTE: Labels are ppt/excel dates (days past 1900) slide.addChart( pptx.charts.BAR, [ { name : 'Too Many Colors Series', labels: [37987,38018,38047,38078,38108,38139], values: [.20, .30, .10, .25, .15, .05] } ], { x:7, y:0.6, w:'45%', h:3, valAxisMaxVal:1, barDir: 'bar', catAxisLineShow: false, valAxisLineShow: false, showValue: true, catLabelFormatCode: "mmm-yy", dataLabelPosition: 'outEnd', dataLabelFormatCode: '#%', valAxisLabelFormatCode: '#%', valAxisMajorUnit: 0.2, chartColors: ['0077BF','4E9D2D','ECAA00','5FC4E3','DE4216','154384', '7D666A','A3C961','EF907B','9BA0A3'], barGapWidthPct: 25 } ); // BOTTOM-LEFT slide.addChart( pptx.charts.BAR, [ { name : 'Two Color Series', labels: ['Jan', 'Feb','Mar', 'Apr', 'May', 'Jun'], values: [.20, .30, .10, .25, .15, .05] } ], { x:0.5, y:4.0, w:'45%', h:3, barDir: 'bar', showValue: true, dataLabelPosition: 'outEnd', dataLabelFormatCode: '#%', valAxisLabelFormatCode: '0.#0', chartColors: ['0077BF','4E9D2D','ECAA00'], valAxisMaxVal: .40, barGapWidthPct: 50 } ); // BOTTOM-RIGHT slide.addChart( pptx.charts.BAR, [ { name : 'Escaped XML Chars', labels: ['Es', 'cap', 'ed', 'XML', 'Chars', "'", '"', '&', '<', '>'], values: [1.20, 2.30, 3.10, 4.25, 2.15, 6.05, 8.01, 2.02, 9.9, 0.9] } ], { x:7, y:4, w:'45%', h:3, barDir: 'bar', showValue: true, dataLabelPosition: 'outEnd', chartColors: ['0077BF','4E9D2D','ECAA00','5FC4E3','DE4216','154384','7D666A','A3C961','EF907B','9BA0A3'], barGapWidthPct: 25, catAxisOrientation: 'maxMin', valAxisOrientation: 'maxMin', valAxisMaxVal: 10, valAxisMajorUnit: 1 } ); }
Add this operation to the _Bulk instance `bulkobj`.
def _add_to_bulk(self, bulkobj): """""" bulkobj.add_update(self._filter, self._doc, False, self._upsert, collation=self._collation)
// UnmarshalCheckpoint tries to unmarshal passed bytes to checkpoint
func (cp *CPUManagerCheckpoint) UnmarshalCheckpoint(blob []byte) error { return json.Unmarshal(blob, cp) }
Update Password @param $username @return mixed
public function mailPasswordResetLink($username) { return $this->apiClient->callEndpoint( sprintf('user/mail/password?username=%s', $username), array(), null, HttpMethod::REQUEST_POST ); }
TD-lambda returns.
def lambda_return(reward, value, length, discount, lambda_): """""" timestep = tf.range(reward.shape[1].value) mask = tf.cast(timestep[None, :] < length[:, None], tf.float32) sequence = mask * reward + discount * value * (1 - lambda_) discount = mask * discount * lambda_ sequence = tf.stack([sequence, discount], 2) return_ = tf.reverse(tf.transpose(tf.scan( lambda agg, cur: cur[0] + cur[1] * agg, tf.transpose(tf.reverse(sequence, [1]), [1, 2, 0]), tf.zeros_like(value[:, -1]), 1, False), [1, 0]), [1]) return tf.check_numerics(tf.stop_gradient(return_), 'return')
// SetRestApiId sets the RestApiId field's value.
func (s *GetIntegrationResponseInput) SetRestApiId(v string) *GetIntegrationResponseInput { s.RestApiId = &v return s }
Static utility method for facilitating writes on input object @param parent the source object @param matchedElement the current spec (leaf) element that was matched with input @param value to write @param opMode to determine if write is applicable
@SuppressWarnings( "unchecked" ) protected static void setData(Object parent, MatchedElement matchedElement, Object value, OpMode opMode) { if(parent instanceof Map) { Map source = (Map) parent; String key = matchedElement.getRawKey(); if(opMode.isApplicable( source, key )) { source.put( key, value ); } } else if (parent instanceof List && matchedElement instanceof ArrayMatchedElement ) { List source = (List) parent; int origSize = ( (ArrayMatchedElement) matchedElement ).getOrigSize(); int reqIndex = ( (ArrayMatchedElement) matchedElement ).getRawIndex(); if(opMode.isApplicable( source, reqIndex, origSize )) { source.set( reqIndex, value ); } } else { throw new RuntimeException( "Should not come here!" ); } }
// Get requests a single machine from the registry
func (m *MachinesClient) Get(ctx context.Context, machineID *identity.ID) (*apitypes.MachineSegment, error) { resp := &apitypes.MachineSegment{} err := m.client.RoundTrip(ctx, "GET", "/machines/"+(*machineID).String(), nil, nil, &resp) return resp, err }
Apply the given filtering criterion to a copy of this Query, using keyword expressions.
def filter_by(self, **kwargs): query = self._copy() for field, value in kwargs.items(): query.domain.append( (field, '=', value) ) return query
Execute the console command. @return void
public function handle() { $events = $this->schedule->dueEvents($this->container); foreach ($events as $event) { $this->line('<info>Running scheduled command:</info> ' .$event->getSummaryForDisplay()); $event->run($this->container); } if (count($events) === 0) { $this->info('No scheduled commands are ready to run.'); } }
Used to create configuration files, set permissions and so on.
def main(overwrite): logger.debug("Checking existence of '%s'.", CONF_PATH) if not os.path.exists(CONF_PATH): logger.debug("Directory %s not found! Panicking..", CONF_PATH) raise UserWarning( "Can't find '%s' - it looks like ProFTPD is not installed!" % ( CONF_PATH, ) ) # check existence of proftpd.conf logger.debug("Checking existence of configuration file '%s'.", CONF_FILE) if not os.path.exists(CONF_FILE): logger.debug("Configuration file not found, creating..") _write_conf_file() else: logger.debug("Found.") if not os.path.exists(CONF_FILE + "_"): logger.debug( "Backing up the configuration file '%s' -> '%s'.", CONF_FILE, CONF_FILE + "_" ) shutil.copyfile(CONF_FILE, CONF_FILE + "_") else: logger.debug( "Backup already exists. '%s' will be overwritten.", CONF_FILE ) if overwrite: logger.debug("--update switch not found, overwriting conf file") _write_conf_file() logger.debug("Checking existence of the '%s' file.", MODULES_FILE) if not os.path.exists(MODULES_FILE) and _is_deb_system(): with open(MODULES_FILE, "w") as f: f.write(DEFAULT_MODULES_CONF) logger.debug("Modules file not found. Created '%s'.", MODULES_FILE) # create data directory, where the user informations will be stored logger.debug("Checking existence of user's directory '%s'.", DATA_PATH) if not os.path.exists(DATA_PATH): logger.debug("Directory '%s' not found, creating..", DATA_PATH) os.makedirs(DATA_PATH, 0777) logger.debug("Done. '%s' created.", DATA_PATH) # create user files if they doesn't exists logger.debug("Checking existence of passwd file '%s'.", LOGIN_FILE) if not os.path.exists(LOGIN_FILE): logger.debug("passwd file not found, creating..") open(LOGIN_FILE, "a").close() logger.debug("Done. '%s' created.") logger.debug("Setting permissions..") os.chown(LOGIN_FILE, get_ftp_uid(), -1) os.chmod(LOGIN_FILE, 0400) # load values from protpd conf file logger.debug("Switching and adding options..") data = "" with open(CONF_FILE) as f: data = f.read() # set path to passwd file logger.debug("\tAuthUserFile") data = add_or_update( data, "AuthUserFile", LOGIN_FILE ) logger.debug("\tRequireValidShell") data = add_or_update(data, "RequireValidShell", "off") logger.debug("\tDefaultRoot") data = add_or_update(data, "DefaultRoot", "~") # http://www.proftpd.org/docs/modules/mod_log.html logger.debug("\tLogFormat") data = add_or_update(data, "LogFormat", 'paths "%f, %u, %m, %{%s}t"') logger.debug("\tExtendedLog") data = add_or_update( data, "ExtendedLog", LOG_FILE + " WRITE paths" ) if not _is_deb_system(): logger.debug("Detected non debian based linux. Aplying SUSE changes.") data = comment(data, "IdentLookups off") data = comment(data, "Include /etc/proftpd/modules.conf") data = add_or_update(data, "User", "ftp") # save changed file logger.debug("Saving into config file..") with open(CONF_FILE, "w") as f: f.write(data) logger.debug("Done.") logger.debug("Sending proftpd signal to reload configuration..") reload_configuration() logger.debug("Done.") logger.info("All set.")
Combine --pythonpath and --pants_config_files(pants.ini) files that are in {buildroot} dir with those invalidation_globs provided by users :param bootstrap_options: :return: A list of invalidation_globs
def compute_invalidation_globs(bootstrap_options): buildroot = get_buildroot() invalidation_globs = [] globs = bootstrap_options.pythonpath + \ bootstrap_options.pants_config_files + \ bootstrap_options.pantsd_invalidation_globs for glob in globs: glob_relpath = os.path.relpath(glob, buildroot) if glob_relpath and (not glob_relpath.startswith("../")): invalidation_globs.extend([glob_relpath, glob_relpath + '/**']) else: logging.getLogger(__name__).warning("Changes to {}, outside of the buildroot" ", will not be invalidated.".format(glob)) return invalidation_globs
delete the file from the filesystem.
def delete(self): """""" if self.isfile: os.remove(self.fn) elif self.isdir: shutil.rmtree(self.fn)
Build SDK client. Can be called only once in onCreate callback on Application class.
public static Observable<RxComapiClient> initialise(@NonNull Application app, @NonNull ComapiConfig config) { String error = checkIfCanInitialise(app, config, false); if (!TextUtils.isEmpty(error)) { return Observable.error(new Exception(error)); } RxComapiClient client = new RxComapiClient(config); return client.initialise(app, config.getCallbackAdapter() != null ? config.getCallbackAdapter() : new CallbackAdapter(), client); }
Add the version of wily to the help heading. :param f: function to decorate :return: decorated function
def add_version(f): doc = f.__doc__ f.__doc__ = "Version: " + __version__ + "\n\n" + doc return f
// Restart the sequence by resetting the current value. This is the only // method that allows direct manipulation of the sequence state which violates // the monotonically increasing or decreasing rule. Use with care and as a // fail safe if required.
func (s *Sequence) Restart() error { // Ensure that the sequence has been initialized. if !s.initialized { return errors.New("sequence has not been initialized") } // Ensure unsigned subtraction won't lead to a problem. if int(s.minvalue)-int(s.increment) < 0 { return errors.New("the minimum value must be less than or equal to the step") } // Set current based on the minvalue and the increment. s.current = s.minvalue - s.increment return nil }
// CreateVirtualDNS creates a new Virtual DNS cluster. // // API reference: https://api.cloudflare.com/#virtual-dns-users--create-a-virtual-dns-cluster
func (api *API) CreateVirtualDNS(v *VirtualDNS) (*VirtualDNS, error) { res, err := api.makeRequest("POST", "/user/virtual_dns", v) if err != nil { return nil, errors.Wrap(err, errMakeRequestError) } response := &VirtualDNSResponse{} err = json.Unmarshal(res, &response) if err != nil { return nil, errors.Wrap(err, errUnmarshalError) } return response.Result, nil }
Edit changelog & version, git commit, and git tag, to set up for release.
def prepare(c): # Print dry-run/status/actions-to-take data & grab programmatic result # TODO: maybe expand the enum-based stuff to have values that split up # textual description, command string, etc. See the TODO up by their # definition too, re: just making them non-enum classes period. # TODO: otherwise, we at least want derived eg changelog/version/etc paths # transmitted from status() into here... actions, state = status(c) # TODO: unless nothing-to-do in which case just say that & exit 0 if not confirm("Take the above actions?"): sys.exit("Aborting.") # TODO: factor out what it means to edit a file: # - $EDITOR or explicit expansion of it in case no shell involved # - pty=True and hide=False, because otherwise things can be bad # - what else? # Changelog! (pty for non shite editing, eg vim sure won't like non-pty) if actions.changelog is Changelog.NEEDS_RELEASE: # TODO: identify top of list and inject a ready-made line? Requires vim # assumption...GREAT opportunity for class/method based tasks! cmd = "$EDITOR {0.packaging.changelog_file}".format(c) c.run(cmd, pty=True, hide=False) # TODO: add a step for checking reqs.txt / setup.py vs virtualenv contents # Version file! if actions.version == VersionFile.NEEDS_BUMP: # TODO: suggest the bump and/or overwrite the entire file? Assumes a # specific file format. Could be bad for users which expose __version__ # but have other contents as well. version_file = os.path.join( _find_package(c), c.packaging.get("version_module", "_version") + ".py", ) cmd = "$EDITOR {0}".format(version_file) c.run(cmd, pty=True, hide=False) if actions.tag == Tag.NEEDS_CUTTING: # Commit, if necessary, so the tag includes everything. # NOTE: this strips out untracked files. effort. cmd = 'git status --porcelain | egrep -v "^\\?"' if c.run(cmd, hide=True, warn=True).ok: c.run( 'git commit -am "Cut {0}"'.format(state.expected_version), hide=False, ) # Tag! c.run("git tag {0}".format(state.expected_version), hide=False)
Uses ssh-keygen to generate a public/private key pair. @return array
public function generate() { $tempPath = sys_get_temp_dir() . '/'; // FastCGI fix for Windows machines, where temp path is not available to // PHP, and defaults to the unwritable system directory. If the temp // path is pointing to the system directory, shift to the 'TEMP' // sub-folder, which should also exist, but actually be writable. if (IS_WIN && $tempPath == getenv("SystemRoot") . '/') { $tempPath = getenv("SystemRoot") . '/TEMP/'; } $keyFile = $tempPath . md5(microtime(true)); if (!is_dir($tempPath)) { mkdir($tempPath); } $return = array('private_key' => '', 'public_key' => ''); $output = @shell_exec('ssh-keygen -t rsa -b 2048 -f '.$keyFile.' -N "" -C "deploy@phpci"'); if (!empty($output)) { $pub = file_get_contents($keyFile . '.pub'); $prv = file_get_contents($keyFile); if (!empty($pub)) { $return['public_key'] = $pub; } if (!empty($prv)) { $return['private_key'] = $prv; } } return $return; }
Marca o atendimento como nao compareceu. @param Novosga\Request $request @Route("/nao_compareceu", name="novosga_attendance_naocompareceu", methods={"POST"})
public function naoCompareceu( Request $request, AtendimentoService $atendimentoService, TranslatorInterface $translator ) { $usuario = $this->getUser(); $unidade = $usuario->getLotacao()->getUnidade(); $atual = $atendimentoService->atendimentoAndamento($usuario->getId(), $unidade); if (!$atual) { throw new Exception( $translator->trans('error.attendance.empty', [], self::DOMAIN) ); } $atendimentoService->naoCompareceu($atual, $usuario); $data = $atual->jsonSerialize(); $envelope = new Envelope(); $envelope->setData($data); return $this->json($envelope); }
If not already created, a new <code>ejb-ref</code> element will be created and returned. Otherwise, the first existing <code>ejb-ref</code> element will be returned. @return the instance defined for the element <code>ejb-ref</code>
public EjbRefType<WebFragmentType<T>> getOrCreateEjbRef() { List<Node> nodeList = childNode.get("ejb-ref"); if (nodeList != null && nodeList.size() > 0) { return new EjbRefTypeImpl<WebFragmentType<T>>(this, "ejb-ref", childNode, nodeList.get(0)); } return createEjbRef(); }
Registers that new API call has been made. @param string $api_key @param string $region @param string $app_header
public function registerAppLimits( string $api_key, string $region, string $app_header ) { $limits = self::parseLimitHeaders($app_header); $this->initApp($api_key, $region, $limits); }
Render the field. @access public @return mixed|string
public function render() { switch ($this->getContext()) { case BaseField::CONTEXT_LIST: return '<img src="' . asset($this->getValue()). '" width="10%">'; break; case BaseField::CONTEXT_FILTER: case BaseField::CONTEXT_FORM: return View::make('krafthaus/bauhaus::models.fields._image') ->with('field', $this); break; } }
// validate makes sure the types are sound
func (typedData *TypedData) validate() error { if err := typedData.Types.validate(); err != nil { return err } if err := typedData.Domain.validate(); err != nil { return err } return nil }
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { current_hostname_responses result = (current_hostname_responses) service.get_payload_formatter().string_to_resource(current_hostname_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.current_hostname_response_array); } current_hostname[] result_current_hostname = new current_hostname[result.current_hostname_response_array.length]; for(int i = 0; i < result.current_hostname_response_array.length; i++) { result_current_hostname[i] = result.current_hostname_response_array[i].current_hostname[0]; } return result_current_hostname; }
Prepare content for notification index @api private @param [Object] target Notification target instance @param [Array<Notificaion>] notification_index Array notification index @param [Hash] params Option parameter to send render_notification
def prepare_content_for(target, notification_index, params) content_for :notification_index do @target = target begin render_notification notification_index, params rescue ActionView::MissingTemplate params.delete(:target) render_notification notification_index, params end end end
removes inactive clients (will be run in its own thread, about once every second)
def cleanup(self): while self.inactive_timeout > 0: self.time = time.time() keys = [] for key, client in self.clients.items.items(): t = getattr(client, "active_at", 0) if t > 0 and self.time - t > self.inactive_timeout: client.kwargs["link"].disconnect() keys.append(key) for key in keys: self.log_debug("Removing client (inactive): %s" % key) del self.clients[key] time.sleep(1)
读取为文本格式<br> 使用{@link ExcelExtractor} 提取Excel内容 @param withSheetName 是否附带sheet名 @return Excel文本 @since 4.1.0
public String readAsText(boolean withSheetName) { final ExcelExtractor extractor = getExtractor(); extractor.setIncludeSheetNames(withSheetName); return extractor.getText(); }