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
PartListSection.tsx
import React, { useMemo } from 'react'; import { cx, css } from '@emotion/css'; import { MenuItem, WithContextMenu, MenuGroup, useTheme2 } from '@grafana/ui'; import { SelectableValue, GrafanaTheme2 } from '@grafana/data'; import { Seg } from './Seg'; import { unwrap } from './unwrap'; import { toSelectableValue } from...
}} /> ))} <AddButton loadOptions={getNewPartOptions} onAdd={onAddNewPart} /> </> ); };
onChange(index, pars);
random_line_split
extern-compare-with-return-type.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
}
assert!(uintvoidret == uintvoidret); assert!(uintuintuintuintret == uintuintuintuintret);
random_line_split
extern-compare-with-return-type.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
pub fn main() { assert!(voidret1 == voidret1); assert!(voidret1 != voidret2); assert!(uintret == uintret); assert!(uintvoidret == uintvoidret); assert!(uintuintuintuintret == uintuintuintuintret); }
{ x+y+z }
identifier_body
extern-compare-with-return-type.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
(x: uint, y: uint, z: uint) -> uint { x+y+z } pub fn main() { assert!(voidret1 == voidret1); assert!(voidret1 != voidret2); assert!(uintret == uintret); assert!(uintvoidret == uintvoidret); assert!(uintuintuintuintret == uintuintuintuintret); }
uintuintuintuintret
identifier_name
0002_auto_20190218_1136.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-18 11:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
name='featureset', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='basicviz.BVFeatureSet'), ), migrations.AddField( model_name='mdbmotif', name='motif_set', field=models.ForeignKey(on_delete=django.db.models....
dependencies = [ ('basicviz', '0088_auto_20190218_1136'), ('motifdb', '0001_initial'), ] operations = [ migrations.CreateModel( name='MDBMotif', fields=[ ('mass2motif_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletio...
identifier_body
0002_auto_20190218_1136.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2019-02-18 11:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('basicviz', '0088_auto_20190218_1136'), ('motifdb', '0001_initial'), ] operations = [ migrations.CreateModel( name='MDBMotif', fields=[ ('mass2motif_ptr', models.OneToOneField(auto_created=True, on_de...
Migration
identifier_name
0002_auto_20190218_1136.py
# -*- coding: utf-8 -*-
class Migration(migrations.Migration): dependencies = [ ('basicviz', '0088_auto_20190218_1136'), ('motifdb', '0001_initial'), ] operations = [ migrations.CreateModel( name='MDBMotif', fields=[ ('mass2motif_ptr', models.OneToOneField(auto_cr...
# Generated by Django 1.11.16 on 2019-02-18 11:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
random_line_split
TypeaheadDemo.ts
import { document, console } from '@ephox/dom-globals'; import { Arr, Future, Option, Result, Strings } from '@ephox/katamari'; import { Class, Element, Value } from '@ephox/sugar'; import { Representing } from 'ephox/alloy/api/behaviour/Representing'; import * as Attachment from 'ephox/alloy/api/system/Attachment'; i...
(sandbox, item, itemValue) { const value = Representing.getValue(item); console.log('*** typeahead menu demo execute on: ', value, ' ***'); return Option.some(true); } }); }; HtmlDisplay.section(gui, 'An example of a typeahead component', Container.sketch({ componen...
onExecute
identifier_name
TypeaheadDemo.ts
import { document, console } from '@ephox/dom-globals'; import { Arr, Future, Option, Result, Strings } from '@ephox/katamari'; import { Class, Element, Value } from '@ephox/sugar'; import { Representing } from 'ephox/alloy/api/behaviour/Representing'; import * as Attachment from 'ephox/alloy/api/system/Attachment'; i...
}); }; HtmlDisplay.section(gui, 'An example of a typeahead component', Container.sketch({ components: [ sketchTypeahead({ selectsOver: true, getDisplayText: (itemData) => itemData.meta && itemData.meta.text ? itemData.meta.text : 'No.text', populateFromB...
{ const value = Representing.getValue(item); console.log('*** typeahead menu demo execute on: ', value, ' ***'); return Option.some(true); }
identifier_body
TypeaheadDemo.ts
import { document, console } from '@ephox/dom-globals'; import { Arr, Future, Option, Result, Strings } from '@ephox/katamari'; import { Class, Element, Value } from '@ephox/sugar'; import { Representing } from 'ephox/alloy/api/behaviour/Representing'; import * as Attachment from 'ephox/alloy/api/system/Attachment'; i...
}); const matches = matching.length > 0 ? matching : [ { type: 'separator', text: 'No items' } ]; const future = Future.pure(matches.slice(0, 5)); return future.map((items) => { const menu = DemoRenders.menu({ value: 'blah.value', it...
{ return [ ]; }
conditional_block
TypeaheadDemo.ts
import { document, console } from '@ephox/dom-globals'; import { Arr, Future, Option, Result, Strings } from '@ephox/katamari'; import { Class, Element, Value } from '@ephox/sugar'; import { Representing } from 'ephox/alloy/api/behaviour/Representing'; import * as Attachment from 'ephox/alloy/api/system/Attachment'; i...
'text': d.text, html, 'meta-demo-content': 'caterpillar', 'item-class': 'class-' + d.value } } } ]; } else { return [ ]; } }); cons...
type: 'item', data: { value: d.value, meta: {
random_line_split
worker.js
'use strict'; const async = require('async'); const getApp = require('../utils/utils.js').getApp; module.exports = function(Worker) { //Worker.validatesPresenceOf('title'); Worker.upsertItem = (data, cb) => { let res = {}; getApp(Worker) .then((app) => { if (!!!data.person) cb({errCode: 'ERR...
if (!!res.worker) res.worker.destroy(); cb({errCode: 'ERR_WORKER_NO_SAVE'}); }); }); }; Worker.remoteMethod('upsertItem', { description: 'upsert client ', http: {verb: 'post'}, accepts: { arg: 'data', type: 'object', description: 'data from form to upsert c...
random_line_split
notes_spec.js
define([ 'js/spec/edxnotes/helpers', 'js/edxnotes/collections/notes' ], function(Helpers, NotesCollection) { 'use strict'; describe('EdxNotes NotesCollection', function() { var notes = Helpers.getDefaultNotes(); beforeEach(function () { this.collection = new NotesCollection(note...
expect(structureUnits.length === collectionUnits.length).toBeTruthy(); for(var i = 0; i < structureUnits.length; i++) { expect(structureUnits[i].attributes).toEqual(collectionUnits[i].attributes); } }; var units = { ...
var compareUnits = function (structureUnits, collectionUnits) {
random_line_split
notes_spec.js
define([ 'js/spec/edxnotes/helpers', 'js/edxnotes/collections/notes' ], function(Helpers, NotesCollection) { 'use strict'; describe('EdxNotes NotesCollection', function() { var notes = Helpers.getDefaultNotes(); beforeEach(function () { this.collection = new NotesCollection(note...
}; var units = { 'i4x://unit/0': [this.collection.at(0), this.collection.at(1)], 'i4x://unit/1': [this.collection.at(2)], 'i4x://unit/2': [this.collection.at(3)], 'i4x://unit/3': [this.collection.at(4)] }; ...
{ expect(structureUnits[i].attributes).toEqual(collectionUnits[i].attributes); }
conditional_block
dapp_id.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 la...
(pub String); impl Into<String> for DappId { fn into(self) -> String { self.0 } } impl From<String> for DappId { fn from(s: String) -> Self { DappId(s) } } #[cfg(test)] mod tests { use serde_json; use super::DappId; #[test] fn should_serialize_dapp_id() { // given let id = DappId("testapp".into());...
DappId
identifier_name
dapp_id.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 la...
use serde_json; use super::DappId; #[test] fn should_serialize_dapp_id() { // given let id = DappId("testapp".into()); // when let res = serde_json::to_string(&id).unwrap(); // then assert_eq!(res, r#""testapp""#); } #[test] fn should_deserialize_dapp_id() { // given let id = r#""testapp""#; ...
random_line_split
dapp_id.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 la...
} #[cfg(test)] mod tests { use serde_json; use super::DappId; #[test] fn should_serialize_dapp_id() { // given let id = DappId("testapp".into()); // when let res = serde_json::to_string(&id).unwrap(); // then assert_eq!(res, r#""testapp""#); } #[test] fn should_deserialize_dapp_id() { // giv...
{ DappId(s) }
identifier_body
project.ts
/* * eventastic * * Copyright(c) 2016 André König <andre.koenig@posteo.de> * MIT Licensed * */ /** * @author André König (andre.koenig@posteo.de) * */ import VError = require('verror'); import { Connection, db } from "rethinkdb"; import { IEvent } from "./types"; import { IProjectionHandler } from "./creat...
hasNext = false; } } whi le (hasNext); return state; }; export default project;
try { const event = await new Promise<IEvent<any>>((resolve, reject) => { events.next<IEvent<any>>((err: Error, event) => { if (err) { return reject(new VError(err, `failed to read an event from the store`)); } ...
conditional_block
project.ts
/* * eventastic * * Copyright(c) 2016 André König <andre.koenig@posteo.de> * MIT Licensed * */ /** * @author André König (andre.koenig@posteo.de) * */ import VError = require('verror'); import { Connection, db } from "rethinkdb"; import { IEvent } from "./types"; import { IProjectionHandler } from "./creat...
hasNext = false; } } while (hasNext); return state; }; export default project;
throw new VError(err, `failed to perform projection`); }
random_line_split
nodes.py
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as publ...
(BaseLayout): """some tabular data attributes : * BaseLayout attributes * cols : the number of columns of the table (REQUIRED) * rheaders : the first row's elements are table's header * cheaders : the first col's elements are table's header * title : the table's optional title """ d...
Table
identifier_name
nodes.py
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as publ...
attributes : * BaseLayout attributes A paragraph must not contains a section ! """ class Table(BaseLayout): """some tabular data attributes : * BaseLayout attributes * cols : the number of columns of the table (REQUIRED) * rheaders : the first row's elements are table's header ...
random_line_split
nodes.py
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as publ...
def add_text(self, text): """shortcut to add text data""" self.children.append(Text(text)) # non container nodes ######################################################### class Text(BaseComponent): """a text portion attributes : * BaseComponent attributes * data : the text valu...
"""return the ancestor nodes""" assert self.parent is not self if self.parent is None: return [] return [self.parent] + self.parent.parents()
identifier_body
nodes.py
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of logilab-common. # # logilab-common is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as publ...
else: self.add_text(child) def append(self, child): """overridden to detect problems easily""" assert child not in self.parents() VNode.append(self, child) def parents(self): """return the ancestor nodes""" assert self.parent is not self ...
self.append(child)
conditional_block
app.py
from gevent import monkey from socketio.server import SocketIOServer from socketio import socketio_manage from flask import Flask, request, render_template, Response from werkzeug.serving import run_with_reloader from socketio.namespace import BaseNamespace from debugger import SocketIODebugger monkey.patch_all() c...
if __name__ == '__main__': app = Flask(__name__) app.route('/')(index) app.route('/debug')(debug) app.route('/socket.io/<path:path>')(run_socketio) app.debug = True app = SocketIODebugger(app, evalex=True, namespace=Namespace) server = SocketIOServer(('', 8080), app, resource='s...
print '\nrun_socketio(path=%s)' % repr(path) socketio_manage(request.environ, {'/api': Namespace}, request) return Response()
identifier_body
app.py
from gevent import monkey from socketio.server import SocketIOServer from socketio import socketio_manage from flask import Flask, request, render_template, Response from werkzeug.serving import run_with_reloader from socketio.namespace import BaseNamespace from debugger import SocketIODebugger monkey.patch_all() c...
(self): print '\nNamespace.recv_connect()' def recv_disconnect(self): print '\nNamespace.recv_disconnect()' self.disconnect() def on_foo(self, msg=None): print '\nNamespace.on_foo(): msg=%s' % repr(msg) self.emit('bar', {'data': 'some server data'}) def on_debug(se...
recv_connect
identifier_name
app.py
from gevent import monkey
from debugger import SocketIODebugger monkey.patch_all() class Namespace(BaseNamespace): def __init__(self, *args, **kwargs): print '\nNamespace.__init__(args=%s, kwargs=%s)' % ( repr(args), repr(kwargs)) super(Namespace, self).__init__(*args, **kwargs) def recv_connect(self): ...
from socketio.server import SocketIOServer from socketio import socketio_manage from flask import Flask, request, render_template, Response from werkzeug.serving import run_with_reloader from socketio.namespace import BaseNamespace
random_line_split
app.py
from gevent import monkey from socketio.server import SocketIOServer from socketio import socketio_manage from flask import Flask, request, render_template, Response from werkzeug.serving import run_with_reloader from socketio.namespace import BaseNamespace from debugger import SocketIODebugger monkey.patch_all() c...
app = Flask(__name__) app.route('/')(index) app.route('/debug')(debug) app.route('/socket.io/<path:path>')(run_socketio) app.debug = True app = SocketIODebugger(app, evalex=True, namespace=Namespace) server = SocketIOServer(('', 8080), app, resource='socket.io', policy_server=False) ...
conditional_block
vidbull.py
''' Vidbull urlresolver plugin Copyright (C) 2013 Vinnydude This program 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. This program is di...
(self): p = self.get_setting('priority') or 100 self.priority = int(p) self.net = Net() def get_media_url(self, host, media_id): try: headers = { 'User-Agent': USER_AGENT } web_url = self.get_url(host, m...
__init__
identifier_name
vidbull.py
''' Vidbull urlresolver plugin Copyright (C) 2013 Vinnydude This program 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. This program is di...
return match.group(1) else: raise Exception('File Link Not Found') except urllib2.HTTPError as e: common.addon.log_error(self.name + ': got http error %d fetching %s' % (e.code, web_url)) return self.unresolvable(code=3, msg=e) except ...
random_line_split
vidbull.py
''' Vidbull urlresolver plugin Copyright (C) 2013 Vinnydude This program 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. This program is di...
return('host', 'media_id') def valid_url(self, url, host): if self.get_setting('enabled') == 'false': return False return (re.match('http://(www.)?vidbull.com/(?:embed-)?' + '[0-9A-Za-z]+', url) or 'vidbull' in host)
return False
conditional_block
vidbull.py
''' Vidbull urlresolver plugin Copyright (C) 2013 Vinnydude This program 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. This program is di...
if self.get_setting('enabled') == 'false': return False return (re.match('http://(www.)?vidbull.com/(?:embed-)?' + '[0-9A-Za-z]+', url) or 'vidbull' in host)
identifier_body
__init__.py
# -*- coding: utf-8 -*- # __init__.py # Copyright (C) 2015 LEAP # # This program 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. # # Th...
self.sync_exchange_phase = [0]
conditional_block
__init__.py
# -*- coding: utf-8 -*- # __init__.py # Copyright (C) 2015 LEAP # # This program 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. # # Th...
:param crypto: An instance of SoledadCrypto so we can encrypt/decrypt document contents when syncing. :type crypto: soledad._crypto.SoledadCrypto :param cert_file: Path to the certificate of the ca used to validate the SSL certificate used by the...
""" A SyncTarget that encrypts data before sending and decrypts data after receiving. Normally encryption will have been written to the sync database upon document modification. The sync database is also used to write temporarily the parsed documents that the remote send us, before being decrypted ...
identifier_body
__init__.py
# -*- coding: utf-8 -*- # __init__.py # Copyright (C) 2015 LEAP # # This program 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. # # Th...
receiving. Normally encryption will have been written to the sync database upon document modification. The sync database is also used to write temporarily the parsed documents that the remote send us, before being decrypted and written to the main database. """ def __init__(self, url, sourc...
class SoledadHTTPSyncTarget(SyncTargetAPI, HTTPDocSender, HTTPDocFetcher): """ A SyncTarget that encrypts data before sending and decrypts data after
random_line_split
__init__.py
# -*- coding: utf-8 -*- # __init__.py # Copyright (C) 2015 LEAP # # This program 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. # # Th...
(SyncTargetAPI, HTTPDocSender, HTTPDocFetcher): """ A SyncTarget that encrypts data before sending and decrypts data after receiving. Normally encryption will have been written to the sync database upon document modification. The sync database is also used to write temporarily the parsed docum...
SoledadHTTPSyncTarget
identifier_name
base.js
define([ 'domReady', 'jquery', 'underscore', 'gettext', 'common/js/components/views/feedback_notification', 'common/js/components/views/feedback_prompt', 'js/utils/date_utils', 'js/utils/module', 'js/utils/handle_iframe_binding', 'edx-ui-toolkit/js/dropdown-menu/dropdown-menu-vie...
(e) { (e).preventDefault(); $.smoothScroll({ offset: -200, easing: 'swing', speed: 1000, scrollElement: null, scrollTarget: $(this).attr('href') }); } function hideNotification(e) { ...
smoothScrollLink
identifier_name
base.js
define([ 'domReady', 'jquery', 'underscore', 'gettext', 'common/js/components/views/feedback_notification', 'common/js/components/views/feedback_prompt', 'js/utils/date_utils', 'js/utils/module', 'js/utils/handle_iframe_binding', 'edx-ui-toolkit/js/dropdown-menu/dropdown-menu-vie...
domReady(function() { var dropdownMenuView; $body = $('body'); $body.on('click', '.embeddable-xml-input', function() { $(this).select(); }); $body.addClass('js'); // alerts/notifications - manual close $('.ac...
(e).preventDefault(); $(this).closest('.wrapper-alert').removeClass('is-shown'); }
random_line_split
base.js
define([ 'domReady', 'jquery', 'underscore', 'gettext', 'common/js/components/views/feedback_notification', 'common/js/components/views/feedback_prompt', 'js/utils/date_utils', 'js/utils/module', 'js/utils/handle_iframe_binding', 'edx-ui-toolkit/js/dropdown-menu/dropdown-menu-vie...
function hideAlert(e) { (e).preventDefault(); $(this).closest('.wrapper-alert').removeClass('is-shown'); } domReady(function() { var dropdownMenuView; $body = $('body'); $body.on('click', '.embeddable-xml-input', function() { ...
{ (e).preventDefault(); $(this) .closest('.wrapper-notification') .removeClass('is-shown') .addClass('is-hiding') .attr('aria-hidden', 'true'); }
identifier_body
base.js
define([ 'domReady', 'jquery', 'underscore', 'gettext', 'common/js/components/views/feedback_notification', 'common/js/components/views/feedback_prompt', 'js/utils/date_utils', 'js/utils/module', 'js/utils/handle_iframe_binding', 'edx-ui-toolkit/js/dropdown-menu/dropdown-menu-vie...
// Initiate the edx tool kit dropdown menu if ($('.js-header-user-menu').length) { dropdownMenuView = new DropdownMenuView({ el: '.js-header-user-menu' }); dropdownMenuView.postRender(); } window.studi...
{ $.ajaxSetup({cache: false}); }
conditional_block
mod.rs
use std::fmt; use super::Tile; use super::Direction; use super::Point; /// Defines the 2D square Grid trait for using the maze generator pub trait Grid { /// Gets tile data at a given position on a grid fn get_tile_data(&self, Point) -> Result<Tile, &'static str>; /// Gets the width and height respectiv...
(&mut self, (x, y): Point, dir: Direction) -> Result<Point, &'static str> { let (width, height) = self.get_dimensions(); let tiles = &mut self.tiles; // Determine directon to carve into let (x_c, y_c): Point = match dir { Direction::Up => (x, y + 1), ...
carve_path
identifier_name
mod.rs
use std::fmt; use super::Tile; use super::Direction; use super::Point; /// Defines the 2D square Grid trait for using the maze generator pub trait Grid { /// Gets tile data at a given position on a grid fn get_tile_data(&self, Point) -> Result<Tile, &'static str>; /// Gets the width and height respectiv...
return Result::Err("Cannot carve in desired dirrection"); } { let from_tile = &mut tiles[y][x]; // Set full tile as connected match *from_tile { Tile::Connected { up: ref mut u, down: r...
{ let (width, height) = self.get_dimensions(); let tiles = &mut self.tiles; // Determine directon to carve into let (x_c, y_c): Point = match dir { Direction::Up => (x, y + 1), Direction::Right => (x + 1, y), // Set direction to same as curre...
identifier_body
mod.rs
use std::fmt; use super::Tile; use super::Direction; use super::Point; /// Defines the 2D square Grid trait for using the maze generator pub trait Grid { /// Gets tile data at a given position on a grid fn get_tile_data(&self, Point) -> Result<Tile, &'static str>; /// Gets the width and height respective...
maze_temp.tiles.push(vec![]); // Push new tiles to the row for _ in 0..width { maze_temp.tiles[j].push(Tile::new()); } } maze_temp } }
random_line_split
tracklist.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import html from tinydb import TinyDB, Query import requests from . import get_logger, CONFIG class TracklistManager(object):
class Tracklist(object): def __init__(self, pid): """ See also https://github.com/StevenMaude/bbc_radio_tracklisting_downloader. :param pid: the unique pid of the episode """ self.pid = pid self.listing = [] url = "http://www.bbc.co.uk/programmes/{}/segm...
db = TinyDB(CONFIG["technical"]["tracklist-db"], indent=2, separators=(',', ': ')) get_logger().info("Starting tracklist manager with database at %s", CONFIG["technical"]["tracklist-db"]) @classmethod def get_tracklist(cls, pid): result = cls.db.get(Query().pid == pid) if not result: ...
identifier_body
tracklist.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import html from tinydb import TinyDB, Query import requests from . import get_logger, CONFIG class TracklistManager(object): db = TinyDB(CONFIG["technical"]["tracklist-db"], indent=2, separators=(',', ': ')) ge...
page = requests.get(url) tree = html.fromstring(page.text) for track in tree.xpath('//div[@class="segment__track"]'): try: artist_names = track.xpath('.//span[@property="byArtist"]//span[@class="artist"]/text()') except ValueError: artist_...
random_line_split
tracklist.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import html from tinydb import TinyDB, Query import requests from . import get_logger, CONFIG class TracklistManager(object): db = TinyDB(CONFIG["technical"]["tracklist-db"], indent=2, separators=(',', ': ')) ge...
else: tracklist = result["tracklist"] return tracklist class Tracklist(object): def __init__(self, pid): """ See also https://github.com/StevenMaude/bbc_radio_tracklisting_downloader. :param pid: the unique pid of the episode """ self.pid = pi...
get_logger().debug("Getting tracklist for: %s", pid) tracklist = Tracklist(pid).listing cls.db.insert({"pid": pid, "tracklist": tracklist})
conditional_block
tracklist.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals from lxml import html from tinydb import TinyDB, Query import requests from . import get_logger, CONFIG class TracklistManager(object): db = TinyDB(CONFIG["technical"]["tracklist-db"], indent=2, separators=(',', ': ')) ge...
(object): def __init__(self, pid): """ See also https://github.com/StevenMaude/bbc_radio_tracklisting_downloader. :param pid: the unique pid of the episode """ self.pid = pid self.listing = [] url = "http://www.bbc.co.uk/programmes/{}/segments.inc".format(s...
Tracklist
identifier_name
destination.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(Model): """Capture storage details for capture description. :param name: Name for capture destination :type name: str :param storage_account_resource_id: Resource id of the storage account to be used to create the blobs :type storage_account_resource_id: str :param blob_container: Blob co...
Destination
identifier_name
destination.py
# coding=utf-8 # --------------------------------------------------------------------------
# Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # --------------------------------------------------------------------------...
# Copyright (c) Microsoft Corporation. All rights reserved.
random_line_split
destination.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
'archive_name_format': {'key': 'properties.archiveNameFormat', 'type': 'str'}, } def __init__(self, name=None, storage_account_resource_id=None, blob_container=None, archive_name_format=None): self.name = name self.storage_account_resource_id = storage_account_resource_id self.b...
"""Capture storage details for capture description. :param name: Name for capture destination :type name: str :param storage_account_resource_id: Resource id of the storage account to be used to create the blobs :type storage_account_resource_id: str :param blob_container: Blob container Name ...
identifier_body
move-4-unique.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
{a: int, b: int, c: int} fn test(foo: Box<Triple>) -> Box<Triple> { let foo = foo; let bar = foo; let baz = bar; let quux = baz; return quux; } pub fn main() { let x = box Triple{a: 1, b: 2, c: 3}; let y = test(x); assert!((y.c == 3)); }
Triple
identifier_name
move-4-unique.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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. struct Triple {a: int, b: int, c: int} fn test(foo: Box<Triple>) -> Box<Triple> { let foo = foo; let bar = foo; let baz = bar; let quux ...
random_line_split
move-4-unique.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
{ let x = box Triple{a: 1, b: 2, c: 3}; let y = test(x); assert!((y.c == 3)); }
identifier_body
runauto.py
import requests import pytest import subprocess # ============================================================================ class TestAuto(object): PREFIX = 'http://localhost:8089' USER = 'testauto' LIST_ID = '' AUTO_ID = '' NUM_BROWSERS = 2 @classmethod def setup_class(cls): c...
pass def get(self, url, **kwargs): full_url = self.PREFIX + url return self.session.get(full_url, **kwargs) def post(self, url, **kwargs): full_url = self.PREFIX + url return self.session.post(full_url, **kwargs) @classmethod def delete(self, url, **kwargs): ...
random_line_split
runauto.py
import requests import pytest import subprocess # ============================================================================ class TestAuto(object): PREFIX = 'http://localhost:8089' USER = 'testauto' LIST_ID = '' AUTO_ID = '' NUM_BROWSERS = 2 @classmethod def setup_class(cls): c...
@pytest.mark.always def test_create_user(self): res = subprocess.run(['docker', 'exec', 'webrecorder_app_1', "python", "-m", "webrecorder.admin", "-c", "testauto@example.com", "testauto", "TestTest123", "archivist", "Auto Test"], stdout=subpro...
full_url = self.PREFIX + url return self.session.delete(full_url, **kwargs)
identifier_body
runauto.py
import requests import pytest import subprocess # ============================================================================ class TestAuto(object): PREFIX = 'http://localhost:8089' USER = 'testauto' LIST_ID = '' AUTO_ID = '' NUM_BROWSERS = 2 @classmethod def setup_class(cls): c...
(self): res = self.post('/api/v1/collections?user=testauto', json={'title': 'Auto Test'}) assert res.json()['collection']['id'] == 'auto-test' assert res.json()['collection']['title'] == 'Auto Test' def test_create_auto(self): params = {'scope_type': 'single...
test_create_coll
identifier_name
saver.py
import torch import pickle import logging from .baseclasses import ScalarMonitor from .meta import Regurgitate class Saver(ScalarMonitor): def __init__(self, save_monitor, model_file, settings_file, **kwargs): self.saved = False self.save_monitor = save_monitor self.model_file = model_file ...
with open(self.settings_file, "wb") as f: pickle.dump(settings, f)
model.cuda()
conditional_block
saver.py
import torch import pickle import logging from .baseclasses import ScalarMonitor from .meta import Regurgitate class Saver(ScalarMonitor): def __init__(self, save_monitor, model_file, settings_file, **kwargs): self.saved = False self.save_monitor = save_monitor self.model_file = model_file ...
with open(self.settings_file, "wb") as f: pickle.dump(settings, f)
with open(self.model_file, 'wb') as f: torch.save(model.cpu().state_dict(), f) if torch.cuda.is_available(): model.cuda()
random_line_split
saver.py
import torch import pickle import logging from .baseclasses import ScalarMonitor from .meta import Regurgitate class Saver(ScalarMonitor): def __init__(self, save_monitor, model_file, settings_file, **kwargs): self.saved = False self.save_monitor = save_monitor self.model_file = model_file ...
def save(self, model, settings): with open(self.model_file, 'wb') as f: torch.save(model.cpu().state_dict(), f) if torch.cuda.is_available(): model.cuda() with open(self.settings_file, "wb") as f: pickle.dump(settings, f)
if self.value is None: self.value = self.save_monitor.value if self.save_monitor.changed: self.save(model, settings) self.value = self.save_monitor.value return self.value
identifier_body
saver.py
import torch import pickle import logging from .baseclasses import ScalarMonitor from .meta import Regurgitate class Saver(ScalarMonitor): def __init__(self, save_monitor, model_file, settings_file, **kwargs): self.saved = False self.save_monitor = save_monitor self.model_file = model_file ...
(self, model=None, settings=None, **kwargs): if self.value is None: self.value = self.save_monitor.value if self.save_monitor.changed: self.save(model, settings) self.value = self.save_monitor.value return self.value def save(self, model, settings): ...
call
identifier_name
issue-54109-without-witness.rs
// run-rustfix // This test is to check if suggestions can be applied automatically. #![allow(dead_code, unused_parens)] fn main() {} fn test_and() { let a = true; let b = false; let _ = a and b; //~ ERROR `and` is not a logical operator if a and b { //~ ERROR `and` is not a logical operator ...
} fn test_or_par() { let a = true; let b = false; if (a or b) { //~ ERROR `or` is not a logical operator println!("both"); } } fn test_while_and() { let a = true; let b = false; while a and b { //~ ERROR `and` is not a logical operator println!("both"); } } fn test_...
{ //~ ERROR `and` is not a logical operator println!("both"); }
conditional_block
issue-54109-without-witness.rs
// run-rustfix // This test is to check if suggestions can be applied automatically. #![allow(dead_code, unused_parens)] fn main() {} fn test_and() { let a = true; let b = false; let _ = a and b; //~ ERROR `and` is not a logical operator if a and b { //~ ERROR `and` is not a logical operator ...
} } fn test_while_and() { let a = true; let b = false; while a and b { //~ ERROR `and` is not a logical operator println!("both"); } } fn test_while_or() { let a = true; let b = false; while a or b { //~ ERROR `or` is not a logical operator println!("both"); } }
fn test_or_par() { let a = true; let b = false; if (a or b) { //~ ERROR `or` is not a logical operator println!("both");
random_line_split
issue-54109-without-witness.rs
// run-rustfix // This test is to check if suggestions can be applied automatically. #![allow(dead_code, unused_parens)] fn main() {} fn
() { let a = true; let b = false; let _ = a and b; //~ ERROR `and` is not a logical operator if a and b { //~ ERROR `and` is not a logical operator println!("both"); } } fn test_or() { let a = true; let b = false; let _ = a or b; //~ ERROR `or` is not a logical operator ...
test_and
identifier_name
issue-54109-without-witness.rs
// run-rustfix // This test is to check if suggestions can be applied automatically. #![allow(dead_code, unused_parens)] fn main() {} fn test_and() { let a = true; let b = false; let _ = a and b; //~ ERROR `and` is not a logical operator if a and b { //~ ERROR `and` is not a logical operator ...
fn test_or_par() { let a = true; let b = false; if (a or b) { //~ ERROR `or` is not a logical operator println!("both"); } } fn test_while_and() { let a = true; let b = false; while a and b { //~ ERROR `and` is not a logical operator println!("both"); } } fn test_wh...
{ let a = true; let b = false; if (a and b) { //~ ERROR `and` is not a logical operator println!("both"); } }
identifier_body
caching.py
from typing import List, Tuple, Any from django.db.models import Max, QuerySet from semantic_version import Version from nextcloudappstore.core.models import App, AppReleaseDeleteLog, Category, \ AppRating, NextcloudRelease def create_etag(pairs: List[Tuple[QuerySet, str]]) -> str: """ Turn a list of que...
(request: Any, version: str) -> str: return create_etag([ (App.objects.all(), 'last_release'), (AppReleaseDeleteLog.objects.all(), 'last_modified'), ]) def apps_all_etag(request: Any) -> str: return create_etag([ (App.objects.all(), 'last_release'), (AppReleaseDeleteLog.obj...
apps_etag
identifier_name
caching.py
from typing import List, Tuple, Any from django.db.models import Max, QuerySet from semantic_version import Version from nextcloudappstore.core.models import App, AppReleaseDeleteLog, Category, \ AppRating, NextcloudRelease def create_etag(pairs: List[Tuple[QuerySet, str]]) -> str: """ Turn a list of que...
def app_etag(request: Any, id: str) -> str: return str(App.objects.get(id=id).last_modified) def app_rating_etag(request: Any, id: str) -> str: return create_etag([(AppRating.objects.filter(app__id=id), 'rated_at')]) def categories_etag(request: Any) -> str: return create_etag([(Category.objects.all(...
return create_etag([ (App.objects.all(), 'last_release'), (AppReleaseDeleteLog.objects.all(), 'last_modified'), ])
identifier_body
caching.py
from typing import List, Tuple, Any from django.db.models import Max, QuerySet from semantic_version import Version from nextcloudappstore.core.models import App, AppReleaseDeleteLog, Category, \ AppRating, NextcloudRelease def create_etag(pairs: List[Tuple[QuerySet, str]]) -> str: """ Turn a list of que...
return '%d-%s' % (release_num, latest_release)
latest_release = ''
conditional_block
caching.py
from typing import List, Tuple, Any from django.db.models import Max, QuerySet from semantic_version import Version from nextcloudappstore.core.models import App, AppReleaseDeleteLog, Category, \ AppRating, NextcloudRelease def create_etag(pairs: List[Tuple[QuerySet, str]]) -> str: """ Turn a list of que...
def app_rating_etag(request: Any, id: str) -> str: return create_etag([(AppRating.objects.filter(app__id=id), 'rated_at')]) def categories_etag(request: Any) -> str: return create_etag([(Category.objects.all(), 'last_modified')]) def app_ratings_etag(request: Any) -> str: return create_etag([(AppRatin...
def app_etag(request: Any, id: str) -> str: return str(App.objects.get(id=id).last_modified)
random_line_split
Utility.js
Object} opt * @param {string} fieldName * @param {*} defaultV * @return {*} */ getOpt(opt, fieldName, defaultV) { if (opt === undefined) { return defaultV; } return (typeof opt[fieldName] !== 'undefined') ? opt[fieldName] : defaultV; }, /** * * @param...
{ round = true; }
conditional_block
Utility.js
angle < 0) { angle += 360; } let directions = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'], octant = Math.round(8 * angle / (2 * Math.PI) + 8) % 8; return directions[octant]; }, /** * * @param {HTMLElement} element * @return {{x: number, y: number}} */ ...
(opt, fieldName, defaultV) { if (opt === undefined) { return defaultV; } return (typeof opt[fieldName] !== 'undefined') ? opt[fieldName] : defaultV; }, /** * * @param {number|string} hex * @return {*} */ hexToRgb(hex) { if (!isNaN(hex)) { hex = "#...
getOpt
identifier_name
Utility.js
angle < 0) { angle += 360; } let directions = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'], octant = Math.round(8 * angle / (2 * Math.PI) + 8) % 8; return directions[octant]; }, /** * * @param {HTMLElement} element * @return {{x: number, y: number}} */ ...
} }, /** * */ Maths: { /** * Gaussian random number * @return {number} */ gaussRandom: function () { if (retV) { retV = false; return vVal; } let u = 2 * Math.random() - 1, v = 2 * Math.random() - 1, ...
}).indexOf(id);
random_line_split
Utility.js
angle < 0) { angle += 360; } let directions = ['S', 'SE', 'E', 'NE', 'N', 'NW', 'W', 'SW'], octant = Math.round(8 * angle / (2 * Math.PI) + 8) % 8; return directions[octant]; }, /** * * @param {HTMLElement} element * @return {{x: number, y: number}} */ ...
element.async = true; break; case 'link': element.type = 'text/css'; element.rel = 'stylesheet'; attr = 'href'; parent = 'head'; } // Inject into document to kick off loading ...
{ return function (url) { // This promise will be used by Promise.all // to determine success or failure return new Promise(function (resolve, reject) { var element = document.createElement(tag), parent = 'body', attr = 'src'; //...
identifier_body
settings.py
from django.conf import settings BACKEND_CLASS = getattr( settings, "COURRIERS_BACKEND_CLASS", "courriers.backends.simple.SimpleBackend" ) MAILCHIMP_API_KEY = getattr(settings, "COURRIERS_MAILCHIMP_API_KEY", "") MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "") MAILJET_CONTACTSLIST_LIMIT = g...
FAIL_SILENTLY = getattr(settings, "COURRIERS_FAIL_SILENTLY", False) NEWSLETTERLIST_MODEL = getattr( settings, "COURRIERS_NEWSLETTERLIST_MODEL", "courriers.models.newsletterlist.NewsletterList", ) NEWSLETTER_MODEL = getattr( settings, "COURRIERS_NEWSLETTER_MODEL", "courriers.models.newsletter.Newslett...
PRE_PROCESSORS = getattr(settings, "COURRIERS_PRE_PROCESSORS", ()) PAGINATE_BY = getattr(settings, "COURRIERS_PAGINATE_BY", 9)
random_line_split
masonry-cards.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-masonry-cards', templateUrl: 'masonry-cards.html', }) export class
{ posts = []; constructor(public navCtrl: NavController, public navParams: NavParams) { } ionViewDidLoad() { this.posts = [ { description: 'Trying out digital painting', image: 'https://s-media-cache-ak0.pinimg.com/564x/d5/63/b0/d563b08194f0a92cc7d381f7f8582a08.jpg' }, ...
MasonryCardsPage
identifier_name
masonry-cards.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-masonry-cards', templateUrl: 'masonry-cards.html', }) export class MasonryCardsPage { posts = []; constructor(public navCtrl: NavController, public navPara...
ionViewDidLoad() { this.posts = [ { description: 'Trying out digital painting', image: 'https://s-media-cache-ak0.pinimg.com/564x/d5/63/b0/d563b08194f0a92cc7d381f7f8582a08.jpg' }, { description: '', image: 'https://s-media-cache-ak0.pinimg.com/236x/43/f3/3d/43f3...
{ }
identifier_body
masonry-cards.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-masonry-cards', templateUrl: 'masonry-cards.html', }) export class MasonryCardsPage { posts = []; constructor(public navCtrl: NavController, public navPara...
}, { description: '', image: 'https://s-media-cache-ak0.pinimg.com/564x/0d/29/35/0d2935d14c17aff1baab75360c9e2bd6.jpg' }, { description: 'Delicious chocolate bread recipe!', image: 'https://s-media-cache-ak0.pinimg.com/564x/06/a9/8e/06a98e67111aae83a481a2c1dbb594a...
}, { description: '', image: 'https://s-media-cache-ak0.pinimg.com/564x/f6/61/5c/f6615ca7068da18157588890f9e9e03a.jpg'
random_line_split
rewrite_from.py
#!/usr/bin/python ''' ## Description A script to get mail from info@example.com and re-write the 'From"' Header as "From: John Doe via info at example.com <noreply@example.com>'" ## Installation Instuctions * Place the script under */usr/local/sbin/rewrite_from.py*. * Edit */etc/aliases*: ``` info: "|/usr/local/sb...
if from_re: from_h = from_re.group(1) if msg['Reply-To']: msg['Reply-To'] = reply_to msg.replace_header('Reply-To', reply_to) else: msg.add_header('Reply-To', reply_to) msg.replace_header('From', from_h + ' via info at example.com <noreply@example.com>') send_mail...
''' Main Function ''' raw_msg = '' for line in sys.stdin: raw_msg = raw_msg + line msg = email.message_from_string(raw_msg) reply_to_re = re.search( r'([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-.]+\.[a-zA-Z0-9-.]+)', msg['From']) if reply_to_re: reply_to = reply_to_re.g...
identifier_body
rewrite_from.py
#!/usr/bin/python ''' ## Description A script to get mail from info@example.com and re-write the 'From"' Header as "From: John Doe via info at example.com <noreply@example.com>'" ## Installation Instuctions * Place the script under */usr/local/sbin/rewrite_from.py*. * Edit */etc/aliases*: ``` info: "|/usr/local/sb...
(): ''' Main Function ''' raw_msg = '' for line in sys.stdin: raw_msg = raw_msg + line msg = email.message_from_string(raw_msg) reply_to_re = re.search( r'([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-.]+\.[a-zA-Z0-9-.]+)', msg['From']) if reply_to_re: reply_to = reply...
main
identifier_name
rewrite_from.py
#!/usr/bin/python ''' ## Description A script to get mail from info@example.com and re-write the 'From"' Header
## Installation Instuctions * Place the script under */usr/local/sbin/rewrite_from.py*. * Edit */etc/aliases*: ``` info: "|/usr/local/sbin/rewrite_from.py" ``` * Run the `newaliases` command. ''' import sys import email import smtplib import re DEBUG = 1 MAIL_SERVER = 'localhost' TO = ["ceo@example.com", "ceoexterna...
as "From: John Doe via info at example.com <noreply@example.com>'"
random_line_split
rewrite_from.py
#!/usr/bin/python ''' ## Description A script to get mail from info@example.com and re-write the 'From"' Header as "From: John Doe via info at example.com <noreply@example.com>'" ## Installation Instuctions * Place the script under */usr/local/sbin/rewrite_from.py*. * Edit */etc/aliases*: ``` info: "|/usr/local/sb...
if msg['Reply-To']: msg['Reply-To'] = reply_to msg.replace_header('Reply-To', reply_to) else: msg.add_header('Reply-To', reply_to) msg.replace_header('From', from_h + ' via info at example.com <noreply@example.com>') send_mail = smtplib.SMTP('localhost') send_mail.sendmai...
from_h = from_re.group(1)
conditional_block
0002_auto__add_field_subscription_paid.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Subscription.paid' db.add_column(u'subscriptions_subscription', 'paid', ...
complete_apps = ['subscriptions']
random_line_split
0002_auto__add_field_subscription_paid.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Subscription.paid' db.add_column(u'subscriptions_subscription', 'paid', ...
models = { u'subscriptions.subscription': { 'Meta': {'ordering': "['created_at']", 'object_name': 'Subscription'}, 'cpf': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '11'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'au...
db.delete_column(u'subscriptions_subscription', 'paid')
identifier_body
0002_auto__add_field_subscription_paid.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class
(SchemaMigration): def forwards(self, orm): # Adding field 'Subscription.paid' db.add_column(u'subscriptions_subscription', 'paid', self.gf('django.db.models.fields.BooleanField')(default=False), keep_default=False) def backwards(self, orm): ...
Migration
identifier_name
pca.rs
//! Principal Component Analysis Module //! //! Contains implementation of PCA. //! //! # Examples //! //! ``` //! use rusty_machine::learning::pca::PCA; //! use rusty_machine::learning::UnSupModel; //! //! use rusty_machine::linalg::Matrix; //! let mut pca = PCA::default(); //! //! let inputs = Matrix::new(3, 2, vec![...
self.components = match self.n { Some(c) => { let slicer: Vec<usize> = (0..c).collect(); Some(v.select_cols(&slicer)) }, None => Some(v) }; self.n_features = Some(inputs.cols()); Ok(()) } } /// Subtract center Vect...
if inputs.cols() > inputs.rows() { v = v.transpose(); self.inv = true; }
random_line_split
pca.rs
//! Principal Component Analysis Module //! //! Contains implementation of PCA. //! //! # Examples //! //! ``` //! use rusty_machine::learning::pca::PCA; //! use rusty_machine::learning::UnSupModel; //! //! use rusty_machine::linalg::Matrix; //! let mut pca = PCA::default(); //! //! let inputs = Matrix::new(3, 2, vec![...
(inputs: &Matrix<f64>, centers: &Vector<f64>) -> Matrix<f64> { // Number of inputs columns and centers length must be the same Matrix::from_fn(inputs.rows(), inputs.cols(), |c, r| inputs.get_unchecked([r, c]) - centers.data().get_unchecked(c)) } #[cfg(test)] mod tests { use linalg::{Ma...
centering
identifier_name
pca.rs
//! Principal Component Analysis Module //! //! Contains implementation of PCA. //! //! # Examples //! //! ``` //! use rusty_machine::learning::pca::PCA; //! use rusty_machine::learning::UnSupModel; //! //! use rusty_machine::linalg::Matrix; //! let mut pca = PCA::default(); //! //! let inputs = Matrix::new(3, 2, vec![...
} /// The default PCA. /// /// Parameters: /// /// - `n` = `None` (keep all components) /// - `center` = `true` /// /// # Examples /// /// ``` /// use rusty_machine::learning::pca::PCA; /// /// let model = PCA::default(); /// ``` impl Default for PCA { fn default() -> Self { PCA { // because n...
{ match self.components { None => Err(Error::new_untrained()), Some(ref rot) => { Ok(rot) } } }
identifier_body
env_path.py
"""ENV Str""" # standard library import os import re from pathlib import Path from typing import Any, Dict, Union class _EnvPath(type(Path()), Path): # pylint: disable=E0241 """A stub of Path with additional attribute.""" # store for the original value passed to EnvPath original_value = None class Env...
string = str(value) for m in re.finditer(r'\${(env|envs|local|remote):(.*?)}', string): try: full_match = m.group(0) env_type = m.group(1) env_key = m.group(2) if env_type != 'env': raise ValueError(f'Invali...
def validate(cls, value: Union[str, Path]) -> Path: """Replace any environment variables in the tcex.json file.""" if isinstance(value, Path): return value
random_line_split
env_path.py
"""ENV Str""" # standard library import os import re from pathlib import Path from typing import Any, Dict, Union class _EnvPath(type(Path()), Path): # pylint: disable=E0241
class EnvPath(Path): """EnvPath custom pydantic model type.""" @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: """.""" field_schema.update(format='file-path') @classmethod def __get_validators__(cls) -> 'CallableGenerator': # noqa: F821 ""...
"""A stub of Path with additional attribute.""" # store for the original value passed to EnvPath original_value = None
identifier_body
env_path.py
"""ENV Str""" # standard library import os import re from pathlib import Path from typing import Any, Dict, Union class _EnvPath(type(Path()), Path): # pylint: disable=E0241 """A stub of Path with additional attribute.""" # store for the original value passed to EnvPath original_value = None class
(Path): """EnvPath custom pydantic model type.""" @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: """.""" field_schema.update(format='file-path') @classmethod def __get_validators__(cls) -> 'CallableGenerator': # noqa: F821 """.""" yi...
EnvPath
identifier_name
env_path.py
"""ENV Str""" # standard library import os import re from pathlib import Path from typing import Any, Dict, Union class _EnvPath(type(Path()), Path): # pylint: disable=E0241 """A stub of Path with additional attribute.""" # store for the original value passed to EnvPath original_value = None class Env...
env_value = os.getenv(env_key) if env_value is not None: string = string.replace(full_match, env_value) except IndexError: return string # convert value to Path and return original value p = _EnvPath(os.path.expanduser(str...
raise ValueError(f'Invalid environment type found ({env_type})')
conditional_block
BasicBlockStartState.js
"use strict"; /*! * Copyright 2016 The ANTLR Project. All rights reserved. * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. */
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate...
random_line_split
BasicBlockStartState.js
"use strict"; /*! * Copyright 2016 The ANTLR Project. All rights reserved. * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3...
} __decorate([ Decorators_1.Override ], BasicBlockStartState.prototype, "stateType", null); exports.BasicBlockStartState = BasicBlockStartState; //# sourceMappingURL=BasicBlockStartState.js.map
{ return ATNStateType_1.ATNStateType.BLOCK_START; }
identifier_body
BasicBlockStartState.js
"use strict"; /*! * Copyright 2016 The ANTLR Project. All rights reserved. * Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information. */ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3...
() { return ATNStateType_1.ATNStateType.BLOCK_START; } } __decorate([ Decorators_1.Override ], BasicBlockStartState.prototype, "stateType", null); exports.BasicBlockStartState = BasicBlockStartState; //# sourceMappingURL=BasicBlockStartState.js.map
stateType
identifier_name
broadcast.py
from __future__ import print_function import sys sys.path.append('..') from src.sim import Sim from src.packet import Packet from networks.network import Network class BroadcastApp(object): def __init__(self, node): self.node = node def
(self, packet): print(Sim.scheduler.current_time(), self.node.hostname, packet.ident) def main(): # parameters Sim.scheduler.reset() # setup network net = Network('../networks/five-nodes.txt') # get nodes n1 = net.get_node('n1') n2 = net.get_node('n2') n3 = net.get_node('n3')...
receive_packet
identifier_name
broadcast.py
from __future__ import print_function import sys sys.path.append('..') from src.sim import Sim from src.packet import Packet from networks.network import Network class BroadcastApp(object):
def main(): # parameters Sim.scheduler.reset() # setup network net = Network('../networks/five-nodes.txt') # get nodes n1 = net.get_node('n1') n2 = net.get_node('n2') n3 = net.get_node('n3') n4 = net.get_node('n4') n5 = net.get_node('n5') # setup broadcast application ...
def __init__(self, node): self.node = node def receive_packet(self, packet): print(Sim.scheduler.current_time(), self.node.hostname, packet.ident)
identifier_body
broadcast.py
from __future__ import print_function import sys sys.path.append('..') from src.sim import Sim from src.packet import Packet from networks.network import Network class BroadcastApp(object): def __init__(self, node): self.node = node def receive_packet(self, packet): print(Sim.scheduler.cu...
main()
conditional_block
broadcast.py
from __future__ import print_function import sys sys.path.append('..') from src.sim import Sim from src.packet import Packet from networks.network import Network class BroadcastApp(object): def __init__(self, node): self.node = node def receive_packet(self, packet): print(Sim.scheduler.cu...
# send a broadcast packet from 3 with TTL 1, so just nodes 1, 4, and 5 # should get it p = Packet( source_address=n3.get_address('n1'), destination_address=0, ident=3, ttl=1, protocol='broadcast', length=100) Sim.scheduler.add(delay=2, event=p, handler=n3.send_packet) # run ...
Sim.scheduler.add(delay=1, event=p, handler=n1.send_packet)
random_line_split
xwjemail.py
# coding: utf-8 ''' Created on 2012-8-30 @author: shanfeng ''' import smtplib from email.mime.text import MIMEText import urllib import web class XWJemail: ''' classdocs ''' def __init__(self, params):
@staticmethod def sendfindpass(user,hash): link = "%s/account/newpass?%s" %(web.ctx.sitehost,urllib.urlencode({'email':user.u_email,"v":hash})) mail_body = """ <html> <head></head> <body> <h4>%s,你好</h4> 您刚才在 liulin.info 申请了找回密码。<br> 请点击下面的链接来重置密码:<br> <a href="%s">%s</a><br> 如果无法点击上面的链接,您可以复制该地址,并粘帖在浏览器的地址栏中访...
''' Constructor ''' pass
identifier_body
xwjemail.py
# coding: utf-8 ''' Created on 2012-8-30 @author: shanfeng ''' import smtplib from email.mime.text import MIMEText import urllib import web class
: ''' classdocs ''' def __init__(self, params): ''' Constructor ''' pass @staticmethod def sendfindpass(user,hash): link = "%s/account/newpass?%s" %(web.ctx.sitehost,urllib.urlencode({'email':user.u_email,"v":hash})) mail_body = """ <html> <head></head> <body> <h4>%s,你好</h4> 您刚才在 liulin.info 申请了找回密...
XWJemail
identifier_name
xwjemail.py
# coding: utf-8 ''' Created on 2012-8-30 @author: shanfeng ''' import smtplib from email.mime.text import MIMEText import urllib import web class XWJemail: ''' classdocs ''' def __init__(self, params): ''' Constructor ''' pass @staticmethod def sendfindpass(user,hash): link = "%s/account/newpass?%s"...
(mail_body,'html','utf-8') #msg=MIMEText(mail_body,'html') if not isinstance(mail_subject,unicode): mail_subject = unicode(mail_subject) msg['Subject']= mail_subject msg['From']=mail_from msg['To'] = mail_to msg["Accept-Language"]="zh-CN" msg["Accept-Charset"]="ISO-8859-1,utf-8" smtp=smtplib.S...
fo重置密码邮件' msg = MIMEText
conditional_block
xwjemail.py
# coding: utf-8 ''' Created on 2012-8-30 @author: shanfeng
import smtplib from email.mime.text import MIMEText import urllib import web class XWJemail: ''' classdocs ''' def __init__(self, params): ''' Constructor ''' pass @staticmethod def sendfindpass(user,hash): link = "%s/account/newpass?%s" %(web.ctx.sitehost,urllib.urlencode({'email':user.u_email,"v":h...
'''
random_line_split