comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Because any rotation can be expressed within 360 degrees
of any given number, and since negative angles sometimes
are one character longer than corresponding positive angle,
we shorten the number to one in the range to [-90, 270[.
|
def optimizeAngle(angle):
# First, we put the new angle in the range ]-360, 360[.
# The modulo operator yields results with the sign of the
# divisor, so for negative dividends, we preserve the sign
# of the angle.
if angle < 0:
angle %= -360
else:
angle %= 360
# 720 degrees is unnecessary, as 360 covers all angles.
# As "-x" is shorter than "35x" and "-xxx" one character
# longer than positive angles <= 260, we constrain angle
# range to [-90, 270[ (or, equally valid: ]-100, 260]).
if angle >= 270:
angle -= 360
elif angle < -90:
angle += 360
return angle
|
Returns a list of all media from all library sections.
This may be a very large dataset to retrieve.
|
def all(self, **kwargs):
items = []
for section in self.sections():
for item in section.all(**kwargs):
items.append(item)
return items
|
Requires: account ID (taken from Client object)
Returns: a list of Server objects
Endpoint: api.newrelic.com
Errors: 403 Invalid API Key
Method: Get
|
def view_servers(self):
endpoint = "https://api.newrelic.com"
uri = "{endpoint}/api/v1/accounts/{id}/servers.xml".format(endpoint=endpoint, id=self.account_id)
response = self._make_get_request(uri)
servers = []
for server in response.findall('.//server'):
server_properties = {}
for field in server:
server_properties[field.tag] = field.text
servers.append(Server(server_properties))
return servers
|
Extract config from dataSource nodes.
@param {Node} node
@return {Object}
@private
|
function getDataSource(node) {
const config = Object.assign({}, copyXmlAttributes(node));
if (node.childNodes.length) {
// parse datasource options
for (let i = 0; i < node.childNodes.length; ++i) {
const childNode = node.childNodes.item(i);
if (childNode.nodeType === TEXT_NODE && childNode.textContent.trim().length > 0) {
throw new ImplementationError(`dataSource contains useless text: "${childNode.textContent.trim()}"`);
}
if (
childNode.nodeType === ELEMENT_NODE &&
childNode.namespaceURI === 'urn:flora:options' &&
childNode.localName === 'option'
) {
if (childNode.attributes.length !== 1)
throw new Error('flora:option element requires a name attribute');
const attr = childNode.attributes.item(0);
if (attr.localName !== 'name') throw new Error('flora:option element requires a name attribute');
if (config[attr.value]) throw new Error(`Data source option "${attr.value}" already defined`);
config[attr.value] = childNode.textContent.trim();
}
}
}
const name = config.name ? config.name : 'primary';
if (config.name) delete config.name;
return { name, config };
}
|
Generates a solver vector of a clause.
@param clause the clause
@return the solver vector
|
private LNGIntVector generateClauseVector(final Formula clause) {
final LNGIntVector clauseVec = new LNGIntVector(clause.numberOfOperands());
for (final Literal lit : clause.literals()) {
int index = this.idxForName(lit.name());
if (index == -1) {
index = this.newVar(false, true);
this.addName(lit.name(), index);
}
final int litNum = lit.phase() ? index * 2 : (index * 2) ^ 1;
clauseVec.push(litNum);
}
return clauseVec;
}
|
Updates the item with the new data value.
:param editor | <QtGui.QWidget>
model | <QtGui.QModel>
index | <QtGui.QModelIndex>
|
def setModelData(self, editor, model, index):
value = editor.currentText()
model.setData(index, wrapVariant(value))
|
Set the LineRoundLimit property
<p>
Used to automatically convert round joins to miter joins for shallow angles.
</p>
@param value property wrapper value around Float
|
public void setLineRoundLimit( Float value) {
PropertyValue propertyValue = lineRoundLimit(value);
constantPropertyUsageMap.put(PROPERTY_LINE_ROUND_LIMIT, propertyValue);
layer.setProperties(propertyValue);
}
|
Concatenate values of a given key as a string.
@param string $value
@param string $glue
@return string
|
public function implode($value, $glue = null)
{
if (is_null($glue)) return implode($this->lists($value));
return implode($glue, $this->lists($value));
}
|
Monitor the original element for changes and update select2 accordingly
abstract
|
function () {
var el = this.opts.element, observer, self = this;
el.on("change.select2", this.bind(function (e) {
if (this.opts.element.data("select2-change-triggered") !== true) {
this.initSelection();
}
}));
this._sync = this.bind(function () {
// sync enabled state
var disabled = el.prop("disabled");
if (disabled === undefined) disabled = false;
this.enable(!disabled);
var readonly = el.prop("readonly");
if (readonly === undefined) readonly = false;
this.readonly(readonly);
syncCssClasses(this.container, this.opts.element, this.opts.adaptContainerCssClass);
this.container.addClass(evaluate(this.opts.containerCssClass, this.opts.element));
syncCssClasses(this.dropdown, this.opts.element, this.opts.adaptDropdownCssClass);
this.dropdown.addClass(evaluate(this.opts.dropdownCssClass, this.opts.element));
});
// IE8-10 (IE9/10 won't fire propertyChange via attachEventListener)
if (el.length && el[0].attachEvent) {
el.each(function() {
this.attachEvent("onpropertychange", self._sync);
});
}
// safari, chrome, firefox, IE11
observer = window.MutationObserver || window.WebKitMutationObserver|| window.MozMutationObserver;
if (observer !== undefined) {
if (this.propertyObserver) { delete this.propertyObserver; this.propertyObserver = null; }
this.propertyObserver = new observer(function (mutations) {
$.each(mutations, self._sync);
});
this.propertyObserver.observe(el.get(0), { attributes:true, subtree:false });
}
}
|
// Next assigns the next result from the results into the value pointer, returning whether the read was successful.
|
func (r *SearchResults) Next(hitPtr *SearchResultHit) bool {
if r.err != nil {
return false
}
row := r.NextBytes()
if row == nil {
return false
}
r.err = json.Unmarshal(row, hitPtr)
if r.err != nil {
return false
}
return true
}
|
Auxiliary method for getting errors in nested entities
@param string $field the field in this entity to check for errors
@return array errors in nested entity if any
|
protected function _nestedErrors($field)
{
$path = explode('.', $field);
// Only one path element, check for nested entity with error.
if (count($path) === 1) {
return $this->_readError($this->get($path[0]));
}
$entity = $this;
$len = count($path);
while ($len) {
$part = array_shift($path);
$len = count($path);
$val = null;
if ($entity instanceof EntityInterface) {
$val = $entity->get($part);
} elseif (is_array($entity)) {
$val = isset($entity[$part]) ? $entity[$part] : false;
}
if (is_array($val) ||
$val instanceof Traversable ||
$val instanceof EntityInterface
) {
$entity = $val;
} else {
$path[] = $part;
break;
}
}
if (count($path) <= 1) {
return $this->_readError($entity, array_pop($path));
}
return [];
}
|
// findVerifiedParents attempts to find certificates in s which have signed the
// given certificate. If any candidates were rejected then errCert will be set
// to one of them, arbitrarily, and err will contain the reason that it was
// rejected.
|
func (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int, errCert *Certificate, err error) {
if s == nil {
return
}
var candidates []int
if len(cert.AuthorityKeyId) > 0 {
candidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)]
}
if len(candidates) == 0 {
candidates = s.byName[string(cert.RawIssuer)]
}
for _, c := range candidates {
if err = cert.CheckSignatureFrom(s.certs[c]); err == nil {
parents = append(parents, c)
} else {
errCert = s.certs[c]
}
}
return
}
|
Appends a task message to the buffer.
@param sourceHSId
@param task
@throws IOException If the buffer is not of the type TASK
@return how many bytes are left in this buffer for adding a new task
|
public int appendTask(long sourceHSId, TransactionInfoBaseMessage task) throws IOException {
Preconditions.checkState(compiledSize == 0, "buffer is already compiled");
final int msgSerializedSize = task.getSerializedSize();
ensureCapacity(taskHeaderSize() + msgSerializedSize);
ByteBuffer bb = m_container.b();
bb.putInt(msgSerializedSize);
bb.putLong(sourceHSId);
int limit = bb.limit();
bb.limit(bb.position() + msgSerializedSize);
task.flattenToBuffer(bb.slice());
bb.limit(limit);
bb.position(bb.position() + msgSerializedSize);
// Don't allow any further expansion to the underlying buffer
if (bb.position() + taskHeaderSize() > DEFAULT_BUFFER_SIZE) {
compile();
return 0;
} else {
return DEFAULT_BUFFER_SIZE - (bb.position() + taskHeaderSize());
}
}
|
taobao.product.add 上传一个产品,不包括产品非主图和属性图片
获取类目ID,必需是叶子类目ID;调用taobao.itemcats.get.v2获取 传入关键属性,结构:pid:vid;pid:vid.调用taobao.itemprops.get.v2获取pid, 调用taobao.itempropvalues.get获取vid;如果碰到用户自定义属性,请用customer_props.
|
def add(self, cid, price, image, name, desc, major, market_time, property_alias, session, **kwargs):
''''''
request = TOPRequest('taobao.product.add')
request['cid'] = cid
request['price'] = price
request['image'] = image
request['name'] = name
request['desc'] = desc
request['major'] = major
request['market_time'] = market_time
request['property_alias'] = property_alias
for k, v in kwargs.iteritems():
if k not in ('outer_id', 'props', 'binds', 'sale_props', 'customer_props', 'order_by', 'ww_status', 'post_free', 'location_state', 'location_city', 'is_3D', 'start_score', 'end_score', 'start_volume', 'end_volume', 'one_station', 'is_cod', 'is_mall', 'is_prepay', 'genuine_security', 'promoted_service', 'stuff_status', 'start_price', 'end_price', 'page_no', 'page_size', 'auction_flag', 'auto_post', 'has_discount', 'is_xinpin') and v==None: continue
if k == 'location_state': k = 'location.state'
if k == 'location_city': k = 'location.city'
request[k] = v
self.create(self.execute(request, session)['product'])
return self
|
得到分词结果 List,不进行断句
@param src 字符串
@return ArrayList<String> 词数组,每个元素为一个词
|
public ArrayList<String> tag2List(String src) {
if(src==null||src.length()==0)
return null;
ArrayList<String> res =null;
try {
Instance inst = new Instance(src);
String[] preds = _tag(inst);
res = FormatCWS.toList(inst, preds);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
|
// parsePositionalArguments tries to parse the given args to an array of values with the
// given types. It returns the parsed values or an error when the args could not be
// parsed. Missing optional arguments are returned as reflect.Zero values.
|
func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([]reflect.Value, error) {
dec := json.NewDecoder(bytes.NewReader(rawArgs))
var args []reflect.Value
tok, err := dec.Token()
switch {
case err == io.EOF || tok == nil && err == nil:
// "params" is optional and may be empty. Also allow "params":null even though it's
// not in the spec because our own client used to send it.
case err != nil:
return nil, err
case tok == json.Delim('['):
// Read argument array.
if args, err = parseArgumentArray(dec, types); err != nil {
return nil, err
}
default:
return nil, errors.New("non-array args")
}
// Set any missing args to nil.
for i := len(args); i < len(types); i++ {
if types[i].Kind() != reflect.Ptr {
return nil, fmt.Errorf("missing value for required argument %d", i)
}
args = append(args, reflect.Zero(types[i]))
}
return args, nil
}
|
@param string $verb
@param string $location
@return Response
@throws EntityException
|
protected function sendApiCall($verb, $location)
{
try {
$this->detectInvalidJsonFields();
$response = $this->client->sendRequest($verb, $location, $this->postFields);
$entity = $this->getItems($response->getBody());
if (isset($entity[0])) {
$this->setFields($entity[0]);
}
return $response;
} catch (ClientException $e) {
if ($e->getResponse() !== null) {
$entity = $this->getItems($e->getResponse()->getBody());
if (isset($entity[0]['validation_messages'])) {
throw new ValidationException(
$entity[0]['validation_messages'],
$this->postFields,
$e->getResponse()->getStatusCode(),
isset($entity[0]['errorCode']) ? $entity[0]['errorCode'] : null
);
} else {
throw new EntityException(
'Exception received from api client: ' . $e->getMessage(),
$e->getCode(),
$e->getResponse()->getStatusCode(),
isset($entity[0]['errorCode']) ? $entity[0]['errorCode'] : null
);
}
} else {
throw new EntityException(
'Exception received from api client: ' . $e->getMessage(),
$e->getCode()
);
}
}
}
|
// Reset resets the count of all buckets.
|
func (w *window) Reset() {
w.bucketLock.Lock()
w.buckets.Do(func(x interface{}) {
x.(*bucket).Reset()
})
w.bucketLock.Unlock()
}
|
List all Galleries
Example Usage:
- require 'kairos'
- client = Kairos::Client.new(:app_id => '1234', :app_key => 'abcde1234')
- client.gallery_list_all
|
def gallery_list_all
# ToDo: Research why Typhoeus works better than Faraday for this endpoint
request = Typhoeus::Request.new(
"#{Kairos::Configuration::GALLERY_LIST_ALL}",
method: :post,
headers: { "Content-Type" => "application/x-www-form-urlencoded",
"app_id" => "#{@app_id}",
"app_key" => "#{@app_key}" }
)
response = request.run
JSON.parse(response.body) rescue "INVALID_JSON: #{response.body}"
end
|
Allows setting HTTP headers to be used for each request.
class Foo
include HTTParty
headers 'Accept' => 'text/html'
end
|
def headers(h = nil)
if h
raise ArgumentError, 'Headers must be an object which responds to #to_hash' unless h.respond_to?(:to_hash)
default_options[:headers] ||= {}
default_options[:headers].merge!(h.to_hash)
else
default_options[:headers] || {}
end
end
|
{@inheritDoc}
@see \Symfony\Component\Translation\Loader\LoaderInterface::load()
|
public function load($resource, $locale, $domain = 'messages') {
$repo = $this->service->getResourceRepository();
if (!$repo->contains($resource)) {
throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
}
// find file in puli repo
$file = $repo->get($resource);
$json = $file->getBody();
$data = Json::decode($json);
$messages = [];
// flatten plural strings
foreach ($data as $key => $value) {
if (is_array($value)) {
$vals = [];
foreach ($value as $k => $v) {
$vals[] = sprintf('%s: %s', $k, $v);
}
$val = implode('|', $vals);
} else {
$val = $value;
}
$messages[$key] = str_replace(['{{', '}}'], '%', $val);
}
// put them into message catalog
$catalogue = new MessageCatalogue($locale);
$catalogue->add($messages, $domain);
return $catalogue;
}
|
CPU information
@return void
|
protected function cpuinfo()
{
$dev = new CpuDevice();
if (PSI_OS == "NetBSD") {
if ($model = $this->grabkey('machdep.cpu_brand')) {
$dev->setModel($model);
}
if ($cpuspeed = $this->grabkey('machdep.tsc_freq')) {
$dev->setCpuSpeed(round($cpuspeed / 1000000));
}
}
if ($dev->getModel() === "") {
$dev->setModel($this->grabkey('hw.model'));
}
$notwas = true;
foreach ($this->readdmesg() as $line) {
if ($notwas) {
if (preg_match($this->_CPURegExp1, $line, $ar_buf)) {
if ($dev->getCpuSpeed() === 0) {
$dev->setCpuSpeed(round($ar_buf[2]));
}
$notwas = false;
}
} else {
if (preg_match("/ Origin| Features/", $line, $ar_buf)) {
if (preg_match("/ Features2[ ]*=.*<(.*)>/", $line, $ar_buf)) {
$feats = preg_split("/,/", strtolower(trim($ar_buf[1])), -1, PREG_SPLIT_NO_EMPTY);
foreach ($feats as $feat) {
if (($feat=="vmx") || ($feat=="svm")) {
$dev->setVirt($feat);
break 2;
}
}
break;
}
} else break;
}
}
$ncpu = $this->grabkey('hw.ncpu');
if (is_null($ncpu) || (trim($ncpu) == "") || (!($ncpu >= 1)))
$ncpu = 1;
for ($ncpu ; $ncpu > 0 ; $ncpu--) {
$this->sys->setCpus($dev);
}
}
|
// initLogRotator initializes the logging rotater to write logs to logFile and
// create roll files in the same directory. It must be called before the
// package-global log rotater variables are used.
|
func initLogRotator(logFile string) {
logDir, _ := filepath.Split(logFile)
err := os.MkdirAll(logDir, 0700)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create log directory: %v\n", err)
os.Exit(1)
}
r, err := rotator.New(logFile, 10*1024, false, 3)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create file rotator: %v\n", err)
os.Exit(1)
}
logRotator = r
}
|
collapse logically equivalent lt/lte values
|
function mergeLtLte(operator, value, fieldMatchers) {
if (typeof fieldMatchers.$eq !== 'undefined') {
return; // do nothing
}
if (typeof fieldMatchers.$lte !== 'undefined') {
if (operator === '$lte') {
if (value < fieldMatchers.$lte) { // more specificity
fieldMatchers.$lte = value;
}
} else { // operator === '$gt'
if (value <= fieldMatchers.$lte) { // more specificity
delete fieldMatchers.$lte;
fieldMatchers.$lt = value;
}
}
} else if (typeof fieldMatchers.$lt !== 'undefined') {
if (operator === '$lte') {
if (value < fieldMatchers.$lt) { // more specificity
delete fieldMatchers.$lt;
fieldMatchers.$lte = value;
}
} else { // operator === '$gt'
if (value < fieldMatchers.$lt) { // more specificity
fieldMatchers.$lt = value;
}
}
} else {
fieldMatchers[operator] = value;
}
}
|
Create a new Map typed path
@param <K>
@param <V>
@param property property name
@param key key type
@param value value type
@return property path
|
public <K, V> MapPath<K, V, PathBuilder<V>> getMap(String property, Class<K> key, Class<V> value) {
return this.<K, V, PathBuilder<V>>getMap(property, key, value, PathBuilder.class);
}
|
Returns a builder for an {@code InsertAllRequest} object given the destination table and the
rows to insert.
|
public static Builder newBuilder(String datasetId, String tableId, Iterable<RowToInsert> rows) {
return newBuilder(TableId.of(datasetId, tableId), rows);
}
|
Set global default encoding
@param string $encoding
|
public static function setDefaultEncoding($encoding=null)
{
if(!is_null($encoding) && is_string($encoding) && !empty($encoding))
{
self::$defaultencoding = $encoding;
}
else
{
self::$defaultencoding = null;
}
}
|
*
Restore reading from a certain row/sheet position and restore schema without
rereadingit.
@param split
@param state
@throws IOException
|
public void reopen(FileInputSplit split, Tuple3<Long, Long, GenericDataType[]> state) throws IOException {
this.customSchema = state.f2;
this.open(split);
this.getOfficeReader().getCurrentParser().setCurrentSheet(state.f0);
this.getOfficeReader().getCurrentParser().setCurrentRow(state.f1);
}
|
Run this section and print out information.
|
def run(self):
""""""
if self.mloginfo.logfile.repl_set:
print(" rs name: %s" % self.mloginfo.logfile.repl_set)
print(" rs members: %s"
% (self.mloginfo.logfile.repl_set_members
if self.mloginfo.logfile.repl_set_members
else "unknown"))
print(" rs version: %s"
% (self.mloginfo.logfile.repl_set_version
if self.mloginfo.logfile.repl_set_version
else "unknown"))
print("rs protocol: %s"
% (self.mloginfo.logfile.repl_set_protocol
if self.mloginfo.logfile.repl_set_protocol
else "unknown"))
else:
print(" no rs info changes found")
|
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated
|
@Override
public EEnum getIfcUnitaryEquipmentTypeEnum() {
if (ifcUnitaryEquipmentTypeEnumEEnum == null) {
ifcUnitaryEquipmentTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1096);
}
return ifcUnitaryEquipmentTypeEnumEEnum;
}
|
// Set mocks base method
|
func (m *MockVolumeDriver) Set(arg0 string, arg1 *api.VolumeLocator, arg2 *api.VolumeSpec) error {
ret := m.ctrl.Call(m, "Set", arg0, arg1, arg2)
ret0, _ := ret[0].(error)
return ret0
}
|
Works like Symbol.__str__(), but allows a custom format to be used for
all symbol/choice references. See expr_str().
|
def custom_str(self, sc_expr_str_fn):
return "\n\n".join(node.custom_str(sc_expr_str_fn)
for node in self.nodes)
|
// ParseJSONFile - Read a file and convert into a representation of the parsed JSON.
|
func ParseJSONFile(path string) (*Container, error) {
if len(path) > 0 {
cBytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
container, err := ParseJSON(cBytes)
if err != nil {
return nil, err
}
return container, nil
}
return nil, ErrInvalidPath
}
|
// CreateOverlayPATNATEntry creates a new child OverlayPATNATEntry under the OverlayAddressPool
|
func (o *OverlayAddressPool) CreateOverlayPATNATEntry(child *OverlayPATNATEntry) *bambou.Error {
return bambou.CurrentSession().CreateChild(o, child)
}
|
Return MD5 Checksum
|
def md5(source):
# fix passing char '+' from source
source = source.replace("%2B", "+")
with open(source) as file_to_check:
data = file_to_check.read()
return hashlib.md5(data).hexdigest()
|
// IsSorted checks whether a slice of KSUIDs is sorted
|
func IsSorted(ids []KSUID) bool {
if len(ids) != 0 {
min := ids[0]
for _, id := range ids[1:] {
if bytes.Compare(min[:], id[:]) > 0 {
return false
}
min = id
}
}
return true
}
|
Return a json dictionary representing this model.
|
def _to_dict(self):
""""""
_dict = {}
if hasattr(self, 'overwrite') and self.overwrite is not None:
_dict['overwrite'] = self.overwrite
return _dict
|
Set sort field and direction
@param string $field Field name
@param string $direction Sort direction
@param int $priority Priority
@return self
|
public function addSort($field = 'time_created', $direction = 'DESC', $priority = 500) {
if (!$field || !$direction) {
return $this;
}
while (isset($this->sorts[$priority])) {
$priority++;
}
$field = sanitize_string($field);
$direction = strtoupper(sanitize_string($direction));
if (!in_array($direction, array('ASC', 'DESC'))) {
$direction = self::DEFAULT_SORT_DIRECTION;
}
$this->removeSort($field);
$this->sorts[$priority] = [
'field' => $field,
'direction' => $direction,
];
ksort($this->sorts);
return $this;
}
|
Returns an ``int`` of the total number of two point field goals the
player attempted during the season.
|
def two_point_attempts(self):
if self.field_goal_attempts and self.three_point_attempts:
return int(self.field_goal_attempts - self.three_point_attempts)
# Occurs when the player didn't take any three pointers, so the number
# of two pointers the player took is equal to the total number of field
# goals the player took.
if self.field_goal_attempts:
return int(self.field_goal_attempts)
# If the player didn't take any shots, they didn't take any two point
# field goals.
return None
|
// SetParallelismPerKPU sets the ParallelismPerKPU field's value.
|
func (s *ParallelismConfigurationDescription) SetParallelismPerKPU(v int64) *ParallelismConfigurationDescription {
s.ParallelismPerKPU = &v
return s
}
|
Called when the signed in status changes, to update the UI
appropriately. After a sign-in, the API is called.
|
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listFiles();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
|
// SetMaxRecords sets the MaxRecords field's value.
|
func (s *DescribeSchemasInput) SetMaxRecords(v int64) *DescribeSchemasInput {
s.MaxRecords = &v
return s
}
|
Sync the requested folders and files.
@return bool
|
public function syncSharedFolders()
{
$shared = (array) $this->config->getContextually('remote.shared');
foreach ($shared as &$file) {
$this->share($file);
}
return true;
}
|
List all RepositoryConfigurations
|
def list_repository_configurations(page_size=200, page_index=0, sort="", q=""):
response = utils.checked_api_call(pnc_api.repositories, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return utils.format_json_list(response.content)
|
// NewPerBuildConfigResolver returns a Resolver that selects Builds to prune per BuildConfig
|
func NewPerBuildConfigResolver(dataSet DataSet, keepComplete int, keepFailed int) Resolver {
return &perBuildConfigResolver{
dataSet: dataSet,
keepComplete: keepComplete,
keepFailed: keepFailed,
}
}
|
Remove the complete fragment and show an empty form fragment
|
public void reset() {
fileLink = null;
formFragment = new FormFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.root, formFragment)
.commit();
}
|
Create a user and assign roles to it.
@param array $data
@param array $users
|
public function createWithUsers(array $data, $users)
{
$role = $this->create((array) $data);
if (! empty($users)) {
$role->users()->attach($users);
}
}
|
Erstellt eine neue Methode
@return GMethod
|
public function createMethod($name, $params = array(), $body = NULL, $modifiers = 256) {
$method = $this->class->createMethod($name, $params, $body, $modifiers);
$method->setClassBuilder($this);
return $method;
}
|
Returns the corrections applied to a particular entry.
Args:
entry: A ComputedEntry object.
Returns:
({correction_name: value})
|
def get_corrections_dict(self, entry):
corrections = {}
for c in self.corrections:
val = c.get_correction(entry)
if val != 0:
corrections[str(c)] = val
return corrections
|
@param \Laravel\Nova\Resource $resource
@return array
|
public function indexFields(Resource $resource): array
{
return $this->resourceFields($resource)->map(function (Field $field) {
if (!$field->computed()) {
return $field->attribute;
}
return $field->name;
})->unique()->all();
}
|
// Gets the default set of OAuth1.0a headers.
|
func headers(consumerKey string) map[string]string {
return map[string]string{
"oauth_consumer_key" : consumerKey,
"oauth_nonce" : nonce(),
"oauth_signature_method" : "HMAC-SHA1",
"oauth_timestamp" : timestamp(),
"oauth_version" : "1.0",
}
}
|
// SetSnapshotName sets the SnapshotName field's value.
|
func (s *DeleteApplicationSnapshotInput) SetSnapshotName(v string) *DeleteApplicationSnapshotInput {
s.SnapshotName = &v
return s
}
|
Returns a JSON response with a callback wrapper, if asked for.
Consider using CORS instead, as JSONP makes the client app insecure.
See the :func:`~coaster.views.decorators.cors` decorator.
|
def jsonp(*args, **kw):
data = json.dumps(dict(*args, **kw), indent=2)
callback = request.args.get('callback', request.args.get('jsonp'))
if callback and __jsoncallback_re.search(callback) is not None:
data = callback + u'(' + data + u');'
mimetype = 'application/javascript'
else:
mimetype = 'application/json'
return Response(data, mimetype=mimetype)
|
-----------------------------------------------------------------------
|
@Override
public List<ProviderAccount> listProviderAccounts(String url,
String username,
String password) {
return duraCloudDao.listProviderAccounts(url, username, password);
}
|
Check security features of an ELF file.
|
def checksec_app(_parser, _, args): # pragma: no cover
import sys
import argparse
import csv
import os.path
def checksec(elf, path, fortifiable_funcs):
relro = 0
nx = False
pie = 0
rpath = False
runpath = False
for header in elf.program_headers:
if header.type == ELF.ProgramHeader.Type.gnu_relro:
relro = 1
elif header.type == ELF.ProgramHeader.Type.gnu_stack:
if not header.flags & ELF.ProgramHeader.Flags.x:
nx = True
if elf.type == ELF.Type.shared:
pie = 1
for entry in elf.dynamic_section_entries:
if entry.type == ELF.DynamicSectionEntry.Type.bind_now and relro == 1:
relro = 2
elif entry.type == ELF.DynamicSectionEntry.Type.flags and \
entry.value & ELF.DynamicSectionEntry.Flags.bind_now:
relro = 2
elif entry.type == ELF.DynamicSectionEntry.Type.flags_1 and \
entry.value & ELF.DynamicSectionEntry.Flags_1.now:
relro = 2
elif entry.type == ELF.DynamicSectionEntry.Type.debug and pie == 1:
pie = 2
elif entry.type == ELF.DynamicSectionEntry.Type.rpath:
rpath = True
elif entry.type == ELF.DynamicSectionEntry.Type.runpath:
runpath = True
rtl_symbol_names = set(
symbol.name
for symbol in elf.symbols
if symbol.name and symbol.shndx == ELF.Symbol.SpecialSection.undef
)
fortified = fortifiable_funcs & rtl_symbol_names
unfortified = fortifiable_funcs & set('__%s_chk' % symbol_name for symbol_name in rtl_symbol_names)
canary = '__stack_chk_fail' in rtl_symbol_names
return {
'path': path,
'relro': relro,
'nx': nx,
'pie': pie,
'rpath': rpath,
'runpath': runpath,
'canary': canary,
'fortified': len(fortified),
'unfortified': len(unfortified),
'fortifiable': len(fortified | unfortified),
}
def check_paths(paths, fortifiable_funcs):
for path in paths:
if os.path.isdir(path):
for data in check_paths(
(os.path.join(path, fn) for fn in os.listdir(path) if fn not in ('.', '..')),
fortifiable_funcs,
):
yield data
else:
try:
elf = ELF(path)
except:
continue
yield checksec(elf, path, fortifiable_funcs)
parser = argparse.ArgumentParser(
prog=_parser.prog,
description=_parser.description,
)
parser.add_argument('path', nargs='+', help='ELF file to check security features of')
parser.add_argument(
'-f', '--format',
dest='format',
choices=['text', 'csv'],
default='text',
help='set output format'
)
parser.add_argument(
'-l', '--libc',
dest='libc',
help='path to the applicable libc.so'
)
args = parser.parse_args(args)
if args.libc:
libc = ELF(args.libc)
fortifiable_funcs = set([
symbol.name
for symbol in libc.symbols
if symbol.name.startswith('__') and symbol.name.endswith('_chk')
])
else:
fortifiable_funcs = set('''__wctomb_chk __wcsncat_chk __mbstowcs_chk __strncpy_chk __syslog_chk __mempcpy_chk
__fprintf_chk __recvfrom_chk __readlinkat_chk __wcsncpy_chk __fread_chk
__getlogin_r_chk __vfwprintf_chk __recv_chk __strncat_chk __printf_chk __confstr_chk
__pread_chk __ppoll_chk __ptsname_r_chk __wcscat_chk __snprintf_chk __vwprintf_chk
__memset_chk __memmove_chk __gets_chk __fgetws_unlocked_chk __asprintf_chk __poll_chk
__fdelt_chk __fgets_unlocked_chk __strcat_chk __vsyslog_chk __stpcpy_chk
__vdprintf_chk __strcpy_chk __obstack_printf_chk __getwd_chk __pread64_chk
__wcpcpy_chk __fread_unlocked_chk __dprintf_chk __fgets_chk __wcpncpy_chk
__obstack_vprintf_chk __wprintf_chk __getgroups_chk __wcscpy_chk __vfprintf_chk
__fgetws_chk __vswprintf_chk __ttyname_r_chk __mbsrtowcs_chk
__wmempcpy_chk __wcsrtombs_chk __fwprintf_chk __read_chk __getcwd_chk __vsnprintf_chk
__memcpy_chk __wmemmove_chk __vasprintf_chk __sprintf_chk __vprintf_chk
__mbsnrtowcs_chk __wcrtomb_chk __realpath_chk __vsprintf_chk __wcsnrtombs_chk
__gethostname_chk __swprintf_chk __readlink_chk __wmemset_chk __getdomainname_chk
__wmemcpy_chk __longjmp_chk __stpncpy_chk __wcstombs_chk'''.split())
if args.format == 'text':
print('RELRO CANARY NX PIE RPATH RUNPATH FORTIFIED PATH')
for data in check_paths(args.path, fortifiable_funcs):
print('{:7} {:6} {:3} {:3} {:5} {:7} {:>9} {}'.format(
('No', 'Partial', 'Full')[data['relro']],
'Yes' if data['canary'] else 'No',
'Yes' if data['nx'] else 'No',
('No', 'DSO', 'Yes')[data['pie']],
'Yes' if data['rpath'] else 'No',
'Yes' if data['runpath'] else 'No',
'{}/{}/{}'.format(data['fortified'], data['unfortified'], data['fortifiable']),
data['path']
))
else:
writer = csv.writer(sys.stdout)
writer.writerow(['path', 'relro', 'canary', 'nx', 'pie', 'rpath', 'runpath', 'fortified', 'unfortified',
'fortifiable'])
for data in check_paths(args.path, fortifiable_funcs):
writer.writerow([
data['path'],
('no', 'partial', 'full')[data['relro']],
'yes' if data['canary'] else 'no',
'yes' if data['nx'] else 'no',
('no', 'dso', 'yes')[data['pie']],
'yes' if data['rpath'] else 'no',
'yes' if data['runpath'] else 'no',
data['fortified'],
data['unfortified'],
data['fortifiable'],
])
|
Unmounts all bind mounts identified by :func:`find_bindmounts`
|
def unmount_bindmounts(self):
""""""
for mountpoint in self.find_bindmounts():
_util.clean_unmount(['umount'], mountpoint, rmdir=False)
|
// getImageStreamTagMarker will return the appropriate marker for when a BuildConfig is missing its input ImageStreamTag
|
func getImageStreamTagMarker(g osgraph.Graph, f osgraph.Namer, bcInputNode graph.Node, imageStreamNode graph.Node, tagNode *imagegraph.ImageStreamTagNode, bcNode graph.Node) osgraph.Marker {
return osgraph.Marker{
Node: bcNode,
RelatedNodes: []graph.Node{bcInputNode,
imageStreamNode},
Severity: osgraph.WarningSeverity,
Key: MissingImageStreamImageWarning,
Message: fmt.Sprintf("%s builds from %s, but the image stream tag does not exist.", f.ResourceName(bcNode), f.ResourceName(bcInputNode)),
Suggestion: getImageStreamTagSuggestion(g, f, tagNode),
}
}
|
// statsSegmentsLOCKED retrieves stats related to segments.
|
func (m *collection) statsSegmentsLOCKED(rv *CollectionStats) {
var sssDirtyTop *SegmentStackStats
var sssDirtyMid *SegmentStackStats
var sssDirtyBase *SegmentStackStats
var sssClean *SegmentStackStats
if m.stackDirtyTop != nil {
sssDirtyTop = m.stackDirtyTop.Stats()
}
if m.stackDirtyMid != nil {
sssDirtyMid = m.stackDirtyMid.Stats()
}
if m.stackDirtyBase != nil {
sssDirtyBase = m.stackDirtyBase.Stats()
}
if m.stackClean != nil {
sssClean = m.stackClean.Stats()
}
sssDirty := &SegmentStackStats{}
sssDirtyTop.AddTo(sssDirty)
sssDirtyMid.AddTo(sssDirty)
sssDirtyBase.AddTo(sssDirty)
rv.CurDirtyOps = sssDirty.CurOps
rv.CurDirtyBytes = sssDirty.CurBytes
rv.CurDirtySegments = sssDirty.CurSegments
if sssDirtyTop != nil {
rv.CurDirtyTopOps = sssDirtyTop.CurOps
rv.CurDirtyTopBytes = sssDirtyTop.CurBytes
rv.CurDirtyTopSegments = sssDirtyTop.CurSegments
}
if sssDirtyMid != nil {
rv.CurDirtyMidOps = sssDirtyMid.CurOps
rv.CurDirtyMidBytes = sssDirtyMid.CurBytes
rv.CurDirtyMidSegments = sssDirtyMid.CurSegments
}
if sssDirtyBase != nil {
rv.CurDirtyBaseOps = sssDirtyBase.CurOps
rv.CurDirtyBaseBytes = sssDirtyBase.CurBytes
rv.CurDirtyBaseSegments = sssDirtyBase.CurSegments
}
if sssClean != nil {
rv.CurCleanOps = sssClean.CurOps
rv.CurCleanBytes = sssClean.CurBytes
rv.CurCleanSegments = sssClean.CurSegments
}
}
|
Return the number of jobs in various waiting states
|
def n_waiting(self):
""""""
return self._counters[JobStatus.no_job] +\
self._counters[JobStatus.unknown] +\
self._counters[JobStatus.not_ready] +\
self._counters[JobStatus.ready]
|
match
@param string $pattern
@param string $string
@param string|null $option
@param string|null $encoding
@return bool
|
public static function match($pattern, $string, $option = 'msr', $encoding = null)
{
$encoding = $encoding === null ? mb_internal_encoding() : $encoding;
$encodingBackup = mb_regex_encoding();
mb_regex_encoding($encoding);
$result = mb_ereg_match($pattern, $string, $option);
mb_regex_encoding($encodingBackup);
return $result;
}
|
Makes an spatial shape representing the time range defined by the two specified dates.
@param from the start {@link Date}
@param to the end {@link Date}
@return a shape
|
public NRShape makeShape(Date from, Date to) {
UnitNRShape fromShape = tree.toUnitShape(from);
UnitNRShape toShape = tree.toUnitShape(to);
return tree.toRangeShape(fromShape, toShape);
}
|
Return the information returned when the specified job id was executed
|
def get_jid(jid):
'''
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM `salt_returns`
WHERE `jid` = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = salt.utils.json.loads(full_ret)
return ret
|
Finds the next {@code '$'} in a class name which can be changed to a {@code '.'} when computing
a canonical class name.
|
private static int nextDollar(String className, CharSequence current, int searchStart) {
while (true) {
int index = className.indexOf('$', searchStart);
if (index == -1) {
return -1;
}
// We'll never have two dots nor will a type name end or begin with dot. So no need to
// consider dollars at the beginning, end, or adjacent to dots.
if (index == 0 || index == className.length() - 1
|| current.charAt(index - 1) == '.' || current.charAt(index + 1) == '.') {
searchStart = index + 1;
continue;
}
return index;
}
}
|
// doDupRowUpdate updates the duplicate row.
|
func (e *InsertExec) doDupRowUpdate(handle int64, oldRow []types.Datum, newRow []types.Datum,
cols []*expression.Assignment) ([]types.Datum, bool, int64, error) {
assignFlag := make([]bool, len(e.Table.WritableCols()))
// See http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_values
e.ctx.GetSessionVars().CurrInsertValues = chunk.MutRowFromDatums(newRow).ToRow()
// NOTE: In order to execute the expression inside the column assignment,
// we have to put the value of "oldRow" before "newRow" in "row4Update" to
// be consistent with "Schema4OnDuplicate" in the "Insert" PhysicalPlan.
row4Update := make([]types.Datum, 0, len(oldRow)+len(newRow))
row4Update = append(row4Update, oldRow...)
row4Update = append(row4Update, newRow...)
// Update old row when the key is duplicated.
for _, col := range cols {
val, err1 := col.Expr.Eval(chunk.MutRowFromDatums(row4Update).ToRow())
if err1 != nil {
return nil, false, 0, err1
}
row4Update[col.Col.Index] = val
assignFlag[col.Col.Index] = true
}
newData := row4Update[:len(oldRow)]
_, handleChanged, newHandle, err := updateRecord(e.ctx, handle, oldRow, newData, assignFlag, e.Table, true)
if err != nil {
return nil, false, 0, err
}
return newData, handleChanged, newHandle, nil
}
|
{@inheritDoc}
@see \n2n\persistence\meta\structure\ColumnFactory::createIntegerColumn()
@return IntegerColumn
|
public function createIntegerColumn(string $name, int $size, bool $signed = true): IntegerColumn {
$column = new SqliteIntegerColumn($name);
$this->table->addColumn($column);
return $column;
}
|
Check that every key-value in superConfig is in subConfig
|
public static boolean verifySubset(Config superConfig, Config subConfig) {
for (Map.Entry<String, ConfigValue> entry : subConfig.entrySet()) {
if (!superConfig.hasPath(entry.getKey()) || !superConfig.getValue(entry.getKey()).unwrapped()
.equals(entry.getValue().unwrapped())) {
return false;
}
}
return true;
}
|
// WithCgroup sets the container's cgroup path
|
func WithCgroup(path string) SpecOpts {
return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {
setLinux(s)
s.Linux.CgroupsPath = path
return nil
}
}
|
Creates a row of widgets in a horizontal panel with a 5 pixel gap between them.
|
public static HorizontalPanel newRow (String styleName, Widget... contents)
{
return newRow(HasAlignment.ALIGN_MIDDLE, styleName, contents);
}
|
Return the Java source code of a whole class
:param _class: `ClassDefItem` object, to get the source from
:return:
|
def get_source_class(self, _class):
if not _class.get_name() in self.classes:
return ""
return self.classes[_class.get_name()]
|
Convenience function to append a list of widgets to a table as a new row.
|
protected static boolean addRow (SmartTable table, List<Widget> widgets)
{
if (widgets == null) {
return false;
}
int row = table.getRowCount();
for (int col=0; col<widgets.size(); ++col) {
table.setWidget(row, col, widgets.get(col));
table.getFlexCellFormatter().setStyleName(row, col, "col"+col);
}
return true;
}
|
Add a path to the list of tracked paths (this can be both dir's or files).
@param string $path the path to track.
@return Tracker this instance.
|
public function addPath($path)
{
if (empty($path) || false === ($real_path = realpath($path))) {
throw new FileNotFoundException(null, 0, null, $path);
}
$this->paths[] = $real_path;
return $this;
}
|
build
@param string $route
@param array $queries
@param string $type
@return string
@throws \Psr\Cache\InvalidArgumentException
|
public function route($route, $queries = [], $type = MainRouter::TYPE_PATH)
{
try {
if ($this->router->hasRoute($this->package->getName() . '@' . $route)) {
return $this->router->build($this->package->getName() . '@' . $route, $queries, $type);
}
return $this->router->build($route, $queries, $type);
} catch (\OutOfRangeException $e) {
if ($this->package->app->get('routing.debug', true)) {
throw new \OutOfRangeException($e->getMessage(), $e->getCode(), $e);
}
return '#';
}
}
|
Prints last response body.
@Then print response
|
public function printResponse()
{
$request = $this->request;
$response = $this->response;
echo sprintf(
"%s %s => %d:\n%s",
$request->getMethod(),
(string) ($request instanceof RequestInterface ? $request->getUri() : $request->getUrl()),
$response->getStatusCode(),
(string) $response->getBody()
);
}
|
发送文件
@param ins
@param size
@param ous
@throws IOException
|
protected void sendFileContent(InputStream ins, long size, OutputStream ous) throws IOException {
LOGGER.debug("开始上传文件流大小为{}", size);
long remainBytes = size;
byte[] buff = new byte[256 * 1024];
int bytes;
while (remainBytes > 0) {
if ((bytes = ins.read(buff, 0, remainBytes > buff.length ? buff.length : (int) remainBytes)) < 0) {
throw new IOException("the end of the stream has been reached. not match the expected size ");
}
ous.write(buff, 0, bytes);
remainBytes -= bytes;
LOGGER.debug("剩余数据量{}", remainBytes);
}
}
|
Create and set a Type Value Pair instance for a given type and value
@param type The type to set
@param value The value to set
@return The Type Value Pair instance
|
protected TypeValuePairType getTypeValuePair(String type, byte[] value) {
TypeValuePairType tvp = new TypeValuePairType();
tvp.setType(type);
//tvp.setValue(Base64.encodeBase64Chunked(value));
// the TVP itself base64 encodes now, no need for this
tvp.setValue(value);
return tvp;
}
|
Get layer output type.
@param inputType Array of InputTypes
@return output type as InputType
@throws InvalidKerasConfigurationException Invalid Keras config
|
@Override
public InputType getOutputType(InputType... inputType) throws InvalidKerasConfigurationException {
if (inputType.length > 1)
throw new InvalidKerasConfigurationException(
"Keras ZeroPadding layer accepts only one input (received " + inputType.length + ")");
return this.getZeroPadding2DLayer().getOutputType(-1, inputType[0]);
}
|
// newOpClientRequest create a client request object.
|
func newOpClientRequest(reqType opClientRequestType, args interface{}) opClientRequest {
return opClientRequest{
op: reqType,
args: args,
response: make(chan interface{}),
}
}
|
Sets the cp tax category remote service.
@param cpTaxCategoryService the cp tax category remote service
|
public void setCPTaxCategoryService(
com.liferay.commerce.product.service.CPTaxCategoryService cpTaxCategoryService) {
this.cpTaxCategoryService = cpTaxCategoryService;
}
|
Add a row to the end of the GUI or before another row.
@param gui
@param [dom] If specified, inserts the dom content in the new row
@param [liBefore] If specified, places the new row before another row
|
function addRow(gui, dom, liBefore) {
var li = document.createElement('li');
if (dom) li.appendChild(dom);
if (liBefore) {
gui.__ul.insertBefore(li, params.before);
} else {
gui.__ul.appendChild(li);
}
gui.onResize();
return li;
}
|
// PostingsForMatchers assembles a single postings iterator against the index reader
// based on the given matchers.
|
func PostingsForMatchers(ix IndexReader, ms ...labels.Matcher) (index.Postings, error) {
var its, notIts []index.Postings
// See which label must be non-empty.
labelMustBeSet := make(map[string]bool, len(ms))
for _, m := range ms {
if !m.Matches("") {
labelMustBeSet[m.Name()] = true
}
}
for _, m := range ms {
matchesEmpty := m.Matches("")
if labelMustBeSet[m.Name()] || !matchesEmpty {
// If this matcher must be non-empty, we can be smarter.
nm, isNot := m.(*labels.NotMatcher)
if isNot && matchesEmpty { // l!="foo"
// If the label can't be empty and is a Not and the inner matcher
// doesn't match empty, then subtract it out at the end.
it, err := postingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
} else if isNot && !matchesEmpty { // l!=""
// If the label can't be empty and is a Not, but the inner matcher can
// be empty we need to use inversePostingsForMatcher.
it, err := inversePostingsForMatcher(ix, nm.Matcher)
if err != nil {
return nil, err
}
its = append(its, it)
} else { // l="a"
// Non-Not matcher, use normal postingsForMatcher.
it, err := postingsForMatcher(ix, m)
if err != nil {
return nil, err
}
its = append(its, it)
}
} else { // l=""
// If the matchers for a labelname selects an empty value, it selects all
// the series which don't have the label name set too. See:
// https://github.com/prometheus/prometheus/issues/3575 and
// https://github.com/prometheus/prometheus/pull/3578#issuecomment-351653555
it, err := inversePostingsForMatcher(ix, m)
if err != nil {
return nil, err
}
notIts = append(notIts, it)
}
}
// If there's nothing to subtract from, add in everything and remove the notIts later.
if len(its) == 0 && len(notIts) != 0 {
allPostings, err := ix.Postings(index.AllPostingsKey())
if err != nil {
return nil, err
}
its = append(its, allPostings)
}
it := index.Intersect(its...)
for _, n := range notIts {
if _, ok := n.(*index.ListPostings); !ok {
// Best to pre-calculate the merged lists via next rather than have a ton
// of seeks in Without.
pl, err := index.ExpandPostings(n)
if err != nil {
return nil, err
}
n = index.NewListPostings(pl)
}
it = index.Without(it, n)
}
return ix.SortedPostings(it), nil
}
|
create scaffold with specified project name.
|
def create_scaffold(project_name):
if os.path.isdir(project_name):
logger.log_warning(u"Folder {} exists, please specify a new folder name.".format(project_name))
return
logger.color_print("Start to create new project: {}".format(project_name), "GREEN")
logger.color_print("CWD: {}\n".format(os.getcwd()), "BLUE")
def create_path(path, ptype):
if ptype == "folder":
os.makedirs(path)
elif ptype == "file":
open(path, 'w').close()
msg = "created {}: {}".format(ptype, path)
logger.color_print(msg, "BLUE")
path_list = [
(project_name, "folder"),
(os.path.join(project_name, "api"), "folder"),
(os.path.join(project_name, "testcases"), "folder"),
(os.path.join(project_name, "testsuites"), "folder"),
(os.path.join(project_name, "reports"), "folder"),
(os.path.join(project_name, "debugtalk.py"), "file"),
(os.path.join(project_name, ".env"), "file")
]
[create_path(p[0], p[1]) for p in path_list]
# create .gitignore file
ignore_file = os.path.join(project_name, ".gitignore")
ignore_content = ".env\nreports/*"
with open(ignore_file, "w") as f:
f.write(ignore_content)
|
// ReloadWithParams - Reloads given page optionally ignoring the cache.
|
func (c *Page) ReloadWithParams(v *PageReloadParams) (*gcdmessage.ChromeResponse, error) {
return gcdmessage.SendDefaultRequest(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "Page.reload", Params: v})
}
|
// Encode serializes the target DeleteSession message into the passed io.Writer
// observing the specified protocol version.
//
// This is part of the wtwire.Message interface.
|
func (m *DeleteSession) Encode(w io.Writer, pver uint32) error {
return nil
}
|
TODO: split iterations into "step" method
|
function() {
var i, j, l;
// Extract nodes positions
this.nodes = [];
for( i = 0 ; i < this.layer.containers.length ; i++) {
var pos = this.layer.containers[i].terminals[0].getXY();
this.nodes.push({
layoutPosX: (pos[0]-400)/200,
layoutPosY: (pos[1]-400)/200,
layoutForceX: 0,
layoutForceY: 0
});
}
// Spring layout parameters
var iterations = 100,
maxRepulsiveForceDistance = 6,
k = 0.3,
c = 0.01;
var d,dx,dy,d2,node,node1,node2;
// Iterations
for (l = 0; l < iterations; l++) {
// Forces on nodes due to node-node repulsions
for (i = 0; i < this.nodes.length; i++) {
node1 = this.nodes[i];
for (j = i + 1; j < this.nodes.length; j++) {
node2 = this.nodes[j];
dx = node2.layoutPosX - node1.layoutPosX;
dy = node2.layoutPosY - node1.layoutPosY;
d2 = dx * dx + dy * dy;
if(d2 < 0.01) {
dx = 0.1 * Math.random() + 0.1;
dy = 0.1 * Math.random() + 0.1;
d2 = dx * dx + dy * dy;
}
d = Math.sqrt(d2);
if(d < maxRepulsiveForceDistance) {
var repulsiveForce = k * k / d;
node2.layoutForceX += repulsiveForce * dx / d;
node2.layoutForceY += repulsiveForce * dy / d;
node1.layoutForceX -= repulsiveForce * dx / d;
node1.layoutForceY -= repulsiveForce * dy / d;
}
}
}
// Forces on this.nodes due to edge attractions
for (i = 0; i < this.edges.length; i++) {
var edge = this.edges[i];
node1 = this.nodes[ edge[0] ];
node2 = this.nodes[ edge[1] ];
dx = node2.layoutPosX - node1.layoutPosX;
dy = node2.layoutPosY - node1.layoutPosY;
d2 = dx * dx + dy * dy;
if(d2 < 0.01) {
dx = 0.1 * Math.random() + 0.1;
dy = 0.1 * Math.random() + 0.1;
d2 = dx * dx + dy * dy;
}
d = Math.sqrt(d2);
if(d > maxRepulsiveForceDistance) {
d = maxRepulsiveForceDistance;
d2 = d * d;
}
var attractiveForce = (d2 - k * k) / k;
node2.layoutForceX -= attractiveForce * dx / d;
node2.layoutForceY -= attractiveForce * dy / d;
node1.layoutForceX += attractiveForce * dx / d;
node1.layoutForceY += attractiveForce * dy / d;
}
// Move by the given force
for (i = 0; i < this.nodes.length; i++) {
node = this.nodes[i];
var xmove = c * node.layoutForceX;
var ymove = c * node.layoutForceY;
node.layoutPosX += xmove;
node.layoutPosY += ymove;
node.layoutForceX = 0;
node.layoutForceY = 0;
}
}
var newPositions = [];
for( i = 0 ; i < this.layer.containers.length ; i++) {
node = this.nodes[i];
newPositions.push([node.layoutPosX*200+400-40, node.layoutPosY*200+400-20]);
}
return newPositions;
}
|
Determine if method whose name and signature is specified is a monitor
wait operation.
@param methodName
name of the method
@param methodSig
signature of the method
@return true if the method is a monitor wait, false if not
|
public static boolean isMonitorWait(String methodName, String methodSig) {
return "wait".equals(methodName) && ("()V".equals(methodSig) || "(J)V".equals(methodSig) || "(JI)V".equals(methodSig));
}
|
// SetRateIncreaseCriteria sets the RateIncreaseCriteria field's value.
|
func (s *ExponentialRolloutRate) SetRateIncreaseCriteria(v *RateIncreaseCriteria) *ExponentialRolloutRate {
s.RateIncreaseCriteria = v
return s
}
|
Decrement the numeric data in the cache
@param string $id
@param int $value
@return int | bool
@throws OperationFailed
|
public function dec($id, $value = 1) {
if (! $this->connectionCheckStatus) {
$this->addServer();
}
$id = $this->prepareId($id);
$result = $this->getClient()->decrement($id, $value);
if ($result === false && $this->operationsExceptions) {
throw new OperationFailed('Decrementing of the data in the cache failed, ID: "' . $id . '"');
}
return $result;
}
|
Entry point for mutable map dsl.
@param map subject
@param nodeClass map class
@return operator
|
public static MapOperator with(final Map map, final Class<? extends Map> nodeClass) {
return new MapOperator(map, nodeClass);
}
|
Minimize chart junk by stripping out unnecessary plot borders and axis ticks.
The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn
|
def remove_border(axes=None, keep=('left', 'bottom'), remove=('right', 'top'), labelcol=ALMOST_BLACK):
ax = axes or plt.gca()
for spine in remove:
ax.spines[spine].set_visible(False)
for spine in keep:
ax.spines[spine].set_linewidth(0.5)
# ax.spines[spine].set_color('white')
# remove all ticks, then add back the ones in keep
# Does this also need to specify the ticks' colour, given the axes/labels are changed?
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_ticks_position('none')
# ax.xaxis.set_ticklabels("")
# ax.yaxis.set_ticklabels("")
for spine in keep:
if spine == 'top':
ax.xaxis.tick_top()
if spine == 'bottom':
ax.xaxis.tick_bottom()
# match the label colour to that of the axes
ax.xaxis.label.set_color(labelcol)
ax.xaxis.set_tick_params(color=labelcol, labelcolor=labelcol)
if spine == 'left':
ax.yaxis.tick_left()
ax.yaxis.label.set_color(labelcol)
ax.yaxis.set_tick_params(color=labelcol, labelcolor=labelcol)
if spine == 'right':
ax.yaxis.tick_right()
return
|
Given the name of an assembler, get the loaded assembler
ready for optimisation.
@param assembler [String] assembler name or shortname
@return [Biopsy::Target] the loaded assembler
|
def get_assembler assembler
ret = @assemblers.find do |a|
a.name == assembler ||
a.shortname == assembler
end
raise "couldn't find assembler #{assembler}" if ret.nil?
ret
end
|
Set image origin
Arguments
---------
new_origin : tuple or list
updated origin for the image.
should have one value for each dimension
Returns
-------
None
|
def set_origin(self, new_origin):
if not isinstance(new_origin, (tuple, list)):
raise ValueError('arg must be tuple or list')
if len(new_origin) != self.dimension:
raise ValueError('must give a origin value for each dimension (%i)' % self.dimension)
libfn = utils.get_lib_fn('setOrigin%s'%self._libsuffix)
libfn(self.pointer, new_origin)
|
// CountByOrganization Counts the amount of invitations, filtered by an organization
|
func (o *InvitationManager) CountByOrganization(globalid string) (int, error) {
count, err := o.collection.Find(bson.M{"organization": globalid}).Count()
return count, err
}
|
Create a new bare repository
|
def create(cls, path, encoding='utf-8'):
""""""
cmd = [GIT, 'init', '--quiet', '--bare', path]
subprocess.check_call(cmd)
return cls(path, encoding)
|
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MetadataOnlyObjectList.
|
func (in *MetadataOnlyObjectList) DeepCopy() *MetadataOnlyObjectList {
if in == nil {
return nil
}
out := new(MetadataOnlyObjectList)
in.DeepCopyInto(out)
return out
}
|
// PutGitMetadata implements the KeybaseService interface for
// KeybaseServiceBase.
|
func (k *KeybaseServiceBase) PutGitMetadata(
ctx context.Context, folder keybase1.Folder, repoID keybase1.RepoID,
metadata keybase1.GitLocalMetadata) error {
return k.gitClient.PutGitMetadata(ctx, keybase1.PutGitMetadataArg{
Folder: folder,
RepoID: repoID,
Metadata: metadata,
})
}
|
Returns the current image in a field.
This is meant to be used with image uploads so that users can see the current value.
@param type $FieldName
@param type $Attributes
@since 2.1
|
public function CurrentImage($FieldName, $Attributes = array()) {
$Result = $this->Hidden($FieldName);
$Value = $this->GetValue($FieldName);
if ($Value) {
TouchValue('class', $Attributes, 'CurrentImage');
$Result .= Img(Gdn_Upload::Url($Value), $Attributes);
}
return $Result;
}
|
Prepare static and dynamic search structures.
|
def _compile(self):
''' '''
self.static = {}
self.dynamic = []
def fpat_sub(m):
return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:'
for rule in self.rules:
target = self.routes[rule]
if not self.syntax.search(rule):
self.static[rule.replace('\\:',':')] = target
continue
gpat = self._compile_pattern(rule)
fpat = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, gpat.pattern)
gpat = gpat if gpat.groupindex else None
try:
combined = '%s|(%s)' % (self.dynamic[-1][0].pattern, fpat)
self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1])
self.dynamic[-1][1].append((gpat, target))
except (AssertionError, IndexError) as e: # AssertionError: Too many groups
self.dynamic.append((re.compile('(^%s$)'%fpat),
[(gpat, target)]))
except re.error as e:
raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, e))
|
// DistanceFrom computes an O(n) distance from the path. Loops over every
// subline to find the minimum distance.
|
func (p *Path) DistanceFrom(point *Point) float64 {
return math.Sqrt(p.SquaredDistanceFrom(point))
}
|
// initKeysDir initializes the keystore root directory. Usually it is ~/.tsh
|
func initKeysDir(dirPath string) (string, error) {
var err error
// not specified? use `~/.tsh`
if dirPath == "" {
u, err := user.Current()
if err != nil {
dirPath = os.TempDir()
} else {
dirPath = u.HomeDir
}
dirPath = filepath.Join(dirPath, defaultKeyDir)
}
// create if doesn't exist:
_, err = os.Stat(dirPath)
if err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(dirPath, os.ModeDir|profileDirPerms)
if err != nil {
return "", trace.ConvertSystemError(err)
}
} else {
return "", trace.Wrap(err)
}
}
return dirPath, nil
}
|
<p>
The group to modify for the snapshot.
</p>
@param groupNames
The group to modify for the snapshot.
|
public void setGroupNames(java.util.Collection<String> groupNames) {
if (groupNames == null) {
this.groupNames = null;
return;
}
this.groupNames = new com.amazonaws.internal.SdkInternalList<String>(groupNames);
}
|
Subsets and Splits
Golang Code and Comments
Retrieves all entries containing the term 'golang' in either the comment or code, providing a basic filter for data related to the Go programming language.