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 |
|---|---|---|---|---|
Bills.py | import time
from Facturacion.Objects.Bill import Bill, ItemLine
from Facturacion.Controllers.ControlDB import BillsController
from Facturacion.Collections.Vendors import Vendors
from Facturacion.Collections.Clients import Clients
from Facturacion.Collections.Items import Items
class Bills:
facturas = {}
contr... |
@classmethod
def load_items(cls, cod_factura):
factura = cls.facturas[cod_factura]
for item in cls.controller.get_items(cod_factura):
factura.add_item(ItemLine(factura, Items.articulos[item[0]], item[1]))
@classmethod
def get_max_code(cls):
if not cls.facturas:
... | for bill in cls.controller.get_bills():
cls.facturas[bill[0]] = Bill(bill[0], Vendors.vendedores[bill[1]], Clients.clientes[bill[2]], bill[3])
cls.load_items(bill[0]) | identifier_body |
smartbanner.js | import OptionParser from './optionparser.js';
import Detector from './detector.js';
import Bakery from './bakery.js';
const DEFAULT_PLATFORMS = 'android,ios';
const DEFAULT_CLOSE_LABEL = 'Close';
let datas = {
originalTop: 'data-smartbanner-original-top',
originalMarginTop: 'data-smartbanner-original-margin-top'
... |
function handleClickout(event, self) {
self.clickout();
}
function handleJQueryMobilePageLoad(event) {
if (!this.positioningDisabled) {
setContentPosition(event.data.height);
}
}
function addEventListeners(self) {
let closeIcon = document.querySelector('.js_smartbanner__exit');
closeIcon.addEventListe... | {
self.exit();
event.preventDefault();
} | identifier_body |
smartbanner.js | import OptionParser from './optionparser.js';
import Detector from './detector.js';
import Bakery from './bakery.js';
const DEFAULT_PLATFORMS = 'android,ios';
const DEFAULT_CLOSE_LABEL = 'Close';
let datas = {
originalTop: 'data-smartbanner-original-top',
originalMarginTop: 'data-smartbanner-original-margin-top'
... | }
let margin = parseFloat(getComputedStyle(wrapper).marginTop);
wrapper.setAttribute(datas.originalMarginTop, isNaN(margin) ? 0 : margin);
wrapper.style.marginTop = value + 'px';
}
}
}
function restoreContentPosition() {
let wrappers = Detector.wrapperElement();
for (let i = 0, l = wr... | wrapper.setAttribute(datas.originalTop, isNaN(top) ? 0 : top);
wrapper.style.top = value + 'px';
} else {
if (wrapper.getAttribute(datas.originalMarginTop)) {
continue; | random_line_split |
smartbanner.js | import OptionParser from './optionparser.js';
import Detector from './detector.js';
import Bakery from './bakery.js';
const DEFAULT_PLATFORMS = 'android,ios';
const DEFAULT_CLOSE_LABEL = 'Close';
let datas = {
originalTop: 'data-smartbanner-original-top',
originalMarginTop: 'data-smartbanner-original-margin-top'
... | () {
if (this.platform === 'android') {
return this.options.buttonUrlGoogle;
} else if (this.platform === 'ios') {
return this.options.buttonUrlApple;
}
return '#';
}
get closeLabel() {
return this.options.closeLabel !== undefined ? this.options.closeLabel : DEFAULT_CLOSE_LABEL;
}... | buttonUrl | identifier_name |
smartbanner.js | import OptionParser from './optionparser.js';
import Detector from './detector.js';
import Bakery from './bakery.js';
const DEFAULT_PLATFORMS = 'android,ios';
const DEFAULT_CLOSE_LABEL = 'Close';
let datas = {
originalTop: 'data-smartbanner-original-top',
originalMarginTop: 'data-smartbanner-original-margin-top'
... |
return Detector.userAgentMatchesRegex(this.options.includeUserAgentRegex);
}
get hideTtl() {
return this.options.hideTtl ? parseInt(this.options.hideTtl) : false;
}
get hidePath() {
return this.options.hidePath ? this.options.hidePath : '/';
}
publish() {
if (Object.keys(this.options).le... | {
return false;
} | conditional_block |
233_clever.py | """
Project Euler - Problem 233
Circle passing through (0,0),(N,0),(0,N),(N,N)
this is a square - so the diameter of the circle
is N*Sqrt(2), and its centre is (N/2,N/2)
Circle equation is
(X-Xc)^2+(Y-Yc)^2=N^2/2 or
(x-N/2)^2 + (y-N/2)^2 = N^2/2
for a given N, the x domain Dx is
lower bound N/2 - N*sqrt(2)/... |
#output:
# f(10000000)=60 (took 10.702s) | random_line_split | |
233_clever.py | """
Project Euler - Problem 233
Circle passing through (0,0),(N,0),(0,N),(N,N)
this is a square - so the diameter of the circle
is N*Sqrt(2), and its centre is (N/2,N/2)
Circle equation is
(X-Xc)^2+(Y-Yc)^2=N^2/2 or
(x-N/2)^2 + (y-N/2)^2 = N^2/2
for a given N, the x domain Dx is
lower bound N/2 - N*sqrt(2)/... |
x=int(x)
print "next x is %d, with tol %f after %d iters" % (x, h0, iters)
if ct>420:
print "\ncanceled"
break
x+=1
print "\nf(%d)=%d (took %.3fs)" % (N, ct, (time()-st))
#output:
# f(10000000)=60 (took 10.702s)
| x+=delta
h1=a*x+b-1.0-N_over_2-sqrt(N_sqrd_over_2-(x-N_over_2)**2)
if h0*h1<0: delta*=-0.5
h0=h1
iters+=1 | conditional_block |
SqlAlchemyForm.tsx | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | type="text"
name="database_name"
data-test="database-name-input"
value={db?.database_name || ''}
placeholder={t('Name your database')}
onChange={onInputChange}
/>
</div>
<div className="helper">
{t('Pick a name to help you identify ... | <input | random_line_split |
index.js | 'use strict';
var redis = require('redis')
, xtend = require('xtend')
, hyperquest = require('hyperquest')
;
module.exports = FetchAndCache;
/**
* Creates a fetchncache instance.
*
* #### redis opts
*
* - **opts.redis.host** *{number=}* host at which redis is listening, defaults to `127.0.0.1`... | (opts) {
if (!(this instanceof FetchAndCache)) return new FetchAndCache(opts);
opts = opts || {};
var redisOpts = xtend({ port: 6379, host: '127.0.0.1' }, opts.redis)
, serviceOpts = xtend({ url: 'http://127.0.0.1' }, opts.service)
this._defaultExpire = opts.expire || 15 * 60 // 15min
this._serviceOpts ... | FetchAndCache | identifier_name |
index.js | 'use strict';
var redis = require('redis')
, xtend = require('xtend')
, hyperquest = require('hyperquest')
;
module.exports = FetchAndCache;
/**
* Creates a fetchncache instance.
*
* #### redis opts
*
* - **opts.redis.host** *{number=}* host at which redis is listening, defaults to `127.0.0.1`... | * @function
* @return {Object} fetchncache instance
*/
proto.clearCache = function () {
if (!this._client) throw new Error('fetchncache was stopped previously and cannot be cleared');
this._client.flushdb();
return this;
}
proto._get = function (uri, cb) {
var body = '';
var url = this._serviceOpts.url +... | * Clears the entire redis cache, so use with care.
* Mainly useful for testing or to ensure that all resources get refreshed.
*
* @name fetchncache::clearCache | random_line_split |
index.js | 'use strict';
var redis = require('redis')
, xtend = require('xtend')
, hyperquest = require('hyperquest')
;
module.exports = FetchAndCache;
/**
* Creates a fetchncache instance.
*
* #### redis opts
*
* - **opts.redis.host** *{number=}* host at which redis is listening, defaults to `127.0.0.1`... |
var proto = FetchAndCache.prototype;
/**
* Fetches the resource, probing the redis cache first and falling back to the service.
* If a transform function is provided (@see opts), that is applied to the result before returning or caching it.
* When fetched from the service it is added to the redis cached according... | {
if (!(this instanceof FetchAndCache)) return new FetchAndCache(opts);
opts = opts || {};
var redisOpts = xtend({ port: 6379, host: '127.0.0.1' }, opts.redis)
, serviceOpts = xtend({ url: 'http://127.0.0.1' }, opts.service)
this._defaultExpire = opts.expire || 15 * 60 // 15min
this._serviceOpts = ser... | identifier_body |
models.py | import arrow
from django.db import models
from common.models import Org, Profile
from django.utils.translation import ugettext_lazy as _
class Teams(models.Model):
|
@property
def created_on_arrow(self):
return arrow.get(self.created_on).humanize()
def get_users(self):
return ",".join(
[str(_id) for _id in list(self.users.values_list("id", flat=True))]
)
# return ','.join(list(self.users.values_list('id', flat=True)))
| name = models.CharField(max_length=100)
description = models.TextField()
users = models.ManyToManyField(Profile, related_name="user_teams")
created_on = models.DateTimeField(_("Created on"), auto_now_add=True)
created_by = models.ForeignKey(
Profile,
related_name="teams_created",
... | identifier_body |
models.py | import arrow
from django.db import models
from common.models import Org, Profile
from django.utils.translation import ugettext_lazy as _
class Teams(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
users = models.ManyToManyField(Profile, related_name="user_teams")
... | (self):
return arrow.get(self.created_on).humanize()
def get_users(self):
return ",".join(
[str(_id) for _id in list(self.users.values_list("id", flat=True))]
)
# return ','.join(list(self.users.values_list('id', flat=True)))
| created_on_arrow | identifier_name |
models.py | import arrow
from django.db import models
from common.models import Org, Profile
from django.utils.translation import ugettext_lazy as _
class Teams(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
users = models.ManyToManyField(Profile, related_name="user_teams")
... | return arrow.get(self.created_on).humanize()
def get_users(self):
return ",".join(
[str(_id) for _id in list(self.users.values_list("id", flat=True))]
)
# return ','.join(list(self.users.values_list('id', flat=True))) |
@property
def created_on_arrow(self): | random_line_split |
ZaResourceController.js | ZaZimbraAdmin.getInstance().getCurrentAppBar().enableButton(ZaOperation.SAVE, false);
}
}
ZaResourceController.prototype.show =
function(entry, openInNewTab, skipRefresh) {
this._setView(entry, openInNewTab, skipRefresh);
}
ZaResourceController.changeActionsStateMethod = function () {
var isToEnable = (this._vi... | ZaApp.getInstance().dialogs["newResourceWizard"].popup();
} catch (ex) {
this._handleException(ex, "ZaResourceController.prototype.newResource", null, false);
}
}
// new button was pressed
ZaResourceController.prototype.newButtonListener =
function(ev) {
if(this._view.isDirty()) {
//parameters for the confirm... |
ZaApp.getInstance().dialogs["newResourceWizard"].setObject(newResource); | random_line_split |
ZaResourceController.js | omainList[i])) {
showNewCalRes = true;
break;
}
}
}
this._popupOperations[ZaOperation.SAVE]=new ZaOperation(ZaOperation.SAVE,ZaMsg.TBB_Save, ZaMsg.ALTBB_Save_tt, "Save", "SaveDis", new AjxListener(this, this.saveButtonListener));
this._popupOperations[ZaOperation.CLOSE]=new ZaOperation(ZaOperatio... | {
this.popupErrorDialog(ZaMsg.FAILED_RENAME_ACCOUNT_1, ex);
} | conditional_block | |
main.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial ... | random_line_split | |
main.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... | () -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = ::std::env::args().collect();
if args.len() >= 2 {
match &args[1][..] {
"client" => return client::main().await,
"server" => return server::main().await,
_ => ()
}
}
println!("usag... | main | identifier_name |
main.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// 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, inc... | {
let args: Vec<String> = ::std::env::args().collect();
if args.len() >= 2 {
match &args[1][..] {
"client" => return client::main().await,
"server" => return server::main().await,
_ => ()
}
}
println!("usage: {} [client | server] ADDRESS", args[0]);
... | identifier_body | |
Lusher_Alexander_home_work_3_.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
def add(x, y):
a=1
while a>0:
a = x & y
b = x ^ y
x = b
y = a << 1
return b
def vowel_count(word):
vo |
if __name__ == '__main__':
# Assignment N 1
text="Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Donec rutrum congue leo eget malesuada."
list=text.split()
max_vowel_number=0
for i in ran... | wels_counter = 0
for letter in word:
if letter.isalpha():
if letter.upper() in 'AEIOUY':
vowels_counter += 1
return vowels_counter
| identifier_body |
Lusher_Alexander_home_work_3_.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
def add(x, y):
a=1
while a>0:
a = x & y
b = x ^ y
x = b
y = a << 1
return b
def vowel_count(word):
vowels_counter = 0
for letter in word:
if letter.isalpha():
if letter.upper() in 'AEIOUY':
vowels_co... | elif length==len(list[i]):
words.append(list[i])
print "maximum length=",length,"words are",words
# Assignment N 3
text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis lorem ut libero malesuada feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec rutrum congue leo e... | ngth=len(list[i])
words[:] = []
words.append(list[i])
| conditional_block |
Lusher_Alexander_home_work_3_.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
def add(x, y):
a=1
while a>0:
a = x & y
b = x ^ y
x = b
y = a << 1
return b
def vowel_count(word):
vowels_counter = 0
for letter in word:
if letter.isalpha():
if letter.upper() in 'AEIOUY':
vowels_co... |
list=text.split()
length=len(list[0])
words=[]
words.append(list[0])
for i in range(1,len(list)-1):
if length<len(list[i]):
length=len(list[i])
words[:] = []
words.append(list[i])
elif length==len(list[i]):
words.append(list[i])
print "maximum length=",length,"words are",words
# ... |
text="Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Donec rutrum congue leo eget malesuada."
| random_line_split |
Lusher_Alexander_home_work_3_.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
def ad | , y):
a=1
while a>0:
a = x & y
b = x ^ y
x = b
y = a << 1
return b
def vowel_count(word):
vowels_counter = 0
for letter in word:
if letter.isalpha():
if letter.upper() in 'AEIOUY':
vowels_counter += 1
return vowels_counter
if __name__ == '__main... | d(x | identifier_name |
extract_feature.py | from extract_feature_lib import *
from sys import argv
from dga_model_eval import *
from __init__ import *
def clear_cache(index, cache):
print "clear cache", index
for tmp in cache:
client[db_name][coll_name_list[index]+"_matrix"].insert(cache[tmp])
def | (index):
#cursor = client[db_name].domain.find({"_id":{"$in": ["emltrk.com", "weminemnc.com"]}})
cursor = client[db_name][coll_name_list[index]].find(timeout=False)
outlier = {"", "ntp.org", "isipp.com", "gccdn.net", "cdngc.net", "gstatic.com", "cloudfront.net"}
cache = {}
num = 1
print index
... | extract_domain_feature | identifier_name |
extract_feature.py | from extract_feature_lib import *
from sys import argv
from dga_model_eval import *
from __init__ import *
def clear_cache(index, cache):
print "clear cache", index
for tmp in cache:
client[db_name][coll_name_list[index]+"_matrix"].insert(cache[tmp])
def extract_domain_feature(index):
#cursor = ... | # client[db_name][coll_name_list[index]+"_matrix"].insert(tmp)
clear_cache(index, cache)
def main(index):
#index = int(raw_input())
if index < 4:
extract_domain_feature(index)
elif index < 8:
extract_ip_feature(index)
else:
for i in range(4, 8):
extrac... | model = init_dga()
cursor = client[db_name][coll_name_list[index]].find(timeout=False)
cache = {}
print index
for row in cursor:
if not ip_p.match(str(row["_id"])):
continue
number = len(row["ITEMS"])
min_ttl = min(row["TTLS"])
max_ttl = max(row["TTLS"])
... | identifier_body |
extract_feature.py | from extract_feature_lib import *
from sys import argv
from dga_model_eval import *
from __init__ import *
def clear_cache(index, cache):
print "clear cache", index
for tmp in cache:
client[db_name][coll_name_list[index]+"_matrix"].insert(cache[tmp])
def extract_domain_feature(index):
#cursor = ... |
this_db_name = pre_db_name
if not flag:
continue
num += 1
print "one more", num, row["_id"]
ip_count = len(row["ITEMS"])
min_ttl = min(row["TTLS"])
max_ttl = max(row["TTLS"])
lifetime = int(row["LAST_SEEN"... | flag = True
break | conditional_block |
extract_feature.py | from extract_feature_lib import *
from sys import argv
from dga_model_eval import *
from __init__ import *
def clear_cache(index, cache):
print "clear cache", index
for tmp in cache:
client[db_name][coll_name_list[index]+"_matrix"].insert(cache[tmp])
def extract_domain_feature(index):
#cursor = ... |
num = 1
print index
for row in cursor:
if get_tail(row["_id"]) in outlier:
continue
# if index == 0 and np.random.randint(1, 100) != 7:
# continue
if index == 0:
if np.random.randint(1, 50) != 7:
flag = False
this... | random_line_split | |
logging.js | jsio('import Class, bind, log');
var loggers = {}
var levels = exports.levels = {
DEBUG: 0,
LOG: 1,
INFO: 2,
WARN: 3,
ERROR: 4
};
var production = false;
exports.setProduction = function(prod) {
production = !!prod;
}
exports.getLogger = function(name) {
if (!(name in loggers)) |
return loggers[name];
}
exports.Logger = Class(function() {
this.init = function(name, level) {
if (!level) {
level = levels.LOG;
}
this.name = name;
this.level = level;
}
this.setLevel = function(level) {
this.level = level;
}
function make... | {
loggers[name] = new exports.Logger(name);
} | conditional_block |
logging.js | jsio('import Class, bind, log');
var loggers = {}
var levels = exports.levels = {
DEBUG: 0,
LOG: 1,
INFO: 2,
WARN: 3,
ERROR: 4
};
var production = false;
exports.setProduction = function(prod) {
production = !!prod;
}
exports.getLogger = function(name) {
if (!(name in loggers)) {
lo... | (level, type) {
return function() {
if (level < this.level || production) return;
log.apply(log, [type, this.name].concat(Array.prototype.slice.call(arguments, 0)));
}
}
this.debug = makeLogFunction(levels.DEBUG, "DEBUG");
this.log = makeLogFunction(levels.LOG, "LOG"... | makeLogFunction | identifier_name |
logging.js | jsio('import Class, bind, log');
var loggers = {}
var levels = exports.levels = {
DEBUG: 0,
LOG: 1,
INFO: 2,
WARN: 3,
ERROR: 4
};
var production = false;
exports.setProduction = function(prod) {
production = !!prod;
}
exports.getLogger = function(name) {
if (!(name in loggers)) {
lo... |
this.debug = makeLogFunction(levels.DEBUG, "DEBUG");
this.log = makeLogFunction(levels.LOG, "LOG");
this.info = makeLogFunction(levels.INFO, "INFO");
this.warn = makeLogFunction(levels.WARN, "WARN");
this.error = makeLogFunction(levels.ERROR, "ERROR");
})
| {
return function() {
if (level < this.level || production) return;
log.apply(log, [type, this.name].concat(Array.prototype.slice.call(arguments, 0)));
}
} | identifier_body |
logging.js | jsio('import Class, bind, log');
var loggers = {}
var levels = exports.levels = {
DEBUG: 0,
LOG: 1,
INFO: 2,
WARN: 3,
ERROR: 4
};
var production = false;
exports.setProduction = function(prod) {
production = !!prod;
}
exports.getLogger = function(name) {
if (!(name in loggers)) {
lo... | }
}
this.debug = makeLogFunction(levels.DEBUG, "DEBUG");
this.log = makeLogFunction(levels.LOG, "LOG");
this.info = makeLogFunction(levels.INFO, "INFO");
this.warn = makeLogFunction(levels.WARN, "WARN");
this.error = makeLogFunction(levels.ERROR, "ERROR");
}) | if (level < this.level || production) return;
log.apply(log, [type, this.name].concat(Array.prototype.slice.call(arguments, 0))); | random_line_split |
get.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (rt: &Runtime) {
let scmd = rt.cli().subcommand_matches("get").unwrap();
let id = scmd.value_of("id").unwrap(); // safe by clap
let path = PathBuf::from(id);
let store = Some(rt.store().path().clone());
let path = StoreId::new(store, path).unwrap_or_else(|e| trace_error_exit(&e, 1));
debug... | get | identifier_name |
get.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | use libimagstore::storeid::StoreId;
use retrieve::print_entry;
pub fn get(rt: &Runtime) {
let scmd = rt.cli().subcommand_matches("get").unwrap();
let id = scmd.value_of("id").unwrap(); // safe by clap
let path = PathBuf::from(id);
let store = Some(rt.store().path().clone());
let path = Store... | random_line_split | |
get.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | {
let scmd = rt.cli().subcommand_matches("get").unwrap();
let id = scmd.value_of("id").unwrap(); // safe by clap
let path = PathBuf::from(id);
let store = Some(rt.store().path().clone());
let path = StoreId::new(store, path).unwrap_or_else(|e| trace_error_exit(&e, 1));
debug!("path = {:?}"... | identifier_body | |
index.ts | export {Location, History} from 'history';
export * from './types';
/**
* Wraps a History Driver to add "click capturing" functionality.
*
* If you want to intercept and handle any click event that leads to a link,
* like on an `<a>` element, you pass your existing driver (e.g. created from
* `makeHistoryDriver()... | * `createMemoryHistory()` function in History v4. Check its
* [docs](https://github.com/mjackson/history/tree/v4.5.1#usage) for a good
* description on the options.
* @return {Function} the History Driver function
* @function makeServerHistoryDriver
*/
export {makeServerHistoryDriver} from './drivers'; | * (strings representing pathnames or location objects) as input, and outputs
* another stream of locations that were applied.
*
* @param {object} options an object with some options specific to
* this driver. These options are the same as for the corresponding | random_line_split |
mod.rs | mod areas;
mod area_frame_allocator;
mod paging;
mod info;
use self::paging::{PAGE_SIZE, PhysicalAddress};
use self::area_frame_allocator::{AreaFrameAllocator};
use spin::{Once, Mutex, MutexGuard};
pub use self::paging::{Page, VirtualAddress};
pub use self::paging::entry::{EntryFlags};
pub const KERNEL_OFFSET: usize... |
/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
align_down(addr + align - 1, align)
}
pub fn init(boot_info: &::bootinfo::BootInfo) {
println!("Initializing Memory");
areas::i... | {
if align.is_power_of_two() {
addr & !(align - 1)
} else if align == 0 {
addr
} else {
panic!("`align` must be a power of 2");
}
} | identifier_body |
mod.rs | mod areas;
mod area_frame_allocator;
mod paging;
mod info;
use self::paging::{PAGE_SIZE, PhysicalAddress};
use self::area_frame_allocator::{AreaFrameAllocator};
use spin::{Once, Mutex, MutexGuard};
pub use self::paging::{Page, VirtualAddress};
pub use self::paging::entry::{EntryFlags};
pub const KERNEL_OFFSET: usize... | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub struct Frame {
number: usize,
}
impl Frame {
fn containing_address(address: PhysicalAddress) -> Frame {
Frame { number: address.get() / PAGE_SIZE }
}
fn start_address(&self) -> PhysicalAddress {
PhysicalAddress::new(self... | MEMORY_CONTROLLER.try().expect("Memory not yet initialized").lock()
}
//TODO Figure out if we want Copy and Clone on this | random_line_split |
mod.rs | mod areas;
mod area_frame_allocator;
mod paging;
mod info;
use self::paging::{PAGE_SIZE, PhysicalAddress};
use self::area_frame_allocator::{AreaFrameAllocator};
use spin::{Once, Mutex, MutexGuard};
pub use self::paging::{Page, VirtualAddress};
pub use self::paging::entry::{EntryFlags};
pub const KERNEL_OFFSET: usize... | else if align == 0 {
addr
} else {
panic!("`align` must be a power of 2");
}
}
/// Align upwards. Returns the smallest x with alignment `align`
/// so that x >= addr. The alignment must be a power of 2.
pub fn align_up(addr: usize, align: usize) -> usize {
align_down(addr + align - 1, alig... | {
addr & !(align - 1)
} | conditional_block |
mod.rs | mod areas;
mod area_frame_allocator;
mod paging;
mod info;
use self::paging::{PAGE_SIZE, PhysicalAddress};
use self::area_frame_allocator::{AreaFrameAllocator};
use spin::{Once, Mutex, MutexGuard};
pub use self::paging::{Page, VirtualAddress};
pub use self::paging::entry::{EntryFlags};
pub const KERNEL_OFFSET: usize... | (start: Frame, end: Frame) -> FrameIter {
FrameIter {
start: start,
end: end,
}
}
}
struct FrameIter {
start: Frame,
end: Frame,
}
impl Iterator for FrameIter {
type Item = Frame;
fn next(&mut self) -> Option<Frame> {
if self.start <= self.end {
... | range_inclusive | identifier_name |
utils.rs | // Copyright 2014 Jonathan Eyolfson
use libc::{c_char, c_int, c_void, size_t, uint32_t, uint64_t};
#[repr(C)]
pub type wl_argument = uint64_t;
#[repr(C)]
pub struct wl_array {
pub size: size_t,
pub alloc: size_t,
pub data: *mut c_void,
}
#[repr(C)]
pub type wl_dispatcher_func_t = extern fn(
_: *cons... | ;
| wl_object | identifier_name |
utils.rs | // Copyright 2014 Jonathan Eyolfson
use libc::{c_char, c_int, c_void, size_t, uint32_t, uint64_t};
#[repr(C)]
pub type wl_argument = uint64_t;
#[repr(C)]
pub struct wl_array {
pub size: size_t,
pub alloc: size_t,
pub data: *mut c_void,
}
#[repr(C)]
pub type wl_dispatcher_func_t = extern fn(
_: *cons... | pub next: *mut wl_list,
}
#[repr(C)]
pub type wl_log_func_t = extern fn(_: *const c_char, ...);
#[repr(C)]
pub struct wl_message {
pub name: *const c_char,
pub signature: *const c_char,
pub types: *mut *const wl_interface,
}
#[repr(C)]
pub struct wl_object; | random_line_split | |
server.ts | import * as express from 'express';
import * as fallback from 'express-history-api-fallback';
import * as openResource from 'open';
import * as serveStatic from 'serve-static';
import * as codeChangeTool from './code_change_tools';
import {resolve} from 'path';
import * as buildConfig from '../../config';
export func... |
export function serveCoverage() {
let server = express();
server.use(
buildConfig.APP_BASE,
serveStatic(resolve(process.cwd(), 'coverage'))
);
server.listen(buildConfig.COVERAGE_PORT, () =>
openResource('http://localhost:' + buildConfig.COVERAGE_PORT + buildConfig.APP_BASE)
);
}
export functi... | {
let server = express();
server.use(
buildConfig.APP_BASE,
serveStatic(resolve(process.cwd(), buildConfig.DOCS_DEST))
);
server.listen(buildConfig.DOCS_PORT, () =>
openResource('http://localhost:' + buildConfig.DOCS_PORT + buildConfig.APP_BASE)
);
} | identifier_body |
server.ts | import * as express from 'express';
import * as fallback from 'express-history-api-fallback';
import * as openResource from 'open';
import * as serveStatic from 'serve-static';
import * as codeChangeTool from './code_change_tools';
import {resolve} from 'path';
import * as buildConfig from '../../config';
export func... | () {
let root = resolve(process.cwd(), buildConfig.PROD_DEST);
let server = express();
server.use(buildConfig.APP_BASE, serveStatic(root));
server.use(fallback('index.html', { root }));
server.listen(buildConfig.PORT, () =>
openResource('http://localhost:' + buildConfig.PORT + buildConfig.APP_BASE)
)... | serveProd | identifier_name |
server.ts | import * as express from 'express';
import * as fallback from 'express-history-api-fallback';
import * as openResource from 'open';
import * as serveStatic from 'serve-static';
import * as codeChangeTool from './code_change_tools';
import {resolve} from 'path';
import * as buildConfig from '../../config';
export func... | }
export function serveProd() {
let root = resolve(process.cwd(), buildConfig.PROD_DEST);
let server = express();
server.use(buildConfig.APP_BASE, serveStatic(root));
server.use(fallback('index.html', { root }));
server.listen(buildConfig.PORT, () =>
openResource('http://localhost:' + buildConfig.PORT... | ); | random_line_split |
oriented-image.desktop.tsx | CrossPlatform} from 'styles'
type State = {
srcTransformed: string
}
type TransformFn = (
canvas: HTMLCanvasElement,
ctx: CanvasRenderingContext2D,
width: number,
height: number
) => void
const uploadedSrc = /https?:\/\/127.0.0.1:.*$/i
const NO_TRANSFORM = 'notransform'
const _cacheNoTransforms: {[K in str... | {
// New src requires changing EXIF transform
if (prevProps.src !== this.props.src) {
this._setTranformForExifOrientation()
}
} | identifier_body | |
oriented-image.desktop.tsx | CrossPlatform} from 'styles'
type State = {
srcTransformed: string
}
type TransformFn = (
canvas: HTMLCanvasElement,
ctx: CanvasRenderingContext2D,
width: number,
height: number
) => void
const uploadedSrc = /https?:\/\/127.0.0.1:.*$/i
const NO_TRANSFORM = 'notransform'
const _cacheNoTransforms: {[K in str... | () {
this._hasComponentMounted = true
if (this._canvasRef) {
this._context = this._canvasRef.getContext('2d')
this._setTranformForExifOrientation()
}
}
componentWillUnmount() {
this._hasComponentMounted = false
this._canvasRef = null
this._context = null
}
componentDidUpdat... | componentDidMount | identifier_name |
oriented-image.desktop.tsx | StylesCrossPlatform} from 'styles'
type State = {
srcTransformed: string
}
type TransformFn = (
canvas: HTMLCanvasElement,
ctx: CanvasRenderingContext2D,
width: number,
height: number
) => void
const uploadedSrc = /https?:\/\/127.0.0.1:.*$/i
const NO_TRANSFORM = 'notransform'
const _cacheNoTransforms: {[K ... | onDragStart={props.onDragStart}
onLoad={props.onLoad}
ref={ref}
onError={props.onError}
/>
))
/*
* OrientedImage handles two situations of reading EXIF orientation bits.
* 1. When the user is adding an image, we want to render a preview of the
* image with the correct exif orientation
* 2. Once t... | // @ts-ignore I can't figure out the ref typing
const ImageRef = React.forwardRef((props: ImageRefProps, ref: React.RefObject<HTMLImageElement>) => (
<img
src={props.src}
style={props.style as React.CSSProperties} | random_line_split |
phases.py | from base import Phase
preparation = Phase('Preparation', 'Initializing connections, fetching data etc.')
volume_creation = Phase('Volume creation', 'Creating the volume to bootstrap onto')
volume_preparation = Phase('Volume preparation', 'Formatting the bootstrap volume')
volume_mounting = Phase('Volume mounting', 'M... | volume_mounting,
os_installation,
package_installation,
system_modification,
system_cleaning,
volume_unmounting,
image_registration,
cleaning,
] | volume_preparation, | random_line_split |
4_04_system_of_systems.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// example 4-04: System of Systems
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
systems: Vec<ParticleSystem>,
}
// A simple particle type
struct Particle {
position: Point2<f32>,
ve... |
struct ParticleSystem {
particles: Vec<Particle>,
origin: Point2<f32>,
}
impl ParticleSystem {
fn new(num: i32, position: Point2<f32>) -> Self {
let origin = position; // An origin point for where particles are birthed
let mut particles = Vec::new(); // Initialise the Vector
for _i... | random_line_split | |
4_04_system_of_systems.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// example 4-04: System of Systems
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
systems: Vec<ParticleSystem>,
}
// A simple particle type
struct Particle {
position: Point2<f32>,
ve... |
}
}
struct ParticleSystem {
particles: Vec<Particle>,
origin: Point2<f32>,
}
impl ParticleSystem {
fn new(num: i32, position: Point2<f32>) -> Self {
let origin = position; // An origin point for where particles are birthed
let mut particles = Vec::new(); // Initialise the Vector
... | {
false
} | conditional_block |
4_04_system_of_systems.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// example 4-04: System of Systems
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct | {
systems: Vec<ParticleSystem>,
}
// A simple particle type
struct Particle {
position: Point2<f32>,
velocity: Vector2<f32>,
acceleration: Vector2<f32>,
life_span: f32,
}
impl Particle {
fn new(l: Point2<f32>) -> Self {
let acceleration = vec2(0.0, 0.05);
let velocity = vec2(r... | Model | identifier_name |
mongo.rs | extern crate bson;
extern crate mongo_driver;
use bson::Bson;
use mongo_driver::CommandAndFindOptions;
use mongo_driver::client::{ClientPool, Uri};
use mongo_driver::collection::UpdateOptions;
use mongo_driver::flags::UpdateFlag;
use config::DBConfig;
use objects::{utils, Object};
use storage::error::{StoreError, Sto... | {
config: DBConfig,
pool: ClientPool,
}
impl MongoStore {
pub fn new(config: &DBConfig) -> StoreResult<MongoStore> {
let conn = MongoStore::conn(
config.username.as_str(),
config.password.as_str(),
config.host.as_str(),
config.port,
);
... | MongoStore | identifier_name |
mongo.rs | extern crate bson;
extern crate mongo_driver;
use bson::Bson;
use mongo_driver::CommandAndFindOptions;
use mongo_driver::client::{ClientPool, Uri};
use mongo_driver::collection::UpdateOptions; |
use config::DBConfig;
use objects::{utils, Object};
use storage::error::{StoreError, StoreResult};
use storage::storage::{Storage, StorageStatus};
pub struct MongoStore {
config: DBConfig,
pool: ClientPool,
}
impl MongoStore {
pub fn new(config: &DBConfig) -> StoreResult<MongoStore> {
let conn = ... | use mongo_driver::flags::UpdateFlag; | random_line_split |
mongo.rs | extern crate bson;
extern crate mongo_driver;
use bson::Bson;
use mongo_driver::CommandAndFindOptions;
use mongo_driver::client::{ClientPool, Uri};
use mongo_driver::collection::UpdateOptions;
use mongo_driver::flags::UpdateFlag;
use config::DBConfig;
use objects::{utils, Object};
use storage::error::{StoreError, Sto... |
_ => None,
},
_ => None,
})
});
res
})
.fold(None, |max, cur| match max {
Some(val) => Some(::std::cmp::max(val, c... | {
Some(datetime.timestamp())
} | conditional_block |
test_bayesian_blocks.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
from .. import bayesian_blocks, RegularEvents
def test_single_change_point(rseed=0):
rng = np.random.RandomState(rseed)
x = np.concatenate([rng.rand(100),
... |
def test_measures_fitness_homoscedastic(rseed=0):
rng = np.random.RandomState(rseed)
t = np.linspace(0, 1, 11)
x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2)
sigma = 0.05
x = x + sigma * rng.randn(len(x))
bins = bayesian_blocks(t, x, sigma, fitness='measures')
assert_allclose(bins, [0, 0... | rng = np.random.RandomState(rseed)
t = rng.rand(100)
t[80:] = t[:20]
x = np.ones_like(t)
x[:20] += 1
bins1 = bayesian_blocks(t)
bins2 = bayesian_blocks(t[:80], x[:80])
assert_allclose(bins1, bins2) | identifier_body |
test_bayesian_blocks.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
from .. import bayesian_blocks, RegularEvents
def test_single_change_point(rseed=0):
rng = np.random.RandomState(rseed)
x = np.concatenate([rng.rand(100),
... | (rseed=0):
rng = np.random.RandomState(rseed)
t = np.linspace(0, 1, 11)
x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2)
sigma = 0.05
x = x + sigma * rng.randn(len(x))
bins = bayesian_blocks(t, x, sigma, fitness='measures')
assert_allclose(bins, [0, 0.45, 0.55, 1])
def test_measures_fitness... | test_measures_fitness_homoscedastic | identifier_name |
test_bayesian_blocks.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
from .. import bayesian_blocks, RegularEvents
def test_single_change_point(rseed=0):
rng = np.random.RandomState(rseed)
x = np.concatenate([rng.rand(100),
... | bins2 = bayesian_blocks(t[:80], x[:80])
assert_allclose(bins1, bins2)
def test_measures_fitness_homoscedastic(rseed=0):
rng = np.random.RandomState(rseed)
t = np.linspace(0, 1, 11)
x = np.exp(-0.5 * (t - 0.5) ** 2 / 0.01 ** 2)
sigma = 0.05
x = x + sigma * rng.randn(len(x))
bins = bay... | bins1 = bayesian_blocks(t) | random_line_split |
session.js | import Ember from 'ember';
import describePromise from 'klondike/util/describe-promise';
function promiseAlias(name) {
return function () {
var promise = this.get('_promise');
return promise[name].apply(promise, arguments);
};
}
export default Ember.Object.extend({
users: null,
fixedKeyBinding: 'a... | var sessionKey = window.sessionStorage.getItem('key') || this.get('fixedKey');
if (!Ember.isEmpty(sessionKey)) {
settings.beforeSend = function(xhr) {
xhr.setRequestHeader(self.get('restClient').get('apiKeyRequestHeaderName'), sessionKey);
};
}
v... | init: function () {
this._super();
var self = this;
var settings = {}; | random_line_split |
session.js | import Ember from 'ember';
import describePromise from 'klondike/util/describe-promise';
function promiseAlias(name) |
export default Ember.Object.extend({
users: null,
fixedKeyBinding: 'application.apiKey',
user: null,
usernameBinding: 'user.username',
keyBinding: 'user.key',
rolesBinding: 'user.roles',
isInitialized: false,
_promise: null,
isLoggedIn: Ember.computed('username', function () {
... | {
return function () {
var promise = this.get('_promise');
return promise[name].apply(promise, arguments);
};
} | identifier_body |
session.js | import Ember from 'ember';
import describePromise from 'klondike/util/describe-promise';
function | (name) {
return function () {
var promise = this.get('_promise');
return promise[name].apply(promise, arguments);
};
}
export default Ember.Object.extend({
users: null,
fixedKeyBinding: 'application.apiKey',
user: null,
usernameBinding: 'user.username',
keyBinding: 'user.key',
role... | promiseAlias | identifier_name |
session.js | import Ember from 'ember';
import describePromise from 'klondike/util/describe-promise';
function promiseAlias(name) {
return function () {
var promise = this.get('_promise');
return promise[name].apply(promise, arguments);
};
}
export default Ember.Object.extend({
users: null,
fixedKeyBinding: 'a... |
this.get('restClient').set('apiKey', key);
}),
});
| {
window.sessionStorage.removeItem('key');
} | conditional_block |
settings_view_test.py | #!/usr/bin/env python
"""Tests for GRR settings-related views."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import gui_test_lib
from grr_response_server.gui.api_plugins import config_test as api_conf... | app.run(test_lib.main) | conditional_block | |
settings_view_test.py | #!/usr/bin/env python
"""Tests for GRR settings-related views."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import gui_test_lib
from grr_response_server.gui.api_plugins import config_test as api_conf... |
def testEachBinaryIsCorrectlyShown(self):
self.CreateAdminUser(u"gui_user")
self.Open("/#/manage-binaries")
self.WaitUntil(self.IsElementPresent,
"css=li[grr-nav-link]:contains('Binaries')")
self.WaitUntilNot(self.IsElementPresent,
"css=li[grr-nav-link]:con... | self.Open("/")
self.WaitUntil(self.IsElementPresent,
"css=li[grr-nav-link]:contains('Binaries') i.fa-lock") | identifier_body |
settings_view_test.py | #!/usr/bin/env python
"""Tests for GRR settings-related views."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import gui_test_lib
from grr_response_server.gui.api_plugins import config_test as api_conf... | (self):
super(TestManageBinariesView, self).setUp()
self.SetUpBinaries()
def testNotAccessibleForNonAdmins(self):
self.Open("/")
self.WaitUntil(self.IsElementPresent,
"css=li[grr-nav-link]:contains('Binaries') i.fa-lock")
def testEachBinaryIsCorrectlyShown(self):
self.Creat... | setUp | identifier_name |
settings_view_test.py | #!/usr/bin/env python
"""Tests for GRR settings-related views."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import gui_test_lib
from grr_response_server.gui.api_plugins import config_test as api_conf... | "div.panel:contains('Python Hacks') "
"tr:contains('1970-01-01 00:00:43 UTC')")
self.WaitUntil(
self.IsElementPresent, "css=grr-config-binaries-view "
"div.panel:contains('Executables') tr:contains('test.exe')")
self.WaitUntil(
self.IsElementPresent, "css=grr-config-bina... | random_line_split | |
HttpServerDumper.py | import http.server
import socketserver
import webbrowser as web
from urllib.parse import urlparse
import serial
import time
alertMsg = bytearray([2,0,0,0])
path = "C:\\code\\GpioPlayground\\UsbReadWrite\\" # need trailing slash
class GetHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
p... | self.end_headers()
self.wfile.write("ok".encode())
return
def do_POST(self):
parsed_path = urlparse(self.path)
print( "Headers are ",self.headers)
print( "Parsed path is",parsed_path.path)
content_len = int(self.headers.get('content-length', 0))
p... | random_line_split | |
HttpServerDumper.py | import http.server
import socketserver
import webbrowser as web
from urllib.parse import urlparse
import serial
import time
alertMsg = bytearray([2,0,0,0])
path = "C:\\code\\GpioPlayground\\UsbReadWrite\\" # need trailing slash
class GetHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
p... | server = socketserver.TCPServer(('', 8081), GetHandler)
print ('Starting server, use <Ctrl-C> to stop')
server.serve_forever() | conditional_block | |
HttpServerDumper.py | import http.server
import socketserver
import webbrowser as web
from urllib.parse import urlparse
import serial
import time
alertMsg = bytearray([2,0,0,0])
path = "C:\\code\\GpioPlayground\\UsbReadWrite\\" # need trailing slash
class GetHandler(http.server.BaseHTTPRequestHandler):
def | (self):
parsed_path = urlparse(self.path)
print( "Headers are ",self.headers)
print( "Parsed path is",parsed_path.path)
self.send_response(200)
self.end_headers()
self.wfile.write("ok".encode())
return
def do_POST(self):
parsed_path = urlparse(se... | do_GET | identifier_name |
HttpServerDumper.py | import http.server
import socketserver
import webbrowser as web
from urllib.parse import urlparse
import serial
import time
alertMsg = bytearray([2,0,0,0])
path = "C:\\code\\GpioPlayground\\UsbReadWrite\\" # need trailing slash
class GetHandler(http.server.BaseHTTPRequestHandler):
| self.wfile.write('{"result":"ok"}'.encode())
return
if __name__ == '__main__':
server = socketserver.TCPServer(('', 8081), GetHandler)
print ('Starting server, use <Ctrl-C> to stop')
server.serve_forever()
| def do_GET(self):
parsed_path = urlparse(self.path)
print( "Headers are ",self.headers)
print( "Parsed path is",parsed_path.path)
self.send_response(200)
self.end_headers()
self.wfile.write("ok".encode())
return
def do_POST(self):
parsed_path = u... | identifier_body |
heap.rs | use std::cell::UnsafeCell;
use std::mem;
use std::ptr;
/// `BytesRef` refers to a slice in tantivy's custom `Heap`.
#[derive(Copy, Clone)]
pub struct BytesRef {
pub start: u32,
pub stop: u32,
}
/// Object that can be allocated in tantivy's custom `Heap`.
pub trait HeapAllocable {
fn with_addr(addr: u32) -... | else {
(self.buffer.len() as u32) - self.used
}
}
pub fn allocate_space(&mut self, num_bytes: usize) -> u32 {
let addr = self.used;
self.used += num_bytes as u32;
let buffer_len = self.buffer.len();
if self.used > buffer_len as u32 {
self.buffer.... | {
0u32
} | conditional_block |
heap.rs | use std::cell::UnsafeCell;
use std::mem;
use std::ptr;
/// `BytesRef` refers to a slice in tantivy's custom `Heap`.
#[derive(Copy, Clone)]
pub struct BytesRef {
pub start: u32,
pub stop: u32,
}
/// Object that can be allocated in tantivy's custom `Heap`.
pub trait HeapAllocable {
fn with_addr(addr: u32) -... | fn get_slice(&self, start: u32, stop: u32) -> &[u8] {
&self.buffer[start as usize..stop as usize]
}
fn get_mut_slice(&mut self, start: u32, stop: u32) -> &mut [u8] {
&mut self.buffer[start as usize..stop as usize]
}
fn allocate_and_set(&mut self, data: &[u8]) -> BytesRef {
... | random_line_split | |
heap.rs | use std::cell::UnsafeCell;
use std::mem;
use std::ptr;
/// `BytesRef` refers to a slice in tantivy's custom `Heap`.
#[derive(Copy, Clone)]
pub struct BytesRef {
pub start: u32,
pub stop: u32,
}
/// Object that can be allocated in tantivy's custom `Heap`.
pub trait HeapAllocable {
fn with_addr(addr: u32) -... | (&mut self, start: u32, stop: u32) -> &mut [u8] {
&mut self.buffer[start as usize..stop as usize]
}
fn allocate_and_set(&mut self, data: &[u8]) -> BytesRef {
let start = self.allocate_space(data.len());
let stop = start + data.len() as u32;
self.get_mut_slice(start, stop).clone_... | get_mut_slice | identifier_name |
sleep.test.ts | /**
* @license
* Copyright 2019 Google 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... | const t0 = clock.now;
await sleep(100);
const t1 = clock.now;
expect(t1 - t0).to.equal(100);
});
}); | it('returns a promise that resolves after a given amount of time', async () => { | random_line_split |
rollup.config.js | import angular from 'rollup-plugin-angular';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';
// rollup-plugin-angular addons
import sass... | // local ones with the same names
preferBuiltins: true, // Default: true
// Lock the module search in this path (like a chroot). Module defined
// outside this path will be mark has external
jail: '/src', // Default: '/'
// If true, inspect resolved files to check that they are
... | // not all files you want to resolve are .js files
extensions: [ '.js', '.json' ], // Default: ['.js']
// whether to prefer built-in modules (e.g. `fs`, `path`) or | random_line_split |
rollup.config.js |
import angular from 'rollup-plugin-angular';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';
// rollup-plugin-angular addons
import sas... | return console.warn(message.message);
}
}
| conditional_block | |
rollup.config.js |
import angular from 'rollup-plugin-angular';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';
// rollup-plugin-angular addons
import sas... | sage) {
const suppressed = [
'UNRESOLVED_IMPORT',
'THIS_IS_UNDEFINED'
];
if (!suppressed.find(code => message.code === code)) {
return console.warn(message.message);
}
}
| rn(mes | identifier_name |
rollup.config.js |
import angular from 'rollup-plugin-angular';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import typescript from 'rollup-plugin-typescript';
import uglify from 'rollup-plugin-uglify';
import { minify } from 'uglify-es';
// rollup-plugin-angular addons
import sas... | const suppressed = [
'UNRESOLVED_IMPORT',
'THIS_IS_UNDEFINED'
];
if (!suppressed.find(code => message.code === code)) {
return console.warn(message.message);
}
}
| identifier_body | |
mutcd-getter.py | #!/usr/bin/env python
"""Get MUTCD SVGs from Wikipedia."""
import urllib
import argparse
import os
import json
from lxml import html
import wikipedia
from pyquery import PyQuery
class MUTCDGetterError(Exception):
|
# Setup arguments.
parser = argparse.ArgumentParser()
parser.add_argument('--title', default='Comparison of MUTCD-Influenced Traffic Signs',
help='The title of the Wikipedia entry containing the tables of MUTCD-inspired signs.')
parser.add_argument('--tables', default='Warning,Regulatory,Mandator... | pass | identifier_body |
mutcd-getter.py | #!/usr/bin/env python
"""Get MUTCD SVGs from Wikipedia."""
import urllib
import argparse
import os
import json
from lxml import html
import wikipedia
from pyquery import PyQuery
class MUTCDGetterError(Exception):
pass
# Setup arguments.
parser = argparse.ArgumentParser()
parser.add_argument('--title', default... | 'data': []
}
table = PyQuery(all_headers.filter(lambda: this.text_content() == table_header + '[edit]').next_all('table')[0])
first_row = table('tr:nth-child(1)')
column = parsed_args.column
if isinstance(column, str):
# If the provided column is a string, find the column index. Wh... | for table_header in table_headers:
table_signs = {
'type': 'category',
'text': table_header, | random_line_split |
mutcd-getter.py | #!/usr/bin/env python
"""Get MUTCD SVGs from Wikipedia."""
import urllib
import argparse
import os
import json
from lxml import html
import wikipedia
from pyquery import PyQuery
class MUTCDGetterError(Exception):
pass
# Setup arguments.
parser = argparse.ArgumentParser()
parser.add_argument('--title', default... |
row_sign_filenames = []
target_cell_imgs.each(lambda: row_sign_filenames.append(
{
'type': 'sign filename',
'text': PyQuery(this).attr('alt').replace(' ', '_'),
}
))
filenames_to_remove = []
for filename in row_sign_file... | continue | conditional_block |
mutcd-getter.py | #!/usr/bin/env python
"""Get MUTCD SVGs from Wikipedia."""
import urllib
import argparse
import os
import json
from lxml import html
import wikipedia
from pyquery import PyQuery
class | (Exception):
pass
# Setup arguments.
parser = argparse.ArgumentParser()
parser.add_argument('--title', default='Comparison of MUTCD-Influenced Traffic Signs',
help='The title of the Wikipedia entry containing the tables of MUTCD-inspired signs.')
parser.add_argument('--tables', default='Warnin... | MUTCDGetterError | identifier_name |
stylesheet_loader.rs | , Mime};
use msg::constellation_msg::PipelineId;
use net_traits::request::{CorsSettings, Destination, Referrer, RequestBuilder};
use net_traits::{
FetchMetadata, FetchResponseListener, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy,
};
use net_traits::{ResourceFetchTiming, ResourceTimingType};
use parking... |
fn resource_timing(&self) -> &ResourceFetchTiming {
&self.resource_timing
}
fn submit_resource_timing(&mut self) {
network_listener::submit_timing(self)
}
}
impl ResourceTimingListener for StylesheetContext {
fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
... | {
&mut self.resource_timing
} | identifier_body |
stylesheet_loader.rs | self, Mime};
use msg::constellation_msg::PipelineId;
use net_traits::request::{CorsSettings, Destination, Referrer, RequestBuilder};
use net_traits::{
FetchMetadata, FetchResponseListener, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy,
};
use net_traits::{ResourceFetchTiming, ResourceTimingType};
use par... | {
// NB: `media` is just an option so we avoid cloning it.
LinkElement { media: Option<MediaList> },
Import(Arc<Stylesheet>),
}
/// The context required for asynchronously loading an external stylesheet.
pub struct StylesheetContext {
/// The element that initiated the request.
elem: Trusted<HTMLE... | StylesheetContextSource | identifier_name |
stylesheet_loader.rs | , Mime};
use msg::constellation_msg::PipelineId;
use net_traits::request::{CorsSettings, Destination, Referrer, RequestBuilder};
use net_traits::{
FetchMetadata, FetchResponseListener, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy,
};
use net_traits::{ResourceFetchTiming, ResourceTimingType};
use parking... | ,
}
if let Some(ref shadow_root) = self.shadow_root {
shadow_root.root().invalidate_stylesheets();
} else {
document.invalidate_stylesheets();
}
// FIXME: Revisit once consensus is reached at:
// https://github.com... | {
Stylesheet::update_from_bytes(
&stylesheet,
&data,
protocol_encoding_label,
Some(environment_encoding),
final_url,
Some(&loader),
... | conditional_block |
stylesheet_loader.rs | self, Mime};
use msg::constellation_msg::PipelineId;
use net_traits::request::{CorsSettings, Destination, Referrer, RequestBuilder};
use net_traits::{
FetchMetadata, FetchResponseListener, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy,
};
use net_traits::{ResourceFetchTiming, ResourceTimingType};
use par... | &self,
source: StylesheetContextSource,
url: ServoUrl,
cors_setting: Option<CorsSettings>,
integrity_metadata: String,
) {
let document = document_from_node(self.elem);
let shadow_root = containing_shadow_root(self.elem).map(|sr| Trusted::new(&*sr));
l... | pub fn load( | random_line_split |
day24.py | # -*- coding: utf-8 -*-
import itertools
def evaluateGroup(packages, grouping):
|
if __name__ == "__main__":
"""Day24: Balancing"""
packages = []
with open('day24.dat') as datafile:
for thisstring in datafile:
packages.append(int(thisstring))
# another way of doing this:
#packages = map(int, [line.strip("\n") for line in open('day24.dat')])
#... | firstcount = 0
qe = 1
weight = [0,0]
for i in range(len(packages)):
weight[ grouping[i] ] = weight[ grouping[i] ] + packages[i]
if (grouping[i] == 0):
firstcount = firstcount + 1
qe = qe*packages[i]
equalweights = (3*weight[0]==weight[1])
return ( equalwe... | identifier_body |
day24.py | # -*- coding: utf-8 -*-
import itertools
def | (packages, grouping):
firstcount = 0
qe = 1
weight = [0,0]
for i in range(len(packages)):
weight[ grouping[i] ] = weight[ grouping[i] ] + packages[i]
if (grouping[i] == 0):
firstcount = firstcount + 1
qe = qe*packages[i]
equalweights = (3*weight[0]==weigh... | evaluateGroup | identifier_name |
day24.py | # -*- coding: utf-8 -*-
import itertools
def evaluateGroup(packages, grouping):
firstcount = 0
qe = 1
weight = [0,0]
for i in range(len(packages)):
weight[ grouping[i] ] = weight[ grouping[i] ] + packages[i]
if (grouping[i] == 0):
firstcount = firstcount + 1
qe... |
print("BEST QE={} with {} in first area. Group={}".format(bestqe, bestfirstcount,bestgroup))
| bestfirstcount=firstcount
if (qe < bestqe):
bestqe = qe
bestgroup = group | conditional_block |
day24.py | # -*- coding: utf-8 -*-
import itertools
def evaluateGroup(packages, grouping):
firstcount = 0
qe = 1
weight = [0,0]
for i in range(len(packages)):
weight[ grouping[i] ] = weight[ grouping[i] ] + packages[i]
if (grouping[i] == 0):
firstcount = firstcount + 1
qe... |
print("BEST QE={} with {} in first area. Group={}".format(bestqe, bestfirstcount,bestgroup)) | random_line_split | |
index.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import sequelize from '../sequelize';
import User from './... |
export default { sync };
export { User, UserLogin, UserClaim, UserProfile };
|
return sequelize.sync(...args);
}
| identifier_body |
index.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import sequelize from '../sequelize';
import User from './... | }
export default { sync };
export { User, UserLogin, UserClaim, UserProfile }; |
function sync(...args) {
return sequelize.sync(...args); | random_line_split |
index.js | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import sequelize from '../sequelize';
import User from './... | ...args) {
return sequelize.sync(...args);
}
export default { sync };
export { User, UserLogin, UserClaim, UserProfile };
| ync( | identifier_name |
solve.rs | // http://rosettacode.org/wiki/24_game/Solve
//! Modeled after [the Scala solution]
//!
//! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala
#![feature(slice_patterns)]
extern crate num;
extern crate permutohedron;
use num::rational::{Ratio, Rational};
use num::traits::Zero;
use permutohedron::He... | () {
let mut r = rationals![1, 3, 7, 9];
assert_eq!(solve(&mut r[..], 24),
Some("(9 / (3 / (1 + 7)))".to_string()));
}
| test_solve | identifier_name |
solve.rs | // http://rosettacode.org/wiki/24_game/Solve
//! Modeled after [the Scala solution]
//!
//! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala
#![feature(slice_patterns)]
extern crate num;
extern crate permutohedron;
use num::rational::{Ratio, Rational};
use num::traits::Zero;
use permutohedron::He... |
/// for a vector of rationals r, find the combination of arithmentic operations that yield
/// `target_val` as a result (if such combination exists)
fn solve(r: &mut [Rational], target_val: isize) -> Option<String> {
// need to sort because next_permutation()
// returns permutations in lexicographic order
... | {
let mut r = rationals![1, 3, 7, 9];
let sol = solve(&mut r[..], 24).unwrap_or("no solution found".to_string());
println!("{}", sol);
} | identifier_body |
solve.rs | // http://rosettacode.org/wiki/24_game/Solve
//! Modeled after [the Scala solution]
//!
//! [the Scala solution]: http://rosettacode.org/wiki/24_game/Solve#Scala
#![feature(slice_patterns)]
extern crate num;
extern crate permutohedron;
use num::rational::{Ratio, Rational};
use num::traits::Zero;
use permutohedron::He... | fn test_solve() {
let mut r = rationals![1, 3, 7, 9];
assert_eq!(solve(&mut r[..], 24),
Some("(9 / (3 / (1 + 7)))".to_string()));
} | #[ignore] | random_line_split |
0.py | # - Coding UTF8 -
#
# Networked Decision Making
# Site: http://code.google.com/p/global-decision-making-system/
#
# License Code: GPL, General Public License v. 2.0
# License Content: Creative Commons Attribution 3.0
#
# Also visit: www.web2py.com
# or Groups: http://groups.google.com/group/web2py
# For d... | # This file contains settings for auth policy which are need before setup
# of rest of configuration so staying here for now
#
#########################################################################
from gluon.storage import Storage
settings = Storage()
#Settings for user logon - lets just uncomment as needed for n... | # His general thinking on why this project is very important is available at
# http://www.scribd.com/doc/98216626/New-Global-Strategy
# | random_line_split |
self_authentication.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | //
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
//! Self-authentication example.
// For explanation of lint checks, run `rustc -W help` or see
// https://github.
// com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%2... | //
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. | random_line_split |
self_authentication.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | () {}
| main | identifier_name |
self_authentication.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | {} | identifier_body | |
analytic_account_open.py | # -*- coding: utf-8 -*-
# Copyright 2015 Eficent - Jordi Ballester Alomar
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AnalyticAccountOpen(models.TransientModel):
_name = 'analytic.account.open'
_description = 'Open single analytic account'
... | @api.multi
def analytic_account_open_window(self):
self.ensure_one()
act_window_id = self.env.ref(
'analytic.action_account_analytic_account_form')
result = act_window_id.read()[0]
acc_id = self.analytic_account_id.id
acc_ids = []
if self.include_child... | for x, y in res:
result[y] = True
return result
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.