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 |
|---|---|---|---|---|
prepare.js | const path = require('path');
const inquirer = require('inquirer');
const yargs = require('yargs');
const {
sanitizeArgs,
ui,
invalidGitRepo,
ingredients,
addIngredients,
promiseTimeout
} = require('../common');
const {
cloneRepo,
deleteGitFolder,
establishLocalGitBindings,
addGitRemote,
pushLoca... |
return true;
});
let projectIngredients = await inquirer.prompt(baseIngredients);
projectIngredients = Object.assign(projectIngredients, args);
projectIngredients.projectName = await checkForExistingFolder(
ui,
projectIngredients.projectName
);
// Check if ... | {
return false;
} | conditional_block |
prepare.js | const path = require('path');
const inquirer = require('inquirer');
const yargs = require('yargs');
const {
sanitizeArgs,
ui,
invalidGitRepo,
ingredients,
addIngredients,
promiseTimeout
} = require('../common');
const {
cloneRepo,
deleteGitFolder,
establishLocalGitBindings,
addGitRemote,
pushLoca... | await addGitRemote(
ui,
projectIngredients.gitOriginURL,
projectIngredients.projectName
);
}
if (recipe.icing && Array.isArray(recipe.icing)) {
ui.log.write(`. Applying icing...`);
let projectDir = path.join(
process.cwd(),
`... | });
if (projectIngredients.gitOriginURL) { | random_line_split |
GroupModal.tsx | import { useState } from 'react';
import { c } from 'ttag';
import { Checkbox, FormModal, generateUID, Label } from '@proton/components';
import { ContactEmail } from '@proton/shared/lib/interfaces/contacts';
import { contactToInput } from '@proton/shared/lib/mail/recipient';
import { RecipientGroup } from '../../../mo... | onSubmit={onClose}
onClose={onClose}
{...rest}
>
<ul className="unstyled">
{contacts.map((contact) => {
const id = `${uid}-${contact.ID}`;
const icon = globalIcon || (mapStatusIcons ? mapStatusIcons[contact.E... | submit={c('Action').t`Close`}
close={null} | random_line_split |
game_manager.js | function GameManager(size, InputManager, Actuator, StorageManager) {
this.size = size; // Size of the grid
this.inputManager = new InputManager;
this.storageManager = new StorageManager;
this.actuator = new Actuator;
this.startTiles = 2;
this.inputManager.on("move", this.move.bind(th... | // Get the vector representing the chosen direction
GameManager.prototype.getVector = function (direction) {
// Vectors representing tile movement
var map = {
0: { x: 0, y: -1 }, // Up
1: { x: 1, y: 0 }, // Right
2: { x: 0, y: 1 }, // Down
3: { x: -1, y: 0 } // Left
};
return map[directi... |
this.actuate();
}
};
| random_line_split |
game_manager.js | function GameManager(size, InputManager, Actuator, StorageManager) |
// Restart the game
GameManager.prototype.restart = function () {
this.storageManager.clearGameState();
this.actuator.continueGame(); // Clear the game won/lost message
this.setup();
};
// Keep playing after winning (allows going over 2048)
GameManager.prototype.keepPlaying = function () {
this.keepPlaying =... | {
this.size = size; // Size of the grid
this.inputManager = new InputManager;
this.storageManager = new StorageManager;
this.actuator = new Actuator;
this.startTiles = 2;
this.inputManager.on("move", this.move.bind(this));
this.inputManager.on("restart", this.restart.bind(this));
... | identifier_body |
game_manager.js | function GameManager(size, InputManager, Actuator, StorageManager) {
this.size = size; // Size of the grid
this.inputManager = new InputManager;
this.storageManager = new StorageManager;
this.actuator = new Actuator;
this.startTiles = 2;
this.inputManager.on("move", this.move.bind(th... | else {
this.storageManager.setGameState(this.serialize());
}
this.actuator.actuate(this.grid, {
score: this.score,
over: this.over,
won: this.won,
bestScore: this.storageManager.getBestScore(),
terminated: this.isGameTerminated()
});
};
// Represent the current game ... | {
this.storageManager.clearGameState();
} | conditional_block |
game_manager.js | function | (size, InputManager, Actuator, StorageManager) {
this.size = size; // Size of the grid
this.inputManager = new InputManager;
this.storageManager = new StorageManager;
this.actuator = new Actuator;
this.startTiles = 2;
this.inputManager.on("move", this.move.bind(this));
this.inputMa... | GameManager | identifier_name |
example.ts |
/**
* debug.js - This is a simple script that is used for debugging purposes only.
*/
import {Storm, RandomFloat, IStormRecord, ISynthesizer, BaseSynthesizer} from './storm';
import {sort, shuffle, random} from './utils/array';
const sparkly = require('sparkly');
// The equation we are trying to optimize!
const q... |
// Invert the absolute results (closer to zero is the goal)
return 1 / Math.abs(record.result);
}
});
let startTime = Date.now();
console.log('Starting new simulation...');
storm
.start()
.then(results => {
let duration = Date.now() - startTime;
let maxChart: number[] = [];
let avgChart: ... | {
return 0;
} | conditional_block |
example.ts | /**
* debug.js - This is a simple script that is used for debugging purposes only.
*/
import {Storm, RandomFloat, IStormRecord, ISynthesizer, BaseSynthesizer} from './storm';
import {sort, shuffle, random} from './utils/array';
const sparkly = require('sparkly');
// The equation we are trying to optimize!
const qu... |
storm
.start()
.then(results => {
let duration = Date.now() - startTime;
let maxChart: number[] = [];
let avgChart: number[] = [];
let i = 1;
let check = results.totalGenerations / 40;
results.generations.filter(g => i++ % check === 0).forEach(g => {
//console.log(`Gen ${g.id}: M... | });
let startTime = Date.now();
console.log('Starting new simulation...'); | random_line_split |
locale_ru.js | /* | This software is allowed to use under GPL or you need to obtain Commercial or Enterise License
to use it in not GPL project. Please contact sales@dhtmlx.com for details
*/
scheduler.locale={
date:{
month_full:["Январь", "Февраль", "Март", "Апрель", "Maй", "Июнь", "Июль", "Август", "Сентябрь", "Oктябрь", "Ноябрь", "Д... | random_line_split | |
server_pg.py | import datetime
import json
import os
import psycopg2 as dbapi2
import re
from flask import Flask
from flask import redirect
from flask import render_template
from flask.helpers import url_for
app = Flask(__name__)
def get_elephantsql_dsn(vcap_services):
"""Returns the data source name for Elep... |
else:
app.config['dsn'] = """user='vagrant' password='vagrant'
host='localhost' port=5432 dbname='itucsdb'"""
app.run(host='0.0.0.0', port=port, debug=debug)
| app.config['dsn'] = get_elephantsql_dsn(VCAP_SERVICES) | conditional_block |
server_pg.py | import datetime
import json
import os
import psycopg2 as dbapi2
import re
from flask import Flask
from flask import redirect
from flask import render_template
from flask.helpers import url_for
app = Flask(__name__)
def get_elephantsql_dsn(vcap_services):
"""Returns the data source name for Elep... | return render_template('home.html', current_time=now.ctime())
@app.route('/initdb')
def initialize_database():
with dbapi2.connect(app.config['dsn']) as connection:
cursor = connection.cursor()
query = """DROP TABLE IF EXISTS COUNTER"""
cursor.execute(query)
query ... | now = datetime.datetime.now()
| random_line_split |
server_pg.py | import datetime
import json
import os
import psycopg2 as dbapi2
import re
from flask import Flask
from flask import redirect
from flask import render_template
from flask.helpers import url_for
app = Flask(__name__)
def get_elephantsql_dsn(vcap_services):
"""Returns the data source name for Elep... |
@app.route('/count')
def counter_page():
with dbapi2.connect(app.config['dsn']) as connection:
cursor = connection.cursor()
query = "UPDATE COUNTER SET N = N + 1"
cursor.execute(query)
connection.commit()
query = "SELECT N FROM COUNTER"
cursor.execut... | with dbapi2.connect(app.config['dsn']) as connection:
cursor = connection.cursor()
query = """DROP TABLE IF EXISTS COUNTER"""
cursor.execute(query)
query = """CREATE TABLE COUNTER (N INTEGER)"""
cursor.execute(query)
query = """INSERT INTO COUNTER (N) VALUES (... | identifier_body |
server_pg.py | import datetime
import json
import os
import psycopg2 as dbapi2
import re
from flask import Flask
from flask import redirect
from flask import render_template
from flask.helpers import url_for
app = Flask(__name__)
def get_elephantsql_dsn(vcap_services):
"""Returns the data source name for Elep... | ():
with dbapi2.connect(app.config['dsn']) as connection:
cursor = connection.cursor()
query = "UPDATE COUNTER SET N = N + 1"
cursor.execute(query)
connection.commit()
query = "SELECT N FROM COUNTER"
cursor.execute(query)
count = cursor.fetchone()[... | counter_page | identifier_name |
webgluniformlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUn... | (&self) -> i32 {
self.id
}
pub fn program_id(&self) -> WebGLProgramId {
self.program_id
}
}
| id | identifier_name |
webgluniformlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUn... |
pub fn id(&self) -> i32 {
self.id
}
pub fn program_id(&self) -> WebGLProgramId {
self.program_id
}
}
| {
reflect_dom_object(box WebGLUniformLocation::new_inherited(id, program_id),
global,
WebGLUniformLocationBinding::Wrap)
} | identifier_body |
blockly.js | /*jshint esversion: 6 */
import Service from '@ember/service';
export default Service.extend({
createCustomBlock(name, options, callback_to_change_block) {
options.colour = options.colour || '#4453ff';
if (Blockly.Blocks[name]) {
//console.warn(`Redefiniendo el bloque ${name}`);
}
Blockly.Bl... | ,
createAlias(new_name, original_block_name) {
let original_block = Blockly.Blocks[original_block_name];
Blockly.Blocks[new_name] = Object.assign({}, original_block);
let new_block = Blockly.Blocks[new_name];
new_block.isCustomBlock = true;
new_block.aliases = [original_block_name];
if (!or... | {
return Object.keys(Blockly.Blocks).filter((e) => {
return Blockly.Blocks[e].isCustomBlock;
}
);
} | identifier_body |
blockly.js | /*jshint esversion: 6 */
import Service from '@ember/service';
export default Service.extend({
createCustomBlock(name, options, callback_to_change_block) { | options.colour = options.colour || '#4453ff';
if (Blockly.Blocks[name]) {
//console.warn(`Redefiniendo el bloque ${name}`);
}
Blockly.Blocks[name] = {
init: function () {
this.jsonInit(options);
if (callback_to_change_block) {
callback_to_change_block.call(this);... | random_line_split | |
blockly.js | /*jshint esversion: 6 */
import Service from '@ember/service';
export default Service.extend({
createCustomBlock(name, options, callback_to_change_block) {
options.colour = options.colour || '#4453ff';
if (Blockly.Blocks[name]) {
//console.warn(`Redefiniendo el bloque ${name}`);
}
Blockly.Bl... |
if (options.code) {
Blockly.MyLanguage[name] = function (block) {
let variables = options.code.match(/\$(\w+)/g);
let code = options.code;
if (variables) {
variables.forEach((v) => {
let regex = new RegExp('\\' + v, "g");
let variable_name = v.slice... | {
Blockly.MyLanguage = Blockly.JavaScript;
} | conditional_block |
blockly.js | /*jshint esversion: 6 */
import Service from '@ember/service';
export default Service.extend({
createCustomBlock(name, options, callback_to_change_block) {
options.colour = options.colour || '#4453ff';
if (Blockly.Blocks[name]) {
//console.warn(`Redefiniendo el bloque ${name}`);
}
Blockly.Bl... | (state) {
Blockly.BlockSvg.START_HAT = state;
}
});
| setStartHat | identifier_name |
build.d.ts | import { MinifyOptions as TerserOptions } from "terser";
import { Configuration as WebpackConfiguration } from "webpack";
import { BundleAnalyzerPlugin } from "webpack-bundle-analyzer";
import * as WebpackChain from "webpack-chain";
import { DefinedDefaultAlgorithmAndOptions } from "compression-webpack-plugin";
import ... | * Can use async/await or directly return a Promise.
*/
afterDev?: (params: QuasarHookParams) => void;
/**
* Run hook before Quasar builds app for production (`$ quasar build`).
* At this point, the distributables folder hasn’t been created yet.
* Can use async/await or directly return a Promise.
*... | * At this point, the dev server has been started and is available should you wish to do something with it. | random_line_split |
tracking.js | * tracking.base(this, a, b);
* }
* tracking.inherits(ChildClass, ParentClass);
*
* var child = new ChildClass('a', 'b', 'c');
* child.foo();
* </pre>
*
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
*/
tracking.inherits = function(childCtor, pa... |
TempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new TempCtor();
childCtor.prototype.constructor = childCtor;
/**
* Calls superclass constructor/method.
*
* This function is only available if you use tracking.inherits to ... | {
} | identifier_body |
tracking.js | * tracking.base(this, a, b);
* }
* tracking.inherits(ChildClass, ParentClass);
*
* var child = new ChildClass('a', 'b', 'c');
* child.foo();
* </pre>
*
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
*/
tracking.inherits = function(childCtor, ... | * `tracker.track(pixels, width, height)` will be in a
* `requestAnimationFrame` loop in order to track all video frames.
*
* Example:
* var tracker = new tracking.ColorTracker();
*
* tracking.track('#video', tracker);
* or
* tracking.track('#video', tracker, { camera: true });
*
* track... | * to pass to the `tracker` instance. When tracking a video, the | random_line_split |
tracking.js | * tracking.base(this, a, b);
* }
* tracking.inherits(ChildClass, ParentClass);
*
* var child = new ChildClass('a', 'b', 'c');
* child.foo();
* </pre>
*
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
*/
tracking.inherits = function(childCtor, pa... |
if (!tracker) {
throw new Error('Tracker not specified, try `tracking.track(element, new tracking.FaceTracker())`.');
}
switch (element.nodeName.toLowerCase()) {
case 'canvas':
return this.trackCanvas_(element, tracker, opt_options);
case 'img':
return this.trackImg_(elem... | {
throw new Error('Element not found, try a different element or selector.');
} | conditional_block |
tracking.js | * tracking.base(this, a, b);
* }
* tracking.inherits(ChildClass, ParentClass);
*
* var child = new ChildClass('a', 'b', 'c');
* child.foo();
* </pre>
*
* @param {Function} childCtor Child class.
* @param {Function} parentCtor Parent class.
*/
tracking.inherits = function(childCtor, pa... | () {
}
TempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new TempCtor();
childCtor.prototype.constructor = childCtor;
/**
* Calls superclass constructor/method.
*
* This function is only available if you use tracking.in... | TempCtor | identifier_name |
cscript.test.js | /* eslint-disable consistent-this */
var cscript = require('../lib/cscript.js')
describe('cscript', function() {
var mockFs, mockExecFile
it('must be initialized', function() {
(function() {
cscript.path()
}).should.throw('must initialize first')
}) | mockExecFile['cscript.exe'].stdout = cscript.CSCRIPT_EXPECTED_OUTPUT
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['cscript.exe'].args[0].should.eql('cscript.exe')
done()
})
})
it('initializes only once', function(do... |
it('if cscript.exe is successfully spawned then no more checks are conducted', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0) | random_line_split |
cscript.test.js | /* eslint-disable consistent-this */
var cscript = require('../lib/cscript.js')
describe('cscript', function() {
var mockFs, mockExecFile
it('must be initialized', function() {
(function() {
cscript.path()
}).should.throw('must initialize first')
})
it('if cscript.exe is successfully spawned then no more... |
setImmediate(function() {
callback(mockExecFile[command].err, mockExecFile[command].stdout, mockExecFile[command].stderr)
})
}
mockExecFile['cscript.exe'] = { calls: 0, stdout: '', stderr: '', err: null }
mockExecFile['where cscript.exe'] = { calls: 0, stdout: '', stderr: '', err: null }
cscript._... | {
throw new Error('missing callback')
} | conditional_block |
index.js | /**
* Entrypoint for the react app
* Provides a basic app wrapper for react
* @author Fabian Beuke <mail@beuke.org>
* @license AGPL-3.0
*/
import { HashRouter } from "react-router-dom";
import Layout from "components/Layout"
import { getMaxDataDate } from "common/utils.js"
import { hydrate, render } from "react-d... | main() | }
| random_line_split |
index.js | /**
* Entrypoint for the react app
* Provides a basic app wrapper for react
* @author Fabian Beuke <mail@beuke.org>
* @license AGPL-3.0
*/
import { HashRouter } from "react-router-dom";
import Layout from "components/Layout"
import { getMaxDataDate } from "common/utils.js"
import { hydrate, render } from "react-d... |
const rootElement = document.getElementById("root")
if (rootElement.hasChildNodes()) {
hydrate(
<HashRouter>
<Layout />
</HashRouter>,
document.getElementById("root")
)
} else {
render(
<HashRouter>
<La... | {
window.history.pushState("", "", url)
} | conditional_block |
helper.py | import datetime
import io
import logging
import logging.handlers
import os
import sys
from collections import deque
from time import perf_counter
import colorlog
class LogHelper:
FORMATTER_COLOR = colorlog.ColoredFormatter('{log_color}{asctime} {name}: {levelname} {message}', style='{')
FORMATTER = logging.F... | (self):
return self.stream.getvalue()
| __str__ | identifier_name |
helper.py | import datetime
import io
import logging
import logging.handlers
import os
import sys
from collections import deque
from time import perf_counter
import colorlog
class LogHelper:
FORMATTER_COLOR = colorlog.ColoredFormatter('{log_color}{asctime} {name}: {levelname} {message}', style='{')
FORMATTER = logging.F... |
def __call__(self, *args, **kwargs):
print(*args, file=self.stream, **kwargs)
def __str__(self):
return self.stream.getvalue()
| if not stream:
stream = io.StringIO()
self.stream = stream | identifier_body |
helper.py | import datetime
import io
import logging
import logging.handlers
import os
import sys
from collections import deque
from time import perf_counter
import colorlog
class LogHelper:
FORMATTER_COLOR = colorlog.ColoredFormatter('{log_color}{asctime} {name}: {levelname} {message}', style='{')
FORMATTER = logging.F... |
@classmethod
def get_script_name(cls):
script_name = os.path.basename(sys.argv[0])
script_name, _ = os.path.splitext(script_name)
return script_name
@classmethod
def generate_simple_rotating_file_handler(cls, path_log_file=None, when='midnight', files_count=7):
if path... | def generate_color_handler(cls, stream=sys.stdout):
handler = logging.StreamHandler(stream)
handler.setFormatter(cls.FORMATTER_COLOR)
return handler | random_line_split |
helper.py | import datetime
import io
import logging
import logging.handlers
import os
import sys
from collections import deque
from time import perf_counter
import colorlog
class LogHelper:
FORMATTER_COLOR = colorlog.ColoredFormatter('{log_color}{asctime} {name}: {levelname} {message}', style='{')
FORMATTER = logging.F... |
class PerformanceMetric:
def __init__(self, *, n_samples=1000, units_suffix='', units_format='.2f', name=None):
super().__init__()
self.name: str = name
self.queue_samples = deque(maxlen=n_samples)
self.total = 0
self.last = 0
self.units_str = units_suffix
... | return time.strftime('%Y%m%d_%H%M%S') | conditional_block |
string_eval.py | import sys
from pathlib import Path
from analysis.PluginBase import AnalysisBasePlugin
from plugins.mime_blacklists import MIME_BLACKLIST_COMPRESSED
try:
from ..internal.string_eval import eval_strings
except ImportError:
sys.path.append(str(Path(__file__).parent.parent / 'internal'))
from string_eval imp... | (AnalysisBasePlugin):
'''
Sort strings by relevance
Credits:
Original version by Paul Schiffer created during Firmware Bootcamp WT16/17 at University of Bonn
Refactored and improved by Fraunhofer FKIE
'''
NAME = 'string_evaluator'
DEPENDENCIES = ['printable_strings']
MIME_BLACKLIST ... | AnalysisPlugin | identifier_name |
string_eval.py | import sys
from pathlib import Path
from analysis.PluginBase import AnalysisBasePlugin
from plugins.mime_blacklists import MIME_BLACKLIST_COMPRESSED
try:
from ..internal.string_eval import eval_strings
except ImportError:
sys.path.append(str(Path(__file__).parent.parent / 'internal'))
from string_eval imp... | '''
Sort strings by relevance
Credits:
Original version by Paul Schiffer created during Firmware Bootcamp WT16/17 at University of Bonn
Refactored and improved by Fraunhofer FKIE
'''
NAME = 'string_evaluator'
DEPENDENCIES = ['printable_strings']
MIME_BLACKLIST = MIME_BLACKLIST_COMPRESSE... | identifier_body | |
string_eval.py | import sys
from pathlib import Path
from analysis.PluginBase import AnalysisBasePlugin
from plugins.mime_blacklists import MIME_BLACKLIST_COMPRESSED
try:
from ..internal.string_eval import eval_strings
except ImportError:
sys.path.append(str(Path(__file__).parent.parent / 'internal'))
from string_eval imp... | file_object.processed_analysis[self.NAME] = dict(string_eval=eval_strings(list_of_printable_strings))
return file_object | def __init__(self, plugin_administrator, config=None, recursive=True, timeout=300):
super().__init__(plugin_administrator, config=config, recursive=recursive, timeout=timeout, plugin_path=__file__)
def process_object(self, file_object):
list_of_printable_strings = file_object.processed_analysis... | random_line_split |
babel-preset-stage-0_vx.x.x.js | // flow-typed signature: 715c8753230e19bbaff4d8c2ee503f1a
// flow-typed version: <<STUB>>/babel-preset-stage-0_v^6.22.0/flow_v0.47.0
/**
* This is an autogenerated libdef stub for:
*
* 'babel-preset-stage-0'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to shar... | declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'babel-preset-stage-0/lib/index' {
declare module.exports: any;
}
// Filename aliases
declare mo... | * community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'babel-preset-stage-0' { | random_line_split |
analytics.ts | import { element } from 'angular';
import {localStorageAvailable} from '../utils/local-storage';
export default function(app) {
app.service('analyticsService', class AnalyticsService {
routeChanged = false;
enabled = false;
askForConsent = false;
gaElement: JQLite;
static $inject = ['$analytics... |
});
}
| {
if (!this.enabled) return;
this.$analytics.setOptOut(true);
this.enabled = false;
if (localStorageAvailable) {
this.$window.localStorage.analyticsEnabled = false;
}
} | identifier_body |
analytics.ts | import { element } from 'angular';
import {localStorageAvailable} from '../utils/local-storage';
export default function(app) {
app.service('analyticsService', class AnalyticsService {
routeChanged = false;
enabled = false;
askForConsent = false;
gaElement: JQLite;
static $inject = ['$analytics... | () {
if (!this.enabled) return;
this.$analytics.setOptOut(true);
this.enabled = false;
if (localStorageAvailable) {
this.$window.localStorage.analyticsEnabled = false;
}
}
});
}
| disable | identifier_name |
analytics.ts | import { element } from 'angular';
import {localStorageAvailable} from '../utils/local-storage';
export default function(app) { | enabled = false;
askForConsent = false;
gaElement: JQLite;
static $inject = ['$analytics', '$document', '$location', '$rootScope', '$window'];
constructor(public $analytics, public $document, public $location, public $rootScope, public $window) {
$rootScope.$on('$routeChangeSuccess', () => th... | app.service('analyticsService', class AnalyticsService {
routeChanged = false; | random_line_split |
problem-039.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// If p is the perimeter of a right angle triangle with integral length sides,
// {a,b,c}, there are exactly three solutions for p = 120.
//
// {20,48,52}, {24,45,51}, {30,40,50}
//
// For which value of p ≤ 10... | pub fn solution() -> u32 {
let mut max = 0;
let mut max_p = 0;
for p in 1..1001 {
// Perimeter will always be even
if p % 2 != 0 {
continue;
}
let count = num_triangles(p);
if count > max {
max = count;
max_p = p;
}
}
... | let mut count = 0;
let psq = p*p;
// a^2 + b^2 = c^2, a + b + c = p; substitute c = p - a - b and rearrange
// solutions must satisfy 2p(a+b) = p^2 + ab
// TODO: This can probably be simplified further, but algebra
for a in 1..p {
for b in 1..p {
if 2*p*(a + b) == psq + a*b {... | identifier_body |
problem-039.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// If p is the perimeter of a right angle triangle with integral length sides,
// {a,b,c}, there are exactly three solutions for p = 120.
//
// {20,48,52}, {24,45,51}, {30,40,50}
//
// For which value of p ≤ 10... | }
}
}
count
}
pub fn solution() -> u32 {
let mut max = 0;
let mut max_p = 0;
for p in 1..1001 {
// Perimeter will always be even
if p % 2 != 0 {
continue;
}
let count = num_triangles(p);
if count > max {
max = count... | if 2*p*(a + b) == psq + a*b {
count += 1; | random_line_split |
problem-039.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// If p is the perimeter of a right angle triangle with integral length sides,
// {a,b,c}, there are exactly three solutions for p = 120.
//
// {20,48,52}, {24,45,51}, {30,40,50}
//
// For which value of p ≤ 10... | {
println!("p = {} has the maximum number of solutions.", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(840, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
}
| in() | identifier_name |
problem-039.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// If p is the perimeter of a right angle triangle with integral length sides,
// {a,b,c}, there are exactly three solutions for p = 120.
//
// {20,48,52}, {24,45,51}, {30,40,50}
//
// For which value of p ≤ 10... | }
}
count
}
pub fn solution() -> u32 {
let mut max = 0;
let mut max_p = 0;
for p in 1..1001 {
// Perimeter will always be even
if p % 2 != 0 {
continue;
}
let count = num_triangles(p);
if count > max {
max = count;
m... | count += 1;
}
| conditional_block |
player.py | from PyQt5.QtCore import pyqtSignal
from model.modelitem import ModelItem
from model.rating import RatingType
from model.transaction import transactional
class Player(ModelItem):
newCurrentGame = pyqtSignal(object, object, object)
"""
Represents a player the client knows about.
"""
def __init__... |
@transactional
def set_currentGame(self, game, _transaction=None):
if self.currentGame == game:
return
old = self._currentGame
self._currentGame = game
_transaction.emit(self.newCurrentGame, self, game, old)
@currentGame.setter
def currentGame(self, val):
... | return self._currentGame | identifier_body |
player.py | from PyQt5.QtCore import pyqtSignal
from model.modelitem import ModelItem
from model.rating import RatingType
from model.transaction import transactional
class Player(ModelItem):
newCurrentGame = pyqtSignal(object, object, object)
"""
Represents a player the client knows about.
"""
def __init__... | def game_count(self, rating_type=RatingType.GLOBAL.value):
try:
return int(self.ratings[rating_type]["number_of_games"])
except KeyError:
return 0
def __repr__(self):
return self.__str__()
def __str__(self):
return (
"Player(id={}, login=... | return 500
| random_line_split |
player.py | from PyQt5.QtCore import pyqtSignal
from model.modelitem import ModelItem
from model.rating import RatingType
from model.transaction import transactional
class Player(ModelItem):
newCurrentGame = pyqtSignal(object, object, object)
"""
Represents a player the client knows about.
"""
def __init__... | (self, val):
# CAVEAT: this will emit signals immediately!
self.set_currentGame(val)
| currentGame | identifier_name |
player.py | from PyQt5.QtCore import pyqtSignal
from model.modelitem import ModelItem
from model.rating import RatingType
from model.transaction import transactional
class Player(ModelItem):
newCurrentGame = pyqtSignal(object, object, object)
"""
Represents a player the client knows about.
"""
def __init__... |
old = self._currentGame
self._currentGame = game
_transaction.emit(self.newCurrentGame, self, game, old)
@currentGame.setter
def currentGame(self, val):
# CAVEAT: this will emit signals immediately!
self.set_currentGame(val)
| return | conditional_block |
test_template_combination.py | # -*- coding: utf-8 -*-
"""Tests for template combination
@Requirement: TemplateCombination
@CaseAutomation: Automated
@CaseLevel: Acceptance
@CaseComponent: API
@TestType: Functional
@CaseImportance: Medium
@Upstream: No
"""
from nailgun import entities
from requests.exceptions import HTTPError
from robottelo.d... |
def setUp(self):
"""Create ConfigTemplate and TemplateConfiguration for each test"""
super(TemplateCombinationTestCase, self).setUp()
self.template = entities.ConfigTemplate(
snippet=False,
template_combinations=[{
'hostgroup_id': self.hostgroup.id,
... | entity.delete() | conditional_block |
test_template_combination.py | # -*- coding: utf-8 -*-
"""Tests for template combination
@Requirement: TemplateCombination
@CaseAutomation: Automated
@CaseLevel: Acceptance
@CaseComponent: API
@TestType: Functional
@CaseImportance: Medium
@Upstream: No
"""
from nailgun import entities
from requests.exceptions import HTTPError
from robottelo.d... | (self):
"""Create ConfigTemplate and TemplateConfiguration for each test"""
super(TemplateCombinationTestCase, self).setUp()
self.template = entities.ConfigTemplate(
snippet=False,
template_combinations=[{
'hostgroup_id': self.hostgroup.id,
... | setUp | identifier_name |
test_template_combination.py | # -*- coding: utf-8 -*-
"""Tests for template combination
|
@CaseAutomation: Automated
@CaseLevel: Acceptance
@CaseComponent: API
@TestType: Functional
@CaseImportance: Medium
@Upstream: No
"""
from nailgun import entities
from requests.exceptions import HTTPError
from robottelo.decorators import skip_if_bug_open, tier1
from robottelo.test import APITestCase
class Templ... | @Requirement: TemplateCombination | random_line_split |
test_template_combination.py | # -*- coding: utf-8 -*-
"""Tests for template combination
@Requirement: TemplateCombination
@CaseAutomation: Automated
@CaseLevel: Acceptance
@CaseComponent: API
@TestType: Functional
@CaseImportance: Medium
@Upstream: No
"""
from nailgun import entities
from requests.exceptions import HTTPError
from robottelo.d... | def setUp(self):
"""Create ConfigTemplate and TemplateConfiguration for each test"""
super(TemplateCombinationTestCase, self).setUp()
self.template = entities.ConfigTemplate(
snippet=False,
template_combinations=[{
'hostgroup_id': self.hostgroup.id,
... | """Implements TemplateCombination tests"""
@classmethod
def setUpClass(cls):
"""Create hostgroup and environment to be used on
TemplateCombination creation
"""
super(TemplateCombinationTestCase, cls).setUpClass()
cls.hostgroup = entities.HostGroup().create()
cls.... | identifier_body |
ifThereIsALotOfLight.js | /*global require */
'use strict';
var _ = require('lodash'),
utils = require('./../build-utils'),
StatementInputBloq = require('./../statementInputBloq');
/**
* Bloq name: mbot-ifthereisalotoflight
*
* Bloq type: Statement-Input
*
* Description:
*
* Return type: none
*/
var bloqMBotIfThereIsALotOfLig... | }, {
id: 'OPERATION',
alias: 'staticDropdown',
options: [{
label: 'bloq-mbot-ifthereisalotoflight-alot',
value: '+'
}, {
label: 'bloq-mbot-ifthereisalotoflight-low',
value: '-'
}, {
... | content: [
[{
alias: 'text',
value: 'if' | random_line_split |
h5ls.py | #!/usr/bin/env python3
"""*.h5 の値の最小・最大などを確認するスクリプト。"""
import argparse
import pathlib
import sys
import h5py
import numpy as np
try:
import pytoolkit as tk
except ImportError:
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent.parent)) | def main():
tk.utils.better_exceptions()
tk.log.init(None)
parser = argparse.ArgumentParser(description="*.h5 の値の最小・最大などを確認するスクリプト。")
parser.add_argument("model_path", type=pathlib.Path, help="対象ファイルのパス(*.h5)")
args = parser.parse_args()
logger.info(f"{args.model_path} Loading...")
absmax_l... | import pytoolkit as tk
logger = tk.log.get(__name__)
| random_line_split |
h5ls.py | #!/usr/bin/env python3
"""*.h5 の値の最小・最大などを確認するスクリプト。"""
import argparse
import pathlib
import sys
import h5py
import numpy as np
try:
import pytoolkit as tk
except ImportError:
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent.parent))
import pytoolkit as tk
logger = tk.log.get(__name... | k.log.init(None)
parser = argparse.ArgumentParser(description="*.h5 の値の最小・最大などを確認するスクリプト。")
parser.add_argument("model_path", type=pathlib.Path, help="対象ファイルのパス(*.h5)")
args = parser.parse_args()
logger.info(f"{args.model_path} Loading...")
absmax_list = []
with h5py.File(args.model_path, mode=... | t | identifier_name |
h5ls.py | #!/usr/bin/env python3
"""*.h5 の値の最小・最大などを確認するスクリプト。"""
import argparse
import pathlib
import sys
import h5py
import numpy as np
try:
import pytoolkit as tk
except ImportError:
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent.parent))
import pytoolkit as tk
logger = tk.log.get(__name... | f"{key}\t min={w.min():.2f} max={w.max():.2f} mean={w.mean():.2f} std={w.std():.2f}"
)
absmax_list.append((key, np.abs(w).max()))
logger.info("abs Top-10:")
for key, absvalue in list(sorted(absmax_list, key=lambda x: -x[1]))[:10]:
logger.info(... | it(None)
parser = argparse.ArgumentParser(description="*.h5 の値の最小・最大などを確認するスクリプト。")
parser.add_argument("model_path", type=pathlib.Path, help="対象ファイルのパス(*.h5)")
args = parser.parse_args()
logger.info(f"{args.model_path} Loading...")
absmax_list = []
with h5py.File(args.model_path, mode="r") as ... | identifier_body |
h5ls.py | #!/usr/bin/env python3
"""*.h5 の値の最小・最大などを確認するスクリプト。"""
import argparse
import pathlib
import sys
import h5py
import numpy as np
try:
import pytoolkit as tk
except ImportError:
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent.parent))
import pytoolkit as tk
logger = tk.log.get(__name... | conditional_block | ||
items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
from scrapy.loader.processors import Join, MapCompose, TakeFirst
from scrapy.loader import ItemLoader
from w3lib.html i... |
class Example(scrapy.Item):
name = scrapy.Field(
input_processor=MapCompose(unicode.title),
output_processor=Join(),
)
price = scrapy.Field(
input_processor=MapCompose(remove_tags, filter_price),
output_processor=TakeFirst(),
)
# eg: ItemLoader(item=Product()).a... | random_line_split | |
items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
from scrapy.loader.processors import Join, MapCompose, TakeFirst
from scrapy.loader import ItemLoader
from w3lib.html i... |
class Example(scrapy.Item):
name = scrapy.Field(
input_processor=MapCompose(unicode.title),
output_processor=Join(),
)
price = scrapy.Field(
input_processor=MapCompose(remove_tags, filter_price),
output_processor=TakeFirst(),
)
# eg: ItemLoader(item=Product())... | return value | conditional_block |
items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
from scrapy.loader.processors import Join, MapCompose, TakeFirst
from scrapy.loader import ItemLoader
from w3lib.html i... | (value):
if value.isdigit():
return value
class Example(scrapy.Item):
name = scrapy.Field(
input_processor=MapCompose(unicode.title),
output_processor=Join(),
)
price = scrapy.Field(
input_processor=MapCompose(remove_tags, filter_price),
output_processor... | filter_price | identifier_name |
items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
from scrapy.loader.processors import Join, MapCompose, TakeFirst
from scrapy.loader import ItemLoader
from w3lib.html i... |
class Example(scrapy.Item):
name = scrapy.Field(
input_processor=MapCompose(unicode.title),
output_processor=Join(),
)
price = scrapy.Field(
input_processor=MapCompose(remove_tags, filter_price),
output_processor=TakeFirst(),
)
# eg: ItemLoader(item=Product())... | if value.isdigit():
return value | identifier_body |
cgls.py | # -----------------------------------------------------------------------
# Copyright: 2010-2022, imec Vision Lab, University of Antwerp
# 2013-2022, CWI, Amsterdam
#
# Contact: astra@astra-toolbox.com
# Website: http://www.astra-toolbox.com/
#
# This file is part of the ASTRA Toolbox.
#
#
# The ASTRA Toolbo... | (astra.plugin.base):
"""CGLS."""
astra_name = "CGLS-PLUGIN"
def initialize(self,cfg):
self.W = astra.OpTomo(cfg['ProjectorId'])
self.vid = cfg['ReconstructionDataId']
self.sid = cfg['ProjectionDataId']
try:
v = astra.data2d.get_shared(self.vid)
s = ... | CGLSPlugin | identifier_name |
cgls.py | # -----------------------------------------------------------------------
# Copyright: 2010-2022, imec Vision Lab, University of Antwerp
# 2013-2022, CWI, Amsterdam
#
# Contact: astra@astra-toolbox.com
# Website: http://www.astra-toolbox.com/
#
# This file is part of the ASTRA Toolbox.
#
#
# The ASTRA Toolbo... |
def run(self, its):
v = self.data_mod.get_shared(self.vid)
s = self.data_mod.get_shared(self.sid)
z = np.zeros(v.shape, dtype=np.float32)
p = np.zeros(v.shape, dtype=np.float32)
r = np.zeros(s.shape, dtype=np.float32)
w = np.zeros(s.shape, dtype=np.float32)
... | self.W = astra.OpTomo(cfg['ProjectorId'])
self.vid = cfg['ReconstructionDataId']
self.sid = cfg['ProjectionDataId']
try:
v = astra.data2d.get_shared(self.vid)
s = astra.data2d.get_shared(self.sid)
self.data_mod = astra.data2d
except Exception:
... | identifier_body |
cgls.py | # -----------------------------------------------------------------------
# Copyright: 2010-2022, imec Vision Lab, University of Antwerp
# 2013-2022, CWI, Amsterdam
#
# Contact: astra@astra-toolbox.com
# Website: http://www.astra-toolbox.com/
#
# This file is part of the ASTRA Toolbox.
#
#
# The ASTRA Toolbo... | # p = W'*r
W.BP(r, out=p)
# gamma = <p,p>
gamma = np.dot(p.ravel(), p.ravel())
for i in range(its):
# w = W * p
W.FP(p, out=w)
# alpha = gamma / <w,w>
alpha = gamma / np.dot(w.ravel(), w.ravel())
# v += alpha * p
... | # r = s - W*v
W.FP(v, out=w)
r[:] = s
r -= w
| random_line_split |
cgls.py | # -----------------------------------------------------------------------
# Copyright: 2010-2022, imec Vision Lab, University of Antwerp
# 2013-2022, CWI, Amsterdam
#
# Contact: astra@astra-toolbox.com
# Website: http://www.astra-toolbox.com/
#
# This file is part of the ASTRA Toolbox.
#
#
# The ASTRA Toolbo... |
# gamma = <z,z>
gamma = newgamma
# p = z + beta * p
p *= beta
p += z
| W.FP(p, out=w)
# alpha = gamma / <w,w>
alpha = gamma / np.dot(w.ravel(), w.ravel())
# v += alpha * p
z[:] = p
z *= alpha
v += z
# r -= alpha * w
w *= -alpha;
r += w
# z = W' * r
W.BP(r... | conditional_block |
context.py | """Askbot template context processor that makes some parameters
from the django settings, all parameters from the askbot livesettings
and the application available for the templates
"""
from django.conf import settings
import askbot
from askbot import api
from askbot.conf import settings as askbot_settings
from askbot.... | (request):
"""The context processor function"""
my_settings = askbot_settings.as_dict()
my_settings['LANGUAGE_CODE'] = settings.LANGUAGE_CODE
my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
my_settings['DEBUG'] = settings.DEBUG
my_settings['ASKBOT_VERSION'] = askbot.get_version()
my_settings... | application_settings | identifier_name |
context.py | """Askbot template context processor that makes some parameters
from the django settings, all parameters from the askbot livesettings
and the application available for the templates
"""
from django.conf import settings
import askbot
from askbot import api
from askbot.conf import settings as askbot_settings
from askbot.... | } | my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url()
return {
'settings': my_settings,
'skin': get_skin(request),
'moderation_items': api.get_info_on_moderation_items(request.user) | random_line_split |
context.py | """Askbot template context processor that makes some parameters
from the django settings, all parameters from the askbot livesettings
and the application available for the templates
"""
from django.conf import settings
import askbot
from askbot import api
from askbot.conf import settings as askbot_settings
from askbot.... | """The context processor function"""
my_settings = askbot_settings.as_dict()
my_settings['LANGUAGE_CODE'] = settings.LANGUAGE_CODE
my_settings['ASKBOT_URL'] = settings.ASKBOT_URL
my_settings['DEBUG'] = settings.DEBUG
my_settings['ASKBOT_VERSION'] = askbot.get_version()
my_settings['LOGIN_URL'] =... | identifier_body | |
sub.rs | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty:... | random_line_split | ||
sub.rs | APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty::{BuiltinBounds};
use middle::ty;
use middle::ty::TyVar;
use m... | <'a>(&'a self) -> Lub<'a> { Lub(*self.get_ref()) }
fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) }
fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t> {
let opp = CombineFields {
a_is_expected: !self.get_ref().a_is_expected,.. *self.get_ref()
};
Sub(opp).tys(b, a... | lub | identifier_name |
sub.rs | APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::ty::{BuiltinBounds};
use middle::ty;
use middle::ty::TyVar;
use m... |
fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) }
fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t> {
let opp = CombineFields {
a_is_expected: !self.get_ref().a_is_expected,.. *self.get_ref()
};
Sub(opp).tys(b, a)
}
fn contraregions(&self, a: ty::Region... | { Lub(*self.get_ref()) } | identifier_body |
timing.py | from time import time
from os import remove
from matplotlib.image import imread
import json
import subprocess
import numpy as np
import matplotlib.pyplot as plt
def time_a_function(program, args):
start = time()
subprocess.call([program] + [args])
end = time()
return float(end - start)
def | (programs):
for p in programs:
remove(p)
def plot_results(times, programs, images):
x = [imread(img)[:,:,0].shape for img in images]
xlabels = [str(xi) for xi in x]
x = [np.prod(xi) for xi in x]
for p in programs:
y, std_y = zip(*times[p])
# plt.plot(x, y, 'o')
plt... | clean | identifier_name |
timing.py | from time import time
from os import remove
from matplotlib.image import imread
import json
import subprocess
import numpy as np
import matplotlib.pyplot as plt
def time_a_function(program, args):
start = time()
subprocess.call([program] + [args])
end = time()
return float(end - start)
| def clean(programs):
for p in programs:
remove(p)
def plot_results(times, programs, images):
x = [imread(img)[:,:,0].shape for img in images]
xlabels = [str(xi) for xi in x]
x = [np.prod(xi) for xi in x]
for p in programs:
y, std_y = zip(*times[p])
# plt.plot(x, y, 'o')
... | random_line_split | |
timing.py | from time import time
from os import remove
from matplotlib.image import imread
import json
import subprocess
import numpy as np
import matplotlib.pyplot as plt
def time_a_function(program, args):
start = time()
subprocess.call([program] + [args])
end = time()
return float(end - start)
def clean... |
def main():
print 'Running make...'
subprocess.call(['make', '-j8'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
programs = ['./grayscale.out', './grayscale-seq.out']
images = ['img/emma{}.png'.format(i) for i in range(1, 6)]
n = 20
times = {}
try:
print 'Loading times.json...... | sizes = [imread(img)[:,:,0].size for img in images]
for p in programs:
print '\n{}'.format(p)
mean_t, std_t = zip(*times[p])
print 'Image'.rjust(13), 'Size'.rjust(8), 'Avg. time'.rjust(10), 'Std. time'.rjust(10)
for img, size, m, s in zip(images, sizes, mean_t, std_t):
pr... | identifier_body |
timing.py | from time import time
from os import remove
from matplotlib.image import imread
import json
import subprocess
import numpy as np
import matplotlib.pyplot as plt
def time_a_function(program, args):
start = time()
subprocess.call([program] + [args])
end = time()
return float(end - start)
def clean... |
def plot_results(times, programs, images):
x = [imread(img)[:,:,0].shape for img in images]
xlabels = [str(xi) for xi in x]
x = [np.prod(xi) for xi in x]
for p in programs:
y, std_y = zip(*times[p])
# plt.plot(x, y, 'o')
plt.errorbar(x, y, yerr=std_y, fmt='o')
plt.xti... | remove(p) | conditional_block |
bootstrap.js | /**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
define(function (require) {
'use strict';
var renderer = require('../template/renderer');
renderer.addAttribute('repeat', renderer.handlers.wrapAttribute);
renderer.addAttribute('outerfasteach', {
... | };
}); | repeat: require('knockoutjs/knockout-repeat'),
fastForEach: require('knockoutjs/knockout-fast-foreach') | random_line_split |
plainMessage.js | module.exports = (title, message, url) => `
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" initial-scale="1" />
</head>
<body>
<table role="presentation" aria-hidden="true" cellspacing="0" cellpadding="0" border="0" align="center">
<tr>
<td>
... | </tr>
<tr>
<td>
<p>${message}</p>
</td>
</tr>
<tr>
<td>
<p><a href="${url}">${url}</a></p>
</td>
</tr>
<tr>
<td>
<p>Sent with ❤️ from <a href="https://spendlogs.ml" style="text-decoration: none; color: #333">Spendl... | </td> | random_line_split |
utils.ts | , it cannot inherit application-specific getters.
// Furthermore, Object has __proto__ getter which is not relevant.
// Array, Boolean, Number, String constructors don’t have any getters.
return false;
}
if (typeof constructor !== 'function') {
// Object.create(null) constructs object with no constr... | return obj && typeof obj === 'object' ? !Object.keys(obj).length : false;
}
| identifier_body | |
utils.ts | ed,
isImmutableUnorderedSet,
} from './jasmineUtils';
type GetPath = {
hasEndProp?: boolean;
lastTraversedObject: unknown;
traversedPath: Array<string>;
value?: unknown;
};
// Return whether object instance inherits getter from its class.
const hasGetterFromConstructor = (object: object, key: string) => {
... | // Therefore, it cannot inherit application-specific getters.
// Furthermore, Object has __proto__ getter which is not relevant.
// Array, Boolean, Number, String constructors don’t have any getters.
return false;
}
if (typeof constructor !== 'function') {
// Object.create(null) constructs objec... | // A literal object has Object as constructor. | random_line_split |
utils.ts | ed,
isImmutableUnorderedSet,
} from './jasmineUtils';
type GetPath = {
hasEndProp?: boolean;
lastTraversedObject: unknown;
traversedPath: Array<string>;
value?: unknown;
};
// Return whether object instance inherits getter from its class.
const hasGetterFromConstructor = (object: object, key: string) => {
... | }
if (has === false) {
allFound = false;
break;
}
}
}
// Remove the first value from the stack of traversed values.
aStack.pop();
bStack.pop();
return allFound;
}
}
const bIterator = b[IteratorSymbol]();
for (const a... | has = true;
}
| conditional_block |
utils.ts | object.constructor;
if (constructor === Object) {
// A literal object has Object as constructor.
// Therefore, it cannot inherit application-specific getters.
// Furthermore, Object has __proto__ getter which is not relevant.
// Array, Boolean, Number, String constructors don’t have any getters.
... | ptyObject(o | identifier_name | |
overloaded-deref-count.rs | // run-pass
use std::cell::Cell;
use std::ops::{Deref, DerefMut};
use std::vec::Vec;
struct DerefCounter<T> {
count_imm: Cell<usize>,
count_mut: usize,
value: T
}
impl<T> DerefCounter<T> {
fn new(value: T) -> DerefCounter<T> {
DerefCounter {
count_imm: Cell::new(0),
co... |
}
pub fn main() {
let mut n = DerefCounter::new(0);
let mut v = DerefCounter::new(Vec::new());
let _ = *n; // Immutable deref + copy a POD.
assert_eq!(n.counts(), (1, 0));
let _ = (&*n, &*v); // Immutable deref + borrow.
assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0));
le... | {
self.count_mut += 1;
&mut self.value
} | identifier_body |
overloaded-deref-count.rs | // run-pass | use std::vec::Vec;
struct DerefCounter<T> {
count_imm: Cell<usize>,
count_mut: usize,
value: T
}
impl<T> DerefCounter<T> {
fn new(value: T) -> DerefCounter<T> {
DerefCounter {
count_imm: Cell::new(0),
count_mut: 0,
value: value
}
}
fn counts... |
use std::cell::Cell;
use std::ops::{Deref, DerefMut}; | random_line_split |
overloaded-deref-count.rs | // run-pass
use std::cell::Cell;
use std::ops::{Deref, DerefMut};
use std::vec::Vec;
struct | <T> {
count_imm: Cell<usize>,
count_mut: usize,
value: T
}
impl<T> DerefCounter<T> {
fn new(value: T) -> DerefCounter<T> {
DerefCounter {
count_imm: Cell::new(0),
count_mut: 0,
value: value
}
}
fn counts(&self) -> (usize, usize) {
(se... | DerefCounter | identifier_name |
Array.prototype.es6.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Array.prototype.es6
* @polyfill
* @nolint
*/
/* eslint-disable no-bitwise, no-extend-native, radix, no-self-compare... | enumerable: false,
writable: true,
configurable: true,
value(searchElement) {
const O = Object(this);
const len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
const n = parseInt(arguments[1]) || 0;
let k;
if (n >= 0) {
k = n;
}... | if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', { | random_line_split |
Array.prototype.es6.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Array.prototype.es6
* @polyfill
* @nolint
*/
/* eslint-disable no-bitwise, no-extend-native, radix, no-self-compare... | (searchElement) {
const O = Object(this);
const len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
const n = parseInt(arguments[1]) || 0;
let k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}... | value | identifier_name |
Array.prototype.es6.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Array.prototype.es6
* @polyfill
* @nolint
*/
/* eslint-disable no-bitwise, no-extend-native, radix, no-self-compare... |
k++;
}
return false;
},
});
}
| {
return true;
} | conditional_block |
Array.prototype.es6.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Array.prototype.es6
* @polyfill
* @nolint
*/
/* eslint-disable no-bitwise, no-extend-native, radix, no-self-compare... | ,
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
enumerable: false,
writable: true,
configurable: true,
value(searchElement) {
const O = Object(this)... | {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
const index = findIndex.call(this, predicate, context);
return index === -1 ? undefined : this[index];
} | identifier_body |
uuid.rs | //! Conversions between ULID and UUID.
use crate::Ulid;
use uuid::Uuid;
impl From<Uuid> for Ulid {
fn from(uuid: Uuid) -> Self {
Ulid(uuid.as_u128())
}
}
impl From<Ulid> for Uuid {
fn from(ulid: Ulid) -> Self {
Uuid::from_u128(ulid.0)
}
}
#[cfg(test)]
mod test {
use super::*;
... | () {
let uuid_txt = "771a3bce-02e9-4428-a68e-b1e7e82b7f9f";
let ulid_txt = "3Q38XWW0Q98GMAD3NHWZM2PZWZ";
let ulid: Ulid = Uuid::parse_str(uuid_txt).unwrap().into();
assert_eq!(ulid.to_string(), ulid_txt);
let uuid: Uuid = ulid.into();
assert_eq!(uuid.to_string(), uuid_t... | uuid_str_cycle | identifier_name |
uuid.rs | //! Conversions between ULID and UUID.
use crate::Ulid;
use uuid::Uuid;
impl From<Uuid> for Ulid {
fn from(uuid: Uuid) -> Self {
Ulid(uuid.as_u128())
}
}
impl From<Ulid> for Uuid {
fn from(ulid: Ulid) -> Self |
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn uuid_cycle() {
let ulid = Ulid::new();
let uuid: Uuid = ulid.into();
let ulid2: Ulid = uuid.into();
assert_eq!(ulid, ulid2);
}
#[test]
fn uuid_str_cycle() {
let uuid_txt = "771a3bce-02e9-4428-a68e-b1e... | {
Uuid::from_u128(ulid.0)
} | identifier_body |
uuid.rs | //! Conversions between ULID and UUID.
| fn from(uuid: Uuid) -> Self {
Ulid(uuid.as_u128())
}
}
impl From<Ulid> for Uuid {
fn from(ulid: Ulid) -> Self {
Uuid::from_u128(ulid.0)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn uuid_cycle() {
let ulid = Ulid::new();
let uuid: Uuid = ulid.into();... | use crate::Ulid;
use uuid::Uuid;
impl From<Uuid> for Ulid { | random_line_split |
function.py | #! /usr/bin/env python
from ppclass import pp
var1 = pp(\
file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc",\
var="ps",\
x=None,\
y=10.,\
t=2.)
var1.get()
var2 = pp(\
file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc",\
var="phisinit",\
x=None,\
y=10.,\
t=2.)
var2.get()
var2 = var2 / 3.72
S = var2.func(var1)
S.p... | S.filename = "function"
S.makeplot() | S.p[0].ylabel = "Surface geopotential height (km)"
S.p[0].ycoeff = 1./1000.
S.p[0].fmt = '%.0f' | random_line_split |
data.py | # coding=UTF-8
'''
Created on 24.09.2017
@author: sysoev
'''
from google.appengine.ext import db
from google.appengine.api import users
import datetime
import time
import logging
from myusers import MyUser
def force_unicode(string):
if type(string) == unicode:
return string
return string.decode('ut... | return None
true_project_key = Project.get(project_key_str).key()
if check_user_have_project(user, true_project_key):
return False
up = UserProject()
up.user_key = user.key()
up.project_key = true_project_key
up.put()
return True
def check_user_have_project(user, true_pro... | user_query = MyUser.all()
user = user_query.filter('username = ', user_name).get()
if user is None: | random_line_split |
data.py | # coding=UTF-8
'''
Created on 24.09.2017
@author: sysoev
'''
from google.appengine.ext import db
from google.appengine.api import users
import datetime
import time
import logging
from myusers import MyUser
def force_unicode(string):
if type(string) == unicode:
return string
return string.decode('ut... |
def check_user_have_project(user, true_project_key):
user_project_keys = [user_proj.project_key.key() for user_proj in
UserProject.all().filter('user_key = ', user.key()).fetch(None)]
return true_project_key in user_project_keys
def deleteUserProject(user_key, project_key):
qu... | user_query = MyUser.all()
user = user_query.filter('username = ', user_name).get()
if user is None:
return None
true_project_key = Project.get(project_key_str).key()
if check_user_have_project(user, true_project_key):
return False
up = UserProject()
up.user_key = user.key()
... | identifier_body |
data.py | # coding=UTF-8
'''
Created on 24.09.2017
@author: sysoev
'''
from google.appengine.ext import db
from google.appengine.api import users
import datetime
import time
import logging
from myusers import MyUser
def force_unicode(string):
if type(string) == unicode:
return string
return string.decode('ut... | (project_key, name, description):
print("log")
req = Request(parent=project_key)
req.name = name
req.description = description
req.perfomer = ""
req.state = 1
req.number = Request(ancestor = project_key).all().length + 1
req.put()
Project.set(project_key).number += 1
return True... | addRequests | identifier_name |
data.py | # coding=UTF-8
'''
Created on 24.09.2017
@author: sysoev
'''
from google.appengine.ext import db
from google.appengine.api import users
import datetime
import time
import logging
from myusers import MyUser
def force_unicode(string):
if type(string) == unicode:
return string
return string.decode('ut... |
p.name = name
p.put()
def addProject(name):
p = Project()
p.name = name
p.put()
return p.key()
class UserProject(db.Model):
user_key = db.ReferenceProperty(MyUser)
project_key = db.ReferenceProperty(Project)
number = 0
def addUserProject(user_name, project_key_str):
user_q... | return | conditional_block |
mv.rs | opt("S", "suffix", "override the usual backup suffix", "SUFFIX");
opts.optopt("t", "target-directory", "move all SOURCE arguments into DIRECTORY", "DIRECTORY");
opts.optflag("T", "no-target-directory", "treat DEST as a normal file");
opts.optflag("u", "update", "move only when the SOURCE file is newer\n \
... | let mut i: u64 = 1; | identifier_name | |
mv.rs | static VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub struct Behaviour {
overwrite: OverwriteMode,
backup: BackupMode,
suffix: String,
update: bool,
target_dir: Option<String>,
no_target_dir: bool,
verbose: bool,
}
#[derive(Clone, Eq, PartialEq)]
pub enum OverwriteMode {
NoClob... | Some(x) => x,
None => {
show_error!("option '--suffix' requires an argument\n\
Try '{} --help' for more information.", NAME);
return 1;
}
}
} else {
"~".to_owned()
};
if matches.opt_present("T") ... | let backup_suffix = if matches.opt_present("suffix") {
match matches.opt_str("suffix") { | random_line_split |
mv.rs | VERSION: &'static str = env!("CARGO_PKG_VERSION");
pub struct Behaviour {
overwrite: OverwriteMode,
backup: BackupMode,
suffix: String,
update: bool,
target_dir: Option<String>,
no_target_dir: bool,
verbose: bool,
}
#[derive(Clone, Eq, PartialEq)]
pub enum OverwriteMode {
NoClobber,
... | if !source.is_dir() {
show_error!("cannot overwrite directory ‘{}’ with non-directory",
target.display());
return 1;
}
return match rename(source, target, &b) {
... | ch b.target_dir {
Some(ref name) => return move_files_into_dir(files, &PathBuf::from(name), &b),
None => {}
}
match files.len() {
0 | 1 => {
show_error!("missing file operand\n\
Try '{} --help' for more information.", NAME);
return 1;
... | identifier_body |
tree.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Traits that nodes must implement. Breaks the otherwise-cyclic dependency
//! between layout and style.
use at... |
}
| {
false
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.