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 |
|---|---|---|---|---|
ImpConcat-Recall.py | 1_img)
# Save the mask
output_name_mask = mask_fold + '%s_%s_brain.nii.gz' % (sub, ses)
'''hdr = avg_mask.header # get a handle for the .nii file's header
hdr.set_zooms((dimsize[0], dimsize[1], dimsize[2]))
nib.save(avg_mask, output_name_mask)'''
# In[17]:
def mod_smooth(in_file, mask_file, fwhm, smooth_type):
... | avg_mask.shape | random_line_split | |
ImpConcat-Recall.py | desired confounds from the confounds_regressors.tsv file from fmriprep, trim the columns corresponding to trimmed volumes, and save as a .txt file.
starttime = time.time()
confounds=[]
confounds_all=[]
mc_all=[]
ntr=[]
ntr=np.zeros((n_runs_recall,1))
for r in range(firstrun,lastrun+1):
fname='_ses-01_task-recall... | (in_file, mask_file, fwhm, smooth_type):
import nipype.interfaces.fsl as fsl
import nipype.interfaces.freesurfer as fs
import os
if smooth_type == 'susan':
if fwhm == 0:
return in_file
smooth = create_susan_smooth()
smooth.base_dir = out_dir#os.getcwd()
smooth... | mod_smooth | identifier_name |
ImpConcat-Recall.py | desired confounds from the confounds_regressors.tsv file from fmriprep, trim the columns corresponding to trimmed volumes, and save as a .txt file.
starttime = time.time()
confounds=[]
confounds_all=[]
mc_all=[]
ntr=[]
ntr=np.zeros((n_runs_recall,1))
for r in range(firstrun,lastrun+1):
fname='_ses-01_task-recall... |
else:
confounds_all=np.vstack([confounds_all,confounds_selected])
print(confounds_selected.shape[0])
print(ntr)
print(sum(ntr[0]))
# In[15]:
mask_imgs=[]
for run in range(firstrun,lastrun+1):
mask_name = ses1_dir + sub + '_ses-01_task-recall_run-0%i_space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz'... | confounds_all=confounds_selected | conditional_block |
test_unihan.py | zip_has_files(['Unihan_Readings.txt'], mock_zip)
assert not zip_has_files(['Unihan_Cats.txt'], mock_zip)
def test_has_valid_zip(tmpdir, mock_zip):
if os.path.isfile(UNIHAN_ZIP_PATH):
assert process.has_valid_zip(UNIHAN_ZIP_PATH)
else:
assert not process.has_valid_zip(UNIHAN_ZIP_PATH)
... |
assert [] == not_in_columns, "normalize filters columns not specified."
assert set(in_columns).issubset(
set(columns)
), "normalize returns correct columns specified + ucn and char."
def test_normalize_simple_data_format(fixture_dir):
"""normalize turns data into simple data format (SDF)."""... | in_columns.append(v) | conditional_block |
test_unihan.py | zip_has_files(['Unihan_Readings.txt'], mock_zip)
assert not zip_has_files(['Unihan_Cats.txt'], mock_zip)
def test_has_valid_zip(tmpdir, mock_zip):
if os.path.isfile(UNIHAN_ZIP_PATH):
assert process.has_valid_zip(UNIHAN_ZIP_PATH)
else:
assert not process.has_valid_zip(UNIHAN_ZIP_PATH)
... | (normalized_data, columns):
items = normalized_data
in_columns = ['kDefinition', 'kCantonese']
for v in items:
assert set(columns) == set(v.keys())
items = process.listify(items, in_columns)
not_in_columns = []
# columns not selected in normalize must not be in result.
for v in i... | test_normalize_only_output_requested_columns | identifier_name |
test_unihan.py | assert zip_has_files(['Unihan_Readings.txt'], mock_zip)
assert not zip_has_files(['Unihan_Cats.txt'], mock_zip)
def test_has_valid_zip(tmpdir, mock_zip):
if os.path.isfile(UNIHAN_ZIP_PATH):
assert process.has_valid_zip(UNIHAN_ZIP_PATH)
else:
assert not process.has_valid_zip(UNIHAN_ZIP_PA... | {
'fields': ['kDefinition'],
'zip_path': str(dest_path),
'work_dir': str(mock_test_dir.join('downloads')),
'destination': str(data_path.join('unihan.csv')),
},
)
)
p.download(urlretrieve_fn=urlretrieve)
assert os... | mock_zip_file.copy(dest_path)
p = Packager(
merge_dict(
test_options.copy, | random_line_split |
test_unihan.py | zip_has_files(['Unihan_Readings.txt'], mock_zip)
assert not zip_has_files(['Unihan_Cats.txt'], mock_zip)
def test_has_valid_zip(tmpdir, mock_zip):
if os.path.isfile(UNIHAN_ZIP_PATH):
assert process.has_valid_zip(UNIHAN_ZIP_PATH)
else:
assert not process.has_valid_zip(UNIHAN_ZIP_PATH)
... | p.export()
assert str(data_path.join('unihan.json')) == p.options['destination']
assert os.path.exists(p.options['destination'])
def test_extract_zip(mock_zip, mock_zip_file, tmpdir):
zf = process.extract_zip(str(mock_zip_file), str(tmpdir))
assert len(zf.infolist()) == 1
assert zf.infolist(... | data_path = tmpdir.join('data')
dest_path = data_path.join('data', 'hey.zip')
def urlretrieve(url, filename, url_retrieve, reporthook=None):
mock_zip_file.copy(dest_path)
p = Packager(
merge_dict(
test_options.copy,
{
'fields': ['kDefinition'],
... | identifier_body |
bg.rs | (&mut self) {
self.valid = false;
}
}
impl BgCache {
/// Invalidates the BG cache of all layers
fn invalidate_all(&mut self) {
self.layers[0].valid = false;
self.layers[1].valid = false;
self.layers[2].valid = false;
self.layers[3].valid = false;
}
}
/// Collect... | invalidate | identifier_name | |
bg.rs | 7 256 - - -
/// 7EXTBG 256 128 - -
/// ```
fn color_bits_for_bg(&self, bg: u8) -> u8 {
match (self.bg_mode(), bg) {
(0, _) => 2,
(1, 1) |
(1, 2) => 4,
(1, 3) => 2,
(2, _) => 4,
(3, 1) => 8,
(3, 2) => ... | random_line_split | ||
builtin_func.go | &BuiltinFn{"print", wrapFn(print)},
&BuiltinFn{"println", wrapFn(println)},
&BuiltinFn{"pprint", pprint},
&BuiltinFn{"into-lines", wrapFn(intoLines)},
&BuiltinFn{"from-lines", wrapFn(fromLines)},
&BuiltinFn{"rat", wrapFn(ratFn)},
&BuiltinFn{"put", put},
&BuiltinFn{"put-all", wrapFn(putAll)},
&Built... | &BuiltinFn{":", nop},
&BuiltinFn{"true", nop},
| random_line_split | |
builtin_func.go | +b.Name] = NewRoVariable(b)
}
}
var (
ErrArgs = errors.New("args error")
ErrInput = errors.New("input error")
ErrStoreNotConnected = errors.New("store not connected")
ErrNoMatchingDir = errors.New("no matching directory")
ErrNotInSameGroup = errors.New("not in the same process gro... |
throw(err)
}
out <- FromJSONInterface(v)
}
}
// each takes a single closure and applies it to all input values.
func each(ec *EvalCtx, f FnValue) {
in := ec.ports[0].Chan
in:
for v := range in {
// NOTE We don't have the position range of the closure in the source.
// Ideally, it should be kept in the C... | {
return
} | conditional_block |
builtin_func.go | for _, field := range eawkWordSep.Split(strings.Trim(line, " \t"), -1) {
args = append(args, String(field))
}
newec := ec.fork("fn of eawk")
ex := newec.PCall(f, args)
ClosePorts(newec.ports)
switch ex {
case nil, Continue:
// nop
case Break:
break in
default:
throw(ex)
}
}
}
func cd... | {
out := ec.ports[1].File
// XXX dup with main.go
buf := make([]byte, 1024)
for runtime.Stack(buf, true) == cap(buf) {
buf = make([]byte, cap(buf)*2)
}
out.Write(buf)
} | identifier_body | |
builtin_func.go | +b.Name] = NewRoVariable(b)
}
}
var (
ErrArgs = errors.New("args error")
ErrInput = errors.New("input error")
ErrStoreNotConnected = errors.New("store not connected")
ErrNoMatchingDir = errors.New("no matching directory")
ErrNotInSameGroup = errors.New("not in the same process gro... | (ec *EvalCtx, args []Value) {
var dir string
if len(args) == 0 {
dir = mustGetHome("")
} else if len(args) == 1 {
dir = ToString(args[0])
} else {
throw(ErrArgs)
}
cdInner(dir, ec)
}
func cdInner(dir string, ec *EvalCtx) {
err := os.Chdir(dir)
if err != nil {
throw(err)
}
if ec.store != nil {
// X... | cd | identifier_name |
settings.py | .environ.get('WFM_DB_PASSWORD', 'wfm'),
},
'userlogs': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'HOST': os.environ.get('WFM_DB_HOST', '127.0.0.1'),
'NAME': 'wfm_log',
'USER': os.environ.get('WFM_DB_USER', 'wfm'),
'PASSWORD': os.environ.get('WFM_DB_PASSWORD', ... | EAL_IP',)
| identifier_body | |
settings.py | ROOT_URLCONF = 'wfm.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
... | 'handlers': ['db', 'console'], | random_line_split | |
settings.py | django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'apps.outsource',
'apps.claims',
'apps.shifts',
'apps.employees',
'apps.remotes',
'apps.notifications',
'apps.l... | похоже, это всё больше не работает, потому что вместо request'а тут какой-то socket
request = getattr(record, 'request', None)
if request and hasattr(request, 'user'): # user
record.user = request.user
else:
record.user = '--'
if request and hasattr(request, 'M... | identifier_name | |
settings.py | ations',
'apps.easy_log',
'compressor',
'social_django',
'axes',
'saml',
'applogs',
'xlsexport',
'wfm_admin',
'rangefilter',
]
AUTHENTICATION_BACKENDS = (
#'django.contrib.auth.backends.ModelBackend',
'apps.authutils.backends.EmailLoginBackend',
'apps.authutils.backend... | name)s.%(module) | conditional_block | |
chainmaker_yaml_types.go | CommitWithoutPublish bool `yaml:"is_commit_without_publish"` //if the node committing block without publishing, TRUE;else, FALSE
IsPrevoteInvalid bool `yaml:"is_prevote_invalid"` //simulate a node which sends an invalid prevote(hash=nil)
IsPrecommitInvalid bool `yaml:"is_precommit_invalid"` //si... |
type redisConfig struct { | random_line_split | |
chainmaker_yaml_types.go | `yaml:"root"`
}
type rpcConfig struct {
Provider string `yaml:"provider"`
Port int `yaml:"port"`
TLSConfig tlsConfig `yaml:"tls"`
RateLimitConfig rateLimitConfig `yaml... | fig.SqlDbConfig.DbPrefix = config.DbPrefix
}
if config.ResultDbConfig != nil && config.ResultDbConfig.SqlDbConfig != nil && config.ResultDbConfig.SqlDbConfig.DbPrefix == "" {
config.ResultDbConfig.SqlDbConfig.DbPrefix = config.DbPrefix
}
if config.ContractEventDbConfig != nil && config.ContractEventDbConfig.... | .HistoryDbConfig.SqlDbConfig.DbPrefix == "" {
config.HistoryDbCon | conditional_block |
chainmaker_yaml_types.go | Config.SqlDbConfig.DbPrefix == "" {
config.BlockDbConfig.SqlDbConfig.DbPrefix = config.DbPrefix
}
if config.StateDbConfig != nil && config.StateDbConfig.SqlDbConfig != nil && config.StateDbConfig.SqlDbConfig.DbPrefix == "" {
config.StateDbConfig.SqlDbConfig.DbPrefix = config.DbPrefix
}
if config.HistoryDb... | list
fun | identifier_name | |
chainmaker_yaml_types.go | `yaml:"root"`
}
type rpcConfig struct {
Provider string `yaml:"provider"`
Port int `yaml:"port"`
TLSConfig tlsConfig `yaml:"tls"`
RateLimitConfig rateLimitConfig `yaml... | .setDefault()
return config.ContractEventDbConfig
}
func (config *StorageConfig) GetDefaultDBConfig() *DbConfig {
lconfig := &LevelDbConfig{
StorePath: config.StorePath,
WriteBufferSize: config.WriteBufferSize,
BloomFilterBits: config.BloomFilterBits,
BlockWriteBufferSize: config.WriteBuf... | GetContractEventDbConfig() *DbConfig {
if config.ContractEventDbConfig == nil {
return config.GetDefaultDBConfig()
}
config | identifier_body |
topology.rs | - start);
let read = self.get_in_seg(seg, start, end)?;
for e in read.iter() {
tmp.push(e);
}
seg += 1;
start = 0;
left -= read.len();
}
Ok(tmp)
}
#[inline]
pub fn len(&self) -> usize {
self.le... | {
self.neighbors.len()
} | identifier_body | |
topology.rs | self.current.len() == self.seg_size {
self.segments.push(::std::mem::replace(&mut self.current,
Vec::with_capacity(self.seg_size)));
}
self.len += 1;
}
pub fn get(&self, offset: usize) -> Option<&T> {
let seg = offset >> se... | (id: u64) -> Self {
Vertex {
id,
#[cfg(feature = "padding")]
padding_1: [0; 8],
#[cfg(feature = "padding")]
padding_2: [0; 7]
}
}
}
pub struct NeighborIter {
cursor: usize,
len: usize,
inner: Arc<Vec<u64>>
}
impl NeighborIter ... | new | identifier_name |
topology.rs | self.current.len() == self.seg_size {
self.segments.push(::std::mem::replace(&mut self.current,
Vec::with_capacity(self.seg_size)));
}
self.len += 1;
}
pub fn get(&self, offset: usize) -> Option<&T> {
let seg = offset >> se... | if peers == 1 || (d % peers as u64) as u32 == partition {
let n = neighbors.entry(*d).or_insert(Vec::new());
if !directed {
n.push(*s);
count += 1;
}
}
}
let mut arc_neighbors = HashMap::new()... | count += 1;
}
| random_line_split |
lib.rs | (feature = "ink-as-dependency"))]
use ::ink_storage::{
collections::HashMap as StorageHashMap,
lazy::Lazy,
traits::SpreadLayout,
};
pub const TIMELOCK_ADMIN_ROLE: RoleId =
RoleId::new(metis_lang::hash!(TIMELOCK_ADMIN_ROLE));
pub const PROPOSER_ROLE: RoleId = RoleId::new(metis_lang::hash!(PROPOSER_ROLE)... |
impl<E> Default for Data<E>
where
E: Env,
{
fn default() -> Self {
Self {
min_delay: Lazy::new(E::Timestamp::from(1_u8)),
timestamps: StorageHashMap::default(),
}
}
}
impl<E: Env> Data<E> {}
/// The `EventEmit` impl the event emit api for component.
pub trait Event... | pub fn new() -> Self {
Self::default()
}
} | random_line_split |
lib.rs | Self {
Self {
min_delay: Lazy::new(E::Timestamp::from(1_u8)),
timestamps: StorageHashMap::default(),
}
}
}
impl<E: Env> Data<E> {}
/// The `EventEmit` impl the event emit api for component.
pub trait EventEmit<E: Env> {
/// Emitted when a call is scheduled as part of o... | {
assert!(
self.is_operation_ready(&id),
"TimelockController: operation is not ready"
);
Storage::<E, Data<E>>::get_mut(self)
.timestamps
.insert(id, E::Timestamp::from(_DONE_TIMESTAMP));
} | identifier_body | |
lib.rs | (feature = "ink-as-dependency"))]
use ::ink_storage::{
collections::HashMap as StorageHashMap,
lazy::Lazy,
traits::SpreadLayout,
};
pub const TIMELOCK_ADMIN_ROLE: RoleId =
RoleId::new(metis_lang::hash!(TIMELOCK_ADMIN_ROLE));
pub const PROPOSER_ROLE: RoleId = RoleId::new(metis_lang::hash!(PROPOSER_ROLE)... | (&self, id: &[u8; 32]) -> bool {
self.get_timestamp(id) > E::Timestamp::from(_DONE_TIMESTAMP)
}
/// Returns whether an operation is ready or not.
fn is_operation_ready(&self, id: &[u8; 32]) -> bool {
let timestamp = self.get_timestamp(id);
timestamp > E::Timestamp::from(_DONE_TIMEST... | is_operation_pending | identifier_name |
scheduling.rs | {
TaskSchedule(T),
KeepAlive,
}
// The valid duration is limited by this upper bound that is
// reserved for the keep alive token!
// TODO: The maximum acceptable value of 795 days that does
// not cause an internal panic has been discovered experimentally.
// No references about this limit can be found in th... | handle_command | identifier_name | |
scheduling.rs | tokio::timer::{
delay_queue::{Expired, Key as DelayQueueKey},
DelayQueue,
};
enum DelayQueueItem<T> {
TaskSchedule(T),
KeepAlive,
}
// The valid duration is limited by this upper bound that is
// reserved for the keep alive token!
// TODO: The maximum acceptable value of 795 days that does
// not cau... | impl<T> TaskSchedulingActor<T>
where
T: TaskSchedule + Send + std::fmt::Debug,
{
pub fn create(
task_scheduler: Box<dyn TaskScheduler<TaskSchedule = T> + Send>,
) -> (
impl Future<Item = (), Error = ()>,
TaskSchedulingActionSender<T>,
TaskSchedulingNotificationReceiver,
)... | scheduled_tasks: ScheduledTasks<T>,
}
| random_line_split |
scheduling.rs | tokio::timer::{
delay_queue::{Expired, Key as DelayQueueKey},
DelayQueue,
};
enum DelayQueueItem<T> {
TaskSchedule(T),
KeepAlive,
}
// The valid duration is limited by this upper bound that is
// reserved for the keep alive token!
// TODO: The maximum acceptable value of 795 days that does
// not cau... |
}
impl<T> Stream for ScheduledTasks<T> {
type Item = <DelayQueue<DelayQueueItem<T>> as Stream>::Item;
type Error = <DelayQueue<DelayQueueItem<T>> as Stream>::Error;
fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
self.lock_inner().poll()
}
}
#[derive(Debug, Clone, Copy... | {
ScheduledTasks(self.0.clone())
} | identifier_body |
messenger.ts | callback to all events fired.
*/
on(name, callback, context?) : this {
return <this>internalOn(this, name, callback, context);
}
/** Remove one or many callbacks. If `context` is null, removes all
* callbacks with that function. If `callback` is null, removes all
* callbacks for th... | {
const handler = handlers[j];
if (
callback && callback !== handler.callback &&
callback !== handler.callback._callback ||
context && context !== handler.context
) {
remaining.push(handler);
} else {
... | conditional_block | |
messenger.ts | protoProps;
if( localEvents || _localEvents ){
const eventsMap = new EventMap( this.prototype._localEvents );
localEvents && eventsMap.addEventsMap( localEvents );
_localEvents && eventsMap.merge( _localEvents );
spec._localEvents = eventsMap;... | {
if (!events) return;
let i = 0, listening;
const context = options.context, listeners = options.listeners;
// Delete all events listeners and "drop" events.
if (!name && !callback && !context) {
const ids = keys(listeners);
for (; i < ids.length; i++) {
listening = li... | identifier_body | |
messenger.ts | : MessengerDefinition, statics? : {} ) => Mixins.MixableConstructor< Messenger >
static predefine : () => Mixins.MixableConstructor< Messenger >
/** @hidden */
_events : _eventsApi.EventsSubscription = void 0;
/** @hidden */
_listeners : Listeners = void 0
/** @hidden */
_listeningTo : L... | OffOptions | identifier_name | |
messenger.ts | | {} )[] ) => Mixins.MixableConstructor< Messenger >
static mixinRules : ( mixinRules : Mixins.MixinRules ) => Mixins.MixableConstructor< Messenger >
static mixTo : ( ...args : Mixins.Constructor<any>[] ) => Mixins.MixableConstructor< Messenger >
static extend : (spec? : MessengerDefinition, statics? : {} ... |
/** @hidden */
class ListeningTo {
count : number = 0
constructor( public obj, public objId, public id, public listeningTo ){}
}
/** @hidden */
export interface ListeningToMap {
[ id : string ] : ListeningTo
}
/** @hidden */
export interface Listeners {
[ id : string ] : Messenger
}
// Guard the `li... | }; | random_line_split |
Client_V1.1.py | _GRAY_MEDIA_STRING2 = 6
CARD_TYPE_W50_GREEN_MEDIA_STRING2 = 7
CARD_TYPE_W50_BLUE_MEDIA_STRING2 = 8
CARD_TYPE_W50_RED_MEDIA_STRING2 = 9
CARD_TYPE_W50_AMBER_MEDIA_STRING2 = 10
CARD_TYPE_W50_GREEN_TITLE_STRING4 = 11
CARD_TYPE_W50_GREEN_TITLE_STRING3 = 12
CARD_TYPE_W50_USERCOLOR_MEDIA_STRING2 = 13
class screen_ui_... | (self):
global card_type
if card_type == 5 or card_type == 13:
card_bgcolor = int(input('\nEnter Background Color: '))
#reads background color from user
#assumed to be a integer value
print('\nBackground color set to: {}\n'.format(card_bgcolor))
else:
print('\nBackground color set b... | BackGround_Color | identifier_name |
Client_V1.1.py | 0_GRAY_MEDIA_STRING2 = 6
CARD_TYPE_W50_GREEN_MEDIA_STRING2 = 7
CARD_TYPE_W50_BLUE_MEDIA_STRING2 = 8
CARD_TYPE_W50_RED_MEDIA_STRING2 = 9
CARD_TYPE_W50_AMBER_MEDIA_STRING2 = 10
CARD_TYPE_W50_GREEN_TITLE_STRING4 = 11
CARD_TYPE_W50_GREEN_TITLE_STRING3 = 12
CARD_TYPE_W50_USERCOLOR_MEDIA_STRING2 = 13
class screen_ui... | print('Input value does not match any defined card types')
exit()
elif screen_type == 1:
i = 6 #to display count of ENUM listing
for types in card_type_t_50:
print('{}'.format(i), types)
i += 1
card_type = int(input('Enter ENUM index (6-13)\nSelect Card type: '))
#re... | except: | random_line_split |
Client_V1.1.py | _GRAY_MEDIA_STRING2 = 6
CARD_TYPE_W50_GREEN_MEDIA_STRING2 = 7
CARD_TYPE_W50_BLUE_MEDIA_STRING2 = 8
CARD_TYPE_W50_RED_MEDIA_STRING2 = 9
CARD_TYPE_W50_AMBER_MEDIA_STRING2 = 10
CARD_TYPE_W50_GREEN_TITLE_STRING4 = 11
CARD_TYPE_W50_GREEN_TITLE_STRING3 = 12
CARD_TYPE_W50_USERCOLOR_MEDIA_STRING2 = 13
class screen_ui_... |
"""
Child-Method 4
This Shows or hides the Flipper
"""
#parameter 4
flipper_visibility = -1
def FlipperVisibility(self):
global screen_type
if screen_type == 1:
choice = int(input('FLIPPER Visibility (0=HIDE/1=SHOW): '))
#reads users choice to either show or hide flipper.
... | global slot_index
global screen_type
#parameter 3
if screen_type == 1:
slot_index = int(input('Enter the slot index (0=LEFT/1=RIGHT): '))
print('Slot index set as: {}\n'.format(slot_index)) | identifier_body |
Client_V1.1.py | _GRAY_MEDIA_STRING2 = 6
CARD_TYPE_W50_GREEN_MEDIA_STRING2 = 7
CARD_TYPE_W50_BLUE_MEDIA_STRING2 = 8
CARD_TYPE_W50_RED_MEDIA_STRING2 = 9
CARD_TYPE_W50_AMBER_MEDIA_STRING2 = 10
CARD_TYPE_W50_GREEN_TITLE_STRING4 = 11
CARD_TYPE_W50_GREEN_TITLE_STRING3 = 12
CARD_TYPE_W50_USERCOLOR_MEDIA_STRING2 = 13
class screen_ui_... |
"""
Child-Method 4
This Shows or hides the Flipper
"""
#parameter 4
flipper_visibility = -1
def FlipperVisibility(self):
global screen_type
if screen_type == 1:
choice = int(input('FLIPPER Visibility (0=HIDE/1=SHOW): '))
#reads users choice to either show or hide flipper.
... | slot_index = int(input('Enter the slot index (0=LEFT/1=RIGHT): '))
print('Slot index set as: {}\n'.format(slot_index)) | conditional_block |
VIEW3D_MT_armature_context_menu.py | =True)
row.label(text="New Name")
row.prop(self, 'new_name', text="")
row.prop(self, 'name_sep', text="")
row = box.row(align=True)
row.label(text="Numbering Starts from")
row.prop(self, 'start_from', text="")
def execute(self, context):
obj = context.active_object
if self.use_rename:
bpy.ops... | lace selected bones' names by using regular expression"
bl_options = {'REGISTER', 'UNDO'}
isAll : BoolProperty(name="Apply to All Bones", default=False)
pattern : StringProperty(name="Target text", default="^")
repl : StringProperty(name="New Text", default="")
@classmethod
def poll(cls, context):
if context.... | ion"
bl_description = "Rep | identifier_name |
VIEW3D_MT_armature_context_menu.py | =True)
row.label(text="New Name")
row.prop(self, 'new_name', text="")
row.prop(self, 'name_sep', text="")
row = box.row(align=True)
row.label(text="Numbering Starts from")
row.prop(self, 'start_from', text="")
def execute(self, context):
obj = context.active_object
if self.use_rename:
bpy.ops... | ame', expand=True)
box = self.layout.box()
if self.use_rename == 'True':
row = box.row(align=True)
row.label(text="Use Root Bones' Names as New Names")
row.prop(self, 'use_root', text="")
row = box.split(factor=0.4, align=True)
row.label(text="Bones' Order")
row.prop(self, 'order', text="")
row... |
row = self.layout.row()
row.use_property_split = True
row.prop(self, 'threshold')
self.layout.prop(self, 'use_ren | identifier_body |
VIEW3D_MT_armature_context_menu.py | align=True)
row.label(text="New Name")
row.prop(self, 'new_name', text="")
row.prop(self, 'name_sep', text="")
row = box.row(align=True)
row.label(text="Numbering Starts from")
row.prop(self, 'start_from', text="")
def execute(self, context):
obj = context.active_object
if self.use_rename:
bp... | new_names = [self.new_name] + [f"{name_head}{num+1:03}" for num in range(len(selectedBones)-1)]
elif self.start_from == 'ZERO':
new_names = [f"{name_head}{num:03}" for num in range(len(selectedBones))]
elif self.start_from == 'ONE':
new_names = [f"{name_head}{num+1:03}" for num in range(len(selectedBo... | if self.use_rename:
name_head = f"{self.new_name}{self.name_sep}"
if self.start_from == 'NO': | random_line_split |
VIEW3D_MT_armature_context_menu.py | self.use_rename:
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')# 直前に行った名前変更が obj.data.bones に反映されていない場合への対処
preCursorCo = context.scene.cursor.location[:]
prePivotPoint = context.scene.tool_settings.transform_pivot_point
preUseMirror = context.object.data.use_mirror_x
context... | CT')
bpy.ops.object.mode_set(mode='OBJECT')
thresho | conditional_block | |
handler.rs | HandlerUpgrErr,
};
use std::{error::Error, io, fmt, num::NonZeroU32, time::Duration};
use std::collections::VecDeque;
use tokio_io::{AsyncRead, AsyncWrite};
use wasm_timer::{Delay, Instant};
use void::Void;
/// The configuration for outbound pings.
#[derive(Clone, Debug)]
pub struct PingConfig {
/// The timeout of... | KeepAlive::Yes
} else {
KeepAlive::No
}
}
fn poll(&mut self) -> Poll<ProtocolsHandlerEvent<protocol::Ping, (), PingResult>, Self::Error> {
if let Some(result) = self.pending_results.pop_back() {
if let Ok(PingSuccess::Ping { .. }) = result {
... | random_line_split | |
handler.rs | self
}
/// Sets the ping interval.
pub fn with_interval(mut self, d: Duration) -> Self {
self.interval = d;
self
}
/// Sets the maximum number of consecutive ping failures upon which the remote
/// peer is considered unreachable and the connection closed.
pub fn wit... | {} | conditional_block | |
handler.rs | HandlerUpgrErr,
};
use std::{error::Error, io, fmt, num::NonZeroU32, time::Duration};
use std::collections::VecDeque;
use tokio_io::{AsyncRead, AsyncWrite};
use wasm_timer::{Delay, Instant};
use void::Void;
/// The configuration for outbound pings.
#[derive(Clone, Debug)]
pub struct PingConfig {
/// The timeout of... | (config: PingConfig) -> Self {
PingHandler {
config,
next_ping: Delay::new(Instant::now()),
pending_results: VecDeque::with_capacity(2),
failures: 0,
_marker: std::marker::PhantomData
}
}
}
impl<TSubstream> ProtocolsHandler for PingHandler... | new | identifier_name |
handler.rs | UpgrErr,
};
use std::{error::Error, io, fmt, num::NonZeroU32, time::Duration};
use std::collections::VecDeque;
use tokio_io::{AsyncRead, AsyncWrite};
use wasm_timer::{Delay, Instant};
use void::Void;
/// The configuration for outbound pings.
#[derive(Clone, Debug)]
pub struct PingConfig {
/// The timeout of an out... |
fn inject_fully_negotiated_outbound(&mut self, rtt: Duration, _info: ()) {
// A ping initiated by the local peer was answered by the remote.
self.pending_results.push_front(Ok(PingSuccess::Ping { rtt }));
}
fn inject_event(&mut self, _: Void) {}
fn inject_dial_upgrade_error(&mut self... | {
// A ping from a remote peer has been answered.
self.pending_results.push_front(Ok(PingSuccess::Pong));
} | identifier_body |
dict.rs | -8.
/// The iterator element type is `(&str, &str)`.
fn iter(&self) -> Iter {
Iter {
inner: self.iter_cstr(),
}
}
/// An iterator over all keys that are valid utf-8.
/// The iterator element type is &str.
fn keys(&self) -> Keys {
Keys {
inner: sel... | () {
let (_strings, _items, raw) = make_raw_dict(2);
let dict = unsafe { ForeignDict::from_ptr(&raw) };
let mut iter = dict.iter_cstr();
assert_eq!(
(
| test_iter_cstr | identifier_name |
dict.rs | 8.
/// The iterator element type is `(&str, &str)`.
fn iter(&self) -> Iter {
Iter {
inner: self.iter_cstr(),
}
}
/// An iterator over all keys that are valid utf-8.
/// The iterator element type is &str.
fn keys(&self) -> Keys {
Keys {
inner: self... |
}
fn size_hint(&self) -> (usize, Option<usize>) {
let bound: usize = unsafe { self.next.offset_from(self.end) as usize };
// We know the exact value, so lower bound and upper bound are the same.
(bound, Some(bound))
}
}
pub struct Iter<'a> {
inner: CIter<'a>,
}
impl<'a> Iter... | {
None
} | conditional_block |
dict.rs | /pipewire-rs/-/merge_requests/12#note_695914.
fn get(&self, key: &str) -> Option<&str> {
self.iter().find(|(k, _)| *k == key).map(|(_, v)| v)
}
}
pub trait WritableDict {
/// Insert the key-value pair, overwriting any old value.
fn insert<T: Into<Vec<u8>>>(&mut self, key: T, value: T);
///... | {
let (_strings, _items, raw) = make_raw_dict(1);
let dict = unsafe { ForeignDict::from_ptr(&raw) };
assert_eq!(r#"{"K0": "V0"}"#, &format!("{:?}", dict))
} | identifier_body | |
dict.rs | -8.
/// The iterator element type is `(&str, &str)`.
fn iter(&self) -> Iter {
Iter {
inner: self.iter_cstr(),
}
}
/// An iterator over all keys that are valid utf-8.
/// The iterator element type is &str.
fn keys(&self) -> Keys {
Keys {
inner: sel... | fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the bitflags that are set for the dict.
fn flags(&self) -> Flags {
Flags::from_bits_truncate(unsafe { (*self.get_dict_ptr()).flags })
}
/// Get the value associated with the provided key.
///
/// If the dict doe... | random_line_split | |
nodekeeper.go | syncHash() (hash []byte, unsyncCount int, err error)
// GetUnsync gets the local unsync list (excluding other nodes unsync lists).
GetUnsync() []*core.ActiveNode
// SetPulse sets internal PulseNumber to number.
SetPulse(number core.PulseNumber)
// Sync initiate transferring unsync -> sync, sync -> active. If appro... | {
nk.cacheUnsyncCalc = nil
nk.cacheUnsyncSize = 0
} | identifier_body | |
nodekeeper.go | get active node by its reference. Returns nil if node is not found.
GetActiveNode(ref core.RecordRef) *core.ActiveNode
// GetActiveNodes get active nodes.
GetActiveNodes() []*core.ActiveNode
// AddActiveNodes set active nodes.
AddActiveNodes([]*core.ActiveNode)
// GetUnsyncHash get hash computed based on the lis... |
nk.unsync = append(nk.unsync, node)
tm := time.Now().Add(nk.timeout)
nk.unsyncTimeout = append(nk.unsyncTimeout, tm)
return nil
}
func (nk *nodekeeper) AddUnsyncGossip(nodes []*core.ActiveNode) error {
nk.unsyncLock.Lock()
defer nk.unsyncLock.Unlock()
if nk.state != awaitUnsync {
return errors.New("Cannot ... | {
return errors.Wrap(err, "Error adding local unsync node")
} | conditional_block |
nodekeeper.go | get active node by its reference. Returns nil if node is not found.
GetActiveNode(ref core.RecordRef) *core.ActiveNode
// GetActiveNodes get active nodes.
GetActiveNodes() []*core.ActiveNode
// AddActiveNodes set active nodes.
AddActiveNodes([]*core.ActiveNode)
// GetUnsyncHash get hash computed based on the lis... | (nodes []*core.ActiveNode) error {
for _, node := range nodes {
if node.PulseNum != nk.pulse {
return errors.Errorf("Node ID:%s pulse:%d is not equal to NodeKeeper current pulse:%d",
node.NodeID.String(), node.PulseNum, nk.pulse)
}
}
return nil
}
func (nk *nodekeeper) checkReference(nodes []*core.ActiveN... | checkPulse | identifier_name |
nodekeeper.go | Node get active node by its reference. Returns nil if node is not found.
GetActiveNode(ref core.RecordRef) *core.ActiveNode
// GetActiveNodes get active nodes.
GetActiveNodes() []*core.ActiveNode
// AddActiveNodes set active nodes.
AddActiveNodes([]*core.ActiveNode)
// GetUnsyncHash get hash computed based on the... | // Sync initiate transferring unsync -> sync, sync -> active. If approved is false, unsync is not transferred to sync.
Sync(approved bool)
// AddUnsync add unsync node to the local unsync list.
// Returns error if node's PulseNumber is not equal to the NodeKeeper internal PulseNumber.
AddUnsync(*core.ActiveNode) e... | // SetPulse sets internal PulseNumber to number.
SetPulse(number core.PulseNumber) | random_line_split |
curiosity-rl.py | =advcore,
args=args,
learning_rate=1e-4,
batch_normalization=bnorm)
elif args.train in ['loco_overfit']:
assert args.localcluster_nsampler <= 0, 'loco_overfit does not support MP training'
TRAINER = loco_overfit.LocoOverfitter
trainer = TRAINER... | session_config = tf.ConfigProto()
session_config.gpu_options.allow_growth = True
server = tf.train.Server(cluster,
job_name=args.job_name, | random_line_split | |
curiosity-rl.py | (args, global_step, batch_normalization):
'''
if len(args.egreedy) != 1 and len(args.egreedy) != args.threads:
assert False,"--egreedy should have only one argument, or match the number of threads"
'''
advcore = curiosity.create_advcore(learning_rate=1e-3, args=args, batch_normalization=batch_no... | create_trainer | identifier_name | |
curiosity-rl.py |
if args.localcluster_nsampler > 0:
TRAINER = a2c_mp.MPA2CTrainer
if args.train == 'a2c_overfit_from_fv':
TRAINER = a2c_overfit.OverfitTrainerFromFV
train_everything = False if args.viewinitckpt else True
trainer = TRAINER(
advcore=advcore,
... |
return hooks
def _create_trainer(self, args):
self.bnorm = tf.placeholder(tf.bool, shape=()) if args.batchnorm else None
self.gs = tf.contrib.framework.get_or_create_global_step()
self.trainer, self.advcore = create_trainer(args, self.gs, batch_normalization=self.bnorm)
def r... | class PretrainLoader(tf.train.SessionRunHook):
def __init__(self, advcore, ckpt):
self.advcore = advcore
self.ckpt = ckpt
def after_create_session(self, session, coord):
self.advcore.load_pretrain(session, self.ckpt)
... | conditional_block |
curiosity-rl.py | ainer
if args.localcluster_nsampler > 0:
TRAINER = a2c_mp.MPA2CTrainer
if args.train == 'a2c_overfit_from_fv':
TRAINER = a2c_overfit.OverfitTrainerFromFV
train_everything = False if args.viewinitckpt else True
trainer = TRAINER(
advcore=advcore,
... |
def get_hooks(self):
hooks = [tf.train.StopAtStepHook(last_step=self.trainer.total_iter)]
if self.args.viewinitckpt:
class PretrainLoader(tf.train.SessionRunHook):
def __init__(self, advcore, ckpt):
self.advcore = advcore
self.ck... | super(TEngine, self).__init__(args)
self.mts_master = ''
self.mts_is_chief = True
self.tid = 0 | identifier_body |
settings.go | {IdSession: getIdSession}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
generateToken, _ := token.SignedString([]byte(os.Getenv("TOKEN_HASH")))
tokenString = generateToken
//define expire token
now := time.Now()
expireDate = now
if user.Remember | else {
expireDate = now.Add(2 * time.Minute)
}
//update IdSession
sessionUser := sessionuserservice.FindToId(getIdSession)
sessionUser.Token = tokenString
sessionUser.TokenExpire = expireDate
sessionuserservice.UpdateOne(sessionUser)
logUser := "Inicio Session .."
logsuserservice.Add(1, c... | {
expireDate = now.AddDate(0, 0, 1)
} | conditional_block |
settings.go | {IdSession: getIdSession}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
generateToken, _ := token.SignedString([]byte(os.Getenv("TOKEN_HASH")))
tokenString = generateToken
//define expire token
now := time.Now()
expireDate = now
if user.Remember {
expireDate = now.AddDate(0, 0... |
func isNoBarAndLessThanTenChar(a models.GenericList, value1 string) bool {
return !strings.HasPrefix(a.Value1, value1)
}
var GetUser = func(w http.ResponseWriter, r *http.Request) {
// listProvinces := genericlistservice.GetListForIdCompanyAndIdentity("", "provinces")
// list := genericlistservice.GetListForIdCo... | {
contentType := reflect.TypeOf(arr)
contentValue := reflect.ValueOf(arr)
newContent := reflect.MakeSlice(contentType, 0, 0)
for i := 0; i < contentValue.Len(); i++ {
if content := contentValue.Index(i); cond(content.Interface()) {
newContent = reflect.Append(newContent, content)
}
}
return newContent.Int... | identifier_body |
settings.go | {IdSession: getIdSession}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
generateToken, _ := token.SignedString([]byte(os.Getenv("TOKEN_HASH")))
tokenString = generateToken
//define expire token
now := time.Now()
expireDate = now
if user.Remember {
expireDate = now.AddDate(0, 0... | (a models.GenericList, value1 string) bool {
return !strings.HasPrefix(a.Value1, value1)
}
var GetUser = func(w http.ResponseWriter, r *http.Request) {
// listProvinces := genericlistservice.GetListForIdCompanyAndIdentity("", "provinces")
// list := genericlistservice.GetListForIdCompanyAndIdentity("", "municipies... | isNoBarAndLessThanTenChar | identifier_name |
settings.go | {IdSession: getIdSession}
token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)
generateToken, _ := token.SignedString([]byte(os.Getenv("TOKEN_HASH")))
tokenString = generateToken
//define expire token
now := time.Now()
expireDate = now
if user.Remember {
expireDate = now.AddDate(0, 0... |
// newUser := models.IUser{
// DateAdd: time.Now(),
// IdCompany: "55555555",
// IdRol: "144444",
// Image: "imagen",
// LastLogin: time.Now(),
// LastName: "apellido",
// Name: "NOmbre",
// Password: utils.Encript([]byte("231154")),
// Status: 1,
// NickName: "usuario1",
// ... | // result := usersservice.FindToId("5e795d655d554045401496e6")
// result.NickName = "ADMIN23"
// fmt.Println(usersservice.UpdateOne(result))
// fmt.Println(result.ID) | random_line_split |
Code_Projet_ML.py | _M"]=[data[data.TICKER == t].RDMT_M.values.mean() for t in list_tickers]
#mot le plus apparus par ticker
stats_by_ticker['MOST_FREQ_WORD']=[data[data.TICKER==t][all_words].sum().argmax() for t in list_tickers]
#nombre d'apparition du mot le plus souvent apparus par ticker
stats_by_ticker['NB_WORD']=[data[data.T... | ("Mot\tApparition\tRdt mensuel moyen")
print("==================================")
for i in range(len(result)):
print("\n{}\t{}\t{}".format(result[i][0],result[i][1],result[i][2].round(4)))
#DataFrame contenant la liste des mots filtrés, leurs rendements moyens et leurs nombres d'apparitions
df = pd.DataFrame(... | t_moy_m])
# Sortie Tableau énoncé
print | conditional_block |
Code_Projet_ML.py | print(data.dtypes)
#On récupère la liste des tickers
list_tickers=data.TICKER.unique().tolist()
#Modification de la base ( date et ajout de données sur les varaitions futures de volume)
data['annee']= pd.to_datetime(data.annee*10000+data.mois*100+data.jour,format='%Y%m%d')
data.rename(columns={'annee': 'date'}, ... | data.head()
#Affichage des caractéristiques
print("Nombre de lignes : {}\nNombre de colonnes : {}\n".format(len(data), len(data.columns)))
data['recommandation'] = pd.to_numeric(data['recommandation']) #on convertit en numeric la donnée de l'apparition du mot 'recommandation'
| random_line_split | |
normalizer.py | Copyright © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to
deal in the Software without restriction, including without limitation the
rights to... | ste_data: dict = {},
data_range: defaultdict = None,
method: str = "task",
scale: int = 100,
offset: int = 1,
) -> None:
"""Constructor for Normalizer.
Args:
perf_measure (str): Name of column to use for metrics calculations.
data (pd.... | data: pd.DataFrame, | random_line_split |
normalizer.py | © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to
deal in the Software without restriction, including without limitation the
rights to use, cop... |
return data
elif self.method == "run":
data.loc[:, self.perf_measure] = (
(data[self.perf_measure].to_numpy() - self.run_min)
/ (self.run_max - self.run_min)
* self.scale
) + self.offset | n self.data_range.keys():
task_min = self.data_range[task]["min"]
task_max = self.data_range[task]["max"]
task_data = data.loc[
data["task_name"] == task, self.perf_measure
].to_numpy()
if task_m... | conditional_block |
normalizer.py | © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to
deal in the Software without restriction, including without limitation the
rights to use, cop... | thod: str) -> bool:
"""Validates normalization method.
Args:
method (str): Normalization method.
Raises:
ValueError: If method is not in list of valid methods.
Returns:
bool: True if validation succeeds.
"""
if method not in self.va... | _method(self, me | identifier_name |
normalizer.py | © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to
deal in the Software without restriction, including without limitation the
rights to use, cop... | raise KeyError(f"Missing required fields: min and max")
else:
return True
def
_validate_method(self, method: str) -> bool:
"""Validates normalization method.
Args:
method (str): Normalization method.
Raises:
ValueError: If method is... | tes data range object.
Args:
data_range (defaultdict): Dictionary object for data range.
task_names (Set[str]): Set of task names in the data.
Raises:
TypeError: If data range is not a dictionary object.
KeyError: If data range is not defined for all tas... | identifier_body |
lib.rs | = 10;
pub const LISTENER_ENDPOINT: &str = "http://localhost:3005";
pub const LOCK_TIMEOUT_EXPIRATION: u64 = 3000; // in milli-seconds
pub trait Trait: system::Trait + timestamp::Trait + SendTransactionTypes<Call<Self>> {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
type CreateRoleOrig... |
// --- Offchain worker methods ---
fn process_ocw_notifications(block_number: T::BlockNumber) {
// Check last processed block
let last_processed_block_ref =
StorageValueRef::persistent(b"product_tracking_ocw::last_proccessed_block");
let mut last_processed_block: u32 = mat... | {
ensure!(
props.len() <= SHIPMENT_MAX_PRODUCTS,
Error::<T>::ShipmentHasTooManyProducts,
);
Ok(())
} | identifier_body |
lib.rs | usize = 10;
pub const LISTENER_ENDPOINT: &str = "http://localhost:3005";
pub const LOCK_TIMEOUT_EXPIRATION: u64 = 3000; // in milli-seconds
pub trait Trait: system::Trait + timestamp::Trait + SendTransactionTypes<Call<Self>> {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
type CreateRo... | let status = shipment.status.clone();
// Create shipping event
let event = Self::new_shipping_event()
.of_type(ShippingEventType::ShipmentRegistration)
.for_shipment(id.clone())
.at_location(None)
.with_readings(vec![])... | .registered_at(<timestamp::Module<T>>::now())
.with_products(products)
.build(); | random_line_split |
lib.rs | _128_concat) ShipmentId => Vec<ShippingEventIndex>;
// Off-chain Worker notifications
pub OcwNotifications get (fn ocw_notifications): map hasher(identity) T::BlockNumber => Vec<ShippingEventIndex>;
}
}
decl_event!(
pub enum Event<T>
where
AccountId = <T as system::Trait>::AccountI... | {
last_processed_block_ref.set(&last_processed_block);
debug::info!(
"[product_tracking_ocw] Notifications successfully processed up to block {}",
last_processed_block
);
} | conditional_block | |
lib.rs | = 10;
pub const LISTENER_ENDPOINT: &str = "http://localhost:3005";
pub const LOCK_TIMEOUT_EXPIRATION: u64 = 3000; // in milli-seconds
pub trait Trait: system::Trait + timestamp::Trait + SendTransactionTypes<Call<Self>> {
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
type CreateRoleOrig... | (block_number: T::BlockNumber) {
// Check last processed block
let last_processed_block_ref =
StorageValueRef::persistent(b"product_tracking_ocw::last_proccessed_block");
let mut last_processed_block: u32 = match last_processed_block_ref.get::<T::BlockNumber>() {
Some(Som... | process_ocw_notifications | identifier_name |
app.rs | fn rate_fps(fps: f64) -> Self {
let update_interval = update_interval(fps);
LoopMode::Rate { update_interval }
}
/// Specify the **Wait** mode with the given number of updates following each non-`Update`
/// event.
///
/// Uses the default update interval.
pub fn wait(updates_f... | random_line_split | ||
app.rs | {
updates_following_event,
update_interval,
}
}
/// Specify the **Wait** mode with the given number of updates following each non-`Update`
/// event.
///
/// Waits long enough to ensure loop iteration never occurs faster than the given `max_fps`.
pub fn wait_wit... | {
self.events_loop_proxy.wakeup()
} | identifier_body | |
app.rs | ` is the set of keys that are currently pressed.
///
/// NOTE: `down` this is tracked by the nannou `App` so issues might occur if e.g. a key is
/// pressed while the app is in focus and then released when out of focus. Eventually we should
/// change this to query the OS somehow, but I don't think `win... | (&self) -> Result<PathBuf, find_folder::Error> {
let exe_path = std::env::current_exe()?;
find_folder::Search::ParentsThenKids(5, 3)
.of(exe_path.parent().expect("executable has no parent directory to search").into())
.for_folder(Self::ASSETS_DIRECTORY_NAME)
}
/// Begin ... | assets_path | identifier_name |
app.rs | f64 = 60.0;
pub const DEFAULT_UPDATES_FOLLOWING_EVENT: usize = 3;
/// Specify the **Rate** mode with the given frames-per-second.
pub fn rate_fps(fps: f64) -> Self {
let update_interval = update_interval(fps);
LoopMode::Rate { update_interval }
}
/// Specify the **Wait** mode with... | {
let event_loop = self.event_loop.clone();
let (tx, rx) = mpsc::channel();
let mut loop_context = audio::stream::LoopContext::new(rx);
thread::Builder::new()
.name("cpal::EventLoop::run thread".into())
.spawn(move || event_loop.run(move |i... | conditional_block | |
elns.py | N_CONFIG) as file:
config = json.load(file)
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return (
None,
f"Can't open '{ELN_CONFIG}' (ELN configuration file). Instance: {eln_instance}",
)
# If no ELN instance was specified, trying the default on... | else:
self.modify_settings.disabled = True
send_button.disabled = True
self.message.value = f"""Warning! The access to ELN is not configured. Please follow <a href="{self.path_to_root}/aiidalab-widgets-base/notebooks/eln_configure.ipynb" target="_blank">the link</a> to config... | ]
self.eln, msg = connect_to_eln()
if self.eln:
tl.dlink((self, "node"), (self.eln, "node")) | random_line_split |
elns.py | N_CONFIG) as file:
config = json.load(file)
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return (
None,
f"Can't open '{ELN_CONFIG}' (ELN configuration file). Instance: {eln_instance}",
)
# If no ELN instance was specified, trying the default on... |
return (
None,
"No ELN instance was provided, the default ELN instance is not configured either. Set a default ELN or select an ELN instance.",
)
class ElnImportWidget(ipw.VBox):
node = tl.Instance(orm.Node, allow_none=True)
def __init__(self, path_to_root="../", **kwargs):
... | if eln_instance in config:
eln_config = config[eln_instance]
eln_type = eln_config.pop("eln_type", None)
else: # The selected instance is not present in the config.
return None, f"Didn't find configuration for the '{eln_instance}' instance."
# If the ELN type cannot... | conditional_block |
elns.py | N_CONFIG) as file:
config = json.load(file)
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return (
None,
f"Can't open '{ELN_CONFIG}' (ELN configuration file). Instance: {eln_instance}",
)
# If no ELN instance was specified, trying the default on... | (self):
config = self.get_config()
default_eln = config.pop("default", None)
if (
default_eln not in config
): # Erase the default ELN if it is not present in the config
self.write_to_config(config)
default_eln = None
self.eln_instance.option... | update_list_of_elns | identifier_name |
elns.py | N_CONFIG) as file:
config = json.load(file)
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return (
None,
f"Can't open '{ELN_CONFIG}' (ELN configuration file). Instance: {eln_instance}",
)
# If no ELN instance was specified, trying the default on... |
def get_config(self):
try:
with open(ELN_CONFIG) as file:
return json.load(file)
except (FileNotFoundError, json.JSONDecodeError, KeyError):
return {}
def update_list_of_elns(self):
config = self.get_config()
default_eln = config.pop("de... | with open(ELN_CONFIG, "w") as file:
json.dump(config, file, indent=4) | identifier_body |
list_buffer.go | ListBuffer instance.
func New() *ListBuffer {
buf := new(ListBuffer)
buf.Init()
return buf
}
// Init initializes a blank ListBuffer instance.
func (buf *ListBuffer) Init() |
// Singleton creates a singleton list containing only the given item.
//
// Singleton returns an error if it is passed
// an uninitialized item, or if the buf is full.
//
// It is correct to call buf.IsFull() prior to all calls to
// buf.Singleton(), since it is not possible to switch upon the type of error
// to ide... | {
buf.Buffer = make([]Node, defaultBufferLength)
buf.FreeHead = 0
buf.Count = 0
for i := 0; i < len(buf.Buffer); i++ {
buf.Buffer[i].Item.Clear()
buf.Buffer[i].Prev = BufferIndex(i - 1)
buf.Buffer[i].Next = BufferIndex(i + 1)
}
buf.Buffer[0].Prev = NilIndex
buf.Buffer[len(buf.Buffer)-1].Next = NilIndex
} | identifier_body |
list_buffer.go | ListBuffer instance.
func New() *ListBuffer {
buf := new(ListBuffer)
buf.Init()
return buf
}
// Init initializes a blank ListBuffer instance.
func (buf *ListBuffer) Init() {
buf.Buffer = make([]Node, defaultBufferLength)
buf.FreeHead = 0
buf.Count = 0
for i := 0; i < len(buf.Buffer); i++ {
buf.Buffer[i].Ite... |
buf.internalDelete(idx)
return nil
}
func (buf *ListBuffer) internalDelete(idx BufferIndex) {
buf.internalUnlink(idx)
if buf.FreeHead != NilIndex {
buf.internalLink(idx, buf.FreeHead)
}
node := &buf.Buffer[idx]
node.Item.Clear()
node.Next = buf.FreeHead
node.Prev = NilIndex
buf.FreeHead = idx
buf.Cou... | {
desc := fmt.Sprintf(
"Item at idx, %d, has the Type value Uninitialized.", idx,
)
return error.New(error.Value, desc)
} | conditional_block |
list_buffer.go | "math"
"github.com/phil-mansfield/rogue/error"
)
// BufferIndex is an integer type used to index into ListBuffer.
//
// Since BufferIndex may be changed to different size or to a type of unknown
// signage, all BufferIndex literals must be constructed from 0, 1,
// MaxBufferCount, and NilIndex alone.
type BufferInd... | random_line_split | ||
list_buffer.go | ListBuffer instance.
func New() *ListBuffer {
buf := new(ListBuffer)
buf.Init()
return buf
}
// Init initializes a blank ListBuffer instance.
func (buf *ListBuffer) Init() {
buf.Buffer = make([]Node, defaultBufferLength)
buf.FreeHead = 0
buf.Count = 0
for i := 0; i < len(buf.Buffer); i++ {
buf.Buffer[i].Ite... | (item Item) (BufferIndex, *error.Error) {
if buf.IsFull() {
desc := fmt.Sprintf(
"buf has reached maximum capacity of %d Items.",
MaxBufferCount,
)
return NilIndex, error.New(error.Value, desc)
} else if item.Type == Uninitialized {
return NilIndex, error.New(error.Value, "item is uninitialized.")
}
... | Singleton | identifier_name |
run_swmm_DDPG.py | = "rwd2" # name of reward function for labeling plots/data
gamma = 0.99
lr = 0.00005
tau = 0.001
batch_size = 100
# Initialize input states TODO dynamically read from swmm input file
temp_height = np.zeros(2, dtype='int32') # St1.depth, St2.depth
temp_valve = np.zeros(2, dtype='int32') # R1.current_setting... | temp_new_flood = np.asarray([St1.flooding, St2.flooding, J3.flooding])
temp_new_valve = np.asarray([R1.current_setting, R2.current_setting])
node_new_states = np.append(temp_new_height, temp_new_flood)
# input_new_states = np.append(node_new_states, temp_new_valve).res... | # Observe next state
temp_new_height = np.asarray([St1.depth, St2.depth])
| random_line_split |
run_swmm_DDPG.py | wd = "rwd2" # name of reward function for labeling plots/data
gamma = 0.99
lr = 0.00005
tau = 0.001
batch_size = 100
# Initialize input states TODO dynamically read from swmm input file
temp_height = np.zeros(2, dtype='int32') # St1.depth, St2.depth
temp_valve = np.zeros(2, dtype='int32') # R1.current_setti... |
St1_depth_episode = []
St2_depth_episode = []
J3_depth_episode = []
St1_flooding_episode = []
St2_flooding_episode = []
J3_flooding_episode = []
R1_position_episode = []
R2_position_episode = []
episode += 1
# initialize simulation
sim = Simulation(swmm_inp)... | actor.load_weights(os.path.join(actor_dir, save_model_name + "_actor.h5"))
critic.load_weights(os.path.join(critic_dir, save_model_name + "_critic.h5")) | conditional_block |
export.go | ctx, cancel := context.WithTimeout(r.Context(), s.bsc.CreateTimeout)
defer cancel()
logger := logging.FromContext(ctx)
// Obtain lock to make sure there are no other processes working to create batches.
lock := "create_batches"
unlockFn, err := s.db.Lock(ctx, lock, s.bsc.CreateTimeout) // TODO(jasonco): double t... |
// Append to files list
files = append(files, objectName)
batchCount++
recordCount = 1
}
exp, done, err = it.Next()
}
if err != nil {
return fmt.Errorf("iterating infections: %v", err)
}
// Create a file for the remaining keys
objectName := fmt.Sprintf(eb.FilenameRoot+"%s-%d", eb.StartTimesta... | {
return err
} | conditional_block |
export.go | {
ctx, cancel := context.WithTimeout(r.Context(), s.bsc.CreateTimeout)
defer cancel()
logger := logging.FromContext(ctx)
// Obtain lock to make sure there are no other processes working to create batches.
lock := "create_batches"
unlockFn, err := s.db.Lock(ctx, lock, s.bsc.CreateTimeout) // TODO(jasonco): doubl... | OnlyLocalProvenance: false, // include federated ids
}
)
it, err := s.db.IterateInfections(ctx, criteria)
if err != nil {
return fmt.Errorf("iterating infections: %v", err)
}
defer it.Close()
exp, done, err := it.Next()
// TODO(lmohanan): Watch for context deadline
for !done && err == nil {
if exp !=... | UntilTimestamp: eb.EndTimestamp,
IncludeRegions: eb.IncludeRegions,
ExcludeRegions: eb.ExcludeRegions, | random_line_split |
export.go | {
ctx, cancel := context.WithTimeout(r.Context(), s.bsc.CreateTimeout)
defer cancel()
logger := logging.FromContext(ctx)
// Obtain lock to make sure there are no other processes working to create batches.
lock := "create_batches"
unlockFn, err := s.db.Lock(ctx, lock, s.bsc.CreateTimeout) // TODO(jasonco): doubl... | }
)
it, err := s.db.IterateInfections(ctx, criteria)
if err != nil {
return fmt.Errorf("iterating infections: %v", err)
}
defer it.Close()
exp, done, err := it.Next()
// TODO(lmohanan): Watch for context deadline
for !done && err == nil {
if exp != nil {
exposureKeys = append(exposureKeys, exp)
re... | {
logger := logging.FromContext(ctx)
logger.Infof("Creating files for export config %v, batchID %v", eb.ConfigID, eb.BatchID)
logger.Infof("MaxRecords %v, since %v, until %v", s.bsc.MaxRecords, eb.StartTimestamp, eb.EndTimestamp)
logger.Infof("Included regions %v, ExcludedRegions %v ", eb.IncludeRegions, eb.Exclud... | identifier_body |
export.go | (w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), s.bsc.CreateTimeout)
defer cancel()
logger := logging.FromContext(ctx)
// Obtain lock to make sure there are no other processes working to create batches.
lock := "create_batches"
unlockFn, err := s.db.Lock(ctx, lock, s.bs... | CreateBatchesHandler | identifier_name | |
unlinked_file.rs | ,
};
match current.children.iter().find(|(name, _)| name.to_smol_str() == seg) {
Some((_, &child)) => current = &crate_def_map[child],
None => continue 'crates,
}
if !current.origin.is_inline() {
continue 'crates;
... | unlinked_file_with_cfg_off | identifier_name | |
unlinked_file.rs | stack.pop();
'crates: for &krate in ctx.sema.db.relevant_crates(parent_id).iter() {
let crate_def_map = ctx.sema.db.crate_def_map(krate);
let Some((_, module)) = crate_def_map.modules().find(|(_, module)| {
module.origin.file_id() == Some(parent_id) && !module.origin.is_inline()
... | {
check_fix(
r#"
//- /main.rs
mod bar {
}
//- /bar/foo/mod.rs
$0
"#,
r#"
mod bar {
mod foo;
}
"#,
);
} | identifier_body | |
unlinked_file.rs | take the parent as our to be module name
"mod" => {
let (name, _) = parent.name_and_extension()?;
(parent.parent()?, name.to_owned())
}
_ => (parent, module_name.to_owned()),
};
// check crate roots, i.e. main.rs, lib.rs, ...
'crates: for &krate in &*ctx.sem... | "#,
r#" | random_line_split | |
h2ctypes.py | float": ctypes.c_float,
"double": ctypes.c_double,
"long double": ctypes.c_longdouble,
"char*": ctypes.c_char_p,
"wchar_t*": ctypes.c_wchar_p,
"void*": ctypes.c_void_p,
"int32_t": ctypes.c_int32,
"uint32_t": ctypes.c_uint32,
"int64_... | (self):
"""Parse ``typedef enum``'s.
"""
# Notes on enum types
#
# GCC:
#
# Normally, the type is unsigned int if there are no negative values in
# the enumeration, otherwise int. If -fshort-enums is specified, then
# if there are negative values i... | parse_enums | identifier_name |
h2ctypes.py | float": ctypes.c_float,
"double": ctypes.c_double,
"long double": ctypes.c_longdouble,
"char*": ctypes.c_char_p,
"wchar_t*": ctypes.c_wchar_p,
"void*": ctypes.c_void_p,
"int32_t": ctypes.c_int32,
"uint32_t": ctypes.c_uint32,
"int64_... | n_stars -= 1
try:
ctype = self.types[pointed_to]
except KeyError:
raise ParseError
if n_stars:
ctype = as_ctype(ctype)
for _ in range(n_stars):
ctype = ctypes.POINTER(ctype)
if array_size is not None:
ctype =... | if pointed_to in ("char", "wchar_t", "void") and n_stars >= 1:
pointed_to += "*" | random_line_split |
h2ctypes.py | type
func.__annotations__["return"] = restype
module_globals[fname] = func
module_all.append(fname)
class Parser:
"""A stateful C header parser.
An instance of the parser keeps tracks of the ``#defines``, whether of
constants or of types (no other preprocessor macro is... | raise AttributeError(
"{} is not a public function of the DLL".format(fname)) | identifier_body | |
h2ctypes.py | float": ctypes.c_float,
"double": ctypes.c_double,
"long double": ctypes.c_longdouble,
"char*": ctypes.c_char_p,
"wchar_t*": ctypes.c_wchar_p,
"void*": ctypes.c_void_p,
"int32_t": ctypes.c_int32,
"uint32_t": ctypes.c_uint32,
"int64_... |
func.__annotations__["return"] = restype
module_globals[fname] = func
module_all.append(fname)
class Parser:
"""A stateful C header parser.
An instance of the parser keeps tracks of the ``#defines``, whether of
constants or of types (no other preprocessor macro is han... | func.__annotations__[arg] = argtype | conditional_block |
lib.rs | (options.keepalive)?;
let transport = ClickhouseTransport::new(stream, compress, pool.clone());
let mut handle = ClientHandle {
inner: Some(transport),
context,
pool: match pool {
None => PoolBinding::No... | tokio::time::timeout(timeout, future).await?
}
#[cf | identifier_body | |
lib.rs | //! customer_id UInt32,
//! amount UInt32,
//! account_name Nullable(FixedString(3))
//! ) Engine=Memory";
//!
//! let block = Block::new()
//! .column("customer_id", vec![1_u32, 3, 5, 7, 9])
//! .column("amount", vec![2_u32, 4, 6, 8, ... | }
Ok(Packet::Exception(e)) => return Err(Error::Server(e)),
Err(e) => return Err(Error::Io(e)),
_ => return Err(Error::Driver(DriverError::UnexpectedPacket)),
}
}
self.inner = h;
self.context.server_info = info.unwrap()... | match packet {
Ok(Packet::Hello(inner, server_info)) => {
info!("[hello] <- {:?}", &server_info);
h = Some(inner);
info = Some(server_info); | random_line_split |
lib.rs | customer_id UInt32,
//! amount UInt32,
//! account_name Nullable(FixedString(3))
//! ) Engine=Memory";
//!
//! let block = Block::new()
//! .column("customer_id", vec![1_u32, 3, 5, 7, 9])
//! .column("amount", vec![2_u32, 4, 6, 8, 10])
//! ... | ns: Options) -> Result<ClientHandle> {
let source = options.into_options_src();
Self::open(source, None).await
}
pub(crate) async fn open(source: OptionsSource, pool: Option<Pool>) -> Result<ClientHandle> {
let options = try_opt!(source.get());
let compress = options.compression... | t(optio | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.