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 |
|---|---|---|---|---|
MessageSigner.go | ature(dmessage, object, signer.GetPublicKey)
return isEncrypted, isSigned, err
}
// SignMessages returns whether messages MUST be signed on sending or receiving
func (signer *MessageSigner) SignMessages() bool {
return signer.signMessages
}
// VerifySignedMessage parses and verifies the message signature
// as per ... |
// Unsubscribe to messages on the given address
func (signer *MessageSigner) Unsubscribe(
address string,
handler func(address string, message string) error) {
signer.messenger.Unsubscribe(address, handler)
}
// PublishEncrypted sign and encrypts the payload and publish the resulting message on the given address
... | {
signer.messenger.Subscribe(address, handler)
} | identifier_body |
main.rs | `None`, it assumes `jq` is in
/// the system path and attempts to invoke it using simply the command `jq`. Otherwise, it invokes
/// `jq` using the provided path.
async fn run_jq(
filter: &String,
json_string: String,
jq_path: &Option<PathBuf>,
) -> Result<String, anyhow::Error> {
let mut cmd_jq = matc... | let filter = String::from("{foo: .foo, baz: .bar}");
let json5_string = String::from(
r##"{
//Foo
foo: 0,
//Bar
bar: 42
}"##,
);
let format = Json5Format::new().unwrap();
let (parsed_json5, json_string) = reader::read_json5(json5_string).unwrap();
let ... | );
}
#[fuchsia_async::run_singlethreaded(test)]
async fn run_jq5_deconstruct_filter() { | random_line_split |
main.rs | `None`, it assumes `jq` is in
/// the system path and attempts to invoke it using simply the command `jq`. Otherwise, it invokes
/// `jq` using the provided path.
async fn run_jq(
filter: &String,
json_string: String,
jq_path: &Option<PathBuf>,
) -> Result<String, anyhow::Error> {
let mut cmd_jq = matc... |
#[fuchsia_async::run_singlethreaded(test)]
async fn run_jq5_deconstruct_filter() {
let filter = String::from("{foo: .foo, baz: .bar}");
let json5_string = String::from(
r##"{
//Foo
foo: 0,
//Bar
bar: 42
}"##,
);
let format = Json5Format::new().unwrap();
... | {
let filter = String::from("{foo2: .foo1, bar2: .bar1}");
let input = String::from(r#"{"foo1": 0, "bar1": 42}"#);
let jq_path = Some(PathBuf::from(JQ_PATH_STR));
assert_eq!(
run_jq(&filter, input, &jq_path).await.unwrap(),
r##"{
"foo2": 0,
"bar2": 42
}
"##
... | identifier_body |
main.rs | `None`, it assumes `jq` is in
/// the system path and attempts to invoke it using simply the command `jq`. Otherwise, it invokes
/// `jq` using the provided path.
async fn run_jq(
filter: &String,
json_string: String,
jq_path: &Option<PathBuf>,
) -> Result<String, anyhow::Error> {
let mut cmd_jq = matc... | (
filter: &String,
file: &PathBuf,
jq_path: &Option<PathBuf>,
) -> Result<String, anyhow::Error> {
let (parsed_json5, json_string) = reader::read_json5_fromfile(&file)?;
run_jq5(&filter, parsed_json5, json_string, jq_path).await
}
async fn run(
filter: String,
files: Vec<PathBuf>,
jq_pa... | run_jq5_on_file | identifier_name |
main.rs | `None`, it assumes `jq` is in
/// the system path and attempts to invoke it using simply the command `jq`. Otherwise, it invokes
/// `jq` using the provided path.
async fn run_jq(
filter: &String,
json_string: String,
jq_path: &Option<PathBuf>,
) -> Result<String, anyhow::Error> {
let mut cmd_jq = matc... | else {
Err(anyhow::anyhow!("jq returned exit code 0 but no output or error message"))
}
}
/// Calls jq on the provided json and then fills back comments at correct places.
async fn run_jq5(
filter: &String,
parsed_json5: ParsedDocument,
json_string: String,
jq_path: &Option<PathBuf>,
) -> ... | {
Err(anyhow::anyhow!("jq returned with non-zero exit code but no error message"))
} | conditional_block |
DAQClient.py | getAttributes(self, bean, fldList):
attrs = self.__client.mbean.getAttributes(bean, fldList)
if type(attrs) == dict and len(attrs) > 0:
for k in attrs.keys():
attrs[k] = self.__unFixValue(attrs[k])
return attrs
def getBeanNames(self):
return self.__beanL... | return { "id" : self.__id,
"compName" : self.name(),
"compNum" : self.num(),
"host" : self.__host,
"rpcPort" : self.__port,
"mbeanPort" : self.__mbeanPort } | identifier_body | |
DAQClient.py | . If obj is a dict or list, recuse into it
converting all such masquerading strings. All other types are
unaltered. This pairs with the similarly named fix* methods in
icecube.daq.juggler.mbean.XMLRPCServer """
if type(obj) is dict:
for k in obj.keys():
ob... |
return attrs
def getBeanNames(self):
return self.__beanList
def getBeanFields(self, bean):
if bean not in self.__beanList:
msg = "Bean %s not in list of beans for %s" % \
(bean, self.__compName)
raise BeanFieldNotFoundException(msg)
ret... | attrs[k] = self.__unFixValue(attrs[k]) | conditional_block |
DAQClient.py | ion. If obj is a dict or list, recuse into it
converting all such masquerading strings. All other types are
unaltered. This pairs with the similarly named fix* methods in
icecube.daq.juggler.mbean.XMLRPCServer """
if type(obj) is dict:
for k in obj.keys():
... | def getSingleBeanField(self, name, field):
if self.__mbean is None:
return None
return self.__mbean.get(name, field)
def host(self):
return self.__host
def id(self):
return self.__id
def isSource(self):
"Is this component a source of data?"
... | else:
csStr += ']'
return csStr
| random_line_split |
DAQClient.py | component name"
def __init__(self, name, num):
self.__name = name
self.__num = num
def __repr__(self):
return self.fullName()
def fileName(self):
return '%s-%d' % (self.__name, self.__num)
def fullName(self):
if self.__num == 0 and self.__name[-3:].lower() != ... | resetLogging | identifier_name | |
lib.rs | . Furthermore, if
/// you need more control of the connection's parameters use [`Options::connect()`].
///
/// **Warning:** There are asynchronous errors that can happen during operation of NATS client.
/// To handle them, add handler for [`Options::error_callback()`].
///
/// # Examples
///
/// If no scheme is provide... | request_with_headers_or_timeout | identifier_name | |
lib.rs | unsafe_code,
unused,
unused_qualifications
)
)]
#![cfg_attr(feature = "fault_injection", deny(
// over time, consider enabling the following commented-out lints:
// clippy::else_if_without_else,
// clippy::indexing_slicing,
// clippy::multiple_crate_versions,
// clippy::m... | missing_docs,
nonstandard_style,
rust_2018_idioms,
trivial_casts,
trivial_numeric_casts, | random_line_split | |
lib.rs | /// # nc.subscribe("foo")?.with_handler(move |m| { m.respond("ans=42")?; Ok(()) });
/// for msg in nc.request_multi("foo", "Help")?.iter().take(1) {}
/// # Ok(())
/// # }
/// ```
pub fn request_multi(&self, subject: &str, msg: impl AsRef<[u8]>) -> io::Result<Subscription> {
// Publish a req... | {
self.0.client.publish(subject, reply, headers, msg.as_ref())
} | identifier_body | |
prebuilt.go | (p *prebuiltLibraryLinker) linkerDeps(ctx DepsContext, deps Deps) Deps {
return p.libraryDecorator.linkerDeps(ctx, deps)
}
func (p *prebuiltLibraryLinker) linkerFlags(ctx ModuleContext, flags Flags) Flags {
return flags
}
func (p *prebuiltLibraryLinker) linkerProps() []interface{} {
return p.libraryDecorator.link... | (name string) string {
return strings.TrimPrefix(name, "prebuilt_")
}
func NewPrebuiltLibrary(hod android.HostOrDeviceSupported) (*Module, *libraryDecorator) {
module, library := NewLibrary(hod)
module.compiler = nil
prebuilt := &prebuiltLibraryLinker{
libraryDecorator: library,
}
module.linker = prebuilt
mo... | implementationModuleName | identifier_name |
prebuilt.go | (p *prebuiltLibraryLinker) linkerDeps(ctx DepsContext, deps Deps) Deps {
return p.libraryDecorator.linkerDeps(ctx, deps)
}
func (p *prebuiltLibraryLinker) linkerFlags(ctx ModuleContext, flags Flags) Flags {
return flags
}
func (p *prebuiltLibraryLinker) linkerProps() []interface{} {
return p.libraryDecorator.link... | p.libraryDecorator.flagExporter.reexportDeps(deps.ReexportedDeps...)
p.libraryDecorator.flagExporter.addExportedGeneratedHeaders(deps.ReexportedGeneratedHeaders...)
p.libraryDecorator.flagExporter.setProvider(ctx)
// TODO(ccross): verify shared library dependencies
srcs := p.prebuiltSrcs(ctx)
if len(srcs) > 0 {... |
p.libraryDecorator.flagExporter.exportIncludes(ctx)
p.libraryDecorator.flagExporter.reexportDirs(deps.ReexportedDirs...)
p.libraryDecorator.flagExporter.reexportSystemDirs(deps.ReexportedSystemDirs...)
p.libraryDecorator.flagExporter.reexportFlags(deps.ReexportedFlags...) | random_line_split |
prebuilt.go |
func (p *prebuiltLibraryLinker) linkerDeps(ctx DepsContext, deps Deps) Deps {
return p.libraryDecorator.linkerDeps(ctx, deps)
}
func (p *prebuiltLibraryLinker) linkerFlags(ctx ModuleContext, flags Flags) Flags {
return flags
}
func (p *prebuiltLibraryLinker) linkerProps() []interface{} {
return p.libraryDecorato... | {} | identifier_body | |
prebuilt.go | (p *prebuiltLibraryLinker) linkerDeps(ctx DepsContext, deps Deps) Deps {
return p.libraryDecorator.linkerDeps(ctx, deps)
}
func (p *prebuiltLibraryLinker) linkerFlags(ctx ModuleContext, flags Flags) Flags {
return flags
}
func (p *prebuiltLibraryLinker) linkerProps() []interface{} {
return p.libraryDecorator.link... | }
if p.shared() {
p.unstrippedOutputFile = in
libName := p.libraryDecorator.getLibName(ctx) + flags.Toolchain.ShlibSuffix()
outputFile := android.PathForModuleOut(ctx, libName)
var implicits android.Paths
if p.stripper.NeedsStrip(ctx) {
stripFlags := flagsToStripFlags(flags)
stripped := and... | {
builderFlags := flagsToBuilderFlags(flags)
if len(srcs) > 1 {
ctx.PropertyErrorf("srcs", "multiple prebuilt source files")
return nil
}
p.libraryDecorator.exportVersioningMacroIfNeeded(ctx)
in := android.PathForModuleSrc(ctx, srcs[0])
if p.static() {
depSet := android.NewDepSetBuilder(android... | conditional_block |
handTrack1.py | , 9 * cols / 30, 10 * cols / 30, 11 * cols / 30, 12 * cols / 30], dtype=np.uint32)
hand_rect_two_x = hand_rect_one_x + 10
hand_rect_two_y = hand_rect_one_y + 10
for i in range(total_rectangle):
cv2.rectangle(frame, (hand_rect_one_y[i], hand_rect_one_x[i]),
(hand_rect_two_y[i]... | global lengthColec
data = np.random.normal(0, 21, 100)
bins = np.arange(0, 21, 1)
plot.xlim([min(data)-.5, max(data)+.5])
plot.hist(data, bins=bins, alpha=0.5)
plot.title('metaData plot')
plot.xlabel('side lengths)')
plot.ylabel('Number of occurance')
plot.show() | identifier_body | |
handTrack1.py | py))
#print("Should be : " + str(bx) + ", "+ str(by))
#print("bad")
#cv2.circle(frame, bx,by, 10,[10,10,10]
#print("num matched: " +str(numMatch))
if numMatch >neededHands and area_cnt > 2000 and ((tempx-bx)**2 + (tempy-by)**2 < 150**2) :#and (areaHand ==... | farthest_point | identifier_name | |
handTrack1.py | 2.calcHist([roi], [0, 1], None, [180, 256], [0, 180, 0, 256])
return cv2.normalize(hand_hist, hand_hist, 0, 255, cv2.NORM_MINMAX)
def hist_masking(backFrame, frame, hist):
global fWidth, fHeight
global bx, by, areaHand, cropped, sx, sy, width, height
range = (int)((7000**(1/2)))
width = 2*int(rang... | if resetCount <=0:
bx = int(fWidth/2)
by = int(fHeight/2)
#print("Reset data: " + str(bx) + " " + str(resetCount) + " " + str(by))
pressed_key = cv2.waitKey(1)
_, frame = capture.read()
if is_hand_hist_created==False:
txtColor = [0,255,0]
... | conditional_block | |
handTrack1.py | 2)
hand_rect_one_y = np.array(
[9 * cols / 30, 10 * cols / 30, 11 * cols / 30, 12 * cols / 30 , 9 * cols / 30, 10 * cols / 30, 11 * cols / 30, 12 * cols / 30, 9 * cols / 30,
10 * cols / 30, 11 * cols / 30, 12 * cols / 30, 9 * cols / 30, 10 * cols / 30, 11 * cols / 30, 12 * cols / 30], dtype=np.uin... | random_line_split | ||
histogramMatching.py | ((rect_corner1[0]+rect_corner2[0])/2,(rect_corner1[1]+rect_corner2[1])/2)
# labels blob numbers
cv2.putText(imgFrame2Copy, str(i), blobs[i].centerPositions[-1], intFontFace, dblFontScale, (0,255,0), intFontThickness);
# draws box around the blob
cv2.rectangle(imgFrame2C... | (point1,point2):
intX = abs(point1[0] - point2[0])
intY = abs(point1[1] - point2[1])
return math.sqrt(math.pow(intX, 2) + math.pow(intY, 2))
#matching algorithm to corelate two blob objects by matching it with the expected one
def matchCurrentFrameBlobsToExistingBlobs(existingBlobs,currentFrameBlobs):
... | distanceBetweenPoints | identifier_name |
histogramMatching.py | ((rect_corner1[0]+rect_corner2[0])/2,(rect_corner1[1]+rect_corner2[1])/2)
# labels blob numbers
cv2.putText(imgFrame2Copy, str(i), blobs[i].centerPositions[-1], intFontFace, dblFontScale, (0,255,0), intFontThickness);
# draws box around the blob
cv2.rectangle(imgFrame2C... |
#find the distance between two points p1 and p2
def distanceBetweenPoints(point1,point2):
intX = abs(point1[0] - point2[0])
intY = abs(point1[1] - point2[1])
return math.sqrt(math.pow(intX, 2) + math.pow(intY, 2))
#matching algorithm to corelate two blob objects by matching it with the expected one
def... | image = np.zeros(imageSize, dtype=np.uint8)
contours = []
for blob in blobs:
if blob.blnStillBeingTracked == True:
contours.append(blob.currentContour)
cv2.drawContours(image, contours, -1,(255,255,255), -1);
cv2.imshow(strWindowsName, image); | identifier_body |
histogramMatching.py |
#changing the colorspace to grayscale
imgFrame1Copy = cv2.cvtColor(imgFrame1Copy,cv2.COLOR_BGR2GRAY)
imgFrame2Copy = cv2.cvtColor(imgFrame2Copy,cv2.COLOR_BGR2GRAY)
#applying gaussianblur
imgFrame1Copy = cv2.GaussianBlur(imgFrame1Copy,(5,5),0)
imgFrame2Copy = cv2.GaussianBlur(imgFrame2Copy,(5,5... | def getDifferenceHulls(imgFrame1,imgFrame2):
#making duplicates of the above frames
imgFrame1Copy = imgFrame1.copy()
imgFrame2Copy = imgFrame2.copy() | random_line_split | |
histogramMatching.py | ((rect_corner1[0]+rect_corner2[0])/2,(rect_corner1[1]+rect_corner2[1])/2)
# labels blob numbers
cv2.putText(imgFrame2Copy, str(i), blobs[i].centerPositions[-1], intFontFace, dblFontScale, (0,255,0), intFontThickness);
# draws box around the blob
cv2.rectangle(imgFrame2C... |
else:
addNewBlob(currentFrameBlob, existingBlobs)
for existingBlob in existingBlobs:
if (existingBlob.blnCurrentMatchFoundOrNewBlob == False):
existingBlob.intNumOfConsecutiveFramesWithoutAMatch +=1;
if (existingBlob.intNumOfConsecutiveFramesWithoutAMatch >= 5):
... | addBlobToExistingBlobs(currentFrameBlob, existingBlobs, intIndexOfLeastDistance) | conditional_block |
chat.js |
}
}
function chat_show()
{
$("chatbox").style.visibility = 'visible';
$("chatntf").style.right = '310px';
setCookie("cards_chatbox", "1", 365);
chat_resize();
post_center();
}
function chat_hide()
{
$("chatbox").style.visibility = 'hidden';
$("chatntf").style.right = '10px';
setCookie("c... | {
return unescape(y);
} | conditional_block | |
chat.js |
function chat_isopen()
{
if(getCookie("cards_chatbox") == "1")
return 1;
else
return 0;
}
function showhide_chat(item)
{
if($(item).style.visibility != 'visible')
{
$(item).style.visibility = 'visible';
$("chatntf").style.right = '310px';
setCookie("cards_chatbox", "1", 365);
}else... | {
$("chatbox").style.visibility = 'hidden';
$("chatntf").style.right = '10px';
setCookie("cards_chatbox", "0", 365);
chat_resize();
post_center();
} | identifier_body | |
chat.js | (getCookie("cards_chatbox") == "1")
return 1;
else
return 0;
}
function showhide_chat(item)
{
if($(item).style.visibility != 'visible')
{
$(item).style.visibility = 'visible';
$("chatntf").style.right = '310px';
setCookie("cards_chatbox", "1", 365);
}else{
$(item).style.visibility = 'h... | (users, userav, newcount, rid, csignature, usersloc)
{
var o = $('chatntf');
/* offline available busy away */
var avm = ["555555", "99cc66", "ff6633", "ffcc00"];
var nbv = "";
var ulist = "";
var maxut = o.getAttribute('data-maxt');
var cct = o.getAttribute('data-ccount');
var ppt ... | chatc_create | identifier_name |
chat.js | chat_resize();
post_center();
}
function chat_isopen()
{
if(getCookie("cards_chatbox") == "1")
return 1;
else
return 0;
}
function showhide_chat(item)
{
if($(item).style.visibility != 'visible')
{
$(item).style.visibility = 'visible';
$("chatntf").style.right = '310px';
setCookie("... | setCookie("cards_chatbox", "0", 365);
| random_line_split | |
canvas_play.js | c.beginPath();
c.moveTo(x,y+radius);
c.lineTo(x,y+height-radius);
c.quadraticCurveTo(x,y+height,x+radius,y+height);
if (t) {
c.lineTo(x+width/2-4,y+height);
c.lineTo(x+width/2,y+height+7);
c.lineTo(x+width/2+4,y+height);
}
c.lineTo(x+width-radius,y+height);
c.quadraticCurveTo... | this.hsc = Math.floor(this.h * this.size);
this.customTextSize = 0;
this.dir = raw.dir;
//присвоивать дефолтную картинку, а потом подгружать новую
this.skin = new Image(); | random_line_split | |
canvas_play.js | (data, f = a => a) {
data.react = f;
this.spaces.add(data);
return data;
}
deleteSpace(link) {
return this.spaces.delete(link);
}
computeVector(A, B) {
return [
B[0] - A[0],
B[1] - A[1],
Math.round(Math.sqrt(Math.pow(B[0] - A[0], 2) + Math.pow(B[1] - A[1], 2)))
];
}
... | this.roundedRect(tmp, 2, (i ? 2 : 9 + height), rectWidth, rectHeight, 5, i);
tmp.fill();
tmp.fillStyle = game.colorOfInterface.text;
tmp.font = `${14 * k}px monospace`;
m.text.forEach((b, j) => tmp.fillText(b, 5, 13 * k + interval * j + (i ? 0 : 7 + height), rectWidth));
}
for (let... | nt.createElement('img');
m.image.src = tmp.canvas.toDataURL();
m.image.onload = () => stopRendering = false;
} */
console.time('draw')
const tmp = game.layer[3],
k = 0.8 + 0.2 * this.size + this.customTextSize,
interval = 12 * k,
rectHeight = m.text.length * interva... | identifier_body |
canvas_play.js | 11 : 4);
tmp.canvas.height = m.height;
tmp.canvas.width = 4 + m.rectWidth;
tmp.fillStyle = game.colorOfInterface.main;
tmp.lineWidth = 3;
this.roundedRect(tmp,2,2,m.rectWidth,m.rectHeight,5,(newMsg ? true : false));
tmp.fill();
tmp.fillStyle = game.colorOfInterface.text;
tmp.font = `${1... | .abs(full | identifier_name | |
s_expressions.rs | use SyntaxKind::*;
impl From<SyntaxKind> for rowan::SyntaxKind {
fn from(kind: SyntaxKind) -> Self {
Self(kind as u16)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Lang {}
impl rowan::Language for Lang {
type Kind = SyntaxKind;
fn kind_from_raw(raw: rowan::Synta... | {
Eof,
RParen,
Ok,
}
impl Parser {
fn parse(mut self) -> Parse {
// Make sure that the root node covers all source
self.builder.start_node(ROOT.into());
// Parse a list of S-expressions
loop {
match self.sexp() {
... | SexpRes | identifier_name |
s_expressions.rs | stack
/// of currently in-progress nodes
use rowan::GreenNodeBuilder;
/// This is the main type this crate exports.
/// It is also immutable, like a GreenNode,
/// but it contains parent pointers, offsets, and
/// has identity semantics.
/// SyntaxNode exist in borrowed and owned flavors,
/// which is controlled by t... | let sexps = "
92
(+ 62 30)
(/ 92 0)
nan | random_line_split | |
s_expressions.rs | use SyntaxKind::*;
impl From<SyntaxKind> for rowan::SyntaxKind {
fn from(kind: SyntaxKind) -> Self {
Self(kind as u16)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Lang {}
impl rowan::Language for Lang {
type Kind = SyntaxKind;
fn kind_from_raw(raw: rowan::Synta... | "R_PAREN@[14; 15)".to_string(),
]
);
}
/// So far, we've been working with a homogeneous untyped tree.
/// It's nice to provide generic tree operations, like traversals,
/// but it's a bad fit for semantic analysis.
/// This crate itself does not provide AST facilities directly,
/// but it is ... | {
let text = "(+ (* 15 2) 62)";
let node = parse(text);
assert_eq!(
format!("{:?}", node),
"ROOT@[0; 15)", // root node, spanning 15 bytes
);
assert_eq!(node.children().count(), 1);
let list = node.children().next().unwrap();
let children = list.children().map(|child| format!... | identifier_body |
s_expressions.rs | SyntaxKind::*;
impl From<SyntaxKind> for rowan::SyntaxKind {
fn from(kind: SyntaxKind) -> Self {
Self(kind as u16)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Lang {}
impl rowan::Language for Lang {
type Kind = SyntaxKind;
fn kind_from_raw(raw: rowan::SyntaxKi... |
}
fn kind(&self) -> SexpKind {
Atom::cast(self.0.clone())
.map(SexpKind::Atom)
.or_else(|| List::cast(self.0.clone()).map(SexpKind::List))
.unwrap()
}
}
// Let's enhance AST nodes with ancillary functions and
// eval.
impl Root {
fn sexps(&self) -> impl Ite... | {
None
} | conditional_block |
play.js | {hanlderName:'list_play',src:'../../assets/images/list_play.png',className:'button-bar-list_play',hidden:false},
{hanlderName:'cycle_list_play',src:'../../assets/images/cycle_list_play.png',className:'button-bar-cycle_list_play',hidden:true},
{hanlderName:'cycle_single_play',src:'../../assets/images/cycle_... | newIndex=null
console.log(musicList);
console.log(nowIndex);
console.log(type);
console.log(playType);
if (musicList.length<=1) {
return
}
//随机播放(点上一曲或者下一曲哪个按钮都没联系,随机切)
if (playType=='random_play') {
//获取一个小于播放列表length的随机数并且不等于当前播放的index
let getRandomNum=fu... | playType=this.data.playType, | random_line_split |
play.js | hanlderName:'list_play',src:'../../assets/images/list_play.png',className:'button-bar-list_play',hidden:false},
{hanlderName:'cycle_list_play',src:'../../assets/images/cycle_list_play.png',className:'button-bar-cycle_list_play',hidden:true},
{hanlderName:'cycle_single_play',src:'../../assets/images/cycle_si... | =>{
return {
...v,
hidden:v.hanlderName==playType?false:true
}
}),
playType:playType
})
//改变自然播放完毕后的逻辑
app.globalData.backgroundAudioManager.onEnded(()=>{
console.log('in');
let nowIndex=this.getNowPlayIndex(),
musicList=this.data.... | ata({
playTypeList:playTypeList.map(v | conditional_block |
controller.go | ,
}
type ControllerConfiguration struct {
ReconcilerSyncLoopPeriod metav1.Duration
}
// DefaultCaffe2JobControllerConfiguration is the suggested caffe2-operator configuration for production.
var DefaultCaffe2JobControllerConfiguration ControllerConfiguration = ControllerConfiguration{
ReconcilerSyncLoopPeriod: meta... |
return true
}
utilruntime.HandleError(fmt.Errorf("Error syncing job: %v", err))
c.workQueue.AddRateLimited(key)
return true
}
// syncCaffe2Job will sync the job with the given. This function is not meant to be invoked
// concurrently with the same key.
//
// When a job is completely processed it will return t... | {
c.workQueue.Forget(key)
} | conditional_block |
controller.go | processNextWorkItem() bool {
key, quit := c.workQueue.Get()
if quit {
return false
}
defer c.workQueue.Done(key)
forget, err := c.syncHandler(key.(string))
if err == nil {
if forget {
c.workQueue.Forget(key)
}
return true
}
utilruntime.HandleError(fmt.Errorf("Error syncing job: %v", err))
c.workQ... | {
var newConditions []api.Caffe2JobCondition
for _, c := range conditions {
if c.Type == condType {
continue
}
newConditions = append(newConditions, c)
}
return newConditions
} | identifier_body | |
controller.go | ,
}
type ControllerConfiguration struct {
ReconcilerSyncLoopPeriod metav1.Duration
}
// DefaultCaffe2JobControllerConfiguration is the suggested caffe2-operator configuration for production.
var DefaultCaffe2JobControllerConfiguration ControllerConfiguration = ControllerConfiguration{
ReconcilerSyncLoopPeriod: meta... | // caffe2JobLister can list/get caffe2jobs from the shared informer's store.
caffe2JobLister listers.Caffe2JobLister
// podLister can list/get pods from the shared informer's store.
podLister corelisters.PodLister
// serviceLister can list/get services from the shared informer's store.
serviceLister corelisters.S... | // caffe2JobClientSet is a clientset for CRD Caffe2Job.
caffe2JobClient jobclient.Interface
| random_line_split |
controller.go | ,
}
type ControllerConfiguration struct {
ReconcilerSyncLoopPeriod metav1.Duration
}
// DefaultCaffe2JobControllerConfiguration is the suggested caffe2-operator configuration for production.
var DefaultCaffe2JobControllerConfiguration ControllerConfiguration = ControllerConfiguration{
ReconcilerSyncLoopPeriod: meta... | () bool {
key, quit := c.workQueue.Get()
if quit {
return false
}
defer c.workQueue.Done(key)
forget, err := c.syncHandler(key.(string))
if err == nil {
if forget {
c.workQueue.Forget(key)
}
return true
}
utilruntime.HandleError(fmt.Errorf("Error syncing job: %v", err))
c.workQueue.AddRateLimited(... | processNextWorkItem | identifier_name |
featureFileReader.js | 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.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
... | (chr, start, end) {
// insure that header has been loaded -- tabix _blockLoader is initialized as side effect
if(!this.dataURI && !this.header) {
await this.readHeader()
}
//console.log("Using index"
const config = this.config
const parser = this.parser
... | loadFeaturesWithIndex | identifier_name |
featureFileReader.js | import GWASParser from "../gwas/gwasParser.js"
import AEDParser from "../aed/AEDParser.js"
import {loadIndex} from "../bam/indexFactory.js"
import getDataWrapper from "./dataWrapper.js"
import BGZLineReader from "../util/bgzLineReader.js"
import BGZBlockLoader from "../bam/bgzBlockLoader.js"
/**
* Reader for "bed lik... | }
}
} | random_line_split | |
featureFileReader.js | 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.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
... | const maxSize = Object.values(index.chrIndex)
.flatMap(chr => chr.blocks)
.map(block => block.max)
.reduce((previous, current) =>
Math.min(previous, current), Number.MAX_SAFE_INTEGER)
... | {
if (this.dataURI) {
await this.loadFeaturesFromDataURI(this.dataURI)
return this.header
} else {
if (this.config.indexURL) {
const index = await this.getIndex()
if (!index) {
// Note - it should be impossible to ... | identifier_body |
featureFileReader.js | 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.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
... |
//console.log("Using index"
const config = this.config
const parser = this.parser
const tabix = this.index.tabix
const refId = tabix ? this.index.sequenceIndexMap[chr] : chr
if (refId === undefined) {
return []
}
const genome = this.genome
... | {
await this.readHeader()
} | conditional_block |
client.go | .URL.Query()
q.Set(k, v)
r.URL.RawQuery = q.Encode()
}
}
func TypeFilter(t MetricType) Filter {
return Param("type", t.shortForm())
}
func TagsFilter(t map[string]string) Filter {
j := tagsEncoder(t)
return Param("tags", j)
}
// Requires HWKMETRICS-233
func IdFilter(regexp string) Filter {
return Param("id"... |
u := &url.URL{
Host: p.Host,
Path: p.Path,
Scheme: "http",
Opaque: fmt.Sprintf("//%s/%s", p.Host, p.Path),
}
return &Client{
url: u,
Tenant: p.Tenant,
client: &http.Client{
Timeout: timeout,
},
}, nil
}
// Public functions
// Older functions..
// Return a single definition
func (self ... | {
p.Path = base_url
} | conditional_block |
client.go | r.URL.Query()
q.Set(k, v)
r.URL.RawQuery = q.Encode()
}
}
func TypeFilter(t MetricType) Filter {
return Param("type", t.shortForm())
}
func TagsFilter(t map[string]string) Filter {
j := tagsEncoder(t)
return Param("tags", j)
}
// Requires HWKMETRICS-233
func IdFilter(regexp string) Filter {
return Param("i... | md := []*MetricDefinition{}
if b != nil {
if err = json.Unmarshal(b, &md); err != nil {
return nil, err
}
}
return md, err
} else if r.StatusCode > 399 {
return nil, self.parseErrorResponse(r)
}
return nil, nil
}
// Update tags
func (self *Client) UpdateTags(t MetricType, id string, tags map[st... | b, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
} | random_line_split |
client.go | {
o = prepend(o, self.Url("GET", TypeEndpoint(t), SingleMetricEndpoint(id), TagEndpoint()))
r, err := self.Send(o...)
if err != nil {
return nil, err
}
defer r.Body.Close()
if r.StatusCode == http.StatusOK {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
tags := make(map[strin... | {
return func(u *url.URL) {
addToUrl(u, "tags")
}
} | identifier_body | |
client.go | err := f(r)
if err != nil {
return nil, err
}
}
return self.client.Do(r)
}
// Commands
func prepend(slice []Modifier, a ...Modifier) []Modifier {
p := make([]Modifier, 0, len(slice)+len(a))
p = append(p, a...)
p = append(p, slice...)
return p
}
// Create new Definition
func (self *Client) Create(md M... | process | identifier_name | |
ifd.rs | 1
TileOffsets 324; // 144 LONG TilesPerImage
TileByteCounts 325; // 145 SHORT or LONG TilesPerImage
InkSet 332; // 14C SHORT 1
InkNames 333; // 14D ASCII t ... | new | identifier_name | |
ifd.rs | 11 SHORT or LONG StripsPerImage
Orientation 274; // 112 SHORT 1
SamplesPerPixel 277; // 115 SHORT 1
RowsPerStrip 278; // 116 SHORT or LONG 1
StripByteCounts 279; // 117 LONG or S... | // tags!{
// // Baseline tags:
// Artist 315; // TODO add support
// // grayscale images PhotometricInterpretation 1 or 3
// BitsPerSample 258;
// CellLength 265; // TODO add support
// CellWidth 264; // TODO add support
// // palette-color images (PhotometricInterpretation 3)
// ColorMa... |
// Note: These tags appear in the order they are mentioned in the TIFF reference
// https://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf | random_line_split |
client.py | query_params['trace'] = self.trace
return super(BigQueryModel, self).request(headers, path_params, query_params, body_value)
# pylint: disable=E1002
class BigQueryHttp(apiclient_request.HttpRequest):
"""Converts errors into BigQuery errors."""
def __init__(self, http_model, *args, **kwargs):
... | (self, use_jwt_credentials_auth=False, jwt_account_name='', jwt_key_func=None, oauth_credentails_file=None, trace=None):
"""
:param trace: A value to add to all outgoing requests
:return:
"""
super(BigQueryClient, self).__init__()
self.trace = trace
self.use_jwt_c... | __init__ | identifier_name |
client.py | query_params['trace'] = self.trace
return super(BigQueryModel, self).request(headers, path_params, query_params, body_value)
# pylint: disable=E1002
class BigQueryHttp(apiclient_request.HttpRequest):
"""Converts errors into BigQuery errors."""
def __init__(self, http_model, *args, **kwargs):
... |
@staticmethod
def is_in_gce_machine():
try:
metadata_uri = 'http://metadata.google.internal'
http = httplib2.Http()
http.request(metadata_uri, method='GET')
return True
except httplib2.ServerNotFoundError:
return False
@property... | 'SERVER_SOFTWARE' in os.environ and os.environ['SERVER_SOFTWARE'].startswith('Google App Engine/') | identifier_body |
client.py | query_params['trace'] = self.trace
return super(BigQueryModel, self).request(headers, path_params, query_params, body_value)
# pylint: disable=E1002
class BigQueryHttp(apiclient_request.HttpRequest):
"""Converts errors into BigQuery errors."""
def __init__(self, http_model, *args, **kwargs):
... | @staticmethod
def factory(bigquery_model):
"""Returns a function that creates a BigQueryHttp with the given model."""
def _create_bigquery_http_request(*args, **kwargs):
captured_model = bigquery_model
return BigQueryHttp(captured_model, *args, **kwargs)
return _... | random_line_split | |
client.py | query_params['trace'] = self.trace
return super(BigQueryModel, self).request(headers, path_params, query_params, body_value)
# pylint: disable=E1002
class BigQueryHttp(apiclient_request.HttpRequest):
"""Converts errors into BigQuery errors."""
def __init__(self, http_model, *args, **kwargs):
... |
elif self.oauth_credentails_file: # Local oauth token
http = httplib2.Http()
storage = Storage(self.oauth_credentails_file)
credentials = storage.get()
if not credentials:
raise EnvironmentError('No credential file present')
http = c... | from google.appengine.api import memcache
scope = 'https://www.googleapis.com/auth/bigquery'
credentials = AppAssertionCredentials(scope=scope)
logging.info("Using Standard appengine authentication")
return credentials.authorize(httplib2.Http(memcache)) | conditional_block |
command.rs | /// Unsigned int vector to clear uvec4 targets.
Uint([u32; 4]),
}
/// Optional instance parameters: (instance count, buffer offset)
pub type InstanceParams = (InstanceCount, VertexCount);
/// An interface of the abstract command buffer. It collects commands in an
/// efficient API-specific manner, to be ready fo... | for buffer in self.inner.mapped_reads().chain(self.inner.mapped_writes()) {
unsafe {
buffer.mapping().unwrap().release_access();
} | random_line_split | |
command.rs | Type, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(S... | (&self) -> AccessInfoBuffers<R> {
self.mapped_reads.iter()
}
/// Returns the mapped buffers that The GPU will write to
pub fn mapped_writes(&self) -> AccessInfoBuffers<R> {
self.mapped_writes.iter()
}
/// Is there any mapped buffer reads ?
pub fn has_mapped_reads(&self) -> bool... | mapped_reads | identifier_name |
command.rs | Type, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(S... |
}
/// Register a buffer write access
pub fn buffer_write(&mut self, buffer: &handle::RawBuffer<R>) {
if buffer.is_mapped() {
self.mapped_writes.insert(buffer.clone());
}
}
/// Returns the mapped buffers that The GPU will read from
pub fn mapped_reads(&self) -> Acce... | {
self.mapped_reads.insert(buffer.clone());
} | conditional_block |
command.rs | Type, InstanceCount, VertexCount,
SubmissionResult, SubmissionError};
use {state, target, pso, shade, texture, handle};
/// A universal clear color supporting integet formats
/// as well as the standard floating-point.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(S... |
}
/// Informations about what is accessed by a bunch of commands.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AccessInfo<R: Resources> {
mapped_reads: HashSet<handle::RawBuffer<R>>,
mapped_writes: HashSet<handle::RawBuffer<R>>,
}
impl<R: Resources> AccessInfo<R> {
/// Creates empty access informati... | {
ClearColor::Uint([v, 0, 0, 0])
} | identifier_body |
xcapture.go | 0 {
chistMu.Lock()
var cbracket hdrhistogram.Bracket
var wbracket hdrhistogram.Bracket
var rbracket hdrhistogram.Bracket
brackets := chist.CumulativeDistribution()
for _, bracket := range brackets {
if bracket.ValueAt > int64(d) {
break
}
cbracket = bracket
}
bracke... | if m <= 0 {
return d
}
r := d % m
if r < 0 {
r = -r
if r+r < m {
return d + r
}
if d1 := d - m + r; d1 < d {
return d1
}
return d // overflow
}
if r+r < m {
return d - r
}
if d1 := d + m - r; d1 > d {
return d1
} | identifier_body | |
xcapture.go | Monitor struct {
C chan CaptureEvent
elCh chan xgb.Event
win *Window
}
func NewResizeMonitor(el *EventLoop, win *Window) *ResizeMonitor {
res := &ResizeMonitor{
C: make(chan CaptureEvent, 1),
elCh: make(chan xgb.Event),
win: win,
}
el.Register(res.elCh)
go res.start()
return res
}
func (res *Res... | {
if rhist.TotalCount()%int64(*fps) == 0 {
chistMu.Lock()
var cbracket hdrhistogram.Bracket
var wbracket hdrhistogram.Bracket
var rbracket hdrhistogram.Bracket
brackets := chist.CumulativeDistribution()
for _, bracket := range brackets {
if bracket.ValueAt > int64(d) {
break
}... | conditional_block | |
xcapture.go | size := b.PageSize
return b.Data[offset : offset+size : offset+size]
}
type BitmapInfoHeader struct {
Size uint32
Width int32
Height int32
Planes uint16
BitCount uint16
Compression [4]byte
SizeImage uint32
XPelsPerMeter int32
YPelsPerMeter int32
ClrUsed uint3... | }
func (b Buffer) Page(idx int) []byte {
offset := b.PageOffset(idx) | random_line_split | |
xcapture.go | (xs ...int) int {
if len(xs) == 0 {
return 0
}
m := xs[0]
for _, x := range xs[1:] {
if x < m {
m = x
}
}
return m
}
// TODO(dh): this definition of a window is specific to Linux. On
// Windows, for example, we wouldn't have an integer specifier for the
// window.
type Window struct {
ID int
mu ... | min | identifier_name | |
converter.rs | use ConvertedShader;
use error::Error;
#[derive(Debug, Clone)]
pub struct ConverterOptions {
/// Additional directories to search in when resolving `#include` statements.
///
/// The path to the file being converted is always implicity used as a search path, taking
/// priority over any paths listed he... | () -> Self {
ConverterOptions {
include_search_paths: Vec::new(),
macros: HashMap::new(),
target_version: GlslVersion::V1_00Es,
}
}
}
impl ConverterOptions {
pub fn new() -> Self {
Self::default()
}
fn resolve_include(&self,
... | default | identifier_name |
converter.rs | use ConvertedShader;
use error::Error;
#[derive(Debug, Clone)]
pub struct ConverterOptions {
/// Additional directories to search in when resolving `#include` statements.
///
/// The path to the file being converted is always implicity used as a search path, taking
/// priority over any paths listed he... | },
})?;
let shader = ast.compile()?;
let uniforms = find_uniform_mappings(&ast)?;
Ok(ConvertedShader {
shader,
uniforms,
})
}
fn hlsl_to_spirv(&mut self,
source: &str,
source_filename: &str,... | {
let source_path = source_path.into();
let source_filename = source_path.to_string_lossy();
let mut source = String::new();
File::open(&source_path)?.read_to_string(&mut source)?;
let spirv = self.hlsl_to_spirv(&source,
source_filename.as... | identifier_body |
converter.rs | use ConvertedShader;
use error::Error;
#[derive(Debug, Clone)]
pub struct ConverterOptions {
/// Additional directories to search in when resolving `#include` statements.
///
/// The path to the file being converted is always implicity used as a search path, taking
/// priority over any paths listed he... | }))
.collect();
find_source_file(name, &search_paths_and_parent)?
}
_ => find_source_file(name, &self.include_search_paths)?
};
let mut content = String::new();
File::open(&path)
.and_then(|mut include... | let path = match (include_type, PathBuf::from(name).parent()) {
(shaderc::IncludeType::Relative, Some(parent_path)) => {
let mut search_paths_and_parent: Vec<_> = iter::once(parent_path)
.chain(self.include_search_paths.iter().map(|path_buf_ref| {
... | random_line_split |
controllers.js | ');
$scope.user = {};
$rootScope.isWelcomePage = false;
$scope.cancel = function() {
$ionicViewSwitcher.nextDirection('back');
$rootScope.shouldHide = true;
$state.go('/01-welcome');
};
$scope.checkInput = function() {
// console.log('Check input fired');
var reName = /^[a-z ,.'-]+$/i;
... | animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
$ionicSlideBoxDelegate.slide(0, 500);
$timeout(function() {
Dropbox.getImages(function() {
$rootScope.gallery = $rootScope.gallery.chunk(6);
$ionicSlideBoxDelegate.update();
// Upd... |
$scope.refreshGallery = function() {
console.log('refreshing gallery');
$ionicLoading.show({ | random_line_split |
main.rs | 100.mhz()).freeze();
let mut delay = hal::delay::Delay::new(cp.SYST, clocks);
let gpiod = dp.GPIOD.split();
let bps = Bps(115200);
let mut tx = configure(dp.USART3, gpiod.pd8, gpiod.pd9, bps, clocks);
let mut buffer = [0u8; 20];
write_string_to_serial(&mut tx, "AHB1: ... |
loop {
if can1.tx[0].tir.read().txrq().bit_is_clear() {
break;
}
}
loop {
led.set_high().unwrap();
delay.delay_ms(1000_u32);
led.set_low().unwrap();
delay.delay_ms(1000_u32);
}
}
loop {
... | random_line_split | |
main.rs | (clocks.hclk().0 / 1000000).numtoa_str(10, &mut buffer);
write_bytes_to_serial(&mut tx, &buffer);
write_string_to_serial(&mut tx, "\n");
let mut buffer = [0u8; 20];
write_string_to_serial(&mut tx, "APB1: ");
(clocks.pclk1().0 / 1000000).numtoa_str(10, &mut buffer);
... | {
if let (Some(dp), Some(cp)) = (
stm32::Peripherals::take(),
cortex_m::peripheral::Peripherals::take(),
) {
let gpiob = dp.GPIOB.split();
let mut led = gpiob.pb7.into_push_pull_output();
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(100.mhz()).freez... | identifier_body | |
main.rs | 100.mhz()).freeze();
let mut delay = hal::delay::Delay::new(cp.SYST, clocks);
let gpiod = dp.GPIOD.split();
let bps = Bps(115200);
let mut tx = configure(dp.USART3, gpiod.pd8, gpiod.pd9, bps, clocks);
let mut buffer = [0u8; 20];
write_string_to_serial(&mut tx, "AHB1: ... |
delay.delay_ms(1000_u32);
write_string_to_serial(&mut tx, "Waiting for INAK to be cleared\n");
}
write_string_to_serial(&mut tx, "INAK cleared\n");
// Set to standard identifier
unsafe {
can1.tx[0]
.tir
.modify(|_, w|... | {
break;
} | conditional_block |
main.rs | 100.mhz()).freeze();
let mut delay = hal::delay::Delay::new(cp.SYST, clocks);
let gpiod = dp.GPIOD.split();
let bps = Bps(115200);
let mut tx = configure(dp.USART3, gpiod.pd8, gpiod.pd9, bps, clocks);
let mut buffer = [0u8; 20];
write_string_to_serial(&mut tx, "AHB1: ... | <X, Y>(
uart: USART3,
tx: PD8<X>,
rx: PD9<Y>,
baudrate: Bps,
clocks: Clocks,
) -> hal::serial::Tx<stm32f4::stm32f413::USART3> {
let config = Config {
baudrate,
..Config::default()
};
let tx = tx.into_alternate_af7();
let rx = rx.into_alternate_af7();
let serial =... | configure | identifier_name |
cfg.py | queen',
'prince',
'princess',
'angel',
'god',
'friend',
'ally',
'spouse',
'covenantor',
'phantom',
'dark spirit',
'bonfire',
'ember',
'fog wall',
... | 'nightmare',
'cosmos',
'oedon',
'communion',
'donation',
| random_line_split | |
automaton.go | transition with the specified source, dest, min, max.
func (r *Automaton) AddTransition(source, dest, min, max int) error {
//bounds := r.nextState / 2
r.growTransitions()
if r.curState != source {
if r.curState != -1 {
r.finishCurrentState()
}
// Move to next source:
r.curState = source
if r.states[... |
func (r *Automaton) growTransitions() {
if r.nextTransition+3 > len(r.transitions) {
r.transitions = util.Grow(r.transitions, r.nextTransition+3)
}
}
// Sorts transitions by dest, ascending, then min label ascending, then max label ascending
type destMinMaxSorter struct {
from, to int
*Automaton
}
func (r *de... | {
if r.nextState+2 > len(r.states) {
r.states = util.Grow(r.states, r.nextState+2)
}
} | identifier_body |
automaton.go | new transition with the specified source, dest, min, max.
func (r *Automaton) | (source, dest, min, max int) error {
//bounds := r.nextState / 2
r.growTransitions()
if r.curState != source {
if r.curState != -1 {
r.finishCurrentState()
}
// Move to next source:
r.curState = source
if r.states[2*r.curState] != -1 {
return fmt.Errorf("from state (%d) already had transitions adde... | AddTransition | identifier_name |
automaton.go | transition with the specified source, dest, min, max.
func (r *Automaton) AddTransition(source, dest, min, max int) error {
//bounds := r.nextState / 2
r.growTransitions()
if r.curState != source {
if r.curState != -1 {
r.finishCurrentState()
}
// Move to next source:
r.curState = source
if r.states[... |
return false
}
func (r *destMinMaxSorter) Swap(i, j int) {
iStart, jStart := 3*i, 3*j
r.swapOne(iStart, jStart)
r.swapOne(iStart+1, jStart+1)
r.swapOne(iStart+2, jStart+2)
}
func (r *destMinMaxSorter) swapOne(i, j int) {
r.transitions[i], r.transitions[j] =
r.transitions[j], r.transitions[i]
}
// Sorts tra... | {
return false
} | conditional_block |
automaton.go | func NewAutomatonV1(numStates, numTransitions int) *Automaton {
return &Automaton{
curState: -1,
deterministic: true,
states: make([]int, numStates*2),
isAccept: bitset.New(uint(numStates)),
transitions: make([]int, numTransitions*3),
}
}
// CreateState Create a new state.
func (r *Automaton)... | random_line_split | ||
main.rs | res.push(mem::take(&mut curtok));
}
}
curtok.push(c);
state = LexerState::ContinueIdent;
} else {
// Punct
match state {
LexerState::Start | LexerState::ContinuePunct => {}
LexerState:... | let mut model: Model = serde_json::from_str(&model_str)?; | random_line_split | |
main.rs |
}
impl ClassifiedTest {
fn max_score(&self) -> f64 {
self.class_scores[0].1
}
}
fn is_id_start(c: char) -> bool {
// This is XID_Start OR '_' (which formally is not a XID_Start).
// We also add fast-path for ascii idents
('a'..='z').contains(&c)
|| ('A'..='Z').contains(&c)
... | {
if let Some(index) = self.map.get(&*feature) {
Some(*index)
} else if read_only {
None
} else {
let new_index = u32::try_from(self.features.len()).unwrap();
self.features.push(feature.clone().into_owned());
self.map.insert(feature.int... | identifier_body | |
main.rs | also add fast-path for ascii idents
('a'..='z').contains(&c)
|| ('A'..='Z').contains(&c)
|| c == '_'
|| (c > '\x7f' && unicode_xid::UnicodeXID::is_xid_start(c))
}
fn is_id_continue(c: char) -> bool {
// This is exactly XID_Continue.
// We also add fast-path for ascii idents
('a... | lse if let prefix @ Some(_) = name.strip_suffix(".stderr") {
prefix
} else if let prefix @ Some(_) = name.strip_suffix(".stdout") {
prefix
} else if let prefix @ Some(_) = name.strip_suffix(".fixed") {
prefix
} else {
None
};
if let... | prefix
} e | conditional_block |
main.rs | also add fast-path for ascii idents
('a'..='z').contains(&c)
|| ('A'..='Z').contains(&c)
|| c == '_'
|| (c > '\x7f' && unicode_xid::UnicodeXID::is_xid_start(c))
}
fn is_id_continue(c: char) -> bool {
// This is exactly XID_Continue.
// We also add fast-path for ascii idents
('a... | (s: &str) -> &str {
const KEYWORDS: &[&str] = &[
"_",
"as",
"break",
"const",
"continue",
"crate",
"else",
"enum",
"extern",
"false",
"fn",
"for",
"if",
"impl",
"in",
"let",
"loop"... | generalize | identifier_name |
lib.rs | () -> c_int {
unsafe {
zmq_ffi::zmq_errno()
}
}
fn strerror(errnum: c_int) -> String {
unsafe {
let s = zmq_ffi::zmq_strerror(errnum);
ffi::CStr::from_ptr(s).to_str().unwrap().to_string()
}
}
/// Report 0MQ library version
///
/// Binding of `void zmq_version (int *major, int *... | errno | identifier_name | |
lib.rs | message.
pub fn with_capcity(len: usize) -> Result<Message, Error> {
let mut msg = zmq_ffi::zmq_msg_t { unknown: [0; MSG_SIZE] };
let rc = unsafe { zmq_ffi::zmq_msg_init_size(&mut msg, len as size_t) };
if rc == -1 {
Err(Error::from_last_err())
} else {
Ok(Me... | /// Bindng of `int zmq_has (const char *capability);`
///
/// The function shall report whether a specified capability is available in the library | random_line_split | |
lib.rs | name: ident, $opt: expr, $map: expr, $rt: ty) => {
pub fn $name(&self) -> Result<$rt, Error> {
let rc = unsafe { zmq_ffi::zmq_ctx_get(self.ctx_ptr, $opt as c_int) };
if rc == -1 {
Err(Error::from_last_err())
} else {
Ok($map(rc))
}
... | /// Move content of a message to another message.
///
/// Binding of `int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src);`.
///
/// Move the content of the message object referenced by src to the message object referenced by dest.
/// No actual copying of message content is performed,
/// dest... | unsafe {
let mut msg = try!(Message::with_capcity(data.len()));
std::ptr::copy_nonoverlapping(data.as_ptr(), msg.as_mut_ptr(), data.len());
Ok(msg)
}
}
| identifier_body |
lib.rs | mq_socket (void *context, int type);`
///
/// The type argument specifies the socket type, which determines the semantics of communication over the socket.
/// The newly created socket is initially unbound, and not associated with any endpoints.
/// In order to establish a message flow a socket must fir... | None
} els | conditional_block | |
ui.js | this.currentframe = 0;
this.frame_x = [];
this.anim_speed = 2;
this.init = function(getLayerContext, state){
this.layercontext = getLayerContext(this.LAYER_ID);
this.state = state;
$("#name").css({
"display": "block",
"z-index": this.LAYER_ID+1
});
$("#name>form").on({
... | switch(this.state){
case "starting":
$(".ui").css({
"z-index": this.LAYER_ID+1
});
break;
case "running":
break;
case "loading":
//check if images finish loading before starting game
var allLoaded = true;
for(var i=0; i<game.system.entities.length; i++){
... | }
};
this.update = function(){ | random_line_split |
ui.js | this.currentframe = 0;
this.frame_x = [];
this.anim_speed = 2;
this.init = function(getLayerContext, state){
this.layercontext = getLayerContext(this.LAYER_ID);
this.state = state;
$("#name").css({
"display": "block",
"z-index": this.LAYER_ID+1
});
$("#name>form").on({
... |
this.score.css("z-index", this.LAYER_ID+1);
game.system.layermanager.clearLayer(this.LAYER_ID);
game.system.state = this.state = "running";
break;
default:
break;
}
};
this.draw = function(){
switch(this.state){
case "starting":
this.score.html("High Score:... | {
break;
} | conditional_block |
input.go | Input struct {
Block
TextFgColor Attribute
TextBgColor Attribute
IsCapturing bool
IsMultiLine bool
TextBuilder TextBuilder
SpecialChars map[string]string
ShowLineNo bool
Name string
CursorX int
CursorY int
//DebugMode bool
//debugMessage string
// internal vars
lines ... |
func (i *Input) moveRight() {
// if we are at the end of the line move to the next
if i.cursorLinePos >= len(i.lines[i.cursorLineIndex]) {
origLine := i.cursorLineIndex
i.moveDown()
if origLine < len(i.lines)-1 {
i.cursorLinePos = 0
}
return
}
i.cursorLinePos++
}
| {
// if we are at the beginning of the line move the cursor to the previous line
if i.cursorLinePos == 0 {
origLine := i.cursorLineIndex
i.moveUp()
if origLine > 0 {
i.cursorLinePos = len(i.lines[i.cursorLineIndex])
}
return
}
i.cursorLinePos--
} | identifier_body |
input.go | Input struct {
Block
TextFgColor Attribute
TextBgColor Attribute
IsCapturing bool
IsMultiLine bool
TextBuilder TextBuilder
SpecialChars map[string]string
ShowLineNo bool
Name string
CursorX int
CursorY int
//DebugMode bool
//debugMessage string
// internal vars
lines ... |
// append a newline in the current position with the content we computed in the previous if statement
i.lines = append(
i.lines[:i.cursorLineIndex+1],
append(
[]string{newString},
i.lines[i.cursorLineIndex+1:]...,
)...,
)
}
// increment the line index, reset the cursor to ... | {
newString = i.lines[i.cursorLineIndex][i.cursorLinePos:]
i.lines[i.cursorLineIndex] = i.lines[i.cursorLineIndex][:i.cursorLinePos]
} | conditional_block |
input.go | Text(text string) {
i.lines = strings.Split(text, NEW_LINE)
}
// Lines returns the slice of strings with the content of the input field. By default lines are separated by \n
func (i *Input) Lines() []string {
return i.lines
}
// Private methods for the input field
// TODO: handle delete key
func (i *Input) backspa... | cursorYOffset += i.cursorLineIndex
}
if i.IsCapturing {
i.CursorX = i.cursorLinePos+cursorXOffset
i.CursorY = cursorYOffset | random_line_split | |
input.go | type Input struct {
Block
TextFgColor Attribute
TextBgColor Attribute
IsCapturing bool
IsMultiLine bool
TextBuilder TextBuilder
SpecialChars map[string]string
ShowLineNo bool
Name string
CursorX int
CursorY int
//DebugMode bool
//debugMessage string
// internal vars
lines ... | (text string) {
i.lines = strings.Split(text, NEW_LINE)
}
// Lines returns the slice of strings with the content of the input field. By default lines are separated by \n
func (i *Input) Lines() []string {
return i.lines
}
// Private methods for the input field
// TODO: handle delete key
func (i *Input) backspace()... | SetText | identifier_name |
blk_device.rs | device represents either a disk with no partitions or a disk
//! partition of an acceptable type (Linux filesystem partitions only at
//! present)
//! - the device currently contains no filesystem or volume id (although this
//! logically implies that the device is not currently mounted, for the sake
//! ... | get_partitions | identifier_name | |
blk_device.rs | satisfies the following
//! criteria:
//! - the device has a non-zero size
//! - the device is of an acceptable type as determined by well known device
//! numbers (eg. SCSI disks)
//! - the device represents either a disk with no partitions or a disk
//! partition of an acceptable type (Linux filesystem part... |
Some(Filesystem {
fstype: fstype.unwrap_or_else(|| String::from("")),
label: label.unwrap_or_else(|| String::from("")),
uuid: uuid.unwrap_or_else(|| String::from("")),
mountpoint: mountinfo
.map(|m| String::from(m.dest.to_string_lossy()))
.unwrap_or_else(|| ... | {
return None;
} | conditional_block |
blk_device.rs | satisfies the following
//! criteria:
//! - the device has a non-zero size
//! - the device is of an acceptable type as determined by well known device
//! numbers (eg. SCSI disks)
//! - the device represents either a disk with no partitions or a disk
//! partition of an acceptable type (Linux filesystem part... |
// Iterate through udev to generate a list of all (block) devices
// with DEVTYPE == "disk"
fn get_disks(
all: bool,
mounts: &HashMap<OsString, MountInfo>,
) -> Result<Vec<BlockDevice>, Error> {
let mut list: Vec<BlockDevice> = Vec::new();
let mut enumerator = Enumerator::new()?;
enumerator.matc... | {
let mut table: HashMap<OsString, MountInfo> = HashMap::new();
for mount in (MountIter::new()?).flatten() {
table.insert(OsString::from(mount.source.clone()), mount);
}
Ok(table)
} | identifier_body |
blk_device.rs | satisfies the following
//! criteria:
//! - the device has a non-zero size
//! - the device is of an acceptable type as determined by well known device
//! numbers (eg. SCSI disks)
//! - the device represents either a disk with no partitions or a disk
//! partition of an acceptable type (Linux filesystem part... |
// Get the list of current filesystem mounts.
fn get_mounts() -> Result<HashMap<OsString, MountInfo>, Error> {
let mut table: HashMap<OsString, MountInfo> = HashMap::new();
for mount in (MountIter::new()?).flatten() {
table.insert(OsString::from(mount.source.clone()), mount);
}
Ok(table)
}
/... | });
}
None
} | random_line_split |
tpm.rs | (context, ek_handle)
*/
pub(crate) fn create_ak(
ctx: &mut Context,
handle: KeyHandle,
) -> Result<(KeyHandle, Name, Vec<u8>)> {
let ak = ak::create_ak(
ctx,
handle,
HashingAlgorithm::Sha256,
SignatureScheme::RsaSsa,
None,
DefaultKey,
)?;
let ak_tpm2b_... | 20 => PcrSlot::Slot20,
21 => PcrSlot::Slot21,
22 => PcrSlot::Slot22, | random_line_split | |
tpm.rs | iosyncratic format tpm2-tools expects. The lengths
// of the vectors were determined by introspection into running tpm2-tools code. This is
// not ideal, and we should aim to move away from it if possible.
pub(crate) fn pcrdata_to_vec(
selection_list: PcrSelectionList,
pcrdata: PcrData,
) -> Vec<u8> {
let p... | hasher.update(&keybytes);
let mut hashvec: Vec<u8> = hasher.finish().into();
keydigest.set(HashingAlgorithm::Sha1, Digest::try_from(hashvec)?);
Ok(keydigest)
}
// Reads a mask in the form of some hex value, ex. "0x408000",
// translating bits that are set to pcrs to include in the list.
//
// The mas... | {
let mut keydigest = DigestValues::new();
let keybytes = match pubkey.id() {
Id::RSA => pubkey.rsa()?.public_key_to_pem()?,
other_id => {
return Err(KeylimeError::Other(format!(
"Converting to digest value for key type {:?} is not yet implemented",
other_id
... | identifier_body |
tpm.rs | iosyncratic format tpm2-tools expects. The lengths
// of the vectors were determined by introspection into running tpm2-tools code. This is
// not ideal, and we should aim to move away from it if possible.
pub(crate) fn pcrdata_to_vec(
selection_list: PcrSelectionList,
pcrdata: PcrData,
) -> Vec<u8> {
let p... | () -> Self {
TpmSigScheme::AlgNull
}
}
// Returns TSS struct corresponding to a signature scheme.
pub(crate) fn get_sig_scheme(
scheme: TpmSigScheme,
) -> Result<TPMT_SIG_SCHEME> {
match scheme {
// The TPM2_ALG_NULL sig scheme can be filled out with placeholder data
// in the detai... | default | identifier_name |
size_cache_fs.go | os.FileInfo, err error) {
var lfi, bfi os.FileInfo
lfi, err = u.cache.Stat(name)
if err == nil {
if u.cacheTime == 0 {
return cacheHit, lfi, nil
}
// TODO checking even if shouldnt ?
if lfi.ModTime().Add(u.cacheTime).Before(time.Now()) {
bfi, err = u.base.Stat(name)
if err != nil {
return cache... | {
return nil, err
} | conditional_block | |
size_cache_fs.go | error removing cache file: %v", err)
}
u.currSize -= file.Size
path := filepath.Dir(file.Path)
for path != "" && path != "." && path != "/" {
f, err := u.cache.Open(path)
if err != nil {
_ = f.Close()
return fmt.Errorf("error opening parent directory: %v", err)
}
dirs, err := f.Readdir(-1)
... | {
// Very important, remove from cache to prevent eviction while opening
info := u.getCacheFile(name)
if info != nil {
u.removeFromCache(name)
}
st, _, err := u.cacheStatus(name)
if err != nil {
return nil, err
}
switch st {
case cacheLocal, cacheHit:
default:
exists, err := Exists(u.base, name)
if... | identifier_body | |
size_cache_fs.go | .ENOENT || os.IsNotExist(err) {
return cacheMiss, nil, nil
}
return cacheMiss, nil, err
}
*/
func (u *SizeCacheFS) cacheStatus(name string) (state cacheState, fi os.FileInfo, err error) {
var lfi, bfi os.FileInfo
lfi, err = u.cache.Stat(name)
if err == nil {
if u.cacheTime == 0 {
return cacheHit, lfi, nil... |
// the dirs from cacheHit, cacheStale fall down here:
bfile, _ := u.base.Open(name) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.