function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def dst(self, dt):
return ZERO | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmYMDToTimestamp(year, month, day):
if year > Y2K38_MAX_YEAR: #Y2K38
year = Y2K38_MAX_YEAR
try:
return int(datetime(year, month, day).strftime("%s"))
except ValueError:
return int(time.mktime(datetime(year, month, day).timetuple())) # Windows platform doesn't have strftime(%s) | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmTimestampToDate(timestamp):
if timestamp > Y2K38_MAX_TIMESTAMP: #Y2K38
timestamp = Y2K38_MAX_TIMESTAMP
return datetime.fromtimestamp(timestamp) | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmCurrentTimestampToDateAsString(format = None):
timestamp = int(time.time())
if format:
return datetime.fromtimestamp(timestamp).strftime(format)
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmTimestampFromDateAsString(dateString, format):
return int(datetime.strptime(dateString, format).strftime("%s")) | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmTimestampFromUTCDateAsString(dateString, format):
dt = datetime.strptime(dateString, format)
return int((dt - datetime.utcfromtimestamp(0)).total_seconds()) | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmTimestampToYearMonthDay(timestamp):
d = datetime.fromtimestamp(timestamp)
return d.year, d.month, d.day | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmNormalizeTimestamp(timestamp):
return int(datetime.fromtimestamp(timestamp).strftime('%s')) | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmNowDateTime():
return datetime.now() | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmCurrentDayTimestamp():
return rmGetStartOfDay(int(time.time())) | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmGetStartOfDay(timestamp):
tuple = datetime.fromtimestamp(timestamp).timetuple()
return int(datetime(tuple.tm_year, tuple.tm_mon, tuple.tm_mday).strftime("%s")) | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmTimestampIsLeapYear(timestamp):
d = datetime.fromtimestamp(timestamp)
#try:
# datetime(d.year, 2, 29)
# return True
#except ValueError:
# return False
if d.year % 400 == 0:
return True
elif d.year % 100 == 0:
return False
elif d.year % 4 == 0:
... | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmDayRange(startDayTimestamp, numDays):
d = datetime.fromtimestamp(startDayTimestamp)
if numDays >=0:
dateList = [int(time.mktime( (d + timedelta(days=x)).timetuple() )) for x in range(0, numDays)]
else:
numDays = -numDays
dateList = [int(time.mktime( (d - timedelta(days=x)).time... | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmGetNumberOfDaysBetweenTimestamps(startTimestamp, endTimestamp):
d1 = datetime.fromtimestamp(startTimestamp)
d2 = datetime.fromtimestamp(endTimestamp)
delta = d2-d1
return delta.days | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def computeSuntransitAndDayLenghtForDayTs(ts, lat, lon, elevation):
ts = rmGetStartOfDayUtc(ts)
n = julianDayFromTimestamp(ts)
J = __computeMeanSolarNoon(n, lon)
M = __computeSolarMeanAnomay(J)
C = __equationOfTheCenter(M)
L = __computeEclipticLongitude(M, C)
Jtr = computeSolarTransit(J, M, ... | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmGetSunriseTimestampForDayTimestamp(ts, lat, lon, elevation):
if lat is None or lon is None:
log.debug("Latitude or longitude is not set. Returning same timestamp")
return ts
Jtr, w0 = computeSuntransitAndDayLenghtForDayTs(ts, lat, -lon, elevation)
Jrise = Jtr-w0/360
tsJrise = julia... | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def julianDayToUTC(JD):
return (JD - 2440587.5)*86400 | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def __sina(degree):
radian = degree/180*3.14159265359
return sin(radian) | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def __asina(x):
if abs(x) > 1:
return -90. if x< 0 else 90.
radian = asin(x)
return radian/(3.14159265359)*180. | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def __computeSolarMeanAnomay(solarNoon): #degrees
return (357.5291 + 0.98560028*solarNoon)%360 | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def __computeEclipticLongitude(solarMeanAnomaly, eqCenter): #degrees (it adds a sum a sines)
L = (solarMeanAnomaly + eqCenter + 180 + 102.9372) % 360
return L | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def __computeSinSunDeclination(L):
delta = __sina(L)*__sina(23.439 )
return delta | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def rmNTPFetch(server = "pool.ntp.org", withRequestDrift = False):
import struct
from socket import socket, AF_INET, SOCK_DGRAM
requestPacket = '\x1b' + 47 * '\0'
startTime = time.time()
try:
sock = socket(AF_INET, SOCK_DGRAM)
sock.settimeout(5)
except Exception, e:
lo... | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def __init__(self, fallback = True):
self.fallback = fallback
self.clock_gettime = None
self.get = None
self.monotonicInit() | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def monotonicFallback(self, asSeconds = True):
if asSeconds:
return int(time.time())
return time.time() | sprinkler/rainmachine-developer-resources | [
26,
38,
26,
4,
1436776616
] |
def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
Adapted from scipy.
"""
import sksurv
if domain != 'py':
return None
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
... | sebp/scikit-survival | [
906,
185,
906,
27,
1482790553
] |
def preprocess_cell(self, cell, resources, index):
# path of notebook directory, relative to conf.py
nb_path = Path(resources['metadata']['path']).relative_to(self.DOC_DIR)
to_root = [os.pardir] * len(nb_path.parts)
if cell.cell_type == 'markdown':
text = cell.source
... | sebp/scikit-survival | [
906,
185,
906,
27,
1482790553
] |
def __getattr__(cls, name):
if name in ('__file__', '__path__'):
return '/dev/null'
elif name[0] == name[0].upper() and name[0] != "_":
# Not very good, we assume Uppercase names are classes...
mocktype = type(name, (), {})
mocktype... | sebp/scikit-survival | [
906,
185,
906,
27,
1482790553
] |
def __init__(self, machine):
"""
Default scan telemetry constructor
:param machine: Scanned machine
"""
super(ScanTelem, self).__init__()
self.machine = machine | guardicore/monkey | [
6098,
725,
6098,
196,
1440919371
] |
def setUp(self):
self.client = TenantClient(self.tenant)
# need a teacher and a student with known password so tests can log in as each, or could use force_login()?
self.test_password = "password"
# need a teacher before students can be created or the profile creation will fail when tr... | timberline-secondary/hackerspace | [
13,
18,
13,
234,
1436242433
] |
def test_all_page_status_codes_for_students(self):
success = self.client.login(username=self.test_student1.username, password=self.test_password)
self.assertTrue(success)
self.assert200('djcytoscape:index')
self.assert200('djcytoscape:quest_map_personalized', args=[self.map.id, self.tes... | timberline-secondary/hackerspace | [
13,
18,
13,
234,
1436242433
] |
def test_x_axis_labels(self):
test_inputs = {
0: {},
7: {},
10: {5: '25s'},
15: {5: '25s', 10: '50'},
20: {5: '25s', 10: '50', 15: '1m'},
25: {5: '25s', 10: '50', 15: '1m', 20: '1.6'},
45: {5: '25s', 10: '50', 15: '1m', 20: '1.6', 25: '2.0', 30: '2.5', 35: '2.9', 40: '3.3'}... | sammyshj/nyx | [
8,
3,
8,
4,
1457028601
] |
def test_draw_subgraph_blank(self, tor_controller_mock):
tor_controller_mock().get_info.return_value = None
data = nyx.panel.graph.BandwidthStats()
rendered = test.render(nyx.panel.graph._draw_subgraph, data.primary, 0, 30, 7, nyx.panel.graph.Bounds.LOCAL_MAX, nyx.panel.graph.Interval.EACH_SECOND, nyx.curs... | sammyshj/nyx | [
8,
3,
8,
4,
1457028601
] |
def test_draw_subgraph(self, tor_controller_mock):
tor_controller_mock().get_info.return_value = '543,543 421,421 551,551 710,710 200,200 175,175 188,188 250,250 377,377'
data = nyx.panel.graph.BandwidthStats()
rendered = test.render(nyx.panel.graph._draw_subgraph, data.primary, 0, 30, 7, nyx.panel.graph.B... | sammyshj/nyx | [
8,
3,
8,
4,
1457028601
] |
def test_draw_accounting_stats(self, tor_controller_mock):
tor_controller_mock().is_alive.return_value = True
accounting_stat = stem.control.AccountingStats(
1410723598.276578,
'awake',
datetime.datetime(2014, 9, 14, 19, 41),
62,
4837, 102944, 107781,
2050, 7440, 9490,
)... | sammyshj/nyx | [
8,
3,
8,
4,
1457028601
] |
def get_first_noncomment_line(filename: str) -> Optional[str]:
try:
with open(filename) as f:
return next(gen_noncomment_lines(f))
except StopIteration:
return None | RudolfCardinal/crate | [
12,
5,
12,
5,
1425998885
] |
def main() -> None:
"""
Command-line entry point.
"""
# noinspection PyTypeChecker
parser = argparse.ArgumentParser(
description="Hash IDs in bulk, using a cryptographic hash function.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'infile'... | RudolfCardinal/crate | [
12,
5,
12,
5,
1425998885
] |
def debug_print(*s):
"""
Print message to console in debugging mode
"""
if muv_props.DEBUG:
print(s) | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def redraw_all_areas():
"""
Redraw all areas
"""
for area in bpy.context.screen.areas:
area.tag_redraw() | Microvellum/Fluid-Designer | [
69,
30,
69,
37,
1461884765
] |
def test_schema(self):
schema = MesonPlugin.get_schema()
self.assertThat(
schema,
Equals(
{
"$schema": "http://json-schema.org/draft-04/schema#",
"additionalProperties": False,
"properties": {
... | ubuntu-core/snapcraft | [
1092,
435,
1092,
66,
1446139395
] |
def test_get_build_environment(self):
plugin = MesonPlugin(part_name="my-part", options=lambda: None)
self.assertThat(plugin.get_build_environment(), Equals(dict())) | ubuntu-core/snapcraft | [
1092,
435,
1092,
66,
1446139395
] |
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
l=len(height)
maxheight=[0 for i in range(l)]
leftmax=0
rightmax=0
res=0
for i in range(l):
if height[i]>leftmax:
leftmax=height[i]
... | dichen001/Go4Jobs | [
1,
1,
1,
2,
1474399542
] |
def test_main(in_sas_id, in_parset_path, in_file_sizes_path, in_f0seqnr_sizes_path):
result = True | brentjens/pyautoplot | [
1,
2,
1,
2,
1461226603
] |
def parse_arguments(argv):
sas_id = int(argv[1])
parset_path = argv[2]
file_sizes_path = argv[3]
f0seqnr_sizes_file_path = argv[4]
return sas_id, parset_path, file_sizes_path, f0seqnr_sizes_file_path | brentjens/pyautoplot | [
1,
2,
1,
2,
1461226603
] |
def __init__(self, user, redirect_to, *args, **kwargs):
super(DefaultBranchForm, self).__init__(*args, **kwargs)
if user.is_superuser:
branches = Branch.objects.all()
else:
branches = Branch.objects.filter(pk__in=user.branches_organized.all)
choices = [(o.id, un... | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def label_from_instance(self, obj):
from django.utils import timezone
current_tz = timezone.get_current_timezone()
date = obj.start_time.astimezone(current_tz).strftime('%A, %b %d')
time = obj.start_time.astimezone(current_tz).strftime(
'%I:%M%p').lstrip('0').lower()
... | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, *args, **kwargs):
super(BranchForm, self).__init__(*args, **kwargs)
self.fields['city'].error_messages['required'] = _(
"Please enter a city")
self.fields['country'].error_messages['required'] = _(
"Please enter a country")
self.initial['site'... | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, *args, **kwargs):
"Sets custom meta data to the form's fields"
super(ModelForm, self).__init__(*args, **kwargs)
self.fields['fullname'].error_messages['required'] = _(
"Please enter your name")
self.fields['email'].error_messages['required'] = _(
... | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, *args, **kwargs):
"Sets custom meta data to the form's fields"
super(TeacherForm, self).__init__(*args, **kwargs)
self.fields['fullname'].error_messages['required'] = _(
"Please enter your name")
self.fields['email'].error_messages['required'] = _(
... | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, *args, **kwargs):
"Sets custom meta data to the form's fields"
super(ModelForm, self).__init__(*args, **kwargs)
self.fields['title'].error_messages['required'] = _(
"Please enter a class title")
self.fields['description'].error_messages['required'] = _(
... | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, *args, **kwargs):
"Sets custom meta data to the form's fields"
super(ModelForm, self).__init__(*args, **kwargs)
self.fields['title'].widget.attrs['class'] = 'barter_item'
self.fields['title'].error_messages['required'] = _(
"Barter item cannot be blank") | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, branch, *args, **kwargs):
""
self.branch = branch
super(BaseBarterItemFormSet, self).__init__(*args, **kwargs) | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, course, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['items'].queryset = BarterItem.objects.filter(
course=course)
self.fields['items'].error_messages['required'] = _(
"Please select at least one item")
... | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, *args, **kwargs):
super(StudentForm, self).__init__(*args, **kwargs)
self.fields['fullname'].error_messages['required'] = _(
"Please enter your name")
self.fields['email'].error_messages['required'] = _(
"Please enter your email")
self.fields['... | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, *args, **kwargs):
super(FeedbackForm, self).__init__(*args, **kwargs)
self.fields['content'].error_messages['required'] = _(
"Please enter your feedback") | orzubalsky/tradeschool | [
16,
5,
16,
31,
1344286300
] |
def __init__(self, selected_individuals, fill_creator):
BaseCreation.__init__(self)
self.__fill_creator = fill_creator
self.__selected_individuals = selected_individuals
self.__individuals = [] | MachineLearningControl/OpenMLC-Python | [
11,
6,
11,
2,
1446331881
] |
def lookup_pimlico_versions():
# Use Github API to find all tagged releases
tag_api_url = "%s/repos/markgw/pimlico/tags" % GITHUB_API
try:
tag_response = urlopen(tag_api_url).read().decode("utf-8")
except Exception as e:
print("Could not fetch Pimlico release tags from {}: {}".format(tag... | markgw/pimlico | [
6,
1,
6,
13,
1475829569
] |
def find_config_value(config_path, key, start_in_pipeline=False):
with open(config_path, "r", encoding="utf-8") as f:
in_pipeline = start_in_pipeline
for line in f:
line = line.strip("\n ")
if in_pipeline and line:
# Look for the required key in the pipeline ... | markgw/pimlico | [
6,
1,
6,
13,
1475829569
] |
def tar_dirname(tar_path):
with tarfile.open(tar_path, "r:gz") as tar:
# Expect first member to be a directory
member = tar.next()
if not member.isdir():
raise ValueError("downloaded tar file was expected to contain a directory, but didn't")
return member.name | markgw/pimlico | [
6,
1,
6,
13,
1475829569
] |
def bootstrap(config_file, git=False):
current_dir = os.path.abspath(os.path.dirname(__file__))
branch_name = git if type(git) is str else "master"
branch_url = "{}{}/".format(RAW_URL, branch_name)
if os.path.exists(os.path.join(current_dir, "pimlico")):
print("Pimlico source directory already ... | markgw/pimlico | [
6,
1,
6,
13,
1475829569
] |
def __init__(self):
self.number_of_decisions = 8
speller = config_speller_8.Config()
robot = config_robot_8.Config()
self.state = []
self.actions = []
self.letters = []
#MENU
menu_state = 0
self.letters.append([u"Speller",u"Robot"
... | BrainTech/openbci | [
12,
9,
12,
3,
1407695699
] |
def __init__(self):
super(MainWindow, self).__init__()
self.video, self.resizeTimer = '', 0
self.parse_cmdline()
self.init_settings()
self.init_logger()
self.init_scale()
self.init_cutter()
self.setWindowTitle(qApp.applicationName())
self.setConten... | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def file_opener(self, filename: str) -> None:
try:
if QFileInfo(filename).suffix() == 'vcp':
self.cutter.openProject(project_file=filename)
if filename == os.path.join(QDir.tempPath(), MainWindow.TEMP_PROJECT_FILE):
os.remove(os.path.join(QDir.temp... | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def get_size(mode: str='NORMAL') -> QSize:
modes = {
'LOW': QSize(800, 425),
'NORMAL': QSize(930, 680),
'HIGH': QSize(1850, 1300)
}
return modes[mode] | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def init_settings(self) -> None:
try:
settings_path = self.get_app_config_path()
except AttributeError:
if sys.platform == 'win32':
settings_path = os.path.join(QDir.homePath(), 'AppData', 'Local', qApp.applicationName().lower())
elif sys.platform == '... | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def log_uncaught_exceptions(cls, exc, tb) -> None:
logging.critical(''.join(traceback.format_tb(tb)))
logging.critical('{0}: {1}'.format(cls, exc)) | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def init_cutter(self) -> None:
self.cutter = VideoCutter(self)
self.cutter.errorOccurred.connect(self.errorHandler)
self.setCentralWidget(self.cutter)
qApp.setWindowIcon(VideoCutter.getAppIcon(encoded=False)) | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def get_bitness() -> int:
from struct import calcsize
return calcsize('P') * 8 | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def reboot(self) -> None:
if self.cutter.mediaAvailable:
self.cutter.saveProject(reboot=True)
self.save_settings()
qApp.exit(MainWindow.EXIT_CODE_REBOOT) | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def lock_gui(self, locked: bool=True) -> None:
if locked:
qApp.setOverrideCursor(Qt.WaitCursor)
self.cutter.cliplist.setEnabled(False)
self.setEnabled(False)
else:
self.setEnabled(True)
self.cutter.cliplist.setEnabled(True)
qApp.res... | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def flatpak(self) -> bool:
return sys.platform.startswith('linux') and QFileInfo(__file__).absolutePath().startswith('/app/') | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def get_path(path: str=None, override: bool=False) -> str:
if override:
if getattr(sys, 'frozen', False) and getattr(sys, '_MEIPASS', False):
# noinspection PyProtectedMember, PyUnresolvedReferences
return os.path.join(sys._MEIPASS, path)
return os.path.jo... | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def errorHandler(self, msg: str, title: str=None) -> None:
qApp.restoreOverrideCursor()
QMessageBox.critical(self, 'An error occurred' if title is None else title, msg, QMessageBox.Ok)
logging.error(msg) | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def cleanup():
shutil.rmtree(MainWindow.WORKING_FOLDER, ignore_errors=True) | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def mousePressEvent(self, event: QMouseEvent) -> None:
if event.button() == Qt.LeftButton and self.cutter.mediaAvailable:
self.cutter.cliplist.clearSelection()
self.cutter.timeCounter.clearFocus()
self.cutter.frameCounter.clearFocus()
# noinspection PyBroadExcepti... | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def dropEvent(self, event: QDropEvent) -> None:
filename = event.mimeData().urls()[0].toLocalFile()
self.file_opener(filename)
event.accept() | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def timerEvent(self, event: QTimerEvent) -> None:
try:
self.cutter.seekSlider.reloadThumbs()
self.killTimer(self.resizeTimer)
self.resizeTimer = 0
except AttributeError:
pass | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def main():
qt_set_sequence_auto_mnemonic(False)
if hasattr(Qt, 'AA_EnableHighDpiScaling'):
QGuiApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
if hasattr(Qt, 'AA_Use96Dpi'):
QGuiApplication.setAttribute(Qt.AA_Use96Dpi, True)
if hasattr(Qt, 'AA_ShareOpenGLContexts'):
... | ozmartian/vidcutter | [
1224,
120,
1224,
257,
1472670250
] |
def index_path(tree_name):
return config['trees'][tree_name]['index_path'] | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def parse_path_filter(filter):
filter = filter.replace('(', '\\(')
filter = filter.replace(')', '\\)')
filter = filter.replace('|', '\\|')
filter = filter.replace('.', '\\.')
def star_repl(m):
if m.group(0) == '*':
return '[^/]*'
else:
return '.*'
filter ... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def parse_search(searchString):
pieces = searchString.split(' ')
result = {}
for i in range(len(pieces)):
if pieces[i].startswith('path:'):
result['pathre'] = parse_path_filter(pieces[i][len('path:'):])
elif pieces[i].startswith('pathre:'):
result['pathre'] = pieces[i... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def __init__(self):
self.results = []
self.qualified_results = []
self.pathre = None
self.compiled = {} | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def add_results(self, results):
self.results.append(results) | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def categorize_path(self, path):
'''
Given a path, decide whether it's "normal"/"test"/"generated". These
are the 3 top-level groups by which results are categorized.
These are hardcoded heuristics that probably could be better defined
in the `config.json` metadata, with a mean... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def sort_compiled(self):
'''
Traverse the `compiled` state in `path_precedences` order, and then
its "qkind" children in their inherent order (which is derived from
the use of `key_precedences` by `get()`), transforming and propagating
the results, applying a `max_count` result l... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def search_files(tree_name, path):
pathFile = os.path.join(index_path(tree_name), 'repo-files')
objdirFile = os.path.join(index_path(tree_name), 'objdir-files')
try:
# We set the locale to make grep much faster.
results = subprocess.check_output(['grep', '-Eih', path, pathFile, objdirFile], ... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def identifier_search(search, tree_name, needle, complete, fold_case):
needle = re.sub(r'\\(.)', r'\1', needle)
pieces = re.split(r'\.|::', needle)
# If the last segment of the search needle is too short, return no results
# because we're worried that would return too many results.
if not complete ... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def do_GET(self):
pid = os.fork()
if pid:
# Parent process
log('request(handled by %d) %s', pid, self.path)
timedOut = [False]
def handler(signum, frame):
log('timeout %d, killing', pid)
timedOut[0] = True
o... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def process_request(self):
url = six.moves.urllib.parse.urlparse(self.path)
path_elts = url.path.split('/')
# Strip any extra slashes.
path_elts = [ elt for elt in path_elts if elt != '' ]
if len(path_elts) >= 2 and path_elts[1] == 'search':
tree_name = path_elts[0]... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def generateWithTemplate(self, replacements, templateFile):
output = open(templateFile).read()
for (k, v) in replacements.items():
output = output.replace(k, v)
databytes = output.encode('utf-8')
self.send_response(200)
self.send_header("Vary", "Accept")
sel... | bill-mccloskey/searchfox | [
169,
56,
169,
5,
1426482198
] |
def handle_spider_item(self, data, url_object):
"""Immediately process the spider item."""
return self.process(data, url_object) | os2webscanner/os2webscanner | [
12,
1,
12,
1,
1405072144
] |
def process(self, data, url_object):
"""Process XML data.
Converts document to json before processing with TextProcessor.
if XML is not well formed, treat it as HTML
"""
logging.info("Process XML %s" % url_object.url)
try:
data = json.dumps(xmltodict.parse(d... | os2webscanner/os2webscanner | [
12,
1,
12,
1,
1405072144
] |
def main():
PEOPLE = insert_people()
sum_salary_all(PEOPLE)
list_people_by_city(PEOPLE) | feroda/lessons-python4beginners | [
2,
12,
2,
3,
1472811971
] |
def sum_salary_all(list_people):
for p in list_people:
sum_salary_single(p) | feroda/lessons-python4beginners | [
2,
12,
2,
3,
1472811971
] |
def list_people_by_city(list_people):
list_city = list_people.sort() | feroda/lessons-python4beginners | [
2,
12,
2,
3,
1472811971
] |
def setUp(self):
super(TestStockCycleCount, self).setUp()
self.res_users_model = self.env["res.users"]
self.cycle_count_model = self.env["stock.cycle.count"]
self.stock_cycle_count_rule_model = self.env["stock.cycle.count.rule"]
self.inventory_model = self.env["stock.inventory"]
... | OCA/stock-logistics-warehouse | [
248,
611,
248,
91,
1402934883
] |
def _create_stock_cycle_count_rule_periodic(self, uid, name, values):
rule = self.stock_cycle_count_rule_model.with_user(uid).create(
{
"name": name,
"rule_type": "periodic",
"periodic_qty_per_period": values[0],
"periodic_count_period"... | OCA/stock-logistics-warehouse | [
248,
611,
248,
91,
1402934883
] |
def _create_stock_cycle_count_rule_accuracy(self, uid, name, values, zone_ids):
rule = self.stock_cycle_count_rule_model.with_user(uid).create(
{
"name": name,
"rule_type": "accuracy",
"accuracy_threshold": values[0],
"apply_in": "locat... | OCA/stock-logistics-warehouse | [
248,
611,
248,
91,
1402934883
] |
def test_cycle_count_planner(self):
"""Tests creation of cycle counts."""
# Common rules:
wh = self.big_wh
locs = self.stock_location_model
for rule in self.big_wh.cycle_count_rule_ids:
locs += wh._search_cycle_count_locations(rule)
locs = locs.exists() # rem... | OCA/stock-logistics-warehouse | [
248,
611,
248,
91,
1402934883
] |
def test_view_methods(self):
"""Tests the methods used to handle views."""
self.cycle_count_1.action_create_inventory_adjustment()
self.cycle_count_1.sudo().action_view_inventory()
inv_count = self.cycle_count_1.inventory_adj_count
self.assertEqual(inv_count, 1, "View method fail... | OCA/stock-logistics-warehouse | [
248,
611,
248,
91,
1402934883
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.