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
SearchUtility.js
/** @flow */ import { INDEX_MODES } from "./constants"; import SearchIndex from "./SearchIndex"; import type { IndexMode } from "./constants"; import type { SearchApiIndex } from "../types"; type UidMap = { [uid: string]: boolean }; /** * Synchronous client-side full-text search utility. * Forked from JS search...
(this._indexMode) { case INDEX_MODES.EXACT_WORDS: return [token]; case INDEX_MODES.PREFIXES: return this._expandPrefixTokens(token); case INDEX_MODES.ALL_SUBSTRINGS: default: return this._expandAllSubstringTokens(token); } } _expandAllSubstringTokens(token: stri...
switch
identifier_name
unban.py
from sigma.core.permission import check_ban import discord async def un
md, message, args): channel = message.channel if args: user_q = args[0] if message.author is not user_q: if check_ban(message.author, channel): ban_list = await message.guild.bans() target_user = None for user in ban_list: ...
ban(c
identifier_name
unban.py
from sigma.core.permission import check_ban import discord async def unban(cmd, message, args): channel = message.channel if args: user_q = args[0] if message.author is not user_q: if check_ban(message.author, channel): ban_list = await message.guild.bans() ...
await message.channel.send(None, embed=out_content) else: out_content = discord.Embed(type='rich', color=0xDB0000, title='⛔ Insufficient Permissions. Ban Permission Required.') await message.channel.send(None, em...
else: out_content = discord.Embed(type='rich', color=0xFF9900, title='⚠ User Not Found In Ban List.')
random_line_split
unban.py
from sigma.core.permission import check_ban import discord async def unban(cmd, message, args): channel = message.channel if args: user_q = args[0] if message.author is not user_q: if
els e: await message.channel.send(cmd.help())
check_ban(message.author, channel): ban_list = await message.guild.bans() target_user = None for user in ban_list: if user.name.lower() == user_q.lower(): target_user = user break if targ...
conditional_block
unban.py
from sigma.core.permission import check_ban import discord async def unban(cmd, message, args): ch
else: out_content = discord.Embed(type='rich', color=0xDB0000, title='⛔ Insufficient Permissions. Ban Permission Required.') await message.channel.send(None, embed=out_content) else: await message.channel.send(cmd.help()...
annel = message.channel if args: user_q = args[0] if message.author is not user_q: if check_ban(message.author, channel): ban_list = await message.guild.bans() target_user = None for user in ban_list: if user.name.lower(...
identifier_body
_walker.py
from typing import Iterable, Callable, Optional, Any, List, Iterator from dupescan.fs._fileentry import FileEntry from dupescan.fs._root import Root from dupescan.types import AnyPath FSPredicate = Callable[[FileEntry], bool] ErrorHandler = Callable[[EnvironmentError], Any] def catch_filter(inner_filter: FSPredicat...
): yield child_obj except EnvironmentError as query_error: self._onerror(query_error) except EnvironmentError as env_error: self._onerror(env_error) dir_obj_q.extend(reversed(next_dir...
dir_obj_q: List[FileEntry] = [ root_obj ] next_dirs: List[FileEntry] = [ ] while len(dir_obj_q) > 0: dir_obj = dir_obj_q.pop() next_dirs.clear() try: for child_obj in dir_obj.dir_content(): try: if ( ...
identifier_body
_walker.py
from typing import Iterable, Callable, Optional, Any, List, Iterator from dupescan.fs._fileentry import FileEntry from dupescan.fs._root import Root from dupescan.types import AnyPath FSPredicate = Callable[[FileEntry], bool] ErrorHandler = Callable[[EnvironmentError], Any] def catch_filter(inner_filter: FSPredicat...
child_obj.is_file and self._file_filter(child_obj) ): yield child_obj except EnvironmentError as query_error: self._onerror(query_error) except EnvironmentE...
elif (
random_line_split
_walker.py
from typing import Iterable, Callable, Optional, Any, List, Iterator from dupescan.fs._fileentry import FileEntry from dupescan.fs._root import Root from dupescan.types import AnyPath FSPredicate = Callable[[FileEntry], bool] ErrorHandler = Callable[[EnvironmentError], Any] def catch_filter(inner_filter: FSPredicat...
except EnvironmentError as query_error: self._onerror(query_error) except EnvironmentError as env_error: self._onerror(env_error) dir_obj_q.extend(reversed(next_dirs)) def flat_iterator( paths: Iterable[AnyPath], dir...
yield child_obj
conditional_block
_walker.py
from typing import Iterable, Callable, Optional, Any, List, Iterator from dupescan.fs._fileentry import FileEntry from dupescan.fs._root import Root from dupescan.types import AnyPath FSPredicate = Callable[[FileEntry], bool] ErrorHandler = Callable[[EnvironmentError], Any] def catch_filter(inner_filter: FSPredicat...
( paths: Iterable[AnyPath], dir_object_filter: Optional[FSPredicate]=None, file_object_filter: Optional[FSPredicate]=None, onerror: Optional[ErrorHandler]=None ) -> Iterator[FileEntry]: return Walker(True, dir_object_filter, file_object_filter, onerror)(paths)
recurse_iterator
identifier_name
controller.js
define([ 'angular', '../module', '../service', 'common/services/bootstrap', ], function(angular, lazyModule, service, bootstrapService) { 'use strict';
/** * [homeController description] * @param {[type]} $scope [description] * @param {[type]} homeService [description] * @return {[type]} [description] */ lazyModule.controller('ContentController', ['$scope', '$modal', '$rootScope', 'HomeService', 'ModalService', ...
random_line_split
convert.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} // FIXME (#23442): replace the above impl for &mut with the following more general one: // // AsMut lifts over DerefMut // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> { // fn as_mut(&mut self) -> &mut U { // self.deref_mut().as_mut() // } // } // From implies Into #[...
{ (*self).as_mut() }
identifier_body
convert.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) -> &mut U { (*self).as_mut() } } // FIXME (#23442): replace the above impl for &mut with the following more general one: // // AsMut lifts over DerefMut // impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> { // fn as_mut(&mut self) -> &mut U { // self.deref...
as_mut
identifier_name
convert.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// Both `String` and `&str` implement `AsRef<str>`: /// /// ``` /// fn is_hello<T: AsRef<str>>(s: T) { /// assert_eq!("hello", s.as_ref()); /// } /// /// let s = "hello"; /// is_hello(s); /// /// let s = "hello".to_string(); /// is_hello(s); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait AsRef<T: ?...
/// /// # Examples ///
random_line_split
dirichlet.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2013 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This fil...
/// # Example /// /// ``` /// use rand::prelude::*; /// use rand_distr::Dirichlet; /// /// let dirichlet = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap(); /// let samples = dirichlet.sample(&mut rand::thread_rng()); /// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples); /// ``` #[cfg_attr(doc_cfg, ...
random_line_split
dirichlet.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2013 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This fil...
(alpha: F, size: usize) -> Result<Dirichlet<F>, Error> { if !(alpha > F::zero()) { return Err(Error::AlphaTooSmall); } if size < 2 { return Err(Error::SizeTooSmall); } Ok(Dirichlet { alpha: vec![alpha; size].into_boxed_slice(), }) }...
new_with_size
identifier_name
dirichlet.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2013 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This fil...
} Ok(Dirichlet { alpha: alpha.to_vec().into_boxed_slice() }) } /// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`. /// /// Requires `size >= 2`. #[inline] pub fn new_with_size(alpha: F, size: usize) -> Result<Dirichlet<F>, Error> { if !(a...
{ return Err(Error::AlphaTooSmall); }
conditional_block
dirichlet.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2013 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. This fil...
#[test] fn test_dirichlet_with_param() { let alpha = 0.5f64; let size = 2; let d = Dirichlet::new_with_size(alpha, size).unwrap(); let mut rng = crate::test::rng(221); let samples = d.sample(&mut rng); let _: Vec<f64> = samples .into_iter() ...
{ let d = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap(); let mut rng = crate::test::rng(221); let samples = d.sample(&mut rng); let _: Vec<f64> = samples .into_iter() .map(|x| { assert!(x > 0.0); x }) .collect();...
identifier_body
renderer.js
const { ipcRenderer, remote } = require('electron'); const mainProcess = remote.require('./main'); const currentWindow = remote.getCurrentWindow();
const $directions = $('.directions-input'); const $notes = $('.notes-input'); const $saveButton = $('.save-recipe-button'); const $seeAllButton = $('.see-all-button'); const $homeButton = $('.home-button'); const $addRecipeButton = $('.add-button'); let pageNav = (page) => { currentWindow.loadURL(`file://${__dirname}...
const $name = $('.name-input'); const $servings = $('.servings-input'); const $time = $('.time-input'); const $ingredients = $('.ingredients-input');
random_line_split
Track.py
# -*- coding: utf-8 -*- ############################################################################### # # Track # Records an event in Mixpanel. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in c...
def set_Verbose(self, value): """ Set the value of the Verbose input for this Choreo. ((optional, boolean) When set to 1, the response will contain more information describing the success or failure of the tracking call.) """ super(TrackInputSet, self)._set_input('Verbose', value) ...
""" Set the value of the Token input for this Choreo. ((required, string) The token provided by Mixpanel. You can find your Mixpanel token in the project settings dialog in the Mixpanel app.) """ super(TrackInputSet, self)._set_input('Token', value)
identifier_body
Track.py
# -*- coding: utf-8 -*-
# Records an event in Mixpanel. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2....
############################################################################### # # Track
random_line_split
Track.py
# -*- coding: utf-8 -*- ############################################################################### # # Track # Records an event in Mixpanel. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in c...
(self, value): """ Set the value of the Time input for this Choreo. ((optional, date) A unix timestamp representing the time the event occurred. If not provided, Mixpanel will use the time the event arrives at the server.) """ super(TrackInputSet, self)._set_input('Time', value) def ...
set_Time
identifier_name
parser_init_mapping.py
# -*- coding: utf-8 -*- """Class representing the mapper for the parser init files.""" from plasoscaffolder.bll.mappings import base_mapping_helper from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping from plasoscaffolder.model import init_data_model class ParserInitMapping( base_sqliteplugin_mappin...
(self, mapping_helper: base_mapping_helper.BaseMappingHelper): """Initializing the init mapper class. Args: mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class for the mapping """ super().__init__() self._helper = mapping_helper def GetRenderedTemplate( ...
__init__
identifier_name
parser_init_mapping.py
# -*- coding: utf-8 -*- """Class representing the mapper for the parser init files.""" from plasoscaffolder.bll.mappings import base_mapping_helper from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping from plasoscaffolder.model import init_data_model class ParserInitMapping( base_sqliteplugin_mappin...
context = {'plugin_name': data.plugin_name, 'is_create_template': data.is_create_template} rendered = self._helper.RenderTemplate( self._PARSER_INIT_TEMPLATE, context) return rendered
Returns: str: the rendered template """
random_line_split
parser_init_mapping.py
# -*- coding: utf-8 -*- """Class representing the mapper for the parser init files.""" from plasoscaffolder.bll.mappings import base_mapping_helper from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping from plasoscaffolder.model import init_data_model class ParserInitMapping( base_sqliteplugin_mappin...
data (init_data_model.InitDataModel): the data for init file Returns: str: the rendered template """ context = {'plugin_name': data.plugin_name, 'is_create_template': data.is_create_template} rendered = self._helper.RenderTemplate( self._PARSER_INIT_TEMPLATE, context)...
"""Class representing the parser mapper.""" _PARSER_INIT_TEMPLATE = 'parser_init_template.jinja2' def __init__(self, mapping_helper: base_mapping_helper.BaseMappingHelper): """Initializing the init mapper class. Args: mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class ...
identifier_body
vxserver.py
# The MIT License (MIT) # Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran # 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 l...
def lineReceived(self, data): try: cmd = json.loads(data) if cmd[u'name'] == 'PRELOAD': vx.addFontPreload(self.id, cmd['args'][0], cmd['args'][1]) return vx.pushWebSocketEvent(self.id, cmd) except ValueError: log.msg("Invalid JSON data received:: %s" % data) cmd = command.process(data) se...
def connectionLost(self, reason): log.msg('application (%s) disconnected' % self.id) vx.unregisterApplication(self.id)
random_line_split
vxserver.py
# The MIT License (MIT) # Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran # 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 ...
(self): self.setLineMode() self.id = None def connectionMade(self): client = self.transport.getHost() log.msg('application at %s connected' % client) self.id = vx.registerApplication(client, self) self.sendEvent("EVENT PRELOAD\n") def connectionLost(self, reason): log.msg('application (%s) disconnect...
__init__
identifier_name
vxserver.py
# The MIT License (MIT) # Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran # 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 ...
def sendEvent(self, event): # log.msg("VxProtocol.sendEvent:: %s" % event) if event.startswith("EVENT"): # log.msg("VxProtocol.sendEvent:: %s" % event) # Prevent overflow attempts by limiting communication to the C side to 256-length buffers event = event[0:255] self.transport.write(event) class Vx...
if cmd['name'] in _available_commands: vx.pushWebSocketEvent(self.id, cmd) return if cmd['name'] == "CLEAR": vx.pushWebSocketEvent(self.id, cmd) # print "Removed call to EXPOSE\n" #self.sendEvent("EVENT EXPOSE\n") return
identifier_body
vxserver.py
# The MIT License (MIT) # Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran # 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 ...
if cmd['name'] == "CLEAR": vx.pushWebSocketEvent(self.id, cmd) # print "Removed call to EXPOSE\n" #self.sendEvent("EVENT EXPOSE\n") return def sendEvent(self, event): # log.msg("VxProtocol.sendEvent:: %s" % event) if event.startswith("EVENT"): # log.msg("VxProtocol.sendEvent:: %s" % event) ...
vx.pushWebSocketEvent(self.id, cmd) return
conditional_block
disk.rs
#![feature(plugin, custom_derive, custom_attribute)] #![plugin(serde_macros)] extern crate drum; extern crate serde; use drum::*; use std::io::*; use std::collections::*; use std::fs::{OpenOptions}; #[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)] enum Value { Array(Vec<Value>), Object(BTreeMap<V...
, _ => panic!() } }, _ => () } Ok(()) } fn main() { run().unwrap(); return; }
{ println!("previous: {}", num); }
conditional_block
disk.rs
#![feature(plugin, custom_derive, custom_attribute)] #![plugin(serde_macros)] extern crate drum; extern crate serde; use drum::*; use std::io::*; use std::collections::*; use std::fs::{OpenOptions}; #[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)] enum Value { Array(Vec<Value>), Object(BTreeMap<V...
() { run().unwrap(); return; }
main
identifier_name
disk.rs
#![feature(plugin, custom_derive, custom_attribute)] #![plugin(serde_macros)] extern crate drum; extern crate serde; use drum::*; use std::io::*; use std::collections::*; use std::fs::{OpenOptions}; #[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)] enum Value { Array(Vec<Value>), Object(BTreeMap<V...
{ run().unwrap(); return; }
identifier_body
disk.rs
#![feature(plugin, custom_derive, custom_attribute)] #![plugin(serde_macros)] extern crate drum; extern crate serde; use drum::*; use std::io::*; use std::collections::*; use std::fs::{OpenOptions}; #[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)] enum Value { Array(Vec<Value>), Object(BTreeMap<V...
}
random_line_split
assignment04.py
#This line asks the user to input an integer that will be recorded as my age my_age = input("Enter your age:") #This line asks the user to input an integer that will be recorded as days_in_a_year days_in_a_year = input("How many days are in a year?") #This line states how many hours are in a day hours_in_a_day = 24 #Th...
print "how many seconds have i been alive?", my_age * days_in_a_year * hours_in_a_day * 60 * 60 #This line says that there are 8 black cars black_cars = 8 #This line says that there are 6 red cars red_cars = 6 #This line states the total amount of black and red cars combined print "What is the total number of black and...
random_line_split
setup.py
from setuptools import setup version = '1.5.0a0' testing_extras = ['nose', 'coverage'] docs_extras = ['Sphinx'] setup( name='WebOb', version=version, description="WSGI request and response object", long_description="""\ WebOb provides wrappers around the WSGI request environment, and an object to he...
'testing':testing_extras, 'docs':docs_extras, }, )
zip_safe=True, test_suite='nose.collector', tests_require=['nose'], extras_require = {
random_line_split
recv_and_pub.py
#!/usr/bin/env python #- # Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # Alternatively, this software may be distributed und...
ba.publish_scope(sid, "", strategy, str_opt) ba.publish_info(rid, sid, strategy, str_opt) def recv_and_pub(sock, ba, rfd): try: sock.bind(("localhost", local_port)) # XXX sfd = sock.fileno() buf = rwbuffer(4096) ...
strategy = NODE_LOCAL # XXX: NODE_LOCAL=0, DOMAIN_LOCAL=2 if len(argv) >= 2: strategy = int(argv[1]) str_opt = None local_port = 0xACDC if len(argv) >= 3: local_port = int(argv[2]) global publishing # XXX publishing = False sock = None wfd, rfd = None, None ...
identifier_body
recv_and_pub.py
#!/usr/bin/env python #- # Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # Alternatively, this software may be distributed und...
(sock, ba, rfd): try: sock.bind(("localhost", local_port)) # XXX sfd = sock.fileno() buf = rwbuffer(4096) while publishing: rlist, wlist, xlist = select([sfd, rfd], [], [sfd, rfd]) if sfd in rlist: ...
recv_and_pub
identifier_name
recv_and_pub.py
#!/usr/bin/env python #- # Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # Alternatively, this software may be distributed und...
ev = Event() ba.getEvent(ev) print ev if not ev: continue print ev.type, "when", publishing if ev.type == START_PUBLISH and not publishing: print "Start publish" sock = socket.socket(socket.AF_INET, s...
print "select:", select_error print "recv_and_pub stopped" while True:
random_line_split
recv_and_pub.py
#!/usr/bin/env python #- # Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # Alternatively, this software may be distributed und...
if wfd: os.close(wfd) if __name__ == "__main__": import sys _main(sys.argv)
os.close(rfd)
conditional_block
handler.ts
// (C) Copyright 2015 Moodle Pty Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agre...
(): boolean | Promise<boolean> { return true; } /** * Whether the rule requires a preflight check when prefetch/start/continue an attempt. * * @param quiz The quiz the rule belongs to. * @param attempt The attempt started/continued. If not supplied, user is starting a new attempt. ...
isEnabled
identifier_name
handler.ts
// (C) Copyright 2015 Moodle Pty Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License.
// distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { Injectable } from '@angular/core'; import { AddonModQuizAcce...
// You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software
random_line_split
handler.ts
// (C) Copyright 2015 Moodle Pty Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agre...
/** * Whether the rule requires a preflight check when prefetch/start/continue an attempt. * * @param quiz The quiz the rule belongs to. * @param attempt The attempt started/continued. If not supplied, user is starting a new attempt. * @param prefetch Whether the user is prefetching the q...
{ return true; }
identifier_body
builders.rs
use std::fmt; use std::rc::Rc; use quire::validate as V; use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor}; use serde::ser::{Serializer, Serialize}; use crate::build_step::{Step, BuildStep}; use crate::builder::commands as cmd; macro_rules! define_commands { ($($module: ident :...
{ if false { unreachable!() } $( else if let Some(b) = self.0.downcast_ref::<cmd::$module::$item>() { b.serialize(s) } )* else { ...
-> Result<S::Ok, S::Error>
random_line_split
builders.rs
use std::fmt; use std::rc::Rc; use quire::validate as V; use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor}; use serde::ser::{Serializer, Serialize}; use crate::build_step::{Step, BuildStep}; use crate::builder::commands as cmd; macro_rules! define_commands { ($($module: ident :...
; fn decode<'x, T, V>(v: V) -> Result<Step, V::Error> where T: BuildStep + Deserialize<'x> + 'static, V: VariantAccess<'x>, { v.newtype_variant::<T>().map(|x| Step(Rc::new(x) as Rc<dyn BuildStep>)) } impl<'a> Deserialize<'a> for CommandName { fn deserialize<D: Deserializer<'a>>(d: D) ...
StepVisitor
identifier_name
builders.rs
use std::fmt; use std::rc::Rc; use quire::validate as V; use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor}; use serde::ser::{Serializer, Serialize}; use crate::build_step::{Step, BuildStep}; use crate::builder::commands as cmd; macro_rules! define_commands { ($($module: ident :...
} impl<'a> Deserialize<'a> for Step { fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Step, D::Error> { d.deserialize_enum("BuildStep", COMMANDS, StepVisitor) } }
{ d.deserialize_identifier(NameVisitor) }
identifier_body
test_therm.py
import RPi.GPIO as GPIO import time import utils import therm GPIO.setmode(GPIO.BOARD) #pwr = utils.PSU(13, 15) #pwr.on()
now = time.time() t_amb = therm.Therm('28-000004e08693') t_c_b = therm.Therm('28-000004e0f7cc') t_c_m = therm.Therm('28-000004e0840a') t_c_t = therm.Therm('28-000004e08e26') t_hs = therm.Therm('28-000004e0804f') print time.time() - now now = time.time() for i in range(samples): temp_row = [t_amb.read_temp(), t_...
#pwr.off() adresses = therm.get_adr() samples = 5 therms = []
random_line_split
test_therm.py
import RPi.GPIO as GPIO import time import utils import therm GPIO.setmode(GPIO.BOARD) #pwr = utils.PSU(13, 15) #pwr.on() #pwr.off() adresses = therm.get_adr() samples = 5 therms = [] now = time.time() t_amb = therm.Therm('28-000004e08693') t_c_b = therm.Therm('28-000004e0f7cc') t_c_m = therm.Therm('28-000004e0840a...
print therms #GPIO.cleanup()
temp_row = [t_amb.read_temp(), t_c_b.read_temp(), t_c_m.read_temp(), t_c_t.read_temp(), t_hs.read_temp()] print temp_row therms.append(temp_row) print time.time() - now now = time.time()
conditional_block
settings.py
# Copyright (c) 2009-2020 - Simon Conseil # Copyright (c) 2013 - Christophe-Marie Duquesne # Copyright (c) 2017 - Mate Lakat # 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...
(filename=None): """Read settings from a config file in the source_dir root.""" logger = logging.getLogger(__name__) logger.info("Reading settings ...") settings = _DEFAULT_CONFIG.copy() if filename: logger.debug("Settings file: %s", filename) settings_path = os.path.dirname(filena...
read_settings
identifier_name
settings.py
# Copyright (c) 2009-2020 - Simon Conseil # Copyright (c) 2013 - Christophe-Marie Duquesne # Copyright (c) 2017 - Mate Lakat # 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...
if not settings['img_processor']: logger.info('No Processor, images will not be resized') logger.debug('Settings:\n%s', pformat(settings, width=120)) return settings def create_settings(**kwargs): """Create a new default setting copy and initialize it with kwargs.""" settings = _DEFAULT...
w, h = settings[key] if h > w: settings[key] = (h, w) logger.warning("The %s setting should be specified with the " "largest value first.", key)
conditional_block
settings.py
# Copyright (c) 2009-2020 - Simon Conseil # Copyright (c) 2013 - Christophe-Marie Duquesne # Copyright (c) 2017 - Mate Lakat # 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...
"""Create a new default setting copy and initialize it with kwargs.""" settings = _DEFAULT_CONFIG.copy() settings.update(kwargs) return settings
identifier_body
settings.py
# Copyright (c) 2009-2020 - Simon Conseil # Copyright (c) 2013 - Christophe-Marie Duquesne # Copyright (c) 2017 - Mate Lakat # 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...
examples: >>> default_settings = create_settings() >>> get_thumb(default_settings, "bar/foo.jpg") "bar/thumbnails/foo.jpg" >>> get_thumb(default_settings, "bar/foo.png") "bar/thumbnails/foo.png" for videos, it returns a jpg file: >>> get_thumb(default_settings, "bar/foo.webm") "bar...
def get_thumb(settings, filename): """Return the path to the thumb.
random_line_split
custom_build.rs
unit: &Unit<'a>) -> CraftResult<(Work, Work, Freshness)> { let _p = profile::start(format!("build script prepare: {}/{}", unit.pkg, unit.target.name())); let overridden = cx.build_state.has_override(unit); let (work_dirty, work_fresh) = if overridden { (Work::new(|_| Ok(())), Work::new(|_| Ok(())))...
// Parses the output of a script. // The `pkg_name` is used for error messages
{ let contents = paths::read_bytes(path)?; BuildOutput::parse(&contents, pkg_name) }
identifier_body
custom_build.rs
fs::create_dir_all(&cx.layout(unit).build(unit.pkg))?; // Prepare the unit of "dirty work" which will actually run the custom build // command. // // Note that this has to do some extra work just before running the command // to determine extra environment variables and such. let dirty = Work:...
build
identifier_name
custom_build.rs
>, unit: &Unit<'a>) -> CraftResult<(Work, Work, Freshness)> { let _p = profile::start(format!("build script prepare: {}/{}", unit.pkg, unit.target.name())); let overridden = cx.build_state.has_override(unit); let (work_dirty, work_fresh) = if overridden { (Work::new(|_| Ok(())), Work::new(|_| Ok(())...
let data = &state.metadata; for &(ref key, ref value) in data.iter() { cmd.env(&format!("DEP_{}_{}", super::envify(&name), super::envify(key)), value); } } if let Some(build_scripts) = build_scripts {...
internal(format!("failed to locate build state for env vars: {}/{:?}", id, kind)) })?;
random_line_split
featured_thumbnail.js
function featured_thumb()
window.onload = featured_thumb;
{ jQuery('ul.thumbnails').each(function(index, element) { var get_class=jQuery(this).attr('class'); var get_parent=jQuery(this).closest('div'); var wt=jQuery(this).closest('div').width();//width total var col=jQuery(this).attr('data-columns');//columns var dt=Math.floor(wt/col); var mt=6; var wa=dt-mt; ...
identifier_body
featured_thumbnail.js
function
(){ jQuery('ul.thumbnails').each(function(index, element) { var get_class=jQuery(this).attr('class'); var get_parent=jQuery(this).closest('div'); var wt=jQuery(this).closest('div').width();//width total var col=jQuery(this).attr('data-columns');//columns var dt=Math.floor(wt/col); var mt=6; var wa=dt-mt;...
featured_thumb
identifier_name
featured_thumbnail.js
function featured_thumb(){ jQuery('ul.thumbnails').each(function(index, element) { var get_class=jQuery(this).attr('class'); var get_parent=jQuery(this).closest('div'); var wt=jQuery(this).closest('div').width();//width total var col=jQuery(this).attr('data-columns');//columns var dt=Math.floor(wt/col); va...
var mg=3; var ft_size=jQuery(this).attr('data-ftsize'); jQuery(this).css('font-size',ft_size+'px'); get_parent.find('ul.thumbnails li').css({'max-width':wa+'px','margin':mg+'px','padding':'0'}); get_parent.find('ul.thumbnails li h5').css({'font-size':ft_size+'px','font-weight':'bold','padding':'0 0 5px','marg...
var wa=dt-mt;
random_line_split
hierarchical-menu.tsx
string[]; /** * CSS class to add to the root element when no refinements. */ noRefinementRoot: string | string[]; /** * CSS class to add to the list element. */ list: string | string[]; /** * CSS class to add to the child list element. */ childList: string | string[]; /** * CSS class...
rootPath, showParentLevel, limit, showMore, showMoreLimit,
random_line_split
hierarchical-menu.tsx
lib/utils/prepareTemplateProps'; import { prepareTemplateProps, getContainerNode, createDocumentationMessageGenerator, } from '../../lib/utils'; import type { TransformItems, Template, WidgetFactory, RendererOptions, SortBy, ComponentCSSClasses, } from '../../types'; import { component } from '../../l...
const containerNode = getContainerNode(container); const cssClasses = { root: cx(suit(), userCssClasses.root), noRefinementRoot: cx( suit({ modifierName: 'noRefinement' }), userCssClasses.noRefinementRoot ), list: cx(suit({ descendantName: 'list' }), userCssClasses.list), childLis...
{ throw new Error(withUsage('The `container` option is required.')); }
conditional_block
FakeGame.ts
/// <reference path="../../../Phaser/Game.ts" /> /// <reference path="../../../Phaser/State.ts" /> class FakeGame extends State {
(game: Game) { super(game); } private car: Phaser.Sprite; private bigCam: Phaser.Camera; public init() { this.load.image('track', '../../assets/games/f1/track.png'); this.load.image('car', '../../assets/games/f1/car1.png'); this.load.start(); } public crea...
constructor
identifier_name
FakeGame.ts
/// <reference path="../../../Phaser/Game.ts" /> /// <reference path="../../../Phaser/State.ts" /> class FakeGame extends State { constructor(game: Game) { super(game); } private car: Phaser.Sprite; private bigCam: Phaser.Camera; public init() { this.load.image('track', '../.....
else if (this.input.keyboard.isDown(Keyboard.RIGHT)) { this.car.rotation += 4; } if (this.game.input.keyboard.isDown(Keyboard.UP)) { this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 150)); } else { ...
{ this.car.rotation -= 4; }
conditional_block
FakeGame.ts
/// <reference path="../../../Phaser/Game.ts" /> /// <reference path="../../../Phaser/State.ts" /> class FakeGame extends State { constructor(game: Game) { super(game); } private car: Phaser.Sprite; private bigCam: Phaser.Camera; public init() { this.load.image('track', '../.....
} }
{ if (this.input.keyboard.isDown(Keyboard.LEFT)) { this.car.rotation -= 4; } else if (this.input.keyboard.isDown(Keyboard.RIGHT)) { this.car.rotation += 4; } if (this.game.input.keyboard.isDown(Keyboard.UP)) { this.car...
identifier_body
FakeGame.ts
/// <reference path="../../../Phaser/Game.ts" /> /// <reference path="../../../Phaser/State.ts" /> class FakeGame extends State { constructor(game: Game) { super(game);
private car: Phaser.Sprite; private bigCam: Phaser.Camera; public init() { this.load.image('track', '../../assets/games/f1/track.png'); this.load.image('car', '../../assets/games/f1/car1.png'); this.load.start(); } public create() { this.camera.setBounds(0, 0, t...
}
random_line_split
cucumber.d.ts
// Type definitions for cucumber 0.4.7 // Project: https://github.com/cucumber/cucumber-js // Definitions by: Matt Frantz <https://github.com/mhfrantz/>
export interface StepCallback { (error?: string | Error, result?: any): void; pending(reason?: any): void; fail(failureReason?: Error): void; // This signature should not be necessary, it is equivalent to the first signature above in the degenerate case. // We include it because otherwise bluebi...
// Definitions: https://github.com/borisyankov/DefinitelyTyped declare module cucumber { // TODO: Is there a way to put type safety on the interface of the "this" object in a step definitions file?
random_line_split
plugin_settings.ts
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
let value; if (config.encrypted_value) { value = new EncryptedValue(config.encrypted_value); } else { value = new PlainTextValue(config.value || ""); } return new Configuration(config.key, value, errors); } get value(): string { if (this._value) { return this._value.getVa...
{ errors = config.errors[config.key]; }
conditional_block
plugin_settings.ts
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
(key: string, value: string) { const config = this.findConfiguration(key); if (config) { config.value = value; } else { this.configuration.push(new Configuration(key, new PlainTextValue(value))); } } toJSON(): any { return { plugin_id: this.plugin_id, configuration: this...
setConfiguration
identifier_name
plugin_settings.ts
/* * Copyright 2018 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
} this._value = new PlainTextValue(val); } toJSON() { if (this._value.isEncrypted()) { return { key: this.key, encrypted_value: this.value }; } else { return { key: this.key, value: this.value }; } } } export class PluginSettings extend...
if (val === this._value.getValue()) { return;
random_line_split
wrapper.rs
unsafe { bindings::Gecko_AttrEquals(self.0, namespace.0.as_ptr(), attr.as_ptr(), val.as_ptr(), /* ignoreCase = */ false) } } fn...
h_attr_dash(&se
identifier_name
wrapper.rs
} } fn can_be_fragmented(&self) -> bool { // FIXME(SimonSapin): Servo uses this to implement CSS multicol / fragmentation // Maybe this isn’t useful for Gecko? false } unsafe fn set_can_be_fragmented(&self, _value: bool) { // FIXME(SimonSapin): Servo uses this to imple...
debug!("Setting dirty descendants: {:?}", self);
random_line_split
wrapper.rs
) } } } impl<'ln> NodeInfo for GeckoNode<'ln> { fn is_element(&self) -> bool { use gecko_bindings::structs::nsINode_BooleanFlag; self.0.mBoolFlags & (1u32 << nsINode_BooleanFlag::NodeIsElement as u32) != 0 } fn is_text_node(&self) -> bool { // This is a DOM constant that isn't ...
/// Ensures the element has data, returning the existing data or allocating /// it. /// /// Only safe to call with exclusive access to the element, given otherwise /// it could race to allocate and leak. pub unsafe fn ensure_data(&self) -> &AtomicRefCell<ElementData> { match self.get_data(...
let ptr = self.0.mServoData.get(); if !ptr.is_null() { debug!("Dropping ElementData for {:?}", self); let data = unsafe { Box::from_raw(self.0.mServoData.get()) }; self.0.mServoData.set(ptr::null_mut()); // Perform a mutable borrow of the data in debug buil...
identifier_body
auth.js
var passport = require('passport'); module.exports = { login: function(req, res) { var auth = passport.authenticate('local', function(err, user) { var errorsMessage = ''; if(err)
if (!user) { errorsMessage += 'Incorrect login data'; } if(errorsMessage.length > 0){ res.render('home', { loginErrors: errorsMessage }); return; } req.logIn(user, functio...
{ errorsMessage += 'Could not fetch user'; }
conditional_block
auth.js
var passport = require('passport'); module.exports = { login: function(req, res) { var auth = passport.authenticate('local', function(err, user) { var errorsMessage = ''; if(err) { errorsMessage += 'Could not fetch user'; } if (!user) { ...
else { res.redirect('/unauthorized'); res.end(); } } } };
random_line_split
icon.py
import base64 from jarr.bootstrap import conf, session from jarr.models import Icon from jarr.utils import jarr_get from .abstract import AbstractController class IconController(AbstractController): _db_cls = Icon _user_id_key = None # type: str @staticmethod def _build_from_url(attrs): if...
return obj
session.flush() session.commit()
conditional_block
icon.py
import base64 from jarr.bootstrap import conf, session from jarr.models import Icon from jarr.utils import jarr_get from .abstract import AbstractController class IconController(AbstractController): _db_cls = Icon _user_id_key = None # type: str @staticmethod def _build_from_url(attrs): if...
session.commit() return obj
def delete(self, obj_id, commit=True): obj = self.get(url=obj_id) session.delete(obj) if commit: session.flush()
random_line_split
icon.py
import base64 from jarr.bootstrap import conf, session from jarr.models import Icon from jarr.utils import jarr_get from .abstract import AbstractController class
(AbstractController): _db_cls = Icon _user_id_key = None # type: str @staticmethod def _build_from_url(attrs): if 'url' in attrs and 'content' not in attrs: try: resp = jarr_get(attrs['url'], timeout=conf.crawler.timeout, user_agent=c...
IconController
identifier_name
icon.py
import base64 from jarr.bootstrap import conf, session from jarr.models import Icon from jarr.utils import jarr_get from .abstract import AbstractController class IconController(AbstractController): _db_cls = Icon _user_id_key = None # type: str @staticmethod def _build_from_url(attrs): if...
def update(self, filters, attrs, return_objs=False, commit=True): attrs = self._build_from_url(attrs) return super().update(filters, attrs, return_objs, commit) def delete(self, obj_id, commit=True): obj = self.get(url=obj_id) session.delete(obj) if commit: ...
return super().create(**self._build_from_url(attrs))
identifier_body
websocket_test.py
from tornado.concurrent import Future from tornado import gen from tornado.httpclient import HTTPError from tornado.log import gen_log from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog from tornado.web import Application, RequestHandler from tornado.websocket import WebSocketHandler, ...
'ws://localhost:%d/notfound' % self.get_http_port(), io_loop=self.io_loop) self.assertEqual(cm.exception.code, 404) @gen_test def test_websocket_http_success(self): with self.assertRaises(WebSocketError): yield websocket_connect( 'ws:/...
yield websocket_connect(
random_line_split
websocket_test.py
from tornado.concurrent import Future from tornado import gen from tornado.httpclient import HTTPError from tornado.log import gen_log from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog from tornado.web import Application, RequestHandler from tornado.websocket import WebSocketHandler, ...
def on_message(self, message): self.write_message(message, isinstance(message, bytes)) def on_close(self): self.close_future.set_result(None) class NonWebSocketHandler(RequestHandler): def get(self): self.write('ok') class WebSocketTest(AsyncHTTPTestCase): def get_app(self...
self.close_future = close_future
identifier_body
websocket_test.py
from tornado.concurrent import Future from tornado import gen from tornado.httpclient import HTTPError from tornado.log import gen_log from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog from tornado.web import Application, RequestHandler from tornado.websocket import WebSocketHandler, ...
(self, close_future): self.close_future = close_future def on_message(self, message): self.write_message(message, isinstance(message, bytes)) def on_close(self): self.close_future.set_result(None) class NonWebSocketHandler(RequestHandler): def get(self): self.write('ok') ...
initialize
identifier_name
lib.rs
//! # Overview //! //! <b>cuckoo-miner</b> is a Rust wrapper around John Tromp's Cuckoo Miner //! C implementations, intended primarily for use in the Grin MimbleWimble //! blockhain development project. However, it is also suitable for use as //! a standalone miner or by any other project needing to use the //! cuck...
// See the License for the specific language governing permissions and // limitations under the License.
random_line_split
package.py
import ckan.controllers.package as package import ckan.lib.dictization.model_dictize as model_dictize import ckan.model as model from ckan.common import c class MapactionPackageController(package.PackageController): def groups(self, id): q = model.Session.query(model.Group) \ .filter(model....
'auth_user_obj': c.userobj, 'use_cache': False} group_list = model_dictize.group_list_dictize(groups, context) c.event_dropdown = [[group['id'], group['display_name']] for group in group_list] return super(MapactionPackageController, self).groups...
context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True,
random_line_split
package.py
import ckan.controllers.package as package import ckan.lib.dictization.model_dictize as model_dictize import ckan.model as model from ckan.common import c class
(package.PackageController): def groups(self, id): q = model.Session.query(model.Group) \ .filter(model.Group.is_organization == False) \ .filter(model.Group.state == 'active') groups = q.all() ''' package = c.get('package') if package: ...
MapactionPackageController
identifier_name
package.py
import ckan.controllers.package as package import ckan.lib.dictization.model_dictize as model_dictize import ckan.model as model from ckan.common import c class MapactionPackageController(package.PackageController):
c.event_dropdown = [[group['id'], group['display_name']] for group in group_list] return super(MapactionPackageController, self).groups(id)
def groups(self, id): q = model.Session.query(model.Group) \ .filter(model.Group.is_organization == False) \ .filter(model.Group.state == 'active') groups = q.all() ''' package = c.get('package') if package: groups = set(groups) - set(packag...
identifier_body
autoscale_setting_resource_paged.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(Paged): """ A paging container for iterating over a list of :class:`AutoscaleSettingResource <azure.mgmt.monitor.models.AutoscaleSettingResource>` object """ _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[AutoscaleSettingR...
AutoscaleSettingResourcePaged
identifier_name
autoscale_setting_resource_paged.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
super(AutoscaleSettingResourcePaged, self).__init__(*args, **kwargs)
identifier_body
autoscale_setting_resource_paged.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
""" A paging container for iterating over a list of :class:`AutoscaleSettingResource <azure.mgmt.monitor.models.AutoscaleSettingResource>` object """ _attribute_map = { 'next_link': {'key': 'nextLink', 'type': 'str'}, 'current_page': {'key': 'value', 'type': '[AutoscaleSettingResource]'...
class AutoscaleSettingResourcePaged(Paged):
random_line_split
pyunit_automl_regression.py
from __future__ import print_function from __future__ import print_function import sys, os sys.path.insert(1, os.path.join("..","..","..","..")) import h2o from h2o.automl import H2OAutoML from tests import pyunit_utils as pu from _automl_utils import import_dataset def test_default_automl_with_regression_task(): ...
family='poisson', ), exclude_algos=['StackedEnsemble'], max_runtime_secs=60, seed=1) aml.train(y=ds.target, training_frame=ds.train) model_names = [aml.leaderboard[i, 0] for i in r...
algo_parameters=dict( distribution='poisson',
random_line_split
pyunit_automl_regression.py
from __future__ import print_function from __future__ import print_function import sys, os sys.path.insert(1, os.path.join("..","..","..","..")) import h2o from h2o.automl import H2OAutoML from tests import pyunit_utils as pu from _automl_utils import import_dataset def
(): ds = import_dataset('regression') aml = H2OAutoML(max_models=2, project_name='aml_regression') aml.train(y=ds.target, training_frame=ds.train, validation_frame=ds.valid, leaderboard_frame=ds.test) print(aml.leader) print(aml.leaderboard) assert aml.leaderboard.columns ==...
test_default_automl_with_regression_task
identifier_name
pyunit_automl_regression.py
from __future__ import print_function from __future__ import print_function import sys, os sys.path.insert(1, os.path.join("..","..","..","..")) import h2o from h2o.automl import H2OAutoML from tests import pyunit_utils as pu from _automl_utils import import_dataset def test_default_automl_with_regression_task(): ...
except: h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "false")) pu.run_tests([ test_default_automl_with_regression_task, test_workaround_for_distribution, ])
m = h2o.get_model(mn) dist = m.params['distribution'] if 'distribution' in m.params else m.params['family'] if 'family' in m.params else None print("{}: distribution = {}".format(mn, dist))
conditional_block
pyunit_automl_regression.py
from __future__ import print_function from __future__ import print_function import sys, os sys.path.insert(1, os.path.join("..","..","..","..")) import h2o from h2o.automl import H2OAutoML from tests import pyunit_utils as pu from _automl_utils import import_dataset def test_default_automl_with_regression_task(): ...
def test_workaround_for_distribution(): try: h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "true")) ds = import_dataset('regression') aml = H2OAutoML(project_name="py_test", algo_parameters=dict( ...
ds = import_dataset('regression') aml = H2OAutoML(max_models=2, project_name='aml_regression') aml.train(y=ds.target, training_frame=ds.train, validation_frame=ds.valid, leaderboard_frame=ds.test) print(aml.leader) print(aml.leaderboard) assert aml.leaderboard.columns == ["model...
identifier_body
mem_map.rs
const BOOT_ROM_START: u16 = 0x0000; const BOOT_ROM_END: u16 = 0x00FF; const CART_ROM_START: u16 = 0x0000; const CART_ROM_END: u16 = 0x7FFF; const CART_ENTRY_POINT: u16 = 0x0100; const CART_HEADER_START: u16 = 0x0100; const CART_HEADER_END: u16 = 0x014F; const CART_FIXED_START: u16 = 0x0150; const CART_FIXED_END: u16...
pub fn ram_size(byte: u8) -> &'static str { match byte { 0x00 => "None", 0x01 => "2 KBytes", 0x02 => "8 Kbytes", 0x03 => "32 KBytes (4 banks of 8KBytes each)", 0x04 => "128 KBytes (16 banks of 8KBytes each)", 0x05 => "64 KBytes (8 banks of 8KBytes each)", _ ...
{ match byte { 0x00 => "32KByte (no ROM banking)", 0x01 => "64KByte (4 banks)", 0x02 => "128KByte (8 banks)", 0x03 => "256KByte (16 banks)", 0x04 => "512KByte (32 banks)", 0x05 => "1MByte (64 banks)", 0x06 => "2MByte (128 banks)", 0x07 => "4MByte (256 ...
identifier_body
mem_map.rs
const BOOT_ROM_START: u16 = 0x0000; const BOOT_ROM_END: u16 = 0x00FF; const CART_ROM_START: u16 = 0x0000; const CART_ROM_END: u16 = 0x7FFF; const CART_ENTRY_POINT: u16 = 0x0100; const CART_HEADER_START: u16 = 0x0100; const CART_HEADER_END: u16 = 0x014F; const CART_FIXED_START: u16 = 0x0150; const CART_FIXED_END: u16...
{ BootRom(u16), CartHeader(u16), CartFixed(u16), CartSwitch(u16), VideoRam(u16), SoundRegister(u16), HighRam(u16), } pub fn cartridge_type(byte: u8) -> &'static str { match byte { 0x00 => "ROM ONLY", 0x01 => "MBC1", 0x02 => "MBC1+RAM", 0x03 => "MBC1+RAM+...
Addr
identifier_name
mem_map.rs
const BOOT_ROM_START: u16 = 0x0000; const BOOT_ROM_END: u16 = 0x00FF; const CART_ROM_START: u16 = 0x0000; const CART_ROM_END: u16 = 0x7FFF; const CART_ENTRY_POINT: u16 = 0x0100; const CART_HEADER_START: u16 = 0x0100; const CART_HEADER_END: u16 = 0x014F; const CART_FIXED_START: u16 = 0x0150; const CART_FIXED_END: u16...
pub fn rom_size(byte: u8) -> &'static str { match byte { 0x00 => "32KByte (no ROM banking)", 0x01 => "64KByte (4 banks)", 0x02 => "128KByte (8 banks)", 0x03 => "256KByte (16 banks)", 0x04 => "512KByte (32 banks)", 0x05 => "1MByte (64 banks)", 0x06 => "2MByte ...
0xFF => "HuC1+RAM+BATTERY", _ => panic!("Unknown Cartridge Type"), } }
random_line_split
load_more.py
def action_comment_load_more(context, action, entity_type, entity_id, last_id, parent_id, **args):
'columns' : ['count(id)'], 'where' : [ ['container_id', container_id], ['id', '<', int(last_id)], # load previous ['parent_id', parent_id], ['status', 1], ], }).execute() if cursor.rowcount >= 0: total = int(cursor.fetchone()[0]) more_id = '_'.join(('more-commens', entity_type, ...
try: entity = IN.entitier.load_single(entity_type, int(entity_id)) if not entity: return output = Object() db = IN.db connection = db.connection container_id = IN.commenter.get_container_id(entity) # TODO: paging # get total total = 0 limit = 10 cursor = db.select({ 'table' : 'enti...
identifier_body
load_more.py
def action_comment_load_more(context, action, entity_type, entity_id, last_id, parent_id, **args): try: entity = IN.entitier.load_single(entity_type, int(entity_id)) if not entity: return output = Object() db = IN.db connection = db.connection container_id = IN.commenter.get_container_id(entity)...
comments = IN.entitier.load_multiple('Comment', ids) for id, comment in comments.items(): comment.weight = id # keep asc order output.add(comment) remaining = total - limit if remaining > 0 and last_id > 0: output.add('TextDiv', { 'id' : more_id, 'value' : str(remaining)...
cursor = db.select({ 'table' : 'entity.comment', 'columns' : ['id'], 'where' : [ ['container_id', container_id], ['id', '<', int(last_id)], ['parent_id', parent_id], # add main level comments only ['status', 1], ], 'order' : {'created' : 'DESC'}, 'limit' : limit, }).exe...
conditional_block
load_more.py
def
(context, action, entity_type, entity_id, last_id, parent_id, **args): try: entity = IN.entitier.load_single(entity_type, int(entity_id)) if not entity: return output = Object() db = IN.db connection = db.connection container_id = IN.commenter.get_container_id(entity) # TODO: paging # get...
action_comment_load_more
identifier_name
load_more.py
def action_comment_load_more(context, action, entity_type, entity_id, last_id, parent_id, **args): try: entity = IN.entitier.load_single(entity_type, int(entity_id)) if not entity: return output = Object() db = IN.db connection = db.connection container_id = IN.commenter.get_container_id(entity)...
}) #if not output: #output.add(type = 'TextDiv', data = {}) output = {more_id : output} context.response = In.core.response.PartialResponse(output = output) except: IN.logger.debug()
'data-href' : ''.join(('/comment/more/!Content/', str(entity_id), '/', str(last_id), '/', str(parent_id))) }, 'weight' : -1,
random_line_split
ent.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Serialize, Deserialize)] pub struct PutRequest { pub blobs: Vec<Vec<u8>>, } #[derive(Serialize, Deserialize)] pub struct GetRequest { pub items: Vec<GetItem>, } #[derive(Serialize, Deserialize)] pub struct GetItem { pub root: St...
{ pub api_url: String, } impl EntClient { pub async fn upload_blob(&self, content: &[u8]) -> Result<(), Box<dyn std::error::Error>> { let req = PutRequest { blobs: vec![content.to_vec()], }; self.upload_blobs(&req).await?; Ok(()) } pub async fn upload_blobs...
EntClient
identifier_name
ent.rs
use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Serialize, Deserialize)] pub struct PutRequest { pub blobs: Vec<Vec<u8>>, } #[derive(Serialize, Deserialize)] pub struct GetRequest { pub items: Vec<GetItem>, } #[derive(Serialize, Deserialize)] pub struct GetItem { pub root: St...
} pub async fn upload_blobs(&self, req: &PutRequest) -> Result<(), Box<dyn std::error::Error>> { let req_json = serde_json::to_string(&req)?; reqwasm::http::Request::post(&format!("{}/api/v1/blobs/put", self.api_url)) .body(req_json) .send() .await ...
self.upload_blobs(&req).await?; Ok(())
random_line_split
file_path_generator.py
# Copyright 2018-present Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
return path depth = weighted_choice(self._package_depths) path, parent_dir = self._generate_path( "//", self._root, depth, self._sizes_by_depth, self._component_generator ) directory = {self.BUILD_FILE_NAME.lower(): None} parent_dir[os.path.basename(path)...
self._last_package_path = None
conditional_block
file_path_generator.py
# Copyright 2018-present Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
return path, directory def _generate_name(self, directory, generator, extension=None): for i in range(1000): name = generator.generate_string() if extension is not None: name += extension if ( name.lower() not in directory ...
elif key_found: del self._available_directories[key]
random_line_split