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 |
|---|---|---|---|---|
mod.rs | be spawned on it by calling the [`spawn`][`Executor::spawn`]
/// method on the `ThreadPool`. Note that since this executor moves futures between different
/// threads, the future in question *must* be [`Send`].
///
/// # Examples
/// ```
/// use std::io;
/// use threader::{
/// executor::Executor,
/// thread_p... |
#[test]
fn custom_thread_count() {
let executor = ThreadPool::with_threads(32).unwrap();
executor.spawn(async {});
}
#[test]
#[ignore]
fn bad_future() {
// A future that spawns a thread, returns Poll::Ready(()), and
// keeps trying to reschedule itself on the t... | {
let executor = ThreadPool::with_threads(0).unwrap();
executor.spawn(async {});
} | identifier_body |
mod.rs | can be spawned on it by calling the [`spawn`][`Executor::spawn`]
/// method on the `ThreadPool`. Note that since this executor moves futures between different
/// threads, the future in question *must* be [`Send`].
///
/// # Examples
/// ```
/// use std::io;
/// use threader::{
/// executor::Executor,
/// thre... | #[test]
fn custom_thread_count() {
let executor = ThreadPool::with_threads(32).unwrap();
executor.spawn(async {});
}
#[test]
#[ignore]
fn bad_future() {
// A future that spawns a thread, returns Poll::Ready(()), and
// keeps trying to reschedule itself on the thr... | let executor = ThreadPool::with_threads(0).unwrap();
executor.spawn(async {});
}
| random_line_split |
main.rs | // Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use futures::{channel::oneshot, FutureExt, TryFutureExt, TryStreamExt};
use iml_agent_comms::{
error::ImlAgentCommsError,
flush_queue,
host::{self, SharedHosts},
messaging::{consume_agent_tx_queue, A... |
Ok(())
}
async fn session_create_req_handler(
sessions: &mut Sessions,
client: Connection,
fqdn: Fqdn,
plugin: PluginName,
) -> Result<(), ImlAgentCommsError> {
let session = Session::new(plugin.clone(), fqdn.clone());
tracing::info!("Creating session {}", session);
let last_opt = s... | {
tracing::warn!("Terminating session because unknown {}", data);
send_message(
client.clone(),
"",
AGENT_TX_RUST,
ManagerMessage::SessionTerminate {
fqdn: data.fqdn,
plugin: data.plugin,
session_id: data.se... | conditional_block |
main.rs | .
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use futures::{channel::oneshot, FutureExt, TryFutureExt, TryStreamExt};
use iml_agent_comms::{
error::ImlAgentCommsError,
flush_queue,
host::{self, SharedHosts},
messaging::{consume_agent_tx_queue,... |
tracing::debug!(
"Put data on host queue {}: Queue size: {:?}",
fqdn,
queue.len()
);
} else {
tracing::warn!(
"Dropping message to {:?} because it ... | queue.push_back(msg.data); | random_line_split |
main.rs | .
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use futures::{channel::oneshot, FutureExt, TryFutureExt, TryStreamExt};
use iml_agent_comms::{
error::ImlAgentCommsError,
flush_queue,
host::{self, SharedHosts},
messaging::{consume_agent_tx_queue,... | () -> Result<(), Box<dyn std::error::Error>> {
iml_tracing::init();
// Handle an error in locks by shutting down
let (tx, rx) = oneshot::channel();
let shared_hosts = host::shared_hosts();
let shared_hosts2 = Arc::clone(&shared_hosts);
let shared_hosts3 = Arc::clone(&shared_hosts);
tokio:... | main | identifier_name |
mod.rs | ;
#[allow(unused)]
mod local_activity_state_machine;
#[allow(unused)]
mod mutable_side_effect_state_machine;
#[allow(unused)]
mod side_effect_state_machine;
#[allow(unused)]
mod signal_external_state_machine;
mod timer_state_machine;
#[allow(unused)]
mod upsert_search_attributes_state_machine;
#[allow(unused)]
mod vers... | (&self) -> bool {
self.was_cancelled_before_sent_to_server()
}
}
/// Exists purely to allow generic implementation of `is_final_state` for all [StateMachine]
/// implementors
trait CheckStateMachineInFinal {
/// Returns true if the state machine is in a final state
fn is_final_state(&self) -> bool;... | was_cancelled_before_sent_to_server | identifier_name |
mod.rs | ;
#[allow(unused)]
mod local_activity_state_machine;
#[allow(unused)]
mod mutable_side_effect_state_machine;
#[allow(unused)]
mod side_effect_state_machine;
#[allow(unused)]
mod signal_external_state_machine;
mod timer_state_machine;
#[allow(unused)]
mod upsert_search_attributes_state_machine;
#[allow(unused)]
mod vers... |
}
/// Exists purely to allow generic implementation of `is_final_state` for all [StateMachine]
/// implementors
trait CheckStateMachineInFinal {
/// Returns true if the state machine is in a final state
fn is_final_state(&self) -> bool;
}
impl<SM> CheckStateMachineInFinal for SM
where
SM: StateMachine,
{... | {
self.was_cancelled_before_sent_to_server()
} | identifier_body |
mod.rs | mod cancel_external_state_machine;
#[allow(unused)]
mod cancel_workflow_state_machine;
#[allow(unused)]
mod child_workflow_state_machine;
mod complete_workflow_state_machine;
#[allow(unused)]
mod continue_as_new_workflow_state_machine;
#[allow(unused)]
mod fail_workflow_state_machine;
#[allow(unused)]
mod local_activit... | random_line_split | ||
main.go | :"title"`
}
// logging
var logger = zerolog.New(zerolog.ConsoleWriter{
Out: os.Stdout,
NoColor: false,
TimeFormat: time.RFC3339,
}).With().Timestamp().Logger().Level(zerolog.GlobalLevel())
func Success(c *fiber.Ctx, code int, payload interface{}) error {
c.Set("Content-Type", "application/json")
c.Stat... |
client = redis.NewClient(&redis.Options{
Addr: dsn, //redis port
})
_, err := client.Ping(context.Background()).Result()
if err != nil {
panic(err)
}
}
var client *redis.Client
func FiberMiddleware(a *fiber.App) {
a.Use(
// Add CORS to each route.
cors.New(),
// Add simple logger.
fiberlogger.New()... | {
dsn = "localhost:6379"
} | conditional_block |
main.go | :"title"`
}
// logging
var logger = zerolog.New(zerolog.ConsoleWriter{
Out: os.Stdout,
NoColor: false,
TimeFormat: time.RFC3339,
}).With().Timestamp().Logger().Level(zerolog.GlobalLevel())
func Success(c *fiber.Ctx, code int, payload interface{}) error {
c.Set("Content-Type", "application/json")
c.Stat... |
var client *redis.Client
func FiberMiddleware(a *fiber.App) {
a.Use(
// Add CORS to each route.
cors.New(),
// Add simple logger.
fiberlogger.New(),
// add recoverer for panic
recover.New(),
)
}
func main() {
readTimeoutSecondsCount, _ := strconv.Atoi(os.Getenv("SERVER_READ_TIMEOUT"))
app := fiber.N... | {
//Initializing redis
dsn := os.Getenv("REDIS_DSN")
if len(dsn) == 0 {
dsn = "localhost:6379"
}
client = redis.NewClient(&redis.Options{
Addr: dsn, //redis port
})
_, err := client.Ping(context.Background()).Result()
if err != nil {
panic(err)
}
} | identifier_body |
main.go | json:"title"`
}
// logging
var logger = zerolog.New(zerolog.ConsoleWriter{
Out: os.Stdout,
NoColor: false,
TimeFormat: time.RFC3339,
}).With().Timestamp().Logger().Level(zerolog.GlobalLevel())
func Success(c *fiber.Ctx, code int, payload interface{}) error {
c.Set("Content-Type", "application/json")
c.... | UserId int64
}
type TokenDetails struct {
AccessToken string
RefreshToken string
AccessUuid string
RefreshUuid string
AtExpires int64
RtExpires int64
}
func CreateToken(userid int64) (*TokenDetails, error) {
td := &TokenDetails{}
td.AtExpires = time.Now().Add(time.Minute * 15).Unix()
td.Access... | }
}
type AccessDetails struct {
AccessUuid string | random_line_split |
main.go | json:"title"`
}
// logging
var logger = zerolog.New(zerolog.ConsoleWriter{
Out: os.Stdout,
NoColor: false,
TimeFormat: time.RFC3339,
}).With().Timestamp().Logger().Level(zerolog.GlobalLevel())
func Success(c *fiber.Ctx, code int, payload interface{}) error {
c.Set("Content-Type", "application/json")
c.... | (c *fiber.Ctx) error {
mapToken := map[string]string{}
if err := c.BodyParser(&mapToken); err != nil {
return Error(c, fiber.StatusUnprocessableEntity, err)
}
refreshToken := mapToken["refresh_token"]
//verify the token
token, err := jwt.Parse(refreshToken, func(token *jwt.Token) (interface{}, error) {
//Ma... | Refresh | identifier_name |
controller.go | "
"github.com/rancher/rancher/pkg/types/config"
"github.com/rancher/rancher/pkg/types/config/systemtokens"
"github.com/rancher/rancher/pkg/user"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
)
const (
composeTokenPrefix = "compos... | tokenPrefix := composeTokenPrefix + user.Name
token, err := l.systemTokens.EnsureSystemToken(tokenPrefix, description, "compose", user.Name, nil, true)
if err != nil {
return obj, err
}
tokenName, _ := tokens.SplitTokenParts(token)
defer func() {
if err := l.systemTokens.DeleteToken(tokenName); err != nil {
... | userID := obj.Annotations["field.cattle.io/creatorId"]
user, err := l.UserClient.Get(userID, metav1.GetOptions{})
if err != nil {
return obj, err
} | random_line_split |
controller.go | (*v3.ComposeConfig, error) {
userID := obj.Annotations["field.cattle.io/creatorId"]
user, err := l.UserClient.Get(userID, metav1.GetOptions{})
if err != nil {
return obj, err
}
tokenPrefix := composeTokenPrefix + user.Name
token, err := l.systemTokens.EnsureSystemToken(tokenPrefix, description, "compose", user... | {
if _, ok := schema.ResourceFields["creatorId"]; !ok {
continue
}
r[k] = schema
} | conditional_block | |
controller.go | "github.com/rancher/rancher/pkg/types/config"
"github.com/rancher/rancher/pkg/types/config/systemtokens"
"github.com/rancher/rancher/pkg/user"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
)
const (
composeTokenPrefix = "compose-... |
baseClusterClient, err := clientbase.NewAPIClient(&clientbase.ClientOpts{
URL: fmt.Sprintf(url, port) + "/cluster",
TokenKey: token,
Insecure: true,
})
if err != nil {
return err
}
baseManagementClient, err := clientbase.NewAPIClient(&clientbase.ClientOpts{
URL: fmt.Sprintf(url, port),
Token... | {
clusterSchemas, managementSchemas, projectSchemas, err := GetSchemas(token, port)
if err != nil {
return err
}
// referenceMap is a map of schemaType with name -> id value
referenceMap := map[string]map[string]string{}
rawData, err := json.Marshal(config)
if err != nil {
return err
}
rawMap := map[stri... | identifier_body |
controller.go | "compose-controller", l.sync)
}
func (l Lifecycle) sync(key string, obj *v3.ComposeConfig) (runtime.Object, error) {
if key == "" || obj == nil {
return nil, nil
}
newObj, err := v32.ComposeConditionExecuted.Once(obj, func() (runtime.Object, error) {
obj, err := l.Create(obj)
if err != nil {
return obj, &... | getAllSchemas | identifier_name | |
process_rwis.py | XBFI',
'56': 'XDYI', '57': 'XTMI', '58': 'XPFI', '59': 'XCTI',
'60': 'XDNI', '61': 'XQCI', '62': 'XSMI', '63': 'XRWI',
'64': 'XETI', '65': 'XCCI', '66': 'XKSI', '67': 'XKNI',
'68': 'XCMI', '69': 'XRGI', '70': 'XKYI', '72': 'XCTI'}
KNOWN_UNKNOWNS = []
def get_nw... | continue
o = open(fn, 'w')
o.write(" ")
o.close()
lts = ob['valid'].astimezone(pytz.timezone("America/Chicago"))
stname = NT.sts[sid]['name']
msg = ("At %s, a wind gust of %.1f mph (%.1f kts) was recorded "
"at the %s (%s) Iowa RWIS station"
... | if sid in ['RBFI4', 'RTMI4', 'RWII4', 'RCAI4', 'RDYI4',
'RDNI4', 'RCDI4', 'RCII4', 'RCLI4', 'VCTI4',
'RGAI4', 'RAVI4']:
continue
ob = obs[sid]
# screening
if ob.get('gust') is None or ob['gust'] < 40:
continue
if np.isnan(ob['... | conditional_block |
process_rwis.py | XBFI',
'56': 'XDYI', '57': 'XTMI', '58': 'XPFI', '59': 'XCTI',
'60': 'XDNI', '61': 'XQCI', '62': 'XSMI', '63': 'XRWI',
'64': 'XETI', '65': 'XCCI', '66': 'XKSI', '67': 'XKNI',
'68': 'XCMI', '69': 'XRGI', '70': 'XKYI', '72': 'XCTI'}
KNOWN_UNKNOWNS = []
def get_nw... |
def get_speed(val):
""" Convert a speed value """
if val in ['', 255]:
return None
return speed(val, 'KMH').value('KT')
def merge(atmos, surface):
"""Create a dictionary of data based on these two dataframes
Args:
atmos (DataFrame): atmospherics
surface (DataFrame): surface... | """Attempt to convert a RWIS temperature into F"""
if val in ['', 32767]:
return None
return temperature(val / 100., 'C').value('F') | identifier_body |
process_rwis.py | 100.
# Rh is unused
data[nwsli]['sknt'] = get_speed(row['SpdAvg'])
data[nwsli]['gust'] = get_speed(row['SpdGust'])
if row['DirMin'] not in ['', 32767, np.nan]:
data[nwsli]['drct'] = row['DirMin']
# DirMax is unused
# Pressure is not reported
# PcInten... | update_iemaccess | identifier_name | |
process_rwis.py | XBFI',
'56': 'XDYI', '57': 'XTMI', '58': 'XPFI', '59': 'XCTI',
'60': 'XDNI', '61': 'XQCI', '62': 'XSMI', '63': 'XRWI', |
KNOWN_UNKNOWNS = []
def get_nwsli(rpuid):
"""Lookup a rpuid and return the NWSLI"""
rpuid = int(rpuid)
for sid in NT.sts:
if NT.sts[sid]['remote_id'] == rpuid:
return sid
return None
def get_temp(val):
"""Attempt to convert a RWIS temperature into F"""
if val in ['', 327... | '64': 'XETI', '65': 'XCCI', '66': 'XKSI', '67': 'XKNI',
'68': 'XCMI', '69': 'XRGI', '70': 'XKYI', '72': 'XCTI'} | random_line_split |
cimport.rs | {
sentinel: c_char,
}
#[link(name = "assimp")]
extern {
/// Reads the given file and returns its content.
///
/// If the call succeeds, the imported data is returned in an aiScene
/// structure. The data is intended to be read-only, it stays property of
/// the ASSIMP library and will be sta... | PropertyStore | identifier_name | |
cimport.rs | ///
/// If the call succeeds, the imported data is returned in an aiScene
/// structure. The data is intended to be read-only, it stays property of
/// the ASSIMP library and will be stable until aiReleaseImport() is
/// called. After you're done with it, call aiReleaseImport() to free the
/// res... | ///
/// * props PropertyStore instance containing import settings.
pub fn aiImportFileFromMemoryWithProperties(buf: *const c_char,
len: c_uint,
flags: c_uint,
hint: *const c_ch... | /// Same as aiImportFileFromMemory, but adds an extra parameter
/// containing importer settings. | random_line_split |
z5113243_ass_2.py | (__name__)
app.config.SWAGGER_UI_DOC_EXPANSION = 'list'
api = Api(
app,
title='Assignment 2 - COMP9321 - Chris Joy (z5113243)',
description='In this assignment, we\'re asked to develop ' \
'a Flask-Restplus data service that allows a client to ' \
'read and store some publicly available economic indicator ' \... |
@api.route(f'/{COLLECTION}/<collection_id>', endpoint=f'{COLLECTION}_by_id')
@api.param('collection_id', f'Unique id, used to distinguish {COLLECTION}.')
class CollectionsById(Resource):
@api.doc(description='[Q2] Deleting a collection with the data service.')
@api.response(200, 'Successfully removed collection.'... | try:
collections = db[COLLECTION].find()
except:
return { 'message': 'Unable to retrieve collections.' }, 400
return [{
'location': f'/{COLLECTION}/{str(doc["_id"])}',
'collection_id': str(doc['_id']),
'creation_time': str(doc['creation_time']),
'indicator': doc['indicator'],... | identifier_body |
z5113243_ass_2.py | (__name__)
app.config.SWAGGER_UI_DOC_EXPANSION = 'list'
api = Api(
app,
title='Assignment 2 - COMP9321 - Chris Joy (z5113243)',
description='In this assignment, we\'re asked to develop ' \
'a Flask-Restplus data service that allows a client to ' \
'read and store some publicly available economic indicator ' \... |
# From now onwards we need to obtain data from the Worldbank API
indicator_data = get_indicator_data(body['indicator_id'])
# Valid indicator hasn't been specified (400)
if indicator_data == 'Invalid indicator':
return { 'message': 'Please specify a valid indicator.' }, 400
# Create and retrie... | return {
'location': f'/{COLLECTION}/{str(existing_collection["_id"])}',
'collection_id': str(existing_collection['_id']),
'creation_time': str(existing_collection['creation_time']),
'indicator': existing_collection['indicator'],
}, 200 | conditional_block |
z5113243_ass_2.py | , bottom40')
#------------- HELPER FUNCTIONS -------------#
def mlab_client(dbuser, dbpassword, mlab_inst, dbname):
return MongoClient(
f'mongodb://{dbuser}:{dbpassword}@{mlab_inst}.mlab.com:39071/{dbname}'
)[dbname]
def api_url(indicator, date='2012:2017', fmt='json', page=1):
return 'http://api.worldbank... | 'entries': filtered_entries,
}, 200 | random_line_split | |
z5113243_ass_2.py | (__name__)
app.config.SWAGGER_UI_DOC_EXPANSION = 'list'
api = Api(
app,
title='Assignment 2 - COMP9321 - Chris Joy (z5113243)',
description='In this assignment, we\'re asked to develop ' \
'a Flask-Restplus data service that allows a client to ' \
'read and store some publicly available economic indicator ' \... | (self, collection_id):
# Check if collection exists
if not db[COLLECTION].find_one({'_id': ObjectId(collection_id)}):
return { 'message': 'Unable to find collection.' }, 404
# Remove collection from db
try:
db[COLLECTION].delete_one({'_id': ObjectId(collection_id)})
except:
return ... | delete | identifier_name |
stacks.rs | ::new();
let run_type = types.len();
types.function(vec![wasm_encoder::ValType::I32], vec![]);
let get_stack_type = types.len();
types.function(
vec![],
vec![wasm_encoder::ValType::I32, wasm_encoder::ValType::I32],
);
let null_type = types.len()... | {
let mut rng = SmallRng::seed_from_u64(0);
let mut buf = vec![0; 2048];
for _ in 0..1024 {
rng.fill_bytes(&mut buf);
let u = Unstructured::new(&buf);
if let Ok(stacks) = Stacks::arbitrary_take_rest(u) {
let wasm = stacks.wasm();
... | identifier_body | |
stacks.rs | mut Unstructured) -> Result<Vec<Function>> {
let mut funcs = vec![Function::default()];
// The indices of functions within `funcs` that we still need to
// generate.
let mut work_list = vec![0];
while let Some(f) = work_list.pop() {
let mut ops = Vec::with_capacity(... | vec![wasm_encoder::ValType::I32, wasm_encoder::ValType::I32],
);
let null_type = types.len();
types.function(vec![], vec![]);
let call_func_type = types.len();
types.function(vec![wasm_encoder::ValType::FUNCREF], vec![]);
section(&mut module, types);
... | let get_stack_type = types.len();
types.function(
vec![], | random_line_split |
stacks.rs | (u: &mut Unstructured) -> Result<Vec<Function>> {
let mut funcs = vec![Function::default()];
// The indices of functions within `funcs` that we still need to
// generate.
let mut work_list = vec![0];
while let Some(f) = work_list.pop() {
let mut ops = Vec::with_capa... | arbitrary_funcs | identifier_name | |
uri.ts |
ls32 = ( h16 ":" h16 ) / IPv4address ; least-significant 32 bits of address
IPv6address = 6( h16 ":" ) ls32
/ "::" 5( h16 ":" ) ls32
/ [ h16 ] "::" 4( h16 ":" ) ls32
/ [ *1( h16 ":... | createRegex | identifier_name | |
uri.ts | 2" %x30-34 DIGIT / "25" %x30-35 ; 0-9 / 10-99 / 100-199 / 200-249 / 250-255
rfc3986.ipv4address = '(?:' + decOctect + '\\.){3}' + decOctect; // IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
/*
h16 = 1*4HEXDIG ; 16 bits of address represented in hexadecimal
ls32 = ( h16 ":"... | ')' +
'|' +
pathAbsolute +
'|' +
pathNoScheme +
'|' +
pathEmpty +
')';
// query = *( pchar / "/" / "?" )
// query = *( pchar / "[" / "]" / "/" / "?" )
rfc3986.query = '[' + pchar + '\\/\\?]*(?=#|$)'; //Finish matching either at the fragment p... | random_line_split | |
uri.ts | ":" ) ls32
/ [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
/ [ *4( h16 ":" ) h16 ] "::" ls32
/ [ *5( h16 ":" ) h16 ] "::" h16
/ [ *6( h16 ":" ) h16 ] "::"
*/
const h16 = hexDigitOnly + '{1,4}';
const l... | {
const rfc = rfc3986;
// Construct expression
const query = options.allowQuerySquareBrackets ? rfc.queryWithSquareBrackets : rfc.query;
const suffix = '(?:\\?' + query + ')?' + '(?:#' + rfc.fragment + ')?';
// relative-ref = relative-part [ "?" query ] [ "#" fragment ]
const relative = opti... | identifier_body | |
uri.ts | h16 + ')?::(?:' + h16 + ':){4}' + ls32;
const IPv6ThreeHex = '(?:(?:' + h16 + ':){0,1}' + h16 + ')?::(?:' + h16 + ':){3}' + ls32;
const IPv6TwoHex = '(?:(?:' + h16 + ':){0,2}' + h16 + ')?::(?:' + h16 + ':){2}' + ls32;
const IPv6OneHex = '(?:(?:' + h16 + ':){0,3}' + h16 + ')?::' + h16 + ':' + ls32;
cons... | {
const scheme = schemes[i];
assert(
scheme instanceof RegExp || typeof scheme === 'string',
'scheme at position ' + i + ' must be a RegExp or String'
);
if (scheme instanceof RegExp) {
selections.push(scheme.source.toStrin... | conditional_block | |
window.rs | fn select_gpu_device(
app: &App,
surface: &wgpu::Surface,
) -> UiResult<(wgpu::Device, wgpu::Queue)> {
use futures::executor::block_on;
let adapter_opts = wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::Default,
compatible_surface: ... | } | random_line_split | |
window.rs | _window()`.
pub(crate) fn new(
app: &mut app::App,
data_model: Box<dyn Layout>,
wnd: winit::window::Window,
visible: bool,
) -> UiResult<Window> {
let size = wnd.inner_size();
let surface = unsafe { app.wgpu_instance.create_surface(&wnd) };
// select adap... | drop | identifier_name | |
window.rs | wgpu::TextureAspect::All,
base_mip_level: 0,
level_count: None,
base_array_layer: 0,
array_layer_count: None,
};
(
device.create_texture(tex_desc).create_view(&tex_view_desc),
tex_extent,
sample_count,
)
}
... | {
return Err(ErrorCode::WINDOW_DOES_NOT_EXIST.into());
} | conditional_block | |
window.rs | = now;
frame_delta
}
/// Creates a standard top level window.
///
/// Call this method inside the closure passed to `App::new_window()`.
pub fn build_window(title: &str, size: (u32, u32)) -> winit::window::WindowBuilder {
winit::window::WindowBuilder::new()
.with_titl... | {
&mut self.renderer.textures
} | identifier_body | |
PNotifyBootstrap3.js | if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super... |
function blank_object() {
return Object.create(null);
}
function run_all(fns) {
fns.forEach(run);
}
function is_function(thing) {
return typeof thing === 'function';
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || a && _typeof(a) === 'object' || ty... | {
return fn();
} | identifier_body |
PNotifyBootstrap3.js |
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty... | }
}
| random_line_split | |
PNotifyBootstrap3.js | if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super... | ($$) {
if ($$.fragment !== null) {
$$.update();
run_all($$.before_update);
var dirty = $$.dirty;
$$.dirty = [-1];
$$.fragment && $$.fragment.p($$.ctx, dirty);
$$.after_update.forEach(add_render_callback);
}
}
var outroing = new Set();
function transition_... | update | identifier_name |
prittynoteAppManager.js | the canvas dynamically
getHeight: function(text, ctx, x, y, mW, lH, img) {
var words = text.split(" "); //all words one by one
var c = 0, a = x, h;
var br = /(`)[\w]{0,}/
$.map(words, function(wd) {
var string = wd + " ";
var m = ctx.measureText(st... | for (var n= 0; n<words.length; n++) {
var string = words[n] + " ";
var m = ctx.measureText(string);
var w = m.width; //width of word + " "
var p = hash.test(string); //match string to regex
var r = rest.test(string);
var sq = startq... |
var qc = 0; //will count, 0 means return color to normal
| random_line_split |
prittynoteAppManager.js | assign the canvas dynamically
getHeight: function(text, ctx, x, y, mW, lH, img) {
var words = text.split(" "); //all words one by one
var c = 0, a = x, h;
var br = /(`)[\w]{0,}/
$.map(words, function(wd) {
var string = wd + " ";
var m = ctx.measure... |
ctx.fillText(string, x, y); //print it out
x += w; //set next "x" offset for the next word
var xnw = ctx.measureText(words[n+1] + " ").width; //check for the future next word
var xn = x + xnw;
//console.log(xn);
if(xn >= cW) { //try ... | {
//test for quotes, will depict the quote length and color it all
if(p) { //change color of only single words with single hash tags
ctx.fillStyle = hTagclr;
string = string.replace('#', '');
w = ctx.measureText(string).w... | conditional_block |
press.py | _train]))
test_db_examples = ut.flatten(ut.parmap(examples_from_db, [(x, im_dir) for x in db_test]))
print 'Number of db train examples:', len(train_db_examples)
print 'Number of meta examples:', len(meta_examples)
train_examples = ut.shuffled_with_seed(meta_examples + train_db_examples)
ut.write_lines(pj(out... | run | identifier_name | |
press.py | 0, label))
ut.sys_check('cp %s %s' % (fname, prev_file))
with ut.TmpDir() as tmp_dir:
# ut.sys_check('ffmpeg -i "%s" -vf scale=%d:%d -ss %f -t %f -r %d "%s/%%07d.png"' % \
# (vid_file, full_dim, full_dim, time,
# sample_dur_secs, sample_fps, tmp_dir))
ut.sys_check... |
examples.append((im_file, prev_file, label, db_file))
except:
print 'Failed to open:', db_file
return examples
def write_data(vid_path, out_dir, train_frac = 0.75):
im_dir = ut.mkdir(pj(out_dir, 'ims'))
in_data = []
meta_files = sorted(ut.glob(vid_path, 'train', '*.txt'))
print '... | raise RuntimeError('No label!') | conditional_block |
press.py | lr_val, 'loss:', \
moving_avg('loss', loss_val), 'acc:', moving_avg('acc', acc_val)
def run(todo = 'all',
vid_path = '/home/ao/Videos/Webcam',
#out_dir = '../results/press-data-v7/',
#out_dir = '../results/press-data-v8/',
#out_dir = '../results/press-data-v9/',
... | train_dir = pj(path, 'training')
check_path = tf.train.latest_checkpoint(train_dir) | random_line_split | |
press.py | , 0, label))
ut.sys_check('cp %s %s' % (fname, prev_file))
with ut.TmpDir() as tmp_dir:
# ut.sys_check('ffmpeg -i "%s" -vf scale=%d:%d -ss %f -t %f -r %d "%s/%%07d.png"' % \
# (vid_file, full_dim, full_dim, time,
# sample_dur_secs, sample_fps, tmp_dir))
ut.sys_chec... |
def read_example(rec_queue):
reader = tf.TFRecordReader()
k, s = reader.read(rec_queue)
feats = {
'im' : tf.FixedLenFeature([], dtype=tf.string),
'im_prev' : tf.FixedLenFeature([], dtype=tf.string),
'label' : tf.FixedLenFeature([], tf.int64)
}
example = tf.parse_single_example(s, features = fe... | tf_file = pj(path, 'train.tf')
if os.path.exists(tf_file):
os.remove(tf_file)
writer = tf.python_io.TFRecordWriter(tf_file)
lines = ut.shuffled_with_seed(ut.read_lines(pj(path, 'train.csv')))
print 'Number of examples:', len(lines)
for line in lines:
fname, prev_fname, label, _ = line.split(',')
l... | identifier_body |
argumentParser.py | ''')
def parse_args(args):
parser = argparse.ArgumentParser(formatter_class=SmartFormatter)
subparsers = parser.add_subparsers(help='Desired operation',dest='operation')
# Make a parent parser for all of the subparsers
parent_parser = argparse.ArgumentParser(add_help=False)
Bflags = parent_p... | print('')
print(' ...::: inStrain v' + __version__ + ' :::...''')
print('''\
Matt Olm and Alex Crits-Christoph. MIT License. Banfield Lab, UC Berkeley.
Choose one of the operations below for more detailed help. See https://instrain.readthedocs.io for documentation.
Example: inStrain pr... | identifier_body | |
argumentParser.py | ", help="Algorithm used to cluster genomes (passed\
to scipy.cluster.hierarchy.linkage)", default='average',
choices={'single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward'})
Bflags = compare_parser.add_argument_group('SNV POOLING OPTIONS')
... | printHelp()
sys.exit(0) | conditional_block | |
argumentParser.py | _only", choices={'paired_only', 'non_discordant', 'all_reads'})
fiflags.add_argument("--priority_reads", help='The location of a list ' \
+ "of reads that should be retained regardless of pairing status " \
+ "(for example long reads or merged reads). This can be a .fastq " \ | + "file or text file with list of read names (will assume file is " \
+ "compressed if ends in .gz", default=None)
# Make a parent parser for read output
readoutput_parent = argparse.ArgumentParser(add_help=False)
fiflags = readoutput_parent.add_argument_group('READ OUTPUT OPTIONS')
# f... | random_line_split | |
argumentParser.py | (self, text, width):
if text.startswith('R|'):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
def printHelp():
print('')
print(' ...::: inStrain v' + __version__ + ' ::... | _split_lines | identifier_name | |
template.js | (price);
d.close().remove();
}else{
alert("请输入数字!");
}
});
});
}
batch();
})(jQuery);
function makeSku() {
var HEADER = "<th width='100px'>商品价格" +
"<a><span class='glyphicon glyphicon-edit batch-price pull-... | this.getText = function () {
return texts.join(";");
};
this.getValues = function () {
return values;
};
this.getTds = function () {
return "<td class='sku'>" + values.join("</td><td class='sku'>") + "</td>";
... | identifier_name | |
template.js |
var target = $(this).data('target');
$('#confirm').click(function (e) {
var price = $('#price').val();
if(!isNaN(price)){
$(target).val(price);
d.close().remove();
}else{
alert("请输入数字!"... | width: 120,
heigth: 20
});
d.show($(this)[0]); | random_line_split | |
template.js | 00px'>进货价格" +
"<a><span class='glyphicon glyphicon-edit batch-price pull-right' data-target='.enterPrice'></span></a>" +
"</th>" +
"<th width='100px'>库存" +
"<a><span class='glyphicon glyphicon-edit batch-price pull-right' data-target='.stock'></span></a>" +
"</th>" +
"<th... | .appendChild(createValueTd(id));
| conditional_block | |
template.js | );
d.close().remove();
}else{
alert("请输入数字!");
}
});
});
}
batch();
})(jQuery);
function makeSku() {
var HEADER = "<th width='100px'>商品价格" +
"<a><span class='glyphicon glyphicon-edit batch-price pull-right'... |
values.push(input.val());
var label = $("." + SKU_NAME + "[data-id=" + forId + "]").val();
texts.push(label + ":" + input.val());
}
}
init(item)
}
function clear(ids) {
var trs = $("#skuBo... | n texts.join(";");
};
this.getValues = function () {
return values;
};
this.getTds = function () {
return "<td class='sku'>" + values.join("</td><td class='sku'>") + "</td>";
};
function init(checkboxe... | identifier_body |
ZenModelBase.py | to see if the current user has permission on remote object.
@param permission: Zope permission to be tested. ie "View"
@param robject: remote objecct on which test is run. Will test on
primary acquisition path.
@rtype: boolean
@permission: ZEN_COMMON
"""
user =... | manage_deleteObjects | identifier_name | |
ZenModelBase.py | else:
REQUEST['URL'] = "%s/%s" % (self.absolute_url_path(), screenName)
screen = getattr(self, screenName, False)
if not screen: return self()
return screen()
@unpublished
def zenScreenUrl(self):
"""
Return the url for the current screen as defi... | """
DEPRECATED Split a path on its '/'.
"""
return zenpathsplit(path) | identifier_body | |
ZenModelBase.py | , relName)
candidate = baseKey
while candidate in rel.objectIds():
candidate = self.prepId('%s%s' % (baseKey, extensionIter.next()))
return candidate
def getIdLink(self): | DEPRECATED Return an a link to this object with its id as the name.
@return: An HTML link to this object
@rtype: string
>>> dmd.Devices.getIdLink()
'<a href="/zport/dmd/Devices">/</a>'
"""
return self.urlLink()
def callZenScreen(self, REQUEST, redirect=Fal... | """ | random_line_split |
ZenModelBase.py | .has_permission(permission, robject.primaryAq())
security.declareProtected(ZEN_VIEW, 'zentinelTabs')
def zentinelTabs(self, templateName, REQUEST=None):
"""
Return a list of hashes that define the screen tabs for this object.
Keys in the hash are:
- action = the name of t... | return self.callZenScreen(REQUEST) | conditional_block | |
main.rs | File, self};
use std::io::Write;
use std::path::PathBuf;
use std::collections::BTreeSet;
#[derive(Default)]
struct Handler {
channel_id: Arc<Mutex<BTreeSet<ChannelId>>>
}
impl Handler {
pub fn new<It: IntoIterator<Item=ChannelId>>(channels: It) -> Handler {
Handler {
channel_id: Arc::new(M... | else {
message.say("Channel was not set");
}
}
}
} else {
message.reply("You do not have the proper permissions to set the channel.");
}
}
impl EventHandler for Handler {
fn message(&self, context: Context, message: Message) {
let mes... | {
message.say("Channel unset");
} | conditional_block |
main.rs | File, self};
use std::io::Write;
use std::path::PathBuf;
use std::collections::BTreeSet;
#[derive(Default)]
struct Handler {
channel_id: Arc<Mutex<BTreeSet<ChannelId>>>
}
impl Handler {
pub fn new<It: IntoIterator<Item=ChannelId>>(channels: It) -> Handler {
Handler {
channel_id: Arc::new(M... | (label_paths: &[&str]) {
hash40::set_labels(
label_paths
.iter()
.map(|label| hash40::read_labels(label | update_labels | identifier_name |
main.rs | File, self};
use std::io::Write;
use std::path::PathBuf;
use std::collections::BTreeSet;
#[derive(Default)]
struct Handler {
channel_id: Arc<Mutex<BTreeSet<ChannelId>>>
}
impl Handler {
pub fn new<It: IntoIterator<Item=ChannelId>>(channels: It) -> Handler |
}
use converter::SUPPORTED_TYPES;
static HELP_TEXT: &str =
"%convert [args] - convert file even if channel isn't set
%help - display this message\n\
%set_channel - watch this channel for files\n\
%unset_channel - don't watch this channel to watch for files\n\
%update - update param labels and install paramxml if no... | {
Handler {
channel_id: Arc::new(Mutex::new(channels.into_iter().collect())),
..Default::default()
}
} | identifier_body |
main.rs | File, self};
use std::io::Write;
use std::path::PathBuf;
use std::collections::BTreeSet;
#[derive(Default)]
struct Handler {
channel_id: Arc<Mutex<BTreeSet<ChannelId>>>
}
impl Handler {
pub fn new<It: IntoIterator<Item=ChannelId>>(channels: It) -> Handler {
Handler {
channel_id: Arc::new(M... | enum SetUnset {
Set,
Unset
}
use SetUnset::*;
fn save_channels(channel_ids: &BTreeSet<ChannelId>, message: &MessageHelper, owner: &User) {
if let Err(e) = fs::write(
CHANNELS_PATH,
channel_ids.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("... | Arthur, Dr. Hypercake, Birdwards, SMG, Meshima, TNN, Blazingflare, TheSmartKid - Param labels\n\
coolsonickirby, SushiiZ - testing help";
| random_line_split |
core_model_estimator.py | self,
tf_session: tf.Session,
learning_rate: float,
training_dataset: DataManager = None,
validation_dataset: DataManager = None,
output_path: str = '../outputs',
use_tpu: str = False,
tpu_name: list =... | (self, data_source: DataManager , mode: str): #pylint: disable=E0202
"""Definition of the model to use. Do not modify the function here
placeholder for the actual definition in `model/` (see example)
Args:
data_source (DataManager): Data manager object for the input data
... | define_model | identifier_name |
core_model_estimator.py | self,
tf_session: tf.Session,
learning_rate: float,
training_dataset: DataManager = None,
validation_dataset: DataManager = None,
output_path: str = '../outputs',
use_tpu: str = False,
tpu_name: list =... |
for idx, element in enumerate(self.otters['validation']):
summary.append(
tf.summary.scalar(name='val/otter_{}'.format(idx), tensor=element))
self.summary_ops['validation'] = tf.summary.merge(summary)
self.writer = tf.summary.FileWriter(self.output_p... | summary.append(
tf.summary.scalar(name='val/loss_{}'.format(idx), tensor=loss)) | conditional_block |
core_model_estimator.py |
# if validation_dataset: self.dataset['validation'] = validation_dataset.datasource
self.datasource = {}
self.datasource['train'] = training_dataset
self.datasource['validation'] = validation_dataset
self._train_model = True if training_dataset is not None else False
... | return restored_step
logging.info('Starting training from scratch.')
return 0
def evaluate(self): | random_line_split | |
core_model_estimator.py | self,
tf_session: tf.Session,
learning_rate: float,
training_dataset: DataManager = None,
validation_dataset: DataManager = None,
output_path: str = '../outputs',
use_tpu: str = False,
tpu_name: list =... |
def _tpu_train(self, steps, input_fn):
# def _input_fn(params):
# featuers, labels = self.datasource['train'].input_fn(params['batch_size'])
# return featuers, labels
self.estimator.train(
input_fn=input_fn,
max_steps=steps)
logging.info('E... | if self.use_tpu:
self._tpu_train(steps, input_fn)
else:
self._regular_train(steps) | identifier_body |
ext.rs | E: Curve>(
mut self,
scalars: impl IntoIterator<Item = &'s Scalar<E>>,
) -> Self
where
Self: Sized,
{
for scalar in scalars {
self.input_scalar(scalar)
}
self
}
fn result_bigint(self) -> BigInt;
fn result_scalar<E: Curve>(self) -> Sca... |
}
unreachable!("The probably of this reaching is extremely small ((2^n-q)/(2^n))^(2^32)")
}
fn digest_bigint(bytes: &[u8]) -> BigInt {
Self::new().chain(bytes).result_bigint()
}
}
/// [Hmac] extension allowing to use bigints to instantiate hmac, update, and finalize it.
pub trait ... | {
return scalar;
} | conditional_block |
ext.rs | mut self,
scalars: impl IntoIterator<Item = &'s Scalar<E>>,
) -> Self
where
Self: Sized,
{
for scalar in scalars {
self.input_scalar(scalar)
}
self
}
fn result_bigint(self) -> BigInt;
fn result_scalar<E: Curve>(self) -> Scalar<E>;
... | self
}
fn chain_scalars<'s, E: Curve>( | random_line_split | |
ext.rs | BigInt::from_bytes(&self.finalize().into_bytes())
}
fn verify_bigint(self, code: &BigInt) -> Result<(), MacError> {
self.verify(&code.to_bytes())
}
}
#[cfg(test)]
mod test {
use sha2::{Sha256, Sha512};
use super::*;
// Test Vectors taken from:
// https://csrc.nist.gov/projects/c... | create_sha256_from_ge_test | identifier_name | |
ext.rs | E: Curve>(
mut self,
scalars: impl IntoIterator<Item = &'s Scalar<E>>,
) -> Self
where
Self: Sized,
{
for scalar in scalars {
self.input_scalar(scalar)
}
self
}
fn result_bigint(self) -> BigInt;
fn result_scalar<E: Curve>(self) -> Sca... |
}
/// [Hmac] extension allowing to use bigints to instantiate hmac, update, and finalize it.
pub trait HmacExt: Sized {
fn new_bigint(key: &BigInt) -> Self;
fn input_bigint(&mut self, n: &BigInt);
fn chain_bigint(mut self, n: &BigInt) -> Self
where
Self: Sized,
{
self.input_bigin... | {
Self::new().chain(bytes).result_bigint()
} | identifier_body |
oldlib.rs | (h: &[u8]) -> bool {
(h[2] & 0x2) != 0
}
pub fn hdr_test_mpeg1(h: &[u8]) -> bool {
(h[1] & 0x08) != 0
}
pub fn hdr_test_not_mpeg25(h: &[u8]) -> bool {
(h[1] & 0x10) != 0
}
pub fn hdr_test_i_stereo(h: &[u8]) -> bool {
(h[3] & 0x10) != 0
}
pub fn hdr_test_ms_stereo(h: &[u8]) -> bool {
(h[3] & 0x20... | hdr_test_padding | identifier_name | |
oldlib.rs | 8],
// mp3_bytes: usize,
// pcm: &[Mp3Sample],
// info: &FrameInfo,
// ) -> i32 {
// 0
// }
pub struct Bs {
pub buf: Vec<u8>,
pub pos: usize,
pub limit: usize,
}
pub struct L12ScaleInfo {
pub scf: [f32; 3 * 64],
pub total_bands: u8,
pub stereo_bands: u8,
pub bitalloc: [u8; ... |
self.pos += n as usize;
p += 1;
next = p & (255 >> s);
while shl > 0 {
shl -= 8;
cache |= next << shl;
next = p;
p += 1;
}
return cache | (next >> -shl);
}
}
/*
pub fn hdr_valid(h: &[u8]) -> bool {
h[0] == 0xFF
... | {
return 0;
} | conditional_block |
oldlib.rs | u8],
// mp3_bytes: usize,
// pcm: &[Mp3Sample],
// info: &FrameInfo,
// ) -> i32 {
// 0
// }
pub struct Bs {
pub buf: Vec<u8>,
pub pos: usize,
pub limit: usize,
}
pub struct L12ScaleInfo {
pub scf: [f32; 3 * 64],
pub total_bands: u8,
pub stereo_bands: u8,
pub bitalloc: [u8;... | 4
} else {
1
}
} else {
0
}
}
pub fn L12_subband_alloc_table(hdr: &[u8], sci: &mut L12ScaleInfo) -> Vec<L12SubbandAlloc> {
let mode = hdr_get_stereo_mode(hdr) as usize;
let mut nbands;
let mut alloc: Vec<L12SubbandAlloc> = vec![];
let stereo_bands ... | random_line_split | |
oldlib.rs | 8],
// mp3_bytes: usize,
// pcm: &[Mp3Sample],
// info: &FrameInfo,
// ) -> i32 {
// 0
// }
pub struct Bs {
pub buf: Vec<u8>,
pub pos: usize,
pub limit: usize,
}
pub struct L12ScaleInfo {
pub scf: [f32; 3 * 64],
pub total_bands: u8,
pub stereo_bands: u8,
pub bitalloc: [u8; ... |
}
/*
pub fn hdr_valid(h: &[u8]) -> bool {
h[0] == 0xFF
&& ((h[1] & 0xF0) == 0xF0 || (h[1] & 0xFE) == 0xE2)
&& hdr_get_layer(h) != 0
&& hdr_get_bitrate(h) != 15
&& hdr_get_sample_rate(h) != 3
}
pub fn hdr_compare(h1: &[u8], h2: &[u8]) -> bool {
hdr_valid(h2)
&& ((h1[1] ... | {
let mut next: u32;
let mut cache: u32 = 0;
let s = (self.pos & 7) as u32;
let mut shl: i32 = n as i32 + s as i32;
let mut p = self.pos as u32 / 8;
if self.pos + (n as usize) > self.limit {
return 0;
}
self.pos += n as usize;
p += 1;
... | identifier_body |
core.py |
def step_check(obs, nstnnets, var, ivar, qc_flag):
"""
Perform "delta test" which, for each station checks each hour
in a day, checks for jumps between consecutive observations
that exceed a given threshold.
"""
iqcflag = istepflag
ndts = len(obs[:, 0, ivar]) # # of hours in d.
le... | td_gt_t_tol = 2.0 # tolerance for dew point being > temperature.
iqcflag = irangeflag # array index of range test.
ndts = len(obs[:, 0, ivar]) # nr of hours in d.
it = 0 # index temp
itd = 0 # index temp dew
for d in range(ndts): # timestamps
for s in range(nstnnets): # stations
... | identifier_body | |
core.py | else:
qc_flag[d, s, ivar, iqcflag] = passflag
# New test which looks for smaller spike in windspeed that is a 1 hour jump that come back down immediately
# not implemented?
# SECOND SET OF TESTS
# if (var in ['spd', 't', 'td', 'slp']) and d != ndts - 1:... |
def spatial_check(obs, nstnnets, lat, lon, elev, var, ivar, qc_flag):
"""
Spatial_check does does a spatial QC test using a simple neighbor check whereby it looks at stations within a radius
and elevation band and checks if at least one value is near the value in question. If not, it tries a bigger radi... | for idx in vali: # Make sure not to stomp on previous persistence tests!
if qc_flag[idx, s, ivar, iqcflag] != level and qc_flag[idx, s, ivar, iqcflag] != passflag:
qc_flag[idx, s, ivar, iqcflag] = notestflag | conditional_block |
core.py | - lon[d, s]) > londiff \
or abs(elev[d, ss] - elev[d, s]) > max_elev_diff:
continue
if qc_flag[d, ss, ivar, irangeflag] == failflag \
or qc_flag[d, ss, ivar, istepflag] in [suspflag, warnflag] \
or qc_flag[d, ss... | # !--- (except itself). First time through get # of stations
# !--- within radius of influence to determine if we can do
# !--- this test.
# do ss = 1, nstnnets
# | random_line_split | |
core.py | :
qc_flag[d, s, ivar, iqcflag] = passflag
# New test which looks for smaller spike in windspeed that is a 1 hour jump that come back down immediately
# not implemented?
# SECOND SET OF TESTS
# if (var in ['spd', 't', 'td', 'slp']) and d != ndts - 1: # o... | (obs, nstnnets, lat, lon, elev, var, ivar, qc_flag):
"""
Spatial_check does does a spatial QC test using a simple neighbor check whereby it looks at stations within a radius
and elevation band and checks if at least one value is near the value in question. If not, it tries a bigger radius
and checks ag... | spatial_check | identifier_name |
pushsync.go | back: %w", p.Address.String(), err)
}
defer debit.Cleanup()
// pass back the receipt
if err := w.WriteMsgWithContext(ctx, receipt); err != nil {
return fmt.Errorf("send receipt to peer %s: %w", p.Address.String(), err)
}
return debit.Apply()
}
// PushChunkToClosest sends chunk to the closest peer by opening ... | warmedUp | identifier_name | |
pushsync.go | WithinStorageRadius(swarm.Address) bool
StorageRadius() uint8
}
type PushSync struct {
address swarm.Address
nonce []byte
streamer p2p.StreamerDisconnecter
store Storer
topologyDriver topology.Driver
unwrap func(swarm.Chunk)
logger log.Logger
accounting accou... | { //no overdraft peers, we have depleted ALL peers
if inflight == 0 {
if ps.fullNode && ps.topologyDriver.IsReachable() {
if cac.Valid(ch) {
go ps.unwrap(ch)
}
return nil, topology.ErrWantSelf
}
ps.logger.Debug("no peers left", "chunk_address", ch.Address(), "error", ... | conditional_block | |
pushsync.go | }
return debit.Apply()
}
if ps.topologyDriver.IsReachable() && ps.store.IsWithinStorageRadius(chunkAddress) {
return store(ctx)
}
receipt, err := ps.pushToClosest(ctx, chunk, false)
if err != nil {
if errors.Is(err, topology.ErrWantSelf) {
return store(ctx)
}
ps.metrics.Forwarder.Inc()
return fm... | {
var status string
if err != nil {
status = "failure"
} else {
status = "success"
}
ps.metrics.PushToPeerTime.WithLabelValues(status).Observe(time.Since(t).Seconds())
} | identifier_body | |
pushsync.go | serve(time.Since(now).Seconds())
ps.metrics.TotalHandlerErrors.Inc()
_ = stream.Reset()
} else {
ps.metrics.TotalHandlerTime.WithLabelValues("success").Observe(time.Since(now).Seconds())
_ = stream.FullClose()
}
}()
var ch pb.Delivery
if err = r.ReadMsgWithContext(ctx, &ch); err != nil {
return fm... | receipt, err = ps.pushChunkToPeer(ctx, peer, ch)
if err != nil {
return
}
| random_line_split | |
trickledag.go | Depth` is -1,
// initial call from `Layout`) add `depthRepeat` sub-graphs of that depth.
for depth := 1; maxDepth == -1 || depth < maxDepth; depth++ {
if db.Done() {
break
// No more data, stop here, posterior append calls will figure out
// where we left off.
}
for repeatIndex := 0; repeatIndex < dep... | {
return errors.New("expected direct block")
} | conditional_block | |
trickledag.go | *h.DagBuilderHelper) (ipld.Node, error) |
// fillTrickleRec creates a trickle (sub-)tree with an optional maximum specified depth
// in the case maxDepth is greater than zero, or with unlimited depth otherwise
// (where the DAG builder will signal the end of data to end the function).
func fillTrickleRec(db *h.DagBuilderHelper, node *h.FSNodeOverDag, maxDept... | {
newRoot := db.NewFSNodeOverDag(ft.TFile)
root, _, err := fillTrickleRec(db, newRoot, -1)
if err != nil {
return nil, err
}
return root, db.Add(root)
} | identifier_body |
trickledag.go | err error) {
// Always do this, even in the base case
if err := db.FillNodeLayer(node); err != nil {
return nil, 0, err
}
// For each depth in [1, `maxDepth`) (or without limit if `maxDepth` is -1,
// initial call from `Layout`) add `depthRepeat` sub-graphs of that depth.
for depth := 1; maxDepth == -1 || dep... | }
// Recursive call for verifying the structure of a trickledag | random_line_split | |
trickledag.go | *h.DagBuilderHelper) (ipld.Node, error) {
newRoot := db.NewFSNodeOverDag(ft.TFile)
root, _, err := fillTrickleRec(db, newRoot, -1)
if err != nil {
return nil, err
}
return root, db.Add(root)
}
// fillTrickleRec creates a trickle (sub-)tree with an optional maximum specified depth
// in the case maxDepth is gr... | (ctx context.Context, fsn *h.FSNodeOverDag, depth int, repeatNumber int, db *h.DagBuilderHelper) error {
if fsn.NumChildren() <= db.Maxlinks() {
return nil
}
// TODO: Why do we need this check, didn't the caller already take
// care of this?
// Recursive step, grab last child
last := fsn.NumChildren() - 1
las... | appendFillLastChild | identifier_name |
main.rs | (all_hole_cards);
let outcomes = Arc::new(Mutex::new(HashMap::new()));
let mut children = Vec::with_capacity(num_threads as usize);
for thread_index in 0..num_threads {
let this_num_sims = get_num_sims_for_thread(total_num_sims, num_threads as i32, thread_index as i32);
let this_board_ref =... | let num_cards = chars.len() / 2;
let mut cards = Vec::with_capacity(num_cards);
for card_index in 0..num_cards {
let rank_index = card_index * 2;
let suit_index = rank_index + 1;
let rank_char = chars[rank_index];
let suit_char = chars[suit_index];
let rank = parse_ra... | let chars: Vec<char> = cards_string.chars().collect();
assert!(chars.len() % 2 == 0, "Odd numbers of characters, cannot be cards: {}", cards_string);
| random_line_split |
main.rs | _hole_cards);
let outcomes = Arc::new(Mutex::new(HashMap::new()));
let mut children = Vec::with_capacity(num_threads as usize);
for thread_index in 0..num_threads {
let this_num_sims = get_num_sims_for_thread(total_num_sims, num_threads as i32, thread_index as i32);
let this_board_ref = boa... |
fn get_num_threads(matches: &Matches) -> i32 {
get_numeric_arg(matches, NUM_THREADS_ARG, num_cpus::get() as i32)
}
fn get_numeric_arg(matches: &Matches, arg: &str, default: i32) -> i32 {
if !matches.opt_present(arg) {
return default;
}
let num_str = matches.opt_str(arg).unwrap();
let num_... | {
get_numeric_arg(matches, NUM_SIMS_ARG, DEFAULT_NUM_SIMS)
} | identifier_body |
main.rs | (all_hole_cards);
let outcomes = Arc::new(Mutex::new(HashMap::new()));
let mut children = Vec::with_capacity(num_threads as usize);
for thread_index in 0..num_threads {
let this_num_sims = get_num_sims_for_thread(total_num_sims, num_threads as i32, thread_index as i32);
let this_board_ref =... | () -> Options {
// Unfortunately, there doesn't seem to be a way to require that an option appears at least once.
let mut opts = Options::new();
opts.opt(HOLE_CARDS_ARG, "hole cards", "A single player's hole cards", "XxYy", HasArg::Yes, Occur::Multi);
opts.opt(NUM_SIMS_ARG, "number of simulations", "The... | create_opts | identifier_name |
main.rs | else {
get_num_sims(&arg_matches)
};
let all_hole_cards = get_hole_cards(&arg_matches);
let num_threads = get_num_threads(&arg_matches);
println!("Simulating {} hands", total_num_sims);
if initial_board.len() > 0 {
println!("For board {:?}", initial_board);
}
println!("Usin... | {
println!("The given board is full, so there's no uncertainty.");
1
} | conditional_block | |
day18.rs | let right_index = explode_pair[1].0;
let right_value = &explode_pair[1].1;
if left_index + 1 != right_index {
panic!("Exploding pair don't have neighbouring indicies, the list is corrupted. List: {:?}", self.values);
}
let mut back_side = self.values.split_off(left_index);... | random_line_split | ||
day18.rs | (&self) -> Self {
Self {
value: self.value,
depth: self.depth + 1,
}
}
}
impl SnailfishNumber {
fn split(&mut self) -> bool {
if let Some(index_to_split) = self
.values
.iter()
.enumerate()
.filter(|(_, v)| v.value ... | deeper | identifier_name | |
day18.rs | )| v.value >= 10)
.map(|(i, _)| i)
.next()
{
let mut back_side = self.values.split_off(index_to_split);
let split_num = back_side.pop_front().unwrap();
let new_depth = split_num.depth + 1;
self.values.push_back(SnailfishValue {
... |
fn part2(input: &str) -> Result<u32, Box<dyn std::error::Error>> {
let sfns = input
.lines()
.map(|l| SnailfishNumber::from_str(l))
.collect::<Result<Vec<_>, _>>()?;
let pairs = sfns.into_iter().permutations(2);
let magnitudes = pairs.map(|p| (p[0].clone() + p[1].clone()).magnitude... | {
let mut sfns = input
.lines()
.map(|l| SnailfishNumber::from_str(l))
.collect::<Result<LinkedList<_>, _>>()?;
let first = sfns.pop_front().ok_or(format!("No numbers were parsed"))?;
let result = sfns.into_iter().fold(first, |a, x| a + x);
Ok(result.magnitude())
} | identifier_body |
stream.rs | &fields as *mut *mut _ as *mut *mut libc::c_void,
len as i64,
&added_id,
ptr::null_mut(),
);
added_id
}
}
// pub fn append(&self, fields: &mut Vec<Sds>) {
// unsafe {
// let mut added_id: *mut StreamID = ptr:... |
unsafe {
StreamID {
ms: u64::from_be(*(ptr as *mut [u8; 8] as *mut u64)),
seq: u64::from_be(*(ptr.offset(8) as *mut [u8; 8] as *mut u64)),
}
}
}
}
#[derive(Clone, Copy)]
#[repr(C)]
pub struct EntryPack;
//use std::fs::File;
//use std::io::p... | {
return StreamID::default();
} | conditional_block |
stream.rs | &fields as *mut *mut _ as *mut *mut libc::c_void,
len as i64,
&added_id,
ptr::null_mut(),
);
added_id
}
}
// pub fn append(&self, fields: &mut Vec<Sds>) {
// unsafe {
// let mut added_id: *mut StreamID = ptr:... | (&self) -> (*const u8, usize) {
(self as *const _ as *const u8, size_of::<StreamID>())
}
fn from_buf(ptr: *const u8, len: usize) -> StreamID {
if len != size_of::<StreamID>() {
return StreamID::default();
}
unsafe {
StreamID {
ms: u64::fr... | to_buf | identifier_name |
stream.rs | &fields as *mut *mut _ as *mut *mut libc::c_void,
len as i64,
&added_id,
ptr::null_mut(),
);
added_id
}
}
// pub fn append(&self, fields: &mut Vec<Sds>) {
// unsafe {
// let mut added_id: *mut ... | s: *const libc::c_char,
value: *mut libc::uint64_t,
) -> libc::c_int;
fn streamCreateNACK(
consumer: *mut streamConsumer
) -> *mut streamNACK;
fn streamFreeNACK(
na: *mut streamNACK
);
fn streamFreeConsumer(
sc: *mut streamConsumer
);
fn stream... | random_line_split | |
stream.rs | &fields as *mut *mut _ as *mut *mut libc::c_void,
len as i64,
&added_id,
ptr::null_mut(),
);
added_id
}
}
// pub fn append(&self, fields: &mut Vec<Sds>) {
// unsafe {
// let mut added_id: *mut StreamID = ptr:... |
fn deserialize() -> *mut listpack {
std::ptr::null_mut()
}
fn append(lp: *mut listpack, fields: &[Sds]) -> *mut listpack {
/* Create a new listpack and radix tree node if needed. Note that when
* a new listpack is created, we populate it with a "master entry". This
* is just a s... | {
// std::fs::File::open()
//
// let mut f = File::open(filename).expect("file not found");
//
// let mut contents = String::new();
// f.read_to_string(&mut contents)
// .expect("something went wrong reading the file");
} | identifier_body |
provision_utils.go | .Fields{
"Arguments": cmd.Args,
"Dir": cmd.Dir,
"Path": cmd.Path,
"Env": cmd.Env,
}).Debug("Running Command")
outputWriter := logger.Writer()
defer outputWriter.Close()
cmd.Stdout = outputWriter
cmd.Stderr = outputWriter
return cmd.Run()
}
func awsPrincipalToService(awsPrincipalName stri... | }).Debug("Inserting Actions for configuration ARN")
// Add this statement to the first policy, iff the actions are non-empty
if len(principalActions) > 0 {
rootPolicy := (*existingIAMRole.Policies)[0]
rootPolicyDoc := rootPolicy.PolicyDocument.(ArbitraryJSONObject)
rootPolicyStatements := rootPolicyDoc[... | {
for _, eachPolicy := range *existingIAMRole.Policies {
policyDoc := eachPolicy.PolicyDocument.(ArbitraryJSONObject)
statements := policyDoc["Statement"]
for _, eachStatement := range statements.([]spartaIAM.PolicyStatement) {
if sourceArn.String() == eachStatement.Resource.String() {
logger.WithF... | conditional_block |
provision_utils.go | Name := CloudFormationResourceName(resourceBaseName, string(keyName))
//////////////////////////////////////////////////////////////////////////////
// IAM Role definition
iamResourceName, err := ensureIAMRoleForCustomResource(customResourceTypeName,
sourceArn,
template,
logger)
if nil != err {
return "", ... | {
// The resource name is a :: delimited one, so let's sanitize that
// to make it a valid JS identifier
jsName := scriptExportNameForCustomResourceType(resourceName)
primaryEntry := fmt.Sprintf("exports[\"%s\"] = createForwarder(\"/%s\");\n",
jsName,
resourceName)
return primaryEntry
} | identifier_body | |
provision_utils.go | We'll walk the policies data in the next section
// to make sure that the sourceARN we have is in the list
statements := CommonIAMStatements.Core
iamPolicyList := gocf.IAMRolePolicyList{}
iamPolicyList = append(iamPolicyList,
gocf.IAMRolePolicy{
PolicyDocument: ArbitraryJSONObject{
"Version": "... | pyName := scriptExportNameForCustomResourceType(resourceName)
return pythonFunctionEntry(pyName, resourceName, logger)
}
func insertPythonProxyResources(serviceName string, | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.