query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Shared preparation work for GATK variant calling. | def _shared_gatk_call_prep(align_bams, items, ref_file, region, out_file, num_cores=1):
"""Shared preparation work for GATK variant calling.
"""
data = items[0]
config = data["config"]
broad_runner = broad.runner_from_config(config)
gatk_type = broad_runner.gatk_type()
for x in align_bams:
... | csn |
Perform a fuzzy simplicial set embedding, using a specified
initialisation method and then minimizing the fuzzy set cross entropy
between the 1-skeletons of the high and low dimensional fuzzy simplicial
sets.
Parameters
----------
data: array of shape (n_samples, n_features)
The source ... | def simplicial_set_embedding(
data,
graph,
n_components,
initial_alpha,
a,
b,
gamma,
negative_sample_rate,
n_epochs,
init,
random_state,
metric,
metric_kwds,
verbose,
):
"""Perform a fuzzy simplicial set embedding, using a specified
initialisation method a... | csn |
Returns the network layers as a string. | def toString(self):
"""
Returns the network layers as a string.
"""
output = ""
for layer in reverse(self.layers):
output += layer.toString()
return output | csn |
The underlying implementation of `ZeroClipboard.setData`.
@private | function(format, data) {
var dataObj;
if (typeof format === "object" && format && typeof data === "undefined") {
dataObj = format;
ZeroClipboard.clearData();
} else if (typeof format === "string" && format) {
dataObj = {};
dataObj[format] = data;
} else {
return;
}
... | csn |
Push an item onto the beginning of an array.
@param array $array
@param mixed $value
@param mixed $key
@return array | public static function prepend($array, $value, $key = null)
{
if (is_null($key)) {
array_unshift($array, $value);
} else {
$array = [$key => $value] + $array;
}
return $array;
} | csn |
Set Hail API OAuth token in the current SiteConfig
@throws | public function setAccessToken($access_token)
{
$this->access_token = $access_token;
$config = SiteConfig::current_site_config();
$config->HailAccessToken = $access_token;
$config->write();
} | csn |
// ConfigureQorResource configure seoCollection for qor admin | func (collection *Collection) ConfigureQorResource(res resource.Resourcer) {
if res, ok := res.(*admin.Resource); ok {
Admin := res.GetAdmin()
collection.resource = res
if collection.SettingResource == nil {
collection.SettingResource = Admin.AddResource(&QorSEOSetting{}, &admin.Config{Invisible: true})
}
... | csn |
// Round rounds the argument f to dec decimal places.
// dec defaults to 0 if not specified. dec can be negative
// to cause dec digits left of the decimal point of the
// value f to become zero. | func Round(f float64, dec int) float64 {
shift := math.Pow10(dec)
tmp := f * shift
if math.IsInf(tmp, 0) {
return f
}
return RoundFloat(tmp) / shift
} | csn |
Smallmessage content including any processor specific content.
@param string $processorname Name of the processor.
@return mixed|string | protected function get_smallmessage($processorname = '') {
if (!empty($processorname) && isset($this->additionalcontent[$processorname])) {
return $this->get_message_with_additional_content($processorname, 'smallmessage');
} else {
return $this->smallmessage;
}
} | csn |
Setup a Configuration with specified Configuration, AMS account and token provider
@param configuration The target configuration
@param apiServer the AMS account uri
@param azureAdTokenProvider the token provider
@return the target Configuration | public static Configuration configureWithAzureAdTokenProvider(
Configuration configuration,
URI apiServer,
TokenProvider azureAdTokenProvider) {
configuration.setProperty(AZURE_AD_API_SERVER, apiServer.toString());
configuration.setProperty(AZURE_AD_TOKEN_PROVIDER, a... | csn |
Run a task asynchronously after at least delay_seconds | def execute_with_delay(task_function, *args, **kwargs):
"""Run a task asynchronously after at least delay_seconds
"""
delay = kwargs.pop('delay', 0)
if get_setting('TEST_DISABLE_ASYNC_DELAY'):
# Delay disabled, run synchronously
logger.debug('Running function "%s" synchronously because '... | csn |
Classifies the areas in an area tree.
@param root the root node of the area tree | public void classifyTree(Area root, FeatureExtractor features)
{
if (classifier != null)
{
System.out.print("tree visual classification...");
testRoot = root;
this.features = features;
//create a new empty set with the same header as the training set
testset = new... | csn |
Sum of the absolute deviations between the central moments of the
instantaneous unit hydrograph and the ARMA approximation. | def dev_moments(self):
"""Sum of the absolute deviations between the central moments of the
instantaneous unit hydrograph and the ARMA approximation."""
return numpy.sum(numpy.abs(self.moments-self.ma.moments)) | csn |
Write to the outputstream the bytes read from the input stream. | public int inputStreamToOutputStream(InputStream is, OutputStream os) throws IOException {
byte buffer[] = new byte[1024 * 100]; // 100kb
int len = -1;
int total = 0;
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
total += len;
}
... | csn |
Finds errors in question slots.
@param string $questiontext The question text
@param array $choices Question choices
@return string|bool Error message or false if no errors | private function validate_slots($questiontext, $choices) {
$error = 'Please check the Question text: ';
if (!$questiontext) {
return get_string('errorquestiontextblank', 'qtype_gapselect');
}
$matches = array();
preg_match_all($this->squarebracketsregex, $questiontex... | csn |
Transforms values to new params | protected function _transform()
{
$index = 1;
foreach ($this->_values as $value) {
$paramName = "{$this->_name}_{$index}";
$this->_params[$paramName] = new Param($this->_type, $value);
$index++;
}
} | csn |
Validate that an attribute is a string.
@param string $attribute
@param mixed $value
@return bool | protected function validateString( $attribute, $value )
{
if ( !$this->hasAttribute( $attribute ) )
{
return true;
}
return is_null( $value ) || is_string( $value );
} | csn |
Assigns B to A.attr, yields, and then assigns A.attr back to its
original value. | def assign(A, attr, B, lock=False):
'''Assigns B to A.attr, yields, and then assigns A.attr back to its
original value.
'''
class NoAttr(object): pass
context = threading.Lock if lock else null_context
with context():
if not hasattr(A, attr):
tmp = NoAttr
else:
... | csn |
Returns a device matcher for the given port path. | def PortPathMatcher(cls, port_path):
"""Returns a device matcher for the given port path."""
if isinstance(port_path, str):
# Convert from sysfs path to port_path.
port_path = [int(part) for part in SYSFS_PORT_SPLIT_RE.split(port_path)]
return lambda device: device.port_p... | csn |
// Provides the necessary information to establish an AWS VPC Peering
// with your private space. | func (s *Service) PeeringInfoInfo(ctx context.Context, spaceIdentity string) (*PeeringInfo, error) {
var peeringInfo PeeringInfo
return &peeringInfo, s.Get(ctx, &peeringInfo, fmt.Sprintf("/spaces/%v/peering-info", spaceIdentity), nil, nil)
} | csn |
// Lendbook returns the full lend book. | func (api *API) Lendbook(currency string, limitBids, limitAsks int) (lendbook Lendbook, err error) {
currency = strings.ToLower(currency)
body, err := api.get("/v1/lendbook/" + currency + "?limit_bids=" + strconv.Itoa(limitBids) + "&limit_asks=" + strconv.Itoa(limitAsks))
if err != nil {
return
}
err = json.Un... | csn |
Look up the frame ID code associated with a string.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/namfrm_c.html
:param frname: The name of some reference frame.
:type frname: str
:return: The SPICE ID code of the frame.
:rtype: int | def namfrm(frname):
"""
Look up the frame ID code associated with a string.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/namfrm_c.html
:param frname: The name of some reference frame.
:type frname: str
:return: The SPICE ID code of the frame.
:rtype: int
"""
frname = sty... | csn |
Make sure the store has a reference to the lock, and then add the lock to refresh the
SmartCache wrapper.
@param lock org.apereo.portal.concurrency.locking.IEntityLock
@param newExpiration java.util.Date
@param newLockType Integer | @Override
public void update(IEntityLock lock, java.util.Date newExpiration, Integer newLockType)
throws LockingException {
if (find(lock) == null) {
throw new LockingException("Problem updating " + lock + " : not found in store.");
}
primAdd(lock, newExpiration);
... | csn |
Cleaning Couchbase rows.
@param array $records
@return array | protected function preCleanRecords($records)
{
$new = [];
foreach ($records as $record) {
if (property_exists($record, $this->transactionTable)) {
$cleaned = (array)$record->{$this->transactionTable};
unset($cleaned[static::ID_FIELD]);
if (... | csn |
// newFlagTracker sets up a flagTracker based on a flagger. | func newFlagTracker(flagger Flagger) *flagTracker {
fTr := &flagTracker{
flagger: flagger,
shorts: map[rune]struct{}{
'h': {}, // "h" is always used for help, so we can't set it.
},
}
fTr.pflagger, fTr.pflag = flagger.(PFlagger)
return fTr
} | csn |
right trim string
@param string $str
@param array $charlist
@return string | public function rtrim($str, $charlist = null)
{
return isset($charlist) ? rtrim($str, $charlist) : rtrim($str);
} | csn |
// DeleteOrganizationBuckets removes all the buckets for a given org | func (s *Service) DeleteOrganizationBuckets(ctx context.Context, id platform.ID) error {
bucks, err := s.findBuckets(ctx, platform.BucketFilter{
OrganizationID: &id,
})
if err != nil {
return err
}
for _, buck := range bucks {
s.bucketKV.Delete(buck.ID.String())
}
return nil
} | csn |
Test whether the keys within a map are stringable - a simple map,
that can be optimized and whose keys can be cached | def are_stringable_keys(self, m):
"""Test whether the keys within a map are stringable - a simple map,
that can be optimized and whose keys can be cached
"""
for x in m.keys():
if len(self.handlers[x].tag(x)) != 1:
return False
return True | csn |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HTPasswdPasswordIdentityProvider. | func (in *HTPasswdPasswordIdentityProvider) DeepCopy() *HTPasswdPasswordIdentityProvider {
if in == nil {
return nil
}
out := new(HTPasswdPasswordIdentityProvider)
in.DeepCopyInto(out)
return out
} | csn |
Provides a list with all the elements in the xml feature descriptor.
@param xmlDescriptorIn the xml feature descriptor
@return a list containing all elements
@throws IOException if inputstream cannot be open
@throws InvalidFormatException if xml is not well-formed | public static List<Element> getDescriptorElements(InputStream xmlDescriptorIn)
throws IOException {
List<Element> elements = new ArrayList<>();
org.w3c.dom.Document xmlDescriptorDOM = createDOM(xmlDescriptorIn);
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList allElements;
try {
... | csn |
Method to fetch a value from either the fields metadata or the
schemas context, in that order.
Args:
key (str): The name of the key to grab the value for.
Keyword Args:
default (object, optional): If the value doesn't exist in the
schema's ``context`` or... | def get_field_value(self, key, default=MISSING):
"""Method to fetch a value from either the fields metadata or the
schemas context, in that order.
Args:
key (str): The name of the key to grab the value for.
Keyword Args:
default (object, optional): If the value ... | csn |
// NewLocation creates and returns a Location type. | func NewLocation(msg string, a ...interface{}) Location {
msg = fmt.Sprintf(msg, a...)
return Location{
error: errors.New(msg),
}
} | csn |
Create a table from a model's metadata.
@return boolean TRUE if the table was created, otherwise FALSE. | public function createTable()
{
if ($this->tableExists() === true) {
return true;
}
$dbh = $this->db();
$driver = $dbh->getAttribute(PDO::ATTR_DRIVER_NAME);
$model = $this->model();
$metadata = $model->metadata();
$table = $this->tabl... | csn |
Extracts a single file from a zip archive.
@param in Input zip stream
@param outdir Output directory
@param name File name
@throws IOException In case of IO error | public static void extractFile(final ZipInputStream in, final File outdir, final String name) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name)));
int count = -1;
while ((count =... | csn |
Get the ID of an object from the fixture.
@param string $class The data class, as specified in your fixture file. Parent classes won't work
@param string $identifier The identifier string, as provided in your fixture file
@return int | public function getId($class, $identifier)
{
if (isset($this->fixtures[$class][$identifier])) {
return $this->fixtures[$class][$identifier];
} else {
return false;
}
} | csn |
Check if provided snippet contains only one CSS property and value.
@param {String} snippet
@returns {Boolean} | function isSingleProperty(snippet) {
snippet = utils.trim(snippet);
// check if it doesn't contain a comment and a newline
if (/\/\*|\n|\r/.test(snippet)) {
return false;
}
// check if it's a valid snippet definition
if (!/^[a-z0-9\-]+\s*\:/i.test(snippet)) {
return false;
}
return snippe... | csn |
Initialize this incoming HTTP request message.
@param sc | public void init(HttpInboundServiceContext sc) {
// for requests, we don't care about the validation
setHeaderValidation(false);
setOwner(sc);
setBinaryParseState(HttpInternalConstants.PARSING_BINARY_VERSION);
} | csn |
parse output from verbose format | def parse_verbose(self, line):
"""
parse output from verbose format
"""
try:
logging.debug(line)
(host, pings) = line.split(' : ')
cnt = 0
lost = 0
times = []
pings = pings.strip().split(' ')
cnt = len(pi... | csn |
Domain disk change events handler | def _domain_event_disk_change_cb(conn, domain, old_src, new_src, dev, reason, opaque):
'''
Domain disk change events handler
'''
_salt_send_domain_event(opaque, conn, domain, opaque['event'], {
'oldSrcPath': old_src,
'newSrcPath': new_src,
'dev': dev,
'reason': _get_libvi... | csn |
Get saveable fields
@return array | public function getSaveableFields(): array
{
return Hash::apply($this->config('fields'), '{*}[saveable=true]', function ($array) {
$formatted = [];
foreach ($array as $data) {
$formatted[$data['name']] = $data;
}
return $formatted;
});... | csn |
Keep only authorized user that have the given permission on a given project.
Please Note that if the permission is 'Anyone' is NOT taking into account by this method. | public Collection<Integer> keepAuthorizedUsersForRoleAndProject(DbSession dbSession, Collection<Integer> userIds, String role, long projectId) {
return executeLargeInputs(
userIds,
partitionOfIds -> mapper(dbSession).keepAuthorizedUsersForRoleAndProject(role, projectId, partitionOfIds),
partitionS... | csn |
saves the file and opens the fileinfo for this file
@param string $path
@param string $filename
@throws \Exception
@throws \ImagickException
@return boolean | public function saveThumb($path = '', $filename = '')
{
if (empty($this->filename)) return false;
try {
$save_name = (empty($path) ? $this->path : $path);
$save_name = "$save_name/" . (empty($filename) ? 'th_' . $this->filename : $filename);
$this->imagemagik->wr... | csn |
Joins two path components, adding a separator only if necessary. | private static String join(String prefix, String suffix) {
int prefixLength = prefix.length();
boolean haveSlash = (prefixLength > 0 && prefix.charAt(prefixLength - 1) == separatorChar);
if (!haveSlash) {
haveSlash = (suffix.length() > 0 && suffix.charAt(0) == separatorChar);
... | csn |
The root path that should be used to put logs related to the tasks running in Jenkins.
@see AsyncAperiodicWork#getLogFile()
@see AsyncPeriodicWork#getLogFile()
@return the path where the logs should be put.
@since 2.114 | public static File getLogsRoot() {
String tagsLogsPath = SystemProperties.getString(LOGS_ROOT_PATH_PROPERTY);
if (tagsLogsPath == null) {
return new File(Jenkins.get().getRootDir(), "logs");
} else {
Level logLevel = Level.INFO;
if (ALREADY_LOGGED) {
... | csn |
// Unload closes the handle to the dynamically-linked gssapi library. | func (lib *Lib) Unload() error {
if lib == nil || lib.handle == nil {
return nil
}
runtime.LockOSThread()
defer runtime.UnlockOSThread()
i := C.dlclose(lib.handle)
if i == -1 {
return fmt.Errorf("%s", C.GoString(C.dlerror()))
}
lib.handle = nil
return nil
} | csn |
// ParseAddConfig validates configs passed on the command line | func ParseAddConfig(cmd *cobra.Command, spec *api.ServiceSpec, flagName string) error {
flags := cmd.Flags()
if flags.Changed(flagName) {
configs, err := flags.GetStringSlice(flagName)
if err != nil {
return err
}
container := spec.Task.GetContainer()
if container == nil {
spec.Task.Runtime = &api.T... | csn |
Get form by name.
@param string $name
The form name.
@param \Symfony\Component\Console\Input\InputInterface $input
The console input.
@param \Symfony\Component\Console\Output\OutputInterface $output
The console output.
@return \Droath\ConsoleForm\Form
The form instance. | public function getFormByName($name, InputInterface $input, OutputInterface $output)
{
if (!isset($this->forms[$name])) {
throw new \Exception(
sprintf('Unable to find %s form.', $name)
);
}
return $this->createInstance($input, $output, $this->forms[$... | csn |
Compute the cumulative distribution of ic50 values for a set of alleles
over a large universe of random peptides, to enable computing quantiles in
this distribution later.
Parameters
----------
peptides : sequence of string or EncodableSequences, optional
Peptides to... | def calibrate_percentile_ranks(
self,
peptides=None,
num_peptides_per_length=int(1e5),
alleles=None,
bins=None):
"""
Compute the cumulative distribution of ic50 values for a set of alleles
over a large universe of random peptides, to en... | csn |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageLayer. | func (in *ImageLayer) DeepCopy() *ImageLayer {
if in == nil {
return nil
}
out := new(ImageLayer)
in.DeepCopyInto(out)
return out
} | csn |
Creates the Clustered Configuration files.
@return bool Return true if success. | public function createClusteredConfiguration()
{
$retval = false;
if ($this->apache_config_path) {
$index_list = $this->nb_server->getSitesIndex();
$index_list->iterate(
function ($site_key, $nb_site) {
$this->createSiteFolders($nb_site);
... | csn |
Deserialize PENMAN graphs from a string
Args:
s (str): serialized PENMAN graphs
model: Xmrs subclass instantiated from decoded triples
Returns:
a list of objects (of class *model*) | def loads(s, model):
"""
Deserialize PENMAN graphs from a string
Args:
s (str): serialized PENMAN graphs
model: Xmrs subclass instantiated from decoded triples
Returns:
a list of objects (of class *model*)
"""
graphs = penman.loads(s, cls=XMRSCodec)
xs = [model.from_... | csn |
Check if this group ID is valid. | def is_group_valid(self, groupID):
"""
Check if this group ID is valid.
"""
cur = self.conn.cursor()
cur.execute('SELECT * FROM groups WHERE id=? LIMIT 1', [groupID])
results = cur.fetchall()
cur.close()
logging.debug('is_group_valid(groupID={}) => {}'.fo... | csn |
This is the callback used by findRecursive to collect data.
This callback method works together with walkRecursive() and is called
for every file/and or directory. The $context is a callback specific
container in which data can be stored and shared between the different
calls to the callback function. The walkRecursiv... | static protected function findRecursiveCallback( ezcBaseFileFindContext $context, $sourceDir, $fileName, $fileInfo )
{
// ignore if we have a directory
if ( $fileInfo['mode'] & 0x4000 )
{
return;
}
// update the statistics
$context->elements[] = $sourceDi... | csn |
Example of getting a topic. | public Topic getTopic(String topicId) throws Exception {
// [START pubsub_get_topic]
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
Topic topic = topicAdminClient.getTopic(topicName);
return topic;
... | csn |
// AllCloudImageMetadata returns all cloud image metadata in the model. | func (s *storage) AllCloudImageMetadata() ([]Metadata, error) {
coll, closer := s.store.GetCollection(s.collection)
defer closer()
results := []Metadata{}
docs := []imagesMetadataDoc{}
err := coll.Find(nil).All(&docs)
if err != nil {
return nil, errors.Annotatef(err, "cannot get all image metadata")
}
for _,... | csn |
Get notaion aspect for string.
@param mixed $notation
@param mixed $aspects | private function getNotationAspectsString($notation, $aspects)
{
$aspects['Type'] = 'varchar(255)';
$aspects['Null'] = 'NO';
$aspects['Default'] = $this->getNotationValue($notation);
return $aspects;
} | csn |
Returns an array having as keys a dotted path of associations that participate
in this eager loader. The values of the array will contain the following keys
- alias: The association alias
- instance: The association instance
- canBeJoined: Whether or not the association will be loaded using a JOIN
- entityClass: The e... | public function associationsMap($table)
{
$map = [];
if (!$this->getMatching() && !$this->getContain() && empty($this->_joinsMap)) {
return $map;
}
$map = $this->_buildAssociationsMap($map, $this->_matching->normalized($table), true);
$map = $this->_buildAssocia... | csn |
// Creates a post on the blog represented by BlogRef | func (b *BlogRef) CreatePost(params url.Values) (*PostRef, error) {
return CreatePost(b.client, b.Name, params)
} | csn |
Get an item from the package extra array
@param PackageInterface $package
@param string $key
@param mixed $default
@return mixed | protected function getPackageExtra(PackageInterface $package, $key, $default = null)
{
$extra = $package->getExtra();
return array_key_exists($key, $extra) ? $extra[ $key ] : $default;
} | csn |
// buildRespJSON handles the first round of unmarshaling into the master Api Response struct | func buildRespJSON(b []byte, response, data interface{}) error {
var err error
err = json.Unmarshal(b, response)
if err != nil {
return err
}
switch rt := response.(type) {
case *ApiResp:
if len(rt.Data) > 0 {
err = json.Unmarshal(rt.Data, &data)
if err != nil {
return err
}
}
}
return nil... | csn |
Update a collection.
@param updateCollectionOptions the {@link UpdateCollectionOptions} containing the options for the call
@return a {@link ServiceCall} with a response type of {@link Collection} | public ServiceCall<Collection> updateCollection(UpdateCollectionOptions updateCollectionOptions) {
Validator.notNull(updateCollectionOptions, "updateCollectionOptions cannot be null");
String[] pathSegments = { "v1/environments", "collections" };
String[] pathParameters = { updateCollectionOptions.environme... | csn |
Runs Oncotator for a group of VCF files. Each sample is annotated individually.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param dict vcfs: Dictionary of VCF FileStoreIDs {Sample identifier: FileStoreID}
:param Namespace config: Input parameters and shared FileStoreIDs
Require... | def annotate_vcfs(job, vcfs, config):
"""
Runs Oncotator for a group of VCF files. Each sample is annotated individually.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param dict vcfs: Dictionary of VCF FileStoreIDs {Sample identifier: FileStoreID}
:param Namespace config: Input ... | csn |
Finishes writing compressed data to the output stream without closing
the underlying stream. Use this method when applying multiple filters
in succession to the same output stream.
@exception IOException if an I/O error has occurred | public void finish() throws IOException {
if (!def.finished()) {
def.finish();
while (!def.finished()) {
int len = def.deflate(buf, 0, buf.length);
if (def.finished() && len <= buf.length - TRAILER_SIZE) {
// last deflater buffer. Fit t... | csn |
Terminate and close the multiprocessing pool if necessary. | def terminate_pool(self):
"""Terminate and close the multiprocessing pool if necessary."""
if self.pool is not None:
self.pool.terminate()
self.pool.join()
del(self.pool)
self.pool = None | csn |
Check for the usage of native support for CustomEvents which is lacking
completely on IE.
@return {boolean} Whether it can be used or not. | function canIuseNativeCustom() {
try {
const p = new NativeCustomEvent('t', {
detail: {
a: 'b'
}
});
return 't' === p.type && 'b' === p.detail.a;
} catch (e) { }
/* istanbul ignore next: hard to reproduce on test environment */
return false;
} | csn |
Dynamically discovers the primary key for this table and sets this objects member variable
accordingly. This returns an array
@param \mysqli $mysqliConn - the mysqli connection to get primary key through.
@param string $tableName - the name of the table to fetch the primary key for.
@return array - the column names tha... | public static function fetchPrimaryKey(\mysqli $mysqliConn, string $tableName) : array
{
$primaryKeyArray = array();
$query = "show index FROM `" . $tableName . "`";
/*@var $result mysqli_result */
$result = $mysqliConn->query($query);
if ($result === FALSE)... | csn |
Executes the SELECT statement, passing the result set to the ResultSetWorker for processing.
The ResultSetWorker must close the result set before returning. | public <T> T executeSelect(Connection conn, DataObject object, ResultSetWorker<T> worker) throws Exception {
PreparedStatement statement = conn.prepareStatement(_sql);
try {
load(statement, object);
return worker.process(statement.executeQuery());
} finally {
... | csn |
Return the ID of the given codec.
@param clazz The non-null class to search for.
@return The ID of the codec.
@throws IllegalArgumentException if the class was null or no ID was assigned
to the class. | public int getCodec(final Class<?> clazz) {
if (clazz == null) {
throw new IllegalArgumentException("Clazz cannot be null.");
}
final Integer id = codecs_ids.get(clazz);
if (id == null) {
throw new IllegalArgumentException("No codec ID assigned to class "
+ clazz);
}
retur... | csn |
Set custom game cycle for clock
@param int $gameCycle
@param bool $legacy | public function setGameCycle($gameCycle, $legacy = false)
{
$this->gameCycle = $gameCycle;
$this->legacy = $legacy;
// ingame days and hours
$hours = $this->gameCycle / self::RYZOM_HOURS_IN_TICKS;
$this->ryzomDay = ($hours / 24) - self::RYZOM_START_SPRING;
$this->ryz... | csn |
Displays the CMS interface with buttons for add page, settings, etc.
Called from an iframe when logged into the CMS. | public function getToolbar(EditorObject $editor, Request $request)
{
$page = PageFacade::find($request->input('page_id'));
View::share([
'page' => $page,
'editor' => $editor,
'auth' => auth(),
'person' => auth()->user(),
]);
if ($... | csn |
Adds tables to the catalog.
@param tableMetadataList the table metadata list
@return the catalog metadata builder | @TimerJ
public CatalogMetadataBuilder withTables(TableMetadata... tableMetadataList) {
for (TableMetadata tableMetadata : tableMetadataList) {
tables.put(tableMetadata.getName(), tableMetadata);
}
return this;
} | csn |
// OnCNETMsg_SplitScreenUser registers a callback for NET_Messages_net_SplitScreenUser | func (c *Callbacks) OnCNETMsg_SplitScreenUser(fn func(*dota.CNETMsg_SplitScreenUser) error) {
c.onCNETMsg_SplitScreenUser = append(c.onCNETMsg_SplitScreenUser, fn)
} | csn |
Method to put the application into the background.
@return boolean
@since 1.0
@throws \RuntimeException | protected function daemonize()
{
// Is there already an active daemon running?
if ($this->isActive())
{
$this->getLogger()->emergency($this->name . ' daemon is still running. Exiting the application.');
return false;
}
// Reset Process Information
$this->safeMode = !!@ ini_get('safe_mode');
$this... | csn |
// EnsurePortProxyRule checks if the specified redirect exists, if not creates it. | func (runner *runner) EnsurePortProxyRule(args []string) (bool, error) {
klog.V(4).Infof("running netsh interface portproxy add v4tov4 %v", args)
out, err := runner.exec.Command(cmdNetsh, args...).CombinedOutput()
if err == nil {
return true, nil
}
if ee, ok := err.(utilexec.ExitError); ok {
// netsh uses exi... | csn |
This property will be looked for in the server response and, if found and
true, will indicate that no more retries should be attempted for this item.
@param sPreventRetryResponseProperty
property name
@return this | @Nonnull
public FineUploader5Retry setPreventRetryResponseProperty (@Nonnull @Nonempty final String sPreventRetryResponseProperty)
{
ValueEnforcer.notEmpty (sPreventRetryResponseProperty, "PreventRetryResponseProperty");
m_sRetryPreventRetryResponseProperty = sPreventRetryResponseProperty;
return this;
... | csn |
Make the given css rule a target for goto
@param [] targets array
@param {CSS.Rule} node | function _makeCSSTarget(targets, rule) {
if (rule.sourceURL) {
var url = rule.sourceURL;
url += ":" + rule.style.range.start;
var name = rule.selectorList.text;
var file = _fileFromURL(url);
targets.push({"type": "css", "url": url, "name": name, "file"... | csn |
Add a servlet instance.
@param name the servlet's name
@param servlet the servlet instance
@return a {@link javax.servlet.ServletRegistration.Dynamic} instance allowing for further
configuration | public ServletRegistration.Dynamic addServlet(String name, Servlet servlet) {
final ServletHolder holder = new NonblockingServletHolder(requireNonNull(servlet));
holder.setName(name);
handler.getServletHandler().addServlet(holder);
final ServletRegistration.Dynamic registration = holder... | csn |
view for markers | function PointView(geometryModel) {
var self = this;
// events to link
var events = [
'click',
'dblclick',
'mousedown',
'mouseover',
'mouseout',
'dragstart',
'drag',
'dragend'
];
this._eventHandlers = {};
this.model = geometryModel;
this.points = [];
var style = _.clone... | csn |
Return whether the file exists within a specified collection of paths
@return [Bool] file exists within specified collection of paths | def file_exists?(paths, file)
paths.any? do |path|
Find.find(path)
.map { |path_file| Shellwords.escape(path_file) }
.include?(file)
end
end | csn |
// SetShutdownScript sets the shutdown script used when draining instances | func (o *LaunchSpecification) SetShutdownScript(v *string) *LaunchSpecification {
if o.ShutdownScript = v; o.ShutdownScript == nil {
o.nullFields = append(o.nullFields, "ShutdownScript")
}
return o
} | csn |
Returns order of another interval compared to this one
@param other Interval to compare with
@return -1 if this interval is before the other interval, 1 if this interval is after
0 otherwise (may indicate the two intervals are same or not comparable) | public int compareIntervalOrder(Interval<E> other)
{
int flags = getRelationFlags(other);
if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_BEFORE, REL_FLAGS_INTERVAL_UNKNOWN)) {
return -1;
} else if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_AFTER, REL_FLAGS_INTERVAL_UNKNOWN)) {
... | csn |
Make the real query to rubygems
It may fail in case we trigger too many requests
@param tries [Integer|nil] (optional) how many times we tried | def query_rubygems(tries = 0)
JSON.parse(open("https://rubygems.org/api/v1/gems/#{gem_name}.json").read)
rescue OpenURI::HTTPError => e
# We may trigger too many requests, in which case give rubygems a break
if e.io.status.include?(HTTP_TOO_MANY_REQUESTS)
if (tries += 1) < 2
slee... | csn |
// getMaxMountAndExistenceCheckAttempts returns a maximum number of cross repository mount attempts from
// source repositories of target registry, maximum number of layer existence checks performed on the target
// repository and whether the check shall be done also with digests mapped to different repositories. The
/... | func getMaxMountAndExistenceCheckAttempts(layer PushLayer) (maxMountAttempts, maxExistenceCheckAttempts int, checkOtherRepositories bool) {
size, err := layer.Size()
switch {
// big blob
case size > middleLayerMaximumSize:
// 1st attempt to mount the blob few times
// 2nd few existence checks with digests assoc... | csn |
Return position of end of cell, and position
of first line after cell, and whether there was an
explicit end of cell marker | def find_cell_end(self, lines):
"""Return position of end of cell, and position
of first line after cell, and whether there was an
explicit end of cell marker"""
if self.cell_type == 'markdown':
# Empty cell "" or ''
if len(self.markdown_marker) <= 2:
... | csn |
returns the namespace uri for a prefix, if declared in the stack | def find_namespace_uri(ns_stack, prefix, uri_check=nil)
tns = ns_stack.reverse.find{|ns| ns.has_key?(prefix)}
uri = tns[prefix] if tns
raise "prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'" if uri_check && uri && uri!=uri_check
uri
end | csn |
// List lists all DaemonSets in the indexer. | func (s *daemonSetLister) List(selector labels.Selector) (ret []*v1beta1.DaemonSet, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1beta1.DaemonSet))
})
return ret, err
} | csn |
// RectBound returns the bounding rectangle of the edge chain that connects the
// vertices defined so far. This bound satisfies the guarantee made
// above, i.e. if the edge chain defines a Loop, then the bound contains
// the LatLng coordinates of all Points contained by the loop. | func (r *RectBounder) RectBound() Rect {
return r.bound.expanded(LatLng{s1.Angle(2 * dblEpsilon), 0}).PolarClosure()
} | csn |
// Dedup adds a canned filter to the handler which suppresses duplicate
// messages.
//
// When an event is received that contains the same message & fields as a
// previous message, the message is not sent on to the next handler. Once a
// different message is received, the filter generates a summary message
// indica... | func (filterHandler *FilterHandler) Dedup() *FilterHandler {
var lastLogEvent *event.Event
var dups int
filterFunc := func(logEvent *event.Event) bool {
if lastLogEvent == nil {
lastLogEvent = logEvent
return true
}
if lastLogEvent.Message == logEvent.Message && reflect.DeepEqual(lastLogEvent.FlatFields... | csn |
Add the attributes that don't match any of the selected types.
@param apiParent the parent attribute
@param types the types to check | private void addIfNotTypes(final ApiAttribute apiParent,
final String... types) {
for (final ApiAttribute object : apiParent.getAttributes()) {
if (!matchOne(object, types)) {
final ApiModelToGedObjectVisitor visitor = createVisitor();
object.accept(visito... | csn |
// EncodeFixed32 writes a 32-bit integer to the Buffer.
// This is the format for the
// fixed32, sfixed32, and float protocol buffer types. | func (p *Buffer) EncodeFixed32(x uint64) error {
p.buf = append(p.buf,
uint8(x),
uint8(x>>8),
uint8(x>>16),
uint8(x>>24))
return nil
} | csn |
Open the NMEAFile. | def open(self, fp, mode='r'):
"""
Open the NMEAFile.
"""
self._file = open(fp, mode=mode)
return self._file | csn |
Get a previous run date relative to the current date or a specific date.
@param string|\DateTime $currentTime Relative calculation date
@param int $nth Number of matches to skip before returning
@param bool $allowCurrentDate Set to TRUE to return the
current date if it matche... | public function getPreviousRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
{
return $this->getCronExpression()->getPreviousRunDate($currentTime, $nth, $allowCurrentDate);
} | csn |
// GetEventsForClient Returns the current events for given client | func (s *Sensu) GetEventsForClient(client string) ([]interface{}, error) {
//return s.get("events", client)
// TODO is this the correct way? need validation??
return s.getList(fmt.Sprintf("events/%s", client), 0, 0)
} | csn |
// ProjectFromNamespace returns the current project installed in the supplied
// Context's namespace.
//
// If the namespace does not have a project namespace prefix, this function
// will return an empty string. | func ProjectFromNamespace(ns string) types.ProjectName {
if !strings.HasPrefix(ns, ProjectNamespacePrefix) {
return ""
}
return types.ProjectName(ns[len(ProjectNamespacePrefix):])
} | csn |
// String returns a string representation of the evidence. | func (dve *DuplicateVoteEvidence) String() string {
return fmt.Sprintf("VoteA: %v; VoteB: %v", dve.VoteA, dve.VoteB)
} | csn |
Replies the property that indictes if the triangle's points are defined in a counter-clockwise order.
@return the ccw property. | @Pure
public ReadOnlyBooleanProperty ccwProperty() {
if (this.ccw == null) {
this.ccw = new ReadOnlyBooleanWrapper(this, MathFXAttributeNames.CCW);
this.ccw.bind(Bindings.createBooleanBinding(() ->
Triangle2afp.isCCW(
getX1(), getY1(), getX2(), getY2(),
getX3(), getY3()),
x1Property(), y1P... | csn |
Where field uses single term
@param string $field
@param $term
@return $this | public function whereTerm(string $field, $term)
{
$param = [
"term" => [
$field => $term
]
];
$this->elasticQuery[] = $param;
return $this;
} | csn |
Called from the input processor to update the touch state and send
touch and mouse events.
@param newState The updated touch state | void setState(TouchState newState) {
if (MonocleSettings.settings.traceEvents) {
MonocleTrace.traceEvent("Set %s", newState);
}
newState.sortPointsByID();
newState.assignPrimaryID();
// Get the cached window for the old state and compute the window for
// the ... | csn |
Do a function call on every worker with different arguments
Parameters
----------
fcn: funtion
Function to call.
args: tuple
The arguments for Pool.map | def allmap(self, fcn, args):
""" Do a function call on every worker with different arguments
Parameters
----------
fcn: funtion
Function to call.
args: tuple
The arguments for Pool.map
"""
results = self.map(_lockstep_fcn,
... | csn |
Validate request queries with registerd commands
:param command: command parameter from request
:param token: token parameter from request
:param team_id: team_id parameter from request
:param method: the request method | def validate(self, command, token, team_id, method):
"""Validate request queries with registerd commands
:param command: command parameter from request
:param token: token parameter from request
:param team_id: team_id parameter from request
:param method: the request method
... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.