query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
from __future__ import print_function
from shapely.geometry import LineString
if __name__=="__main__":
line = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)])
print (line.simplify(1.0, preserve_topology=False))
| #include <iostream>
#include <cmath>
#include <utility>
#include <vector>
#include <stdexcept>
using namespace std;
typedef std::pair<double, double> Point;
double PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd)
{
double dx = lineEnd.first - lineStart.first;
double dy = lineEnd.... | codetrans_contest |
Adds admin pool sections.
@param ArrayNodeDefinition $node | private function addPoolsSection(ArrayNodeDefinition $node)
{
$node
->children()
->arrayNode('pools')
->addDefaultsIfNotSet()
->children()
->arrayNode('method')
->addDefaultsIfNotSet()
... | csn |
func convertStructDevice(in *Device) *proto.DetectedDevice {
if in == nil {
return nil
}
return &proto.DetectedDevice{
| ID: in.ID,
Healthy: in.Healthy,
HealthDescription: in.HealthDesc,
HwLocality: convertStructDeviceLocality(in.HwLocality),
}
} | csn_ccr |
Return whether the hostname and port combination was already seen | def _server_known(cls, host, port):
"""
Return whether the hostname and port combination was already seen
"""
with PostgreSql._known_servers_lock:
return (host, port) in PostgreSql._known_servers | csn |
// RunAndCaptureOSCommand runs the given command and
// captures the stdout and stderr | func RunAndCaptureOSCommand(cmd *exec.Cmd,
stdoutWriter io.Writer,
stderrWriter io.Writer,
logger *logrus.Logger) error {
logger.WithFields(logrus.Fields{
"Arguments": cmd.Args,
"Dir": cmd.Dir,
"Path": cmd.Path,
"Env": cmd.Env,
}).Debug("Running Command")
cmd.Stdout = stdoutWriter
cmd.St... | csn |
Gets the alias
@return string | public function getAlias() {
//Check and see if there is another relationship with the same name
$multipleFound = false;
foreach($this->getRelationships() as $relationship) {
if($relationship !== $this && $relationship->getRemoteTable() == $this->getRemoteTable()) {
$... | csn |
// NewNamespace creates a new namespace. | func NewNamespace() Namespace {
return &namespace{
taken: make(map[string]struct{}),
gave: make(map[string][]string),
}
} | csn |
A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function.
## Input
The input for your function will be an array with a list of common duc... | def create_report(names):
result = {}
for name in names:
if name.startswith("Labrador Duck"):
return ["Disqualified data"]
name = name.upper().replace("-", " ").split()
count = int(name.pop())
if len(name) == 1: code = name[0][:6]
eli... | apps |
Search the factory that can handle the type.
@param string $taskType The task type to search.
@return null|TaskFactoryInterface | private function getFactoryForType($taskType)
{
foreach ($this->factories as $factory) {
if ($factory->isTypeSupported($taskType)) {
return $factory;
}
}
return null;
} | csn |
Creates a padding by the remaining space after scaling the content.
E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and
Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0)
because the content would not be scaled (since scale_h=1) and therefore
t... | def from_scale(scale_w, scale_h=None):
"""Creates a padding by the remaining space after scaling the content.
E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and
Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0)
because the content would not b... | csn |
public function add($key, $message)
{
if ($this->unique($key, | $message)) $this->messages[$key][] = $message;
} | csn_ccr |
def call(self, addr, args, continue_at, cc=None):
"""
Add an exit representing calling another function via pointer.
:param addr: The address of the function to call
:param args: The list of arguments to call the function with
:param continue_at: Later, when the ca... | if isinstance(call_state.addr, SootAddressDescriptor):
pass
elif call_state.libc.ppc64_abiv == 'ppc64_1':
call_state.regs.r2 = self.state.mem[addr + 8:].long.resolved
addr = call_state.mem[addr:].long.resolved
elif call_state.arch.name in ('MIPS32', 'MIPS64'):
... | csn_ccr |
Download a plugin, unzip it and rename it
@param $req
@param $res
@param $args
@return mixed
@throws RunBBException | public function download($req, $res, $args)
{
$repoList = Container::get('remote')->getExtensionsInfoList();
// not care about indexes, simple retrieve twice
// get category
$category = Utils::recursiveArraySearch($args['name'], $repoList);
// get plugin
$plugKey = Ut... | csn |
public function deploy($environment)
{
$supervisors = collect($this->parsed)->first(function ($_, $name) use ($environment) {
return Str::is($name, $environment);
});
if (empty($supervisors)) {
return; |
}
foreach ($supervisors as $supervisor => $options) {
$this->add($options);
}
} | csn_ccr |
def get_token(self, appname, username, password):
"""
get the security token by connecting to TouchWorks API
"""
ext_exception = TouchWorksException(
TouchWorksErrorMessages.GET_TOKEN_FAILED_ERROR)
data = {'Username': username,
'Password': password... |
uuid.UUID(resp.text, version=4)
return SecurityToken(resp.text)
except ValueError:
logger.error('response was not valid uuid string. %s' % resp.text)
raise ext_exception
except Exception as ex:
logger.exception(ex)
... | csn_ccr |
protected function preparePropertyDefinitionData(array $data)
{
$data[JSONConstants::JSON_PROPERTY_TYPE_PROPERTY_TYPE] = PropertyType::cast(
$data[JSONConstants::JSON_PROPERTY_TYPE_PROPERTY_TYPE]
);
if (isset($data[JSONConstants::JSON_PROPERTY_TYPE_DEAULT_VALUE])) {
... | $data[JSONConstants::JSON_PROPERTY_TYPE_RESOLUTION]
);
}
if (isset($data[JSONConstants::JSON_PROPERTY_TYPE_PRECISION])) {
$data[JSONConstants::JSON_PROPERTY_TYPE_PRECISION] = DecimalPrecision::cast(
$data[JSONConstants::JSON_PROPERTY_TYPE_PRECISION]
... | csn_ccr |
def open(self, mode='a', **kwargs):
"""
Open the file in the specified mode
Parameters
----------
mode : {'a', 'w', 'r', 'r+'}, default 'a'
See HDFStore docstring or tables.open_file for info about modes
"""
tables = _tables()
if self._mode !... | "PyTables [{version}] no longer supports opening multiple "
"files\n"
"even in read-only mode on this HDF5 version "
"[{hdf_version}]. You can accept this\n"
"and not open the same file multiple times at once,\n"
... | csn_ccr |
Percent encode values per custom specification | function percentEscape(value) {
// Percent-escape per specification
var escapedString = '';
for (var i = 0; i < value.length; i++) {
var char = value.charCodeAt(i);
if ((char >= 48 && char <= 57) || // 09
(char >= 65 && char <= 90) || // AZ
(char >= 9... | csn |
use kwargs with a dict in python | def _sourced_dict(self, source=None, **kwargs):
"""Like ``dict(**kwargs)``, but where the ``source`` key is special.
"""
if source:
kwargs['source'] = source
elif self.source:
kwargs['source'] = self.source
return kwargs | cosqa |
Reloads the space. | def reload(self):
"""
Reloads the space.
"""
result = self._client._get(
self.__class__.base_url(
self.sys['id']
)
)
self._update_from_resource(result)
return self | csn |
Chef has arrived in Dagobah to meet with Yoda to study cooking. Yoda is a very busy cook and he doesn't want to spend time with losers. So he challenges the Chef to a series of games, and agrees to teach the Chef if Chef can win at least P of the games. The total number of games is K. The games will be played on a ches... | import math
dp = []
dp.append(0)
for i in range(1,1000005):
dp.append(math.log(i) + dp[i-1])
t = int(input())
for i in range(t):
n,m,p,k = input().split()
n = int(n)
m = int(m)
p = int(p)
k = int(k)
if p==0 or (n%2==0 and m%2==0):
ans = 1.0
print(ans)
elif n%2==1 and m%2==1:
ans=0.0
print(ans*100)
e... | apps |
public static <T extends Number> Func2<T, T, T> add() {
return new Func2<T, T, T>() {
@SuppressWarnings("unchecked")
@Override
public T call(T a, T b) {
if (a instanceof Integer)
return (T) (Number) (a.intValue() + b.intValue());
... | return (T) (Number) (a.floatValue() + b.floatValue());
else if (a instanceof Byte)
return (T) (Number) (a.byteValue() + b.byteValue());
else if (a instanceof Short)
return (T) (Number) (a.shortValue() + b.shortValue());
... | csn_ccr |
Evaluate inline comments at the tail of source code. | def evaluate_inline_tail(self, groups):
"""Evaluate inline comments at the tail of source code."""
if self.lines:
self.line_comments.append([groups['line'][2:].replace('\\\n', ''), self.line_num, self.current_encoding]) | csn |
// ManagedState returns a new managed state with the statedb as it's backing layer | func ManageState(statedb *StateDB) *ManagedState {
return &ManagedState{
StateDB: statedb.Copy(),
accounts: make(map[common.Address]*account),
}
} | csn |
// NewPostgreSQLTarget - creates new PostgreSQL target. | func NewPostgreSQLTarget(id string, args PostgreSQLArgs) (*PostgreSQLTarget, error) {
params := []string{args.ConnectionString}
if !args.Host.IsEmpty() {
params = append(params, "host="+args.Host.String())
}
if args.Port != "" {
params = append(params, "port="+args.Port)
}
if args.User != "" {
params = appe... | csn |
def _run_step(step_obj, step_declaration, initialized_resources):
"""Actually run a step."""
start_time = time.time()
# Open any resources that need to be opened before we run this step
for res_name in step_declaration.resources.opened:
initialized_resources[res_name].open()
# Create a di... | out = step_obj.run(resources=used_resources)
else:
out = step_obj.run()
# Close any resources that need to be closed before we run this step
for res_name in step_declaration.resources.closed:
initialized_resources[res_name].close()
end_time = time.time()
return (end_time - ... | csn_ccr |
public GwtValidationContext<T> appendKey(final String name, final Object key) {
final GwtValidationContext<T> temp = new GwtValidationContext<>(this.rootBeanClass,
this.rootBean, this.beanDescriptor, this.messageInterpolator, this.traversableResolver,
this.validator, this.validatedObjects);
temp... | PathImpl.createCopy(this.path);
temp.path.addPropertyNode(name);
NodeImpl.makeIterableAndSetMapKey(temp.path.getLeafNode(), key);
return temp;
} | csn_ccr |
// parseResponse is a helper function that was refactored out so that the XML parsing behavior can be isolated and unit tested | func parseResponse(xml []byte) (*etree.Document, *etree.Element, error) {
var doc *etree.Document
err := maybeDeflate(xml, func(xml []byte) error {
doc = etree.NewDocument()
return doc.ReadFromBytes(xml)
})
if err != nil {
return nil, nil, err
}
el := doc.Root()
if el == nil {
return nil, nil, fmt.Erro... | csn |
// SetMinPoW sets the minimum PoW, and notifies the peers. | func (api *PublicWhisperAPI) SetMinPoW(ctx context.Context, pow float64) (bool, error) {
return true, api.w.SetMinimumPoW(pow)
} | csn |
def _add_umis_with_fastp(read_fq, umi_fq, out_fq, cores):
"""Add UMIs to reads from separate UMI file using fastp.
"""
with utils.open_gzipsafe(umi_fq) as in_handle:
in_handle.readline() # name
umi_size = len(in_handle.readline().strip())
cmd = ("fastp -Q -A -L -G -w 1 --in1 {read_fq} -... | "
"--out1 >(bgzip --threads {cores} -c > {out_fq}) --out2 /dev/null "
"-j /dev/null -h /dev/null")
do.run(cmd.format(**locals()), "Add UMIs to fastq file with fastp") | csn_ccr |
Check offline configuration file | def check_offline_configuration(self):
''' Check offline configuration file'''
quit_on_start = False
database_url = self.config.get('Database Parameters', 'database_url')
host = self.config.get('Server Parameters', 'host', 'localhost')
if database_url[:6] != 'sqlite':
... | csn |
Download RAW data as SRA file.
The files will be downloaded to the sample directory created ad hoc
or the directory specified by the parameter. The sample has to come
from sequencing eg. mRNA-seq, CLIP etc.
An important parameter is a filetype. By default an SRA
is accessed by ... | def download_SRA(self, email, directory='./', **kwargs):
"""Download RAW data as SRA file.
The files will be downloaded to the sample directory created ad hoc
or the directory specified by the parameter. The sample has to come
from sequencing eg. mRNA-seq, CLIP etc.
An importan... | csn |
Logs an error.
@param logger
reference to the logger
@param e
reference to the error | public static void logError(final Logger logger, final Error e)
{
logger.logError(Level.ERROR, "Unexpected Error", e);
} | csn |
function (sControlName) {
return APIInfo.getIndexJsonPromise().then(function (aData) {
function findSymbol (a) {
return a.some(function (o) {
var bFound = o.name === sControlName;
if (!bFound && o.nodes) {
return | findSymbol(o.nodes);
}
return bFound;
});
}
return findSymbol(aData);
});
} | csn_ccr |
func (dns *dnsControl) HasSynced() bool {
a := dns.svcController.HasSynced()
b := true
if dns.epController != nil {
b = dns.epController.HasSynced()
}
c := true
if dns.podController != nil {
| c = dns.podController.HasSynced()
}
d := dns.nsController.HasSynced()
return a && b && c && d
} | csn_ccr |
def await_flush_completion(self, timeout=None):
"""
Mark all partitions as ready to send and block until the send is complete
"""
try:
for batch in self._incomplete.all():
log.debug('Waiting on produce to %s',
batch.produce_future.top... | raise Errors.UnknownError('Future not done')
if batch.produce_future.failed():
log.warning(batch.produce_future.exception)
finally:
self._flushes_in_progress.decrement() | csn_ccr |
def users
if text?
@server.online_members(include_idle: true).select { |u| u.can_read_messages? self }
elsif voice? |
@server.voice_states.map { |id, voice_state| @server.member(id) if !voice_state.voice_channel.nil? && voice_state.voice_channel.id == @id }.compact
end
end | csn_ccr |
public function getFullUrl(string $name = '')
{
if (!isset($this->media[0])) {
return null;
}
return $this->media[0]->disk === 's3'
| ? $this->media[0]->getTemporaryUrl(new \DateTime('+1 hour'))
: $this->media[0]->getFullUrl($name);
} | csn_ccr |
Import a CSV from a string or filename and return array.
The filename can be either a resource from fopen() or a string containing the csv data. Filenames will be wrapped trough {{Yii::getAlias()}} method.
@param string $filename Can be either a filename which is parsed by {{luya\helpers\FileHelper::getFileContent()}... | public static function csv($filename, array $options = [])
{
$filename = Yii::getAlias($filename);
// check if a given file name is provided or a csv based on the content
if (FileHelper::getFileInfo($filename)->extension) {
$resource = fopen($filename, 'r');
} el... | csn |
Generate the correct URL for serving a file direct from the file system
@param $sObject
@param $sBucket
@return string | public function urlServeRaw($sObject, $sBucket)
{
$sUrl = 'assets/uploads/' . $sBucket . '/' . $sObject;
return $this->urlMakeSecure($sUrl, false);
} | csn |
Updates the given product grouping.
@param Request $request
@param Product $itemgroup
@return void | public function update(Request $request, Product $itemgroup)
{
$itemgroup->groupWith(
$request->get('associates')
);
return redirect()
->route('itemgroup.edit', $itemgroup)
->with('status', trans('globals.success_text'));
} | csn |
private static AlluxioFuseOptions parseOptions(String[] args, AlluxioConfiguration alluxioConf) {
final Options opts = new Options();
final Option mntPoint = Option.builder("m")
.hasArg()
.required(true)
.longOpt("mount-point")
.desc("Desired local mount point for alluxio-fuse.")... | // keep the -o
for (final String fopt: fopts) {
fuseOpts.add("-o" + fopt);
if (noUserMaxWrite && fopt.startsWith("max_write")) {
noUserMaxWrite = false;
}
}
}
// check if the user has specified his own max_write, otherwise get it
// from ... | csn_ccr |
public static function validateType($type)
{
if (!in_array($type, [self::TYPE_INFO, self::TYPE_SUCCESS, self::TYPE_WARNING, | self::TYPE_ERROR])) {
throw new \InvalidArgumentException('Invalid resource message type "%s".', $type);
}
} | csn_ccr |
def migrate_value(value):
"""Convert `value` to a new-style value, if necessary and possible.
An "old-style" value is a value that uses any `value` field other than
the `tensor` field. A "new-style" value is a value that uses the
`tensor` field. TensorBoard continues to support old-style values on
disk; this... | A `Summary.Value` object. This argument is not modified.
Returns:
If the `value` is an old-style value for which there is a new-style
equivalent, the result is the new-style value. Otherwise---if the
value is already new-style or does not yet have a new-style
equivalent---the value will be returned ... | csn_ccr |
Let's call some positive integer classy if its decimal representation contains no more than $3$ non-zero digits. For example, numbers $4$, $200000$, $10203$ are classy and numbers $4231$, $102306$, $7277420000$ are not.
You are given a segment $[L; R]$. Count the number of classy integers $x$ such that $L \le x \le R$... |
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
# this math tutorial is boring
classy=set()
for i in range(19):
for j in range(i):
for k in range(j):
for a in range(10): # a=0 for good measure
for b in range(10):
for c in range(10):
... | apps |
// Create new account | func (c *Client) CreateAccount(ctx context.Context, path string, payload *CreateAccountPayload, contentType string) (*http.Response, error) {
req, err := c.NewCreateAccountRequest(ctx, path, payload, contentType)
if err != nil {
return nil, err
}
return c.Client.Do(ctx, req)
} | csn |
Check if the cell is considered big.
@param CellFeature cell_detection:
@return: | def is_cell_big(self, cell_detection):
"""
Check if the cell is considered big.
@param CellFeature cell_detection:
@return:
"""
return cell_detection.area > self.parameters_tracking["big_size"] * self.scale * self.scale | csn |
def largest_sphere(target, fixed_diameter='pore.fixed_diameter', iters=5):
r"""
Finds the maximum diameter pore that can be placed in each location without
overlapping any neighbors.
This method iteratively expands pores by increasing their diameter to
encompass half of the distance to the nearest ... | AFTER this model is
run, the pores will overlap. This can be remedied by running this model
again.
"""
network = target.project.network
P12 = network['throat.conns']
C1 = network['pore.coords'][network['throat.conns'][:, 0]]
C2 = network['pore.coords'][network['throat.conns'][:, 1]]
L... | csn_ccr |
Deletes objects that match a set of conditions supplied.
This method forwards filters directly to the repository. It does not instantiate entities and
it does not trigger Entity callbacks or validations.
Returns the number of objects matched and deleted. | def delete_all(self, *args, **kwargs):
"""Deletes objects that match a set of conditions supplied.
This method forwards filters directly to the repository. It does not instantiate entities and
it does not trigger Entity callbacks or validations.
Returns the number of objects matched an... | csn |
Set a bot variable.
Equivalent to ``! var`` in RiveScript code.
:param str name: The name of the variable to set.
:param str value: The value of the variable.
Set this to ``None`` to delete the variable. | def set_variable(self, name, value):
"""Set a bot variable.
Equivalent to ``! var`` in RiveScript code.
:param str name: The name of the variable to set.
:param str value: The value of the variable.
Set this to ``None`` to delete the variable.
"""
if value i... | csn |
Return the production name for a glyph name from the GlyphData.xml
database according to the AGL specification.
This should be run only if there is no official entry with a production
name in it.
Handles single glyphs (e.g. "brevecomb") and ligatures (e.g.
"brevecomb_acutecomb"). Returns None when... | def _construct_production_name(glyph_name, data=None):
"""Return the production name for a glyph name from the GlyphData.xml
database according to the AGL specification.
This should be run only if there is no official entry with a production
name in it.
Handles single glyphs (e.g. "brevecomb") and... | csn |
# Task
Elections are in progress!
Given an array of numbers representing votes given to each of the candidates, and an integer which is equal to the number of voters who haven't cast their vote yet, find the number of candidates who still have a chance to win the election.
The winner of the election must secure stri... | def elections_winners(votes, k):
m = max(votes)
return sum(x + k > m for x in votes) or votes.count(m) == 1 | apps |
An error thrown during verification. Can be either
a mempool transaction validation error or a blockchain
block verification error. Ultimately used to send
`reject` packets to peers.
@constructor
@extends Error
@param {Block|TX} msg
@param {String} code - Reject packet code.
@param {String} reason - Reject packet reaso... | function VerifyError(msg, code, reason, score, malleated) {
Error.call(this);
assert(typeof code === 'string');
assert(typeof reason === 'string');
assert(score >= 0);
this.type = 'VerifyError';
this.message = '';
this.code = code;
this.reason = reason;
this.score = score;
this.hash = msg.hash('he... | csn |
Limits the result count to the number specified.
>>> df.limit(1).collect()
[Row(age=2, name=u'Alice')]
>>> df.limit(0).collect()
[] | def limit(self, num):
"""Limits the result count to the number specified.
>>> df.limit(1).collect()
[Row(age=2, name=u'Alice')]
>>> df.limit(0).collect()
[]
"""
jdf = self._jdf.limit(num)
return DataFrame(jdf, self.sql_ctx) | csn |
# Task
Given a `sequence` of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it.
# Example
For `sequence = [1, 3, 2, 1]`, the output should be `false`;
For `sequence = [1, 3, 2]`, the output should be `true`.
# Input/Output
- `[input]` ... | def almost_increasing_sequence(sequence):
save, first = -float('inf'), True
for i,x in enumerate(sequence):
if x > save: save = x
elif first:
if i == 1 or x > sequence[i-2]: save = x
first = False
else: return False
return True | apps |
Initiates a password reset request for the user with the specified email address
The callback function must have the following signature:
`function ($selector, $token)`
Both pieces of information must be sent to the user, usually embedded in a link
When the user wants to proceed to the second step of the password r... | public function forgotPassword($email, callable $callback, $requestExpiresAfter = null, $maxOpenRequests = null) {
$email = self::validateEmailAddress($email);
$this->throttle([ 'enumerateUsers', $this->getIpAddress() ], 1, (60 * 60), 75);
if ($requestExpiresAfter === null) {
// use six hours as the default
... | csn |
function sendBinary ( $to, $from, $body, $udh ) {
//Binary messages must be hex encoded
$body = bin2hex ( $body );
$udh = bin2hex ( $udh );
// Make sure $from is valid
$from = $this->validateOriginator($from);
// Send away!
$post = | array(
'from' => $from,
'to' => $to,
'type' => 'binary',
'body' => $body,
'udh' => $udh
);
return $this->sendRequest ( $post );
} | csn_ccr |
// NewApplicationResourceActionsListCommand returns a new instance of an `argocd app actions list` command | func NewApplicationResourceActionsListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
var namespace string
var kind string
var group string
var resourceName string
var all bool
var command = &cobra.Command{
Use: "list APPNAME",
Short: "Lists available actions on a resource",
}
command.Run... | csn |
func MustParseModule(input string) *Module {
parsed, | err := ParseModule("", input)
if err != nil {
panic(err)
}
return parsed
} | csn_ccr |
Overwrites an argument.
@param string $argument
@param string|array $value | protected function overwriteArgument($argument, $value)
{
$arguments = $this->arguments();
$arguments[$argument] = $value;
$this->arguments($arguments);
} | csn |
// ExtractPrivateKeyAttributes extracts role and gun values from private key bytes | func ExtractPrivateKeyAttributes(pemBytes []byte) (data.RoleName, data.GUN, error) {
return extractPrivateKeyAttributes(pemBytes, notary.FIPSEnabled())
} | csn |
Create the application from the configured schema file name. | private void createApplication() {
String schema = getSchema();
ContentType contentType = null;
if (m_config.schema.toLowerCase().endsWith(".json")) {
contentType = ContentType.APPLICATION_JSON;
} else if (m_config.schema.toLowerCase().endsWith(".xml")) {
co... | csn |
def use_google_symbol(fct):
'''
Removes ".PA" or other market indicator from yahoo symbol
convention to suit google convention
'''
def decorator(symbols):
google_symbols = []
# If one symbol string
if isinstance(symbols, str):
symbols = [symbols]
symbols... | symbol[:dot_pos] if (dot_pos > 0) else symbol)
data = fct(google_symbols)
#NOTE Not very elegant
data.columns = [s for s in symbols if s.split('.')[0] in data.columns]
return data
return decorator | csn_ccr |
function(page) {
if (this.output.name != 'website' || page.search === false) {
return page;
}
var text;
this.log.debug.ln('index page', page.path);
text = page.content;
// Decode HTML
text = Html.decode(tex... | text = text.replace(/[\n ]+/g, ' ');
var keywords = [];
if (page.search) {
keywords = page.search.keywords || [];
}
// Add to index
var doc = {
url: this.output.toURL(page.path),
title: page.title,
... | csn_ccr |
uses the array previously returned by 'getKeyframeOrder' to sort data | function( values, stride, order ) {
var nValues = values.length;
var result = new values.constructor( nValues );
for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
var srcOffset = order[ i ] * stride;
for ( var j = 0; j !== stride; ++ j ) {
result[ dstOffset ++ ] = values[ srcOffset + ... | csn |
Extend an error of some sort into a DiscordjsError.
@param {Error} Base Base error to extend
@returns {DiscordjsError} | function makeDiscordjsError(Base) {
return class DiscordjsError extends Base {
constructor(key, ...args) {
super(message(key, args));
this[kCode] = key;
if (Error.captureStackTrace) Error.captureStackTrace(this, DiscordjsError);
}
get name() {
return `${super.name} [${this[kCode]}... | csn |
func (c *Command) Start() error {
cmd, err := c.buildCmd()
if err != nil {
return err
}
cmd.Stdout = logfile(c.GetLogfile())
cmd.Stderr = logfile(c.GetLogfile())
if c.WorkingDir != "" {
cmd.Dir = c.WorkingDir
}
if c.UseEnv {
flagEnv := filepath.Join(cmd.Dir, | ".env")
env, _ := ReadEnv(flagEnv)
cmd.Env = env.asArray()
} else if len(c.Env) > 0 {
cmd.Env = c.Env.asArray()
}
pid, err := start(cmd)
if err != nil {
return err
}
c.Pid = pid
return nil
} | csn_ccr |
func (c *client) CreateDatabase(ctx context.Context, name string, options *CreateDatabaseOptions) (Database, error) {
input := struct {
CreateDatabaseOptions
Name string `json:"name"`
}{
Name: name,
}
if options != nil {
input.CreateDatabaseOptions = *options
}
req, err := c.conn.NewRequest("POST", path.J... | req)
if err != nil {
return nil, WithStack(err)
}
if err := resp.CheckStatus(201); err != nil {
return nil, WithStack(err)
}
db, err := newDatabase(name, c.conn)
if err != nil {
return nil, WithStack(err)
}
return db, nil
} | csn_ccr |
public function describe()
{
return $this->option ? $this->option->describe() : |
sprintf('%s \'%s\'', GetOpt::translate(static::TRANSLATION_KEY), $this->getName());
} | csn_ccr |
def status_message(self):
"""Detailed message about whether the dependency is installed.
:rtype: str
"""
if self.is_available:
return "INSTALLED {0!s}"
elif self.why and self.package:
return "MISSING {0!s:<20}needed for {0.why}, part of the {0.package} ... | return "MISSING {0!s:<20}needed for {0.why}"
elif self.package:
return "MISSING {0!s:<20}part of the {0.package} package"
else:
return "MISSING {0!s:<20}" | csn_ccr |
// LExpireAt expires the list at when. | func (db *DB) LExpireAt(key []byte, when int64) (int64, error) {
if when <= time.Now().Unix() {
return 0, errExpireValue
}
return db.lExpireAt(key, when)
} | csn |
func makeSquareMapping(face font.Face, runes []rune, padding fixed.Int26_6) (map[rune]fixedGlyph, fixed.Rectangle26_6) {
width := sort.Search(int(fixed.I(1024*1024)), func(i int) bool {
width := fixed.Int26_6(i)
_, bounds := makeMapping(face, runes, padding, width) |
return bounds.Max.X-bounds.Min.X >= bounds.Max.Y-bounds.Min.Y
})
return makeMapping(face, runes, padding, fixed.Int26_6(width))
} | csn_ccr |
Check if ``path1`` is a parent directory of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path1`` is a parent directory of ``path2``
Example:
>>> isparent("foo/bar", "foo/bar/spam.txt")
True
... | def isparent(path1, path2):
# type: (Text, Text) -> bool
"""Check if ``path1`` is a parent directory of ``path2``.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str): A PyFilesytem path.
Returns:
bool: `True` if ``path1`` is a parent directory of ``path2``
Example:
... | csn |
Perform sigma clipping on an array, ignoring non finite values.
During each iteration return an array whose elements c obey:
mean -std*lo < c < mean + std*hi
where mean/std are the mean std of the input array.
Parameters
----------
arr : iterable
An iterable array of numeric types.
... | def sigmaclip(arr, lo, hi, reps=3):
"""
Perform sigma clipping on an array, ignoring non finite values.
During each iteration return an array whose elements c obey:
mean -std*lo < c < mean + std*hi
where mean/std are the mean std of the input array.
Parameters
----------
arr : iterabl... | csn |
public function read()
{
if (!$this->active || $this->reachedEnd) {
return false;
}
if ($frame = $this->client->readFrame()) {
if ($this->stopOnEnd && $frame['browser'] == 'end') {
| $this->reachedEnd = true;
return false;
}
}
return $frame;
} | csn_ccr |
Copy the artifact at `src_path` with hash `artifact_hash` to artifacts
cache dir.
If an artifact already exists at that location, it is assumed to be
identical (since it's based on hash), and the copy is skipped.
TODO: pruning policy to limit cache size. | def copy_artifact(src_path: str, artifact_hash: str, conf: Config):
"""Copy the artifact at `src_path` with hash `artifact_hash` to artifacts
cache dir.
If an artifact already exists at that location, it is assumed to be
identical (since it's based on hash), and the copy is skipped.
TODO: pruni... | csn |
Return an array of object with the categories of the post
stdClass Object
(
[term_id] => int
[name] => string
[slug] => string
[term_group] => int
[term_taxonomy_id] => int
[taxonomy] => category
[description] => string
[parent] => int
[count] => int
[permalink] => string
)
@return Collection | public function presentCategories()
{
$args = array(
'fields' => 'all',
'orderby' => 'name',
'order' => 'ASC'
);
$categories = wp_get_post_categories($this->ID, $args);
if (count($categories) == 0 || !$categories)
{
return null;
}
$cats = array();
foreach ($categories as $c)
{... | csn |
// ExtractExtraHeaders returns the first found ExtraHeadersOption from the
// given variadic arguments or nil otherwise. If multiple options are found, the
// inner maps are merged. | func ExtractExtraHeaders(opts ...interface{}) *opt.ExtraHeadersOption {
merged := make(map[string]string)
for _, o := range opts {
if v, ok := o.(*opt.ExtraHeadersOption); ok {
for key, value := range v.Get() {
merged[key] = value
}
}
}
if len(merged) == 0 {
return nil
}
return opt.ExtraHeaders... | csn |
Called when a new file or directory is created.
Todo:
This should be also used (extended from another class?) to watch
for some special name file (like ".boussole-watcher-stop" create to
raise a KeyboardInterrupt, so we may be able to unittest the
watcher (click.... | def on_created(self, event):
"""
Called when a new file or directory is created.
Todo:
This should be also used (extended from another class?) to watch
for some special name file (like ".boussole-watcher-stop" create to
raise a KeyboardInterrupt, so we may be... | csn |
def apply_code!(letter, *pars)
case letter
when 'A'
@cur_row -= pars[0] ? pars[0] : 1
@cur_row = @max_row if @max_row and @cur_row > @max_row
when 'B'
@cur_row += pars[0] ? pars[0] : 1
@cur_row = @max_row if @max_row and @cur_row > @max_row
when 'C'
@cur_col += pars[0] ? pars[0] : 1
w... | 1
@cur_col = pars[1] ? pars[1] : 1
@max_row = @cur_row if @max_row and @cur_row > @max_row
when 'f'
@cur_row = pars[0] ? pars[0] : 1
@cur_col = pars[1] ? pars[1] : 1
@max_row = @cur_row if @max_row and @cur_row > @max_row
end
if @cur_row < 1
@cur_row = 1
end
if @cur_col < 1
@... | csn_ccr |
public static void setNoCache(HttpServletRequest request,
HttpServletResponse response)
{
//get rid of unwanted whitespace
String protocol = request.getProtocol().trim();
// if ("HTTP/1.0".equals(protocol))
{
response.setHeader("Pragma", "no-cache");
}
// else if ("HTTP/1.1".equals(pr... | //Internet Explorer:
//date and timestamp will be set to jan 1st 1970, so no caching is performed.
// response.setDateHeader("Expires", 0);
}
long now = System.currentTimeMillis();
response.setDateHeader("Date", now);
response.setDateHeader("Expires", now);
response.setDateHeader("Last-Modified"... | csn_ccr |
function _getMessageConsumer(channel, handle, validate, routingKey) {
return function* _consumeMessage(message) {
try {
logger.debug({ message, routingKey }, '[worker#listen] received message');
const content = _parseMessage(message);
if (!content) return channel.ack(message);
... | if (_.isError(validatedContent)) return channel.ack(message);
const handleSuccess = yield _handleMessage(
handle,
validatedContent || content,
message.fields
);
if (!handleSuccess) return channel.nack(message);
return channel.ack(message);
} c... | csn_ccr |
public static function stderr($text, $raw = false)
{
if ($raw) {
return fwrite(STDERR, $text);
} elseif (extension_loaded('posix') && | posix_isatty(STDERR)) {
return fwrite(STDERR, static::colorize($text));
} else {
return fwrite(STDERR, static::decolorize($text));
}
} | csn_ccr |
Write msg on stdout. If no encoding is specified
the detected encoding of stdout is used. If the encoding
can't encode some chars they are replaced by '?'
:param msg: message
:type msg: unicode on python2 | str on python3 | def printo(msg, encoding=None, errors='replace', std_type='stdout'):
"""Write msg on stdout. If no encoding is specified
the detected encoding of stdout is used. If the encoding
can't encode some chars they are replaced by '?'
:param msg: message
:type msg: unicode on python2 | str on python3
"... | csn |
// pollStdOutAndErr polls std out and err | func (p *RemoteMonitor) pollStdOutAndErr(
cmd *exec.Cmd,
contextID string,
) (err error) {
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
// Stdout/err processing
go processIOReader(stdout, contextID)
go processIOReader(stderr,... | csn |
Set the error mode.
@param int $errorMode
@return $this | public function setErrorMode($errorMode)
{
if (in_array($errorMode, [\PDO::ERRMODE_SILENT, \PDO::ERRMODE_WARNING, \PDO::ERRMODE_EXCEPTION])) {
$this->errorMode = $errorMode;
}
return $this;
} | csn |
public static function replaceAttributes($xml, $tagName, callable $callback)
{
if (strpos($xml, '<' . $tagName) === false)
{
return $xml;
}
return preg_replace_callback(
'((<' . preg_quote($tagName) . ')(?=[ />])[^>]*?(/?>))',
function ($m) use ($callback)
| {
return $m[1] . self::serializeAttributes($callback(self::parseAttributes($m[0]))) . $m[2];
},
$xml
);
} | csn_ccr |
protected function getTargetRow(): array
{
$row = $this->dictionary->getRow($this->targetId);
if (!$row) {
| throw new TranslationNotFoundException($this->getKey(), $this->dictionary);
}
return $row;
} | csn_ccr |
Cleanly shutdown the server. | def shutdown_server(self):
"""
Cleanly shutdown the server.
"""
if not self._closing:
self._closing = True
else:
log.warning("Close is already in progress")
return
if self._server:
self._server.close()
yield fr... | csn |
Sets the designated parameter to the query name of the given type.
@param integer $parameterIndex the parameter index (one-based)
@param ObjectTypeInterface $type the object type | public function setType($parameterIndex, ObjectTypeInterface $type)
{
$this->setParameter($parameterIndex, $this->escape($type->getQueryName()));
} | csn |
protected function text_content($content) {
if (!is_null($this->contenttransformer)) { // Apply content transformation
| $content = $this->contenttransformer->process($content);
}
return is_null($content) ? null : $this->xml_safe_text_content($content); // Safe UTF-8 and encode
} | csn_ccr |
// Format returns the parameters separated by spaces except for filename and
// line which are separated by a colon. | func DefaultFormatter(entry loggo.Entry) string {
// Just get the basename from the filename
filename := filepath.Base(entry.Filename)
return fmt.Sprintf("%s %s:%d %s", entry.Module, filename, entry.Line, entry.Message)
} | csn |
Returns the list of fields of the given table, and if empty the list of fields for each table.
@param string $table
@return array|null | public function get_fields(string $table = ''): ?array
{
if ( !empty($this->class_cfg) ){
if ( $table ){
return $this->class_cfg['arch'][$table] ?? null;
}
return $this->class_cfg['arch'];
}
return null;
} | csn |
// RemoteConnectionStatus returns summary information about connections to the specified offer. | func (st *State) RemoteConnectionStatus(offerUUID string) (*RemoteConnectionStatus, error) {
conns, err := st.OfferConnections(offerUUID)
if err != nil {
return nil, errors.Trace(err)
}
result := &RemoteConnectionStatus{
totalCount: len(conns),
}
for _, conn := range conns {
rel, err := st.KeyRelation(conn.... | csn |
public final void cancelOperation(String projectId, String zone, String operationId) {
CancelOperationRequest request =
CancelOperationRequest.newBuilder()
.setProjectId(projectId)
| .setZone(zone)
.setOperationId(operationId)
.build();
cancelOperation(request);
} | csn_ccr |
def date_to_datetime(self, time_input, tz=None):
""" Convert ISO 8601 and other date strings to datetime.datetime type.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
Returns:
(datetime... | timezone
if tz is not None and tz != dt.tzname():
if dt.tzinfo is None:
dt = self._replace_timezone(dt)
dt = dt.astimezone(timezone(tz))
except IndexError:
pass
except TypeError:
pass
except ValueError:
... | csn_ccr |
private function getRequestBody(array $parameters, array $files)
{
$body = array();
foreach ($parameters as $parameterName => $parameterValue) {
if (is_scalar($parameterValue) || (is_null($parameterValue) && $parameterName !== 'id')) {
$body[] = array(
... | if (is_resource($fileResource)) {
$metaData = stream_get_meta_data($fileResource);
$body[] = array(
'name' => $parameterName,
'contents' => $fileResource,
'filename' => basename($metaData['uri']),
);
... | csn_ccr |
Configures the default router object. | protected function setupUrlRouting()
{
$rewriter = new Rewriter();
$rewriter->initialize();
$router = Router::urlRouting();
$this->setConfig("runtime.rewriter_reference", $rewriter);
$this->setConfig("runtime.router_reference", $router);
} | csn |
generate proxy object with given InvocationHandler and the object to
do proxy
@param handler InvocationHandler instance
@param toProxy the object to do proxy
@return proxy object generated with Proxy.newProxyInstance(...)
@see InvocationHandler
@see Proxy#newProxyInstance(ClassLoader, Class[], InvocationHandler) | @SuppressWarnings("unchecked")
public static <T> T proxy(InvocationHandler handler, T toProxy) {
return (T) Proxy.newProxyInstance(toProxy.getClass().getClassLoader(), toProxy.getClass().getInterfaces(), handler);
} | csn |
// FmtQuerySources returns a comma separated list of query
// sources. If there were no query sources, it returns the string
// "none". | func (stats *LogStats) FmtQuerySources() string {
if stats.QuerySources == 0 {
return "none"
}
sources := make([]string, 2)
n := 0
if stats.QuerySources&QuerySourceMySQL != 0 {
sources[n] = "mysql"
n++
}
if stats.QuerySources&QuerySourceConsolidator != 0 {
sources[n] = "consolidator"
n++
}
return str... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.