file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
key_value_table_demo.py | import json
import pprint
from a2qt import QtWidgets
from a2widget.key_value_table import KeyValueTable
from a2widget.a2text_field import A2CodeField
_DEMO_DATA = {
'Name': 'Some Body',
'Surname': 'Body',
'Street. Nr': 'Thingstreet 8',
'Street': 'Thingstreet',
'Nr': '8',
'PLZ': '12354',
... | show() | conditional_block | |
qscintilla.py | #############################################################################
##
## Copyright (c) 2011 Riverbank Computing Limited <info@riverbankcomputing.com>
##
## This file is part of PyQt.
##
## This file may be used under the terms of the GNU General Public
## License versions 2.0 or 3.0 as published by the Fre... | ## Please review the following information to ensure GNU General
## Public Licensing requirements will be met:
## http://trolltech.com/products/qt/licenses/licensing/opensource/. If
## you are unsure which license is appropriate for your use, please
## review the following information:
## http://trolltech.com/products/... | random_line_split | |
qscintilla.py | #############################################################################
##
## Copyright (c) 2011 Riverbank Computing Limited <info@riverbankcomputing.com>
##
## This file is part of PyQt.
##
## This file may be used under the terms of the GNU General Public
## License versions 2.0 or 3.0 as published by the Fre... | return "PyQt4.Qsci", ("QsciScintilla", ) | identifier_body | |
qscintilla.py | #############################################################################
##
## Copyright (c) 2011 Riverbank Computing Limited <info@riverbankcomputing.com>
##
## This file is part of PyQt.
##
## This file may be used under the terms of the GNU General Public
## License versions 2.0 or 3.0 as published by the Fre... | ():
return "PyQt4.Qsci", ("QsciScintilla", )
| moduleInformation | identifier_name |
make-sim-options.py | #!/usr/bin/python
#This script create simulation and reconstruction options
import os
import sys
import re
if len(sys.argv)<4:
print "Usage: make-sim-options.py <decay_file> <output_prefix> <event_number>"
exit(1)
HOME_DIR = os.environ['HOME']
JPSIKKROOT_DIR = os.environ['JPSIKKROOT']
SHARE_DIR = os.path.joi... | DECAY_FILE = os.path.abspath(os.path.join(SHARE_DIR,sys.argv[1]))
PREFIX = sys.argv[2]
RTRAW_FILE = os.path.abspath(PREFIX+".rtraw")
DST_FILE = os.path.abspath(PREFIX+".dst")
ROOT_FILE = os.path.abspath(PREFIX+".root") | random_line_split | |
make-sim-options.py | #!/usr/bin/python
#This script create simulation and reconstruction options
import os
import sys
import re
if len(sys.argv)<4:
|
HOME_DIR = os.environ['HOME']
JPSIKKROOT_DIR = os.environ['JPSIKKROOT']
SHARE_DIR = os.path.join(JPSIKKROOT_DIR, "share")
TEMPLATE_DIR = os.path.join(JPSIKKROOT_DIR, "share/template")
TEMPLATE_SIM_FILE = os.path.joint(TEMPLATE_DIR, "simulation.cfg")
print HOMEDIR, JPSIKKROOT_DIR, TE
DECAY_FILE = os.path.abspath(os.... | print "Usage: make-sim-options.py <decay_file> <output_prefix> <event_number>"
exit(1) | conditional_block |
test_text.py | # This file is part of Checkbox.
#
# Copyright 2012 Canonical Ltd.
# Written by:
# Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
# Daniel Manrique <roadmr@ubuntu.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# th... | self.assertEqual(stream.getvalue(), expected_bytes) | random_line_split | |
test_text.py | # This file is part of Checkbox.
#
# Copyright 2012 Canonical Ltd.
# Written by:
# Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
# Daniel Manrique <roadmr@ubuntu.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# th... | exporter = TextSessionStateExporter()
# Text exporter expects this data format
data = {'result_map': {'job_name': {'outcome': 'fail'}}}
stream = BytesIO()
exporter.dump(data, stream)
expected_bytes = "job_name: fail\n".encode('UTF-8')
self.assertEqual(stream.getvalue(), e... | identifier_body | |
test_text.py | # This file is part of Checkbox.
#
# Copyright 2012 Canonical Ltd.
# Written by:
# Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
# Daniel Manrique <roadmr@ubuntu.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# th... | (TestCase):
def test_default_dump(self):
exporter = TextSessionStateExporter()
# Text exporter expects this data format
data = {'result_map': {'job_name': {'outcome': 'fail'}}}
stream = BytesIO()
exporter.dump(data, stream)
expected_bytes = "job_name: fail\n".encode(... | TextSessionStateExporterTests | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::path::Path;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use stack_config::StackConfig;
use tracing::{even... | else {
event!(Level::DEBUG, "System RC configurations loaded");
}
if let Some(home) = home_dir {
if let Err(e) = load_user(&mut loader, &home) {
event!(Level::INFO, home = ?home, "Unable to load user configuration, skipped: {:?}", e);
} else {
event!(Level::DEBU... | {
event!(
Level::INFO,
etc_eden_dir = ?etc_eden_dir,
"Unable to load system RC configurations, skipped: {:?}",
e
);
} | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::path::Path;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use stack_config::StackConfig;
use tracing::{even... | (loader: &mut EdenFsConfigLoader, etc_dir: &Path) -> Result<()> {
let rcs_dir = etc_dir.join("config.d");
let entries = std::fs::read_dir(&rcs_dir)
.with_context(|| format!("Unable to read configuration from {:?}", rcs_dir))?;
for rc in entries {
let rc = match rc {
Ok(rc) => rc... | load_system_rcs | identifier_name |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::path::Path;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use stack_config::StackConfig;
use tracing::{even... | continue;
}
};
let name = rc.file_name();
let name = if let Some(name) = name.to_str() {
name
} else {
continue;
};
if name.starts_with('.') || !name.ends_with(".toml") {
continue;
}
if let ... | event!(
Level::INFO,
"Unable to read configuration, skipped: {:?}",
e
); | random_line_split |
utils.js | "use strict";
// copied from http://www.broofa.com/Tools/Math.uuid.js
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
exports.uuid = function () {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i==8 || i==13 || i==18 || i=... | } | if (buf[i] === 0x0a) return i;
}
return -1; | random_line_split |
utils.js | "use strict";
// copied from http://www.broofa.com/Tools/Math.uuid.js
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
exports.uuid = function () {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i==8 || i==13 || i==18 || i=... | (num, n, p) {
var s = '' + num;
p = p || '0';
while (s.length < n) s = p + s;
return s;
}
exports.pad = _pad;
exports.date_to_str = function (d) {
return _daynames[d.getDay()] + ', ' + _pad(d.getDate(),2) + ' ' +
_monnames[d.getMonth()] + ' ' + d.getFullYear() + ' ' +
_pad(d... | _pad | identifier_name |
utils.js | "use strict";
// copied from http://www.broofa.com/Tools/Math.uuid.js
var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
exports.uuid = function () {
var chars = CHARS, uuid = new Array(36), rnd=0, r;
for (var i = 0; i < 36; i++) {
if (i==8 || i==13 || i==18 || i=... |
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _monnames = ['Jan', 'Feb', 'Mar', 'Apr', '... | {return n<10 ? '0'+n : n} | identifier_body |
pollutionController.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
from urllib.request import urlopen
def | ():
html = urlopen("http://www.aqhi.gov.hk/en/aqhi/past-24-hours-aqhi45fd.html?stationid=80")
soup = BeautifulSoup(html, "lxml")
return soup
def getLatestAQHI(dataTable):
aqhiTable = dataTable.findAll('tr')[1].findAll('td')
aqhi = {}
aqhi['dateTime'] = aqhiTable[0].text
aqhi['index'] = aqhiTable[1].text
return... | getSoupAQHI | identifier_name |
pollutionController.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
from urllib.request import urlopen
def getSoupAQHI():
html = urlopen("http://www.aqhi.gov.hk/en/aqhi/past-24-hours-aqhi45fd.html?stationid=80")
soup = BeautifulSoup(html, "lxml")
return soup
def getLatestAQHI(dataTable):
aqhiTable = data... |
def getPollutionData():
soupAQHI = getSoupAQHI()
dataTableAQHI = soupAQHI.find('table', {'id' : 'dd_stnh24_table'})
aqhi = getLatestAQHI(dataTableAQHI)
rawAQICN = getRawAQICN()
aqicn = getLatestAQICN(rawAQICN)
data = {}
data['AQHI'] = aqhi['index']
data['AQHITS'] = aqhi['dateTime']
data['AQICN'] = aqic... | aqi = source.split("Air Pollution.")[1]
aqi = aqi.split("title")[1]
aqi = aqi.split("</div>")[0]
aqi = aqi.split(">")[1]
aqits = source.split("Updated on ")[1].strip()
aqits = aqits.split("<")[0]
aqhiData = {}
aqhiData['index'] = aqi
aqhiData['dateTime'] = aqits
return aqhiData | identifier_body |
pollutionController.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
from urllib.request import urlopen
def getSoupAQHI():
html = urlopen("http://www.aqhi.gov.hk/en/aqhi/past-24-hours-aqhi45fd.html?stationid=80")
soup = BeautifulSoup(html, "lxml")
return soup
def getLatestAQHI(dataTable):
aqhiTable = data... | aqits = source.split("Updated on ")[1].strip()
aqits = aqits.split("<")[0]
aqhiData = {}
aqhiData['index'] = aqi
aqhiData['dateTime'] = aqits
return aqhiData
def getPollutionData():
soupAQHI = getSoupAQHI()
dataTableAQHI = soupAQHI.find('table', {'id' : 'dd_stnh24_table'})
aqhi = getLatestAQHI(dataTableA... | random_line_split | |
nodes.py | # GeneaCrystal Copyright (C) 2012-2013
# Christian Jaeckel, <christian.doe@gmail.com>
# Frederic Kerber, <fkerber@gmail.com>
# Pascal Lessel, <maverickthe6@gmail.com>
# Michael Mauderer, <mail@michaelmauderer.de>
#
# GeneaCrystal is free software: you can redistribute it and/or modify
# it under the ... |
def onBack():
self.__value = self.__value[0:-1]
self.__edit.text = self.__value
def onEnter():
if not self.__value == "":
highscore.addEntry(self.__value, score)
if callback is ... | self.__value += keyCode
self.__edit.text += keyCode | conditional_block |
nodes.py | # GeneaCrystal Copyright (C) 2012-2013
# Christian Jaeckel, <christian.doe@gmail.com>
# Frederic Kerber, <fkerber@gmail.com>
# Pascal Lessel, <maverickthe6@gmail.com>
# Michael Mauderer, <mail@michaelmauderer.de>
#
# GeneaCrystal is free software: you can redistribute it and/or modify
# it under the ... | (self):
pass
class HighscoreEntryNode(avg.DivNode):
def __init__(self, mode, score, allScores, callback=None, theme=None, *args, **kwargs):
avg.DivNode.__init__(self, *args, **kwargs)
if theme is None:
from geneacrystal import themes
theme ... | delete | identifier_name |
nodes.py | # GeneaCrystal Copyright (C) 2012-2013
# Christian Jaeckel, <christian.doe@gmail.com>
# Frederic Kerber, <fkerber@gmail.com>
# Pascal Lessel, <maverickthe6@gmail.com>
# Michael Mauderer, <mail@michaelmauderer.de>
#
# GeneaCrystal is free software: you can redistribute it and/or modify
# it under the ... | def __init__(self, finishCB, *args, **kwargs):
super(StaticOverlayNode, self).__init__(*args, **kwargs)
self.__anim = None
self.__initalRadius=self._background.size.x*0.08
self.__circle = avg.CircleNode(pos=(self._background.size.x//2, self._background.size.y//2), r=self.__initalRadi... | identifier_body | |
nodes.py | # GeneaCrystal Copyright (C) 2012-2013
# Christian Jaeckel, <christian.doe@gmail.com>
# Frederic Kerber, <fkerber@gmail.com>
# Pascal Lessel, <maverickthe6@gmail.com>
# Michael Mauderer, <mail@michaelmauderer.de>
| # GeneaCrystal is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GeneaCrystal is distributed in the hope that it will be useful,... | #
| random_line_split |
jquery.freakload.js | /*
* freakLoad - v0.1.0
* Preloader JS library
* https://github.com/nofreakz/freakLoad
*
* Copyright (c) 2014
* MIT License
*/
;(function($, win, doc) {
'use strict';
/*
* DEFAULTS
*/
var _plugin = 'freakLoad',
itemTpl = {
node: undefined,
url: '',
... | (items, options) {
this.opt = $.extend(true, {}, defaults, options);
this.init(items);
}
Plugin.prototype = {
/*
* DATA
*/
data: {
// use queue as object to possibility multiple queues
queue: {
loaded: 0,
... | Plugin | identifier_name |
jquery.freakload.js | /*
* freakLoad - v0.1.0
* Preloader JS library
* https://github.com/nofreakz/freakLoad
*
* Copyright (c) 2014
* MIT License
*/
;(function($, win, doc) {
'use strict';
/*
* DEFAULTS
*/
var _plugin = 'freakLoad',
itemTpl = {
node: undefined,
url: '',
... |
Plugin.prototype = {
/*
* DATA
*/
data: {
// use queue as object to possibility multiple queues
queue: {
loaded: 0,
items: [],
groups: {} // @groupTpl
},
requested: {
... | {
this.opt = $.extend(true, {}, defaults, options);
this.init(items);
} | identifier_body |
jquery.freakload.js | /*
* freakLoad - v0.1.0
* Preloader JS library
* https://github.com/nofreakz/freakLoad
*
* Copyright (c) 2014
* MIT License
*/
;(function($, win, doc) {
'use strict';
/*
* DEFAULTS
*/
var _plugin = 'freakLoad',
itemTpl = {
node: undefined,
url: '',
... | });
$[_plugin](items, generalOptions);
};
})(jQuery, window, document); | return $.extend({node: item}, dataset, itemOptions); | random_line_split |
jquery.freakload.js | /*
* freakLoad - v0.1.0
* Preloader JS library
* https://github.com/nofreakz/freakLoad
*
* Copyright (c) 2014
* MIT License
*/
;(function($, win, doc) {
'use strict';
/*
* DEFAULTS
*/
var _plugin = 'freakLoad',
itemTpl = {
node: undefined,
url: '',
... | else {
$[_plugin]('add', fn);
}
// finally if the method doesn't exist or is a private method show a console error
} else if (!method || (typeof fn === 'string' && fn.charAt(0) === '_')) {
throw 'Method ' + fn + ' does not exist on jQuery.' + _plugin;
}
... | {
return method.apply(data, Array.prototype.slice.call(args, 1));
} | conditional_block |
phylomap.js | function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0)... | (node,attribs,lat,lon) {
//console.log('adding node to selection list. Length now:',phylomap.selectedOccurrences.length)
var record = {}
// if there are extra attributes on this node, copy them over to the trait matrix selection entry
for (attrib in attribs) {
record[attrib] = attribs[attrib]
... | addLocationToSelectedList | identifier_name |
phylomap.js | function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0)... |
// this function loops through all of the occurrence points and assigns colors depending on the value
// of the individual occurence point within the range across all the points
function updateOccurrencePointColors() {
var minRed = 160.0/256.0
var minGreen = 80.0/256.0
// find out which attribute has been select... | {
//console.log(points,"\n");
var markers = phylomap.geojsmap.map.createLayer("feature",{"renderer":"vgl"})
var uiLayer = phylomap.geojsmap.map.createLayer('ui', {"renderer":"vgl"});
var tooltip = uiLayer.createWidget('dom', {position: {x: 0, y: 0}});
tooltipElem = $(tooltip.canvas()).attr('id', 'tool... | identifier_body |
phylomap.js | function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0)... |
}
createMarker(latlng, name, text, selectionID, icon);
bounds.extend(latlng);
addLocationToSelectedList(treeNode,attribs,thisloc[1],thisloc[0])
};
}
}
// recursive traversal of the current tree to uncover all nodes below the passed node and
// map them. The clade root is passed so highlighting can ... | {
attribs = treeNode.node_data['attributes'][i]
// add descriptions to the text markers
for (var attrib in attribs) {
text = text + ' [' + attrib+']:'+attribs[attrib] + '\n'
};
} | conditional_block |
phylomap.js | function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
function log(msg) {
setTimeout(function() {
throw new Error(msg);
}, 0)... | },
data: points,
width: 1000,
height: 700,
latitude: 'lat',
longitude: 'lon',
size: 'renderSize',
//tileUrl: 'http://c.tiles.wmflabs.org/hillshading/${z}/${x}/${y}.png',
//tileUrl: 'http://tile.stamen.com/terrain/${z}/${x}/${y}.jpg',
tileUrl: 'https://{s}.tile.thunderforest.com/landscape/{... | latitude: 9.9725 | random_line_split |
update-tuple.spec.tsx | import app, { Component, Update } from '../src/apprun';
describe('Component', () => {
it('should support non-event-typed update tuple', () => {
class | extends Component {
state = 0;
update = [
['+1', state => ++state, { once: true }],
['+1a', state => ++state],
];
}
const t = new Test().start() as any;
t.run('+1');
t.run('+1');
t.run('+1a');
expect(t.state).toEqual(2);
})
it('should support state-type... | Test | identifier_name |
update-tuple.spec.tsx | import app, { Component, Update } from '../src/apprun';
describe('Component', () => {
it('should support non-event-typed update tuple', () => {
class Test extends Component {
state = 0;
update = [
['+1', state => ++state, { once: true }],
['+1a', state => ++state],
];
}
... |
type Events = '+1-once' | '+1';
class Test extends Component<number, Events> {
state = 0;
update: Update<number, Events> = [
['+1-once', state => ++state, { once: true }],
['+1', state => ++state],
];
}
const t = new Test().start() as any;
t.run('+1-once');
t... | t.run('method2');
expect(t.state).toEqual(2);
})
it('should support event-typed update tuple', () => { | random_line_split |
style.ts | import styled, { css } from 'styled-components';
import { centerIcon } from '~/renderer/mixins';
import {
TOOLBAR_BUTTON_WIDTH,
TOOLBAR_BUTTON_HEIGHT,
} from '~/constants/design';
import { ITheme } from '~/interfaces';
export const Icon = styled.div`
width: 100%;
height: 100%;
will-change: background-image;... | ? 'rgba(255, 255, 255, 0.1)'
: 'rgba(0, 0, 0, 0.06)'};
`};
`; |
${({ theme }: { theme: ITheme }) => css`
border: 3px solid
${theme['toolbar.lightForeground'] | random_line_split |
GeopointInput.js | import PropTypes from 'prop-types'
import React from 'react'
import config from 'config:@lyra/google-maps-input'
import Button from 'part:@lyra/components/buttons/default'
import Dialog from 'part:@lyra/components/dialogs/default'
import Fieldset from 'part:@lyra/components/fieldsets/default'
import {
PatchEvent,
s... | () {
const {value, type, markers} = this.props
if (!config || !config.apiKey) {
return (
<div>
<p>
The{' '}
<a href="https://vegapublish.com/docs/schema-types/geopoint-type">
Geopoint type
</a>{' '}
needs a Google Maps API ke... | render | identifier_name |
GeopointInput.js | import PropTypes from 'prop-types'
import React from 'react'
import config from 'config:@lyra/google-maps-input'
import Button from 'part:@lyra/components/buttons/default'
import Dialog from 'part:@lyra/components/dialogs/default'
import Fieldset from 'part:@lyra/components/fieldsets/default'
import {
PatchEvent,
s... |
return (
<Fieldset
legend={type.title}
description={type.description}
className={styles.root}
markers={markers}
>
{value && (
<div>
<img
className={styles.previewImage}
src={getStaticImageUrl(value)}
... | {
return (
<div>
<p>
The{' '}
<a href="https://vegapublish.com/docs/schema-types/geopoint-type">
Geopoint type
</a>{' '}
needs a Google Maps API key with access to:
</p>
<ul>
<li>Google Maps JavaScript ... | conditional_block |
GeopointInput.js | import PropTypes from 'prop-types'
import React from 'react'
import config from 'config:@lyra/google-maps-input'
import Button from 'part:@lyra/components/buttons/default'
import Dialog from 'part:@lyra/components/dialogs/default'
import Fieldset from 'part:@lyra/components/fieldsets/default'
import {
PatchEvent,
s... |
handleChange = latLng => {
const {type, onChange} = this.props
onChange(
PatchEvent.from([
setIfMissing({
_type: type.name
}),
set(latLng.lat(), ['lat']),
set(latLng.lng(), ['lng'])
])
)
}
handleClear = () => {
const {onChange} = this.props
... | {
this.setState(prevState => ({modalOpen: !prevState.modalOpen}))
} | identifier_body |
GeopointInput.js | import PropTypes from 'prop-types'
import React from 'react'
import config from 'config:@lyra/google-maps-input'
import Button from 'part:@lyra/components/buttons/default'
import Dialog from 'part:@lyra/components/dialogs/default'
import Fieldset from 'part:@lyra/components/fieldsets/default'
import {
PatchEvent,
s... | import GoogleMapsLoadProxy from './GoogleMapsLoadProxy'
const getLocale = context => {
const intl = context.intl || {}
return (
intl.locale ||
(typeof window !== 'undefined' && window.navigator.language) ||
'en'
)
}
const getStaticImageUrl = value => {
const loc = `${value.lat},${value.lng}`
con... | random_line_split | |
translate-text.service.spec.ts | // Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// 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 ap... | const textAndAvailability = TranslateTextService.getTextToTranslate();
expect(textAndAvailability).toEqual(expectedTextAndAvailability);
});
it('should return {null, False} for completely empty states', function() {
const expectedTextAndAvailability = {
text: null,
more: fals... | TranslateTextService.init('1', 'en', () => {});
$httpBackend.flush();
| random_line_split |
view_utils.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {assertDataInRange, assertDefined, assertGreaterThan, assertLessThan} from '../../util/assert';
import {LCont... | (value: RNode | LView | LContainer | StylingContext):
StylingContext|null {
while (Array.isArray(value)) {
// This check is same as `isStylingContext()` but we don't call at as we don't want to call
// `Array.isArray()` twice and give JITer more work for inlining.
if (typeof value[TYPE] === 'number') ... | unwrapStylingContext | identifier_name |
view_utils.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {assertDataInRange, assertDefined, assertGreaterThan, assertLessThan} from '../../util/assert';
import {LCont... |
export function isContentQueryHost(tNode: TNode): boolean {
return (tNode.flags & TNodeFlags.hasContentQuery) !== 0;
}
export function isComponent(tNode: TNode): boolean {
return (tNode.flags & TNodeFlags.isComponent) === TNodeFlags.isComponent;
}
export function isComponentDef<T>(def: DirectiveDef<T>): def is ... | {
// Could be an LView or an LContainer. If LContainer, unwrap to find LView.
const slotValue = hostView[nodeIndex];
const lView = isLView(slotValue) ? slotValue : slotValue[HOST];
return lView;
} | identifier_body |
view_utils.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {assertDataInRange, assertDefined, assertGreaterThan, assertLessThan} from '../../util/assert';
import {LCont... | * Returns the monkey-patch value data present on the target (which could be
* a component, directive or a DOM node).
*/
export function readPatchedData(target: any): LView|LContext|null {
ngDevMode && assertDefined(target, 'Target expected');
return target[MONKEY_PATCH_KEY_NAME];
}
export function readPatchedLV... |
/** | random_line_split |
emulators.py | # encoding: utf-8
import os
def emulator_rom_launch_command(emulator, rom):
"""Generates a command string that will launch `rom` with `emulator` (using
the format provided by the user). The return value of this function should
be suitable to use as the `Exe` field of a Steam shortcut"""
# Normalizing the stri... | (emulator):
"""Returns the directory which stores the emulator. The return value of this
function should be suitable to use as the 'StartDir' field of a Steam
shortcut"""
return os.path.dirname(emulator.location)
| emulator_startdir | identifier_name |
emulators.py | # encoding: utf-8
import os
def emulator_rom_launch_command(emulator, rom):
|
def emulator_startdir(emulator):
"""Returns the directory which stores the emulator. The return value of this
function should be suitable to use as the 'StartDir' field of a Steam
shortcut"""
return os.path.dirname(emulator.location)
| """Generates a command string that will launch `rom` with `emulator` (using
the format provided by the user). The return value of this function should
be suitable to use as the `Exe` field of a Steam shortcut"""
# Normalizing the strings is just removing any leading/trailing quotes.
# The beautiful thing is tha... | identifier_body |
emulators.py | # encoding: utf-8
import os
def emulator_rom_launch_command(emulator, rom):
"""Generates a command string that will launch `rom` with `emulator` (using
the format provided by the user). The return value of this function should
be suitable to use as the `Exe` field of a Steam shortcut"""
# Normalizing the stri... | # substitute values in at runtime. Right now the only supported values are:
# %l - The location of the emulator (to avoid sync bugs)
# %r - The location of the ROM (so the emulator knows what to launch)
# %fn - The ROM filename without its extension (for emulators that utilize separete configuration files)
#
... | random_line_split | |
variables_12.js | var searchData=
[
['sample',['Sample',['../a04155.html#aee7b23bef7e0cdd87974d3c9d36e9d73',1,'SAMPLELIST']]],
['sample_5fiteration_5f',['sample_iteration_',['../a04551.html#aef5b9a97853a4d8a409b451b445bbd0a',1,'tesseract::LSTMRecognizer']]],
['samplecount',['SampleCount',['../a04123.html#a67f65514626f5d21844400c52... | ['startdelta',['StartDelta',['../a04215.html#a2ff3e161c404e6647da48c724fecaf41',1,'TABLE_FILLER']]],
['step_5fcount',['step_count',['../a02507.html#a34a59945d65b7db4f0f8aa11a3cfe8c0',1,'EDGEPT']]],
['stepcount',['stepcount',['../a04763.html#a5619d323d56f236d28852959d8898769',1,'C_OUTLINE_FRAG']]],
['stepdir',['... | ['start_5fbox_5f',['start_box_',['../a04907.html#a340698db98509f605d57c88efcb62a9a',1,'tesseract::StringRenderer']]],
['start_5fof_5fdawg',['start_of_dawg',['../a04603.html#addd4c725934785d09cdc821098dfe79e',1,'tesseract::RecodeNode']]],
['start_5fof_5fword',['start_of_word',['../a04603.html#a0ba756b9c78f3c3dc047... | random_line_split |
sectors.rs | use rand::{seq, ChaChaRng, SeedableRng};
use rayon::prelude::*;
use std::{
collections::HashMap,
sync::atomic::{AtomicBool, Ordering},
time::Instant,
usize::MAX,
};
use config::GameConfig;
use entities::Faction;
use entities::Sector;
use utils::Point;
/// Used for generating sectors.
pub struct Sector... | .into_iter()
.map(|point| (point, 0))
.collect();
// Run K means until convergence, i.e until no reassignments
let mut has_assigned = true;
while has_assigned {
let wrapped_assigned = AtomicBool::new(false);
// Assign to closest centr... | .cloned()
.collect::<Vec<_>>();
// System to cluster_id mapping
let mut cluster_map: HashMap<Point, usize> = system_locations | random_line_split |
sectors.rs | use rand::{seq, ChaChaRng, SeedableRng};
use rayon::prelude::*;
use std::{
collections::HashMap,
sync::atomic::{AtomicBool, Ordering},
time::Instant,
usize::MAX,
};
use config::GameConfig;
use entities::Faction;
use entities::Sector;
use utils::Point;
/// Used for generating sectors.
pub struct Sector... | (&self, config: &GameConfig, system_locations: Vec<Point>) -> Vec<Sector> {
// Measure time for generation.
let now = Instant::now();
info!("Simulating expansion for initial sectors...");
let seed: &[_] = &[config.map_seed as u32];
let mut rng: ChaChaRng = ChaChaRng::from_seed(s... | generate | identifier_name |
sectors.rs | use rand::{seq, ChaChaRng, SeedableRng};
use rayon::prelude::*;
use std::{
collections::HashMap,
sync::atomic::{AtomicBool, Ordering},
time::Instant,
usize::MAX,
};
use config::GameConfig;
use entities::Faction;
use entities::Sector;
use utils::Point;
/// Used for generating sectors.
pub struct Sector... |
/// Split the systems in to a set number of clusters using K-means.
pub fn generate(&self, config: &GameConfig, system_locations: Vec<Point>) -> Vec<Sector> {
// Measure time for generation.
let now = Instant::now();
info!("Simulating expansion for initial sectors...");
let se... | {
SectorGen {}
} | identifier_body |
sectors.rs | use rand::{seq, ChaChaRng, SeedableRng};
use rayon::prelude::*;
use std::{
collections::HashMap,
sync::atomic::{AtomicBool, Ordering},
time::Instant,
usize::MAX,
};
use config::GameConfig;
use entities::Faction;
use entities::Sector;
use utils::Point;
/// Used for generating sectors.
pub struct Sector... |
}
*cluster_id = closest_cluster;
});
has_assigned = wrapped_assigned.load(Ordering::Relaxed);
// Calculate new centroids
centroids
//.par_iter_mut()
.iter_mut()
.enumerate()
... | {
wrapped_assigned.store(true, Ordering::Relaxed);
closest_cluster = i;
closest_distance = distance;
} | conditional_block |
course.py | # -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.
""" Course page """
import web
from inginious.frontend.pages.utils import INGIniousPage
class CoursePage(INGIniousPage):
""" Course page """
def get_... |
def show_page(self, course, current_page=0, current_tag=""):
""" Prepares and shows the course page """
username = self.user_manager.session_username()
if not self.user_manager.course_is_open_to_user(course, lti=False):
return self.template_helper.get_renderer().course_unavaila... | """ GET request """
course = self.get_course(courseid)
user_input = web.input()
page = int(user_input.get("page", 1)) - 1
tag = user_input.get("tag", "")
return self.show_page(course, page, tag) | identifier_body |
course.py | # -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.
""" Course page """
import web
from inginious.frontend.pages.utils import INGIniousPage
class CoursePage(INGIniousPage):
""" Course page """
def get_... |
tasks = course.get_tasks()
last_submissions = self.submission_manager.get_user_last_submissions(5, {"courseid": course.get_id(),
"taskid": {"$in": list(tasks.keys())}})
for submission in last_submissions:
... | return self.template_helper.get_renderer().course_unavailable() | conditional_block |
course.py | # -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.
""" Course page """
import web
from inginious.frontend.pages.utils import INGIniousPage
class CoursePage(INGIniousPage):
""" Course page """
def get_... | (self, course, current_page=0, current_tag=""):
""" Prepares and shows the course page """
username = self.user_manager.session_username()
if not self.user_manager.course_is_open_to_user(course, lti=False):
return self.template_helper.get_renderer().course_unavailable()
task... | show_page | identifier_name |
course.py | # -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.
""" Course page """
import web
from inginious.frontend.pages.utils import INGIniousPage
class CoursePage(INGIniousPage):
""" Course page """
def get_... | for user_task in user_tasks:
tasks_data[user_task["taskid"]]["succeeded"] = user_task["succeeded"]
tasks_data[user_task["taskid"]]["grade"] = user_task["grade"]
weighted_score = user_task["grade"] * tasks[user_task["taskid"]].get_grading_weight()
tasks_score[0] +... | tasks_score[1] += task.get_grading_weight() if tasks_data[taskid]["visible"] else 0
| random_line_split |
app.js | /*
* Copyright 2016 e-UCM (http://www.e-ucm.es/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* This project has received funding from the European Union’s Horizon
* 2020 research and innovation programme under grant agreeme... | });
$stateProvider.state({
name: 'login',
url: '/login',
templateUrl: 'view/login'
});
$stateProvider.state({
name: 'signup',
url: '/signup',
templateUrl: 'view/signup'
});
$stateProvider.state({
... | random_line_split | |
app.js | /*
* Copyright 2016 e-UCM (http://www.e-ucm.es/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* This project has received funding from the European Union’s Horizon
* 2020 research and innovation programme under grant agreeme... | $location.search('game', params.game._id);
$location.search('version', $scope.selectedVersion._id);
});
}
});
$scope.$on('selectClass', function (event, params) {
if (params.class) {
$scope.selectedClass = p... | $location.url('game');
}
| conditional_block |
menu.e2e.ts | describe('Menu', () => {
beforeEach(() => {
cy.visit('e2e/standalone.html');
});
it('should have valid items count', () => {
cy.get('.menu-content')
.find('li')
.should('have.length', 34);
});
it('should sync active menu items while scroll', () => {
cy.contains('h1', 'Introduction')
... | .wait(100)
.get('[role=menuitem].active')
.should('have.text', 'Introduction');
cy.url().should('include', '#section/Introduction');
});
it('should update URL hash when clicking on menu items', () => {
cy.contains('[role=menuitem].-depth1', 'pet').click({ force: true });
cy.location(... | cy.contains('h1', 'Introduction')
.scrollIntoView() | random_line_split |
custom_build.rs | use std::collections::{HashMap, BTreeSet};
use std::fs;
use std::io::prelude::*;
use std::path::PathBuf;
use std::str;
use std::sync::{Mutex, Arc};
use core::{PackageId, PackageSet};
use util::{CargoResult, human, Human};
use util::{internal, ChainError, profile, paths};
use util::Freshness;
use super::job::Work;
use... |
}
| {
// Do a quick pre-flight check to see if we've already calculated the
// set of dependencies.
if out.contains_key(unit) {
return &out[unit]
}
let mut to_link = BTreeSet::new();
let mut plugins = BTreeSet::new();
if !unit.target.is_custom_build() &&... | identifier_body |
custom_build.rs | use std::collections::{HashMap, BTreeSet};
use std::fs;
use std::io::prelude::*;
use std::path::PathBuf;
use std::str;
use std::sync::{Mutex, Arc};
use core::{PackageId, PackageSet};
use util::{CargoResult, human, Human};
use util::{internal, ChainError, profile, paths};
use util::Freshness;
use super::job::Work;
use... |
let data = match iter.next() {
Some(val) => val,
None => continue
};
// getting the `key=value` part of the line
let mut iter = data.splitn(2, '=');
let key = iter.next();
let value = iter.next();
let (... | {
// skip this line since it doesn't start with "cargo:"
continue;
} | conditional_block |
custom_build.rs | use std::collections::{HashMap, BTreeSet};
use std::fs;
use std::io::prelude::*;
use std::path::PathBuf;
use std::str;
use std::sync::{Mutex, Arc};
use core::{PackageId, PackageSet};
use util::{CargoResult, human, Human};
use util::{internal, ChainError, profile, paths};
use util::Freshness;
use super::job::Work;
use... | (config: &super::BuildConfig,
packages: &PackageSet) -> BuildState {
let mut sources = HashMap::new();
for package in packages.iter() {
match package.manifest().links() {
Some(links) => {
sources.insert(links.to_string(),
... | new | identifier_name |
custom_build.rs | use std::collections::{HashMap, BTreeSet};
use std::fs;
use std::io::prelude::*;
use std::path::PathBuf;
use std::str;
use std::sync::{Mutex, Arc};
use core::{PackageId, PackageSet};
use util::{CargoResult, human, Human};
use util::{internal, ChainError, profile, paths};
use util::Freshness;
use super::job::Work;
use... | // line started with `cargo:` but didn't match `key=value`
_ => bail!("Wrong output in {}: `{}`", whence, line),
};
match key {
"rustc-flags" => {
let (libs, links) = try!(
BuildOutput::parse_rustc_flags... | let key = iter.next();
let value = iter.next();
let (key, value) = match (key, value) {
(Some(a), Some(b)) => (a, b.trim_right()), | random_line_split |
flex-item.directive.ts | import {Directive, Input, HostBinding, ElementRef} from "@angular/core";
/**
* A directive to control flex items layout properties.
*/
@Directive({
selector: '[flex]'
})
export class FlexItemDirective{
/**
* Controls the flex-basis property.
* @type {string} size value (px, vh, vp, em, %, etc...)
... |
constructor(private el: ElementRef) {}
@Input("gravity")
set gravity(value: string) {
switch (value){
case 'start':
this._gravity = 'flex-start';
break;
case 'center':
this._gravity = 'center';
break;
... | private _gravity: string = 'inherit'; | random_line_split |
flex-item.directive.ts | import {Directive, Input, HostBinding, ElementRef} from "@angular/core";
/**
* A directive to control flex items layout properties.
*/
@Directive({
selector: '[flex]'
})
export class | {
/**
* Controls the flex-basis property.
* @type {string} size value (px, vh, vp, em, %, etc...)
*/
@HostBinding('style.flex-basis')
@HostBinding('style.-webkit-flex-basis')
@Input('flex')
basis: string = 'auto';
/**
* Controls the flex-grow property.
* @type {number}... | FlexItemDirective | identifier_name |
time.rs | //! Utilities for mapping between human-usable time units and BAPS3's
//! preferred time units.
/// Enum of available time units.
///
/// This does not contain every possible time unit anyone may want to use with
/// a BAPS3 client, but covers the main possibilities.
///
/// Each unit specified in terms of its equival... | {
/// Hours (1 hour = 60 minutes)
Hours,
/// Minutes (1 minute = 60 seconds).
Minutes,
/// Seconds (1 second = 1,000 milliseconds).
Seconds,
/// Milliseconds (1 millisecond = 1,000 microseconds).
Milliseconds,
/// Microseconds (the BAPS3 base unit).
Microseconds
}
impl TimeUnit... | TimeUnit | identifier_name |
time.rs | //! Utilities for mapping between human-usable time units and BAPS3's
//! preferred time units.
/// Enum of available time units.
///
/// This does not contain every possible time unit anyone may want to use with
/// a BAPS3 client, but covers the main possibilities.
///
/// Each unit specified in terms of its equival... |
/// Multiplexes a series of unit flags into a TimeUnit.
/// Larger units take precedence.
pub fn from_flags(h: bool, m: bool, s: bool, ms: bool) -> TimeUnit {
if h { TimeUnit::Hours }
else if m { TimeUnit::Minutes }
else if s { TimeUnit::Seconds }
el... | random_line_split | |
time.rs | //! Utilities for mapping between human-usable time units and BAPS3's
//! preferred time units.
/// Enum of available time units.
///
/// This does not contain every possible time unit anyone may want to use with
/// a BAPS3 client, but covers the main possibilities.
///
/// Each unit specified in terms of its equival... |
} | {
if h { TimeUnit::Hours }
else if m { TimeUnit::Minutes }
else if s { TimeUnit::Seconds }
else if ms { TimeUnit::Milliseconds }
else { TimeUnit::Microseconds }
} | identifier_body |
time.rs | //! Utilities for mapping between human-usable time units and BAPS3's
//! preferred time units.
/// Enum of available time units.
///
/// This does not contain every possible time unit anyone may want to use with
/// a BAPS3 client, but covers the main possibilities.
///
/// Each unit specified in terms of its equival... |
else { TimeUnit::Microseconds }
}
} | { TimeUnit::Milliseconds } | conditional_block |
mem.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::encryptionpb::EncryptedContent;
use super::metadata::*;
use crate::crypter::*;
use crate::{AesGcmCrypter, Error, Iv, Result};
/// An in-memory backend, it saves master key in memory.
pub(crate) struct MemAesGcmBackend {
pub key: Vec<... |
let key = &self.key;
let iv_value = content
.get_metadata()
.get(MetadataKey::Iv.as_str())
.ok_or_else(|| {
// IV is missing. The metadata of the encrypted content is invalid or corrupted.
Error::Other(box_err!("metadata {} not found",... | {
// Currently we only support aes256-gcm. A different method could mean the encrypted
// content is written by a future version of TiKV, and we don't know how to handle it.
// Fail immediately instead of fallback to previous key.
return Err(Error::Other(box_err!(
... | conditional_block |
mem.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::encryptionpb::EncryptedContent;
use super::metadata::*;
use crate::crypter::*;
use crate::{AesGcmCrypter, Error, Iv, Result};
/// An in-memory backend, it saves master key in memory.
pub(crate) struct MemAesGcmBackend {
pub key: Vec<... |
#[test]
fn test_mem_backend_authenticate() {
let pt = vec![1u8, 2, 3];
let key = Vec::from_hex("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
.unwrap();
let backend = MemAesGcmBackend::new(key).unwrap();
let encrypted_content = backend.encrypt_... | {
// See more http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip
let pt = Vec::from_hex("25431587e9ecffc7c37f8d6d52a9bc3310651d46fb0e3bad2726c8f2db653749")
.unwrap();
let ct = Vec::from_hex("84e5f23f95648fa247cb28eef53abec947dbf05ac953734618111583840bd980")
... | identifier_body |
mem.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::encryptionpb::EncryptedContent;
use super::metadata::*;
use crate::crypter::*;
use crate::{AesGcmCrypter, Error, Iv, Result};
/// An in-memory backend, it saves master key in memory.
pub(crate) struct MemAesGcmBackend {
pub key: Vec<... | let gcm_tag = AesGcmTag::from(tag.as_slice());
let ciphertext = content.get_content();
let plaintext = AesGcmCrypter::new(key, iv)
.decrypt(ciphertext, gcm_tag)
.map_err(|e|
// Decryption error, likely caused by mismatched tag. It could be the tag is
... | // Tag is missing. The metadata of the encrypted content is invalid or corrupted.
Error::Other(box_err!("gcm tag not found"))
})?; | random_line_split |
mem.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use kvproto::encryptionpb::EncryptedContent;
use super::metadata::*;
use crate::crypter::*;
use crate::{AesGcmCrypter, Error, Iv, Result};
/// An in-memory backend, it saves master key in memory.
pub(crate) struct MemAesGcmBackend {
pub key: Vec<... | (&self, plaintext: &[u8], iv: Iv) -> Result<EncryptedContent> {
let mut content = EncryptedContent::default();
content.mut_metadata().insert(
MetadataKey::Method.as_str().to_owned(),
MetadataMethod::Aes256Gcm.as_slice().to_vec(),
);
let iv_value = iv.as_slice().to... | encrypt_content | identifier_name |
003.rs | #![feature(slicing_syntax)]
extern crate test;
extern crate time;
| use std::os;
fn solution() -> u64 {
let mut n = 600_851_475_143;
for factor in iter::count(3, 2) {
while n % factor == 0 {
n /= factor;
}
if factor * factor > n {
return n;
} else if n == 1 {
return factor;
}
}
unreachable!(... | use std::io::stdio;
use std::iter; | random_line_split |
003.rs | #![feature(slicing_syntax)]
extern crate test;
extern crate time;
use std::io::stdio;
use std::iter;
use std::os;
fn solution() -> u64 {
let mut n = 600_851_475_143;
for factor in iter::count(3, 2) {
while n % factor == 0 {
n /= factor;
}
if factor * factor > n {
... | {
match os::args()[] {
[_, ref flag] if flag[] == "-a" => return println!("{}", solution()),
_ => {},
}
for line in stdio::stdin().lock().lines() {
let iters: u64 = line.unwrap()[].trim().parse().unwrap();
let start = time::precise_time_ns();
for _ in range(0, iters... | identifier_body | |
003.rs | #![feature(slicing_syntax)]
extern crate test;
extern crate time;
use std::io::stdio;
use std::iter;
use std::os;
fn solution() -> u64 {
let mut n = 600_851_475_143;
for factor in iter::count(3, 2) {
while n % factor == 0 {
n /= factor;
}
if factor * factor > n {
... | ,
}
for line in stdio::stdin().lock().lines() {
let iters: u64 = line.unwrap()[].trim().parse().unwrap();
let start = time::precise_time_ns();
for _ in range(0, iters) {
test::black_box(solution());
}
let end = time::precise_time_ns();
println!("{}"... | {} | conditional_block |
003.rs | #![feature(slicing_syntax)]
extern crate test;
extern crate time;
use std::io::stdio;
use std::iter;
use std::os;
fn solution() -> u64 {
let mut n = 600_851_475_143;
for factor in iter::count(3, 2) {
while n % factor == 0 {
n /= factor;
}
if factor * factor > n {
... | () {
match os::args()[] {
[_, ref flag] if flag[] == "-a" => return println!("{}", solution()),
_ => {},
}
for line in stdio::stdin().lock().lines() {
let iters: u64 = line.unwrap()[].trim().parse().unwrap();
let start = time::precise_time_ns();
for _ in range(0, it... | main | identifier_name |
zip.js | import gulp from 'gulp';
import path from 'path';
import runSequence from 'run-sequence';
import { spawn } from 'child_process';
const pkg = require('../package.json');
function zip(src, dest) {
const current_process = spawn('7z', ['a', '-tzip', dest, src], {cwd: './tmp'});
let is_error = false;
return new Pro... | return resolve();
});
});
}
function releaseFile(platform) {
return `Championify-${platform}-${pkg.version}.zip`;
}
gulp.task('zip:osx', function(cb) {
const src = `${pkg.name}.app`;
const dest = path.join('../releases', releaseFile('OSX'));
return zip(src, dest, cb);
});
gulp.task('zip:win', fun... | random_line_split | |
zip.js | import gulp from 'gulp';
import path from 'path';
import runSequence from 'run-sequence';
import { spawn } from 'child_process';
const pkg = require('../package.json');
function zip(src, dest) {
const current_process = spawn('7z', ['a', '-tzip', dest, src], {cwd: './tmp'});
let is_error = false;
return new Pro... | (platform) {
return `Championify-${platform}-${pkg.version}.zip`;
}
gulp.task('zip:osx', function(cb) {
const src = `${pkg.name}.app`;
const dest = path.join('../releases', releaseFile('OSX'));
return zip(src, dest, cb);
});
gulp.task('zip:win', function(cb) {
const src = pkg.name;
const dest = path.join(... | releaseFile | identifier_name |
zip.js | import gulp from 'gulp';
import path from 'path';
import runSequence from 'run-sequence';
import { spawn } from 'child_process';
const pkg = require('../package.json');
function zip(src, dest) {
const current_process = spawn('7z', ['a', '-tzip', dest, src], {cwd: './tmp'});
let is_error = false;
return new Pro... |
gulp.task('zip:osx', function(cb) {
const src = `${pkg.name}.app`;
const dest = path.join('../releases', releaseFile('OSX'));
return zip(src, dest, cb);
});
gulp.task('zip:win', function(cb) {
const src = pkg.name;
const dest = path.join('../releases', releaseFile('WIN'));
return zip(src, dest, cb);
});
... | {
return `Championify-${platform}-${pkg.version}.zip`;
} | identifier_body |
bpf_base.rs | use crate::abi::Endian;
use crate::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, TargetOptions};
pub fn opts(endian: Endian) -> TargetOptions | {
TargetOptions {
allow_asm: true,
endian,
linker_flavor: LinkerFlavor::BpfLinker,
atomic_cas: false,
executables: true,
dynamic_linking: true,
no_builtins: true,
panic_strategy: PanicStrategy::Abort,
position_independent_executables: true,
... | identifier_body | |
bpf_base.rs | use crate::abi::Endian;
use crate::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, TargetOptions};
pub fn opts(endian: Endian) -> TargetOptions {
TargetOptions {
allow_asm: true,
endian,
linker_flavor: LinkerFlavor::BpfLinker,
atomic_cas: false,
executables: true, | no_builtins: true,
panic_strategy: PanicStrategy::Abort,
position_independent_executables: true,
// Disable MergeFunctions since:
// - older kernels don't support bpf-to-bpf calls
// - on newer kernels, userspace still needs to relocate before calling
// BPF_PRO... | dynamic_linking: true, | random_line_split |
bpf_base.rs | use crate::abi::Endian;
use crate::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, TargetOptions};
pub fn | (endian: Endian) -> TargetOptions {
TargetOptions {
allow_asm: true,
endian,
linker_flavor: LinkerFlavor::BpfLinker,
atomic_cas: false,
executables: true,
dynamic_linking: true,
no_builtins: true,
panic_strategy: PanicStrategy::Abort,
position_... | opts | identifier_name |
XMLControl.py | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import xml.etree.ElementTree
from xml.etree.cElementTree import ElementTree, Element, SubElement
from xml.etree.cElementTree import fromstring, tostring
import ... | def __init__(self, parent):
fsui.TextArea.__init__(self, parent, horizontal_scroll=True)
self.path = ""
def connect_game(self, info):
tree = self.get_tree()
root = tree.getroot()
if not root.tag == "config":
return
game_node = self.find_or_create_node... | random_line_split | |
XMLControl.py | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import xml.etree.ElementTree
from xml.etree.cElementTree import ElementTree, Element, SubElement
from xml.etree.cElementTree import fromstring, tostring
import ... |
def load_xml(self, path):
with open(path, "rb") as f:
data = f.read()
self.set_text(data)
def save(self):
if not self.path:
print("no path to save XML to")
return
self.save_xml(self.path)
def save_xml(self, path):
self.get_t... | data = tostring(tree.getroot(), encoding="UTF-8").decode("UTF-8")
std_decl = "<?xml version='1.0' encoding='UTF-8'?>"
if data.startswith(std_decl):
data = data[len(std_decl):].strip()
self.set_text(data) | identifier_body |
XMLControl.py | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import xml.etree.ElementTree
from xml.etree.cElementTree import ElementTree, Element, SubElement
from xml.etree.cElementTree import fromstring, tostring
import ... |
def get_tree(self):
text = self.get_text().strip()
try:
root = fromstring(text.encode("UTF-8"))
except Exception:
# FIXME: show message
import traceback
traceback.print_exc()
return
tree = ElementTree(root)
indent_... | self.set_text("") | conditional_block |
XMLControl.py | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import xml.etree.ElementTree
from xml.etree.cElementTree import ElementTree, Element, SubElement
from xml.etree.cElementTree import fromstring, tostring
import ... | (self, tree):
data = tostring(tree.getroot(), encoding="UTF-8").decode("UTF-8")
std_decl = "<?xml version='1.0' encoding='UTF-8'?>"
if data.startswith(std_decl):
data = data[len(std_decl):].strip()
self.set_text(data)
def load_xml(self, path):
with open(path, "rb... | set_tree | identifier_name |
emberTemplates.js | module.exports = {
options: {
templateCompilerPath: 'bower_components/ember/ember-template-compiler.js',
handlebarsPath: 'bower_components/handlebars/handlebars.js',
preprocess: function (source) {
return source.replace(/\s+/g, ' ');
},
templateName: function (sourceFile) {
/*
These are how templa... |
else {
templateName = prefix + fileName;
}
console.log('Compiling ' + sourceFile.blue + ' to ' + templateName.green);
return templateName;
}
},
compile: {
files: {
'tmp/compiled-templates.js': ['templates/**/*.{hbs,handlebars}', 'app/**/*.{hbs,handlebars}']
}
}
};
| {
if (fileName === moduleName) {
templateName = moduleName;
}
else {
templateName = moduleName + '/' + prefix + fileName;
}
} | conditional_block |
emberTemplates.js | module.exports = {
options: {
templateCompilerPath: 'bower_components/ember/ember-template-compiler.js',
handlebarsPath: 'bower_components/handlebars/handlebars.js',
preprocess: function (source) {
return source.replace(/\s+/g, ' ');
},
templateName: function (sourceFile) {
/*
These are how templa... | }
},
compile: {
files: {
'tmp/compiled-templates.js': ['templates/**/*.{hbs,handlebars}', 'app/**/*.{hbs,handlebars}']
}
}
}; |
console.log('Compiling ' + sourceFile.blue + ' to ' + templateName.green);
return templateName; | random_line_split |
test_input.py | #!/usr/bin/env python
# Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# *... | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
class TestInput(object):
"""Groups information about a test for easy passing of data."""
def __i... | # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | random_line_split |
test_input.py | #!/usr/bin/env python
# Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# *... | (self, test_name, timeout):
"""Holds the input parameters for a test.
Args:
test: name of test (not an absolute path!)
timeout: Timeout in msecs the driver should use while running the test
"""
self.test_name = test_name
self.timeout = timeout
# Tes... | __init__ | identifier_name |
test_input.py | #!/usr/bin/env python
# Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# *... | return "TestInput('%s', %d, %s, %s)" % (self.test_name, self.timeout, self.should_run_pixel_tests, self.reference_files) | identifier_body | |
lib.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 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 F... |
#[macro_use] extern crate libimagstore;
extern crate libimagerror;
extern crate libimagutil;
module_entry_path_mod!("links");
pub mod iter;
pub mod linkable;
pub mod link;
pub mod storecheck; |
#[cfg(test)]
extern crate env_logger; | random_line_split |
types.pre.rs | use std::{fmt, str};
#[derive(Debug)]
pub struct Machine<'a> {
pub memory: CambridgeArray<'a, u8>,
pub output: UTF8Wrapper<'a>,
#ifdef PROFILE
pub trace: ProfileShim,
#endif
}
pub struct CambridgeArray<'a, T: 'a>(pub &'a [T]); // Cambridge is Oxford's rival
pub struct UTF8Wrapper<'a>(pub &'a [u8]);
#ifde... | (pub fn() -> Profile);
#endif
impl<'a, T: fmt::Display> fmt::Debug for CambridgeArray<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "["));
if self.0.len() > 0 {
for e in &self.0[..] {
try!(write!(f, " {}", e));
}
}
... | ProfileShim | identifier_name |
types.pre.rs | use std::{fmt, str};
#[derive(Debug)]
pub struct Machine<'a> {
pub memory: CambridgeArray<'a, u8>,
pub output: UTF8Wrapper<'a>,
#ifdef PROFILE
pub trace: ProfileShim,
#endif
}
pub struct CambridgeArray<'a, T: 'a>(pub &'a [T]); // Cambridge is Oxford's rival
pub struct UTF8Wrapper<'a>(pub &'a [u8]);
#ifde... |
write!(f, " ]")
}
}
impl<'a> fmt::Debug for UTF8Wrapper<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "\n{}", try!(str::from_utf8(self.0).map_err(|_| fmt::Error)))
}
}
#ifdef PROFILE
#[derive(Debug, Default)]
pub struct Profile {
pub instructions: u32,
pub ... | {
for e in &self.0[..] {
try!(write!(f, " {}", e));
}
} | conditional_block |
types.pre.rs | use std::{fmt, str};
#[derive(Debug)]
pub struct Machine<'a> {
pub memory: CambridgeArray<'a, u8>,
pub output: UTF8Wrapper<'a>,
#ifdef PROFILE
pub trace: ProfileShim,
#endif
}
pub struct CambridgeArray<'a, T: 'a>(pub &'a [T]); // Cambridge is Oxford's rival
pub struct UTF8Wrapper<'a>(pub &'a [u8]);
#ifde... |
}
#ifdef PROFILE
#[derive(Debug, Default)]
pub struct Profile {
pub instructions: u32,
pub increments: u32, pub decrements: u32, pub overflows: u32, pub underflows: u32,
pub lefts: u32, pub rights: u32, pub left_grows: u32, pub right_grows: u32,
pub ins: u32, pub in_revconvs: u32, pub in_unaries: u32,... | {
write!(f, "\n{}", try!(str::from_utf8(self.0).map_err(|_| fmt::Error)))
} | identifier_body |
types.pre.rs | use std::{fmt, str};
#[derive(Debug)]
pub struct Machine<'a> {
pub memory: CambridgeArray<'a, u8>,
pub output: UTF8Wrapper<'a>,
#ifdef PROFILE
pub trace: ProfileShim,
#endif
}
| #ifdef PROFILE
pub struct ProfileShim(pub fn() -> Profile);
#endif
impl<'a, T: fmt::Display> fmt::Debug for CambridgeArray<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "["));
if self.0.len() > 0 {
for e in &self.0[..] {
try!(write!(f, " ... | pub struct CambridgeArray<'a, T: 'a>(pub &'a [T]); // Cambridge is Oxford's rival
pub struct UTF8Wrapper<'a>(pub &'a [u8]); | random_line_split |
Input.d.ts | type InputType =
| 'text'
| 'email'
| 'select'
| 'file'
| 'radio'
| 'checkbox'
| 'textarea'
| 'button'
| 'reset'
| 'submit'
| 'date'
| 'datetime-local'
| 'hidden'
| 'image'
| 'month'
| 'number'
| 'range'
| 'search'
| 'tel'
| 'url'
| 'week'
| 'password'
| 'datetime'
| 'tim... | declare var Input: React.StatelessComponent<InputProps>;
export default Input; | random_line_split | |
base.py | import numpy as np
from tfs.core.util import run_once_for_each_obj
from tfs.core.initializer import DefaultInit
from tfs.core.loss import DefaultLoss
from tfs.core.regularizers import DefaultRegularizer
from tfs.core.monitor import DefaultMonitor
from tfs.core.optimizer import DefaultOptimizer
from tfs.core.layer impor... | (self,X,y,step):
self.run(self.train_op,feed_dict={self.input:X,self.true_output:y})
def predict(self,X):
if self.num_gpu==0:
_in = self.input
_out = self.output
else:
_in = self.input[0]
_out = self.output[0]
return self.run(_out,feed_dict={_in:X})
def eval_node_input(self... | step | identifier_name |
base.py | import numpy as np
from tfs.core.util import run_once_for_each_obj
from tfs.core.initializer import DefaultInit
from tfs.core.loss import DefaultLoss
from tfs.core.regularizers import DefaultRegularizer
from tfs.core.monitor import DefaultMonitor
from tfs.core.optimizer import DefaultOptimizer
from tfs.core.layer impor... | def _func(input_vals):
feed = {t:v in zip(input_vals,input_tensors)}
return self.run(output_tensors,feed_dict=feed)
return _func
def score(self,datasubset):
y_pred = self.predict(datasubset.data)
y_pred = np.argmax(y_pred,1)
y_true = datasubset.labels
y_true = np.argmax(y_true,1)
... |
def function(self,input_tensors,output_tensors): | random_line_split |
base.py | import numpy as np
from tfs.core.util import run_once_for_each_obj
from tfs.core.initializer import DefaultInit
from tfs.core.loss import DefaultLoss
from tfs.core.regularizers import DefaultRegularizer
from tfs.core.monitor import DefaultMonitor
from tfs.core.optimizer import DefaultOptimizer
from tfs.core.layer impor... |
return '\n'.join(info)
@with_graph
@run_once_for_each_obj
def build(self,input_shape,dtype=tf.float32):
self._dtype = dtype
"""Build the computational graph
inTensor: the network input tensor.
"""
if not self.num_gpu:
self._build(input_shape,dtype)
else:
tower_grads = []
... | s = '%-20s@%20s'%(n.name,n.device)
if hasattr(n,'tfs_nodename'):
s=s+' --%s'%n.tfs_nodename
info.append(s) | conditional_block |
base.py | import numpy as np
from tfs.core.util import run_once_for_each_obj
from tfs.core.initializer import DefaultInit
from tfs.core.loss import DefaultLoss
from tfs.core.regularizers import DefaultRegularizer
from tfs.core.monitor import DefaultMonitor
from tfs.core.optimizer import DefaultOptimizer
from tfs.core.layer impor... |
def _compute_loss(self,idx):
loss = self.losser.compute(idx)
if loss is None:
return loss
return loss + self.regularizer.compute()
@property
def loss(self):
return self._loss
def build_variables_table(self):
for l in self.net_def:
for k in l.variables:
v = l.variable... | self.run_initor(self.initializer) | identifier_body |
models.py | #!/usr/bin/python
#
# Copyright 2010 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 ag... |
class QuestionModel(QuizBaseModel):
"""Represents a question.
Attributes:
body: Text asscociated with quiz.
choices: List of possible choices.
shuffle_choices: If set choices are randomly shuffled.
hints: Ordered list of progressive hints
"""
# implicit id
body = db.TextProperty()
choi... | """Dumps choice to a dictionary for passing around as JSON object."""
data_dict = {'body': self.body,
'id': str(self.key())}
return data_dict | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.