file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
iadfa.py | from fsa import *
from nameGenerator import *
class IncrementalAdfa(Dfa):
"""This class is an Acyclic Deterministic Finite State Automaton
constructed by a list of words.
"""
def __init__(self, words, nameGenerator = None, sorted = False):
if nameGenerator is None:
nameGenerator ... |
def createFromSortedListOfWords(self, words):
self.register = {}
self.finalStates = []
self.startState = self.nameGenerator.generate()
self.states = {self.startState : State(self.startState)}
lastWord = None
for word in words:
if word.endswith('\n'):
... | childs = nextChilds
| random_line_split |
iadfa.py | from fsa import *
from nameGenerator import *
class IncrementalAdfa(Dfa):
"""This class is an Acyclic Deterministic Finite State Automaton
constructed by a list of words.
"""
def __init__(self, words, nameGenerator = None, sorted = False):
if nameGenerator is None:
nameGenerator ... |
def replaceOrRegister(self, stateName):
#childName = self.finalStates[-1]
childName, lastSymbol = self.lastChild(stateName)
if not self.markedAsRegistered(childName):
if self.hasChildren(childName):
self.replaceOrRegister(childName)
equivale... | input = list(self.states[stateName].transitions.keys())
input.sort()
return (self.states[stateName].transitions[input[-1]], input[-1]) | identifier_body |
getTemp.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re, os, time
# function: read and parse sensor data file
def read_sensor(path):
value = "U"
try:
f = open(path, "r")
line = f.readline()
if re.match(r"([0-9a-f]{2} ){9}: crc=[0-9a-f]{2} YES", line):
line = f.readline()
m = re.match(r"([0-9a-... | # path = "/sys/bus/w1/devices/28-0314640daeff/w1_slave"
# print read_sensor(path)
# time.sleep(30)
flag = 1
temp = 0
temp2 = 0
while (flag):
temp2 = temp
temp = read_sensor("/sys/bus/w1/devices/28-0314640daeff/w1_slave")
if temp2 != temp:
print temp
time.sleep(11) | "/sys/bus/w1/devices/28-0314640daeff/w1_slave"
)
# read sensor data
#for path in pathes: | random_line_split |
getTemp.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re, os, time
# function: read and parse sensor data file
def | (path):
value = "U"
try:
f = open(path, "r")
line = f.readline()
if re.match(r"([0-9a-f]{2} ){9}: crc=[0-9a-f]{2} YES", line):
line = f.readline()
m = re.match(r"([0-9a-f]{2} ){9}t=([+-]?[0-9]+)", line)
if m:
value = str(round(float(m.group(2)) / 1000.0,1))
f.close()
exce... | read_sensor | identifier_name |
getTemp.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re, os, time
# function: read and parse sensor data file
def read_sensor(path):
|
# define pathes to 1-wire sensor data
pathes = (
"/sys/bus/w1/devices/28-0314640daeff/w1_slave"
)
# read sensor data
#for path in pathes:
# path = "/sys/bus/w1/devices/28-0314640daeff/w1_slave"
# print read_sensor(path)
# time.sleep(30)
flag = 1
temp = 0
temp2 = 0
while (flag):
temp2 = temp
temp = rea... | value = "U"
try:
f = open(path, "r")
line = f.readline()
if re.match(r"([0-9a-f]{2} ){9}: crc=[0-9a-f]{2} YES", line):
line = f.readline()
m = re.match(r"([0-9a-f]{2} ){9}t=([+-]?[0-9]+)", line)
if m:
value = str(round(float(m.group(2)) / 1000.0,1))
f.close()
except (IOErro... | identifier_body |
getTemp.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import re, os, time
# function: read and parse sensor data file
def read_sensor(path):
value = "U"
try:
f = open(path, "r")
line = f.readline()
if re.match(r"([0-9a-f]{2} ){9}: crc=[0-9a-f]{2} YES", line):
line = f.readline()
m = re.match(r"([0-9a-... | temp2 = temp
temp = read_sensor("/sys/bus/w1/devices/28-0314640daeff/w1_slave")
if temp2 != temp:
print temp
time.sleep(11) | conditional_block | |
collection.rs | //! This module contains code to parse all supported collection formats.
use std::fs::File;
use std::io::Read;
use crate::level::*;
use crate::util::*;
enum FileFormat {
Ascii,
Xml,
}
/// A collection of levels. This type contains logic for parsing a collection file. Other than
/// that, it is simply a list... |
let level_strings: Vec<_> = content
.split(EMPTY_LINE)
.map(|x| x.trim_matches(&eol))
.filter(|x| !x.is_empty())
.collect();
let name = level_strings[0].lines().next().unwrap();
let description = level_strings[0]
.splitn(1, &eol)
... | let mut file = file;
// Read the collection’s file
let mut content = "".to_string();
file.read_to_string(&mut content)?; | random_line_split |
collection.rs | //! This module contains code to parse all supported collection formats.
use std::fs::File;
use std::io::Read;
use crate::level::*;
use crate::util::*;
enum FileFormat {
Ascii,
Xml,
}
/// A collection of levels. This type contains logic for parsing a collection file. Other than
/// that, it is simply a list... | self) -> Option<&str> {
match self.description {
Some(ref x) => Some(&x),
None => None,
}
}
pub fn first_level(&self) -> &Level {
&self.levels[0]
}
/// Get all levels.
pub fn levels(&self) -> &[Level] {
self.levels.as_ref()
}
pub fn ... | scription(& | identifier_name |
collection.rs | //! This module contains code to parse all supported collection formats.
use std::fs::File;
use std::io::Read;
use crate::level::*;
use crate::util::*;
enum FileFormat {
Ascii,
Xml,
}
/// A collection of levels. This type contains logic for parsing a collection file. Other than
/// that, it is simply a list... | },
Ok(Event::Text(ref e)) => match state {
State::Nothing => {}
State::Line if !parse_levels => {}
_ => {
let s = e.unescape_and_decode(&reader).unwrap();
match state {
... | conditional_block | |
translate.py | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# T... | for language in languages:
self.context.deleteLanguage(language)
return self.request.response.redirect(self.request.URL[-1]) | random_line_split | |
translate.py | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# T... |
def editMessages(self):
# Handle new Messages
for count in range(5):
msg_id = self.request.get('new-msg_id-%i' %count, '')
if msg_id:
for language in self.getEditLanguages():
msg = self.request.get('new-%s-%i' %(language, count),
... | msg_id = self.request['msg_id']
for language in self.getEditLanguages():
msg = self.request['msg_lang_%s' %language]
if msg != self.context.translate(msg_id,
target_language=language):
self.context.updateMessage(msg_id, msg, la... | identifier_body |
translate.py | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# T... |
# Handle edited Messages
keys = filter(lambda k: k.startswith('edit-msg_id-'),
self.request.keys())
keys = map(lambda k: k[12:], keys)
for key in keys:
msg_id = self.request['edit-msg_id-'+key]
for language in self.getEditLanguages():
... | for language in self.getEditLanguages():
msg = self.request.get('new-%s-%i' %(language, count),
msg_id)
self.context.addMessage(msg_id, msg, language) | conditional_block |
translate.py | ##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# T... | (BaseView):
def getMessages(self):
"""Get messages"""
filter = self.request.get('filter', '%')
messages = []
for msg_id in self.context.getMessageIds(filter):
messages.append((msg_id, len(messages)))
return messages
def getTranslation(self, msgid, target_l... | Translate | identifier_name |
chain.rs | extern crate futures;
extern crate tokio_core;
use std::net::TcpStream;
use std::thread;
use std::io::{Write, Read};
use futures::Future;
use futures::stream::Stream;
use tokio_core::io::read_to_end;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
... | () {
let mut l = t!(Core::new());
let srv = t!(TcpListener::bind(&t!("127.0.0.1:0".parse()), &l.handle()));
let addr = t!(srv.local_addr());
let t = thread::spawn(move || {
let mut s1 = TcpStream::connect(&addr).unwrap();
s1.write_all(b"foo ").unwrap();
let mut s2 = TcpStream::c... | chain_clients | identifier_name |
chain.rs | extern crate futures;
extern crate tokio_core;
use std::net::TcpStream;
use std::thread;
use std::io::{Write, Read};
use futures::Future;
use futures::stream::Stream;
use tokio_core::io::read_to_end;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
... | t.join().unwrap();
assert_eq!(data, b"foo bar baz");
} | random_line_split | |
chain.rs | extern crate futures;
extern crate tokio_core;
use std::net::TcpStream;
use std::thread;
use std::io::{Write, Read};
use futures::Future;
use futures::stream::Stream;
use tokio_core::io::read_to_end;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;
macro_rules! t {
($e:expr) => (match $e {
... | {
let mut l = t!(Core::new());
let srv = t!(TcpListener::bind(&t!("127.0.0.1:0".parse()), &l.handle()));
let addr = t!(srv.local_addr());
let t = thread::spawn(move || {
let mut s1 = TcpStream::connect(&addr).unwrap();
s1.write_all(b"foo ").unwrap();
let mut s2 = TcpStream::conn... | identifier_body | |
processor-info.component.ts | import { Component, AfterViewInit, OnDestroy, ViewChild, ElementRef, Input } from "@angular/core";
import Overlay from 'ol/overlay';
import Proj from 'ol/proj';
import { MapService } from '../../map/map.service';
import {TimeService} from '../../app/time.service';
import {ProcessorsService} from '../processors.servi... | (evt) {
window.removeEventListener('mousemove', move);
window.removeEventListener('mouseup', end);
if (moved)
that.retrieveDataValue(that.position);
}
window.addEventListener('mousemove', move);
win... | end | identifier_name |
processor-info.component.ts | import { Component, AfterViewInit, OnDestroy, ViewChild, ElementRef, Input } from "@angular/core";
import Overlay from 'ol/overlay';
import Proj from 'ol/proj';
import { MapService } from '../../map/map.service';
import {TimeService} from '../../app/time.service';
import {ProcessorsService} from '../processors.servi... | }
moved = true;
}
function end(evt) {
window.removeEventListener('mousemove', move);
window.removeEventListener('mouseup', end);
if (moved)
that.retrieveDataValue(that.positi... | that.position = [coord[0] + offset[0], coord[1] + offset[1]]
overlay.setPosition(that.position);
that.data = {
status: 'empty',
value: 0 | random_line_split |
processor-info.component.ts | import { Component, AfterViewInit, OnDestroy, ViewChild, ElementRef, Input } from "@angular/core";
import Overlay from 'ol/overlay';
import Proj from 'ol/proj';
import { MapService } from '../../map/map.service';
import {TimeService} from '../../app/time.service';
import {ProcessorsService} from '../processors.servi... |
});
}
getGeoCoordinates(coord) {
if (!this.viewer) {
return null;
}
if (this.viewer.getView().getProjection() != 'EPSG:4326') {
coord = Proj.transform(coord, this.viewer.getView().getProjection(), 'EPSG:4326');
}
return coord;
}
... | {
this.retrieveDataValue(this.position);
} | conditional_block |
processor-info.component.ts | import { Component, AfterViewInit, OnDestroy, ViewChild, ElementRef, Input } from "@angular/core";
import Overlay from 'ol/overlay';
import Proj from 'ol/proj';
import { MapService } from '../../map/map.service';
import {TimeService} from '../../app/time.service';
import {ProcessorsService} from '../processors.servi... |
retrieveDataValue(coordinate) {
this.data = {
status: 'loading',
value: 0
}
this.processorLayer.getSourceValue(coordinate).then((value)=>{
this.data = {
status: 'ready',
value: value
}
});
thi... | {
if (!this.viewer) {
return null;
}
if (this.viewer.getView().getProjection() != 'EPSG:4326') {
coord = Proj.transform(coord, this.viewer.getView().getProjection(), 'EPSG:4326');
}
return coord;
} | identifier_body |
menu.ts | console.log('##########################################');
var System = (<any>window).System;
import ng = require('angular2/angular2');
import $ = require('jquery');
const css = require('./menu.css');
var hoverOpenMenuList = [];
console.log(ng,ng.Component);
@ng.Component({
selector:'menu'
})
@ng.View({
templ... |
}
open(){
this.$element.show();
}
close(){
this.$element.hide();
}
static closeAlHoverMenu(){
for(var i in hoverOpenMenuList){
var menu = hoverOpenMenuList[i];
menu.close();
}
}
}
@ng.Component({
selector:'item'
})
@ng.View({
template:`
<li>
<ng-content></ng-co... | {
var parent = this.$element.parent();
parent.hover((e)=>{
Menu.closeAlHoverMenu();
var offset = parent.offset();
this.$element.css({
position:'fixed',top:offset.top,left:offset.left + parent[0].scrollWidth
});
this.open();
hoverOpenMenuList.push(thi... | conditional_block |
menu.ts | console.log('##########################################');
var System = (<any>window).System;
import ng = require('angular2/angular2');
import $ = require('jquery');
const css = require('./menu.css');
var hoverOpenMenuList = [];
console.log(ng,ng.Component);
@ng.Component({
selector:'menu'
})
@ng.View({
templ... |
open(){
this.$element.show();
}
close(){
this.$element.hide();
}
static closeAlHoverMenu(){
for(var i in hoverOpenMenuList){
var menu = hoverOpenMenuList[i];
menu.close();
}
}
}
@ng.Component({
selector:'item'
})
@ng.View({
template:`
<li>
<ng-content></ng-content... | {
this.$element = $(el.nativeElement);
var showAction = this.$element.attr('show-action');
if(showAction == "parent:hover"){
var parent = this.$element.parent();
parent.hover((e)=>{
Menu.closeAlHoverMenu();
var offset = parent.offset();
this.$element.css({
posi... | identifier_body |
menu.ts | console.log('##########################################');
var System = (<any>window).System;
import ng = require('angular2/angular2');
import $ = require('jquery');
const css = require('./menu.css');
var hoverOpenMenuList = [];
console.log(ng,ng.Component);
@ng.Component({
selector:'menu'
})
@ng.View({
templ... | {
$element:JQuery;
constructor(private el:ng.ElementRef){
this.$element = $(el.nativeElement);
}
}
| Item | identifier_name |
menu.ts | console.log('##########################################');
var System = (<any>window).System;
import ng = require('angular2/angular2');
import $ = require('jquery');
const css = require('./menu.css');
var hoverOpenMenuList = [];
console.log(ng,ng.Component);
@ng.Component({
selector:'menu'
})
@ng.View({
templ... | if(showAction == "parent:hover"){
var parent = this.$element.parent();
parent.hover((e)=>{
Menu.closeAlHoverMenu();
var offset = parent.offset();
this.$element.css({
position:'fixed',top:offset.top,left:offset.left + parent[0].scrollWidth
});
this.open()... |
constructor(private el:ng.ElementRef){
this.$element = $(el.nativeElement);
var showAction = this.$element.attr('show-action'); | random_line_split |
cms.base.js | /*##################################################|*/
/* #CMS.BASE# */
(function namespacing(CMS) {
CMS.$(document).ready(function ($) {
// assign correct jquery to $ namespace
$ = CMS.$ || $;
// the following is added because IE is stupid
// $.ajax requests in IE8 fail without this hack
// ref: http://st... |
return uri;
},
setUrl: function (str, options) {
var uri = str;
// now we neet to get the partials of the element
var getUrlObj = this.getUrl(uri);
var query = getUrlObj.queryKey;
var serialized = '';
var index = 0;
// we could loop the query and replace the param at the right ... |
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if($1) { uri[o.q.name][$1] = $2; }
}); | random_line_split |
cms.base.js | /*##################################################|*/
/* #CMS.BASE# */
(function namespacing(CMS) {
CMS.$(document).ready(function ($) {
// assign correct jquery to $ namespace
$ = CMS.$ || $;
// the following is added because IE is stupid
// $.ajax requests in IE8 fail without this hack
// ref: http://st... |
// do some url checks
var base_doc_url = document.URL.match(/^http[s]{0,1}:\/\/[^\/]+\//)[0];
var base_settings_url = settings.url.match(/^http[s]{0,1}:\/\/[^\/]+\//);
if(base_settings_url != null) {
base_settings_url = base_settings_url[0];
}
if(!(/^http:.*/.test(settings.ur... | {
var cookieValue = null;
if(document.cookie && (document.cookie != '')) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = $.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.sub... | identifier_body |
cms.base.js | /*##################################################|*/
/* #CMS.BASE# */
(function namespacing(CMS) {
CMS.$(document).ready(function ($) {
// assign correct jquery to $ namespace
$ = CMS.$ || $;
// the following is added because IE is stupid
// $.ajax requests in IE8 fail without this hack
// ref: http://st... | (name) {
var cookieValue = null;
if(document.cookie && (document.cookie != '')) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = $.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (coo... | getCookie | identifier_name |
custom.js | // slideshow settings
$(document).ready(function() {
$('.slideshow').cycle({
fx: 'fade' // transition type : fade, scrollUp, shuffle, etc...
});
});
$(document).ready( function() {
Cufon.replace('.footer-one-third h2', { fontFamily: 'ColaborateLight', fontSize: '20px', color:'#cdb380' } );
Cufon.replace(... |
}); |
$('#sidebar .widget').corner(); | random_line_split |
eventlist.component.ts | import {Component, EventEmitter, OnInit, TemplateRef, ViewEncapsulation} from '@angular/core';
import {routerTransition} from '../../router.animations';
import { CalendarService } from '../calendar.service'; | @Component({
selector: 'app-eventlist',
templateUrl: './eventlist.component.html',
styleUrls: ['./eventlist.component.scss'],
animations: [routerTransition()],
host: {'[@routerTransition]': ''}
})
export class EventlistComponent implements OnInit {
viewDate: Date = new Date();
days : Array<Eventdate>;
... | import { Eventdate, Windy } from '../eventdate';
import 'rxjs/Rx';
import {environment} from "../../../environments/environment";
import { Http, Response } from '@angular/http';
| random_line_split |
eventlist.component.ts | import {Component, EventEmitter, OnInit, TemplateRef, ViewEncapsulation} from '@angular/core';
import {routerTransition} from '../../router.animations';
import { CalendarService } from '../calendar.service';
import { Eventdate, Windy } from '../eventdate';
import 'rxjs/Rx';
import {environment} from "../../../environm... |
}
| {
this.viewDate.setMonth(this.viewDate.getMonth() + 1);
this.reload();
} | identifier_body |
eventlist.component.ts | import {Component, EventEmitter, OnInit, TemplateRef, ViewEncapsulation} from '@angular/core';
import {routerTransition} from '../../router.animations';
import { CalendarService } from '../calendar.service';
import { Eventdate, Windy } from '../eventdate';
import 'rxjs/Rx';
import {environment} from "../../../environm... | () {
this.viewDate.setMonth(this.viewDate.getMonth() + 1);
this.reload();
}
}
| next | identifier_name |
vmem_serialize.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::lc_state::LcSecded;
use crate::util::present::Present;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;
use anyhow::{anyh... |
}
let word_with_ecc = secded.ecc_encode(word)?;
let mut word_str = String::new();
for byte in word_with_ecc.iter().rev() {
write!(word_str, "{:02x}", byte)?;
}
output.push(format!(
"{} // {:06x}: {}",
... | {
word_annotation.push(annotations[idx].clone());
} | conditional_block |
vmem_serialize.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::lc_state::LcSecded;
use crate::util::present::Present;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;
use anyhow::{anyh... |
/// Add an item to this partition.
pub fn push_item(&mut self, item: VmemItem) {
self.items.push(item);
}
/// Produces a tuple containing OTP HEX lines with annotations.
fn write_to_buffer(&self, keys: &HashMap<String, Vec<u8>>) -> Result<(Vec<u8>, Vec<String>)> {
if self.size % 8... | {
self.size = size;
} | identifier_body |
vmem_serialize.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details. | // SPDX-License-Identifier: Apache-2.0
use crate::otp::lc_state::LcSecded;
use crate::util::present::Present;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;
use anyhow::{anyhow, bail, ensure, Result};
use zerocopy::AsBytes;
enum ItemType {
Bytes(Vec<u8>),
Unvalued(usize),
}
... | random_line_split | |
vmem_serialize.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
use crate::otp::lc_state::LcSecded;
use crate::util::present::Present;
use std::collections::HashMap;
use std::convert::TryInto;
use std::fmt::Write;
use anyhow::{anyh... | (&self) -> usize {
match &self.value {
ItemType::Bytes(b) => b.len(),
ItemType::Unvalued(size) => *size,
}
}
}
pub type DigestIV = u64;
pub type DigestCnst = u128;
/// Digest information for an OTP partition.
#[derive(PartialEq)]
pub enum DigestType {
Unlocked,
Soft... | size | identifier_name |
visualizer.js | import Boolius from "./boolius"; // which in turn imports all the classes it depends upon
import XMLius from "./xmlius";
import Mathius from "./mathius";
window.onload = function () {
d3.select("#modeSelect").on("change", function (e) {
var selectedMode = d3.select("#modeSelect").node().value.toLowerCase();
... | (d.value === true || d.value === false) {
d.value = !d.value;
//var myInt = parseInt( d.name );
//conditionTruthValues[ myInt ] = d.value;
var myVar = d.name;
evaluator.state[myVar] = d.value;
updateWithoutDeleting(root);
}
}
} // you clicke... | if | identifier_name |
visualizer.js | import Boolius from "./boolius"; // which in turn imports all the classes it depends upon
import XMLius from "./xmlius";
import Mathius from "./mathius";
window.onload = function () {
d3.select("#modeSelect").on("change", function (e) {
var selectedMode = d3.select("#modeSelect").node().value.toLowerCase();
... | // comments will be engulfed by the text of a node
// and ignored when the node is asked for its text as a string
[["COMMENT"], "#TEXT_NODE"],
[["<", "/", "IDENT", ">"], "CLOSETAG"],
[["<", "IDENT", ">"], "OPENTAG"],
[["<", "IDENT", "/", ">"], "XMLNODE"],
... | let grammarObject = [
[["OPENCOMMENT", "WILDCARD", "CLOSECOMMENT"], "COMMENT"], | random_line_split |
visualizer.js | import Boolius from "./boolius"; // which in turn imports all the classes it depends upon
import XMLius from "./xmlius";
import Mathius from "./mathius";
window.onload = function () {
d3.select("#modeSelect").on("change", function (e) {
var selectedMode = d3.select("#modeSelect").node().value.toLowerCase();
... |
}
} // you clicked something that isn't in a boolean flow
else {
if (showOverlay) {
var attributeText = d.attributes
? JSON.stringify(d.attributes)
: "None";
if (!d.children && !d._children) {
// it's a leaf
//showValueOverlay( d.value );
... | {
d.value = !d.value;
//var myInt = parseInt( d.name );
//conditionTruthValues[ myInt ] = d.value;
var myVar = d.name;
evaluator.state[myVar] = d.value;
updateWithoutDeleting(root);
} | identifier_body |
pawn.py | """ Just a purple sphere """
from vapory import *
objects = [
# SUN
LightSource([1500,2500,-2500], 'color',1),
# SKY
Sphere( [0,0,0],1, 'hollow',
Texture(
Pigment( 'gradient', [0,1,0],
'color_map{[0 color White] [1 color Blu... | Union( Sphere([0,1,0],0.35),
Cone([0,0,0],0.5,[0,1,0],0.0),
Texture( Pigment( 'color', [1,0.65,0])),
Finish( 'phong', 0.5)
)
]
scene = Scene( Camera( 'ultra_wide_angle',
'angle',45,
'location',[0.0 , 0.6 ,-3.0],
... |
# PAWN | random_line_split |
api_ping_check.py | ###############################################
# RabbitMQ in Action
# Chapter 10 - RabbitMQ ping (HTTP API) check.
###############################################
#
#
# Author: Jason J. W. Williams
# (C)2011
###############################################
import sys, json, httplib, urllib, base64, socket
#(apic.0)... |
#/(apic.7) RabbitMQ alive, return OK status
print "OK: Broker alive: %s" % response.read()
exit(EXIT_OK)
| print "CRITICAL: Broker not alive: %s" % response.read()
exit(EXIT_CRITICAL) | conditional_block |
api_ping_check.py | ###############################################
# RabbitMQ in Action
# Chapter 10 - RabbitMQ ping (HTTP API) check.
###############################################
#
#
# Author: Jason J. W. Williams
# (C)2011
###############################################
import sys, json, httplib, urllib, base64, socket
#(apic.0)... |
response = conn.getresponse()
#/(apic.6) RabbitMQ not responding/alive, return critical status
if response.status > 299:
print "CRITICAL: Broker not alive: %s" % response.read()
exit(EXIT_CRITICAL)
#/(apic.7) RabbitMQ alive, return OK status
print "OK: Broker alive: %s" % response.read()
exit(EXIT_OK) | exit(EXIT_CRITICAL) | random_line_split |
analytics.js | /**
Copyright 2015 Couchbase, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | () {
if (async) {
async.cancel();
}
}
function unbind() {
$(mainAsync).unbind('cancelled', onCancel);
}
$(mainAsync).bind('cancelled', onCancel);
var async;
return async = getCPS({url: '/_uistats', data: data, missingValue: mark404}, cancelMark, fun... | onCancel | identifier_name |
analytics.js | /**
Copyright 2015 Couchbase, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... | }
});
if (!samples[selected.name]) {
selected = _.detect(infos, function (info) {return samples[info.name];}) || selected;
}
return {
interval: stats.interval,
zoomLevel: v.need(zoomLevel),
selected: selected,
samples: samples,
timestamp: samples.timestamp,
... | samples[k] = subSamples[k];
auxTS[k] = timestamps; | random_line_split |
analytics.js | /**
Copyright 2015 Couchbase, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
if (!selectionCell) {
return;
}
selectionCell.setValue(graphParam);
self.widget.forceNextRendering();
});
})();
(function () {
function handler() {
var val = effectiveSelected.value;
val = val && val.name;
$('.js_analytics-small-gra... | {
debugger
throw new Error("shouldn't happen");
} | conditional_block |
analytics.js | /**
Copyright 2015 Couchbase, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
var shadowSize = 3;
if (window.G_vmlCanvasManager) {
shadowSize = 0;
}
function renderSmallGraph(jq, options) {
function reqOpt(name) {
var rv = options[name];
if (rv === undefined)
throw new Error("missing option: " + name);
return rv;
}
var data = reqOpt('data');
... | {
var i = queuedUpdates.length;
while (--i >= 0) {
queuedUpdates[i]();
}
queuedUpdates.length = 0;
} | identifier_body |
app.js | 'use strict';
angular.module('citizenForumsShowApp', [
'citizenForumsShowApp.services',
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'uiGmapgoogle-maps',
'xeditable',
'restangular',
'nl2br'
]).config(['$interpolateProvider', function($i... | uiGmapGoogleMapApiProvider.configure({
// key: '', // TODO set Google Maps API key
v: '3.17',
language: 'es',
sensor: false,
libraries: 'drawing,geometry,visualization'
});
})
.run(function(editableOptions) {
editableOptions.the... | random_line_split | |
event_loop.rs | use std::sync::{Arc, Condvar, Mutex};
use std::thread::spawn;
use std::time::{Duration, Instant};
use super::schedule_queue::*;
use super::scheduler::*;
#[derive(Clone)]
pub struct EventLoop {
queue: Arc<(Mutex<ScheduleQueue<Box<Action + Send>>>, Condvar)>,
}
impl EventLoop {
/// Creates a new EventLoop
p... | () -> Self {
let queue = Arc::new((Mutex::new(ScheduleQueue::new()), Condvar::new()));
let scheduler = EventLoop { queue: queue.clone() };
spawn(move || {
loop {
let mut action = dequeue(&queue);
action.invoke();
}
});
sc... | new | identifier_name |
event_loop.rs | use std::sync::{Arc, Condvar, Mutex};
use std::thread::spawn;
use std::time::{Duration, Instant};
use super::schedule_queue::*;
use super::scheduler::*;
#[derive(Clone)]
pub struct EventLoop {
queue: Arc<(Mutex<ScheduleQueue<Box<Action + Send>>>, Condvar)>,
}
impl EventLoop {
/// Creates a new EventLoop
p... |
}
}
| {
action();
} | conditional_block |
event_loop.rs | use std::sync::{Arc, Condvar, Mutex};
use std::thread::spawn;
use std::time::{Duration, Instant};
use super::schedule_queue::*;
use super::scheduler::*;
#[derive(Clone)]
pub struct EventLoop {
queue: Arc<(Mutex<ScheduleQueue<Box<Action + Send>>>, Condvar)>,
}
impl EventLoop {
/// Creates a new EventLoop
p... | } else {
queue.enqueue(record);
continue;
}
}
} else {
queue = cvar.wait(queue).unwrap();
}
}
}
impl ParallelScheduler for EventLoop {
fn schedule<F>(&self, func: F, delay: Duration)
where F:... | let r = cvar.wait_timeout(queue, timeout).unwrap();
queue = r.0;
if r.1.timed_out() {
return record.0; | random_line_split |
event_loop.rs | use std::sync::{Arc, Condvar, Mutex};
use std::thread::spawn;
use std::time::{Duration, Instant};
use super::schedule_queue::*;
use super::scheduler::*;
#[derive(Clone)]
pub struct EventLoop {
queue: Arc<(Mutex<ScheduleQueue<Box<Action + Send>>>, Condvar)>,
}
impl EventLoop {
/// Creates a new EventLoop
p... |
}
| {
if let Some(action) = self.take() {
action();
}
} | identifier_body |
builder.rs | //! Cretonne instruction builder.
//!
//! A `Builder` provides a convenient interface for inserting instructions into a Cretonne
//! function. Many of its methods are generated from the meta language instruction definitions.
use ir;
use ir::types;
use ir::{InstructionData, DataFlowGraph};
use ir::{Opcode, Type, Inst, ... |
(self.inst, self.dfg)
}
}
#[cfg(test)]
mod tests {
use cursor::{Cursor, FuncCursor};
use ir::{Function, InstBuilder, ValueDef};
use ir::types::*;
use ir::condcodes::*;
#[test]
fn types() {
let mut func = Function::new();
let ebb0 = func.dfg.make_ebb();
let... | {
// The old result values were either detached or non-existent.
// Construct new ones.
self.dfg.make_inst_results(self.inst, ctrl_typevar);
} | conditional_block |
builder.rs | //! Cretonne instruction builder.
//!
//! A `Builder` provides a convenient interface for inserting instructions into a Cretonne
//! function. Many of its methods are generated from the meta language instruction definitions.
use ir;
use ir::types;
use ir::{InstructionData, DataFlowGraph};
use ir::{Opcode, Type, Inst, ... | inst = dfg.make_inst(data);
// Make an `Interator<Item = Option<Value>>`.
let ru = self.reuse.as_ref().iter().cloned();
dfg.make_inst_results_reusing(inst, ctrl_typevar, ru);
}
(inst, self.inserter.insert_built_inst(inst, ctrl_typevar))
}
}
/// Instru... | {
let dfg = self.inserter.data_flow_graph_mut(); | random_line_split |
builder.rs | //! Cretonne instruction builder.
//!
//! A `Builder` provides a convenient interface for inserting instructions into a Cretonne
//! function. Many of its methods are generated from the meta language instruction definitions.
use ir;
use ir::types;
use ir::{InstructionData, DataFlowGraph};
use ir::{Opcode, Type, Inst, ... | (&self) -> &DataFlowGraph {
self.inserter.data_flow_graph()
}
fn data_flow_graph_mut(&mut self) -> &mut DataFlowGraph {
self.inserter.data_flow_graph_mut()
}
fn build(mut self, data: InstructionData, ctrl_typevar: Type) -> (Inst, &'f mut DataFlowGraph) {
let inst;
{
... | data_flow_graph | identifier_name |
cursor.rs | extern crate sdl2;
use std::env;
use std::path::Path;
use sdl2::event::Event;
use sdl2::image::{LoadSurface, InitFlag};
use sdl2::keyboard::Keycode;
use sdl2::mouse::Cursor;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
pub fn run(png: &Path) -> Result<(), String> {
let sdl_context = ... | () -> Result<(), String> {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run /path/to/image.(png|jpg)")
} else {
run(Path::new(&args[1]))?;
}
Ok(())
}
| main | identifier_name |
cursor.rs | extern crate sdl2;
use std::env;
use std::path::Path; | use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
pub fn run(png: &Path) -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let _image_context = sdl2::image::init(InitFlag::PNG | InitFlag::JPG)?;
let window = video_subsystem.win... | use sdl2::event::Event;
use sdl2::image::{LoadSurface, InitFlag};
use sdl2::keyboard::Keycode;
use sdl2::mouse::Cursor; | random_line_split |
cursor.rs | extern crate sdl2;
use std::env;
use std::path::Path;
use sdl2::event::Event;
use sdl2::image::{LoadSurface, InitFlag};
use sdl2::keyboard::Keycode;
use sdl2::mouse::Cursor;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
pub fn run(png: &Path) -> Result<(), String> {
let sdl_context = ... | {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run /path/to/image.(png|jpg)")
} else {
run(Path::new(&args[1]))?;
}
Ok(())
} | identifier_body | |
cursor.rs | extern crate sdl2;
use std::env;
use std::path::Path;
use sdl2::event::Event;
use sdl2::image::{LoadSurface, InitFlag};
use sdl2::keyboard::Keycode;
use sdl2::mouse::Cursor;
use sdl2::pixels::Color;
use sdl2::rect::Rect;
use sdl2::surface::Surface;
pub fn run(png: &Path) -> Result<(), String> {
let sdl_context = ... |
}
}
}
Ok(())
}
fn main() -> Result<(), String> {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run /path/to/image.(png|jpg)")
} else {
run(Path::new(&args[1]))?;
}
Ok(())
}
| {} | conditional_block |
toHTML.js | 'use strict'
const he = require('he')
const node = require('./node')
const debug = require('debug')('arraydom.toHTML')
const pad = Array(80).join(' ') // don't bother to indent more than 80
const selfClosing = {
// from http://xahlee.info/js/html5_non-closing_tag.html
// These are the tags that don't need an e... |
s += '</' + tag + '>'
if (oldIndent >= 0) {
s += '\n'
}
return s
}
module.exports = toHTML
| {
s += pad.slice(0, (indent) * 2)
} | conditional_block |
toHTML.js | 'use strict'
const he = require('he')
const node = require('./node')
const debug = require('debug')('arraydom.toHTML')
const pad = Array(80).join(' ') // don't bother to indent more than 80
const selfClosing = {
// from http://xahlee.info/js/html5_non-closing_tag.html
// These are the tags that don't need an e... | const tag = parts[0]
debug('parts', parts)
// 'document' is our pseudo-element for handling the fact that HTML
// documents are not trees when you allow comments, doctype, etc.
if (tag === 'document') {
return children.map(toHTML).join('')
}
if (indent >= 0) {
s += pad.slice(0, (indent) * 2)
... | random_line_split | |
toHTML.js | 'use strict'
const he = require('he')
const node = require('./node')
const debug = require('debug')('arraydom.toHTML')
const pad = Array(80).join(' ') // don't bother to indent more than 80
const selfClosing = {
// from http://xahlee.info/js/html5_non-closing_tag.html
// These are the tags that don't need an e... |
function Serializer (options) {
}
// would be more efficient to use some kind of output stream instead
// of a string, probably...
Serializer.prototype.serialize = function (tree, indent) {
const tags = tree[0]
const attrs = node.attrs(tree)
const children = node.children(tree)
debug('starting with', tags)... | {
options = options || {}
const s = new Serializer(options)
let indent = 0
if (options.compact) {
indent = undefined
}
return s.serialize(tree, indent)
} | identifier_body |
toHTML.js | 'use strict'
const he = require('he')
const node = require('./node')
const debug = require('debug')('arraydom.toHTML')
const pad = Array(80).join(' ') // don't bother to indent more than 80
const selfClosing = {
// from http://xahlee.info/js/html5_non-closing_tag.html
// These are the tags that don't need an e... | (s) {
//console.log('ENCODE', JSON.stringify(s))
if (typeof s === 'number') {
s = '' + s
}
return he.encode(s, {useNamedReferences: true})
}
/*
return a copy of this node where the second element is defintely the
attribute object. By calling this in all the right places, we allow
people to omit tha... | encode | identifier_name |
greedy.py | # -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the right... | layer):
"""
TODO...
"""
def play(self, game, state):
"""
TODO...
"""
action_list = game.getSetOfValidActions(state)
choosen_action = None
# Choose actions that lead to immediate victory...
for action in action_list:
next_state = game... | eedyPlayer(P | identifier_name |
greedy.py | # -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the right... | return choosen_action
| oosen_action = random.choice(action_list)
| conditional_block |
greedy.py | # -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the right... | return choosen_action | random_line_split | |
greedy.py | # -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the right... | "
TODO...
"""
action_list = game.getSetOfValidActions(state)
choosen_action = None
# Choose actions that lead to immediate victory...
for action in action_list:
next_state = game.nextState(state, action, self)
if game.hasWon(self, next_state):
... | identifier_body | |
test16a.js | if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('../alasql.js');
};
if(false) | {
describe('Test 16b', function() {
it('Grouping', function(done){
alasql('create database test16;use test16');
alasql.tables.students = new alasql.Table({data: [
{studentid:58,studentname:'Sarah Patrik',courseid:1, startdate: new Date(2014,0,10), amt:10, schoolid:1},
{studentid:102,studentname:'John Stewar... | conditional_block | |
test16a.js | if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('../alasql.js');
};
if(false) {
describe('Test 16b', function() {
it('Grouping', function(done){
alasql('create database test16;use test16');
alasql.tables.students = new alasql.Table({data: [
{studentid:58,studentname:'S... | {schoolid:1, schoolname: 'Northern School', regionid:'north'},
{schoolid:2, schoolname: 'Southern School', regionid:'south'},
{schoolid:3, schoolname: 'Eastern School', regionid:'east'},
{schoolid:4, schoolname: 'Western School', regionid:'west'},
]});
var res = alasql.exec('SELECT * '+
' FROM stud... | {courseid:4, coursename: 'fourth', schoolid:2},
{courseid:5, coursename: 'fifth', schoolid:2}
]});
alasql.tables.schools = new alasql.Table({data:[ | random_line_split |
switch-between-vi-emacs.py | #!/usr/bin/env python
"""
Example that displays how to switch between Emacs and Vi input mode.
"""
from prompt_toolkit import prompt
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.styles import style... |
else:
event.cli.editing_mode = EditingMode.VI
# Add a bottom toolbar to display the status.
style = style_from_dict({
Token.Toolbar: 'reverse',
})
def get_bottom_toolbar_tokens(cli):
" Display the current input mode. "
text = 'Vi' if cli.editing_mode == Edi... | event.cli.editing_mode = EditingMode.EMACS | conditional_block |
switch-between-vi-emacs.py | #!/usr/bin/env python
"""
Example that displays how to switch between Emacs and Vi input mode.
"""
from prompt_toolkit import prompt
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.styles import style... |
prompt('> ', key_bindings_registry=manager.registry,
get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
style=style)
if __name__ == '__main__':
run()
| " Display the current input mode. "
text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs'
return [
(Token.Toolbar, ' [F4] %s ' % text)
] | identifier_body |
switch-between-vi-emacs.py | #!/usr/bin/env python
"""
Example that displays how to switch between Emacs and Vi input mode.
"""
from prompt_toolkit import prompt
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.styles import style... | })
def get_bottom_toolbar_tokens(cli):
" Display the current input mode. "
text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs'
return [
(Token.Toolbar, ' [F4] %s ' % text)
]
prompt('> ', key_bindings_registry=manager.registry,
get_bottom_to... | random_line_split | |
switch-between-vi-emacs.py | #!/usr/bin/env python
"""
Example that displays how to switch between Emacs and Vi input mode.
"""
from prompt_toolkit import prompt
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.styles import style... | (cli):
" Display the current input mode. "
text = 'Vi' if cli.editing_mode == EditingMode.VI else 'Emacs'
return [
(Token.Toolbar, ' [F4] %s ' % text)
]
prompt('> ', key_bindings_registry=manager.registry,
get_bottom_toolbar_tokens=get_bottom_toolbar_tokens,
... | get_bottom_toolbar_tokens | identifier_name |
ip_vtk58.py | # Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import config
from install_package import InstallPackage
import os
import re
import shutil
import sys
import utils
BASENAME = "VTK"
GIT_REPO = "http://vtk.org/VTK.git"
GIT_TAG = "v5.8.0"
VTK_BASE_VERSION = "vtk-5.8"
# this... |
def unpack(self):
pass
def configure(self):
if os.path.exists(
os.path.join(self.build_dir, 'CMakeFiles/cmake.check_cache')):
utils.output("VTK build already configured.")
return
if not os.path.exists(self.bu... | if os.path.exists(self.source_dir):
utils.output("VTK already checked out, skipping step.")
else:
utils.goto_archive()
ret = os.system("git clone %s %s" % (GIT_REPO, BASENAME))
if ret != 0:
utils.error("Could not clone VTK repo. Fix and try agai... | identifier_body |
ip_vtk58.py | # Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import config
from install_package import InstallPackage
import os
import re
import shutil
import sys
import utils
BASENAME = "VTK"
GIT_REPO = "http://vtk.org/VTK.git"
GIT_TAG = "v5.8.0"
VTK_BASE_VERSION = "vtk-5.8"
# this... |
os.chdir(self.build_dir)
# we save, set and restore the PP env variable, else
# stupid setuptools complains
save_env = os.environ.get('PYTHONPATH', '')
os.environ['PYTHONPATH'] = config.VTK_PYTHON
ret = utils.make_command('VTK.sln', install=True... | os.makedirs(config.VTK_PYTHON) | conditional_block |
ip_vtk58.py | # Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved. | from install_package import InstallPackage
import os
import re
import shutil
import sys
import utils
BASENAME = "VTK"
GIT_REPO = "http://vtk.org/VTK.git"
GIT_TAG = "v5.8.0"
VTK_BASE_VERSION = "vtk-5.8"
# this patch does three things:
# 1. adds try/catch blocks to all python method calls in order
# to trap bad_all... | # See COPYRIGHT for details.
import config | random_line_split |
ip_vtk58.py | # Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import config
from install_package import InstallPackage
import os
import re
import shutil
import sys
import utils
BASENAME = "VTK"
GIT_REPO = "http://vtk.org/VTK.git"
GIT_TAG = "v5.8.0"
VTK_BASE_VERSION = "vtk-5.8"
# this... | (self):
posix_file = os.path.join(self.build_dir,
'bin/libvtkWidgetsPython.so')
nt_file = os.path.join(self.build_dir, 'bin', config.BUILD_TARGET,
'vtkWidgetsPythonD.dll')
if utils.file_exists(posix_file, nt_file):
utils.output("VTK already built. Skipp... | build | identifier_name |
thrift.rs | // Copyright 2019-2020 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
#![allow(dead_code)]
use crate::codec::ParseError;
pub const STOP: u8 = 0;
pub const VOID: u8 = 1;
pub const BOOL: u8 = 2;
pub const BYTE: u8 = 3;
pub const DOUBLE: u8 = 4;
pub const I... | (&self) -> usize {
self.buffer.len()
}
/// add protocol version to buffer
pub fn protocol_header(&mut self) -> &Self {
self.buffer.extend_from_slice(&[128, 1, 0, 1]);
self
}
/// write the framed length to the buffer
#[inline]
pub fn frame(&mut self) -> &Self {
... | len | identifier_name |
thrift.rs | // Copyright 2019-2020 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
#![allow(dead_code)]
use crate::codec::ParseError;
pub const STOP: u8 = 0;
pub const VOID: u8 = 1;
pub const BOOL: u8 = 2;
pub const BYTE: u8 = 3;
pub const DOUBLE: u8 = 4;
pub const I... | }
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn ping() {
let mut buffer = ThriftBuffer::new();
// new buffer has 4 bytes to hold framing later
assert_eq!(buffer.len(), 4);
assert_eq!(buffer.as_bytes(), &[0, 0, 0, 0]);
buffer.protocol_header();
ass... | Err(ParseError::Incomplete) | random_line_split |
thrift.rs | // Copyright 2019-2020 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
#![allow(dead_code)]
use crate::codec::ParseError;
pub const STOP: u8 = 0;
pub const VOID: u8 = 1;
pub const BOOL: u8 = 2;
pub const BYTE: u8 = 3;
pub const DOUBLE: u8 = 4;
pub const I... | else {
Err(ParseError::Incomplete)
}
}
None => Err(ParseError::Unknown),
}
} else {
Err(ParseError::Incomplete)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn ping() {
let mut buffer = ThriftBuffer::new();
... | {
Ok(())
} | conditional_block |
thrift.rs | // Copyright 2019-2020 Twitter, Inc.
// Licensed under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
#![allow(dead_code)]
use crate::codec::ParseError;
pub const STOP: u8 = 0;
pub const VOID: u8 = 1;
pub const BOOL: u8 = 2;
pub const BYTE: u8 = 3;
pub const DOUBLE: u8 = 4;
pub const I... |
/// add protocol version to buffer
pub fn protocol_header(&mut self) -> &Self {
self.buffer.extend_from_slice(&[128, 1, 0, 1]);
self
}
/// write the framed length to the buffer
#[inline]
pub fn frame(&mut self) -> &Self {
let bytes = self.buffer.len() - 4;
for ... | {
self.buffer.len()
} | identifier_body |
typings.d.ts | interface Date {
now(): number;
}
declare module 'http' {
import { IncomingMessage } from 'http';
export interface Response<TBody> extends IncomingMessage {
body?: TBody;
}
}
declare module 'redis' {
export function createClient(port: number, host?: string, options?: ClientOptions): Redis... | rename_commands?: { [command: string]: string };
tls?: any;
prefix?: string;
retry_strategy?: Function;
}
export class RedisClient {
expire(key: string, seconds: number): void;
getAsync(key: string): Promise<string>;
setAsync(key: string, value: any): P... | family?: string; | random_line_split |
typings.d.ts | interface Date {
now(): number;
}
declare module 'http' {
import { IncomingMessage } from 'http';
export interface Response<TBody> extends IncomingMessage {
body?: TBody;
}
}
declare module 'redis' {
export function createClient(port: number, host?: string, options?: ClientOptions): Redis... | {
constructor(options: any);
exportKey(keyType?: string): string;
}
export = NodeRsa;
}
| NodeRsa | identifier_name |
__init__.py | """
"""
from .register import get_registered_layers
#custom layer import begins
import axpy
import flatten
import argmax
import reshape
import roipooling
import priorbox
import permute
import detection_out
import normalize
import select
import crop
import reduction
#custom layer import ends
custom_layers = get_regi... | (template, kind, node):
""" make a PaddleNode for custom layer which means construct
a piece of code to define a layer implemented in 'custom_layers'
Args:
@template (PaddleNode): a factory to new a instance of PaddleNode
@kind (str): type of custom layer
@node (graph.Node): a l... | make_node | identifier_name |
__init__.py | """
"""
from .register import get_registered_layers
#custom layer import begins
import axpy
import flatten
import argmax
import reshape
import roipooling
import priorbox
import permute
import detection_out
import normalize
import select
import crop
import reduction
#custom layer import ends
custom_layers = get_regi... | """
return kind in custom_layers
def compute_output_shape(kind, node):
assert kind in custom_layers, "layer[%s] not exist in custom layers" % (
kind)
shape_func = custom_layers[kind]['shape']
parents = node.parents
inputs = [list(p.output_shape) for p in parents]
arg_names, kwargs... |
def has_layer(kind):
""" test whether this layer exists in custom layer | random_line_split |
__init__.py | """
"""
from .register import get_registered_layers
#custom layer import begins
import axpy
import flatten
import argmax
import reshape
import roipooling
import priorbox
import permute
import detection_out
import normalize
import select
import crop
import reduction
#custom layer import ends
custom_layers = get_regi... |
def has_layer(kind):
""" test whether this layer exists in custom layer
"""
return kind in custom_layers
def compute_output_shape(kind, node):
assert kind in custom_layers, "layer[%s] not exist in custom layers" % (
kind)
shape_func = custom_layers[kind]['shape']
parents = node.par... | """ set args for function 'f' using the parameters in node.layer.parameters
Args:
f (function): a python function object
params (object): a object contains attributes needed by f's arguments
Returns:
arg_names (list): a list of argument names
kwargs (dict): a dict contains need... | identifier_body |
__init__.py | """
"""
from .register import get_registered_layers
#custom layer import begins
import axpy
import flatten
import argmax
import reshape
import roipooling
import priorbox
import permute
import detection_out
import normalize
import select
import crop
import reduction
#custom layer import ends
custom_layers = get_regi... |
if node is not None and len(node.metadata):
kwargs.update(node.metadata)
return arg_list, kwargs
def has_layer(kind):
""" test whether this layer exists in custom layer
"""
return kind in custom_layers
def compute_output_shape(kind, node):
assert kind in custom_layers, "layer[%s] ... | kwargs[arg_name] = params[arg_name] | conditional_block |
upsert_iss_domains.py | #!/usr/bin/env python
"""Upserts Domains from Salesforce Domain__c.
"""
import logging
import os
from django.core.management.base import BaseCommand
import iss.models
import iss.salesforce
logger = logging.getLogger(os.path.basename(__file__))
class Command(BaseCommand):
def add_arguments(self, parser):
... |
def handle(self, *args, **options):
upsert_domains(options['modified_within'])
def upsert_domains(modified_since=7):
"""Upsert Domains for SF Domain__c modified in last `modified_since` days.
"""
logger.info('upserting domains modified in last {since} days'.
format(since=modi... | parser.add_argument('-m', '--modified-within',
type=int,
metavar='n-days',
default=7,
help='upsert Domains modified within n-days') | identifier_body |
upsert_iss_domains.py | #!/usr/bin/env python
"""Upserts Domains from Salesforce Domain__c.
"""
import logging
import os
from django.core.management.base import BaseCommand
import iss.models
import iss.salesforce
logger = logging.getLogger(os.path.basename(__file__))
class Command(BaseCommand):
def | (self, parser):
parser.add_argument('-m', '--modified-within',
type=int,
metavar='n-days',
default=7,
help='upsert Domains modified within n-days')
def handle(self, *args, **options):
ups... | add_arguments | identifier_name |
upsert_iss_domains.py | #!/usr/bin/env python
"""Upserts Domains from Salesforce Domain__c.
"""
import logging
import os
from django.core.management.base import BaseCommand
import iss.models
import iss.salesforce
logger = logging.getLogger(os.path.basename(__file__))
class Command(BaseCommand):
def add_arguments(self, parser):
... | iss.models.Domain.upsert(domain) | conditional_block | |
upsert_iss_domains.py | #!/usr/bin/env python
"""Upserts Domains from Salesforce Domain__c.
"""
import logging
import os
| from django.core.management.base import BaseCommand
import iss.models
import iss.salesforce
logger = logging.getLogger(os.path.basename(__file__))
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('-m', '--modified-within',
type=int,
... | random_line_split | |
search.component.ts | import { Component } from '@angular/core';
import { Query } from './query';
import { SearchService } from './search.service';
import { Car } from './car';
import { CarListComponent } from './car-list.component';
@Component({
selector: 'to-search',
providers: [ SearchService],
directives: [ CarListComponent ],
... |
private getDefaultStartDate() {
let date = new Date();
date.setDate(date.getDate() + 1);
return this.parseDate(date);
}
private getDefaultEndDate() {
let date = new Date();
date.setDate(date.getDate() + 2);
return this.parseDate(date);
}
private parseDate(date: Date) {
let [mon... | {
return {
location: '',
startDate: this.getDefaultStartDate(),
endDate: this.getDefaultEndDate(),
pickupTime: '08:00',
dropoffTime: '20:00'
}
} | identifier_body |
search.component.ts | import { Component } from '@angular/core';
import { Query } from './query';
import { SearchService } from './search.service';
import { Car } from './car';
import { CarListComponent } from './car-list.component';
@Component({
selector: 'to-search',
providers: [ SearchService],
directives: [ CarListComponent ],
... | let [month, day, year] = date.toLocaleDateString('en-US', { day: '2-digit', month: '2-digit', year: 'numeric' }).split('/');
return [year, month, day].join('-');
}
} | }
private parseDate(date: Date) { | random_line_split |
search.component.ts | import { Component } from '@angular/core';
import { Query } from './query';
import { SearchService } from './search.service';
import { Car } from './car';
import { CarListComponent } from './car-list.component';
@Component({
selector: 'to-search',
providers: [ SearchService],
directives: [ CarListComponent ],
... | () {
this.query = this.getDefaultQuery();
this.results = null;
}
private getDefaultQuery(): Query {
return {
location: '',
startDate: this.getDefaultStartDate(),
endDate: this.getDefaultEndDate(),
pickupTime: '08:00',
dropoffTime: '20:00'
}
}
private getDefaultSta... | clear | identifier_name |
master.py | """
Extensions to mitmproxy master.
"""
import multiprocessing
from seproxer import mitmproxy_extensions
import seproxer.mitmproxy_extensions.addons # NOQA
import seproxer.mitmproxy_extensions.options
| import mitmproxy.addons
import mitmproxy.proxy.server
import mitmproxy.master
class ProxyMaster(mitmproxy.master.Master):
"""
Implements mitmproxy master to produce flows through a shared Queue and a shared
state attribute that specifies if there are any responses pending
"""
def __init__(self, #... | random_line_split | |
master.py | """
Extensions to mitmproxy master.
"""
import multiprocessing
from seproxer import mitmproxy_extensions
import seproxer.mitmproxy_extensions.addons # NOQA
import seproxer.mitmproxy_extensions.options
import mitmproxy.addons
import mitmproxy.proxy.server
import mitmproxy.master
class ProxyMaster(mitmproxy.master.M... | """
Implements mitmproxy master to produce flows through a shared Queue and a shared
state attribute that specifies if there are any responses pending
"""
def __init__(self, # type: ignore # (mypy doesn't like multiprocessing lib)
options: seproxer.mitmproxy_extensions.options,
... | identifier_body | |
master.py | """
Extensions to mitmproxy master.
"""
import multiprocessing
from seproxer import mitmproxy_extensions
import seproxer.mitmproxy_extensions.addons # NOQA
import seproxer.mitmproxy_extensions.options
import mitmproxy.addons
import mitmproxy.proxy.server
import mitmproxy.master
class ProxyMaster(mitmproxy.master.M... |
return tick_result
| flow_results = self._memory_stream_addon.get_stream()
self._memory_stream_addon.start()
# Push the results to the result queue1
self.results_queue.put(flow_results)
self.push_event.clear() | conditional_block |
master.py | """
Extensions to mitmproxy master.
"""
import multiprocessing
from seproxer import mitmproxy_extensions
import seproxer.mitmproxy_extensions.addons # NOQA
import seproxer.mitmproxy_extensions.options
import mitmproxy.addons
import mitmproxy.proxy.server
import mitmproxy.master
class | (mitmproxy.master.Master):
"""
Implements mitmproxy master to produce flows through a shared Queue and a shared
state attribute that specifies if there are any responses pending
"""
def __init__(self, # type: ignore # (mypy doesn't like multiprocessing lib)
options: seproxer.mitmpr... | ProxyMaster | identifier_name |
jquery.smoothscroll.js | // SmoothScroll v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Patrick Brunner (original idea)
// - Michael Herf (Pulse Algorithm)
// - Justin Force (Resurect)
// Scroll Variables (tweakable)
var framerate = 150; // [Hz]
var animtime = 7... | x -= 1;
expx = 1 - Math.exp(-x);
val = start + (expx * (1 - start));
}
return val * pulseNormalize;
}
function pulse(x) {
if (x >= 1) return 1;
if (x <= 0) return 0;
if (pulseNormalize == 1) {
pulseNormalize /= pulse_(1);
}
return pulse_(x);
}
addEvent("mousedown", mousedown);
addEvent(... | // the previous animation ended here:
start = Math.exp(-1);
// simple viscous drag | random_line_split |
jquery.smoothscroll.js | // SmoothScroll v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Patrick Brunner (original idea)
// - Michael Herf (Pulse Algorithm)
// - Justin Force (Resurect)
// Scroll Variables (tweakable)
var framerate = 150; // [Hz]
var animtime = 7... | (type, fn, bubble) {
window.addEventListener(type, fn, (bubble||false));
}
function removeEvent(type, fn, bubble) {
window.removeEventListener(type, fn, (bubble||false));
}
function isNodeName(el, tag) {
return (el.nodeName||"").toLowerCase() === tag.toLowerCase();
}
function directionCheck(x, y) {
x = (x > ... | addEvent | identifier_name |
jquery.smoothscroll.js | // SmoothScroll v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Patrick Brunner (original idea)
// - Michael Herf (Pulse Algorithm)
// - Justin Force (Resurect)
// Scroll Variables (tweakable)
var framerate = 150; // [Hz]
var animtime = 7... |
}
/************************************************
* SCROLLING
************************************************/
var que = [];
var pending = false;
var lastScroll = +new Date;
/**
* Pushes scroll actions to the scrolling queue.
*/
function scrollArray(elem, left, top, delay) {
delay || (delay = 1000);
di... | {
body.style.backgroundAttachment = "scroll";
html.style.backgroundAttachment = "scroll";
} | conditional_block |
jquery.smoothscroll.js | // SmoothScroll v1.2.1
// Licensed under the terms of the MIT license.
// People involved
// - Balazs Galambosi (maintainer)
// - Patrick Brunner (original idea)
// - Michael Herf (Pulse Algorithm)
// - Justin Force (Resurect)
// Scroll Variables (tweakable)
var framerate = 150; // [Hz]
var animtime = 7... |
addEvent("mousedown", mousedown);
addEvent("mousewheel", wheel);
addEvent("load", init);
| {
if (x >= 1) return 1;
if (x <= 0) return 0;
if (pulseNormalize == 1) {
pulseNormalize /= pulse_(1);
}
return pulse_(x);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.