file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
render.py | super(ZoomGroup, self).__init__(parent)
self.zoom = zoom
def set_state(self):
pyglet.gl.glPushMatrix()
pyglet.gl.glScalef(self.zoom, self.zoom, 1)
def unset_state(self):
pyglet.gl.glPopMatrix()
def __eq__(self, other):
return (
self.... | (Component):
COMPONENT_NAME = 'layout_renderable'
def __init__(self, tile):
self.tile = tile
class RenderSystem(object):
zoom = 3
GROUP_LEVEL = pyglet.graphics.OrderedGroup(0)
GROUP_DIGITS = pyglet.graphics.OrderedGroup(1)
GROUP_HUD = pyglet.graphics.OrderedGroup(2)
... | LayoutRenderable | identifier_name |
hashsplit.go | the checksum window,
// then the same window can span multiple chunks,
// meaning a chunk boundary is not independent of the preceding chunk.
// If you leave this set to zero,
// 64 is what you'll get.
// If you really mean "I want no minimum,"
// set this to 1.
MinSize int
// SplitBits is the number of trail... | (r io.Reader, f func([]byte, uint) error) error {
s := NewSplitter(f)
_, err := io.Copy(s, r)
if err != nil {
return err
}
return s.Close()
}
// NewSplitter produces a new Splitter with the given callback.
// The Splitter is an io.WriteCloser.
// As bytes are written to it,
// it finds chunk boundaries and call... | Split | identifier_name |
hashsplit.go | s.checkSplit()
err := s.f(s.chunk, level)
s.chunk = nil
return err
}
func (s *Splitter) checkSplit() (uint, bool) {
splitBits := s.SplitBits
if splitBits == 0 {
splitBits = defaultSplitBits
}
h := s.rs.Sum32()
tz := uint(bits.TrailingZeros32(h))
if tz >= splitBits {
return tz - splitBits, true
}
return... | {
return nil, ErrNotFound
} | conditional_block | |
hashsplit.go | when SplitBits==13.)
SplitBits uint
// The function to invoke on each chunk produced.
f func([]byte, uint) error
// The chunk being built.
chunk []byte
// This is the recommended rolling-checksum algorithm for hashsplitting
// according to the document at github.com/hashsplit/hashsplit-spec
// (presently in... | {
if len(tb.levels) == 0 {
tb.levels = []*TreeBuilderNode{new(TreeBuilderNode)}
}
tb.levels[0].Chunks = append(tb.levels[0].Chunks, bytes)
for _, n := range tb.levels {
n.size += uint64(len(bytes))
}
for i := uint(0); i < level; i++ {
if i == uint(len(tb.levels))-1 {
tb.levels = append(tb.levels, &TreeBu... | identifier_body | |
hashsplit.go | finds chunk boundaries and calls the callback.
//
// The callback receives the bytes of the chunk,
// and the chunk's "level,"
// which is the number of extra trailing zeroes in the rolling checksum
// (in excess of Splitter.SplitBits).
//
// Do not forget to call Close on the Splitter
// to flush any remaining chunk ... | return nil, nil
}
if len(tb.levels[0].Chunks) > 0 {
for i := 0; i < len(tb.levels)-1; i++ { | random_line_split | |
bigrand.rs | uint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
/// Generate a random `BigInt` within the given range. The lower
/// bound is inclusive; the upper bound is exclusive. Fails when
/// the upper bound is not greater than the lower bound.
fn gen_bigint_range(&mut self, lbound: &BigInt... | <R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
&self.base + BigInt::from(rng.gen_biguint_below(&self.len))
}
#[inline]
fn sample_single<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> ... | sample | identifier_name |
bigrand.rs | _zero() {
// ...except that if the BigUint is zero, we need to try
// again with probability 0.5. This is because otherwise,
// the probability of generating a zero BigInt would be
// double that of any other number.
if self.gen() {
... | {
if bit_size < 2 {
panic!("prime size must be at least 2-bit");
}
let mut b = bit_size % 8;
if b == 0 {
b = 8;
}
let bytes_len = (bit_size + 7) / 8;
let mut bytes = vec![0u8; bytes_len];
loop {
self.fill_bytes(&mut b... | identifier_body | |
bigrand.rs | uint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
/// Generate a random `BigInt` within the given range. The lower
/// bound is inclusive; the upper bound is exclusive. Fails when
/// the upper bound is not greater than the lower bound.
fn gen_bigint_range(&mut self, lbound: &BigInt... | lazy_static! {
| /// odd by construction.
#[cfg(feature = "prime")]
const SMALL_PRIMES: [u8; 15] = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53];
#[cfg(feature = "prime")] | random_line_split |
bigrand.rs | if self.gen() {
continue;
} else {
NoSign
}
} else if self.gen() {
Plus
} else {
Minus
};
return BigInt::from_biguint(sign, biguint);
}
}
... | {
bytes[0] |= 3u8.wrapping_shl(b as u32 - 2);
} | conditional_block | |
cartracker.py | # create background subtractor
fgbg = cv2.createBackgroundSubtractorMOG2()
# where the centroids will be stored
pts = deque(maxlen=args["buffer"])
counter = 0
(dX, dY) = (0, 0)
direction = ""
#setting variables before the image processing
frames_count, fps, width, height = cap.get(cv2.CAP_PROP_FRAME_COUNT), cap.get... | #arguments to start with
ap.add_argument("-b", "--buffer", type=int, default=5000,
help="max buffer size")
args = vars(ap.parse_args())
| random_line_split | |
cartracker.py | # creates a pandas data frame with the number of rows the same length as frame count
df = pd.DataFrame(index=range(int(frames_count)))
df.index.name = "Frames"
framenumber = 0 # keeps track of current frame
carids = [] # blank list to add car ids
totalcars = 0 # keeps track of total cars
#capturing data
while(T... |
#drawing hte current centroid
cxx = cxx[cxx != 0]
cyy = cyy[cyy != 0]
minx_index2 = []
miny_index2 = []
maxrad = 30
# if there are centroids in the specified area
if len(cxx):
if not carids: # if carids is empty
# loops through all cent... | if pts[i - 1] is None or pts[i] is None:
continue
# draw the centroid tracker
cv2.circle(image, (pts[i - 1]), 2, (0,0,255), -1) | conditional_block |
util.go | {
var tags []interface{}
for eachKey, eachValue := range tagMap {
tags = append(tags, map[string]interface{}{
"Key": eachKey,
"Value": eachValue,
})
}
return tags
}
// Struct to encapsulate transforming data into
type templateConverter struct {
templateReader io.Reader
additionalTemplatePro... | {
return nil, existingStackDefinitionErr
} | conditional_block | |
util.go | (data map[string]interface{}) (*gocf.StringExpr, error) {
if len(data) <= 0 {
return nil, fmt.Errorf("FnJoinExpr data is empty")
}
for eachKey, eachValue := range data {
switch eachKey {
case "Ref":
return gocf.Ref(eachValue.(string)).String(), nil
case "Fn::GetAtt":
attrValues, attrValuesErr := toExpr... | parseFnJoinExpr | identifier_name | |
util.go | 1]), gocf.String(attrValues[2])), nil
}
}
return nil, fmt.Errorf("Unsupported AWS Function detected: %#v", data)
}
////////////////////////////////////////////////////////////////////////////////
// Public
////////////////////////////////////////////////////////////////////////////////
// S3AllKeysArnForBucket re... |
// MapToResourceTags transforms a go map[string]string to a CloudFormation-compliant
// Tags representation. See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html
func MapToResourceTags(tagMap map[string]string) []interface{} {
var tags []interface{}
for eachKey, eachV... | {
arnParts := []gocf.Stringable{gocf.String("arn:aws:s3:::")}
switch bucket.(type) {
case string:
// Don't be smart if the Arn value is a user supplied literal
arnParts = append(arnParts, gocf.String(bucket.(string)))
case *gocf.StringExpr:
arnParts = append(arnParts, bucket.(*gocf.StringExpr))
case gocf.Re... | identifier_body |
util.go | : %+v", bucket))
}
return gocf.Join("", arnParts...).String()
}
// MapToResourceTags transforms a go map[string]string to a CloudFormation-compliant
// Tags representation. See http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html
func MapToResourceTags(tagMap map[string]st... | session, sessionErr := session.NewSession()
if sessionErr != nil {
return nil, sessionErr | random_line_split | |
gravity.js | function | ( element, options ) {
/*
Provide local access to the DOM node(s) that called the plugin,
as well local access to the plugin name and default options.
*/
this.element = element;
this._name = pluginName;
this._defaults = $.fn.gravity.defaults;
/*
... | Plugin | identifier_name |
gravity.js | function Plugin ( element, options ) | Calling the init method here in the "Plugin" constructor function
allows us to store all methods (including the init method) in the
plugin's prototype. Storing methods required by the plugin in its
prototype lowers the memory footprint, as each instance of the
... | {
/*
Provide local access to the DOM node(s) that called the plugin,
as well local access to the plugin name and default options.
*/
this.element = element;
this._name = pluginName;
this._defaults = $.fn.gravity.defaults;
/*
The "$.exte... | identifier_body |
gravity.js | function Plugin ( element, options ) {
/*
Provide local access to the DOM node(s) that called the plugin,
as well local access to the plugin name and default options.
*/
this.element = element;
this._name = pluginName;
this._defaults = $.fn.gravity.def... | else{
group.data.padding = {
top: group.data.aHeight - group.data.gHeight
};
}
$(group.parent).css({
'padding-top': group.data.padding.top
});
// apply to DOM
... | {
group.data.padding = {
top: delta.top - group.data.offset.top
};
} | conditional_block |
gravity.js |
function Plugin ( element, options ) {
/*
Provide local access to the DOM node(s) that called the plugin,
as well local access to the plugin name and default options.
*/
this.element = element;
this._name = pluginName;
this._defaults = $.fn.gravity.de... | instances of the plugin.
More: http://api.jquery.com/jquery.extend/
*/
this.options = $.extend( {}, this._defaults, options );
/*
The "init" method is the starting point for all plugin logic.
Calling the init method here in the "Plugin" construct... | empty so that we don't alter the default options for future | random_line_split |
lsfiles.go | = fname
} else {
newparent = parent + "/" + fname
}
if dir == "" {
newdir = fname
} else {
newdir = dir + "/" + fname
}
recurseFiles := findUntrackedFilesFromDir(c, opts, root, newparent, newdir, tracked, recursedir, ignorePatterns)
untracked = append(untracked, recurseFiles...)
} e... | {
continue
} | conditional_block | |
lsfiles.go | recursedir, ignorePatterns)
untracked = append(untracked, recurseFiles...)
} else {
var filePath File
if parent == "" {
filePath = File(strings.TrimPrefix(fname.String(), root.String()))
} else {
filePath = File(strings.TrimPrefix((parent + "/" + fname).String(), root.String()))
}
indexPat... | Len | identifier_name | |
lsfiles.go | }
files:
for _, fi := range files {
fname := File(fi.Name())
if fi.Name() == ".git" {
continue
}
for _, pattern := range ignorePatterns {
var name File
if parent == "" {
name = fname
} else {
name = parent + "/" + fname
}
if pattern.Matches(name.String(), fi.IsDir()) {
continue f... | {
files, err := ioutil.ReadDir(dir.String())
if err != nil {
return nil
}
for _, ignorefile := range opts.ExcludePerDirectory {
ignoreInDir := ignorefile
if dir != "" {
ignoreInDir = dir + "/" + ignorefile
}
if ignoreInDir.Exists() {
log.Println("Adding excludes from", ignoreInDir)
patterns, er... | identifier_body | |
lsfiles.go | return nil
}
for _, ignorefile := range opts.ExcludePerDirectory {
ignoreInDir := ignorefile
if dir != "" {
ignoreInDir = dir + "/" + ignorefile
}
if ignoreInDir.Exists() {
log.Println("Adding excludes from", ignoreInDir)
patterns, err := ParseIgnorePatterns(c, ignoreInDir, dir)
if err != nil ... | files, err := ioutil.ReadDir(dir.String())
if err != nil { | random_line_split | |
plot_all_sampled_days.py | # with centroid and angle displayed
import mpl_toolkits.basemap as bm
from mpl_toolkits.basemap import Basemap, cm
from netCDF4 import Dataset as NetCDFFile
import numpy as np
import matplotlib.pyplot as plt
import sys,os
cwd=os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd+'/../../MetBot')
sys.path.append(cwd+'/.... | # To plot a maps for flagged CB days
# after selection based on angle and centroid
#
# plotted over a larger domain | random_line_split | |
plot_all_sampled_days.py |
elif dsets=='spec': # edit for the dset you want
#ndset=1
#dsetnames=['ncep']
ndset=1
dsetnames=['cmip5']
ndstr=str(ndset)
for d in range(ndset):
dset=dsetnames[d]
dcnt=str(d+1)
print 'Running on '+dset
print 'This is dset '+dcnt+' of '+ndstr+' in list'
outdir=thisdir+'/'+dset+'/'... | ndset=len(dset_mp.dset_deets)
dsetnames=list(dset_mp.dset_deets) | conditional_block | |
lib.rs | //!
//! assert_eq!(get_symbol_description(&BAR).unwrap(), "the second symbol!");
//! ```
//!
//! For static symbols, the implementations of [Eq]/[Ord]/[Hash](std::hash::Hash) et. al use only the namespace's [type_id](std::any::Any::type_id)
//! plus the symbol's numerical `id`.
//!
//! Typically, the boilerplate code f... | f,
"{}::{}",
instance.namespace_name(),
instance.symbol_name()
)
}
}
}
}
impl PartialEq for Symbol {
fn eq(&self, rhs: &Symbol) -> bool {
match (self, rhs) {
(Self::Static(thi... | Self::Static(ns, id) => {
write!(f, "{}::{}", ns.namespace_name(), ns.symbol_name(*id))
}
Self::Dynamic(instance) => {
write!( | random_line_split |
lib.rs | {
(Self::Static(this_ns, this_id), Self::Static(rhs_ns, rhs_id)) => {
let this_type_id = this_ns.type_id();
let rhs_type_id = rhs_ns.type_id();
if this_type_id == rhs_type_id {
this_id.cmp(&rhs_id)
} else {
... | {
let test_state = TestState::new();
test_state.assert_full_eq(&STATIC_A_0, &STATIC_A_0);
test_state.assert_full_eq(&STATIC_A_1, &STATIC_A_1);
test_state.assert_full_eq(&STATIC_B_0, &STATIC_B_0);
test_state.assert_full_ne(&STATIC_A_0, &STATIC_A_1);
test_state.assert_ful... | identifier_body | |
lib.rs | (self, rhs) {
(Self::Static(this_ns, this_id), Self::Static(rhs_ns, rhs_id)) => {
*this_id == *rhs_id && this_ns.type_id() == rhs_ns.type_id()
}
(Self::Dynamic(this), Self::Dynamic(rhs)) => {
this.type_id() == rhs.type_id() && this.dyn_eq(rhs.as_ref()... | test_equality | identifier_name | |
xapian_backend.py | start_time = self.folders_with_date[0][0]
end_time = start_time + datetime.timedelta(days=50)
weibos = self.db.statuses.find({
self.schema['posted_at_key']: {
'$gte': calendar.timegm(start_time.timetuple()),
'$lt': calendar.timegm(end_ti... | n self.databases[folder]
#@profile
def load_and_index_weibos(self, start_time=None):
if not debug and start_time:
| identifier_body | |
xapian_backend.py | )):
value = xapian.sortable_serialise(value)
return value
def _marshal_term(term):
"""
Private utility method that converts Python terms to a string for Xapian terms.
"""
if isinstance(term, int):
term = str(term)
return term
def _database(folder, writable=False):
"""
... | if self.empty:
return other
| random_line_split | |
xapian_backend.py | (self):
self.emotion_words = [line.strip('\r\n') for line in file(EXTRA_EMOTIONWORD_PATH)]
def load_scws(self):
s = scws.Scws()
s.set_charset(SCWS_ENCODING)
s.set_dict(CHS_DICT_PATH, scws.XDICT_MEM)
s.add_dict(CHT_DICT_PATH, scws.XDICT_MEM)
s.add_dict(CUSTOM_DICT_PA... | load_extra_dic | identifier_name | |
xapian_backend.py | and_parts.append(node)
# Now we combine the parts into a usable query. AND together all of
# the necessary parts. Then for each $or part, create a new query
# that ANDs the necessary part with the $or part.
clauses = []
for or_group in pro... | dd_argument('-p', '--print_folders', action='store_true', help='PRINT FOLDER THEN EXIT')
parser.add_argument('-s', '--start_time', nargs=1, help='DATETIME')
parser.add_argument('dbpath', help='PATH_TO_DATABASE')
args = parser.parse_args(sys.argv[1:])
debug = args.debug
dbpath = args.dbpath
if a... | conditional_block | |
y.go | , -1000, -1000, 56, 2, 1, -8,
-10, -1000, -1000, -10, -10, -10, 114, -1000, -10, -10,
-9, -14, -16, -2, 136, -4, -13, -1000, -10, -10,
-10, -10, -10, -10, -10, -10, -10, -10, 104, -1000,
-10, -10, -10, 16, -10, 15, 14, 48, 48, -1000,
-1000, 84, 84, 84, 84, 84, 84, -1000, -23, -25,
70, -1000, 136, -1000, -1000, -1... | /* put a state and value onto the stack */
if yyDebug >= 4 {
__yyfmt__.Printf("char %v in %v\n", yyTokname(yychar), yyStatname(yystate))
}
yyp++
if yyp >= len(yyS) {
nyys := make([]yySymType, len(yyS)*2)
copy(nyys, yyS)
yyS = nyys
}
yyS[yyp] = yyVAL
yyS[yyp].yys = yystate
yynewstate:
yyn = yyPact[yys... | {
var yyn int
var yylval yySymType
var yyVAL yySymType
yyS := make([]yySymType, yyMaxDepth)
Nerrs := 0 /* number of errors */
Errflag := 0 /* error recovery flag */
yystate := 0
yychar := -1
yyp := -1
goto yystack
ret0:
return 0
ret1:
return 1
yystack: | identifier_body |
y.go | , -1000, -1000, 56, 2, 1, -8,
-10, -1000, -1000, -10, -10, -10, 114, -1000, -10, -10,
-9, -14, -16, -2, 136, -4, -13, -1000, -10, -10,
-10, -10, -10, -10, -10, -10, -10, -10, 104, -1000,
-10, -10, -10, 16, -10, 15, 14, 48, 48, -1000,
-1000, 84, 84, 84, 84, 84, 84, -1000, -23, -25,
70, -1000, 136, -1000, -1000, -1... |
2, -2, 1, 3, 4, 5, 0, 0, 0, 0,
0, 10, 11, 0, 0, 0, 0, 12, 0, 0,
0, 0, 0, 0, 28, 0, 0, 6, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 24,
0, 0, 0, 0, 0, 0, 0, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 13, 0, 0,
0, 7, 29, 8, 9, 25, 26, 0, 0, 0,
0, 27,
}
var yyTok1 = []int{
1, 3, 3, 3, 3, 3, 3, 3, 3, 3,
25, 3, 3, 3, 3, 3, ... | }
var yyDef = []int{ | random_line_split |
y.go | , -1000, -1000, 56, 2, 1, -8,
-10, -1000, -1000, -10, -10, -10, 114, -1000, -10, -10,
-9, -14, -16, -2, 136, -4, -13, -1000, -10, -10,
-10, -10, -10, -10, -10, -10, -10, -10, 104, -1000,
-10, -10, -10, 16, -10, 15, 14, 48, 48, -1000,
-1000, 84, 84, 84, 84, 84, 84, -1000, -23, -25,
70, -1000, 136, -1000, -1000, -1... | (lex yyLexer, lval *yySymType) int {
c := 0
char := lex.Lex(lval)
if char <= 0 {
c = yyTok1[0]
goto out
}
if char < len(yyTok1) {
c = yyTok1[char]
goto out
}
if char >= yyPrivate {
if char < yyPrivate+len(yyTok2) {
c = yyTok2[char-yyPrivate]
goto out
}
}
for i := 0; i < len(yyTok3); i += 2 {
... | yylex1 | identifier_name |
y.go | , -10, -10, -10, -10, -10, 104, -1000,
-10, -10, -10, 16, -10, 15, 14, 48, 48, -1000,
-1000, 84, 84, 84, 84, 84, 84, -1000, -23, -25,
70, -1000, 136, -1000, -1000, -1000, -1000, -10, 45, -10,
80, -1000,
}
var yyPgo = []int{
0, 65, 46, 0, 44, 6, 42,
}
var yyR1 = []int{
0, 6, 1, 1, 1, 1, 2, 2, 2, 2,
4, 4, 3, 3, ... | {
yychar = yylex1(yylex, &yylval)
} | conditional_block | |
mod.rs | + 'static,
{
name: String,
broker: B,
default_queue_name: String,
task_options: TaskOptions,
}
/// Used to create a `Celery` app with a custom configuration.
pub struct CeleryBuilder<B>
where
B: Broker + 'static,
{
config: Config<B>,
}
impl<B> CeleryBuilder<B>
where
B: Broker + 'static,
{... | TaskStatus::Pending => pending_tasks += 1,
TaskStatus::Finished => pending_tasks -= 1,
};
} | random_line_split | |
mod.rs | >(&self, task: &T) -> Self {
Self {
timeout: task.timeout().or(self.timeout),
max_retries: task.max_retries().or(self.max_retries),
min_retry_delay: task.min_retry_delay().unwrap_or(self.min_retry_delay),
max_retry_delay: task.max_retry_delay().unwrap_or(self.max_... |
Ok(())
}
/// Wraps `try_handle_delivery` to catch any and all errors that might occur.
async fn handle_delivery(
&self,
delivery_result: Result<B::Delivery, B::DeliveryError>,
event_tx: UnboundedSender<TaskEvent>,
) {
if let Err(e) = self.try_handle_delivery(de... | {
self.broker.decrease_prefetch_count().await?;
} | conditional_block |
mod.rs | <T: Task>(&self, task: &T) -> Self {
Self {
timeout: task.timeout().or(self.timeout),
max_retries: task.max_retries().or(self.max_retries),
min_retry_delay: task.min_retry_delay().unwrap_or(self.min_retry_delay),
max_retry_delay: task.max_retry_delay().unwrap_or(s... | overrides | identifier_name | |
ddpg.py | cube_green_2', [2.0, 0.32, 0.80])
])
SUM_DIR = '../SUM_DIR'
TRAIN_DIR = '../TRAIN_DIR'
class DDPG(object):
def __init__(self):
pass
@staticmethod
def execute(sess, actor, critic, train = True):
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
summary_writer ... | (object):
def __init__(self, sess, state_dim, action_dim, learning_rate, tau):
self.sess = sess
self.s_dim = state_dim
self.a_dim = action_dim
self.learning_rate = learning_rate
self.tau = tau
self.actor_inputs_dirt, self.actor_weights, self.actor_out = self.create_actor_network('actor_network')
sel... | ActorNetwork | identifier_name |
ddpg.py | ('cube_green_2', [2.0, 0.32, 0.80])
])
SUM_DIR = '../SUM_DIR'
TRAIN_DIR = '../TRAIN_DIR'
class DDPG(object):
def __init__(self):
pass
@staticmethod
def execute(sess, actor, critic, train = True):
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
summary_writ... |
def predict(self, inputs):
return self.sess.run(self.actor_out, feed_dict = {
self.actor_inputs_dirt: inputs
})
def predict_target(self, inputs):
return self.sess.run(self.target_actor_out, feed_dict = {self.target_actor_inputs_dirt: inputs})
def update_target_network(self):
self.sess.run(self.upda... | self.sess.run(self.optimize, feed_dict = {self.actor_inputs_dirt: inputs,
self.action_gradient: a_gradient}) | identifier_body |
ddpg.py | ('cube_green_2', [2.0, 0.32, 0.80])
])
SUM_DIR = '../SUM_DIR'
TRAIN_DIR = '../TRAIN_DIR'
class DDPG(object):
def __init__(self):
pass
@staticmethod
def execute(sess, actor, critic, train = True):
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
summary_writ... | epsilon -= 0.7 / 1000.0
if np.random.random() > epsilon:
a_type = "Exploit"
a = actor.predict(s_t.reshape(-1, 84, 84, 3)).reshape(2, 3)
else:
a_type = "Explore"
a = np.random.random_sample([2, 3])
action = np.argmax(a, axis = 1)
print(action)
s_t1, ... | delete_models_name = [names for names in gazebo_client.get_model_states().name if
names.startswith('cube')]
delete_models_path = [names[:-2] for names in delete_models_name]
env.gazebo_client.delete_gazebo_sdf_models(delete_models_name)
env.gazebo_client.shuffle_models(delete_model... | conditional_block |
ddpg.py |
TAU = 0.01
cube_map_pose = OrderedDict([('cube_blue_1', [1.5, -0.3, 0.80]), ('cube_blue_2', [1.5, -0.05, 0.80]),
('cube_red_1', [1.5, 0.2, 0.80]), ('cube_red_2', [1.7, -0.15, 0.80]),
('cube_green_1', [1.65, 0.05, 0.80]), ('cube_green_2', [1.6, 0.32, 0.80])
... |
PARAM_FILE = '../param/training_parameters_2018_06_20.csv'
SUM_FILE = '../SUM_DIR/summary_2018_06_20.csv' | random_line_split | |
core.ts | -post-processor**@1234abcd**
// TODO: read this from OwlBot.yaml.
_CONTAINER: args.image,
_DEFAULT_BRANCH: args.defaultBranch ?? 'master',
},
},
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buildId: string = (resp as any).metadata.build.id;
const det... | f (conclusion === 'success') {
text = `successfully ran ${build.steps.length} steps 🎉!`;
}
return {
conclusion,
summary,
text,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function buildFailureFrom(error: any, detailsUrl: string): BuildResponse {
if (typeof error.name ==... | conclusion = 'failure';
summary = `${++failures} steps failed 🙁`;
text += `❌ step ${step.name} failed with status ${step.status}\n`;
}
}
i | conditional_block |
core.ts | -post-processor**@1234abcd**
// TODO: read this from OwlBot.yaml.
_CONTAINER: args.image,
_DEFAULT_BRANCH: args.defaultBranch ?? 'master',
},
},
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buildId: string = (resp as any).metadata.build.id;
const det... | getCloudBuildInstance() {
return new CloudBuildClient();
}
/*
* Load OwlBot lock file from .github/.OwlBot.lock.yaml.
* TODO(bcoe): abstract into common helper that supports .yml.
*
* @param {string} repoFull - repo in org/repo format.
* @param {number} pullNumber - pull request to base branch on.
* @param {Oc... | he && cachedOctokit) return cachedOctokit;
let tokenString: string;
if (auth instanceof Object) {
const token = await getGitHubShortLivedAccessToken(
auth.privateKey,
auth.appId,
auth.installation
);
tokenString = token.token;
} else {
tokenString = auth;
}
const octokit = ne... | identifier_body |
core.ts | js-post-processor**@1234abcd**
// TODO: read this from OwlBot.yaml.
_CONTAINER: args.image,
_DEFAULT_BRANCH: args.defaultBranch ?? 'master',
},
},
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buildId: string = (resp as any).metadata.build.id; | const build = await waitForBuild(project, buildId, cb);
return {detailsURL, ...summarizeBuild(build)};
} catch (e) {
const err = e as Error;
logger.error(`triggerPostProcessBuild: ${err.message}`, {
stack: err.stack,
});
return buildFailureFrom(err, detailsURL);
}
}
function summarize... | const detailsURL = detailsUrlFrom(buildId, project);
try {
// TODO(bcoe): work with fenster@ to figure out why awaiting a long
// running operation does not behave as expected:
// const [build] = await resp.promise(); | random_line_split |
core.ts | -post-processor**@1234abcd**
// TODO: read this from OwlBot.yaml.
_CONTAINER: args.image,
_DEFAULT_BRANCH: args.defaultBranch ?? 'master',
},
},
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buildId: string = (resp as any).metadata.build.id;
const det... | Key: string,
appId: number,
installation: number
): Promise<Token> {
const payload = {
// issued at time
// Note: upstream API seems to fail if decimals are included
// in unixtime, this is why parseInt is run:
iat: parseInt('' + Date.now() / 1000),
// JWT expiration time (10 minute maximum)
... | ortLivedAccessToken(
private | identifier_name |
main.py | print("GGF. stimmt etwas mit dem Pfad für die Ordnererstellung nicht.")
def write_into_csv_file(new_directory_name, output_csv_filename, all_texts, output_count_pos_tags):
#Wir versehen jedes Wort in jeder der .xml Dateien mit dem von Spacy erkannten Part-of-Speech Tag
#Die Satzenden finden wir mit "doc.sent... | ist_with_qs_and_os_counted_trigger_lists = [praeposition_triggers_for_qs_links, praeposition_triggers_for_os_links]
if read_all == 0:
break
return_list = [sub_tag_dict, sub_tag_QS_link_types, double_list_with_qs_and_os_counted_trigger_lists, count_motion_verb]
return return_list
def write_... | ers_for_os_links[potential_match[1]] = 1
double_l | conditional_block |
main.py | _ != "PUNCT": #Count amount of 'real' words in a sentence
words_in_sentence += 1
if token.pos_ in counter_for_pos:
counter_for_pos[token.pos_] += 1
else:
counter_for_pos[token.pos_] = 1
... | plt.title("Anzahl der Wörter pro Satz")
plt.xlabel("Satzlänge")
plt.ylabel("Häufigkeit") | random_line_split | |
main.py | der PoS Tags in eine extra Datei.
output_count_pos_tags_csv = str(output_count_pos_tags) + ".csv"
with open(output_count_pos_tags_csv, 'w', newline='') as myfile:
thewriter = csv.writer(myfile)
thewriter.writerow(['Part-of-Speech', 'Anzahl'])
for pos_part in counter_for_pos:
... | _inp | identifier_name | |
main.py | ellen in der .csv Datei an
#Wir zählen parallel die Häufigkeit der verschiedenen PoS Tags und schreiben diese in ein anderes File.
#Wir zählen hier auch die Satzlängen
cur_abs_path = os.path.abspath("")
path = os.path.join(cur_abs_path, new_directory_name)
os.chdir(path)
full_output_csv_name = s... | unted_qs_and_os_link_praep_triggers.csv"
with open(csv_name, 'w', newline='') as myfile:
thewriter = csv.writer(myfile)
thewriter.writerow(['Linktyp:', 'QsLink'])
thewriter.writerow(['Triggerwort:', 'Anzahl der Triggerungen:'])
for entry in list_with_dicts_for_qs_and_os_link_triggers... | identifier_body | |
conn.go | ) (*RUDPConn, error) {
c := &RUDPConn{}
c.localAddr = localAddr
c.remoteAddr = remoteAddr
c.rudpConnType = connTypeClient
c.sendSeqNumber = 0
c.recvPacketChannel = make(chan *packet, 1<<5)
c.rudpConnStatus = connStatusConnecting
if err := c.clientBuildConn(); err != nil {
return nil, err
}
c.sendPacketCha... | else if c.rudpConnType == connTypeServer {
c.serverRecv()
}
}
func (c *RUDPConn) clientRecv() {
for {
select {
case <-c.recvStop:
return
default:
buf := make([]byte, rawUDPPacketLenLimit)
n, err := c.rawUDPConn.Read(buf)
if err != nil {
c.errBus <- err
return
}
buf = buf[:n]
apa... | {
c.clientRecv()
} | conditional_block |
conn.go | c := &RUDPConn{}
c.localAddr = localAddr
c.remoteAddr = remoteAddr
c.rudpConnType = connTypeClient
c.sendSeqNumber = 0
c.recvPacketChannel = make(chan *packet, 1<<5)
c.rudpConnStatus = connStatusConnecting
if err := c.clientBuildConn(); err != nil {
return nil, err
}
c.sendPacketChannel = make(chan *packe... |
// DialRUDP client dial server, building a relieable connection
func DialRUDP(localAddr, remoteAddr *net.UDPAddr) (*RUDPConn, error) { | random_line_split | |
conn.go | ("errBus recv error: %v\n", err)
c.err = err
c.resendStop <- err
c.recvStop <- err
c.sendStop <- err
if c.rudpConnType == connTypeClient {
c.heartbeatStop <- err
}
if c.rudpConnType == connTypeServer {
c.closeConnCallbackListener()
}
}
func (c *RUDPConn) keepLive() {
ticker := time.NewTicker(time.Durati... | {
readCnt := len(b)
n := len(b)
if n == 0 {
return 0, nil
}
curWrite := 0
if len(c.outputDataTmpBuffer) != 0 {
if n <= len(c.outputDataTmpBuffer) {
copy(b, c.outputDataTmpBuffer[:n])
c.outputDataTmpBuffer = c.outputDataTmpBuffer[n:]
return readCnt, nil
} else {
n -= len(c.outputDataTmpBuffer)
... | identifier_body | |
conn.go | ) (*RUDPConn, error) {
c := &RUDPConn{}
c.localAddr = localAddr
c.remoteAddr = remoteAddr
c.rudpConnType = connTypeClient
c.sendSeqNumber = 0
c.recvPacketChannel = make(chan *packet, 1<<5)
c.rudpConnStatus = connStatusConnecting
if err := c.clientBuildConn(); err != nil {
return nil, err
}
c.sendPacketCha... | () {
ticker := time.NewTicker(time.Duration(c.sendTickNano) * time.Nanosecond)
defer ticker.Stop()
for {
select {
case c.sendTickNano = <-c.sendTickModifyEvent:
ticker.Stop()
ticker = time.NewTicker(time.Duration(c.sendTickNano) * time.Nanosecond)
case <-c.sendStop:
return
case <-ticker.C:
c.send... | send | identifier_name |
plotXsectLimitComparison.py | os.path.basename(fname)
if name.lower().endswith(".csv"):
name = name[:-4]
else:
name = fname[pos+1:]
fname = fname[:pos]
masses, observedValues, expectedValues, \
expected_minus_2_sigma_values, \
expected_minus_1_sigma_values, ... | )
parser.add_option(
"--relative",
help="instead of plotting the absolute cross section exclusions, plot the relative (w.r.t. to the input signal)",
default=False,
action="store_true",
)
parser.add_option(
"--isabs",
help="specify that a given file contains ABSOLUTE rather than RELATIV... | "--ymax",
type=float,
help="manually sepcify the y scale",
default=None, | random_line_split |
plotXsectLimitComparison.py | .path.basename(fname)
if name.lower().endswith(".csv"):
name = name[:-4]
else:
name = fname[pos+1:]
fname = fname[:pos]
masses, observedValues, expectedValues, \
expected_minus_2_sigma_values, \
expected_minus_1_sigma_values, \
... |
else:
typeName = "SM"
# convert to absolute cross sections
for line, fname in zip(data, csvFnames):
if fname in inputIsAbs:
# already absolute
continue
line['observedValues'] = PlotUtils.multiplyArrayByXsectAndBR(line['masses... | typeName = "FP" | conditional_block |
plotXsectLimitComparison.py |
while True:
color += 1
if color not in colorsToAvoid:
break
# define a name: if there is a comma in the file name assume that the
# part before the comma is the actual file name and the part after it
# is the label we should use
#
... | """ @param relative if true, the exclusion of the ratios
(relative to the inputs given) are plotted. If False,
these ratios are multiplied by the SM cross sections
and branching ratios into gamma gamma
@param inputIsAbs is a list (set) of file names which
should be treated as i... | identifier_body | |
plotXsectLimitComparison.py | (csvFnames, relative, includeExpected = True, fermiophobic = None, ymax = None, inputIsAbs = None, drawXsectBR = False,
minMass = None,
maxMass = None,
plotLog = False
):
""" @param relative if true, the exclusion of the ratios
(relative to the inputs give... | makePlot | identifier_name | |
test.rs | ()).unwrap())
/// # }
/// #
/// # fn main() {
/// use gotham::tls::test::TestServer;
///
/// let test_server = TestServer::new(|| Ok(my_handler)).unwrap();
///
/// let response = test_server.client().get("http://localhost/").perform().unwrap();
/// assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
#[... | {
test::common_tests::async_echo(TestServer::new, TestServer::client)
} | identifier_body | |
test.rs | fn client(&self) -> TestClient<Self, TestConnect> {
self.data.client(self)
}
/// Spawns the given future on the `TestServer`'s internal runtime.
/// This allows you to spawn more futures ontop of the `TestServer` in your
/// tests.
pub fn spawn<F>(&self, future: F)
where
F: Fut... | async_test_server_adds_client_address_to_state | identifier_name | |
test.rs | = Certificate(include_bytes!("tls_cert.der").to_vec());
let key = PrivateKey(include_bytes!("tls_key.der").to_vec());
ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(vec![cert], key)
.expect("Unable to create TLS server config")
}
/// The ... | else {
tcp.connected()
}
}
}
impl<IO> AsyncRead for TlsConnectionStream<IO>
where
IO: AsyncRead + AsyncWrite + Unpin,
{
#[inline]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut ReadBuf,
) -> Poll<Result<(), io::Error>> {
self.pro... | {
tcp.connected().negotiated_h2()
} | conditional_block |
test.rs | = Certificate(include_bytes!("tls_cert.der").to_vec());
let key = PrivateKey(include_bytes!("tls_key.der").to_vec());
ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(vec![cert], key)
.expect("Unable to create TLS server config")
}
/// The ... | Ok(stream) => {
let domain = ServerName::try_from(req.host().unwrap()).unwrap();
match tls.connect(domain, stream).await {
Ok(tls_stream) => {
info!("Client TcpStream connected: {:?}", tls_stream);
... |
async move {
match TcpStream::connect(address).await { | random_line_split |
databases.go | TableCreator is a Database that can create new tables which have a Primary Key with columns that have
// prefix lengths.
type IndexedTableCreator interface {
Database
// CreateIndexedTable creates the table with the given name and schema using the index definition provided for its
// primary key index.
CreateIndexe... | {
for _, name := range tableNames {
if tblName == name {
return name, true
}
}
lwrName := strings.ToLower(tblName)
for _, name := range tableNames {
if lwrName == strings.ToLower(name) {
return name, true
}
}
return "", false
} | identifier_body | |
databases.go | TableCreator interface {
Database
// CreateTemporaryTable creates the table with the given name and schema. If a temporary table with that name already exists, must
// return sql.ErrTableAlreadyExists
CreateTemporaryTable(ctx *Context, name string, schema PrimaryKeySchema, collation CollationID) error
}
// TableDr... | {
return err
} | conditional_block | |
databases.go | (ctx *Context, oldName, newName string) error
}
// VersionedDatabase is a Database that can return tables as they existed at different points in time. The engine
// supports queries on historical table data via the AS OF construct introduced in SQL 2011.
type VersionedDatabase interface {
Database
// GetTableInsensi... | GetTableInsensitive | identifier_name | |
databases.go | type CollatedDatabaseProvider interface {
MutableDatabaseProvider
// CreateCollatedDatabase creates a collated database and adds it to the provider's collection.
CreateCollatedDatabase(ctx *Context, name string, collation CollationID) error
}
// TableFunctionProvider is an interface that allows custom table functi... | GetEvent(ctx *Context, name string) (EventDefinition, bool, error)
// GetEvents returns all EventDetails for the database.
GetEvents(ctx *Context) ([]EventDefinition, error)
// SaveEvent stores the given EventDetails to the database. The integrator should verify that
// the name of the new event is unique amongst ... | // handle execution logic for events. Integrators only need to store and retrieve EventDetails.
type EventDatabase interface {
Database
// GetEvent returns the desired EventDetails and if it exists in the database. | random_line_split |
funcs.py | (slab,newaxis=None,axis=0,verbose=False):
"""Adds an extra axis to a data slab.
<slab>: variable to which the axis is to insert.
<newaxis>: axis object, could be of any length. If None, create a dummy
singleton axis.
<axis>: index of axis to be inserted, e.g. 0 if <newaxis> is inserted
... | addExtraAxis | identifier_name | |
funcs.py | return quantiles
#-------Copies selected attributes from source object to dict--
def attribute_obj2dict(source_object,dictionary=None,verbose=False):
'''Copies selected attributes from source object to dict
to <dictionary>.
<source_object>: object from which attributes are copied.
<dictionary>: N... | print('# <getQuantiles>: %0.3f left quantile: %f. %0.3f right quantile: %f.'\
%(pii,ql[ii],1-pii,qr[ii]))
| random_line_split | |
funcs.py | variable------------
att_dict=attribute_obj2dict(slab)
slab2=cdms.createVariable(slab2,axes=axislist,attributes=att_dict,\
typecode='f')
slab2.id=slab.id
if verbose:
print('\n# <addExtraAxis>: Originial variable shape:',slab.shape)
print('# <addExtraAxis>: New variable shap... |
# interpret string dimension
#elif type(axis)==type('t'):
elif isinstance(axis,str if sys.version_info[0]>=3 else basestring):
axis=axis.lower()
if axis in ['time', 'tim', 't']:
dim_id = 'time'
elif axis in ['level', 'lev','z']:
dim_id = 'level'
eli... | return axis | conditional_block |
funcs.py | variable------------
att_dict=attribute_obj2dict(slab)
slab2=cdms.createVariable(slab2,axes=axislist,attributes=att_dict,\
typecode='f')
slab2.id=slab.id
if verbose:
print('\n# <addExtraAxis>: Originial variable shape:',slab.shape)
print('# <addExtraAxis>: New variable shap... | try:
attdict=attribute_obj2dict(var1)
hasatt=True
except:
hasatt=False
if not hasattr(var1.getAxis(axis),'units'):
ax=var1.getAxis(axis)
ax.units=''
var1.setAxis(axis,ax)
if not hasattr(var2.getAxis(axis),'units'):
ax=var2.getAxis(axis)
ax... | '''Concatenate 2 variables along axis.
<var1>,<var2>: Variables to be concatenated, in the order of \
<var1>, <var2>;
<axis>: int, index of axis to be concatenated along.
Return <result>
'''
import MV2 as MV
import numpy
try:
order=var1.getAxisListIndex()
except:
... | identifier_body |
aat_common_test.go | (t *testing.T) {
// adapted from fontttools
src := deHexStr(
"0004 0006 0003 000C 0001 0006 " +
"0002 0001 001E " + // glyph 1..2: mapping at offset 0x1E
"0005 0004 001E " + // glyph 4..5: mapping at offset 0x1E
"FFFF FFFF FFFF " + // end of search table
"0007 0008")
class, _, err := ParseAATLookup(src... | TestAATLookup4 | identifier_name | |
aat_common_test.go | // extracted from macos Tamil MN font
src = []byte{0, 4, 0, 6, 0, 5, 0, 24, 0, 2, 0, 6, 0, 151, 0, 129, 0, 42, 0, 156, 0, 153, 0, 88, 0, 163, 0, 163, 0, 96, 1, 48, 1, 48, 0, 98, 255, 255, 255, 255, 0, 100, 0, 4, 0, 10, 0, 11, 0, 12, 0, 13, 0, 14, 0, 15, 0, 16, 0, 17, 0, 18, 0, 19, 0, 20, 0, 21, 0, 22, 0, 23, 0, 24, 0... | {
// adapted from fontttools
src := deHexStr(
"0004 0006 0003 000C 0001 0006 " +
"0002 0001 001E " + // glyph 1..2: mapping at offset 0x1E
"0005 0004 001E " + // glyph 4..5: mapping at offset 0x1E
"FFFF FFFF FFFF " + // end of search table
"0007 0008")
class, _, err := ParseAATLookup(src, 4)
tu.Assert... | identifier_body | |
aat_common_test.go | " + // 44: STXHeader.StateArrayOffset=74 (+36=110)
"0000 006E " + // 48: STXHeader.EntryTableOffset=110 (+36=146)
"0000 0086 " + // 52: STXHeader.InsertionActionOffset=134 (+36=170)
// Glyph class table.
"0002 0006 " + // 56: ClassTable.LookupFormat=2, .UnitSize=6
"0006 0018 " + // 60: .NUnits=6, .S... | dFile(filepath)
tu.AssertNoErr(t, err)
kerx, _, err := ParseKerx(table, 0xFF)
tu.AssertNoErr(t, err)
tu.Assert(t, len(kerx.Tables) > 0)
for _, subtable := range kerx.Tables {
tu.Assert(t, subtable.TupleCount > 0 == strings.Contains(filepath, "VF"))
switch data := subtable.Data.(type) {
case KerxDat... | conditional_block | |
aat_common_test.go | morxLigatureData := deHexStr(
"0002 0000 " + // 0: Version=2, Reserved=0
"0000 0001 " + // 4: MorphChainCount=1
"0000 0001 " + // 8: DefaultFlags=1
"0000 00DA " + // 12: StructLength=218 (+8=226)
"0000 0000 " + // 16: MorphFeatureCount=0
"0000 0001 " + // 20: MorphSubtableCount=1
"0000 00CA " + ... | random_line_split | ||
args.go | p (bool) [int]
//
// Tests the value passed in for truth (a boolean predicate) and
// converts the result to its equivalent C true/false integer
// value. Sets the int to 1 if the expression was true and 0 if it was
// false. This accepts any valid Python value. See Truth Value Testing
// for more information about ho... | string, re | identifier_name | |
args.go | // This format converts a bytes-like object to a C pointer to a
// character string; it does not accept Unicode objects. The bytes
// buffer must not contain embedded NUL bytes; if it does, a TypeError
// exception is raised.
//
// y* (bytes, bytearray or bytes-like object) [Py_buffer]
//
// This variant on s* doesn’t ... | random_line_split | ||
args.go | assumes that the
// byte string object uses the encoding passed in as parameter.
//
// Numbers
//
// b (int) [unsigned char]
//
// Convert a nonnegative Python integer to an unsigned tiny int,
// stored in a C unsigned char.
//
// B (int) [unsigned char]
//
// Convert a Python integer to a tiny int without overflow ch... | results[i]
swi | conditional_block | |
args.go | receiving field is too small to receive the value (actually, the
// semantics are inherited from downcasts in C — your mileage may
// vary).
//
// A few other characters have a meaning in a format string. These may
// not occur inside nested parentheses. They are:
//
// |
//
// Indicates that the remaining arguments i... |
kwOnly_i = 0xFFFF
ops = in[:0]
N := len(format)
for i := 0; i < N; {
op := formatOp{code: format[i]}
i++
if i < N {
if mod := format[i]; mod == '*' || mod == '#' {
op.modifier = mod
i++
}
}
switch op.code {
case ':', ';':
name = format[i:]
i = N
case '$':
kwOnly_i = len(ops) | identifier_body | |
sudo.py | import imutils
import numpy as np
from sklearn.metrics import pairwise
import mss, os
#-----------------------------------------------------------------------------------------------------------------------------------
#global var
background = None
_cnt = 0
#--------------------------------------------------------... | eight for running average
alphaWeight = 0.5 #if we set lower value, running average will be performed over larger amt of previous frames and vice-a-versa
stream = 'http://192.168.0.4:8080/video'
#get the reference to the webcam
camera = cv2.VideoCapture(stream)
top, right, bottom, left = 10, 350, ... | alize w | identifier_name |
sudo.py | 2
import imutils
import numpy as np
from sklearn.metrics import pairwise
import mss, os
#-----------------------------------------------------------------------------------------------------------------------------------
#global var
background = None
_cnt = 0
#------------------------------------------------------... | #print(extreme_top + " " + extreme_bottom + " " + extreme_left + " " + extreme_right)
#palm center
cX = (extreme_left[0] + extreme_right[0]) / 2
cY = (extreme_top[1] + extreme_bottom[1]) / 2
cX = np.round(cX).astype("int") #convert to int
cY = np.round(cY).astype("int")
#maximum euclidean ... | extreme_top = tuple(convex_hull[convex_hull[:, :, 1].argmin()][0])
extreme_bottom = tuple(convex_hull[convex_hull[:, :, 1].argmax()][0])
extreme_left = tuple(convex_hull[convex_hull[:, :, 0].argmin()][0])
extreme_right = tuple(convex_hull[convex_hull[:, :, 0].argmax()][0]) | random_line_split |
sudo.py | import imutils
import numpy as np
from sklearn.metrics import pairwise
import mss, os
#-----------------------------------------------------------------------------------------------------------------------------------
#global var
background = None
_cnt = 0
#--------------------------------------------------------... |
roi = frame[top:bottom, right:left] #get roi
#convert to grayscale and blur
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7,7), 0) #(src ,kernel_size(height and width), sigmaX and sigmaY both set to 0)
#https://docs.opencv.org/2.4/modules/imgproc/d... | we set lower value, running average will be performed over larger amt of previous frames and vice-a-versa
stream = 'http://192.168.0.4:8080/video'
#get the reference to the webcam
camera = cv2.VideoCapture(stream)
top, right, bottom, left = 10, 350, 225, 590 #ROI Co-ords
num_frames = 0 #initi... | identifier_body |
sudo.py | import imutils
import numpy as np
from sklearn.metrics import pairwise
import mss, os
#-----------------------------------------------------------------------------------------------------------------------------------
#global var
background = None
_cnt = 0
#--------------------------------------------------------... | else:
#segment hand region
hand = segmentation(gray)
if hand is not None:
#unpack thresholded image and segmented region
(thresholded, segmented) = hand
| ad()
frame = imutils.resize(frame, width=700) #resize frame
frame = cv2.flip(frame, 1) #flip around x-axis -- dest(i,j) = src(i,cols-j-1)
clone = frame.copy()
(height, width) = frame.shape[:2] #get height and width of frame
#print(str(height) +" "+ str(width))
r... | conditional_block |
cloudFoundryDeploy.go | = findMtar()
if err != nil {
return err
}
log.Entry().Debugf("Using mtar file '%s' found in workspace", mtarFilePath)
} else {
exists, err := fileUtils.FileExists(mtarFilePath)
if err != nil {
return errors.Wrapf(err, "Cannot check if file path '%s' exists", mtarFilePath)
}
if !exists {
r... |
func getAppName(config *cloudFoundryDeployOptions) (string, error) {
if len(config.AppName) > 0 {
return config.AppName, nil
}
if config.DeployType == "blue-green" {
return "", fmt.Errorf("Blue-green plugin requires app name to be passed (see https://github.com/bluemixgaragelondon/cf-blue-green-deploy/issues/... | {
manifestFileName := config.Manifest
if len(manifestFileName) == 0 {
manifestFileName = "manifest.yml"
}
return manifestFileName, nil
} | identifier_body |
cloudFoundryDeploy.go | log.Entry().Infof("Manifest file '%s' was in legacy format has been transformed and updated.", manifestFile)
} else {
log.Entry().Debugf("Manifest file '%s' was not in legacy format. No transformation needed, no update performed.", manifestFile)
}
return nil
}
func prepareCfPushCfNativeDeploy(config *cloudFound... | toMap | identifier_name | |
cloudFoundryDeploy.go | (smokeTestScript, 0755)
if err != nil {
return []string{}, fmt.Errorf("failed to make smoke-test script executable: %w", err)
}
pwd, err := fileUtils.Getwd()
if err != nil {
return []string{}, fmt.Errorf("failed to get current working directory for execution of smoke-test script: %w", err)
}
return ... | {
return fmt.Errorf("Cannot handle credentials inside mta extension files: %w", err)
} | conditional_block | |
cloudFoundryDeploy.go | 0, "name")
if err != nil {
return "", err
}
var name string
var ok bool
if name, ok = appName.(string); !ok {
return "", fmt.Errorf("appName from manifest '%s' has wrong type", manifestFile)
}
if len(name) == 0 {
return "", fmt.Errorf("appName from manifest '%s' is empty", manifestFile)
}
return name, ni... | if len(config.MtaDeployParameters) > 0 {
deployParams = append(deployParams, strings.Split(config.MtaDeployParameters, " ")...) | random_line_split | |
viewer.rs | .1, 0.2, 0.3, 1.0);
}
gl::Enable(gl::DEPTH_TEST);
// TODO: keyboard switch?
// draw in wireframe
// gl::PolygonMode(gl::FRONT_AND_BACK, gl::LINE);
};
let (root, scene) = Self::load(source, scene_index);
let mut viewer = GltfViewer {
... | _ => ()
} | random_line_split | |
viewer.rs | {
let gl_request = GlRequest::Specific(Api::OpenGl, (3, 3));
let gl_profile = GlProfile::Core;
let (events_loop, gl_window, dpi_factor, inner_size) =
if headless {
let headless_context = glutin::HeadlessRendererBuilder::new(width, height)
// .with... | (source: &str, scene_index: usize) -> (Root, Scene) {
let mut start_time = Instant::now();
// TODO!: http source
// let gltf =
if source.starts_with("http") {
panic!("not implemented: HTTP support temporarily removed.")
// let http_source = HttpSource::new(source)... | load | identifier_name |
viewer.rs | let gl_request = GlRequest::Specific(Api::OpenGl, (3, 3));
let gl_profile = GlProfile::Core;
let (events_loop, gl_window, dpi_factor, inner_size) =
if headless {
let headless_context = glutin::HeadlessRendererBuilder::new(width, height)
// .with_gl... | ;
self.orbit_controls.position = cam_pos;
self.orbit_controls.target = center;
self.orbit_controls.camera.znear = size / 100.0;
self.orbit_controls.camera.zfar = Some(size * 20.0);
self.orbit_controls.camera.update_projection_matrix();
}
pub fn start_render_loop(&mut se... | {
Point3::new(
center.x + size / 2.0,
center.y + size / 5.0,
center.z + size / 2.0,
)
} | conditional_block |
viewer.rs | f32 / 2.0;
unsafe {
print_context_info();
gl::ClearColor(0.0, 1.0, 0.0, 1.0); // green for debugging
gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
if headless || !visible {
// transparent background for screenshots
gl:... | {
let mut keep_running = true;
#[allow(single_match)]
events_loop.poll_events(|event| {
match event {
glutin::Event::WindowEvent{ event, .. } => match event {
WindowEvent::CloseRequested => {
keep_running = false;
},
Win... | identifier_body | |
cq_reactor.rs | use super::{CmdId, CqId, InterruptSources, Nvme, NvmeComp, NvmeCmd, SqId};
/// A notification request, sent by the future in order to tell the completion thread that the
/// current task wants a notification when a matching completion queue entry has been seen.
#[derive(Debug)]
pub enum NotifReq {
RequestCompletio... | random_line_split | ||
cq_reactor.rs | message: Arc<Mutex<Option<CompletionMessage>>>,
cq_id: CqId,
sq_id: SqId,
cmd_id: CmdId,
},
PendingAvailSubmission {
waker: task::Waker,
sq_id: SqId,
},
}
struct CqReactor {
int_sources: InterruptSources,
nvme: Arc<Nvme>,
pending_reqs: Vec<PendingR... | (
nvme: Arc<Nvme>,
interrupt_sources: InterruptSources,
receiver: Receiver<NotifReq>,
) -> thread::JoinHandle<()> {
// Actually, nothing prevents us from spawning additional threads. the channel is MPMC and
// everything is properly synchronized. I'm not saying this is strictly required, but with
... | start_cq_reactor_thread | identifier_name |
cq_reactor.rs | message: Arc<Mutex<Option<CompletionMessage>>>,
cq_id: CqId,
sq_id: SqId,
cmd_id: CmdId,
},
PendingAvailSubmission {
waker: task::Waker,
sq_id: SqId,
},
}
struct CqReactor {
int_sources: InterruptSources,
nvme: Arc<Nvme>,
pending_reqs: Vec<PendingR... |
fn new(
nvme: Arc<Nvme>,
mut int_sources: InterruptSources,
receiver: Receiver<NotifReq>,
) -> Result<Self> {
Ok(Self {
event_queue: Self::create_event_queue(&mut int_sources)?,
int_sources,
nvme,
pending_reqs: Vec::new(),
... | {
use syscall::flag::*;
let fd = syscall::open("event:", O_CLOEXEC | O_RDWR)?;
let mut file = unsafe { File::from_raw_fd(fd as RawFd) };
for (num, irq_handle) in int_sources.iter_mut() {
if file
.write(&Event {
id: irq_handle.as_raw_fd() a... | identifier_body |
xcbwin.rs |
}
// If no depth matches return root visual
return (scr.root_visual(), scr.root_depth());
}
pub struct XCB {
conn: Arc<Connection>,
scr_num: i32,
win: Window,
root: Window,
bufpix: Pixmap,
gc: Gcontext,
colour: Colormap,
visual: Visualid,
de... | {
for v in d.visuals() {
return (v.visual_id(), depth);
}
} | conditional_block | |
xcbwin.rs | u16), // (w, h)
pos: (i16, i16), // (x, y)
scr_size: (u16, u16),
bottom: bool,
click_fn: Arc<Mutex<Box<Fn(i16, i16, u8) + Sync + Send>>>,
}
impl XCB {
pub fn new() -> XCB {
// Create XCB struct to return
let (conn, scr_num) = {
let (conn, scr_num) = Connection:... | impl Dock for XCB {
fn create_surface(&self) -> cairo::Surface {
// Prepare cairo variables
let cr_conn = unsafe {
cairo::XCBConnection::from_raw_none(
self.conn.get_raw_conn() as *mut cairo_sys::xcb_connection_t)
};
let cr_draw = cairo::XCBDrawable(self... | self.pos = (x as i16, y as i16);
}
}
| random_line_split |
xcbwin.rs | u16), // (w, h)
pos: (i16, i16), // (x, y)
scr_size: (u16, u16),
bottom: bool,
click_fn: Arc<Mutex<Box<Fn(i16, i16, u8) + Sync + Send>>>,
}
impl XCB {
pub fn new() -> XCB {
// Create XCB struct to return
let (conn, scr_num) = {
let (conn, scr_num) = Connection:... | (&self, name: &str) -> Atom {
let atom = intern_atom(&self.conn, false, name);
atom.get_reply().unwrap().atom()
}
fn get_screen(&self) -> Screen {
let setup = self.conn.get_setup();
let screen = setup.roots().nth(self.scr_num as usize).unwrap();
return screen;
}
... | get_atom | identifier_name |
xcbwin.rs | (CW_COLORMAP, x.colour),
(CW_BORDER_PIXEL, 0),
];
create_window(&*x.conn,
x.depth,
x.win,
x.root,
x.pos.0, x.pos.1,
x.size.0, x.size.1,
0,
... | {
free_pixmap(&*self.conn, self.win);
free_pixmap(&*self.conn, self.bufpix);
free_gc(&*self.conn, self.gc);
free_colormap(&*self.conn, self.colour);
} | identifier_body | |
lib.rs | eg `${JULIA_DIR}/bin`), the second must
/// be either an absolute or a relative path to a system image.
///
/// This method will return an error if either of the two paths doesn't exist or if Julia
/// has already been initialized. It is unsafe because it can race with another crate
/// initializin... | scope | identifier_name | |
lib.rs | ScopeExt
//! [`ScopeExt::scope`]: crate::memory::scope::ScopeExt::scope
//! [`Scope`]: crate::memory::scope::Scope
//! [`Scope::value_scope`]: crate::memory::scope::Scope::value_scope
//! [`Scope::result_scope`]: crate::memory::scope::Scope::result_scope
#![forbid(rustdoc::broken_intra_doc_links)]
pub mod convert;
pu... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.