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 |
|---|---|---|---|---|
provision_utils.go | .CloudWatchLogsLambdaEventSource
default:
return "", fmt.Errorf("Unsupported principal for IAM role creation: %s", awsPrincipalName)
}
// What's the stable IAMRoleName?
resourceBaseName := fmt.Sprintf("CustomResource%sIAMRole", awsPrincipalToService(awsPrincipalName))
stableRoleName := CloudFormationResourceNam... | createNewPythonProxyEntry | identifier_name | |
vk.rs | log_dims: [u32; 2],
}
impl VulkanBackend {
fn window_size_dependent_setup(&self) -> Result<(Arc<(dyn GraphicsPipelineAbstract + Send + Sync)>,
Vec<Arc<dyn FramebufferAbstract + Send + Sync>>),
Box<dyn Error>>{
... | () -> Result<Self, Box<dyn Error>> {
println!("Beginning Vulkan setup...");
let instance = {
let extensions = vulkano_win::required_extensions();
Instance::new(None, &extensions, None)
}?;
// We then choose which physical device to use.
//
// In a... | new | identifier_name |
vk.rs | )
.build_vk_surface(&events_loop, instance.clone())?;
let window = surface.window();
let queue_family = physical.queue_families().find(|&q| {
q.supports_graphics() && surface.is_supported(q).unwrap_or(false)
}).ok_or(SimpleError::new("Found no suitable devices"))?;
... | random_line_split | ||
ovs_configurator.py | ") as cfg:
config = yaml.load(cfg)
cmd = ["ssh-keygen", "-y", "-f", "/dev/stdin"]
key = config["ssh"]["private-key"]
public_key = subprocess.run(
cmd, stdout=subprocess.PIPE, input=key.encode("utf-8")
).stdout.decode("utf-8")
config["ssh"]["public-key"] = public_key
return confi... | for disk in disks:
disk["mounted"] = is_mounted(disk)
disk["size"] = float(disk["size"]) / (1024 ** 3)
print(disk["name"] + ": " + str(disk["size"]))
if disk["name"] == "sr0":
disk["type"] = "cdrom"
if disk["size"] == float("60.0"):
... | disks = json.loads(res.stdout)["blockdevices"] | random_line_split |
ovs_configurator.py | ") as cfg:
config = yaml.load(cfg)
cmd = ["ssh-keygen", "-y", "-f", "/dev/stdin"]
key = config["ssh"]["private-key"]
public_key = subprocess.run(
cmd, stdout=subprocess.PIPE, input=key.encode("utf-8")
).stdout.decode("utf-8")
config["ssh"]["public-key"] = public_key
return confi... |
@click.command()
@click.option(
"--config_path", default="system-config.yaml", help="Path to system-config"
)
def main(config_path):
config = prepare_config(config_path)
env_type = config["environment"]["type"]
loader = jinja2.FileSystemLoader("./templates/{}".format(env_type))
nodes_ips = {}
... | nodes = []
for node in config["nodes"]:
if role in node["roles"]:
nodes.append(node)
return nodes | identifier_body |
ovs_configurator.py | ") as cfg:
config = yaml.load(cfg)
cmd = ["ssh-keygen", "-y", "-f", "/dev/stdin"]
key = config["ssh"]["private-key"]
public_key = subprocess.run(
cmd, stdout=subprocess.PIPE, input=key.encode("utf-8")
).stdout.decode("utf-8")
config["ssh"]["public-key"] = public_key
return confi... |
osds[cpunode["ip"]] = disks
for disk in useabledisks:
disks[disk["name"]] = 2
elif backend["name"] in ("backend01", "backend02"):
# cachecbakcend01 takes first half of the large ssd on cpu nodes
osds = {}
backend["osds"] = ... | useabledisks = useabledisks[
int(cachebackendcount / 2) : cachebackendcount
] | conditional_block |
ovs_configurator.py | ") as cfg:
config = yaml.load(cfg)
cmd = ["ssh-keygen", "-y", "-f", "/dev/stdin"]
key = config["ssh"]["private-key"]
public_key = subprocess.run(
cmd, stdout=subprocess.PIPE, input=key.encode("utf-8")
).stdout.decode("utf-8")
config["ssh"]["public-key"] = public_key
return confi... | (config_path):
config = prepare_config(config_path)
env_type = config["environment"]["type"]
loader = jinja2.FileSystemLoader("./templates/{}".format(env_type))
nodes_ips = {}
nodes = []
storage_nodes = get_nodes(config, "storage")
cpu_nodes = get_nodes(config, "cpu")
cpucount = specs["n... | main | identifier_name |
windows.rs | st) {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"Poll instance is dead.",
));
}
ffi::create_io_completion_port(soc.as_raw_socket(), self.completion_port, 0)?;
let op = ffi::Operation::new(token);
soc.operations.push_b... |
let mut overlapped = ffi::WSAOVERLAPPED::zeroed();
ffi::post_queued_completion_status(self.completion_port, 0, 0, &mut overlapped)?;
Ok(())
}
}
// possible Arc<InnerSelector> needed
#[derive(Debug)]
pub struct Selector {
completion_port: isize,
}
impl Selector {
pub fn new() -> io... | {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"Poll instance is dead.",
));
} | conditional_block |
windows.rs | st) {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"Poll instance is dead.",
));
}
ffi::create_io_completion_port(soc.as_raw_socket(), self.completion_port, 0)?;
let op = ffi::Operation::new(token);
soc.operations.push_b... | (token: usize) -> Self {
Operation {
wsaoverlapped: WSAOVERLAPPED::zeroed(),
token,
}
}
}
// You can find most of these here: https://docs.microsoft.com/en-us/windows/win32/winprog/windows-data-types
/// The HANDLE type is actually a `*mut c_v... | new | identifier_name |
windows.rs | can't express that in Rust so it's much easier for us to treat
/// this as an isize instead;
pub type HANDLE = isize;
pub type BOOL = bool;
pub type WORD = u16;
pub type DWORD = u32;
pub type ULONG = u32;
pub type PULONG = *mut ULONG;
pub type ULONG_PTR = *mut usize;
pub type PULONG... | {
let mut ul_num_entries_removed: u32 = 0;
// can't coerce directly to *mut *mut usize and cant cast `&mut` as `*mut`
// let completion_key_ptr: *mut &mut usize = completion_key_ptr;
// // but we can cast a `*mut ...`
// let completion_key_ptr: *mut *mut usize = completion_key_pt... | identifier_body | |
windows.rs | Cst) {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"Poll instance is dead.",
));
}
ffi::create_io_completion_port(soc.as_raw_socket(), self.completion_port, 0)?;
let op = ffi::Operation::new(token);
soc.operations.push_... | pub const INFINITE: u32 = 0xFFFFFFFF;
#[link(name = "Kernel32")]
extern "stdcall" {
// https://docs.microsoft.com/en-us/windows/win32/fileio/createiocompletionport
fn CreateIoCompletionPort(
filehandle: HANDLE | random_line_split | |
igor_test.go | }
// TableName returns the table name associated with the structure
func (NestTable) TableName() string {
return "nest_table"
}
func init() {
if db, e = igor.Connect("user=donotexists dbname=wat sslmode=error"); e == nil {
panic("Connect with a wrong connection string should fail, but succeeded")
}
connection... |
func TestModelCreateUpdatesSelectDelete(t *testing.T) {
if db.Create(&User{}) == nil {
t.Error("Create an user without assign a value to fields that have no default should fail")
}
user := createUser()
user.Profile = createProfile(user.Counter)
// First
var p Profile
if e = db.First(&p, uint64(99)); e == ... | {
row := NestTable{}
row.ID = 1
row.SliceOfInt64 = []int64{1, 2}
row.SliceOfString = []string{"slice", "support yeah"}
if e = db.Create(&row); e != nil {
t.Errorf("Inserting a new row with a type that uses a nested struct should be possible. But got %v", e)
}
} | identifier_body |
igor_test.go | }
// TableName returns the table name associated with the structure
func (NestTable) | () string {
return "nest_table"
}
func init() {
if db, e = igor.Connect("user=donotexists dbname=wat sslmode=error"); e == nil {
panic("Connect with a wrong connection string should fail, but succeeded")
}
connectionString := "host=localhost port=5432 user=igor dbname=igor password=igor sslmode=disable connect... | TableName | identifier_name |
igor_test.go |
Unless required by applicable law or agreed to in writing, software
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.
*/
package ig... | You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 | random_line_split | |
igor_test.go | Galeone",
Email: "please validate the @email . com",
Gender: true,
BirthDate: time.Now(),
}
if e = db.Create(&user); e != nil {
panic(fmt.Sprintf("Create(&user) filling fields having no default should work, but got: %s\n", e.Error()))
}
return user
}
// createProfile creates the profile for a test ... | {
t.Errorf("Expected to receive 4 notifications, but counted only: %d\n", count)
} | conditional_block | |
strobe.rs | STROBEv");
st_buf[13..18].copy_from_slice(STROBE_VERSION.as_bytes());
let mut st = AlignedKeccakState(st_buf);
keccakf_u8(&mut st);
let mut strobe = Strobe {
st,
sec,
rate,
pos: 0,
pos_begin: 0,
is_receiver: None,
... | {
// Special case of case below. This is PRF. Use `squeeze` instead of `exchange`.
self.squeeze(data);
} | conditional_block | |
strobe.rs | {
#[doc = $doc_str]
pub fn $name(&mut self, data: &mut [u8], more: bool) {
let flags = $flags;
self.operate(flags, data, more);
}
#[doc = $doc_str]
pub fn $meta_name(&mut self, data: &mut [u8], more: bool) {
let flags = $flags | OpFlags::M;
... | self.operate_no_mutate(flags, data, more);
}
#[doc = $doc_str]
pub fn $meta_name(&mut self, data: &[u8], more: bool) {
let flags = $flags | OpFlags::M;
self.operate_no_mutate(flags, data, more);
}
};
}
impl Strobe {
/// Makes a new `Strobe` o... | #[doc = $doc_str]
pub fn $name(&mut self, data: &[u8], more: bool) {
let flags = $flags; | random_line_split |
strobe.rs | {
#[doc = $doc_str]
pub fn $name(&mut self, data: &mut [u8], more: bool) {
let flags = $flags;
self.operate(flags, data, more);
}
#[doc = $doc_str]
pub fn $meta_name(&mut self, data: &mut [u8], more: bool) {
let flags = $flags | OpFlags::M;
... | (&mut self, data: &[u8]) {
for b in data {
self.st.0[self.pos] ^= *b;
self.pos += 1;
if self.pos == self.rate {
self.run_f();
}
}
}
/// XORs the given data into the state, then sets the data equal the state. This is a special
... | absorb | identifier_name |
strobe.rs | ` in that we assume we've been given all zeros as
/// input, and like `overwrite` in that we do not mutate (or take) any input.
fn zero_state(&mut self, mut bytes_to_zero: usize) {
static ZEROS: [u8; 8 * KECCAK_BLOCK_SIZE] = [0u8; 8 * KECCAK_BLOCK_SIZE];
// Do the zero-writing in chunks
... | {
self.generalized_ratchet(num_bytes_to_zero, more, /* is_meta */ true)
} | identifier_body | |
serve_core.py | .seek(0, os.SEEK_END)
size = f.tell()
end_pos = self._search_backwards(f, f.tell(), END_DELIM)
if end_pos == -1:
print("Cannot find end delimiter:", END_DELIM, file=sys.stderr)
sys.exit(1)
start_pos = self._search_backwards(f, end_pos, STAR... | return binascii.unhexlify(s) | identifier_body | |
serve_core.py | ._search_backwards(f, f.tell(), END_DELIM)
if end_pos == -1:
print("Cannot find end delimiter:", END_DELIM, file=sys.stderr)
sys.exit(1)
start_pos = self._search_backwards(f, end_pos, START_DELIM)
if start_pos == -1:
print("Cannot find ... | send_nack | identifier_name | |
serve_core.py | "]
self.pcTaskName = e["n"]
self.eCurrentState = e["st"]
self.uxCurrentPriority = e["cpri"]
self.uxBasePriority = e["bpri"]
self.pxStackBase = e["sb"]
self.pxTopOfStack = e["sp"]
if "regs" in e:
self.regs = base64.decodebytes(bytes(e["regs"]["data"], "... | self.send_str("1")
elif pkt == "qAttached":
self.send_str("1")
elif pkt == "qSymbol::":
self.send_str("OK")
elif pkt == "qfThreadInfo":
if core.tasks:
self.send_str("m%s" % ",".join("%016x" % t f... | if t:
self.send_str("QC%016x" % t)
else: | random_line_split |
serve_core.py | "]
self.pcTaskName = e["n"]
self.eCurrentState = e["st"]
self.uxCurrentPriority = e["cpri"]
self.uxBasePriority = e["bpri"]
self.pxStackBase = e["sb"]
self.pxTopOfStack = e["sp"]
if "regs" in e:
self.regs = base64.decodebytes(bytes(e["regs"]["data"], "... |
elif pkt == "qfThreadInfo":
if core.tasks:
self.send_str("m%s" % ",".join("%016x" % t for t in core.tasks))
else:
self.send_str("l")
elif pkt == "qsThreadInfo":
self.send_str("l")
elif pkt.start... | self.send_str("OK") | conditional_block |
methods.ts | ')
let account = getAccount(this.userId)
check(json, Match.ObjectIncluding({collection_name : String}))
Report_Data.insert({account_id: account._id, ...json})
},
/*
Used to fetch distinct collection names belonging to an account
TODO: restrict to user roles
*/
Fetch_Collection_Names: function() {
enfor... |
if(column.formulaId) {
type = 'formula'
}
return { index: i, id: uuidv4(), type, property, propertyValue, value }
})
}
// generates rows within a table, if collection driven
const generateRows = (table: Table) => {
check(table, {id : String, title : String, type : String,
columns : ... | {
type = 'property'
value = doc[property]
} | conditional_block |
methods.ts | Editor')
let account = getAccount(this.userId)
check(json, Match.ObjectIncluding({collection_name : String}))
Report_Data.insert({account_id: account._id, ...json})
},
/*
Used to fetch distinct collection names belonging to an account
TODO: restrict to user roles
*/
Fetch_Collection_Names: function() {
... | id: uuidv4(),
cells: generateCells(table.columns, document)
}))
} else return table.rows
}
const createRowsInTable = () => {
// run for each table, ensuring proper amount of rows
report?.tables.forEach((table: Table) => {
table.rows = <Array<TableRow>> generateRows(table)
return tabl... | const collection = performQuery(table.collection)
return collection.map((document: ReportData) => ({ | random_line_split |
string_parser.py | text = rega_style.sub('', text)
text = rega_html.sub('', text)
return text
def translit(text: str):
"""Транслит текста с русского в латиницу
:param text: текст для транслита
"""
if not text:
return ''
alphabet = string.ascii_lowercase
rus = ('абвгдеёжзийклмнопрстуфхцчшщ... | if summa_len <= 3:
if kop > 0:
return summa_str
return rub
| conditional_block | |
string_parser.py | = None
# -----------------------------------------
# Значения уже могут содержаться в q_string
# -----------------------------------------
if var in q_string:
q_vars[var] = q_string[var]
# --------
# GET/POST
# --------
if method.get(var):
... | digit = float(digit)
except ValueError:
digit = 0
try:
digit = int(digit)
except ValueError:
digit = 0
digit_str = str(digit)
summa = summa_format(digit)
if ' ' in summa:
digits = summa.split(' ')
else:
digits = [summa, ]
digit... | if not type(digit) == int:
try: | random_line_split |
string_parser.py | None
# -----------------------------------------
# Значения уже могут содержаться в q_string
# -----------------------------------------
if var in q_string:
q_vars[var] = q_string[var]
# --------
# GET/POST
# --------
if method.get(var):
... | (alphabet, ))
result = ''
for item in text:
letter = ''
item = item.lower()
if item in rus:
ind = rus.index(item)
letter = eng[ind]
else:
if item in chars:
letter = item
result += letter
return result
def digit_to_s... | ascii_lowercase
rus = ('абвгдеёжзийклмнопрстуфхцчшщъыьэюя №')
eng = ('a', 'b', 'v', 'g', 'd', 'e', 'yo', 'j', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'shh', '', 'y', '', 'e', 'yu', 'ya', '-', '-')
chars = ('-0123456789_%s' % | identifier_body |
string_parser.py | """
if not domain:
return ''
if '://' in domain:
domain = domain.split('://')[1]
if '?' in domain:
domain = domain.split("?")[0]
if '/' in domain:
domain = domain.split('/')[0]
if '#' in domain:
domain = domain.split('#')[0]
domain = domain.encode('idna... | ой в punycode
| identifier_name | |
main.rs | { "add" } else { "remove" });
let address: String = format!("{}:{}", &server.ip, &server.port);
let cmd: String = format!("whitelist {} {}", act, mc_user.name);
let res = retry(Fixed::from_millis(2000).take(10), || {
match rcon::Connection::connect(&address, &server.pass) {
Ok(mut val) => is... | {
// whack
if msg.contains("discord_id") {
response = "You have already linked your account.\nYou may only have one linked account at a time.\nTo unlink, please type `!unlink`";
} else if msg.contains("minecraft_uuid") {
response = "Somebody has linked this Minecraf... | conditional_block | |
main.rs | _member_data_if_available: Option<Member>) {
let discord_vals: DiscordConfig = get_config().discord;
if &discord_vals.guild_id == guild.as_u64() {
println!("{} is leaving Mooncord", user.name);
rem_account(*user.id.as_u64());
}
}
}
lazy_static! {
static ref POOL: Pool<ConnectionManager<M... | (_discord_id: u64) -> Option<MinecraftUser> {
use self::schema::minecrafters::dsl::*;
let connection = POOL.get().unwrap();
let res = minecrafters.filter(discord_id.eq(_discord_id))
.load::<FullMCUser>(&connection)
.expect("Error loading minecraft user");
if res.len() < 1 {
println!("[WARN] NO PL... | sel_mc_account | identifier_name |
main.rs | _member_data_if_available: Option<Member>) {
let discord_vals: DiscordConfig = get_config().discord;
if &discord_vals.guild_id == guild.as_u64() {
println!("{} is leaving Mooncord", user.name);
rem_account(*user.id.as_u64());
}
}
}
lazy_static! {
static ref POOL: Pool<ConnectionManager<M... | );
// Start listening for events, single shard. Shouldn't need more than one shard
if let Err(why) = client.start() {
println!("An error occurred while running the client: {:?}", why);
}
}
fn add_accounts(discordid: u64, mc_user: &MinecraftUser) -> QueryResult<usize> {
use self::schema::minecrafters;
... | client.with_framework(
StandardFramework::new()
.configure(|c| c.prefix("!"))
.group(&GENERAL_GROUP), | random_line_split |
address_transactions.go | recordIterator
err error
}
func newTxIter(rw *blockReadWriter, iter *recordIterator) *txIter {
return &txIter{rw: rw, iter: iter}
}
func (i *txIter) Transaction() (proto.Transaction, bool, error) {
value, err := i.iter.currentRecord()
if err != nil {
return nil, false, err
}
var meta txMeta
err = meta.unmar... |
if err := at.persist(); err != nil {
return err
}
at.params.providesData = true
return nil
}
func (at *addressTransactions) offsetFromBytes(offsetBytes []byte) uint64 {
return binary.BigEndian.Uint64(offsetBytes)
}
func (at *addressTransactions) handleRecord(record []byte) error {
key := record[:proto.Addres... | {
// Already provides.
return nil
} | conditional_block |
address_transactions.go |
var (
fileSizeKeyBytes = []byte{txsByAddressesFileSizeKeyPrefix}
)
type txMeta struct {
offset uint64
failed bool
}
func (m *txMeta) bytes() []byte {
buf := make([]byte, txMetaSize)
binary.BigEndian.PutUint64(buf, m.offset)
buf[8] = 0
if m.failed {
buf[8] = 1
}
return buf
}
func (m *txMeta) unmarshal(dat... | maxEmsortMem = 200 * 1024 * 1024 // 200 MiB.
txMetaSize = 8 + 1
) | random_line_split | |
address_transactions.go | recordIterator
err error
}
func newTxIter(rw *blockReadWriter, iter *recordIterator) *txIter {
return &txIter{rw: rw, iter: iter}
}
func (i *txIter) | () (proto.Transaction, bool, error) {
value, err := i.iter.currentRecord()
if err != nil {
return nil, false, err
}
var meta txMeta
err = meta.unmarshal(value)
if err != nil {
return nil, false, err
}
tx, err := i.rw.readTransactionByOffset(meta.offset)
if err != nil {
return nil, false, err
}
return t... | Transaction | identifier_name |
address_transactions.go | recordIterator
err error
}
func newTxIter(rw *blockReadWriter, iter *recordIterator) *txIter {
return &txIter{rw: rw, iter: iter}
}
func (i *txIter) Transaction() (proto.Transaction, bool, error) {
value, err := i.iter.currentRecord()
if err != nil {
return nil, false, err
}
var meta txMeta
err = meta.unmar... | return at.stor.addRecordBytes(newRecord[:proto.AddressIDSize], newRecord[proto.AddressIDSize:])
}
if _, err := at.addrTransactionsBuf.Write(newRecord); err != nil {
return err
}
return nil
}
func (at *addressTransactions) newTransactionsByAddrIterator(addr proto.Address) (*txIter, error) {
if !at.params.prov... | {
if at.rw.offsetLen != 8 {
return errors.New("unsupported meta length")
}
newRecord := make([]byte, addrTxRecordSize)
blockNum, err := at.stateDB.newestBlockIdToNum(blockID)
if err != nil {
return err
}
copy(newRecord[:proto.AddressIDSize], addr.ID().Bytes())
pos := proto.AddressIDSize
info, err := at.rw.... | identifier_body |
mod.rs | exactly 3 rows fixed at compile-time and the same number of columns, but we want the
//! number of columns to vary. One way to do this is to use `proptest` combinators in combination
//! with [matrix](fn.matrix.html) as follows:
//!
//! ```
//! use nalgebra::{Dyn, OMatrix, Const};
//! use nalgebra::proptest::matrix;
/... | /// use proptest::prelude::*;
///
/// proptest! {
/// # /*
/// #[test]
/// # */
/// fn my_test(a in matrix(0 .. 5i32, Const::<3>, 0 ..= 5)) {
/// // Let's make sure we've got the correct type first
/// let a: OMatrix<_, Const::<3>, Dyn> = a;
/// prop_assert!(a.nrows() == 3);
/// ... | /// ```
/// use nalgebra::proptest::matrix;
/// use nalgebra::{OMatrix, Const, Dyn}; | random_line_split |
mod.rs | 3 rows fixed at compile-time and the same number of columns, but we want the
//! number of columns to vary. One way to do this is to use `proptest` combinators in combination
//! with [matrix](fn.matrix.html) as follows:
//!
//! ```
//! use nalgebra::{Dyn, OMatrix, Const};
//! use nalgebra::proptest::matrix;
//! use p... |
}
impl From<RangeInclusive<usize>> for DimRange<Dyn> {
fn from(range: RangeInclusive<usize>) -> Self {
DimRange::from(Dyn(*range.start())..=Dyn(*range.end()))
}
}
impl<D: Dim> DimRange<D> {
/// Converts the `DimRange` into an instance of `RangeInclusive`.
pub fn to_range_inclusive(&self) -> R... | {
DimRange(range)
} | identifier_body |
mod.rs | //! }
//! }
//!
//! # fn main() { test_dynamic(); test_static_and_mixed(); test_vectors(); }
//! ```
//!
//! While this may be convenient, the default strategies for built-in types in `proptest` can
//! generate *any* number, including integers large enough to easily lead to overflow when used in
//! matrix operati... | default | identifier_name | |
probe_reports.rs | , Error>>,
dur: Duration,
timeout_result: Error,
) -> Result<R, Error> {
let (tx, rx) = futures::channel::oneshot::channel();
std::thread::spawn(move || {
std::thread::sleep(dur);
let _ = tx.send(timeout_result);
});
match select(fut, rx).await {
Either::Left((r, _)) => r... |
}
if let Some(node_links) = result.links {
for link in node_links.iter() {
if let Some(source) = link.source {
if node_id != source {
failure::bail!("Invalid source node id {:?} from {:?}", source, node_id);
}
... | {
peer_connections.extend(node_peer_connections.into_iter());
} | conditional_block |
probe_reports.rs | <R, Error>>,
dur: Duration,
timeout_result: Error,
) -> Result<R, Error> {
let (tx, rx) = futures::channel::oneshot::channel();
std::thread::spawn(move || {
std::thread::sleep(dur);
let _ = tx.send(timeout_result);
});
match select(fut, rx).await {
Either::Left((r, _)) =>... | (&mut self, key: &str, value: &str) -> &mut Self {
self.set_value(key, Attr::HTML(value.to_string()))
}
fn set_bool(&mut self, key: &str, value: bool) -> &mut Self {
self.set_value(key, Attr::Bool(value))
}
fn render(self) -> String {
let mut out = String::new();
for (k... | set_html | identifier_name |
probe_reports.rs | <R, Error>>,
dur: Duration,
timeout_result: Error,
) -> Result<R, Error> {
let (tx, rx) = futures::channel::oneshot::channel();
std::thread::spawn(move || {
std::thread::sleep(dur);
let _ = tx.send(timeout_result);
});
match select(fut, rx).await {
Either::Left((r, _)) =>... | {
Ok(r) => peers = r,
Err(_) => break,
}
}
let own_id = (|| -> Result<NodeId, Error> {
for peer in peers.iter() {
if peer.is_self {
return Ok(peer.id);
}
}
failure::bail!("Cannot find myself");
})()?;
... | )
.await | random_line_split |
lib.rs | * A `global` for a thread ID is injected.
/// * Four bytes in linear memory are reserved for the counter of thread
/// IDs.
/// * A `start` function is injected (or prepended if one already exists)
/// which initializes memory for the first thread and otherwise allocates
/// thread ids for al... | random_line_split | ||
lib.rs | have work to do. If shared memory isn't enabled, though then
// this isn't an atomic module so there's nothing to do. We still allow,
// though, an environment variable to force us to go down this path to
// remain compatibile with older LLVM outputs.
match wasm_conventions::get_memory(... |
fn delete_synthetic_global(module: &mut Module, name: &str) -> Result<u32, Error> {
let id = match delete_synthetic_export(module, name)? {
walrus::ExportItem::Global(g) => g,
_ => bail!("`{}` must be a global", name),
};
let g = match module.globals.get(id).kind {
walrus::GlobalKi... | {
match delete_synthetic_export(module, name)? {
walrus::ExportItem::Function(f) => Ok(f),
_ => bail!("`{}` must be a function", name),
}
} | identifier_body |
lib.rs | have work to do. If shared memory isn't enabled, though then
// this isn't an atomic module so there's nothing to do. We still allow,
// though, an environment variable to force us to go down this path to
// remain compatibile with older LLVM outputs.
match wasm_conventions::get_memory(... | {
init: walrus::FunctionId,
size: u32,
align: u32,
}
fn inject_start(
module: &mut Module,
tls: Tls,
addr: u32,
stack_pointer: GlobalId,
stack_size: u32,
memory: MemoryId,
) -> Result<(), Error> {
use walrus::ir::*;
assert!(stack_size % PAGE_SIZE == 0);
let mut builder... | Tls | identifier_name |
lib.rs | to the one(s) initially added on build.
///
/// Returns a new [`FontId`](struct.FontId.html) to reference this font.
pub fn add_font(&mut self, font: F) -> FontId {
self.glyph_brush.add_font(font)
}
}
impl<R, GF, F, H> GlyphCruncher<F, Extra> for GlyphBrush<R, GF, F, H>
where
F: Font,
... | {
cache.pipe_data.out_depth.take();
} | conditional_block | |
lib.rs | Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing,
/// glyph draw caching & efficient GPU texture cache updating and re-sizing on demand.
///
/// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html).
///
/// # Example
/// ```no_run
/// # use gfx_glyph::{GlyphBrushB... | <'a, S>(&mut self, section: S)
where
S: Into<Cow<'a, Section<'a>>>,
{
self.glyph_brush.queue(section)
}
/// Returns a [`DrawBuilder`](struct.DrawBuilder.html) allowing the queued glyphs to be drawn.
///
/// Drawing will trim the cache, see [caching behaviour](#caching-behaviour)... | queue | identifier_name |
lib.rs | /// Object allowing glyph drawing, containing cache state. Manages glyph positioning cacheing,
/// glyph draw caching & efficient GPU texture cache updating and re-sizing on demand.
///
/// Build using a [`GlyphBrushBuilder`](struct.GlyphBrushBuilder.html).
///
/// # Example
/// ```no_run
/// # use gfx_glyph::{GlyphBru... | gfx::handle::Texture<R, TexSurface>,
gfx_core::handle::ShaderResourceView<R, f32>,
),
texture_filter_method: texture::FilterMethod,
factory: GF,
program: gfx::handle::Program<R>,
draw_cache: Option<DrawnGlyphBrush<R>>,
glyph_brush: glyph_brush::GlyphBrush<GlyphVertex, Extra, F, H... | random_line_split | |
lib.rs | DV: RawAndFormat<Raw = RawDepthStencilView<R>>,
{
let mut brush_action;
loop {
let tex = self.font_cache_tex.0.clone();
brush_action = self.glyph_brush.process_queued(
|rect, tex_data| {
let offset = [rect.min[0] as u16, rect.min[1] as u... | {
let kind = texture::Kind::D2(
width as texture::Size,
height as texture::Size,
texture::AaMode::Single,
);
let tex = factory.create_texture(
kind,
1,
gfx::memory::Bind::SHADER_RESOURCE,
gfx::memory::Usage::Dynamic,
Some(<TexChannel as format... | identifier_body | |
encyclopediaWnd.py | *)')
BOLD_PARSER = re.compile(r'\*+(.*?)\*+')
ENCYC = {}
HEADER = """<color:2DCBC9><linkcolor:AAAA00><shadowcolor:000000><shadow:1:1><just:center><lmargin%%:2><rmargin%%:98><font:Arial Bold:20>Encyclopedia
<font:Arial:14><just:right><a:chatlink%s>Add to Chat</a>\n<just:left>"""
HOME = """
<a:ZoneIndex>Zones</a>
<a... | <a:SkillIndex>Skills</a>
<a:ClassIndex>Classes</a>
<a:RecipeIndex>Recipes</a><br>
<a:EnchantingDisenchantingIndex>Enchanting / Disenchanting</a>
"""
PAGECACHE = {}
ENCWND = None
class EncWindow:
def __init__(self):
self.encText = TGEObject("ENCYC_TEXT")
self.encScroll = TGEObject("ENCYC_SCROLL"... | <a:SpellIndex>Spells</a> | random_line_split |
encyclopediaWnd.py | .curIndex = -1
def setPage(self,mypage,append = True):
try:
page = ENCYC[mypage]
except:
return False
try:
text = PAGECACHE[mypage]
except KeyError:
text = ""
pos = self.encScroll.childRelPos.split(" ... | page = args[1].replace('gamelink','')
if page.startswith('charlink'): # link to tell, not encyc
commandCtrl = TomeGui.tomeCommandCtrl
if not commandCtrl.visible:
TGECall("PushChatGui")
commandCtrl.visible = True
commandCtrl.makeFirstResponder(True)
comman... | identifier_body | |
encyclopediaWnd.py | *)')
BOLD_PARSER = re.compile(r'\*+(.*?)\*+')
ENCYC = {}
HEADER = """<color:2DCBC9><linkcolor:AAAA00><shadowcolor:000000><shadow:1:1><just:center><lmargin%%:2><rmargin%%:98><font:Arial Bold:20>Encyclopedia
<font:Arial:14><just:right><a:chatlink%s>Add to Chat</a>\n<just:left>"""
HOME = """
<a:ZoneIndex>Zones</a>
<a... |
return
def encyclopediaGetLink(searchvalue):
if not searchvalue:
return None
if not ENCWND:
PyExec()
formatted = GetTWikiName(searchvalue)
link = None
if ENCYC.has_key(formatted):
link = "<a:%s>%s</a>"%(formatted,searchvalue)
elif ENCYC.has_key("Item%s"%formatted):... | TGECall("MessageBoxOK","Entry not found","No entry for %s in encyclopedia."%searchvalue) | conditional_block |
encyclopediaWnd.py | *)')
BOLD_PARSER = re.compile(r'\*+(.*?)\*+')
ENCYC = {}
HEADER = """<color:2DCBC9><linkcolor:AAAA00><shadowcolor:000000><shadow:1:1><just:center><lmargin%%:2><rmargin%%:98><font:Arial Bold:20>Encyclopedia
<font:Arial:14><just:right><a:chatlink%s>Add to Chat</a>\n<just:left>"""
HOME = """
<a:ZoneIndex>Zones</a>
<a... | (self):
self.encText = TGEObject("ENCYC_TEXT")
self.encScroll = TGEObject("ENCYC_SCROLL")
self.history = []
self.positions = {}
self.curIndex = -1
def setPage(self,mypage,append = True):
try:
page = ENCYC[mypage]
except:
retur... | __init__ | identifier_name |
report.go | ", flag.ExitOnError)
fs.StringVar(&cmd.dbPath, "db-path", "", "Path to database. Required.")
fs.StringVar(&cmd.seriesFilePath, "series-file", "", "Optional path to series file. Defaults /path/to/db-path/_series")
fs.BoolVar(&cmd.byMeasurement, "measurements", true, "Segment cardinality by measurements")
// TODO(edd... |
errC <- fn(shardIDs[i])
}
}()
}
// Check for error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
return err
}
}
return nil
}
type cardinality struct {
name []byte
short []uint32
set *tsdb.SeriesIDSet
}
func (c *cardinality) add(x uint64) {
if c.set != nil {
c.set.AddN... | {
return // No more work.
} | conditional_block |
report.go | i", flag.ExitOnError)
fs.StringVar(&cmd.dbPath, "db-path", "", "Path to database. Required.")
fs.StringVar(&cmd.seriesFilePath, "series-file", "", "Optional path to series file. Defaults /path/to/db-path/_series")
fs.BoolVar(&cmd.byMeasurement, "measurements", true, "Segment cardinality by measurements")
// TODO(ed... | (i, j int) { a[i], a[j] = a[j], a[i] }
func (cmd *Command) cardinalityByMeasurement(shardID uint64) error {
idx := cmd.shardIdxs[shardID]
itr, err := idx.MeasurementIterator()
if err != nil {
return err
} else if itr == nil {
return nil
}
defer itr.Close()
OUTER:
for {
name, err := itr.Next()
if e... | Swap | identifier_name |
report.go | i", flag.ExitOnError)
fs.StringVar(&cmd.dbPath, "db-path", "", "Path to database. Required.")
fs.StringVar(&cmd.seriesFilePath, "series-file", "", "Optional path to series file. Defaults /path/to/db-path/_series")
fs.BoolVar(&cmd.byMeasurement, "measurements", true, "Segment cardinality by measurements")
// TODO(ed... | defer cmd.sfile.Close()
// Open all the indexes.
for id, pth := range cmd.shardPaths {
pth = path.Join(pth, "index")
// Verify directory is an index before opening it.
if ok, err := tsi1.IsIndexDir(pth); err != nil {
return err
} else if !ok {
return fmt.Errorf("not a TSI index directory: %q", pth)
... | } | random_line_split |
report.go | err != nil {
return err
}
}
return nil
}
// calculateCardinalities calculates the cardinalities of the set of shard being
// worked on concurrently. The provided function determines how cardinality is
// calculated and broken down.
func (cmd *Command) calculateCardinalities(fn func(id uint64) error) error {
/... | {
allMap, ok := cmd.cardinalities[id]
if !ok {
return nil
}
var totalCardinality int64
all := make(cardinalities, 0, len(allMap))
for _, card := range allMap {
n := card.cardinality()
if n == 0 {
continue
}
totalCardinality += n
all = append(all, card)
}
sort.Sort(sort.Reverse(all))
| identifier_body | |
tier_fs.go | return fmt.Errorf("removing dir: %w", err)
}
return filepath.SkipDir
}
return nil
}
if err := storeLocalFile(rPath, info.Size(), eviction); err != nil {
return err
}
return nil
}); err != nil {
return fmt.Errorf("walking the fs dir: %w", err)
}
return nil
}
func (tfs *TierFS) removeFro... | workspaceTempFilePath | identifier_name | |
tier_fs.go | The directory where TierFS files are kept locally.
localBaseDir string
// Maximum number of bytes an instance of TierFS can allocate to local files.
// This is not a hard limit - there might be short period of times where TierFS
// uses more disk due to ongoing writes and slow disk cleanups.
allocatedDiskBytes i... |
tierFS.eviction = eviction
return tierFS, nil
}
// handleExistingFiles should only be called during init of the TierFS.
// It does 2 things:
// 1. Adds stored files to the eviction control
// 2. Remove workspace directories and all its content if it
// exist under the namespace dir.
func handleExistingFiles(evic... | {
return nil, fmt.Errorf("handling existing files: %w", err)
} | conditional_block |
tier_fs.go | The directory where TierFS files are kept locally.
localBaseDir string
// Maximum number of bytes an instance of TierFS can allocate to local files.
// This is not a hard limit - there might be short period of times where TierFS
// uses more disk due to ongoing writes and slow disk cleanups.
allocatedDiskBytes i... |
func (tfs *TierFS) store(namespace, originalPath, filename string) error {
f, err := os.Open(originalPath)
if err != nil {
return fmt.Errorf("open file %s: %w", originalPath, err)
}
stat, err := f.Stat()
if err != nil {
return fmt.Errorf("file stat %s: %w", originalPath, err)
}
if err := tfs.adaptor.Put(... | {
p := path.Join(tfs.fsLocalBaseDir, string(rPath))
if err := os.Remove(p); err != nil {
tfs.logger.WithError(err).WithField("path", p).Error("Removing file failed")
errorsTotal.WithLabelValues(tfs.fsName, "FileRemoval")
return
}
if err := tfs.syncDir.deleteDirRecIfEmpty(path.Dir(p)); err != nil {
tfs.logg... | identifier_body |
tier_fs.go | // Maximum number of bytes an instance of TierFS can allocate to local files.
// This is not a hard limit - there might be short period of times where TierFS
// uses more disk due to ongoing writes and slow disk cleanups.
allocatedDiskBytes int64
}
const workspaceDir = "workspace"
// NewFS creates a new TierFS.
/... | fsBlockStoragePrefix string
// The directory where TierFS files are kept locally.
localBaseDir string
| random_line_split | |
bufimage.go | ImageFile.Path()]
if !ok {
imageFileSet[currentImageFile.Path()] = currentImageFile
paths = append(paths, currentImageFile.Path())
continue
}
if !storedImageFile.IsImport() && !currentImageFile.IsImport() {
return nil, fmt.Errorf("%s is a non-import in multiple images", currentImageFile.... | {
imageFiles := image.Files()
protoImage := &imagev1.Image{
File: make([]*imagev1.ImageFile, len(imageFiles)),
}
for i, imageFile := range imageFiles {
protoImage.File[i] = imageFileToProtoImageFile(imageFile)
}
return protoImage
} | identifier_body | |
bufimage.go | Reorders the ImageFiles to be in DAG order.
// Duplicates can exist across the Images, but only if duplicates are non-imports.
func MergeImages(images ...Image) (Image, error) {
switch len(images) {
case 0:
return nil, nil
case 1:
return images[0], nil
default:
var paths []string
imageFileSet := make(map[s... |
return ImageWithOnlyPaths(
image,
request.GetFileToGenerate(),
nil,
)
}
// NewImageForProtoOption is an option for use with NewImageForProto.
type NewImageForProtoOption func(*newImageForProtoOptions)
// WithNoReparse instructs NewImageForProto to skip the reparse step. The reparse
// step is usually needed ... | {
return nil, err
} | conditional_block |
bufimage.go | Reorders the ImageFiles to be in DAG order.
// Duplicates can exist across the Images, but only if duplicates are non-imports.
func MergeImages(images ...Image) (Image, error) {
switch len(images) {
case 0:
return nil, nil
case 1:
return images[0], nil
default:
var paths []string
imageFileSet := make(map[s... | () NewImageForProtoOption {
return func(options *newImageForProtoOptions) {
options.noReparse = true
}
}
// WithUnusedImportsComputation instructs NewImageForProto to compute unused imports
// for the files. These are usually computed by the compiler and stored in the image.
// But some sources of images may not i... | WithNoReparse | identifier_name |
bufimage.go | // MergeImages returns a new Image for the given Images. ImageFiles
// treated as non-imports in at least one of the given Images will
// be treated as non-imports in the returned Image. The first non-import
// version of a file will be used in the result.
//
// Reorders the ImageFiles to be in DAG order.
// Duplicates... | }
| random_line_split | |
decorators.py | """
Copyright (c) 2018, xamoom GmbH
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, copy, modify, merge, publish, distribute, s... | self.include_traceback_in_errors = include_traceback_in_errors
self.error_hook = error_hook
self.include_relationships = include_relationships
self.options_hook = options_hook
self.cached_get_hook = cached_get_hook
self.cached_set_hook = cached_set_hook
self.nest_... | def __init__( self,
meta=None,
links=None,
included=None,
success_status=200,
before_send_hook=None,
include_traceback_in_errors=False,
error_hook=None,
cache... | identifier_body |
decorators.py | """
Copyright (c) 2018, xamoom GmbH
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, copy, modify, merge, publish, distribute, s... |
return message
return wrapped_f
def __load_included(self, data_message,do_nesting=False):
included = []
if isinstance(data_message,list):
for d in data_message:
included = included + d.get_included(do_nesting=do_nesting)
else:
... |
janus_logger.error("Traceback: " + tb) | random_line_split |
decorators.py | """
Copyright (c) 2018, xamoom GmbH
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, copy, modify, merge, publish, distribute, s... |
return None
else:
if isinstance(messages, (list, tuple)) == False:
raise Exception('Methods using the "describe" decorator have to return a list of subclasses of DataMessage to describe.')
msg_descriptions = []
... | self.before_send_hook(204,None,None) | conditional_block |
decorators.py | """
Copyright (c) 2018, xamoom GmbH
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, copy, modify, merge, publish, distribute, s... | (*a, **ka):
try:
#first check if this is not a HTTP OPTIONS call using a method defined based on the WS framework.
#if it is one return empty array and do nothing else.
if self.options_hook != None:
if self.options_hook() == True:
... | wrapped_f | identifier_name |
compression.py | '),
tf.keras.layers.MaxPool2D(pool_size=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.train.AdamOptimizer(learni... | (root):
"""
Encodes a huffman tree to string of '0's and '1's
"""
# converter = {'float32':float2bitstr, 'int32':int2bitstr}
code_list = []
def encode_node(node):
if node.value is not None: # node is leaf node
code_list.append('1')
lst = list(int2bitstr(node.val... | encode_huffman_tree | identifier_name |
compression.py | relu'),
tf.keras.layers.MaxPool2D(pool_size=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.train.AdamOptimizer(le... | return
if node.value is not None:
value2code[node.value] = code
return
generate_code(node.left, code + '0 | frequency_map = defaultdict(int)
for value in np.nditer(arr):
value = int(value)
frequency_map[value] += 1
heap = [Node(frequency, value, None, None) for value, frequency in frequency_map.items()]
heapify(heap)
# Merge nodes
while len(heap) > 1:
node1 = heappop(heap)
... | identifier_body |
compression.py | relu'),
tf.keras.layers.MaxPool2D(pool_size=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.train.AdamOptimizer(le... | # gradient = grads[gradient_num].numpy().flatten()
#
# # Get the gradient of the nonzero position
# nonzero_gradient = gradient[Sparse_layer[layer_id].flatten() != 0].flatten()
# nonzero_index = np.where(Sparse_layer[layer_id].flatten() != 0)[0]
# # print(len(... | # for layer_id in Sparse_layer:
# gradient_num += 2 | random_line_split |
compression.py | '),
tf.keras.layers.MaxPool2D(pool_size=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.train.AdamOptimizer(learni... |
else:
end = j*BATCH_SIZE + BATCH_SIZE
X, Y = x_train[begin:end], y_train[begin:end]
# train on each batch
model.train_on_batch(X, Y)
# apply Sparse connection
for layer_id in Sparse_layer:
w = model.layers[layer_id].get_weights()
w[0] ... | end = x_train.shape[0] | conditional_block |
radixsort.go | wrapper tunrs an Int64Interface into a Uint64Interface for
// guessIntShift
type intwrapper struct{ Int64Interface }
func (iw intwrapper) Key(i int) uint64 {
return int64Key(iw.Int64Interface.Key(i))
}
// ByInt64 sorts data by an int64 key.
func ByInt64(data Int64Interface) {
l := data.Len()
shift := guessIntShift... | max = k
}
}
// skip past common prefixes, bail if all keys equal
diff := min ^ max
if diff == 0 {
return
}
if diff>>shift == 0 || diff>>(shift+radix) != 0 {
// find highest 1 bit in diff
log2diff := 0
for diff != 0 {
log2diff++
diff >>= 1
}
nextShift := log2diff - radix
if nextShift < 0 ... | {
data := dataI.(Uint64Interface)
shift, a, b := uint(t.offs), t.pos, t.end
if b-a < qSortCutoff {
qSort(data, a, b)
return
}
// use a single pass over the keys to bucket data and find min/max
// (for skipping over bits that are always identical)
var bucketStarts, bucketEnds [1 << radix]int
min := data.Key... | identifier_body |
radixsort.go | var qSortCutoff = 1 << 7
const keyPanicMessage = "sort failed: Key and Less aren't consistent with each other"
const keyUint64Help = " (for float data, sortutil Key functions may help resolve this)"
const panicMessage = "sort failed: could be a data race, a radixsort bug, or a subtle bug in the interface implementatio... | // certain tests so we can more easily exercise the radix sorting. This was
// around the break-even point in some sloppy tests. | random_line_split | |
radixsort.go | wrapper tunrs an Int64Interface into a Uint64Interface for
// guessIntShift
type intwrapper struct{ Int64Interface }
func (iw intwrapper) Key(i int) uint64 {
return int64Key(iw.Int64Interface.Key(i))
}
// ByInt64 sorts data by an int64 key.
func ByInt64(data Int64Interface) {
l := data.Len()
shift := guessIntShift... |
if k > max {
max = k
}
}
// skip past common prefixes, bail if all keys equal
diff := min ^ max
if diff == 0 {
return
}
if diff>>shift == 0 || diff>>(shift+radix) != 0 {
// find highest 1 bit in diff
log2diff := 0
for diff != 0 {
log2diff++
diff >>= 1
}
nextShift := log2diff - radix
i... | {
min = k
} | conditional_block |
radixsort.go | wrapper tunrs an Int64Interface into a Uint64Interface for
// guessIntShift
type intwrapper struct{ Int64Interface }
func (iw intwrapper) Key(i int) uint64 {
return int64Key(iw.Int64Interface.Key(i))
}
// ByInt64 sorts data by an int64 key.
func ByInt64(data Int64Interface) {
l := data.Len()
shift := guessIntShift... | (data Uint64Interface, l int) uint {
if l < qSortCutoff {
return 64 - radix
}
step := l >> 5
if l > 1<<16 {
step = l >> 8
}
if step == 0 { // only for tests w/qSortCutoff lowered
step = 1
}
min := data.Key(l - 1)
max := min
for i := 0; i < l; i += step {
k := data.Key(i)
if k < min {
min = k
}
... | guessIntShift | identifier_name |
std_fs.rs | Option<u32>,
) -> FsResult<()> {
spawn_blocking(move || chown(&path, uid, gid)).await?
}
fn remove_sync(&self, path: &Path, recursive: bool) -> FsResult<()> {
remove(path, recursive)
}
async fn remove_async(&self, path: PathBuf, recursive: bool) -> FsResult<()> {
spawn_blocking(move || remove(&p... |
fn write_file_sync(
&self,
path: &Path,
options: OpenOptions,
data: &[u8],
) -> FsResult<()> {
let opts = open_options(options);
let mut file = opts.open(path)?;
#[cfg(unix)]
if let Some(mode) = options.mode {
use std::os::unix::fs::PermissionsExt;
file.set_permissions(... | {
let atime = filetime::FileTime::from_unix_time(atime_secs, atime_nanos);
let mtime = filetime::FileTime::from_unix_time(mtime_secs, mtime_nanos);
spawn_blocking(move || {
filetime::set_file_times(path, atime, mtime).map_err(Into::into)
})
.await?
} | identifier_body |
std_fs.rs | , path: PathBuf) -> FsResult<PathBuf> {
spawn_blocking(move || fs::read_link(path))
.await?
.map_err(Into::into)
}
fn truncate_sync(&self, path: &Path, len: u64) -> FsResult<()> {
truncate(path, len)
}
async fn truncate_async(&self, path: PathBuf, len: u64) -> FsResult<()> {
spawn_block... | stat | identifier_name | |
std_fs.rs | (path)?;
Err(FsError::NotSupported)
}
#[cfg(unix)]
fn chown(path: &Path, uid: Option<u32>, gid: Option<u32>) -> FsResult<()> {
use nix::unistd::chown;
use nix::unistd::Gid;
use nix::unistd::Uid;
let owner = uid.map(Uid::from_raw);
let group = gid.map(Gid::from_raw);
let res = chown(path, owner, group);
... | .collect();
Ok(entries)
}
| random_line_split | |
std_fs.rs | else {
// If no mask provided, we query the current. Requires two syscalls.
let prev = umask(Mode::from_bits_truncate(0o777));
let _ = umask(prev);
prev
};
#[cfg(target_os = "linux")]
{
Ok(r.bits())
}
#[cfg(any(
target_os = "macos",
target_os = "openbsd",
... | {
// If mask provided, return previous.
umask(Mode::from_bits_truncate(mask as mode_t))
} | conditional_block | |
folder.js | is to begin with the end of the `query`, and for each letter
// matched, the letter is captured, its position influences the score, and we
// go to the next letter.
for (var i = leafLower.length - 1; i >= 0; i--) {
var l = leafLower[i]; // letter
if (countlettersmatched > 0 && !alpha.test(l)) {
s... | // It is already selected.
delete selectedFile[i];
nSelectedFiles--;
slots[i].classList.remove('selected-file');
if (nSelectedFiles <= 0) {
// Hide the file-specific buttons.
deleteFileBut.style.display = 'none';
confFileBut.style.display = 'none';
} else if (nSelectedFiles === 1... | conditional_block | |
folder.js | ] !== '/') {
leaf.path += '/'; // FIXME server side bug
}
this.leaf = leaf;
this.stars = (stars|0) || 0;
this.indexes = indexes || [];
}
Score.prototype = {
add: function(n) { this.stars += (n|0); },
};
// Return a Score object, {leaf, stars, indexes}:
//
// - `leaf` is an Object like {path: '/', meta:... | var search = '?';
for (key in params) {
if (params[key] instanceof Array) {
for (var i = 0; i < params[key].length; i++) {
search += encodeURIComponent(key) + '=' + encodeURIComponent(params[key][i]) + '&';
}
} else {
search += encodeURIComponent(key) + '=' + (params[key] !== undefin... | identifier_body | |
folder.js | search.focus();
e.preventDefault(); // Don't input it in the search bar.
}
} else { // The search widget is focused.
if (e.keyCode === 27) { // ESC.
search.blur();
}
}
}
}
// Fuzzy matching.
//
function sorter (file1, file2) { return file2.stars - file1.stars; }
// `l... | return window.location.search.slice(1).split('&').reduce(function(acc, param) {
var parts = param.split('=');
var key = parts[0], value = parts[1];
if (acc[key] instanceof Array) {
acc[key].push(value); | random_line_split | |
folder.js | i < len; i++) {
fileSelectionEventListenerReset[i]();
}
fileSelectionEventListenerReset = [];
for (var i = 0; i < slots.length; i++) {
slots[i].addEventListener('click', (function(i) {
var onclick = function onclick(e) {
var nomod = !(e.ctrlKey || e.shiftKey || e.altKey || e.metaKey);
... | ify (sc | identifier_name | |
main.py | map do not allow further X-shift in that dir.
for sq in currentElement:
if (d == 'l' and sq.pos.left == 150) or (d == 'r' and sq.pos.left == 425):
return
for sq in currentElement:
screen.blit(background, sq.pos, (150, 0, 26, 26))
for sq in currentElement:
sq.moveHorizontally(d)
screen.bli... |
def updateScore(currentScore, highScore):
"""
Update current score and high score on the screen & also make sure they're centered
"""
screen.fill(pygame.Color("black"), (10, 210, 130, 20))
hsWidth = getTextWidth(str(highScore))
hsPos = (150 - hsWidth) // 2, 210
displayText(str(highScore), GOLD, hsPos)... | hsTxt, _ = GAME_FONT.render(text, BLACK)
return hsTxt.get_width() | identifier_body |
main.py | the map do not allow further X-shift in that dir.
for sq in currentElement:
if (d == 'l' and sq.pos.left == 150) or (d == 'r' and sq.pos.left == 425):
return
for sq in currentElement:
screen.blit(background, sq.pos, (150, 0, 26, 26))
for sq in currentElement:
sq.moveHorizontally(d)
screen... | """
# Make sure that the rotation will not place the tetromino out of map at the top
for sq in element:
if sq.pos[1] <= 0:
return
for sq in element:
screen.blit(background, sq.pos, (150, 0, 26, 26))
# Also, make sure that element stays within the map after rotation
tmpArr = []
for sq i... | The point is the center of the bounding box | random_line_split |
main.py | map do not allow further X-shift in that dir.
for sq in currentElement:
if (d == 'l' and sq.pos.left == 150) or (d == 'r' and sq.pos.left == 425):
return
for sq in currentElement:
screen.blit(background, sq.pos, (150, 0, 26, 26))
for sq in currentElement:
sq.moveHorizontally(d)
screen.bli... |
updateScore(currentScore, highScore)
return [currentScore, highScore]
def displayGameOver():
"""
When the game is over clear the screen and display a game over message
"""
screen.fill(pygame.Color('black'), (0, 0, SCREEN_SIZE[0], SCREEN_SIZE[1]))
goText, rect1 = GAME_FONT.render('Game Over', WHITE)
... | highScore = currentScore
updateHighScore(highScore) | conditional_block |
main.py | map do not allow further X-shift in that dir.
for sq in currentElement:
if (d == 'l' and sq.pos.left == 150) or (d == 'r' and sq.pos.left == 425):
return
for sq in currentElement:
screen.blit(background, sq.pos, (150, 0, 26, 26))
for sq in currentElement:
sq.moveHorizontally(d)
screen.bli... | (element):
"""
Rotate 90 deg each square that the tetris element is made up of around a pivot point
The point is the center of the bounding box
"""
# Make sure that the rotation will not place the tetromino out of map at the top
for sq in element:
if sq.pos[1] <= 0:
return
for sq in eleme... | rotateElement | identifier_name |
register.rs | _LEN, TENDERMINT_NODE_ID_LEN};
use crate::utils;
use web3::transports::Http;
use web3::types::H160;
const API_PORT: &str = "api_port";
const CAPACITY: &str = "capacity";
const PRIVATE: &str = "private";
const NO_STATUS_CHECK: &str = "no_status_check";
#[derive(Debug, Getters)]
pub struct Register {
node_ip: IpAdd... | ;
if is_registered {
Ok(Registered::AlreadyRegistered)
} else {
let tx = utils::with_progress(
"Registering the node in the smart contract...",
step_counter.format_next_step().as_str(),
"Transaction with... | {
false
} | conditional_block |
register.rs | no_status_check: bool,
eth: EthereumParams,
}
#[derive(PartialEq, Debug)]
pub enum Registered {
TransactionSent(H256),
Deployed {
app_ids: Vec<u64>,
ports: Vec<u16>,
tx: H256,
},
Enqueued(H256),
AlreadyRegistered,
}
impl Register {
/// Creates `Register` structure
... | {
let account: Address = "4180fc65d613ba7e1a385181a219f1dbfe7bf11d".parse().unwrap();
EthereumArgs::with_acc_creds(account, credentials)
} | identifier_body | |
register.rs | IP_LEN, TENDERMINT_NODE_ID_LEN};
use crate::utils;
use web3::transports::Http; | const NO_STATUS_CHECK: &str = "no_status_check";
#[derive(Debug, Getters)]
pub struct Register {
node_ip: IpAddr,
tendermint_key: H256,
tendermint_node_id: H160,
api_port: u16,
capacity: u16,
private: bool,
no_status_check: bool,
eth: EthereumParams,
}
#[derive(PartialEq, Debug)]
pub e... | use web3::types::H160;
const API_PORT: &str = "api_port";
const CAPACITY: &str = "capacity";
const PRIVATE: &str = "private"; | random_line_split |
register.rs | IP_LEN, TENDERMINT_NODE_ID_LEN};
use crate::utils;
use web3::transports::Http;
use web3::types::H160;
const API_PORT: &str = "api_port";
const CAPACITY: &str = "capacity";
const PRIVATE: &str = "private";
const NO_STATUS_CHECK: &str = "no_status_check";
#[derive(Debug, Getters)]
pub struct Register {
node_ip: Ip... | <'a, 'b>() -> App<'a, 'b> {
let args = &[
node_ip().display_order(1),
tendermint_key().display_order(2),
base64_tendermint_key().display_order(3),
tendermint_node_id().display_order(4),
Arg::with_name(API_PORT)
.alias(API_PORT)
.long(API_PORT)
... | subcommand | identifier_name |
bamToNucleosomePositions.py | ig_sizes
from singlecellmultiomics.utils import is_autosome, pool_wrapper
import numpy as np
from multiprocessing import Pool
from more_itertools import windowed
from glob import glob
import pyBigWig
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks
import argparse
from itertools import pr... | h.addHeader(list(zip(contigs, [sizes[c] for c in contigs])))
# Obtain nucleosome and linker votes for each contig
for ret_contig, (vote_nucleosome, vote_linker) in zip(
molecule_coordinate_dicts.keys(),
workers.imap(pool_wrapper,
(
... | # Add headers for all output bigwigfiles
for h in (linkers_out, nuc_out, merged_out):
# Write header | random_line_split |
bamToNucleosomePositions.py | _sizes
from singlecellmultiomics.utils import is_autosome, pool_wrapper
import numpy as np
from multiprocessing import Pool
from more_itertools import windowed
from glob import glob
import pyBigWig
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks
import argparse
from itertools import prod... |
def _generate_molecule_coordinate_dict(args, max_fragment_size=800):
bam_path, sel_contig= args
molecule_coordinate_dict = defaultdict(list) # cell->[ (start,end), (start,end) ..]
with pysam.AlignmentFile(bam_path) as alignments:
# pysam.FastaFile(get_reference_path_from_bam(alignments)) as refer... | for f in molecule:
f.R2_primer_length = 6
mlen = molecule.estimated_max_length
if mlen is None:
return None
return mlen + 2 # 2 extra bases because 1 base is potentially lost on both sides | identifier_body |
bamToNucleosomePositions.py | _sizes
from singlecellmultiomics.utils import is_autosome, pool_wrapper
import numpy as np
from multiprocessing import Pool
from more_itertools import windowed
from glob import glob
import pyBigWig
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks
import argparse
from itertools import prod... | (bams, molecule_coordinate_dicts, p_nuc_bin_size = 5, alias='npos', n_threads=None ):
contigs = get_contigs(bams[0])
sizes = get_contig_sizes(bams[0])
# Create output bigwig file handles and worker pool
linker_vote_write_path= f'{alias}_linkers.bw'
nuc_vote_write_path= f'{alias}_nucleosomes.bw'
... | coordinate_dicts_to_nucleosome_position_files | identifier_name |
bamToNucleosomePositions.py | _sizes
from singlecellmultiomics.utils import is_autosome, pool_wrapper
import numpy as np
from multiprocessing import Pool
from more_itertools import windowed
from glob import glob
import pyBigWig
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks
import argparse
from itertools import prod... |
# Any starting point of a molecule is _always_ part of a linker
# lets say += 25bp
c=o_start_a
s = int(((c-linker_vote_radius))/p_nuc_bin_size)
e = int(((c+linker_vote_radius))/p_nuc_bin_size)+1
vote_linker[s:(e+1)] += 1/(e-s)
if en... | s = int(((start_a + 70 ))/p_nuc_bin_size)
e = int(((end_a - 70))/p_nuc_bin_size)
vote_nucleosome[ s:(e+1) ] += 1/(e-s) | conditional_block |
ast.js | <\\]/) : makeRegexParser(/^[^{}$<\\]/)
const regularLiteralWithoutBar = wikilinks ? makeRegexParser(/^[^{}[\]$\\|]/) : makeRegexParser(/^[^{}$\\|]/)
const regularLiteralWithoutSpace = wikilinks ? makeRegexParser(/^[^{}[\]$\s]/) : makeRegexParser(/^[^{}$\s]/)
// There is a general pattern:
// parse a thing;
/... |
const wikilinkContents = choice([
pipedWikilink,
unpipedWikilink
])
function wikilink () {
let result = null
const parsedResult = sequence([
openWikilink,
wikilinkContents,
closeWikilink
])
if (parsedResult !== null) {
const parsedLinkContents = parsedResult[1]... | {
const result = sequence([
nOrMore(1, paramExpression)
])
return result === null
? null
: [
['CONCAT'].concat(result[0])
]
} | identifier_body |
ast.js | ]$<\\]/) : makeRegexParser(/^[^{}$<\\]/)
const regularLiteralWithoutBar = wikilinks ? makeRegexParser(/^[^{}[\]$\\|]/) : makeRegexParser(/^[^{}$\\|]/)
const regularLiteralWithoutSpace = wikilinks ? makeRegexParser(/^[^{}[\]$\s]/) : makeRegexParser(/^[^{}$\s]/)
// There is a general pattern:
// parse a thing;
... | return res === null ? null : res[0].concat(res[1])
},
function () {
const res = sequence([templateName, nOrMore(0, templateParam)])
if (res === null) {
return null
}
return [res[0]].concat(res[1])
}
])
const openTemplate = makeStringParser('{{')
const closeTemp... | random_line_split | |
ast.js | (n, p) {
return () => {
const originalPos = pos
const result = []
let parsed = p()
while (parsed !== null) {
result.push(parsed)
parsed = p()
}
if (result.length < n) {
pos = originalPos
return null
}
return result
}
}
/... | nOrMore | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.