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 |
|---|---|---|---|---|
__init__.py | # Copyright 2019 TWO SIGMA OPEN SOURCE, LLC
#
# 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... |
def run():
try:
parse()
except KeyboardInterrupt:
return 130
return 0
| return [dict(module="beakerx_tabledisplay")] | identifier_body |
table_edit.js | $(document).ready(function(){
$("table.editable td").dblclick(function () {
var eContent = $(this).text();
var eCell = $(this);
if(eContent.indexOf('<') >= 0 || eCell.parents('table').hasClass('oc_disable')) return false;
... |
});
if(eState == 1)
$(this).attr('data-state','2');
else{
$(this).removeAttr('data-state');
$(this).html('Edit');
}
});
$("table.editable").on("click",".remove",function(){
rRow = $(this).parents("tr");
$("#row_delete... | {
var eContent = $(this).find('input').val();
if(eContent != null){
$(this).removeClass("editing").html(eContent);
// Here your ajax action after Save button pressed
}
} | conditional_block |
table_edit.js | $(document).ready(function(){
$("table.editable td").dblclick(function () {
var eContent = $(this).text();
var eCell = $(this);
if(eContent.indexOf('<') >= 0 || eCell.parents('table').hasClass('oc_disable')) return false;
... | (row){
row.remove();
// Here your ajax action after delete confirmed
}
$("#row_delete").dialog({
autoOpen: false,
resizable: false,
modal: true,
buttons: {
"Delete": function() {
remove_row(rRow);
$(this).dialog(... | remove_row | identifier_name |
table_edit.js | $(document).ready(function(){
$("table.editable td").dblclick(function () {
var eContent = $(this).text();
var eCell = $(this);
if(eContent.indexOf('<') >= 0 || eCell.parents('table').hasClass('oc_disable')) return false;
... |
$("#row_delete").dialog({
autoOpen: false,
resizable: false,
modal: true,
buttons: {
"Delete": function() {
remove_row(rRow);
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("... | {
row.remove();
// Here your ajax action after delete confirmed
} | identifier_body |
table_edit.js | $(document).ready(function(){
$("table.editable td").dblclick(function () {
var eContent = $(this).text(); | eCell.html('<input type="text" value="' + eContent + '"/>');
var eInput = eCell.find("input");
eInput.focus();
eInput.keypress(function(e){
if (e.which == 13) {
var newContent = $(this).val();
eCell.html(newContent).removeClass("edit... | var eCell = $(this);
if(eContent.indexOf('<') >= 0 || eCell.parents('table').hasClass('oc_disable')) return false;
eCell.addClass("editing"); | random_line_split |
stages.js | merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software... | });
};
/**
* Esta función sirve para que, dado
*
*/
exports.second = function(req, res) {
console.log("BODY: " + req.body.fcbklist_value);
if(req.body.fcbklist_value.length < 2) {
res.redirect("/account/experiments/compare/");
} else {
//res.send(req.body);
var orArray = [];
req.body.fcbk... |
console.log(exps);
res.render('account/experiments/compare/stage1', {
code: req.csrfToken(),
experiments: exps
});
}
| conditional_block |
stages.js | whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING... | function(err, results){
console.log("FIN: " + arr.length);
console.log(params.intersect(commons));
//res.send(data);
/*var ret = { | random_line_split | |
use_suggestion_placement.rs | // Copyright 2016 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 | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-cloudabi no std::path support
macro_rules! y {
() => {}
}
mod m {
pub const A: i32 = 0;
}
mod foo {
#[derive(Debug)]
pub stru... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | random_line_split |
use_suggestion_placement.rs | // Copyright 2016 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 ... | ;
// test whether the use suggestion isn't
// placed into the expansion of `#[derive(Debug)]
type Bar = Path; //~ ERROR cannot find
}
fn main() {
y!();
let _ = A; //~ ERROR cannot find
foo();
}
fn foo() {
type Dict<K, V> = HashMap<K, V>; //~ ERROR cannot find
}
| Foo | identifier_name |
use_suggestion_placement.rs | // Copyright 2016 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 ... | {
type Dict<K, V> = HashMap<K, V>; //~ ERROR cannot find
} | identifier_body | |
callback.py | #! /usr/bin/python3
"""Callback a callable asset."""
import struct
import decimal
D = decimal.Decimal
from . import (util, config, exceptions, litecoin, util)
from . import order
FORMAT = '>dQ'
LENGTH = 8 + 8
ID = 21
def validate (db, source, fraction, asset, block_time, block_index, parse):
cursor = db.curso... | order.cancel_order_match(db, order_match, 'cancelled', block_index)
# Cancel open orders involving asset.
cursor.execute('''SELECT * from orders \
WHERE status = ? AND (give_asset = ? OR get_asset = ?)''', ('open', asset, asset))
for order_element in list(c... | for order_match in list(cursor): | random_line_split |
callback.py | #! /usr/bin/python3
"""Callback a callable asset."""
import struct
import decimal
D = decimal.Decimal
from . import (util, config, exceptions, litecoin, util)
from . import order
FORMAT = '>dQ'
LENGTH = 8 + 8
ID = 21
def validate (db, source, fraction, asset, block_time, block_index, parse):
cursor = db.curso... | db, source, fraction, asset):
call_price, callback_total, outputs, problems = validate(db, source, fraction, asset, util.last_block(db)['block_time'], util.last_block(db)['block_index'], parse=False)
if problems: raise exceptions.CallbackError(problems)
print('Total quantity to be called back:', util.devise... | mpose ( | identifier_name |
callback.py | #! /usr/bin/python3
"""Callback a callable asset."""
import struct
import decimal
D = decimal.Decimal
from . import (util, config, exceptions, litecoin, util)
from . import order
FORMAT = '>dQ'
LENGTH = 8 + 8
ID = 21
def validate (db, source, fraction, asset, block_time, block_index, parse):
cursor = db.curso... | # Cancel open orders involving asset.
cursor.execute('''SELECT * from orders \
WHERE status = ? AND (give_asset = ? OR get_asset = ?)''', ('open', asset, asset))
for order_element in list(cursor):
order.cancel_order(db, order_element, 'cancelled', block_inde... | der.cancel_order_match(db, order_match, 'cancelled', block_index)
| conditional_block |
callback.py | #! /usr/bin/python3
"""Callback a callable asset."""
import struct
import decimal
D = decimal.Decimal
from . import (util, config, exceptions, litecoin, util)
from . import order
FORMAT = '>dQ'
LENGTH = 8 + 8
ID = 21
def validate (db, source, fraction, asset, block_time, block_index, parse):
|
if last_issuance['issuer'] != source:
problems.append('not asset owner')
return None, None, None, problems
if not last_issuance['callable']:
problems.append('uncallable asset')
return None, None, None, problems
elif last_issuance['call_date'] > b... | cursor = db.cursor()
problems = []
# TODO
if not config.TESTNET:
problems.append('callbacks are currently disabled on mainnet')
return None, None, None, problems
# TODO
if fraction > 1:
problems.append('fraction greater than one')
elif fraction <= 0:
problems.ap... | identifier_body |
Honeybee_Radiance Mirror Material By Color.py | #
# Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari
#
# This file is part of Honeybee.
#
# Copyright (c) 2013-2015, Mostapha Sadeghipour Roudsari <Sadeghipour@gmail.com>
# Honeybee is free software; you can redistribute it and/or modify
# it under the terms of the GNU Ge... |
def createRadMaterial(modifier, name, *args):
# I should check the inputs here
radMaterial = "void " + modifier + " " + name + "\n" + \
"0\n" + \
"0\n" + \
`int(len(args))`
for arg in args: radMaterial = radMaterial + (" " +... | return (math.sqrt(0.8402528435 + 0.0072522239 * (transmittance ** 2)) - 0.9166530661 ) / 0.0036261119 / transmittance | identifier_body |
Honeybee_Radiance Mirror Material By Color.py | #
# Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari
#
# This file is part of Honeybee.
#
# Copyright (c) 2013-2015, Mostapha Sadeghipour Roudsari <Sadeghipour@gmail.com>
# Honeybee is free software; you can redistribute it and/or modify
# it under the terms of the GNU Ge... | ():
modifier = "mirror"
if sc.sticky.has_key('honeybee_release'):
try:
if not sc.sticky['honeybee_release'].isCompatible(ghenv.Component): return -1
except:
warning = "You need a newer version of Honeybee to use this compoent." + \
"Use updateHoneybee com... | main | identifier_name |
Honeybee_Radiance Mirror Material By Color.py | #
# Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari
#
# This file is part of Honeybee.
#
# Copyright (c) 2013-2015, Mostapha Sadeghipour Roudsari <Sadeghipour@gmail.com>
# Honeybee is free software; you can redistribute it and/or modify
# it under the terms of the GNU Ge... |
RADMaterial = createRadMaterial(modifier, materialName, RTransmittance, GTransmittance, BTransmittance)
return RADMaterial
else:
msg = "Transmittance values should be between 0 and 1"
e = gh.G... | try:
if not sc.sticky['honeybee_release'].isCompatible(ghenv.Component): return -1
except:
warning = "You need a newer version of Honeybee to use this compoent." + \
"Use updateHoneybee component to update userObjects.\n" + \
"If you have already updated userObjec... | conditional_block |
Honeybee_Radiance Mirror Material By Color.py | #
# Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari
#
# This file is part of Honeybee.
#
# Copyright (c) 2013-2015, Mostapha Sadeghipour Roudsari <Sadeghipour@gmail.com>
# Honeybee is free software; you can redistribute it and/or modify
# it under the terms of the GNU Ge... | for arg in args: radMaterial = radMaterial + (" " + "%.3f"%arg)
return radMaterial + "\n"
def main():
modifier = "mirror"
if sc.sticky.has_key('honeybee_release'):
try:
if not sc.sticky['honeybee_release'].isCompatible(ghenv.Component): return -1
except:
... | "0\n" + \
"0\n" + \
`int(len(args))`
| random_line_split |
chrome_extension_reload_test.js | 'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actua... | },
custom_options: function(test) {
test.expect(1);
var actual = grunt.file.read('tmp/custom_options');
var expected = grunt.file.read('test/expected/custom_options');
test.equal(actual, expected, 'should describe what the custom option(s) behavior is.');
test.done();
},
}; | var expected = grunt.file.read('test/expected/default_options');
test.equal(actual, expected, 'should describe what the default behavior is.');
test.done(); | random_line_split |
mutations.ts | import {
GraphQLObjectType,
GraphQLString,
GraphQLInt,
GraphQLBoolean,
GraphQLNonNull,
} from 'graphql';
import { mutationWithClientMutationId } from 'graphql-relay';
import { videoType } from './types';
import { createVideo } from './api';
const videoMutation = mutationWithClientMutationId({
name: 'AddVi... | .catch(reject);
}),
})
const mutationType = new GraphQLObjectType({
name: 'Mutation',
description: 'The root mutation type.',
fields: {
createVideo: videoMutation,
},
});
export {
mutationType,
}; | .then((video) => accept({ video })) | random_line_split |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITE... | *
* THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED | random_line_split |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... |
#[test]
fn test() {
let nthreads = 8u;
let nmsgs = 1000u;
let q = Queue::new();
match q.pop() {
Empty => {}
Inconsistent | Data(..) => panic!()
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in range(0, nthreads) ... | {
let q = Queue::new();
q.push(box 1i);
q.push(box 2i);
} | identifier_body |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... |
}
}
drop(tx);
for _ in range(0, nthreads) {
rx.recv();
}
}
}
| { i += 1 } | conditional_block |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | (&mut self) {
unsafe {
let mut cur = *self.tail.get();
while !cur.is_null() {
let next = (*cur).next.load(Relaxed);
let _: Box<Node<T>> = mem::transmute(cur);
cur = next;
}
}
}
}
#[cfg(test)]
mod tests {
use pre... | drop | identifier_name |
optimize_dead_defs.rs | use std::collections::{HashSet};
use grit;
pub fn optimize(mut prog: grit::ProgDef) -> grit::ProgDef {
let info = collect_prog_info(&prog);
prog.fun_defs = prog.fun_defs.into_iter().filter(|def| {
info.used_funs.contains(&def.name)
}).collect();
prog.obj_defs = prog.obj_defs.into_iter().filter(|def| {
... | for arg in args.iter() {
collect_val(info, arg);
}
},
grit::Op::ExternCall(_, _, ref args) =>
for arg in args.iter() {
collect_val(info, arg);
},
grit::Op::AllocClos(ref closs) =>
for &(_, ref clos_name, ref captures) in closs.iter() {
info.used_funs.ins... | fn collect_op(info: &mut ProgInfo, op: &grit::Op) {
match *op {
grit::Op::Call(_, ref callee, ref args) => {
collect_callee(info, callee); | random_line_split |
optimize_dead_defs.rs | use std::collections::{HashSet};
use grit;
pub fn optimize(mut prog: grit::ProgDef) -> grit::ProgDef {
let info = collect_prog_info(&prog);
prog.fun_defs = prog.fun_defs.into_iter().filter(|def| {
info.used_funs.contains(&def.name)
}).collect();
prog.obj_defs = prog.obj_defs.into_iter().filter(|def| {
... | for &(_, ref val) in var_vals.iter() {
collect_val(info, val);
},
}
}
fn collect_jump(info: &mut ProgInfo, jump: &grit::Jump) {
match *jump {
grit::Jump::Goto(_) => {},
grit::Jump::TailCall(ref callee, ref args) => {
collect_callee(info, callee);
for arg in args.iter() {
... | {
match *op {
grit::Op::Call(_, ref callee, ref args) => {
collect_callee(info, callee);
for arg in args.iter() {
collect_val(info, arg);
}
},
grit::Op::ExternCall(_, _, ref args) =>
for arg in args.iter() {
collect_val(info, arg);
},
grit::Op::AllocClos(r... | identifier_body |
optimize_dead_defs.rs | use std::collections::{HashSet};
use grit;
pub fn | (mut prog: grit::ProgDef) -> grit::ProgDef {
let info = collect_prog_info(&prog);
prog.fun_defs = prog.fun_defs.into_iter().filter(|def| {
info.used_funs.contains(&def.name)
}).collect();
prog.obj_defs = prog.obj_defs.into_iter().filter(|def| {
info.used_objs.contains(&def.name)
}).collect();
... | optimize | identifier_name |
optimize_dead_defs.rs | use std::collections::{HashSet};
use grit;
pub fn optimize(mut prog: grit::ProgDef) -> grit::ProgDef {
let info = collect_prog_info(&prog);
prog.fun_defs = prog.fun_defs.into_iter().filter(|def| {
info.used_funs.contains(&def.name)
}).collect();
prog.obj_defs = prog.obj_defs.into_iter().filter(|def| {
... | ,
grit::Op::ExternCall(_, _, ref args) =>
for arg in args.iter() {
collect_val(info, arg);
},
grit::Op::AllocClos(ref closs) =>
for &(_, ref clos_name, ref captures) in closs.iter() {
info.used_funs.insert(clos_name.clone());
for capture in captures.iter() {
c... | {
collect_callee(info, callee);
for arg in args.iter() {
collect_val(info, arg);
}
} | conditional_block |
menu.js | import { addTimer } from './timer/timer';
import { showProfile } from './profile/profile';
import { showHelp } from './help/help';
import { getAllUsers } from './timer/listUtil/getAllUsers';
import { isWorking } from './timer/listUtil/isWorking';
import { timerTimeout } from './timer/listUtil/timerTimeout';
import { r... | ot) {
const channel = bot.channel;
const timerList = {};
let userList = await getAllUsers(); // eslint-disable-line
const menuMsg = await channel.send('', {
embed: { description: '`⏺ Start Recording! | 👤 Your Profile | ❓ Need help?`' },
});
// add reactions to message
for (const emoji in emojiMap)... | (res, b | identifier_name |
menu.js | import { addTimer } from './timer/timer';
import { showProfile } from './profile/profile';
import { showHelp } from './help/help';
import { getAllUsers } from './timer/listUtil/getAllUsers';
import { isWorking } from './timer/listUtil/isWorking';
import { timerTimeout } from './timer/listUtil/timerTimeout';
import { r... | let userList = await getAllUsers(); // eslint-disable-line
const menuMsg = await channel.send('', {
embed: { description: '`⏺ Start Recording! | 👤 Your Profile | ❓ Need help?`' },
});
// add reactions to message
for (const emoji in emojiMap) {
await menuMsg.react(emoji);
}
await channel.send('... | async function menuGUI(res, bot) {
const channel = bot.channel;
const timerList = {}; | random_line_split |
menu.js | import { addTimer } from './timer/timer';
import { showProfile } from './profile/profile';
import { showHelp } from './help/help';
import { getAllUsers } from './timer/listUtil/getAllUsers';
import { isWorking } from './timer/listUtil/isWorking';
import { timerTimeout } from './timer/listUtil/timerTimeout';
import { r... | if (emojiMap[reaction.emoji.name]) {
emojiMap[reaction.emoji.name](bot, user, timerList);
}
await reaction.remove(user);
return false;
});
res();
setInterval(() => {
timerTimeout(bot, timerList);
}, 60000);
setInterval(async () => {
refreshPoints(timerList);
isWorking(use... | st channel = bot.channel;
const timerList = {};
let userList = await getAllUsers(); // eslint-disable-line
const menuMsg = await channel.send('', {
embed: { description: '`⏺ Start Recording! | 👤 Your Profile | ❓ Need help?`' },
});
// add reactions to message
for (const emoji in emojiMap) {
awai... | identifier_body |
util.rs | use std::fs::{File, OpenOptions};
use std::hash::Hasher;
use std::io::{Result, Write};
use std::path::Path;
use std::result::Result::Ok;
use std::sync::atomic::{AtomicUsize, Ordering};
use twox_hash::XxHash32 as TwoXhash32;
pub struct XxHash32(TwoXhash32);
impl XxHash32 {
pub fn new() -> XxHash32 |
pub fn update(&mut self, buf: &[u8]) {
self.0.write(buf);
}
pub fn get(&self) -> u32 {
self.0.finish() as u32
}
}
impl Write for XxHash32 {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.update(buf);
Ok(buf.len())
}
fn flush(&mut self) -> Result<... | {
XxHash32(TwoXhash32::with_seed(0))
} | identifier_body |
util.rs | use std::fs::{File, OpenOptions};
use std::hash::Hasher;
use std::io::{Result, Write};
use std::path::Path;
use std::result::Result::Ok;
use std::sync::atomic::{AtomicUsize, Ordering};
use twox_hash::XxHash32 as TwoXhash32;
pub struct XxHash32(TwoXhash32);
impl XxHash32 {
pub fn new() -> XxHash32 {
XxHas... |
pub fn get_file_handle(path: &Path, write: bool) -> Result<File> {
if write {
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)
} else {
OpenOptions::new().read(true).open(path)
}
}
pub struct Sequence(AtomicUsize);
i... | pub fn xxhash32(buf: &[u8]) -> u32 {
let mut hash = TwoXhash32::with_seed(0);
hash.write(buf);
hash.finish() as u32
} | random_line_split |
util.rs | use std::fs::{File, OpenOptions};
use std::hash::Hasher;
use std::io::{Result, Write};
use std::path::Path;
use std::result::Result::Ok;
use std::sync::atomic::{AtomicUsize, Ordering};
use twox_hash::XxHash32 as TwoXhash32;
pub struct XxHash32(TwoXhash32);
impl XxHash32 {
pub fn new() -> XxHash32 {
XxHas... |
let exp = ((bytes as f64).ln() / (unit as f64).ln()) as usize;
let units = if si { "kMGTPE" } else { "KMGTPE" };
let pre = format!(
"{}{}",
units.chars().nth(exp - 1).unwrap(),
if si { "" } else { "i" }
);
format!("{:.1} {}B", bytes / unit.pow(exp as u32), pre)
}
| {
return format!("{} B", bytes);
} | conditional_block |
util.rs | use std::fs::{File, OpenOptions};
use std::hash::Hasher;
use std::io::{Result, Write};
use std::path::Path;
use std::result::Result::Ok;
use std::sync::atomic::{AtomicUsize, Ordering};
use twox_hash::XxHash32 as TwoXhash32;
pub struct | (TwoXhash32);
impl XxHash32 {
pub fn new() -> XxHash32 {
XxHash32(TwoXhash32::with_seed(0))
}
pub fn update(&mut self, buf: &[u8]) {
self.0.write(buf);
}
pub fn get(&self) -> u32 {
self.0.finish() as u32
}
}
impl Write for XxHash32 {
fn write(&mut self, buf: &[u8]... | XxHash32 | identifier_name |
fdentry.rs | use crate::host;
use std::fs::File;
use std::os::unix::prelude::{FileTypeExt, FromRawFd, IntoRawFd, RawFd};
use std::path::PathBuf;
#[derive(Debug)]
pub struct FdEntry {
pub fd_object: FdObject,
pub rights_base: host::__wasi_rights_t,
pub rights_inheriting: host::__wasi_rights_t,
pub preopen_path: Opti... | (rawfd: RawFd) -> FdEntry {
let (ty, mut rights_base, rights_inheriting) =
determine_type_rights(rawfd).expect("can determine file rights");
use nix::fcntl::{fcntl, OFlag, F_GETFL};
let flags_bits = fcntl(rawfd, F_GETFL).expect("fcntl succeeds");
let flags = OFlag::from_bits... | from_raw_fd | identifier_name |
fdentry.rs | use crate::host;
use std::fs::File;
use std::os::unix::prelude::{FileTypeExt, FromRawFd, IntoRawFd, RawFd};
use std::path::PathBuf;
#[derive(Debug)]
pub struct FdEntry {
pub fd_object: FdObject,
pub rights_base: host::__wasi_rights_t,
pub rights_inheriting: host::__wasi_rights_t,
pub preopen_path: Opti... |
impl Drop for FdObject {
fn drop(&mut self) {
if self.needs_close {
nix::unistd::close(self.rawfd).unwrap_or_else(|e| eprintln!("FdObject::drop(): {}", e));
}
}
} | pub needs_close: bool,
// TODO: directories
} | random_line_split |
ahoy.rs | extern crate curl;
extern crate term_painter;
extern crate rustc_serialize;
extern crate toml;
use std::path::Path;
use std::env;
use turbo::util::{CliResult, Config};
use self::term_painter::Color::*;
use self::term_painter::ToStyle;
use self::rustc_serialize::json;
use meg::util::parse_toml::Configz;
//use self::c... | let we = Configz { rand: "sample".to_string()};
let data = we.load(path);
let value: toml::Value = data.unwrap();
let host = value.lookup("api.host").unwrap().as_str().unwrap();
let res = curl::http::handle()
.get(host)
.exec();
let x = res.unwrap().get_code().to_string();
... | let path = Path::new(&set_path).to_str().unwrap(); | random_line_split |
ahoy.rs | extern crate curl;
extern crate term_painter;
extern crate rustc_serialize;
extern crate toml;
use std::path::Path;
use std::env;
use turbo::util::{CliResult, Config};
use self::term_painter::Color::*;
use self::term_painter::ToStyle;
use self::rustc_serialize::json;
use meg::util::parse_toml::Configz;
//use self::c... |
Ok(None)
}
//#[derive(Debug)]
//pub struct ErrCode {
// desc: String
//}
pub fn ahoy() -> String {
let hme = env::home_dir().unwrap();
let y = hme.to_str().unwrap();
let set_path = format!("{}/.megam/megam.toml", y.to_string());
let path = Path::new(&set_path).to_str().unwrap();
let ... | {
println!("{}",
Red.paint("Megam is down!"));
println!("{}",
Blue.paint("Please check whether your host is setup in /home/.megam/megam.toml"));
} | conditional_block |
ahoy.rs | extern crate curl;
extern crate term_painter;
extern crate rustc_serialize;
extern crate toml;
use std::path::Path;
use std::env;
use turbo::util::{CliResult, Config};
use self::term_painter::Color::*;
use self::term_painter::ToStyle;
use self::rustc_serialize::json;
use meg::util::parse_toml::Configz;
//use self::c... | ;
pub fn execute(_: Options, _: &Config) -> CliResult<Option<()>> {
//println!("executing; cmd=meg-version; args={:?}", env::args().collect::<Vec<_>>());
let code = self::ahoy();
// match self::ahoy() {
// Ok(v) => println!("Megam is up and running!"),
// Err(e) => println!("Megam... | Options | identifier_name |
ahoy.rs | extern crate curl;
extern crate term_painter;
extern crate rustc_serialize;
extern crate toml;
use std::path::Path;
use std::env;
use turbo::util::{CliResult, Config};
use self::term_painter::Color::*;
use self::term_painter::ToStyle;
use self::rustc_serialize::json;
use meg::util::parse_toml::Configz;
//use self::c... |
/*
fn error_return(result: Result<curl::http::response::Response, ErrCode>) -> Result<curl::http::response::Response, ErrCode> {
match result {
Ok(n) => {
return Ok(n)
},
Err(FailOne) => return Err(FailOne),
}
} */
| {
let hme = env::home_dir().unwrap();
let y = hme.to_str().unwrap();
let set_path = format!("{}/.megam/megam.toml", y.to_string());
let path = Path::new(&set_path).to_str().unwrap();
let we = Configz { rand: "sample".to_string()};
let data = we.load(path);
let value: toml::Value = data.unw... | identifier_body |
KodiRecordedModel.ts | "use strict";
import * as path from 'path';
import ApiModel from '../ApiModel';
import Sql from '../../../Sql/Sql';
import ModelUtil from '../../ModelUtil';
class KodiRecordedModel extends ApiModel {
private getKodiRecordedListSql: Sql;
constructor(_getKodiRecordedListSql: Sql) {
super();
thi... | this.getKodiRecordedListSql.execute(this.option, (rows) => {
this.results = [];
let list = {}
rows.forEach((data: {}) => {
if(this.results.length >= this.option["length"]) { return; }
//トランスコードされた同じ動画を重複させない
if(typeof list[dat... | //thumbsDir を抽出
let epgrecThumbsPath = configJson.thumbsPath;
let thumbsDir = epgrecThumbsPath.slice(epgrecRoot.length + 1, epgrecThumbsPath.length)
| random_line_split |
KodiRecordedModel.ts | "use strict";
import * as path from 'path';
import ApiModel from '../ApiModel';
import Sql from '../../../Sql/Sql';
import ModelUtil from '../../ModelUtil';
class KodiRecordedModel extends ApiModel {
private getKodiRecordedListSql: Sql;
| (_getKodiRecordedListSql: Sql) {
super();
this.getKodiRecordedListSql = _getKodiRecordedListSql;
}
public execute(): void {
if(this.checkNull(this.option["length"])) { this.option["length"] = 1000; }
this.option["asc"] = this.option["asc"] == 1;
//host
let confi... | constructor | identifier_name |
KodiRecordedModel.ts | "use strict";
import * as path from 'path';
import ApiModel from '../ApiModel';
import Sql from '../../../Sql/Sql';
import ModelUtil from '../../ModelUtil';
class KodiRecordedModel extends ApiModel {
private getKodiRecordedListSql: Sql;
constructor(_getKodiRecordedListSql: Sql) {
super();
thi... | let tsPath = data["path"].toString('UTF-8');
let thumbnail = `${ epgrecHost }/` + ModelUtil.encodeURL(`${ thumbsDir }/${ path.basename(tsPath) }.jpg`);
let videoPath = "";
let status = data["status"];
let ts_del = data["ts_del"];
... | list[data["id"]] = data["trans_id"];
| conditional_block |
no-callback-literal.js | /**
* Ensures that the callback pattern is followed properly
* with an Error object (or undefined or null) in the first position.
*/
'use strict'
// ------------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------... |
case 'ConditionalExpression':
return couldBeError(node.consequent) || couldBeError(node.alternate)
default:
return node.value === null
}
}
// ------------------------------------------------------------------------------
// Rule Definition
// ---------------------------------------------------... | {
let exprs
switch (node.type) {
case 'Identifier':
case 'CallExpression':
case 'NewExpression':
case 'MemberExpression':
case 'TaggedTemplateExpression':
case 'YieldExpression':
return true // possibly an error object.
case 'AssignmentExpression':
return couldBeError(node.r... | identifier_body |
no-callback-literal.js | /**
* Ensures that the callback pattern is followed properly | 'use strict'
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
/**
* Determine if a node has a possiblity to be an Error object
* @param {ASTNode} node ASTNode to check
* @returns {boolea... | * with an Error object (or undefined or null) in the first position.
*/
| random_line_split |
no-callback-literal.js | /**
* Ensures that the callback pattern is followed properly
* with an Error object (or undefined or null) in the first position.
*/
'use strict'
// ------------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------... | (node) {
let exprs
switch (node.type) {
case 'Identifier':
case 'CallExpression':
case 'NewExpression':
case 'MemberExpression':
case 'TaggedTemplateExpression':
case 'YieldExpression':
return true // possibly an error object.
case 'AssignmentExpression':
return couldBeErro... | couldBeError | identifier_name |
test_mkl.py | import pytest
import numpy as np
import scipy.linalg
import scipy.sparse
import qutip
if qutip.settings.has_mkl:
from qutip._mkl.spsolve import mkl_splu, mkl_spsolve
pytestmark = [
pytest.mark.skipif(not qutip.settings.has_mkl,
reason='MKL extensions not found.'),
]
class Test_spsolve... | [0, 0],
])
x = mkl_spsolve(A, b, verbose=True)
ans = np.array([[-0.66666667, 1],
[0.33333333, 0],
[0, 0]])
np.testing.assert_allclose(x.toarray(), ans)
@pytest.mark.parametrize('dtype', [np.float64, np.complex128])
def ... | ])
b = scipy.sparse.csr_matrix([
[0, 1],
[1, 0], | random_line_split |
test_mkl.py | import pytest
import numpy as np
import scipy.linalg
import scipy.sparse
import qutip
if qutip.settings.has_mkl:
from qutip._mkl.spsolve import mkl_splu, mkl_spsolve
pytestmark = [
pytest.mark.skipif(not qutip.settings.has_mkl,
reason='MKL extensions not found.'),
]
class Test_spsolve... | (self):
Adense = np.array([[0, 1, 1],
[1, 0, 1],
[0, 0, 1]])
As = scipy.sparse.csr_matrix(Adense)
np.random.seed(1234)
x = np.random.randn(3)
b = As * x
x2 = mkl_spsolve(As, b, verbose=True)
np.testing.assert_a... | test_single_rhs_vector_real | identifier_name |
test_mkl.py | import pytest
import numpy as np
import scipy.linalg
import scipy.sparse
import qutip
if qutip.settings.has_mkl:
from qutip._mkl.spsolve import mkl_splu, mkl_spsolve
pytestmark = [
pytest.mark.skipif(not qutip.settings.has_mkl,
reason='MKL extensions not found.'),
]
class Test_spsolve... |
lu.delete()
expected_X = scipy.linalg.solve(M, N)
np.testing.assert_allclose(test_X, expected_X)
| test_X[:, k] = lu.solve(N[:, k]) | conditional_block |
test_mkl.py | import pytest
import numpy as np
import scipy.linalg
import scipy.sparse
import qutip
if qutip.settings.has_mkl:
from qutip._mkl.spsolve import mkl_splu, mkl_spsolve
pytestmark = [
pytest.mark.skipif(not qutip.settings.has_mkl,
reason='MKL extensions not found.'),
]
class Test_spsolve... |
def test_rhs_shape_is_maintained(self):
A = scipy.sparse.csr_matrix(np.array([
[1, 0, 2],
[0, 0, 3],
[-4, 5, 6],
], dtype=np.complex128))
b = np.array([0, 2, 0], dtype=np.complex128)
out = mkl_spsolve(A, b, verbose=True)
assert b.shape ==... | M = np.array([
[1, 0, 2],
[0, 0, 3],
[-4, 5, 6],
], dtype=dtype)
sM = scipy.sparse.csr_matrix(M)
N = np.array([
[3, 0, 1],
[0, 2, 0],
[0, 0, 0],
], dtype=dtype)
sX = mkl_spsolve(sM, N, verbose=True)
X... | identifier_body |
submaker_supersu.py | from .submaker import Submaker
import zipfile
import os
import shutil
import logging
logger = logging.getLogger(__name__ )
class SuperSuSubmaker(Submaker):
def make(self, workDir):
supersuZipProp = self.getTargetConfigProperty("root.methods.supersu.path")
assert supersuZipProp.getValue(), "Must s... |
self.__addDirToZip(newSuperSuZip, os.path.join(tmpDir, "common"), "common")
if self.getMaker().getConfig().isMakeable("update.busybox"):
#process file, with busybox onboard in assumption
with open(os.path.join(tmpDir, "META-INF/com/google/androi... | os.remove(os.path.join(tmpDir, superuserApkPath)) | conditional_block |
submaker_supersu.py | from .submaker import Submaker
import zipfile
import os
import shutil
import logging
logger = logging.getLogger(__name__ )
class SuperSuSubmaker(Submaker):
def make(self, workDir):
supersuZipProp = self.getTargetConfigProperty("root.methods.supersu.path")
assert supersuZipProp.getValue(), "Must s... | currPostInst = superSuConfig.get("script.post", [], directOnly=True)
currPostInst.append(postinstFilePath)
superSuConfig.set("update.script.post", currPostInst)
self.setValue("update.files.add." + newSuperSuZipPath.replace(workDir, "").replace(".", "\.") , {
... |
superSuConfig = supersuZipProp.getConfig() | random_line_split |
submaker_supersu.py | from .submaker import Submaker
import zipfile
import os
import shutil
import logging
logger = logging.getLogger(__name__ )
class | (Submaker):
def make(self, workDir):
supersuZipProp = self.getTargetConfigProperty("root.methods.supersu.path")
assert supersuZipProp.getValue(), "Must set %s to the supersu zip file" % supersuZipProp.getKey()
includeApk = self.getTargetConfigValue("root.methods.supersu.include_apk", True)
... | SuperSuSubmaker | identifier_name |
submaker_supersu.py | from .submaker import Submaker
import zipfile
import os
import shutil
import logging
logger = logging.getLogger(__name__ )
class SuperSuSubmaker(Submaker):
def make(self, workDir):
| )
unsupportedArchs = includeArchs.difference(archs)
if len(unsupportedArchs):
unsupportedArchs = list(unsupportedArchs)
raise ValueError("Can't find archs: [%s] in supersu" % (", ".join(unsupportedArchs)))
targetAr... | supersuZipProp = self.getTargetConfigProperty("root.methods.supersu.path")
assert supersuZipProp.getValue(), "Must set %s to the supersu zip file" % supersuZipProp.getKey()
includeApk = self.getTargetConfigValue("root.methods.supersu.include_apk", True)
includeArchs = set(self.getTargetConfigVal... | identifier_body |
ocr_on_cropped.py | import cv2
import cv2.cv as cv | img = cv2.imread("GBIAe.jpg") # numpy.ndarray
height, width, channels = img.shape
# crop the image
crop = (2*height/3, width/3)
roi = img[crop[0]:height, crop[1]:2*width/3]
# Convert the cropped area, which is a numpy.ndarray, to cv2.cv.iplimage
bitmap = cv.CreateImageHeader((roi.shape[1], roi.shape[0]), cv.IPL_DEP... | import tesseract
cv.NamedWindow("win") | random_line_split |
workernavigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WorkerNavigatorBinding;
use crate::dom::bindings::codegen::Bindings::... |
// https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename
fn AppCodeName(&self) -> DOMString {
navigatorinfo::AppCodeName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform
fn Platform(&self) -> DOMString {
navigatorinfo::Platform()
}
// http... | {
navigatorinfo::AppName()
} | identifier_body |
workernavigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WorkerNavigatorBinding;
use crate::dom::bindings::codegen::Bindings::... | } | .or_init(|| Permissions::new(&self.global()))
} | random_line_split |
workernavigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::WorkerNavigatorBinding;
use crate::dom::bindings::codegen::Bindings::... | (&self) -> DOMString {
navigatorinfo::Language()
}
// https://w3c.github.io/permissions/#navigator-and-workernavigator-extension
fn Permissions(&self) -> DomRoot<Permissions> {
self.permissions
.or_init(|| Permissions::new(&self.global()))
}
}
| Language | identifier_name |
placeholder.js | /**
* Placeholder test - checks that an attribute or the content of an
* element itself is not a placeholder (i.e. 'click here' for links).
*/
'use strict';
quail.components.placeholder = function (quail, test, Case, options) {
var resolve = function resolve(element, resolution) {
test.add(Case({
eleme... | else if (options.empty && quail.isUnreadable(text)) {
resolve(this, 'failed');
} else if (quail.strings.placeholders.indexOf(text) > -1) {
resolve(this, 'failed');
}
// It passes.
else {
resolve(this, 'passed');
}
} else {
if (options.empty && typeof ... | {
resolve(this, 'failed');
} | conditional_block |
placeholder.js | /**
* Placeholder test - checks that an attribute or the content of an
* element itself is not a placeholder (i.e. 'click here' for links).
*/
'use strict';
quail.components.placeholder = function (quail, test, Case, options) {
var resolve = function resolve(element, resolution) {
test.add(Case({
eleme... | resolve(this, 'failed');
}
// It passes.
else {
resolve(this, 'passed');
}
} else {
if (options.empty && typeof text !== 'number') {
resolve(this, 'failed');
}
}
});
}; | resolve(this, 'failed');
} else if (quail.strings.placeholders.indexOf(text) > -1) { | random_line_split |
rnn_util.py | import numpy as np
def speak_to_me(model, csxframe, stochastic=False, ngrams=50):
pred = csxframe.primer()
human = csxframe.translate(pred)
chain = "[{}]".format("".join(human))
for _ in range(ngrams): | return chain
def keras_speak(net, dat, stochastic=False, ngrams=50):
pred = dat.primer()
human = dat.translate(pred)
chain = "[{}]".format("".join(human))
for _ in range(ngrams):
inputs = pred[:, -(dat.timestep - 1):, :]
nextpred = net.feedforward(inputs)
pred = np.column_s... | inputs = pred[:, -(csxframe.timestep - 1):, :]
nextpred = model.feedforward(inputs)
pred = np.column_stack((pred, nextpred.reshape(1, *nextpred.shape)))
human = csxframe.translate(nextpred, use_proba=stochastic)
chain += "".join(human) | random_line_split |
rnn_util.py | import numpy as np
def speak_to_me(model, csxframe, stochastic=False, ngrams=50):
pred = csxframe.primer()
human = csxframe.translate(pred)
chain = "[{}]".format("".join(human))
for _ in range(ngrams):
inputs = pred[:, -(csxframe.timestep - 1):, :]
nextpred = model.feedforward(inputs)
... |
return chain
| inputs = pred[:, -(dat.timestep - 1):, :]
nextpred = net.feedforward(inputs)
pred = np.column_stack((pred, nextpred.reshape(1, *nextpred.shape)))
human = dat.translate(nextpred, use_proba=stochastic)
chain += "".join(human) | conditional_block |
rnn_util.py | import numpy as np
def | (model, csxframe, stochastic=False, ngrams=50):
pred = csxframe.primer()
human = csxframe.translate(pred)
chain = "[{}]".format("".join(human))
for _ in range(ngrams):
inputs = pred[:, -(csxframe.timestep - 1):, :]
nextpred = model.feedforward(inputs)
pred = np.column_stack((pred... | speak_to_me | identifier_name |
rnn_util.py | import numpy as np
def speak_to_me(model, csxframe, stochastic=False, ngrams=50):
|
def keras_speak(net, dat, stochastic=False, ngrams=50):
pred = dat.primer()
human = dat.translate(pred)
chain = "[{}]".format("".join(human))
for _ in range(ngrams):
inputs = pred[:, -(dat.timestep - 1):, :]
nextpred = net.feedforward(inputs)
pred = np.column_stack((pred, next... | pred = csxframe.primer()
human = csxframe.translate(pred)
chain = "[{}]".format("".join(human))
for _ in range(ngrams):
inputs = pred[:, -(csxframe.timestep - 1):, :]
nextpred = model.feedforward(inputs)
pred = np.column_stack((pred, nextpred.reshape(1, *nextpred.shape)))
hum... | identifier_body |
strings.js | define({
"addTaskTip": "하나 이상의 필터를 위젯에 추가하고 각각에 대한 매개변수를 구성합니다.",
"enableMapFilter": "프리셋 레이어 필터를 맵에서 제거합니다.",
"newFilter": "새 필터",
"filterExpression": "필터 식",
"layerDefaultSymbolTip": "레이어의 기본 심볼 사용",
"uploadImage": "이미지 업로드",
"selectLayerTip": "레이어를 선택하세요.",
"setTitleTip": "제목을 설정하세요.",
"noTasksTip"... | "zoombacktoTip": "레이어 필터가 모두 해제된 경우 처음 맵 범위로 확대",
"groupByLayerTip": "레이어별로 필터 그룹화",
"autoApplyWhenValueInput": "값 입력 후 이 필터 자동 적용",
"autoApplyWhenWidgetOpen": "위젯이 열릴 때 이 필터 적용",
"info": "정보",
"expressions": "식",
"allowCustom": "사용자 정의 필터 생성 허용",
"filterActions": "기타 필터 작업",
"custom": "사용자 정의 필터 활성화"... | random_line_split | |
unloggedin.py | magic"
def func(self):
session = self.caller
player = PlayerDB.objects.player_search(self.lhs)
if len(player) != 1:
player = None
else:
player = player[0]
if player.name.lower() != self.lhs.lower():
player=None
pswd = None
... | (self):
"""
Uses the Django admin api. Note that unlogged-in commands
have a unique position in that their func() receives
a session object instead of a source_object like all
other types of logged-in commands (this is because
there is no object yet before the player has ... | func | identifier_name |
unloggedin.py | magic"
def func(self):
session = self.caller
player = PlayerDB.objects.player_search(self.lhs)
if len(player) != 1:
player = None
else:
player = player[0]
if player.name.lower() != self.lhs.lower():
player=None
pswd = None
... |
session.msg(string % (playername, playername))
except Exception:
# We are in the middle between logged in and -not, so we have to handle tracebacks
# ourselves at this point. If we don't, we won't see any errors at all.
string = "%s\nThis is a bug. Please e-mail... | string += "\n\nYou can now log with the command 'connect %s <your password>'." | conditional_block |
unloggedin.py | magic"
def func(self):
session = self.caller
player = PlayerDB.objects.player_search(self.lhs)
if len(player) != 1:
player = None
else:
player = player[0]
if player.name.lower() != self.lhs.lower():
player=None
pswd = None
... | class Create(MuxCommand):
"""
Create a new account.
Usage (at login screen):
create <playername> <password>
create "player name" "pass word"
This creates a new player account.
If you have spaces in your name, enclose it in quotes.
"""
key = "create"
aliases = ["cre", "cr"]... | random_line_split | |
unloggedin.py | magic"
def func(self):
session = self.caller
player = PlayerDB.objects.player_search(self.lhs)
if len(player) != 1:
player = None
else:
player = player[0]
if player.name.lower() != self.lhs.lower():
player=None
pswd = None
... | other types of logged-in commands (this is because
there is no object yet before the player has logged in)
"""
session = self.caller
args = self.args
# extract quoted parts
parts = [part.strip() for part in re.split(r"\"|\'", args) if part.strip()]
if len... | """
Connect to the game.
Usage (at login screen):
connect playername password
connect "player name" "pass word"
Use the create command to first create an account before logging in.
If you have spaces in your name, enclose it in quotes.
"""
key = "connect"
aliases = ["conn", "c... | identifier_body |
cast.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | <T>(arr: &ArrayRef) -> &PrimitiveArray<T>
where
T: ArrowPrimitiveType,
{
arr.as_any()
.downcast_ref::<PrimitiveArray<T>>()
.expect("Unable to downcast to primitive array")
}
/// Force downcast ArrayRef to DictionaryArray<T>
pub fn as_dictionary_array<T>(arr: &ArrayRef) -> &DictionaryArray<T>
wh... | as_primitive_array | identifier_name |
cast.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
/// Force downcast ArrayRef to DictionaryArray<T>
pub fn as_dictionary_array<T>(arr: &ArrayRef) -> &DictionaryArray<T>
where
T: ArrowDictionaryKeyType,
{
arr.as_any()
.downcast_ref::<DictionaryArray<T>>()
.expect("Unable to downcast to dictionary array")
}
macro_rules! array_downcast_fn {
... | {
arr.as_any()
.downcast_ref::<PrimitiveArray<T>>()
.expect("Unable to downcast to primitive array")
} | identifier_body |
cast.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | }
/// Force downcast ArrayRef to DictionaryArray<T>
pub fn as_dictionary_array<T>(arr: &ArrayRef) -> &DictionaryArray<T>
where
T: ArrowDictionaryKeyType,
{
arr.as_any()
.downcast_ref::<DictionaryArray<T>>()
.expect("Unable to downcast to dictionary array")
}
macro_rules! array_downcast_fn {
... | random_line_split | |
TableConnectableBlokk.ts | import { gql } from '@apollo/client'
import { connectableContextMenuConnectableFragment } from 'v2/components/ConnectableContextMenu/fragments/connectableContextMenu'
export const channelTableContentsConnectableFragment = gql`
fragment ChannelTableContentsConnectable on Konnectable {
__typename
...Connectab... |
... on Model {
created_at(relative: true)
updated_at(relative: true)
}
... on Attachment {
file_url
image_url(size: THUMB)
created_at
file_url
image_url
source {
url
provider_url
}
}
... on Embed {
embed_html
image_... | }
} | random_line_split |
global-position-strategy.d.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { PositionStrategy } from './position-strategy';
import { OverlayReference } from '../overlay-reference';
/**
... | top(value?: string): this;
/**
* Sets the left position of the overlay. Clears any previously set horizontal position.
* @param value New left offset.
*/
left(value?: string): this;
/**
* Sets the bottom position of the overlay. Clears any previously set vertical position.
* @pa... | /**
* Sets the top position of the overlay. Clears any previously set vertical position.
* @param value New top offset.
*/ | random_line_split |
global-position-strategy.d.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { PositionStrategy } from './position-strategy';
import { OverlayReference } from '../overlay-reference';
/**
... | implements PositionStrategy {
/** The overlay to which this strategy is attached. */
private _overlayRef;
private _cssPosition;
private _topOffset;
private _bottomOffset;
private _leftOffset;
private _rightOffset;
private _alignItems;
private _justifyContent;
private _width;
... | GlobalPositionStrategy | identifier_name |
ViewInfo.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
import raw from 'raw.macro';
import {... |
render() {
const classname =
this.props.match.path === '/info' ? 'info-view-center' : 'info-view';
return (
<div className={classname}>
<ReactMarkdown plugins={[gfm]} children={markdown} />
</div>
);
}
}
InfoView.propTypes = {};
const mapStateToProps = null;
const mapDispa... | {
if (document.body) {
document.body.className = document.body.className.replace(
InfoView.BODY_CLASS,
''
);
}
} | identifier_body |
ViewInfo.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
import raw from 'raw.macro';
import {... | class InfoView extends Component {
static propTypes = {
setNavigationVisibility: PropTypes.func
};
static BODY_CLASS = 'helerm-info-view';
componentDidMount() {
if (document.body) {
document.body.className = document.body.className + InfoView.BODY_CLASS;
}
this.props.setNavigationVisibil... | const markdown = raw('./content_fi.md');
| random_line_split |
ViewInfo.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
import raw from 'raw.macro';
import {... |
}
render() {
const classname =
this.props.match.path === '/info' ? 'info-view-center' : 'info-view';
return (
<div className={classname}>
<ReactMarkdown plugins={[gfm]} children={markdown} />
</div>
);
}
}
InfoView.propTypes = {};
const mapStateToProps = null;
const mapD... | {
document.body.className = document.body.className.replace(
InfoView.BODY_CLASS,
''
);
} | conditional_block |
ViewInfo.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
import raw from 'raw.macro';
import {... | () {
if (document.body) {
document.body.className = document.body.className + InfoView.BODY_CLASS;
}
this.props.setNavigationVisibility(true);
}
componentWillUnmount() {
if (document.body) {
document.body.className = document.body.className.replace(
InfoView.BODY_CLASS,
... | componentDidMount | identifier_name |
manager.py | ids = dict(server_pids) # make a copy
while True:
for server, pids in server_pids.items():
for pid in pids:
try:
# let pid stop if it wants to
os.waitpid(pid, os.WNOHANG)
except OSError, e:
if e.errno no... |
elif server == 'rest':
server_names.update(REST_SERVERS)
elif '*' in server:
# convert glob to regex
server_names.update([s for s in ALL_SERVERS if
re.match(server.replace('*', '.*'), s)])
else:
... | server_names.update(MAIN_SERVERS) | conditional_block |
manager.py | name__, repr(str(self)))
def __hash__(self):
return hash(str(self))
def __eq__(self, other):
try:
return self.server == other.server
except AttributeError:
return False
def get_pid_file_name(self, conf_file):
"""Translate conf_file to a correspondin... | if conf_file in conf_files:
already_started = True
print _("%s running (%s - %s)") % (self.server, pid, conf_file)
elif not kwargs.get('number', 0):
already_started = True | random_line_split | |
manager.py | ids = {}
for server in self.servers:
signaled_pids = server.stop(**kwargs)
if not signaled_pids:
print _('No %s running') % server
else:
server_pids[server] = signaled_pids
# all signaled_pids, i.e. list(itertools.chain(*server_pids.va... | status | identifier_name | |
manager.py | _pids = dict(server_pids) # make a copy
while True:
for server, pids in server_pids.items():
for pid in pids:
try:
# let pid stop if it wants to
os.waitpid(pid, os.WNOHANG)
except OSError, e:
if e.errno ... | killed_pids.add(killed_pid)
if not killed_pids.symmetric_difference(signaled_pids):
# all proccesses have been stopped
return 0
# reached interval n watch_pids w/o killing all servers
for server, pids in server_pids.items():
if not kil... | """stops a server
"""
server_pids = {}
for server in self.servers:
signaled_pids = server.stop(**kwargs)
if not signaled_pids:
print _('No %s running') % server
else:
server_pids[server] = signaled_pids
# all signaled_p... | identifier_body |
assign-card-student.ts | /**
* Created by manel on 31/5/17.
*/
import { Component, ViewChild, ElementRef } from '@angular/core';
import {
Loading, NavController, NavParams,
Platform
} from 'ionic-angular';
import { TranslateService } from 'ng2-translate/ng2-translate';
import {CollectionCard} from "../../../../../model/collectionCard";
i... | @Component({
selector: 'page-assign-card-student',
templateUrl: './assign-card-student.html'
})
export class CardAssignStudent {
@ViewChild('map') mapElement: ElementRef;
public collectionCard: CollectionCard = new CollectionCard();
public cards: Array<Card> = Array<Card>();
loading: Loading;
public stud... | random_line_split | |
assign-card-student.ts | /**
* Created by manel on 31/5/17.
*/
import { Component, ViewChild, ElementRef } from '@angular/core';
import {
Loading, NavController, NavParams,
Platform
} from 'ionic-angular';
import { TranslateService } from 'ng2-translate/ng2-translate';
import {CollectionCard} from "../../../../../model/collectionCard";
i... | (
public navParams: NavParams,
public navController: NavController,
public utilsService: UtilsService,
public collectionService: CollectionService,
public translateService: TranslateService,
public ionicService: IonicService,
public platform: Platform,
) {
this.collectionCard.id = t... | constructor | identifier_name |
assign-card-student.ts | /**
* Created by manel on 31/5/17.
*/
import { Component, ViewChild, ElementRef } from '@angular/core';
import {
Loading, NavController, NavParams,
Platform
} from 'ionic-angular';
import { TranslateService } from 'ng2-translate/ng2-translate';
import {CollectionCard} from "../../../../../model/collectionCard";
i... |
this.navController.setRoot(MenuPage).then(()=>{
this.navController.push(CollectionTpage);
});
}
public assignToRandomStudent(){
let studentPosition = this.randomNumber(0,this.students.length);
let studentName;
this.students.forEach(student => {
if (student.id == this.students[stude... | {
this.collectionService.assignCardToStudent(studentId,this.cards[i].id).subscribe(response => {
this.utilsService.presentToast('Card assigned to student successfuly');
},
error => {
this.ionicService.showAlert(this.translateService.instant('APP.ERROR'), error);
});
... | conditional_block |
rectangle_wave.rs | //! Game Boy sounds 1 and 2 generate a rectangular waveform
//! with an envelope function. Channel 1 can also sweep through a
//! frequency range.
use spu::{Sample, Mode};
use spu::envelope::Envelope;
pub struct RectangleWave {
/// True if the sound is generating samples
running: bool,
/// Signal d... | return Some(div);
}
// Update the frequency
let offset = div >> (self.shift as usize);
match self.direction {
SweepDirection::Up => {
let div = div + offset;
if div > 0x7ff {
// We stop on overflow
... | // Do nothing and wait for the next step | random_line_split |
rectangle_wave.rs | //! Game Boy sounds 1 and 2 generate a rectangular waveform
//! with an envelope function. Channel 1 can also sweep through a
//! frequency range.
use spu::{Sample, Mode};
use spu::envelope::Envelope;
pub struct RectangleWave {
/// True if the sound is generating samples
running: bool,
/// Signal d... |
pub fn mode(&self) -> Mode {
self.mode
}
pub fn set_mode(&mut self, mode: Mode) {
self.mode = mode;
}
pub fn set_length(&mut self, len: u8) {
if len >= 64 {
panic!("sound length out of range: {}", len);
}
let len = len as u32;
self.rem... | {
// New envelope will become active at the next start
self.start_envelope = envelope;
if !envelope.dac_enabled() {
self.running = false;
}
} | identifier_body |
rectangle_wave.rs | //! Game Boy sounds 1 and 2 generate a rectangular waveform
//! with an envelope function. Channel 1 can also sweep through a
//! frequency range.
use spu::{Sample, Mode};
use spu::envelope::Envelope;
pub struct | {
/// True if the sound is generating samples
running: bool,
/// Signal duty cycle
duty: DutyCycle,
/// Period counter, the period length is configurable and is used
/// to select the desired output frequency. This counter loops 8
/// times per cycle to let us generate the ... | RectangleWave | identifier_name |
Dialog.js | define([
'dojo/_base/declare',
'dojo/query',
'dojo/_base/array',
'dojo/_base/lang',
'dojo/_base/html',
'dijit/_Widget',
'dijit/_TemplatedMixin',
'dijit/_WidgetsInTemplateMixin',
'dijit/Dialog',
'dojo/on',
'dgrid/Grid',
'dgrid/Keyboard',
'dgrid/Selection',
'dojo/te... | _hideDialog: function () {
if (this.isDestroyedAfterHiding) this.destroyRecursive();
}
});
}); | random_line_split | |
properties_methods1.js | /** @constructor */
function RecordSet(f) {
| /*
[
{
symbols: [
{
doc: { tags: [] },
returns: [],
type: "",
properties: [],
isa: "CONSTRUCTOR",
desc: "",
alias: "RecordSet",
memberof: "",
params: [
... | /** @function */
this.write = f;
}
| identifier_body |
properties_methods1.js | /** @constructor */
function Re | ) {
/** @function */
this.write = f;
}
/*
[
{
symbols: [
{
doc: { tags: [] },
returns: [],
type: "",
properties: [],
isa: "CONSTRUCTOR",
desc: "",
alias: "RecordSet",
... | cordSet(f | identifier_name |
properties_methods1.js | /** @constructor */
function RecordSet(f) {
/** @function */
this.write = f; | [
{
symbols: [
{
doc: { tags: [] },
returns: [],
type: "",
properties: [],
isa: "CONSTRUCTOR",
desc: "",
alias: "RecordSet",
memberof: "",
params: [
... | }
/* | random_line_split |
test_shelve.py | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... |
def test_unshelve(self):
uuid = self._post_server()
self._test_server_action(uuid, 'os-shelve', 'shelve')
self._test_server_action(uuid, 'os-unshelve', 'unshelve')
class UnshelveJson277Test(test_servers.ServersSampleBase):
sample_dir = "os-shelve"
microversion = '2.77'
scenar... | uuid = self._post_server()
self._test_server_action(uuid, 'os-shelve', 'shelve')
self._test_server_action(uuid, 'os-shelve-offload', 'shelveOffload') | identifier_body |
test_shelve.py | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... | (self):
uuid = self._post_server()
self._test_server_action(uuid, 'os-shelve', 'shelve')
self._test_server_action(uuid, 'os-unshelve-null', 'unshelve')
| test_unshelve_no_az | identifier_name |
test_shelve.py | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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 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 th... | # | random_line_split |
mtwt.rs | key = (ctxt, id, to);
* match table.rename_memo.borrow_mut().entry(key) {
Vacant(entry) => entry.set(idx_push(&mut *table.table.borrow_mut(), Rename(id, to, ctxt))),
Occupied(entry) => entry.into_mut(),
}
}
/// Apply a list of renamings to a context
// if these rename lists get long, it would... | let resolvedthis =
resolve_internal(Ident{name:id.name, ctxt:subctxt},
table, resolve_table);
if (resolvedthis == resolvedfrom)
&& (marksof_internal(ctxt, resolvedthis, table)
== marksof_... | table, resolve_table); | random_line_split |
mtwt.rs | key = (ctxt, id, to);
* match table.rename_memo.borrow_mut().entry(key) {
Vacant(entry) => entry.set(idx_push(&mut *table.table.borrow_mut(), Rename(id, to, ctxt))),
Occupied(entry) => entry.into_mut(),
}
}
/// Apply a list of renamings to a context
// if these rename lists get long, it would... | ,
Mark(mark, tl) => {
xor_push(&mut result, mark);
loopvar = tl;
},
Rename(_,name,tl) => {
// see MTWT for details on the purpose of the stopname.
// short version: it prevents duplication of effort.
if n... | {
return result;
} | conditional_block |
mtwt.rs | () = HashMap::new();
});
with_resolve_table_mut(|table| *table = HashMap::new());
}
/// Add a value to the end of a vec, return its index
fn idx_push<T>(vec: &mut Vec<T>, val: T) -> u32 {
vec.push(val);
(vec.len() - 1) as u32
}
/// Resolve a syntax object to a name, per MTWT.
pub fn resolve(id: Ident)... | test_marksof | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.