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 |
|---|---|---|---|---|
run_utils.py |
def set_seed(seed):
print('seed = {0}'.format(seed))
os.environ['RECSYS_SEED'] = str(seed)
np.random.seed(seed)
def get_seed():
env = os.getenv('RECSYS_SEED')
if env:
return int(env)
return -1
def build_urm():
urm_data = load_csv(DataFiles.TRAIN)
urm_data = [[int(row[i]) i... | (n_items):
price_icm_items, _, price_icm_values = __load_icm_csv(DataFiles.ICM_PRICE, third_type=float)
price_icm_values = __encode_values(price_icm_values)
n_features = max(price_icm_values) + 1
shape = (n_items, n_features)
ones = np.ones(len(price_icm_values))
price_icm = sps.csr_matrix((ones... | build_price_icm | identifier_name |
run_utils.py | .seed(seed)
def get_seed():
env = os.getenv('RECSYS_SEED')
if env:
return int(env)
return -1
def build_urm():
urm_data = load_csv(DataFiles.TRAIN)
urm_data = [[int(row[i]) if i <= 1 else int(float(row[i])) for i in range(len(row))] for row in urm_data]
users, items, ratings = map(np.... | le = LabelEncoder()
le.fit(values)
return le.transform(values) | identifier_body | |
run_utils.py |
def set_seed(seed):
print('seed = {0}'.format(seed))
os.environ['RECSYS_SEED'] = str(seed)
np.random.seed(seed)
def get_seed():
env = os.getenv('RECSYS_SEED')
if env:
return int(env)
return -1
def build_urm():
urm_data = load_csv(DataFiles.TRAIN)
urm_data = [[int(row[i]) i... |
else:
return evaluate_algorithm(recommender, urm_test, excluded_users=excluded_users, verbose=verbose)
def evaluate_mp(recommender, urm_tests, excluded_users=[], cython=False, verbose=True, n_processes=0):
assert type(urm_tests) == list
assert len(urm_tests) >= 1
assert type(n_processes) == i... | if verbose:
print('Ignoring argument excluded_users')
from cython_modules.evaluation import evaluate_cython
if verbose:
print('Using Cython evaluation')
return evaluate_cython(recommender, urm_test, verbose=verbose) | conditional_block |
run_utils.py | 3
def set_seed(seed):
print('seed = {0}'.format(seed))
os.environ['RECSYS_SEED'] = str(seed)
np.random.seed(seed)
def get_seed():
env = os.getenv('RECSYS_SEED')
if env:
return int(env)
return -1
def build_urm():
urm_data = load_csv(DataFiles.TRAIN)
urm_data = [[int(row[i]) ... | age_ucm = sps.csr_matrix((age_ucm_values, (age_ucm_users, age_ucm_features)), shape=shape, dtype=int)
return age_ucm
def build_region_ucm(n_users):
region_ucm_users, region_ucm_features, region_ucm_values = __load_icm_csv(DataFiles.UCM_REGION, third_type=float)
n_features = max(region_ucm_features) + ... | age_ucm_users, age_ucm_features, age_ucm_values = __load_icm_csv(DataFiles.UCM_AGE, third_type=float)
n_features = max(age_ucm_features) + 1
shape = (n_users, n_features) | random_line_split |
Home.js | ] = useState([]);
const [database, setDatabase] = useState([])
const [isModal, setIsModal] = useState(false);
const [isChecked, setIsChecked] = useState({
filters:[
{type: "meat", checked: false, text: "Kjøtt"},
{type: "fish", checked: false, text: "Fisk"},
{type: "veg", checked: false, text... | setError(error);
}
}
readCollection("dinners")
}, [])
//set filteredData to "database"
useEffect(() => {
setFilteredData([...database])
}, [database]);
//Apply filter when a filter is added/removed
useEffect(() => {
applyFilter();
}, [isChecked]);
//Organize co... | try{
const collection = await firebaseInstance.firestore().collection(text)
const readCollection = await collection.get()
let returnArray = [];
readCollection.forEach(item => {
const itemData = item.data() || {};
returnArray.push({
id: item... | identifier_body |
Home.js | ] = useState([]);
const [database, setDatabase] = useState([])
const [isModal, setIsModal] = useState(false);
const [isChecked, setIsChecked] = useState({
filters:[
{type: "meat", checked: false, text: "Kjøtt"},
{type: "fish", checked: false, text: "Fisk"},
{type: "veg", checked: false, text... | }
})
if (fishArr.length > 0 || vegArr.length > 0 || meatArr.length > 0) {
tempArr = [...fishArr, ...vegArr, ...meatArr];
}
//filters glutenFree and lactoseFree - based on the tempArr that's already filtered by meat, fish and vegetarian courses
isChecked.filters.forEach(param => {
... | let veg = item => item.type === "veg";
vegArr = filter(veg, tempArr);
}
| conditional_block |
Home.js | () {
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [weekday, setWeekday] = useState([]);
const [friday, setFriday] = useState([]);
const [sunday, setSunday] = useState([]);
const [fastFood, setFastFood] = useState([]);
const [dinnerList, setDinnerList]... | Home | identifier_name | |
Home.js | ] = useState([]);
const [database, setDatabase] = useState([])
const [isModal, setIsModal] = useState(false);
const [isChecked, setIsChecked] = useState({
filters:[
{type: "meat", checked: false, text: "Kjøtt"},
{type: "fish", checked: false, text: "Fisk"},
{type: "veg", checked: false, text... | {type: "fri", checked: false, text: "Fredag", index: 4},
{type: "sat", checked: false, text: "Lørdag", index: 5},
{type: "sun", checked: false, text: "Søndag", index:6},
]}
);
const storage = useStorageContext();
//----------------------------------------------------------------useEffect... | random_line_split | |
proxy.rs | (String),
}
pub trait Authenticate {
fn authenticate(&self, req: &Request<Body>) -> Result<Identity, String>;
}
pub enum AuthzResult {
Allow,
Disallow,
}
pub trait Authorize {
fn authorize(&self, i: &Identity, req: &Request<Body>) -> Result<AuthzResult, String>;
}
pub trait SiteAuthorize {
fn au... |
}
pub enum Trace {
TraceId(String),
TraceSecurity(String, openssl::x509::X509),
TraceRequest(String, Request<Body>),
TraceResponse(String, Request<Body>),
}
fn make_absolute(req: &mut Request<Body>) {
/* RFC 7312 5.4
When a proxy receives a request with an absolute-form of
request-ta... | {
Ok(Identity::Anonymous)
} | identifier_body |
proxy.rs | addrs.next() {
Some(addr) => addr,
None => return result(502),
},
Err(e) => {
eprintln!("Upstream resolution: ({}): {}", hostname, e);
return Box::new(futures::future::ok(result_502_resolve_failed(&hostname)));
}
... | }
println!("Trace recv");
Ok(())
}); | random_line_split | |
proxy.rs | (String),
}
pub trait Authenticate {
fn authenticate(&self, req: &Request<Body>) -> Result<Identity, String>;
}
pub enum AuthzResult {
Allow,
Disallow,
}
pub trait Authorize {
fn authorize(&self, i: &Identity, req: &Request<Body>) -> Result<AuthzResult, String>;
}
pub trait SiteAuthorize {
fn au... | (&self) -> Proxy<U, S, A> {
Proxy {
tracer: self.tracer.iter().map(|t| t.clone()).next(),
ca: self.ca.clone(),
auth_config: self.auth_config.clone(),
upstream_ssl_pool: pool::Pool::empty(100),
}
}
fn handle<C: Connect + 'static>(
&self,
... | dup | identifier_name |
partdisk.go | .frandi = basedir+"/"+randstring(rstl)
}
//Creates a random string made of lower case letters only
func randstring(size int) string {
rval := make([]byte,size)
rand.Seed(time.Now().UnixNano())
for i:=0; i<size; i++ {
rval[i] = byte(rand.Intn(26) + 97)
}
return string(rval)
}
//Creates a random list of bytes wi... | for index, value := range fS.fileSizes {
semiTotal += value * fS.fileAmmount[index]
rst += fmt.Sprintf("Files of size: %d, count: %d, total size: %d\n", value, fS.fileAmmount[index], value*fS.fileAmmount[index])
}
rst += fmt.Sprintf("Total size reserved: %d bytes.\n", semiTotal)
return rst
}
//Generate a messa... | func GetDefFiles(fS *FileCollection) string {
var semiTotal uint64
var rst string | random_line_split |
partdisk.go | randi = basedir+"/"+randstring(rstl)
}
//Creates a random string made of lower case letters only
func randstring(size int) string {
rval := make([]byte,size)
rand.Seed(time.Now().UnixNano())
for i:=0; i<size; i++ {
rval[i] = byte(rand.Intn(26) + 97)
}
return string(rval)
}
//Creates a random list of bytes with... | (fS *FileCollection, ts int64, filelock chan int64) {
var lt time.Time
var err error
select {
case <- time.After(5 * time.Second):
//If 5 seconds pass without getting the proper lock, abort
log.Printf("partdisk.CreateFiles(): timeout waiting for lock\n")
return
case chts := <- filelock:
if chts == ts { //... | CreateFiles | identifier_name |
partdisk.go | randi = basedir+"/"+randstring(rstl)
}
//Creates a random string made of lower case letters only
func randstring(size int) string {
rval := make([]byte,size)
rand.Seed(time.Now().UnixNano())
for i:=0; i<size; i++ {
rval[i] = byte(rand.Intn(26) + 97)
}
return string(rval)
}
//Creates a random list of bytes with... | filelock <- chts
return
}
}
//Lock obtained proper, create/delete the files
err = adrefiles(fS)
if err != nil {
log.Printf("CreateFiles(): Error creating file: %s\n",err.Error())
return
}
log.Printf("CreateFiles(): Request %d completed in %d seconds\n",ts,int64(time.Since(lt).Seconds()))
}
//Add or ... | {
var lt time.Time
var err error
select {
case <- time.After(5 * time.Second):
//If 5 seconds pass without getting the proper lock, abort
log.Printf("partdisk.CreateFiles(): timeout waiting for lock\n")
return
case chts := <- filelock:
if chts == ts { //Got the lock and it matches the timestamp received
... | identifier_body |
partdisk.go | }
}
return tfsize,nil
}
//Compute the number of files of each size required for the size requested
//tsize contains the number of bytes to allocate
//hlimit is the maximum size that can be requested
func DefineFiles(tsize uint64, hilimit uint64, flS *FileCollection) error {
var nfiles, remain uint64
tfs, err := ... | {
base[x]=byte(rand.Intn(95) + 32) //ASCII 32 to 126
} | conditional_block | |
main.py | (counter))
frame = cv2.resize(frame, None, fx=0.4, fy=0.4)
height, width, channels = frame.shape
startingtime = time.time()
frame_id = 0
# Detecting objects
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.for... | ():
# get a random row and column index
current_row_index = np.random.randint(environment_rows)
current_column_index = np.random.randint(environment_columns)
# continue choosing random row and column indexes until a non-terminal state is identified
# (i.e., until the chosen state is a 'path whi... | get_starting_location | identifier_name |
main.py | output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3)) # to get list of colors for each possible class
# Loading image
with open("{}.jpeg".format(counter), "wb") as f:
f.write(p)
frame = cv2.imread("{}.j... | net = cv2.dnn.readNet("yolo/yolov3.weights", "yolo/yolov3.cfg")
counter = 1
with open("yolo/coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
| random_line_split | |
main.py | (counter))
frame = cv2.resize(frame, None, fx=0.4, fy=0.4)
height, width, channels = frame.shape
startingtime = time.time()
frame_id = 0
# Detecting objects
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.for... |
# Define a function that will get the shortest path between any location within the source that
# the car is allowed to travel and the goal.
def get_shortest_path(start_row_index, start_column_index):
# return immediately if this is an invalid starting location
if is_terminal_state(start_row_index, st... | new_row_index = current_row_index
new_column_index = current_column_index
if actions[action_index] == 'up' and current_row_index > 0:
new_row_index -= 1
elif actions[action_index] == 'right' and current_column_index < environment_columns - 1:
new_column_index += 1
elif actions[acti... | identifier_body |
main.py | int(center_y - h / 2)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
count_label = []
count = []
font = cv2.FONT_HERSHEY_PLAIN
for i in r... | action_index = get_next_action(row_index, column_index, epsilon)
# perform the chosen action, and transition to the next state (i.e., move to the next location)
old_row_index, old_column_index = row_index, column_index # store the old row and column indexes
row_index, column_index = get_ne... | conditional_block | |
smart_contract_service_impl.go | was occured during getting repository list"))
return
}
for _, repo := range repoList {
localReposPath := scs.SmartContractDirPath + "/" +
strings.Replace(repo.FullName, "/", "_", -1)
err = os.MkdirAll(localReposPath, 0755)
if err != nil {
errorHandler(errors.New("An error was occured during m... | e(tarPath_config)
if err != nil {
logger_s.Errorln("An error occured while reading config | conditional_block | |
smart_contract_service_impl.go | () {
}
func NewSmartContractService(githubID string,smartContractDirPath string) SmartContractService{
return &SmartContractServiceImpl{
GithubID:githubID,
SmartContractDirPath:smartContractDirPath,
SmartContractMap: make(map[string]SmartContract),
}
}
func (scs *SmartContractServiceImpl) PullAllSmartContrac... | Init | identifier_name | |
smart_contract_service_impl.go | {
repoList, err := domain.GetRepositoryList(authenticatedGit)
if err != nil {
errorHandler(errors.New("An error was occured during getting repository list"))
return
}
for _, repo := range repoList {
localReposPath := scs.SmartContractDirPath + "/" +
strings.Replace(repo.FullName, "/", "_", -1)
... |
err = cmd.Run()
if err != nil {
logger_s.Errorln("SmartContract build error")
return err
}
cmd = exec.Command("chmod", "777", TMP_DIR + "/" + sc.Name)
cmd.Dir = sc.SmartContractPath + "/" + transaction.TxData.ContractID
err = cmd.Run()
if err != nil {
logger_s.Errorln("Chmod Error")
return err
}
logg... | {
return errors.New("Tx Marshal Error")
}
sc, ok := scs.SmartContractMap[transaction.TxData.ContractID];
if !ok {
logger_s.Errorln("Not exist contract ID")
return errors.New("Not exist contract ID")
}
_, err = os.Stat(sc.SmartContractPath)
if os.IsNotExist(err) {
logger_s.Errorln("File or Directory Not... | identifier_body |
smart_contract_service_impl.go | () {
repoList, err := domain.GetRepositoryList(authenticatedGit)
if err != nil {
errorHandler(errors.New("An error was occured during getting repository list"))
return
}
for _, repo := range repoList {
localReposPath := scs.SmartContractDirPath + "/" +
strings.Replace(repo.FullName, "/", "_", -1)
... | }
_, err = file.WriteString("Deployed at " + now + "\n")
if err != nil {
return "", errors.New("An error occured while writing file!")
}
err = file.Close()
if err != nil {
return "", errors.New("An error occured while closing file!")
}
err = domain.CommitAndPush(scs.SmartContractDirPath + "/" + new_repos_... | return "", errors.New("An error occured while creating or opening file!") | random_line_split |
main.rs | }
}
// Simple `split_once` "polyfill" since it's currently unstable.
fn split_once(text: &str, pat: char) -> Option<(&str, &str)> {
let mut iter = text.splitn(2, pat);
Some((iter.next()?, iter.next()?))
}
async fn parse_name_and_discriminator(
args: &mut Args,
) -> Option<Result<(String, u16), &'static s... | let committee_msg = committee_channel
.say(
ctx,
&MessageBuilder::new()
.push("Received request from ")
.mention(&msg.author)
.push(if is_external {
format!(
" to forward message to {}",
... |
let cleaned_content = content_safe(ctx, args.rest(), &ContentSafeOptions::default()).await;
let typing = msg.channel_id.start_typing(&ctx.http)?;
| random_line_split |
main.rs | }
}
// Simple `split_once` "polyfill" since it's currently unstable.
fn split_once(text: &str, pat: char) -> Option<(&str, &str)> {
let mut iter = text.splitn(2, pat);
Some((iter.next()?, iter.next()?))
}
async fn parse_name_and_discriminator(
args: &mut Args,
) -> Option<Result<(String, u16), &'static s... | mmand("forward")]
async fn forward(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let config = {
let data = ctx.data.read().await;
data.get::<ConfigContainer>().unwrap().clone()
};
let delegate_member = if let Ok(member) = ctx
.http
.get_member(config.guild... |
#[co | identifier_name |
main.rs | }
}
// Simple `split_once` "polyfill" since it's currently unstable.
fn split_once(text: &str, pat: char) -> Option<(&str, &str)> {
l | fn parse_name_and_discriminator(
args: &mut Args,
) -> Option<Result<(String, u16), &'static str>> {
let mut name = String::new();
while let Ok(arg) = args.single::<String>() {
let mut fragment = arg.as_str();
if name.is_empty() {
match fragment.strip_prefix('@') {
... | et mut iter = text.splitn(2, pat);
Some((iter.next()?, iter.next()?))
}
async | identifier_body |
NeatDatePicker.js | winY = Dimensions.get('window').height
const NeatDatePicker = ({
isVisible,
initialDate, mode,
onCancel, onConfirm,
minDate, maxDate,
startDate, endDate,
onBackButtonPress, onBackdropPress,
chinese, colorOptions,
}) => {
const [showChangeYearModal, setShowChangeYearModal] = useState(fa... | {sevenDays.map((weekDay, index) => (
<View style={styles.keys} key={index.toString()}>
<Text style={[styles.weekDays, { color: weekDaysColor }]}>
{weekDay}
</Text>
... | <View style={styles.keys_container}>
{/* week days */} | random_line_split |
country-card.component.ts | .route.params.subscribe(params => {
this.selectedCountryId = params['id'];
this.getCountryData();
this.getShapeFile();
this.getCountriesList();
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
getShapeFile() {
this.countryCardService
.getShapeFile()
.then(respon... |
});
}
resetStyle(e: any) {
this.geoJsonLayer(e.target);
}
removeGeoLayer = function () {
if (this.geoJsonLayer != undefined) {
this.mapObj.removeLayer(this.geoJsonLayer);
}
}
// chart
loadSpiderChart() {
Highcharts.chart('spider-chart-container', {
chart: {
... | {
var currentBounds = L.geoJson(layer).getBounds();
this.mapObj.fitBounds(currentBounds);
setTimeout(() => {
let zoomDiff = this.mapObj.getZoom()
if (this.mapObj.getZoom() > 4) {
zoomDiff = 4;
}
this.mapObj.setView(this.mapObj.getCenter(), zoom... | conditional_block |
country-card.component.ts | .route.params.subscribe(params => {
this.selectedCountryId = params['id'];
this.getCountryData();
this.getShapeFile();
this.getCountriesList();
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
getShapeFile() |
getCountriesList() {
this.countryCardService
.getCountryList()
.then(responseObj => {
this.countriesList = this.countryCardService.getSortedData(responseObj.features); // first sort the response object
});
}
// country data
getCountryData() {
this.countryCardService
... | {
this.countryCardService
.getShapeFile()
.then(responseObj => {
this.geoJsonData = responseObj;
this.loadmap();
this.loadlayer();
});
} | identifier_body |
country-card.component.ts | .route.params.subscribe(params => {
this.selectedCountryId = params['id'];
this.getCountryData();
this.getShapeFile();
this.getCountriesList();
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
getShapeFile() {
this.countryCardService
.getShapeFile()
.then(respon... |
// change the country for country card event hadler
onSelect(selection: any) {
this.selectedCountryName = selection.properties.name;
this.selectedCountryId = selection.properties.iso_a3;
this.selectedCountryFlagId = selection.properties.iso_a2.toLowerCase();
this.router.navigate(['/country-card', ... | random_line_split | |
country-card.component.ts | this.route.params.subscribe(params => {
this.selectedCountryId = params['id'];
this.getCountryData();
this.getShapeFile();
this.getCountriesList();
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
getShapeFile() {
this.countryCardService
.getShapeFile()
.then(r... | (e: any) {
this.geoJsonLayer(e.target);
}
removeGeoLayer = function () {
if (this.geoJsonLayer != undefined) {
this.mapObj.removeLayer(this.geoJsonLayer);
}
}
// chart
loadSpiderChart() {
Highcharts.chart('spider-chart-container', {
chart: {
polar: true,
ty... | resetStyle | identifier_name |
pars_upload.rs | impl Reply, Error = Rejection> + Clone {
let cors = warp::cors()
.allow_origin(pars_origin)
.allow_headers(&[header::AUTHORIZATION])
.allow_methods(&[Method::POST])
.build();
warp::path!("pars" / String)
.and(warp::post())
// Max upload size is set to a very hig... | }
fn document_from_form_data(storage_file: StorageFile, metadata: BlobMetadata) -> Document {
Document {
id: metadata.file_name.to_string(),
name: metadata.title.to_string(),
document_type: DocumentType::Par,
author: metadata.author.to_string(),
products: metadata.product_na... | random_line_split | |
pars_upload.rs | impl Reply, Error = Rejection> + Clone {
let cors = warp::cors()
.allow_origin(pars_origin)
.allow_headers(&[header::AUTHORIZATION])
.allow_methods(&[Method::POST])
.build();
warp::path!("pars" / String)
.and(warp::post())
// Max upload size is set to a very hig... | products.push(group);
}
}
}
let file_name = file_field
.as_ref()
.and_then(|field| field.file_name())
.ok_or(SubmissionError::MissingField { name: "file" })?
.to_string();
let file_data = file_field
.and_then(|field| field.into_fi... | {
let mut products = Vec::new();
let mut file_field = None;
for field in fields {
if field.name == "file" {
file_field = Some(field.value);
continue;
}
if field.name == "product_name" {
products.push(vec![]);
}
match products.las... | identifier_body |
pars_upload.rs | impl Reply, Error = Rejection> + Clone {
let cors = warp::cors()
.allow_origin(pars_origin)
.allow_headers(&[header::AUTHORIZATION])
.allow_methods(&[Method::POST])
.build();
warp::path!("pars" / String)
.and(warp::post())
// Max upload size is set to a very hig... |
None => {
let group = vec![field];
products.push(group);
}
}
}
let file_name = file_field
.as_ref()
.and_then(|field| field.file_name())
.ok_or(SubmissionError::MissingField { name: "file" })?
.to_string();
le... | {
group.push(field);
} | conditional_block |
pars_upload.rs | impl Reply, Error = Rejection> + Clone {
let cors = warp::cors()
.allow_origin(pars_origin)
.allow_headers(&[header::AUTHORIZATION])
.allow_methods(&[Method::POST])
.build();
warp::path!("pars" / String)
.and(warp::post())
// Max upload size is set to a very hig... | {
job_ids: Vec<Uuid>,
}
#[derive(Debug, Serialize)]
struct UpdateResponse {
delete: JobStatusResponse,
upload: Vec<Uuid>,
}
async fn read_pars_upload(
form_data: FormData,
) -> Result<(Vec<BlobMetadata>, Vec<u8>), SubmissionError> {
let fields = collect_fields(form_data)
.await
.m... | UploadResponse | identifier_name |
calc_CORL2017_Tables.py | </style>
<title> Self-Driving Car Research </title>
<p>By Mojtaba Valipour @ Shiraz University - 2018 </p>
<p><a href="http://vpcom.ir/">vpcom.ir</a></p>
</head>
<body><p>MODEL: %s</a></p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p></body>
</html>
"""
# Tested by latexbase.com
late... | background-color: #dddddd;
} | random_line_split | |
calc_CORL2017_Tables.py | kilometers travelled before an infraction.
\\end{center}
\\subsubsection{Infractions : Navigation With Dynamic Obstacles}
\\begin{center}
%s
Average number of kilometers travelled before an infraction.
\\end{center}
\\subsubsection{Num Infractions : Straight}
\\begin{center}
%s
Number of infractions occured in the ... | dataListTable2[metricIdx][i].append(summed_driven_kilometers[i] / metric_sum_values[i]) | conditional_block | |
sketch.js | of game
fill(0, 100);
rect(0,185, WIDTH, 150);
fill(255, 200, 0, 200);
textAlign(LEFT);
textSize(20);
text("Instructions: You're a bunny", WIDTH/8, HEIGHT/2 - 20);
image(bunnyFront, 4*WIDTH/6+5, HEIGHT/2 - 45, 40, 40);
text("trying to collect carrots!", WIDTH/8, HEIGHT/2 + 20);
image(carrotimg, 3*W... | check | identifier_name | |
sketch.js | ///set it up!
function setup(){
framerate = 20;
var myCanvas = createCanvas(WIDTH, HEIGHT);
myCanvas.parent("js-game");
var randomNumber = floor(random(0,3));
}
function draw(){
///Credit to class game template
if (gameState == 0){
startScreen();
} else if (gameState == 1){
update();
} else if (game... |
else if (6 <= i) {
let y = HEIGHT/2 - HEIGHT/5 + (platformSize + 10);
platforms[i] = new platform(x, y, platformSize);
}
else if (3 <= i < 6) {
let y = HEIGHT/2 - HEIGHT/5 + (platformSize + 10) * 2;
platforms[i] = new platform(x, y, platformSize);
}
}
//an array of spots/tomatoes! altered... | {
let y = HEIGHT/2 - HEIGHT/5;
platforms[i] = new platform(x, y, platformSize);
} | conditional_block |
sketch.js | }
///set it up!
function setup(){
framerate = 20;
var myCanvas = createCanvas(WIDTH, HEIGHT);
myCanvas.parent("js-game");
var randomNumber = floor(random(0,3));
}
function draw(){
///Credit to class game template
if (gameState == 0){
startScreen();
} else if (gameState == 1){
update();
} else i... | function gameOver(){
imageMode(CORNER);
//graphics
background(grassimg);
textFont(font);
textSize(50);
fill(255, 200, 0, 200);
textAlign(CENTER);
text("Game Over!", WIDTH/2, HEIGHT/4);
textSize(20);
text("Final Score: " + score, WIDTH/2, HEIGHT/4 + 30);
textSize(25);
text("Press Space to... | //game over | random_line_split |
rbtree.go | () bool {
return n.Left == nil || n.Left.Color == Black
}
// LeftRed the left child of a node is black if not nil and its color is black.
func (n *Node) LeftRed() bool {
return n.Left != nil && n.Left.Color == Red
}
// RightBlack the right child of a node is black if nil or its color is black.
func (n *Node) RightB... | LeftBlack | identifier_name | |
rbtree.go | add one key/value node in the tree, replace that if exist
func (t *RBTree) Add(item compare.Lesser) {
t.lock.Lock()
defer t.lock.Unlock()
t.Node = addTreeNode(t.stack, t.Node, item)
}
// Find node
func (t *RBTree) Find(key compare.Lesser) interface{} {
t.lock.RLock()
defer t.lock.RUnlock()
return Find(t.Node,... |
s := stack.sibling()
// case 3: P is red, S is red, PP is black
// execute: set P,S to black, PP to red
// result: black count through PP is not change, continue balance on parent of PP
if s != nil && s.Color == Red {
p.Color = Black
s.Color = Black
pp.Color = Red
stack.pop().pop()
continu... | {
return
} | conditional_block |
rbtree.go | Add add one key/value node in the tree, replace that if exist
func (t *RBTree) Add(item compare.Lesser) {
t.lock.Lock()
defer t.lock.Unlock()
t.Node = addTreeNode(t.stack, t.Node, item)
}
// Find node
func (t *RBTree) Find(key compare.Lesser) interface{} {
t.lock.RLock()
defer t.lock.RUnlock()
return Find(t.N... | node = node.Left
case node.Item.Less(item):
stack.push(node, Right)
node = node.Right
default:
ret = node.Item
break FOR
}
}
// not find
if node == nil {
return root, nil
}
var inorderSuccessor *Node
// find the inorder successor
if node.Right != nil {
stack.push(node, | FOR:
for node != nil {
switch {
case item.Less(node.Item):
stack.push(node, Left) | random_line_split |
rbtree.go |
// RightRed the right child of a node is black if not nil and its color is black.
func (n *Node) RightRed() bool {
return n.Right != nil && n.Right.Color == Red
}
// RBTree red-black tree
type RBTree struct {
Node *Node
lock sync.RWMutex
stack *stack
}
// New create a new red-black tree
func New() *RBTree {
... | {
return n.Right == nil || n.Right.Color == Black
} | identifier_body | |
Estimate_Hazard.py | if info[7]=='1': #if they are male
hd[House_Name][0][2][1].append(info)
elif info[7]=='0': #if they are female
hd[House_Name][0][2][2].append(info)
else:
print 'b',info
else:
print 'bb',info
print info[8]
elif info[3]=='': #if they are alive
if info[8]=='1':#if they are noble
... | (k, lam, age, alive):
joint = thinkbayes2.MakeJoint(k, lam)
suite = GOT(joint)
suite.Update((age, alive))
k, lam = suite.Marginal(0, label=k.label), suite.Marginal(1, label=lam.label)
return k, lam
def makePMF(k,lam):
k.label = 'K'
lam.label = 'Lam'
print("Updating deaths")
numDead = len(dead)
ticks = math... | Update | identifier_name |
Estimate_Hazard.py | if info[7]=='1': #if they are male
hd[House_Name][0][2][1].append(info)
elif info[7]=='0': #if they are female
hd[House_Name][0][2][2].append(info)
else:
print 'b',info
else:
print 'bb',info
print info[8]
elif info[3]=='': #if they are alive
if info[8]=='1':#if they are noble
... |
for info in data:
for key in houselist:
house_list(key,info)
def ages(alive,dead):
got=72
cok=69
sos=81
ffc=45
dwd=72
bd={'got':got,'cok':cok,'sos':sos,'ffc':ffc,'dwd':dwd}
bnd={'got':0,'cok':1,'sos':2,'ffc':3,'dwd':4}
introductions=[]
lifetimes=[]
for pers in dead:
if pers[9]=='1':
start='got'
... | print 'e',info | conditional_block |
Estimate_Hazard.py | if info[7]=='1': #if they are male
hd[House_Name][0][2][1].append(info)
elif info[7]=='0': #if they are female
hd[House_Name][0][2][2].append(info)
else:
print 'b',info
else:
print 'bb',info
print info[8]
elif info[3]=='': #if they are alive
if info[8]=='1':#if they are noble
... | for key in houselist:
house_list(key,info)
def ages(alive,dead):
got=72
cok=69
sos=81
ffc=45
dwd=72
bd={'got':got,'cok':cok,'sos':sos,'ffc':ffc,'dwd':dwd}
bnd={'got':0,'cok':1,'sos':2,'ffc':3,'dwd':4}
introductions=[]
lifetimes=[]
for pers in dead:
if pers[9]=='1':
start='got'
elif pers[10]=='1':... | print 'e',info
for info in data: | random_line_split |
Estimate_Hazard.py | ': #if they are smallfolk
if info[7]=='1': #if they are male
hd[House_Name][1][2][1].append(info)
elif info[7]=='0': #if they are female
hd[House_Name][1][2][2].append(info)
else:
print 'd',info
else:
print 'e',info
for info in data:
for key in houselist:
house_list(key,info)
def ... | cur_house=hd[house]
alive1=cur_house[1][1][1] #Noble Men
alive2=cur_house[1][1][2] #Noble Women
alive3=cur_house[1][2][1] #Small Men
alive4=cur_house[1][2][2] #Small Women
alive1.pop(0)
alive2.pop(0)
alive3.pop(0)
alive4.pop(0)
dead1=cur_house[0][1][1]
dead2=cur_house[0][1][2]
dead3=cur_house[0][2][1]
dea... | identifier_body | |
main.rs | , table, tag};
use options_clap::get_options_clap;
use options::{OptimMethod, TerminatingOutput};
use fatigue::dadn::DaDn;
use fatigue::COMMENT;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use log::error;
use std::io::Write;
mod list;
mod optimise;
mod sweep;
mod factors;
mod options;
mod options_cl... | {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors),
OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options, &mut factors),
OptimMethod::All => {
... | identifier_body | |
main.rs | AC_PI_2;
use std::process;
use std::collections::BTreeSet;
use fatigue::{beta, cycle, dadn, fracto, grow, io, material, table, tag};
use options_clap::get_options_clap;
use options::{OptimMethod, TerminatingOutput};
use fatigue::dadn::DaDn;
use fatigue::COMMENT;
use std::error::Error;
use std::fs::File;
use std::path::... | OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options, &mut factors),
OptimMethod::All => {
sweep::sweep(options, &mut factors);
| fn optimise_error(options: &options::EasiOptions, mut factors: &mut [f64]) {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors), | random_line_split |
main.rs | io, material, table, tag};
use options_clap::get_options_clap;
use options::{OptimMethod, TerminatingOutput};
use fatigue::dadn::DaDn;
use fatigue::COMMENT;
use std::error::Error;
use std::fs::File;
use std::path::Path;
use log::error;
use std::io::Write;
mod list;
mod optimise;
mod sweep;
mod factors;
mod options;
m... | {
sweep::sweep(options, &mut factors);
optimise::nelder_match_crack(options, &mut factors);
optimise_gsl::gsl_match_crack(options, &mut factors)
} | conditional_block | |
main.rs | _PI_2;
use std::process;
use std::collections::BTreeSet;
use fatigue::{beta, cycle, dadn, fracto, grow, io, material, table, tag};
use options_clap::get_options_clap;
use options::{OptimMethod, TerminatingOutput};
use fatigue::dadn::DaDn;
use fatigue::COMMENT;
use std::error::Error;
use std::fs::File;
use std::path::Pa... | (options: &options::EasiOptions, mut factors: &mut [f64]) {
match options.optimise.method {
OptimMethod::Sweep => sweep::sweep(options, &mut factors),
OptimMethod::Nelder => optimise::nelder_match_crack(&options, &mut factors),
OptimMethod::Levenberg => optimise_gsl::gsl_match_crack(&options... | optimise_error | identifier_name |
player.go | rematchOffer"`
AcceptRematch bool `json:"acceptRematch"`
FinishRoom bool `json:"finishRoom"`
userId string
}
// readPump pumps messages from the websocket connection to the room's hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most o... | serveGame | identifier_name | |
player.go | chan bool
oppAcceptedDraw chan bool
oppResigned chan bool
rematchOffer chan bool
oppAcceptedRematch chan bool
oppReady chan bool
oppDisconnected chan bool
oppGone chan bool
oppReconnected chan bool
cleanup func()
switchColors func()
color string
game... | w, err := p.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(move)
if err := w.Close(); err != nil {
return
}
case msg, ok := <-p.sendChat: // Chat msg
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The hub closed the channel.
p.conn.Writ... | {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
p.conn.Close()
}()
for {
select {
case <-p.disconnect:
// Finish this goroutine to not to send messages anymore
return
case move, ok := <-p.sendMove: // Opponent moved a piece
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
... | identifier_body |
player.go | chan bool
oppAcceptedDraw chan bool
oppResigned chan bool
rematchOffer chan bool
oppAcceptedRematch chan bool
oppReady chan bool
oppDisconnected chan bool
oppGone chan bool
oppReconnected chan bool
cleanup func()
switchColors func()
color string
game... |
w, err := p.conn.NextWriter(websocket.TextMessage)
if err != nil {
log.Println("Could not make next writer:", err)
return
}
w.Write(msgB)
// Add queued chat messages to the current websocket message.
n := len(p.sendChat)
for i := 0; i < n; i++ {
msg = <-p.sendChat
if (msg.userId ... | {
log.Println("Could not marshal data:", err)
break
} | conditional_block |
player.go | {
defer func() {
if p.room != nil {
p.room.disconnect<- p
}
p.sendMove = nil
p.conn.Close()
}()
p.conn.SetReadLimit(maxMessageSize)
p.conn.SetReadDeadline(time.Now().Add(pongWait))
p.conn.SetPongHandler(func(string) error { p.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, msg... | cleanup: cleanup, | random_line_split | |
plugin.go | 1beta1.AddToScheme(scheme)
kubeletconfigv1.AddToScheme(scheme)
}
// RegisterCredentialProviderPlugins is called from kubelet to register external credential provider
// plugins according to the CredentialProviderConfig config file.
func RegisterCredentialProviderPlugins(pluginConfigFile, pluginBinDir string) error {
... |
// isImageAllowed returns true if the image matches against the list of allowed matches by the plugin.
func (p *pluginProvider) isImageAllowed(image string) bool {
for _, matchImage := range p.matchImages {
if matched, _ := credentialprovider.URLsMatchStr(matchImage, image); matched {
return true
}
}
retur... | {
return true
} | identifier_body |
plugin.go | v1beta1.AddToScheme(scheme)
kubeletconfigv1.AddToScheme(scheme)
}
// RegisterCredentialProviderPlugins is called from kubelet to register external credential provider
// plugins according to the CredentialProviderConfig config file.
func RegisterCredentialProviderPlugins(pluginConfigFile, pluginBinDir string) error {... | if !ok {
klog.Errorf("Invalid response type returned by external credential provider")
return credentialprovider.DockerConfig{}
}
var cacheKey string
switch cacheKeyType := response.CacheKeyType; cacheKeyType {
case credentialproviderapi.ImagePluginCacheKeyType:
cacheKey = image
case credentialproviderapi.... | klog.Errorf("Failed getting credential from external registry credential provider: %v", err)
return credentialprovider.DockerConfig{}
}
response, ok := res.(*credentialproviderapi.CredentialProviderResponse) | random_line_split |
plugin.go | v1beta1.AddToScheme(scheme)
kubeletconfigv1.AddToScheme(scheme)
}
// RegisterCredentialProviderPlugins is called from kubelet to register external credential provider
// plugins according to the CredentialProviderConfig config file.
func RegisterCredentialProviderPlugins(pluginConfigFile, pluginBinDir string) error {... | (pluginBinDir string, provider kubeletconfig.CredentialProvider) (*pluginProvider, error) {
mediaType := "application/json"
info, ok := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), mediaType)
if !ok {
return nil, fmt.Errorf("unsupported media type %q", mediaType)
}
gv, ok := apiVersions[prov... | newPluginProvider | identifier_name |
plugin.go | 1beta1.AddToScheme(scheme)
kubeletconfigv1.AddToScheme(scheme)
}
// RegisterCredentialProviderPlugins is called from kubelet to register external credential provider
// plugins according to the CredentialProviderConfig config file.
func RegisterCredentialProviderPlugins(pluginConfigFile, pluginBinDir string) error {
... |
gv, ok := apiVersions[provider.APIVersion]
if !ok {
return nil, fmt.Errorf("invalid apiVersion: %q", provider.APIVersion)
}
clock := clock.RealClock{}
return &pluginProvider{
clock: clock,
matchImages: provider.MatchImages,
cache: cache.NewExpirationStore(cacheKey... | {
return nil, fmt.Errorf("unsupported media type %q", mediaType)
} | conditional_block |
Article.js | () {
var [ claps, setClaps] = React.useState(0);
const follows = [
{
image:
"https://upload.wikimedia.org/wikipedia/commons/a/a7/20180602_FIFA_Friendly_Match_Austria_vs._Germany_Mesut_%C3%96zil_850_0704.jpg",
nama: "Amin Subagiyo",
comment:
"Lorem ipsum dolor sit amet, consec... | Article | identifier_name | |
Article.js | 1576214873",
nama: "King Salman",
comment:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in... | Lying by Ryan Holiday / The Brass Check by Upton Sinclair I strongly
recommend that you take the time in 2018 to read these books. In light
of this year, you owe it to yourself to study and better understand
how our media system works. In The Filter Bubble, Eli Pariser warns of
... | also knew how to tell a story and create a collective cause. He could
work within the system but knew how to shake it up and generate
attention. This book is a classic and woefully underrated. Whatever
you set out to do in 2018, this book can provide you with strategic
... | random_line_split |
Article.js |
const [spacing, setSpacing] = React.useState(2);
const classes = useStyles();
const handleChange = event => {
setSpacing(Number(event.target.value));
};
return (
<div className="post">
<HomeBar />
<div>
<br></br>
<br></br>
<br></br>
<img src="https://mi... | {
var [ claps, setClaps] = React.useState(0);
const follows = [
{
image:
"https://upload.wikimedia.org/wikipedia/commons/a/a7/20180602_FIFA_Friendly_Match_Austria_vs._Germany_Mesut_%C3%96zil_850_0704.jpg",
nama: "Amin Subagiyo",
comment:
"Lorem ipsum dolor sit amet, consectet... | identifier_body | |
__init__.py | ,
'_setCustomVar': dict((i, None) for i in range(1, 6)),
'_setDomainName': False,
'_setAllowLinker': False,
'_addTrans': [],
'_addItem': [],
'_trackTrans': False,
'_trackEvent': [],
}
def setAccount(self, account_id):
... |
if self.data_struct['_track | for i in self.data_struct[category]:
if single_push:
single_pushes.append(i)
else:
script.append(u"""_gaq.push(%s);""" % i) | random_line_split |
__init__.py | ,
'_setCustomVar': dict((i, None) for i in range(1, 6)),
'_setDomainName': False,
'_setAllowLinker': False,
'_addTrans': [],
'_addItem': [],
'_trackTrans': False,
'_trackEvent': [],
}
def setAccount(self, account_id):
... | single_pushes.append(u"""['_setDomainName', '%s']""" % self.data_struct['_setDomainName'])
else:
script.append(u"""_gaq.push(['_setDomainName', '%s']);""" % self.data_struct['_setDomainName'])
# _setAllowLinker
if self.data_struct['_setAllowLinker']:
... | if single_push:
script.append(u"""_gaq.push(""")
# according to GA docs, the order to submit via javascript is:
# # _setAccount
# # _setDomainName
# # _setAllowLinker
# #
# # cross domain tracking reference
# # http://code.google.com/apis/analytics/do... | identifier_body |
__init__.py | , 6)),
'_setDomainName': False,
'_setAllowLinker': False,
'_addTrans': [],
'_addItem': [],
'_trackTrans': False,
'_trackEvent': [],
}
def setAccount(self, account_id):
"""This should really never be called, best to setup du... | single_pushes.append(u"""['_trackTrans']""") | conditional_block | |
__init__.py | (text=''):
text = str(text)
return text.replace("\'", "\\'")
class GaqHub(object):
data_struct = None
def __init__(self, account_id, single_push=False):
"""Sets up self.data_struct dict which we use for storage.
You'd probably have something like this in your base controller:
... | escape_text | identifier_name | |
aio.rs | .complete.send(Ok((retbuf, None))).expect("Could not send AioSession response");
entry.complete.send(Ok((retbuf, None)));
}
Err(e) => panic!("pread error {:?}", e),
}
... |
// let reads = (0..5).map(|_| {
// println!("foo"); | random_line_split | |
aio.rs | Ok(_) => (),
Err(e) => panic!("get_evfd_stream failed: {}", e),
};
let evfd = ctx.evfd.as_ref().unwrap().clone();
// Add the eventfd to the file descriptors we are
// interested in. This will use epoll under the hood.
let sourc... | {
curr_polls: u64,
curr_preads: u64,
curr_pwrites: u64,
prev_polls: u64,
prev_preads: u64,
prev_pwrites: u64,
}
impl Future for AioThread {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
trace!(
"============ AioThread... | AioStats | identifier_name |
workflow.py | gold standard for crossvalidation, and then remove the new gold standard from the priors
"""
utils.Debug.vprint("Resampling prior {pr} and gold standard {gs}".format(pr=self.priors_data.shape,
gs=self.gold_standard.shape)... | the preprocessing/postprocessing workflow
"""
return create_inferelator_workflow(regression=regression, workflow=workflow)() | random_line_split | |
workflow.py | 1] == 1
self.tf_names = tfs.values.flatten().tolist()
def read_metadata(self, file=None):
"""
Read metadata file into meta_data or make fake metadata
"""
if file is None:
file = self.meta_data_file
try:
self.meta_data = self.input_dataframe(f... | workflow_class = workflow | conditional_block | |
workflow.py | _AXIS
shuffle_prior_axis = None
# Computed data structures [G: Genes, K: Predictors, N: Conditions
expression_matrix = None # expression_matrix dataframe [G x N]
tf_names = None # tf_names list [k,]
meta_data = None # meta data dataframe [G x ?]
priors_data = None # priors data dataframe [G... | (expression_matrix):
"""
Create a meta_data dataframe from basic defaults
"""
metadata_rows = expression_matrix.columns.tolist()
metadata_defaults = {"isTs": "FALSE", "is1stLast": "e", "prevCol": "NA", "del.t": "NA", "condName": None}
data = {}
for key in metadata... | create_default_meta_data | identifier_name |
workflow.py | _and_priors()
def read_expression(self, file=None):
"""
Read expression matrix file into expression_matrix
"""
if file is None:
file = self.expression_matrix_file
self.expression_matrix = self.input_dataframe(file)
def read_tfs(self, file=None):
"""
... | """
This is the factory method to create workflow ckasses that combine preprocessing and postprocessing (from workflow)
with a regression method (from regression)
:param regression: RegressionWorkflow subclass
A class object which implements the run_regression and run_bootstrap methods for a specif... | identifier_body | |
handshake.rs | /// If the client timestamp has been seen before, or is not strictly increasing,
/// we can abort the handshake early and avoid heavy Diffie-Hellman computations.
/// If the client timestamp is valid, we store it.
#[derive(Default)]
pub struct AntiReplayTimestamps(HashMap<x25519::PublicKey, u64>);
impl AntiReplayTimes... | their_public_key
),
));
}
}
// if on a mutually authenticated network
if let Some(anti_replay_timestamps) = &anti_replay_timestamps {
// check that the payload received as the client timestamp (in seconds)
... | // TODO: security logging (mimoo)
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"noise: client connecting to us with an unknown public key: {}", | random_line_split |
handshake.rs | If the client timestamp has been seen before, or is not strictly increasing,
/// we can abort the handshake early and avoid heavy Diffie-Hellman computations.
/// If the client timestamp is valid, we store it.
#[derive(Default)]
pub struct AntiReplayTimestamps(HashMap<x25519::PublicKey, u64>);
impl AntiReplayTimestam... |
};
self.dial(socket, anti_replay_timestamps.is_some(), remote_public_key)
.await?
}
ConnectionOrigin::Inbound => {
self.accept(socket, anti_replay_timestamps, trusted_peers)
.await?
}
};
... | {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"noise: SHOULD NOT HAPPEN: missing server's key when dialing",
));
} | conditional_block |
handshake.rs | /// If the client timestamp has been seen before, or is not strictly increasing,
/// we can abort the handshake early and avoid heavy Diffie-Hellman computations.
/// If the client timestamp is valid, we store it.
#[derive(Default)]
pub struct AntiReplayTimestamps(HashMap<x25519::PublicKey, u64>);
impl AntiReplayTimes... | (&self, pubkey: x25519::PublicKey, timestamp: u64) -> bool {
if let Some(last_timestamp) = self.0.get(&pubkey) {
×tamp <= last_timestamp
} else {
false
}
}
/// Stores the timestamp
pub fn store_timestamp(&mut self, pubkey: x25519::PublicKey, timestamp: u... | is_replay | identifier_name |
acpi.rs | dp20.xsdt_addr.try_into()?) }
}
}
/// System Description Table types.
enum SdtType {
Xsdt,
Madt,
}
impl SdtType {
/// Returns the signature of the SDT.
fn signature(&self) -> &[u8] {
match self {
SdtType::Xsdt => b"XSDT",
SdtType::Madt => b"APIC",
}
}
}
... | flags | identifier_name | |
acpi.rs | the Root System Description Pointer (RSDP) of ACPI 2.0+.
#[derive(Debug)]
pub struct Rsdp20 {
rsdp20: AcpiRsdp20,
}
impl Rsdp20 {
/// Creates a new `Rsdp20` from a given pointer.
///
/// # Errors
///
/// This function returns error if the pointer does not point to a valid
/// RSDP 2.0+ str... |
}
// If we reach this point, the table could not be found.
Err(Error::NotFound)
}
}
/// Size of the SDT header.
const ACPI_MADT_FIELDS_SIZE: usize = core::mem::size_of::<AcpiMadtFields>();
/// Maximum number of entries in the MADT.
const ACPI_MADT_ENTRIES_LEN: usize = 256;
/// Extra fie... | {
return unsafe { Madt::new(entry.try_into()?) };
} | conditional_block |
acpi.rs | .
pub unsafe fn new(rsdp20_ptr: Ptr) -> Result<Self, Error> {
let rsdp20_ptr = rsdp20_ptr.0 as *const AcpiRsdp20;
let rsdp20 = core::ptr::read_unaligned(rsdp20_ptr);
// Check table's signature.
if rsdp20.signature != ACPI_RSDP_SIGNATURE {
return Err(Error::InvalidSignatu... | {
// Parse header.
let hdr = AcpiSdtHeader::new(madt_ptr, SdtType::Madt)?;
// Parse fields.
let fields = core::ptr::read_unaligned(
(madt_ptr.0 as *const u8).add(ACPI_SDT_SIZE)
as *const AcpiMadtFields,
);
// Parse entries.
let mut nu... | identifier_body | |
acpi.rs | Represents the Root System Description Pointer (RSDP) of ACPI 2.0+.
#[derive(Debug)]
pub struct Rsdp20 {
rsdp20: AcpiRsdp20,
}
impl Rsdp20 {
/// Creates a new `Rsdp20` from a given pointer.
///
/// # Errors
///
/// This function returns error if the pointer does not point to a valid
/// RS... | Xsdt,
Madt,
}
impl SdtType {
/// Returns the signature of the SDT.
fn signature(&self) -> &[u8] {
match self {
SdtType::Xsdt => b"XSDT",
SdtType::Madt => b"APIC",
}
}
}
/// System Description Table header of the ACPI specification. It is common to
/// all Sy... | random_line_split | |
snapshot.rs | are devices, rather than virtual
// files. As such, we don't check those for size.
#[must_use]
fn is_kcore_ok() -> bool {
metadata(Path::new("/proc/kcore"))
.map(|x| x.len() > 0x2000)
.unwrap_or(false)
&& can_open(Path::new("/proc/kcore"))
}
// try to perform an action, either returning o... | mod tests {
use super::*;
#[test]
fn translate_ranges() { | random_line_split | |
snapshot.rs | _>) -> std::fmt::Result {
format_error(self, f)
}
}
pub(crate) type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, ValueEnum)]
pub enum Source {
/// Provides a read-only view of physical memory. Access to memory using
/// this device must be paged aligned and read one page at a... |
// try to perform an action, either returning on success, or having the result
// of the error in an indented string.
//
// This special cases `DiskUsageEstimateExceeded` errors, as we want this to
// fail fast and bail out of the `try_method` caller.
macro_rules! try_method {
($func:expr) => {{
match $fu... | {
metadata(Path::new("/proc/kcore"))
.map(|x| x.len() > 0x2000)
.unwrap_or(false)
&& can_open(Path::new("/proc/kcore"))
} | identifier_body |
snapshot.rs | , are devices, rather than virtual
// files. As such, we don't check those for size.
#[must_use]
fn is_kcore_ok() -> bool {
metadata(Path::new("/proc/kcore"))
.map(|x| x.len() > 0x2000)
.unwrap_or(false)
&& can_open(Path::new("/proc/kcore"))
}
// try to perform an action, either returning ... | translate_ranges | identifier_name | |
snapshot.rs | <'_>) -> std::fmt::Result {
format_error(self, f)
}
}
pub(crate) type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, ValueEnum)]
pub enum Source {
/// Provides a read-only view of physical memory. Access to memory using
/// this device must be paged aligned and read one page at... | else if can_open(Path::new("/dev/crash")) {
self.create_source(&Source::DevCrash)?;
} else if can_open(Path::new("/dev/mem")) {
self.create_source(&Source::DevMem)?;
} else {
return Err(Error::UnableToCreateSnapshot(
"no source... | {
self.create_source(&Source::ProcKcore)?;
} | conditional_block |
real_comparison.py |
_last_rain=None
_last_rain_pos=-1
_lr_pos_in_file=-1
_lr_curfile=0
_rainvar="RAINNC"
_testvar=None
# _var_names=["QVAPOR",[op.add,"QCLOUD","QICE"],"RAINNC",[op.add,"T2",300],"U","V","W"]
_var_names=["QVAPOR",[op.add,"QCLOUD","QICE"],[op.add,"QRAIN","QSNOW"],[op.add,"T2",300],"... |
def __next__(self):
self.curpos+=1
output_data=Bunch()
filename=self.files[self._curfile]
for v in self._var_names:
if type(v)==str:
curdata=self.load_data(v)
curvarname=v
elif type(v)==l... | return self | identifier_body |
real_comparison.py |
_last_rain=None
_last_rain_pos=-1
_lr_pos_in_file=-1
_lr_curfile=0
_rainvar="RAINNC"
_testvar=None
# _var_names=["QVAPOR",[op.add,"QCLOUD","QICE"],"RAINNC",[op.add,"T2",300],"U","V","W"]
_var_names=["QVAPOR",[op.add,"QCLOUD","QICE"],[op.add,"QRAIN","QSNOW"],[op.add,"T2",300],"... | (self):
return self
def __next__(self):
self.curpos+=1
output_data=Bunch()
filename=self.files[self._curfile]
for v in self._var_names:
if type(v)==str:
curdata=self.load_data(v)
curvarname=v
... | __iter__ | identifier_name |
real_comparison.py | "]
x=slice(0,None) #by default take all data in the file in x,y, and z
y=slice(0,None)
# z=slice(0,None)
z=slice(0,10)
# zslices=dict(qv=slice(0,10),qc=slice(0,10),t=slice(1),)
# yslices=dict()
# yslices.setdefault(y)
llh
def __init__(self, filenames,start_pos=0,datatype="WRF")... | random_line_split | ||
real_comparison.py |
_last_rain=None
_last_rain_pos=-1
_lr_pos_in_file=-1
_lr_curfile=0
_rainvar="RAINNC"
_testvar=None
# _var_names=["QVAPOR",[op.add,"QCLOUD","QICE"],"RAINNC",[op.add,"T2",300],"U","V","W"]
_var_names=["QVAPOR",[op.add,"QCLOUD","QICE"],[op.add,"QRAIN","QSNOW"],[op.add,"T2",300],"... |
# Get/Set the position in the timeseries, while properly updating the filenumber and position in file
@property
def curpos(self):
return self._curpos
@curpos.setter
def curpos(self,pos):
self._curpos=pos
self._pos_in_file= int(self._curpos) % int(self.times_per_fi... | return data | conditional_block |
PanoImageRenderer.js | this._image && this._imageIsReady &&
(!this._isVideo || this._image.readyState >= 2 /* HAVE_CURRENT_DATA */);
}
bindTexture() {
return new Promise((res, rej) => {
if (!this._contentLoader) {
rej("ImageLoader is not initialized");
return;
}
this._contentLoader.get()
.then(() => {
this.... | ) &&
this.fie | conditional_block | |
PanoImageRenderer.js | ,
glMatrix.toRadian(this.fieldOfView),
this.canvas.width / this.canvas.height,
0.1,
100);
this.context.viewport(0, 0, this.context.drawingBufferWidth, this.context.drawingBufferHeight);
}
_initWebGL() {
let gl;
// TODO: Following code does need to be executed only if width/height, cubicStrip prop... | random_line_split | ||
PanoImageRenderer.js | alConfig, renderingContextAttributes
) {
// Super constructor
super();
this.sphericalConfig = sphericalConfig;
this.fieldOfView = sphericalConfig.fieldOfView;
this.width = width;
this.height = height;
this._lastQuaternion = null;
this._lastYaw = null;
this._lastPitch = null;
this._lastFieldOfVie... | eo, spheric | identifier_name | |
PanoImageRenderer.js | 한다.
// image is reference for content in contentLoader, so it may be not valid if contentLoader is destroyed.
this._image = this._contentLoader.getElement();
return this._contentLoader.get()
.then(this._onContentLoad, this._onContentError)
.catch(e => setTimeout(() => { throw e; }));// Prevent exceptions f... | this._renderer = new SphereRenderer(this.sphericalConfig.stereoFormat);
break;
default:
this._renderer = new SphereRenderer(STEREO_FORMAT.NONE);
break;
}
this._renderer.on(Renderer.EVENTS.ERROR, e => {
this.trigger(EVENTS.ERROR, {
type: ERROR_TYPE.RENDERER_ERROR,
message: e.message
... | }
this._imageType = imageType;
this._isCubeMap = imageType === ImageType.CUBEMAP;
if (this._renderer) {
this._renderer.off();
}
switch (imageType) {
case ImageType.CUBEMAP:
this._renderer = new CubeRenderer();
break;
case ImageType.CUBESTRIP:
this._renderer = new CubeStripRenderer();... | identifier_body |
row.rs | }
pub fn read(io: &mut dyn Read) -> Result<BoxRow> {
let mut header = [0; ROW_LAYOUT.size()];
io.read_exact(&mut header).context("reading header")?;
let header_crc32c = (&header[0..4]).read_u32::<LittleEndian>().unwrap();
let header_crc32c_calculated = crc32c(&header[4..]);
... | header_crc32c, header_crc32c_calculated);
}
let len = (&header[ROW_LAYOUT.size() - 8..]).read_u32::<LittleEndian>().unwrap();
let mut row = BoxRow { ptr: Self::alloc(len) };
row.as_bytes_mut().copy_from_slice(&header);
debug_assert!(row.len == len);
io... | random_line_split | |
row.rs | }
pub fn read(io: &mut dyn Read) -> Result<BoxRow> {
let mut header = [0; ROW_LAYOUT.size()];
io.read_exact(&mut header).context("reading header")?;
let header_crc32c = (&header[0..4]).read_u32::<LittleEndian>().unwrap();
let header_crc32c_calculated = crc32c(&header[4..]);
... | (&self) -> &[u8] {
&self.0 | unparsed | identifier_name |
main.go | .upstream)
if err != nil {
glog.Fatalf("Failed to build parse upstream URL: %v", err)
}
spdyMetrics := monitoring.NewSPDYMetrics()
spdyProxy := spdy.New(kcfg, upstreamURL, spdyMetrics)
kubeClient, err := kubernetes.NewForConfig(kcfg)
if err != nil {
glog.Fatalf("Failed to instantiate Kubernetes client: %v",... | newReverseProxy | identifier_name | |
main.go |
func main() {
cfg := config{
auth: proxy.Config{
Authentication: &authn.AuthnConfig{
X509: &authn.X509Config{},
Header: &authn.AuthnHeaderConfig{},
OIDC: &authn.OIDCConfig{},
},
Authorization: &authz.Config{},
},
cors: corsConfig{},
}
flagset := pflag.NewFlagSet(os.Args[0], pflag.Ex... | {
if version, ok := versions[versionName]; ok {
return version, nil
}
return 0, fmt.Errorf("unknown tls version %q", versionName)
} | identifier_body | |
main.go | should listen on.")
flagset.StringVar(&cfg.secureListenAddress, "secure-listen-address", "", "The address the kube-rbac-proxy HTTPs server should listen on.")
flagset.StringVar(&cfg.upstream, "upstream", "", "The upstream URL to proxy to once requests have successfully been authenticated and authorized.")
flagset.B... |
cert, err := tls.X509KeyPair(certBytes, keyBytes)
if err != nil {
glog.Fatalf("Failed to load generated self signed cert and key: %v", err)
}
version, err := tlsVersion(cfg.tls.minVersion)
if err != nil {
glog.Fatalf("TLS version invalid: %v", err)
}
cipherSuiteIDs, err := cliflag.TLSCip... | {
glog.Fatalf("Failed to generate self signed cert and key: %v", err)
} | conditional_block |
main.go | server should listen on.")
flagset.StringVar(&cfg.secureListenAddress, "secure-listen-address", "", "The address the kube-rbac-proxy HTTPs server should listen on.")
flagset.StringVar(&cfg.upstream, "upstream", "", "The upstream URL to proxy to once requests have successfully been authenticated and authorized.")
fl... | glog.Fatalf("Failed to build parse upstream URL: %v", err)
}
spdyMetrics := monitoring.NewSPDYMetrics()
spdyProxy := spdy.New(kcfg, upstreamURL, spdyMetrics)
kubeClient, err := kubernetes.NewForConfig(kcfg)
if err != nil {
glog.Fatalf("Failed to instantiate Kubernetes client: %v", err)
}
var oidcAuthentic... | if err != nil { | random_line_split |
main.go | (w, r, url, http.StatusFound)
}
// oauth2callback is the handler to which Google's OAuth service redirects the
// user after they have granted the appropriate permissions.
func oauth2callbackHandler(w http.ResponseWriter, r *http.Request) {
// Create an oauth transport with a urlfetch.Transport embedded inside.
t :=... | return nil, err
}
return imageData, nil
}
func notifyOpenGlass(conn *picarus.Conn, svc *mirror.Service, trans *oauth.Transport, t *mirror.TimelineItem, userId string) {
if !hasFlagSingle(userId, "flags", "user_openglass") {
LogPrintf("openglass: flag user_openglass")
return
}
var err error
flags, err := g... | {
a, err := svc.Timeline.Attachments.Get(t.Id, t.Attachments[0].Id).Do()
if err != nil {
LogPrintf("getattachment: metadata")
return nil, err
}
req, err := http.NewRequest("GET", a.ContentUrl, nil)
if err != nil {
LogPrintf("getattachment: http")
return nil, err
}
resp, err := trans.RoundTrip(req)
if er... | identifier_body |
main.go | (w, r, url, http.StatusFound)
}
// oauth2callback is the handler to which Google's OAuth service redirects the
// user after they have granted the appropriate permissions.
func oauth2callbackHandler(w http.ResponseWriter, r *http.Request) {
// Create an oauth transport with a urlfetch.Transport embedded inside.
t :=... |
resp, err := trans.RoundTrip(req)
if err != nil {
LogPrintf("getattachment: content")
return nil, err
}
defer resp.Body.Close()
imageData, err := ioutil.ReadAll(resp.Body)
if err != nil {
LogPrintf("getattachment: body")
return nil, err
}
return imageData, nil
}
func notifyOpenGlass(conn *picarus.Conn... | {
LogPrintf("getattachment: http")
return nil, err
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.