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
rustwin.rs
WinEvent { EventNone, MouseMotion(Window, Buttons,ScreenPos), MouseButtonDown(Window,Buttons,ScreenPos), MouseButtonUp(Window,Buttons,ScreenPos), KeyDown(Window,Key_t,Modifiers,ScreenPos), KeyUp(Window,Key_t,Modifiers,ScreenPos), Accelerometer(Window,(i32,i32,i32)), JoypadEvent(Window,Vec2d,Vec2d,Buttons), Mu...
(w:&Window)->bool { *w==g_root_window } pub fn get_key_state(k:char)->i32 { unsafe { if g_keys[(k as uint) & 255] {1} else {0} } } pub struct Joypad { sticks:[Vec2f,..2], buttons:i32, press:i32, unpress:i32 // rumble ? tilt ? accelerometers? } impl Joypad { pub fn new()->Joypad { Joypad{ sticks:[zero(),zer...
is_root_window
identifier_name
provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class ShopifyAccount(ProviderAccount): pass class ShopifyProvider(OAuth2Provider): id = 'shopify' name = 'Shopify' a...
def get_default_scope(self): return ['read_orders', 'read_products'] def extract_uid(self, data): return str(data['shop']['id']) def extract_common_fields(self, data): # See: https://docs.shopify.com/api/shop # User is only available with Shopify Plus, email is the only ...
ret = super(ShopifyProvider, self).get_auth_params(request, action) shop = request.GET.get('shop', None) if shop: ret.update({'shop': shop}) return ret
identifier_body
provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class ShopifyAccount(ProviderAccount): pass class ShopifyProvider(OAuth2Provider): id = 'shopify' name = 'Shopify' a...
(self, data): # See: https://docs.shopify.com/api/shop # User is only available with Shopify Plus, email is the only # common field return dict(email=data['shop']['email']) providers.registry.register(ShopifyProvider)
extract_common_fields
identifier_name
provider.py
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class ShopifyAccount(ProviderAccount): pass class ShopifyProvider(OAuth2Provider): id = 'shopify' name = 'Shopify' a...
return ret def get_default_scope(self): return ['read_orders', 'read_products'] def extract_uid(self, data): return str(data['shop']['id']) def extract_common_fields(self, data): # See: https://docs.shopify.com/api/shop # User is only available with Shopify Plus, ...
ret.update({'shop': shop})
conditional_block
provider.py
class ShopifyAccount(ProviderAccount): pass class ShopifyProvider(OAuth2Provider): id = 'shopify' name = 'Shopify' account_class = ShopifyAccount def get_auth_params(self, request, action): ret = super(ShopifyProvider, self).get_auth_params(request, action) shop = request.GET.ge...
from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider
random_line_split
chat.websocket.ts
/// <reference path="../vendor/underscore.d.ts" /> /// <reference path="../vendor/strophe.d.ts" /> var WEB_API_HOST = window.location.hostname; var WEB_API_PORT = 8000; var webSockets = {}; function HasWebSocketForRoom(room) { return webSockets.hasOwnProperty(room); } function SendRoomMessage(room, msg) { ...
oom, onConnectedCallback) { var roomHost = GetHostFromRoom(room); if (!roomHost) { throw new Error('expected to find chat host from room "' + room + '"'); } var webSocket = webSockets[room] = new WebSocket('ws://' + WEB_API_HOST + ':' + WEB_API_PORT + '/api/chat', 'xmpp'); webSocket.onope...
eateWebSocketForRoom(r
identifier_name
chat.websocket.ts
/// <reference path="../vendor/underscore.d.ts" /> /// <reference path="../vendor/strophe.d.ts" /> var WEB_API_HOST = window.location.hostname; var WEB_API_PORT = 8000; var webSockets = {}; function HasWebSocketForRoom(room) { return webSockets.hasOwnProperty(room); } function SendRoomMessage(room, msg) { ...
function ParseXml(xml) { if (typeof DOMParser !== 'undefined') { var domParser = new DOMParser(); return domParser.parseFromString(xml, 'text/xml'); } else if (typeof ActiveXObject !== 'undefined' && new ActiveXObject("Microsoft.XMLDOM")) { var xmlDoc = new ActiveXObject("Microsoft.XMLDO...
if (parts.length == 2) { return parts[1]; } }
random_line_split
chat.websocket.ts
/// <reference path="../vendor/underscore.d.ts" /> /// <reference path="../vendor/strophe.d.ts" /> var WEB_API_HOST = window.location.hostname; var WEB_API_PORT = 8000; var webSockets = {}; function HasWebSocketForRoom(room) { return webSockets.hasOwnProperty(room); } function SendRoomMessage(room, msg) { ...
if (!_.isString(attrs.version)) { attrs.version = '1.0'; } return { toString: function() { var data = []; for (var key in attrs) { if (attrs.hasOwnProperty(key) && key != 'xmlns' && key != 'xmlns:stream' && key != 'version') { dat...
attrs['xmlns:stream'] = 'http://etherx.jabber.org/streams'; }
conditional_block
chat.websocket.ts
/// <reference path="../vendor/underscore.d.ts" /> /// <reference path="../vendor/strophe.d.ts" /> var WEB_API_HOST = window.location.hostname; var WEB_API_PORT = 8000; var webSockets = {}; function HasWebSocketForRoom(room) { return webSockets.hasOwnProperty(room); } function SendRoomMessage(room, msg) { ...
function CreateWebSocketForRoom(room, onConnectedCallback) { var roomHost = GetHostFromRoom(room); if (!roomHost) { throw new Error('expected to find chat host from room "' + room + '"'); } var webSocket = webSockets[room] = new WebSocket('ws://' + WEB_API_HOST + ':' + WEB_API_PORT + '/api/cha...
if (HasWebSocketForRoom(room)) { SendRoomMessage(room, $msg({ to: room, from: room + '/' + userName, type: 'groupchat' }).c('body').t(input)); } else { CreateWebSocketForRoom(room, function() { SendWebSocketGroupChatMessage(messageType, room, input); }); } }
identifier_body
textwidget.py
from roam.api import RoamEvents from PyQt4.QtGui import QLineEdit, QPlainTextEdit from PyQt4.QtCore import QEvent from roam.editorwidgets.core import EditorWidget, registerwidgets class TextWidget(EditorWidget): widgettype = 'Text' def __init__(self, *args):
def initWidget(self, widget): widget.textChanged.connect(self.emitvaluechanged) widget.installEventFilter(self) def eventFilter(self, object, event): # Hack I really don't like this but there doesn't seem to be a better way at the # moment if event.type() == QEvent.Focus...
super(TextWidget, self).__init__(*args) def createWidget(self, parent): return QLineEdit(parent)
random_line_split
textwidget.py
from roam.api import RoamEvents from PyQt4.QtGui import QLineEdit, QPlainTextEdit from PyQt4.QtCore import QEvent from roam.editorwidgets.core import EditorWidget, registerwidgets class TextWidget(EditorWidget): widgettype = 'Text' def __init__(self, *args): super(TextWidget, self).__init__(*args) ...
else: return True def setvalue(self, value): # Not the best way but should cover most use cases # for now value = value or '' value = unicode(value) try: self.widget.setPlainText(value) except AttributeError: self.widget.s...
return False
conditional_block
textwidget.py
from roam.api import RoamEvents from PyQt4.QtGui import QLineEdit, QPlainTextEdit from PyQt4.QtCore import QEvent from roam.editorwidgets.core import EditorWidget, registerwidgets class TextWidget(EditorWidget): widgettype = 'Text' def __init__(self, *args): super(TextWidget, self).__init__(*args) ...
(self, parent): return QPlainTextEdit(parent)
createWidget
identifier_name
textwidget.py
from roam.api import RoamEvents from PyQt4.QtGui import QLineEdit, QPlainTextEdit from PyQt4.QtCore import QEvent from roam.editorwidgets.core import EditorWidget, registerwidgets class TextWidget(EditorWidget):
if not self.value(): return False else: return True def setvalue(self, value): # Not the best way but should cover most use cases # for now value = value or '' value = unicode(value) try: self.widget.setPlainText(value) ...
widgettype = 'Text' def __init__(self, *args): super(TextWidget, self).__init__(*args) def createWidget(self, parent): return QLineEdit(parent) def initWidget(self, widget): widget.textChanged.connect(self.emitvaluechanged) widget.installEventFilter(self) def eventFil...
identifier_body
PointerEvent.spec.ts
import * as helpers from '@interactjs/core/tests/_helpers' import * as pointerUtils from '@interactjs/utils/pointerUtils' import PointerEvent from './PointerEvent' test('PointerEvent constructor', () => { const type = 'TEST_EVENT' const pointerId = -100 const testPointerProp = ['TEST_POINTER_PROP'] const poin...
expect(pointerEvent.clientX).toBe(event.clientX - origin.x) // subtractOrigin updates clientY correctly expect(pointerEvent.clientY).toBe(event.clientY - origin.y) pointerEvent._addOrigin(origin) // addOrigin with the subtracted origin reverts to original coordinates expect(['pageX', 'pageY', 'clientX', 'c...
// subtractOrigin updates clientX correctly
random_line_split
writer.py
#!/usr/bin/env python #coding=utf-8 # Filename: writer.py ''' 日志记录 @author: 1th @data: 2017.2.28 ''' from time import sleep import datetime from simpleat.conf import settings, globalvar from simpleat.core import exceptions from .logger import write_log _CMD_OUT = settings.CMD_OUT # 是否在命令行进行输出 _LOG_OUT = settings.LOG...
content, level = globalvar.g_hold_lognote.get() if _LOG_OUT: log(content, level) sleep(0.5)
identifier_body
writer.py
#!/usr/bin/env python #coding=utf-8 # Filename: writer.py '''
''' from time import sleep import datetime from simpleat.conf import settings, globalvar from simpleat.core import exceptions from .logger import write_log _CMD_OUT = settings.CMD_OUT # 是否在命令行进行输出 _LOG_OUT = settings.LOG_OUT # 程序运行过程中是否开启日志输出 _LOG_DIR = settings.LOG_DIR # log文件存储文件夹 def log(logmsg, level, logstr=_LO...
日志记录 @author: 1th @data: 2017.2.28
random_line_split
writer.py
#!/usr/bin/env python #coding=utf-8 # Filename: writer.py ''' 日志记录 @author: 1th @data: 2017.2.28 ''' from time import sleep import datetime from simpleat.conf import settings, globalvar from simpleat.core import exceptions from .logger import write_log _CMD_OUT = settings.CMD_OUT # 是否在命令行进行输出 _LOG_OUT = settings.LOG...
level: 日志等级 logstr: log文件文件夹 ''' fulllogmsg = ''.join(['[', datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), \ '] - ', level, ' - ', unicode(logmsg)]) try: write_log(fulllogmsg, level, logstr) except exceptions.WriteLogException as wle: if _CMD_OUT: ...
:
identifier_name
writer.py
#!/usr/bin/env python #coding=utf-8 # Filename: writer.py ''' 日志记录 @author: 1th @data: 2017.2.28 ''' from time import sleep import datetime from simpleat.conf import settings, globalvar from simpleat.core import exceptions from .logger import write_log _CMD_OUT = settings.CMD_OUT # 是否在命令行进行输出 _LOG_OUT = settings.LOG...
conditional_block
test_init.py
"""The tests for the Switch component.""" import pytest from homeassistant import core from homeassistant.components import switch from homeassistant.const import CONF_PLATFORM from homeassistant.setup import async_setup_component from tests.components.switch import common @pytest.fixture(autouse=True) def entities...
async def test_methods(hass, entities, enable_custom_integrations): """Test is_on, turn_on, turn_off methods.""" switch_1, switch_2, switch_3 = entities assert await async_setup_component( hass, switch.DOMAIN, {switch.DOMAIN: {CONF_PLATFORM: "test"}} ) await hass.async_block_till_done() ...
"""Initialize the test switch.""" platform = getattr(hass.components, "test.switch") platform.init() yield platform.ENTITIES
identifier_body
test_init.py
"""The tests for the Switch component.""" import pytest from homeassistant import core from homeassistant.components import switch from homeassistant.const import CONF_PLATFORM from homeassistant.setup import async_setup_component from tests.components.switch import common @pytest.fixture(autouse=True) def
(hass): """Initialize the test switch.""" platform = getattr(hass.components, "test.switch") platform.init() yield platform.ENTITIES async def test_methods(hass, entities, enable_custom_integrations): """Test is_on, turn_on, turn_off methods.""" switch_1, switch_2, switch_3 = entities asse...
entities
identifier_name
test_init.py
"""The tests for the Switch component.""" import pytest from homeassistant import core from homeassistant.components import switch from homeassistant.const import CONF_PLATFORM from homeassistant.setup import async_setup_component from tests.components.switch import common @pytest.fixture(autouse=True) def entities...
) state2 = hass.states.get("switch.ac") assert state2 is not None assert state.state != state2.state assert state2.context.user_id == hass_admin_user.id
{"entity_id": state.entity_id}, True, core.Context(user_id=hass_admin_user.id),
random_line_split
balance-history-graph.component.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, Injector, Input } from '@angular/core'; import { FrontendDashboardAccount } from 'app/api/models'; import { BaseComponent } from 'app/shared/base.component'; import moment from 'moment-mini-ts'; import { BehaviorSubject, interval } from 'rxjs'; import { takeWh...
const values = balances.map(b => parseFloat(b.amount)); let maxValue = Math.max(...values); let minValue = Math.min(...values); let valueRange = maxValue - minValue; // Rescale the displayed max / min according to the actual range. // For example, from 1345 to 1378, consider from 1300 to 1400....
{ // Won't show a graph with a single data point return; }
conditional_block
balance-history-graph.component.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, Injector, Input } from '@angular/core'; import { FrontendDashboardAccount } from 'app/api/models'; import { BaseComponent } from 'app/shared/base.component'; import moment from 'moment-mini-ts'; import { BehaviorSubject, interval } from 'rxjs'; import { takeWh...
return; } const values = balances.map(b => parseFloat(b.amount)); let maxValue = Math.max(...values); let minValue = Math.min(...values); let valueRange = maxValue - minValue; // Rescale the displayed max / min according to the actual range. // For example, from 1345 to 1378, consider...
const currency = this.account.account.currency; const balances = (this.account?.balances || []); if (balances.length <= 1) { // Won't show a graph with a single data point
random_line_split
balance-history-graph.component.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, Injector, Input } from '@angular/core'; import { FrontendDashboardAccount } from 'app/api/models'; import { BaseComponent } from 'app/shared/base.component'; import moment from 'moment-mini-ts'; import { BehaviorSubject, interval } from 'rxjs'; import { takeWh...
(bb: DOMRect): void { this.width = bb.width; this.height = bb.height; this.xMax = this.width - 20; this.yMin = 15; this.yMax = this.height - 40; const currency = this.account.account.currency; const balances = (this.account?.balances || []); if (balances.length <= 1) { // Won't sh...
init
identifier_name
balance-history-graph.component.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, Injector, Input } from '@angular/core'; import { FrontendDashboardAccount } from 'app/api/models'; import { BaseComponent } from 'app/shared/base.component'; import moment from 'moment-mini-ts'; import { BehaviorSubject, interval } from 'rxjs'; import { takeWh...
ngAfterViewInit() { const element = this.element; this.addSub(interval(50).pipe(takeWhile(() => !this.initialized$.value)).subscribe(() => { const rect = element.getBoundingClientRect(); if (rect.width > 0) { this.init(rect); this.initialized$.next(true); } })); } ...
{ super(injector); }
identifier_body
limitprocessor_identifier_hint_test.py
#!/usr/bin/env python3 """ Test for Hintidentifier """ import datetime import unittest from base_test import PschedTestBase from pscheduler.limitprocessor.identifier.hint import * DATA = { "hint": "value", "match": { "style": "exact", "match": "testing", "case-insensitive": False ...
unittest.main()
conditional_block
limitprocessor_identifier_hint_test.py
#!/usr/bin/env python3 """ Test for Hintidentifier """ import datetime import unittest from base_test import PschedTestBase from pscheduler.limitprocessor.identifier.hint import * DATA = { "hint": "value", "match": { "style": "exact", "match": "testing", "case-insensitive": False ...
if __name__ == '__main__': unittest.main()
""" Test the Identifier """ def test_data_is_valid(self): """Limit Processor / Identifier Hint / Data Validation""" self.assertEqual(data_is_valid(DATA), (True, "OK")) self.assertEqual(data_is_valid({}), (False, "At /: 'hint' is a required property")) self.assertRaises(Valu...
identifier_body
limitprocessor_identifier_hint_test.py
#!/usr/bin/env python3 """ Test for Hintidentifier """ import datetime import unittest from base_test import PschedTestBase from pscheduler.limitprocessor.identifier.hint import * DATA = { "hint": "value", "match": { "style": "exact", "match": "testing", "case-insensitive": False ...
def test_identifier(self): """Limit Processor / Identifier Hint / Identifier""" ident = IdentifierHint(DATA) self.assertEqual(ident.evaluate(HINTS_HIT), True) self.assertEqual(ident.evaluate(HINTS_MISS), False) if __name__ == '__main__': unittest.main()
random_line_split
limitprocessor_identifier_hint_test.py
#!/usr/bin/env python3 """ Test for Hintidentifier """ import datetime import unittest from base_test import PschedTestBase from pscheduler.limitprocessor.identifier.hint import * DATA = { "hint": "value", "match": { "style": "exact", "match": "testing", "case-insensitive": False ...
(self): """Limit Processor / Identifier Hint / Data Validation""" self.assertEqual(data_is_valid(DATA), (True, "OK")) self.assertEqual(data_is_valid({}), (False, "At /: 'hint' is a required property")) self.assertRaises(ValueError, data_is_valid, 123) def test_identifier(self): ...
test_data_is_valid
identifier_name
ray.rs
use glium::{Program, Display, VertexBuffer, Surface, DrawParameters}; use glium::{Depth, Blend}; use glium::DepthTest::IfLessOrEqual; use glium::BlendingFunction::Addition; use glium::LinearBlendingFactor::{SourceAlpha, OneMinusSourceAlpha}; use glium::index::NoIndices; use glium::index::PrimitiveType::TriangleStrip; ...
target.draw(&self.vertices, &NoIndices(TriangleStrip), &self.program, &uniforms, &DrawParameters { blend: Blend { color: Addition { source: SourceAlpha, destination: OneMinusSourceAlpha }, alpha: Addition { source: SourceAlpha, destination: OneMinusSourc...
{ match state { &game::Ray::Static { position, orientation, width, border, .. } | &game::Ray::Dynamic { position, orientation, width, border, .. } => { let mvp = support.scene().to_mat() * support.scene().position(position) * support.scene().orientation(orientation) * support.scene().scale(width...
identifier_body
ray.rs
use glium::{Program, Display, VertexBuffer, Surface, DrawParameters}; use glium::{Depth, Blend}; use glium::DepthTest::IfLessOrEqual; use glium::BlendingFunction::Addition; use glium::LinearBlendingFactor::{SourceAlpha, OneMinusSourceAlpha}; use glium::index::NoIndices; use glium::index::PrimitiveType::TriangleStrip; ...
varying vec2 v_position; void main() { // get the texel from the background video or visualizer vec4 texel = texture2D(background, vec2(gl_FragCoord.x / width, gl_FragCoord.y / height)); // invert color vec3 pixel = vec3(1.0 - texel.r, 1.0 - texel.g, 1.0 - texel.b); ...
uniform float height; uniform float border; uniform vec4 color;
random_line_split
ray.rs
use glium::{Program, Display, VertexBuffer, Surface, DrawParameters}; use glium::{Depth, Blend}; use glium::DepthTest::IfLessOrEqual; use glium::BlendingFunction::Addition; use glium::LinearBlendingFactor::{SourceAlpha, OneMinusSourceAlpha}; use glium::index::NoIndices; use glium::index::PrimitiveType::TriangleStrip; ...
<S: Surface>(&self, target: &mut S, support: &Support, state: &Self::State) { match state { &game::Ray::Static { position, orientation, width, border, .. } | &game::Ray::Dynamic { position, orientation, width, border, .. } => { let mvp = support.scene().to_mat() * support.scene().position(position) * ...
render
identifier_name
reindeer-race-test.js
var expect = require("chai").expect; var reindeerRace = require("../../src/day-14/reindeer-race"); describe("--- Day 14: (1/2) distance traveled --- ", () => { it("counts the distance traveled after 1000s", () => { var reindeerSpecs = [ "Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seco...
"Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.", "Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds." ]; expect(reindeerRace.race(reindeerSpecs, 1000).winnerByPoints.pointsAwarded).to.equal(689); }); });
describe("--- Day 14: (2/2) points awarded --- ", () => { it("counts the points awarded for being in the lead after 1000s", () => { var reindeerSpecs = [
random_line_split
BlendMode.ts
import { Particle } from '../Particle'; import { getBlendMode } from '../ParticleUtils'; import { IEmitterBehavior, BehaviorOrder } from './Behaviors'; import { BehaviorEditorConfig } from './editor/Types'; /** * A Blend Mode behavior that applies a blend mode value to the particle at initialization. * * Example co...
} }
{ next.blendMode = getBlendMode(this.value); next = next.next; }
conditional_block
BlendMode.ts
import { Particle } from '../Particle'; import { getBlendMode } from '../ParticleUtils'; import { IEmitterBehavior, BehaviorOrder } from './Behaviors'; import { BehaviorEditorConfig } from './editor/Types'; /** * A Blend Mode behavior that applies a blend mode value to the particle at initialization. * * Example co...
implements IEmitterBehavior { public static type = 'blendMode'; public static editorConfig: BehaviorEditorConfig = null; public order = BehaviorOrder.Normal; private value: string; constructor(config: { /** * Blend mode of all particles. This value is a key from * [PixiJs...
BlendModeBehavior
identifier_name
BlendMode.ts
import { Particle } from '../Particle'; import { getBlendMode } from '../ParticleUtils'; import { IEmitterBehavior, BehaviorOrder } from './Behaviors'; import { BehaviorEditorConfig } from './editor/Types'; /** * A Blend Mode behavior that applies a blend mode value to the particle at initialization. * * Example co...
initParticles(first: Particle): void { let next = first; while (next) { next.blendMode = getBlendMode(this.value); next = next.next; } } }
{ this.value = config.blendMode; }
identifier_body
BlendMode.ts
import { Particle } from '../Particle'; import { getBlendMode } from '../ParticleUtils'; import { IEmitterBehavior, BehaviorOrder } from './Behaviors'; import { BehaviorEditorConfig } from './editor/Types'; /** * A Blend Mode behavior that applies a blend mode value to the particle at initialization. * * Example co...
{ next.blendMode = getBlendMode(this.value); next = next.next; } } }
random_line_split
simd.rs
// Copyright 2013-2014 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-MI...
let f64x2 = f64x2(64.5f64, 65.5f64); zzz(); } #[inline(never)] fn zzz() { () }
let f32x4 = f32x4(60.5f32, 61.5f32, 62.5f32, 63.5f32);
random_line_split
simd.rs
// Copyright 2013-2014 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-MI...
{ () }
identifier_body
simd.rs
// Copyright 2013-2014 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-MI...
() { () }
zzz
identifier_name
word_counter.py
""" word_counter Provides helper functions for word counts. """ import os import re from collections import Counter STOPWORDS_FILE = os.path.join(os.path.dirname(__file__), "STOPWORDS") # Get the frequencies of each word as a dictionary. # strings = a list of strings, can be strings of any length/number of wo...
if is_dict: return dict(filtered) else: return filtered
is_dict = False if type(frequencies) is dict: is_dict = True frequencies = frequencies.items() # Load stopwords from file stopwords = load_stopwords() # Add in additional stopwords if additional_stopwords is not None: for word in additional_stopwords: stopwords....
identifier_body
word_counter.py
""" word_counter Provides helper functions for word counts. """ import os import re from collections import Counter STOPWORDS_FILE = os.path.join(os.path.dirname(__file__), "STOPWORDS") # Get the frequencies of each word as a dictionary. # strings = a list of strings, can be strings of any length/number of wo...
# Convert back to original form if is_dict: return dict(filtered) else: return filtered
filtered.append(word)
conditional_block
word_counter.py
""" word_counter Provides helper functions for word counts. """ import os import re from collections import Counter STOPWORDS_FILE = os.path.join(os.path.dirname(__file__), "STOPWORDS") # Get the frequencies of each word as a dictionary. # strings = a list of strings, can be strings of any length/number of wo...
return set([x.strip() for x in open(STOPWORDS_FILE).read().split('\n')]) else: return set() # Filter out stopworks from a frequencies dict or tuple def filter_stopwords(frequencies, additional_stopwords=None): # Convert to tuples for easy of development if dictionary is_dict = False if...
random_line_split
word_counter.py
""" word_counter Provides helper functions for word counts. """ import os import re from collections import Counter STOPWORDS_FILE = os.path.join(os.path.dirname(__file__), "STOPWORDS") # Get the frequencies of each word as a dictionary. # strings = a list of strings, can be strings of any length/number of wo...
(strings): return get_frequencies(strings).items() # Load stopwords from file, if it exists def load_stopwords(): if os.path.isfile(STOPWORDS_FILE): return set([x.strip() for x in open(STOPWORDS_FILE).read().split('\n')]) else: return set() # Filter out stopworks from a frequencies dict o...
get_frequencies_tuple
identifier_name
account_db.rs
2015, 2016 Ethcore (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 later version. // Parity ...
}
random_line_split
account_db.rs
// Copyright 2015, 2016 Ethcore (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 later version....
(&mut self, _key: H256, _value: DBValue) { unimplemented!() } fn remove(&mut self, _key: &H256) { unimplemented!() } } /// DB backend wrapper for Account trie pub struct AccountDBMut<'db> { db: &'db mut HashDB, address_hash: H256, } impl<'db> AccountDBMut<'db> { /// Create a new AccountDB from an address. ...
emplace
identifier_name
account_db.rs
Copyright 2015, 2016 Ethcore (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 later version. ...
} struct WrappingMut<'db>(&'db mut HashDB); impl<'db> HashDB for WrappingMut<'db>{ fn keys(&self) -> HashMap<H256, i32> { unimplemented!() } fn get(&self, key: &H256) -> Option<DBValue> { if key == &SHA3_NULL_RLP { return Some(DBValue::from_slice(&NULL_RLP_STATIC)); } self.0.get(key) } fn contains(...
{ unimplemented!() }
identifier_body
account_db.rs
Copyright 2015, 2016 Ethcore (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 later version. ...
self.0.get(key) } fn contains(&self, key: &H256) -> bool { if key == &SHA3_NULL_RLP { return true; } self.0.contains(key) } fn insert(&mut self, _value: &[u8]) -> H256 { unimplemented!() } fn emplace(&mut self, _key: H256, _value: DBValue) { unimplemented!() } fn remove(&mut self, _key: &H25...
{ return Some(DBValue::from_slice(&NULL_RLP_STATIC)); }
conditional_block
group__manhattan__space__container.js
var group__manhattan__space__container =
[ "distance", "group__manhattan__space__container.html#ga750b3a1e76a42ec52d2cadcc5ab8ff73", null ], [ "norm", "group__manhattan__space__container.html#gaed3fca875aa3c37c377abaab63d55e3b", null ], [ "squared_distance", "group__manhattan__space__container.html#ga27c404a932fab3cd47727b40e7d79d57", null ], ...
[
random_line_split
test_line.py
import copy import pytest from peek.line import InvalidIpAddressException, Line, InvalidStatusException # 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python" test_line_contents = { 'ip_address': '127.0.0.1', 'timestamp': '[01/Jan/1970:00:00:01 +0000]', 'verb': 'GET', ...
with pytest.raises(InvalidStatusException): Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
identifier_body
test_line.py
import copy import pytest from peek.line import InvalidIpAddressException, Line, InvalidStatusException # 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python" test_line_contents = { 'ip_address': '127.0.0.1', 'timestamp': '[01/Jan/1970:00:00:01 +0000]', 'verb': 'GET', ...
return test_contents test_line = Line(line_contents=test_line_contents) class TestLineInstantiation: @pytest.mark.parametrize('expected,actual', [ ('127.0.0.1', test_line.ip_address), (1, test_line.timestamp), ('GET', test_line.verb), ('/', test_line.path), (200, tes...
test_contents.update(updates)
conditional_block
test_line.py
import copy import pytest from peek.line import InvalidIpAddressException, Line, InvalidStatusException # 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python" test_line_contents = { 'ip_address': '127.0.0.1', 'timestamp': '[01/Jan/1970:00:00:01 +0000]', 'verb': 'GET', ...
return test_contents test_line = Line(line_contents=test_line_contents) class TestLineInstantiation: @pytest.mark.parametrize('expected,actual', [ ('127.0.0.1', test_line.ip_address), (1, test_line.timestamp), ('GET', test_line.verb), ('/', test_line.path), (200, test...
def get_updated_line_contents(updates=None): test_contents = copy.deepcopy(test_line_contents) if updates is not None: test_contents.update(updates)
random_line_split
test_line.py
import copy import pytest from peek.line import InvalidIpAddressException, Line, InvalidStatusException # 127.0.0.1 - - [01/Jan/1970:00:00:01 +0000] "GET / HTTP/1.1" 200 193 "-" "Python" test_line_contents = { 'ip_address': '127.0.0.1', 'timestamp': '[01/Jan/1970:00:00:01 +0000]', 'verb': 'GET', ...
(self): with pytest.raises(InvalidStatusException): Line(line_contents=get_updated_line_contents({'status': 'foobar'}))
test_passing_non_parseable_status_throws_exception
identifier_name
roster.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import {bindActionCreators} from 'redux'; import { Link } from 'react-router'; import { List } from 'semantic-ui-react'; import { fetchRoster } from './../actions/action_index'; class Roster extends Component { componentWillMount(){ ...
() { return( <div className="roster-list"> {this.renderList()} </div> ) } } const mapStateToProps = function({ profiles }) { return { profiles } }; const mapDispatchToProps = function (dispatch) { return bindActionCreators({ fetchRoster }, dispatch); }; export default conne...
render
identifier_name
roster.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import {bindActionCreators} from 'redux'; import { Link } from 'react-router'; import { List } from 'semantic-ui-react'; import { fetchRoster } from './../actions/action_index'; class Roster extends Component { componentWillMount(){ ...
render() { return( <div className="roster-list"> {this.renderList()} </div> ) } } const mapStateToProps = function({ profiles }) { return { profiles } }; const mapDispatchToProps = function (dispatch) { return bindActionCreators({ fetchRoster }, dispatch); }; export defa...
</div> </div> ) }) }
random_line_split
roster.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import {bindActionCreators} from 'redux'; import { Link } from 'react-router'; import { List } from 'semantic-ui-react'; import { fetchRoster } from './../actions/action_index'; class Roster extends Component { componentWillMount(){ ...
return ( <div key={profile.profileid} className="profile-individual"> <div className='profile-information'> <h3> <span className="profile-name">{profile.nickname ? profile.nickname : profile.firstname} {profile.lastname.charAt(0).toUpperCase()}</span></h3> <br /> ...
{return null} // don't show profile unless active
conditional_block
roster.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import {bindActionCreators} from 'redux'; import { Link } from 'react-router'; import { List } from 'semantic-ui-react'; import { fetchRoster } from './../actions/action_index'; class Roster extends Component { componentWillMount()
renderList() { if(!this.props.profiles.roster.length) { return <div>Loading Roster...</div>; } return this.props.profiles.roster.map((profile) => { if (!profile.active) {return null} // don't show profile unless active return ( <div key={profile.profileid} className="prof...
{ this.props.fetchRoster(); }
identifier_body
choicelists.py
# -*- coding: UTF-8 -*- # Copyright 2019-2020 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) from django.db import models from lino_xl.lib.ledger.choicelists import VoucherStates from lino.api import dd, _ class
(VoucherStates): pass add = OrderStates.add_item add('10', _("Waiting"), 'draft', is_editable=True) add('20', _("Active"), 'active', is_editable=True) add('30', _("Urgent"), 'urgent', is_editable=True) add('40', _("Done"), 'registered') add('50', _("Cancelled"), 'cancelled') OrderStates.draft.add_transition(requi...
OrderStates
identifier_name
choicelists.py
# -*- coding: UTF-8 -*- # Copyright 2019-2020 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) from django.db import models from lino_xl.lib.ledger.choicelists import VoucherStates from lino.api import dd, _ class OrderStates(VoucherStates):
add = OrderStates.add_item add('10', _("Waiting"), 'draft', is_editable=True) add('20', _("Active"), 'active', is_editable=True) add('30', _("Urgent"), 'urgent', is_editable=True) add('40', _("Done"), 'registered') add('50', _("Cancelled"), 'cancelled') OrderStates.draft.add_transition(required_states="active urgent...
pass
identifier_body
choicelists.py
# -*- coding: UTF-8 -*- # Copyright 2019-2020 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) from django.db import models from lino_xl.lib.ledger.choicelists import VoucherStates from lino.api import dd, _ class OrderStates(VoucherStates): pass
add('30', _("Urgent"), 'urgent', is_editable=True) add('40', _("Done"), 'registered') add('50', _("Cancelled"), 'cancelled') OrderStates.draft.add_transition(required_states="active urgent registered cancelled") OrderStates.active.add_transition(required_states="draft urgent registered cancelled") OrderStates.urgent.a...
add = OrderStates.add_item add('10', _("Waiting"), 'draft', is_editable=True) add('20', _("Active"), 'active', is_editable=True)
random_line_split
add_profile.py
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
def execute(self): profiles = list(self.settings["profile_set"].MaterialProfiles or []) profile = self.file.create_entity("IfcMaterialProfile", **{"Material": self.settings["material"]}) profiles.append(profile) self.settings["profile_set"].MaterialProfiles = profiles retur...
self.settings[key] = value
conditional_block
add_profile.py
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell.
# # IfcOpenShell is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public ...
# # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version.
random_line_split
add_profile.py
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
(self): profiles = list(self.settings["profile_set"].MaterialProfiles or []) profile = self.file.create_entity("IfcMaterialProfile", **{"Material": self.settings["material"]}) profiles.append(profile) self.settings["profile_set"].MaterialProfiles = profiles return profile
execute
identifier_name
add_profile.py
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
profiles = list(self.settings["profile_set"].MaterialProfiles or []) profile = self.file.create_entity("IfcMaterialProfile", **{"Material": self.settings["material"]}) profiles.append(profile) self.settings["profile_set"].MaterialProfiles = profiles return profile
identifier_body
IconSpeakerNotesOff.js
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconSpeakerNotesOff(props: IconProps)
IconSpeakerNotesOff.displayName = 'IconSpeakerNotesOff'; IconSpeakerNotesOff.category = 'action';
{ const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M10.54 11l-.54-.54L7.54 8 6 6.46 2.38 2.84 1.27 1.73 0 3l2.01 2.01L2 22l4-4h9l5.73 5.73L22 22.46 17.54 18l-7-7zM8 14H6v-2h2v2zm-2-3V9l2 2H6zm14-9H4.08L10 7.92V6h8v2h-7.92l1 1H18v2h-4.92l6.99 6.99C2...
identifier_body
IconSpeakerNotesOff.js
/* @flow */ import React from 'react';
import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconSpeakerNotesOff(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M10.54 11l-.54-.54L7.54 8 6 6.46 2.38 2...
import Icon from 'mineral-ui/Icon';
random_line_split
IconSpeakerNotesOff.js
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function
(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M10.54 11l-.54-.54L7.54 8 6 6.46 2.38 2.84 1.27 1.73 0 3l2.01 2.01L2 22l4-4h9l5.73 5.73L22 22.46 17.54 18l-7-7zM8 14H6v-2h2v2zm-2-3V9l2 2H6zm14-9H4.08L10 7.92V6h8v2h-7.92l1 1H18v...
IconSpeakerNotesOff
identifier_name
matchers.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2012 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the L...
elif 'DONTCARE' in (d1value, d2value): continue elif self.approx_equal and within_tolerance: continue elif d1value != d2value: return DictMismatch(key, d1value, d2value)
return did_match
conditional_block
matchers.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2012 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the L...
return DictMismatch(key, d1value, d2value)
continue elif d1value != d2value:
random_line_split
matchers.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2012 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the L...
class DictMatches(object): def __init__(self, d1, approx_equal=False, tolerance=0.001): self.d1 = d1 self.approx_equal = approx_equal self.tolerance = tolerance def __str__(self): return 'DictMatches(%s)' % (pprint.pformat(self.d1)) # Useful assertions def match(sel...
return {}
identifier_body
matchers.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2012 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the L...
(object): def __init__(self, d1, approx_equal=False, tolerance=0.001): self.d1 = d1 self.approx_equal = approx_equal self.tolerance = tolerance def __str__(self): return 'DictMatches(%s)' % (pprint.pformat(self.d1)) # Useful assertions def match(self, d2): """A...
DictMatches
identifier_name
user-layer.ts
import {MapService} from '../../map/map.service'; import {UserService} from '../user/user.service'; import VectorSource from 'ol/source/vector'; import VectorLayer from 'ol/layer/vector'; import Feature from 'ol/feature'; import Polygon from 'ol/geom/polygon'; import GeoJSON from 'ol/format/geojson'; import Proj from ...
let extent = geom.getExtent() if (view.getProjection().getCode() != 'EPSG:4326') { extent = Proj.transformExtent(extent, 'EPSG:4326', view.getProjection()); } view.fit(extent, { ...
geometry: geom }); this.layer.getSource().addFeature(feature);
random_line_split
user-layer.ts
import {MapService} from '../../map/map.service'; import {UserService} from '../user/user.service'; import VectorSource from 'ol/source/vector'; import VectorLayer from 'ol/layer/vector'; import Feature from 'ol/feature'; import Polygon from 'ol/geom/polygon'; import GeoJSON from 'ol/format/geojson'; import Proj from ...
(user) { if (user) { let coords = user.subscription.area; if (coords) { let view = this.viewer.getView(); try { let geom = this.jsonParser.readGeometryFromObject({type: 'MultiPolygon', coordinates: coords}, { ...
updateUserArea
identifier_name
user-layer.ts
import {MapService} from '../../map/map.service'; import {UserService} from '../user/user.service'; import VectorSource from 'ol/source/vector'; import VectorLayer from 'ol/layer/vector'; import Feature from 'ol/feature'; import Polygon from 'ol/geom/polygon'; import GeoJSON from 'ol/format/geojson'; import Proj from ...
let extent = geom.getExtent() if (view.getProjection().getCode() != 'EPSG:4326') { extent = Proj.transformExtent(extent, 'EPSG:4326', view.getProjection()); } view.fit(extent, { ...
{ let coords = user.subscription.area; if (coords) { let view = this.viewer.getView(); try { let geom = this.jsonParser.readGeometryFromObject({type: 'MultiPolygon', coordinates: coords}, { dataProject...
conditional_block
user-layer.ts
import {MapService} from '../../map/map.service'; import {UserService} from '../user/user.service'; import VectorSource from 'ol/source/vector'; import VectorLayer from 'ol/layer/vector'; import Feature from 'ol/feature'; import Polygon from 'ol/geom/polygon'; import GeoJSON from 'ol/format/geojson'; import Proj from ...
private initLayer() { let source = new VectorSource({}); this.layer = new VectorLayer({ source: source }); this.viewer.getLayers().push(this.layer); this.jsonParser = new GeoJSON(); } private updateUserArea(user) { if (user) { let ...
{ mapService.getViewer().then((viewer) => { this.viewer = viewer; this.initLayer(); this.updateUserArea(userService.getCurrentUser()); }); userService.getUser().subscribe((user)=>{ if (this.viewer) { this.updateUserArea(us...
identifier_body
touch.py
rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantia...
# # do_normalize(touch) # calculate the screen coordinates from the touch values, using the calibration values # touch must be the tuple return by get_touch # def do_normalize(self, touch): xmul = self.calibration[3] + (self.calibration[1] - self.calibration[3]) * (touch[1] / 4096) xadd = self.cali...
if self.ready: self.ready = False return self.x, self.y return None
identifier_body
touch.py
the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substa...
# buff = self.buff buf_length = self.buf_length buffptr = 0 nsamples = 0 while timeout > 0: if nsamples == buf_length: meanx = sum([c[0] for c in buff]) // buf_length meany = sum([c[1] for c in buff]) // buf_length dev =...
return None
random_line_split
touch.py
rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantia...
# Asynchronous get_touch def get_touch_async(self): if self.ready: self.ready = False return self.x, self.y return None # # do_normalize(touch) # calculate the screen coordinates from the touch values, using the calibration values # touch must be the tuple return by get_tou...
if nsamples == buf_length: meanx = sum([c[0] for c in buff]) // buf_length meany = sum([c[1] for c in buff]) // buf_length dev = sum([(c[0] - meanx)**2 + (c[1] - meany)**2 for c in buff]) / buf_length if dev <= self.margin: # got one; compare against the s...
conditional_block
touch.py
rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantia...
(self, confidence=5, margin=50, delay=10, calibration=None): if not self.asynchronous: # Ignore attempts to change on the fly. confidence = max(min(confidence, 25), 5) if confidence != self.buf_length: self.buff = [[0,0] for x in range(confidence)] self.bu...
touch_parameter
identifier_name
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
export = keys;
random_line_split
DockingSchema.ts
import { FieldProcessorAdt, FieldSchema, ValueSchema } from '@ephox/boulder'; import * as Boxes from '../../alien/Boxes'; import * as Fields from '../../data/Fields'; export default [ FieldSchema.optionObjOf('contextual', [ FieldSchema.strictString('fadeInClass'), FieldSchema.strictString('fadeOutClass'), ...
Fields.onHandler('onUndocked') ] as FieldProcessorAdt[];
random_line_split
main.rs
extern crate getopts; use getopts::Options; use std::env; use std::io::{self, Write}; use std::net::{IpAddr, TcpStream}; use std::str::FromStr; use std::sync::mpsc::{Sender, channel}; use std::thread; // Max possible port const MAX: u16 = 65535; fn main() { let args: Vec<String> = env::args().collect(); let ...
println!("{} is open", v); } } // scan scans ports at an IP address and sends any open ports it finds back on its // channel. scan exits once MAX has been reached. fn scan(tx: Sender<u16>, start_port: u16, addr: IpAddr, num_threads: u16) { let mut port: u16 = start_port + 1; loop { match ...
println!(""); out.sort(); for v in out {
random_line_split
main.rs
extern crate getopts; use getopts::Options; use std::env; use std::io::{self, Write}; use std::net::{IpAddr, TcpStream}; use std::str::FromStr; use std::sync::mpsc::{Sender, channel}; use std::thread; // Max possible port const MAX: u16 = 65535; fn main() { let args: Vec<String> = env::args().collect(); let ...
} }
{ let mut port: u16 = start_port + 1; loop { match TcpStream::connect((addr, port)) { Ok(_) => { // Found open port, indicate progress and send to main thread print!("."); io::stdout().flush().unwrap(); tx.send(port).unwrap(); ...
identifier_body
main.rs
extern crate getopts; use getopts::Options; use std::env; use std::io::{self, Write}; use std::net::{IpAddr, TcpStream}; use std::str::FromStr; use std::sync::mpsc::{Sender, channel}; use std::thread; // Max possible port const MAX: u16 = 65535; fn main() { let args: Vec<String> = env::args().collect(); let ...
(tx: Sender<u16>, start_port: u16, addr: IpAddr, num_threads: u16) { let mut port: u16 = start_port + 1; loop { match TcpStream::connect((addr, port)) { Ok(_) => { // Found open port, indicate progress and send to main thread print!("."); io::...
scan
identifier_name
controllers.js
'use strict'; angular.module('Home').controller('ModalDeleteAssetCtrl', function ($scope, $modalInstance, parentScope, HomeService, asset, name, token, typeId, menuId) { $scope.name = name; $scope.message = "Are you sure you want to delete this asset ?"; $sc...
} } else { $scope.error = "Invalid server response"; } } ); $modalInstance.close(); }; $scope.cancel = function () { ...
{ $scope.message = response.message; }
conditional_block
controllers.js
'use strict'; angular.module('Home').controller('ModalDeleteAssetCtrl', function ($scope, $modalInstance, parentScope, HomeService, asset, name, token, typeId, menuId) { $scope.name = name; $scope.message = "Are you sure you want to delete this asset ?"; $sc...
parentScope.removeAssetFromTemplate(typeId, asset); } else { $scope.message = response.message; } } } else {...
if (response.success) {
random_line_split
page.py
from element import BasePageElement from locators import PageFooterLocators from selenium.webdriver.common.action_chains import ActionChains class BasePage(object): def __init__(self, driver): self.driver = driver class FooterPage(BasePage): def
(self): return "Lauren Nicole Smith 2015" in self.driver.page_source def click_github_button(self): element = self.driver.find_element(*PageFooterLocators.GET_GITHUB_BUTTON) element.click() return "https://github.com/technolotrix" in self.driver.current_url def click_linkedin_b...
is_copyright_matches
identifier_name
page.py
from element import BasePageElement from locators import PageFooterLocators from selenium.webdriver.common.action_chains import ActionChains class BasePage(object): def __init__(self, driver): self.driver = driver class FooterPage(BasePage): def is_copyright_matches(self): return "Lauren...
def click_gplus_button(self): element = self.driver.find_element(*PageFooterLocators.GET_GPLUS_BUTTON) element.click() return "" in self.driver.current_url def click_html5up_link(self): element = self.driver.find_element(*PageFooterLocators.GET_HTML5UP_LINK) element.cli...
def click_twitter_button(self): element = self.driver.find_element(*PageFooterLocators.GET_TWITTER_BUTTON) element.click() return "" in self.driver.current_url
random_line_split
page.py
from element import BasePageElement from locators import PageFooterLocators from selenium.webdriver.common.action_chains import ActionChains class BasePage(object): def __init__(self, driver): self.driver = driver class FooterPage(BasePage): def is_copyright_matches(self): return "Lauren...
element = self.driver.find_element(*PageFooterLocators.GET_HTML5UP_LINK) element.click() return "http://html5up.net" in self.driver.current_url
identifier_body
xz.rs
use crate::decode; use crate::encode::lzma2; use crate::encode::util; use crate::xz::{footer, header, CheckMethod, StreamFlags}; use byteorder::{LittleEndian, WriteBytesExt}; use crc::{crc32, Hasher32}; use std::io; use std::io::Write; pub fn encode_stream<R, W>(input: &mut R, output: &mut W) -> io::Result<()> where ...
); let padding_size = ((unpadded_size ^ 0x03) + 1) & 0x03; let padding = vec![0; padding_size]; output.write_all(padding.as_slice())?; // Checksum = None (cf. above) Ok((unpadded_size, unpacked_size)) } fn write_index<W>(output: &mut W, unpadded_size: usize, unpacked_size: usize) -> io::Resul...
unpacked_size
random_line_split
xz.rs
use crate::decode; use crate::encode::lzma2; use crate::encode::util; use crate::xz::{footer, header, CheckMethod, StreamFlags}; use byteorder::{LittleEndian, WriteBytesExt}; use crc::{crc32, Hasher32}; use std::io; use std::io::Write; pub fn encode_stream<R, W>(input: &mut R, output: &mut W) -> io::Result<()> where ...
digested.write_all(padding.as_slice())?; } let crc32 = digest.sum32(); count_output.write_u32::<LittleEndian>(crc32)?; Ok(count_output.count()) } fn write_multibyte<W>(output: &mut W, mut value: u64) -> io::Result<()> where W: io::Write, { loop { let byte = (value & 0x7F) as ...
{ let mut count_output = util::CountWrite::new(output); let mut digest = crc32::Digest::new(crc32::IEEE); { let mut digested = util::HasherWrite::new(&mut count_output, &mut digest); digested.write_u8(0)?; // No more block let num_records = 1; write_multibyte(&mut digested, ...
identifier_body
xz.rs
use crate::decode; use crate::encode::lzma2; use crate::encode::util; use crate::xz::{footer, header, CheckMethod, StreamFlags}; use byteorder::{LittleEndian, WriteBytesExt}; use crc::{crc32, Hasher32}; use std::io; use std::io::Write; pub fn encode_stream<R, W>(input: &mut R, output: &mut W) -> io::Result<()> where ...
else { output.write_u8(0x80 | byte)?; } } Ok(()) }
{ output.write_u8(byte)?; break; }
conditional_block
xz.rs
use crate::decode; use crate::encode::lzma2; use crate::encode::util; use crate::xz::{footer, header, CheckMethod, StreamFlags}; use byteorder::{LittleEndian, WriteBytesExt}; use crc::{crc32, Hasher32}; use std::io; use std::io::Write; pub fn encode_stream<R, W>(input: &mut R, output: &mut W) -> io::Result<()> where ...
<R, W>(input: &mut R, output: &mut W) -> io::Result<(usize, usize)> where R: io::BufRead, W: io::Write, { let (unpadded_size, unpacked_size) = { let mut count_output = util::CountWrite::new(output); // Block header let mut digest = crc32::Digest::new(crc32::IEEE); { ...
write_block
identifier_name
better_conv_net.py
import theano import theano.tensor as T import numpy as np import sys sys.path.insert(0, '../data_loader/') import load from theano.tensor.nnet.conv import conv2d from theano.tensor.signal.downsample import max_pool_2d # load data x_train, t_train, x_test, t_test = load.cifar10(dtype=theano.config.floatX, grayscale=F...
w_c1 = init_weights((4, 3, 3, 3)) b_c1 = init_weights((4,)) w_c2 = init_weights((8, 4, 3, 3)) b_c2 = init_weights((8,)) w_h3 = init_weights((8 * 4 * 4, 100)) b_h3 = init_weights((100,)) w_o = init_weights((100, 10)) b_o = init_weights((10,)) params = [w_c1, b_c1, w_c2, b_c2, w_h3, b_h3, w_o, b_o] p_y_given_x = mode...
c1 = T.maximum(0, conv2d(x, w_c1) + b_c1.dimshuffle('x', 0, 'x', 'x')) p1 = max_pool_2d(c1, (3, 3)) c2 = T.maximum(0, conv2d(p1, w_c2) + b_c2.dimshuffle('x', 0, 'x', 'x')) p2 = max_pool_2d(c2, (2, 2)) p2_flat = p2.flatten(2) h3 = T.maximum(0, T.dot(p2_flat, w_h3) + b_h3) p_y_given_x = T.nnet.sof...
identifier_body
better_conv_net.py
import theano import theano.tensor as T import numpy as np import sys sys.path.insert(0, '../data_loader/') import load from theano.tensor.nnet.conv import conv2d from theano.tensor.signal.downsample import max_pool_2d # load data x_train, t_train, x_test, t_test = load.cifar10(dtype=theano.config.floatX, grayscale=F...
predictions_test = predict(x_test) accuracy = np.mean(predictions_test == labels_test) print "accuracy: {}\n".format(accuracy)
x_batch = x_train[start:start + batch_size] t_batch = t_train[start:start + batch_size] cost = train(x_batch, t_batch)
conditional_block
better_conv_net.py
import theano import theano.tensor as T import numpy as np import sys sys.path.insert(0, '../data_loader/') import load from theano.tensor.nnet.conv import conv2d from theano.tensor.signal.downsample import max_pool_2d # load data x_train, t_train, x_test, t_test = load.cifar10(dtype=theano.config.floatX, grayscale=F...
(shape): return theano.shared(floatX(np.random.randn(*shape) * 0.1)) def momentum(cost, params, learning_rate, momentum): grads = theano.grad(cost, params) updates = [] for p, g in zip(params, grads): mparam_i = theano.shared(np.zeros(p.get_value().shape, dtype=theano.config.floatX)) ...
init_weights
identifier_name
better_conv_net.py
import theano import theano.tensor as T import numpy as np import sys sys.path.insert(0, '../data_loader/') import load from theano.tensor.nnet.conv import conv2d from theano.tensor.signal.downsample import max_pool_2d # load data x_train, t_train, x_test, t_test = load.cifar10(dtype=theano.config.floatX, grayscale=F...
# define symbolic Theano variables x = T.tensor4() t = T.matrix() # define model: neural network def floatX(x): return np.asarray(x, dtype=theano.config.floatX) def init_weights(shape): return theano.shared(floatX(np.random.randn(*shape) * 0.1)) def momentum(cost, params, learning_rate, momentum): grads ...
random_line_split
mod.rs
pub mod event; use crate::Opt; use diesel::pg::PgConnection; use diesel::r2d2::ConnectionManager; use diesel_migrations::{ find_migrations_directory, mark_migrations_in_directory, run_pending_migrations, setup_database, }; use r2d2::{Pool, PooledConnection}; use std::error::Error; pub type DatabasePool = Pool<Con...
pub fn run_migrations(db_pool: &DatabasePool) { let connection = db_pool.get().expect("Could not connect to database"); setup_database(&connection).expect("Could not set up database"); let migrations_dir = find_migrations_directory().expect("Could not find migrations directory"); let migrations = m...
{ let db_manager: ConnectionManager<PgConnection> = ConnectionManager::new(&opt.database); let db_pool: Pool<ConnectionManager<PgConnection>> = Pool::builder().max_size(15).build(db_manager)?; Ok(db_pool) }
identifier_body
mod.rs
pub mod event; use crate::Opt; use diesel::pg::PgConnection; use diesel::r2d2::ConnectionManager; use diesel_migrations::{ find_migrations_directory, mark_migrations_in_directory, run_pending_migrations, setup_database, }; use r2d2::{Pool, PooledConnection}; use std::error::Error; pub type DatabasePool = Pool<Con...
else { eprintln!( "No database migrations available in \"{}\".", migrations_dir.to_string_lossy() ); } run_pending_migrations(&connection).expect("Could not run database migrations"); }
{ println!("Migrations:"); for (migration, applied) in migrations { println!( " [{}] {}", if applied { "X" } else { " " }, migration .file_path() .and_then(|p| p.file_name()) .map(|p|...
conditional_block
mod.rs
pub mod event; use crate::Opt; use diesel::pg::PgConnection; use diesel::r2d2::ConnectionManager; use diesel_migrations::{ find_migrations_directory, mark_migrations_in_directory, run_pending_migrations, setup_database, }; use r2d2::{Pool, PooledConnection}; use std::error::Error; pub type DatabasePool = Pool<Con...
(opt: &Opt) -> Result<DatabasePool, Box<dyn Error>> { let db_manager: ConnectionManager<PgConnection> = ConnectionManager::new(&opt.database); let db_pool: Pool<ConnectionManager<PgConnection>> = Pool::builder().max_size(15).build(db_manager)?; Ok(db_pool) } pub fn run_migrations(db_pool: &Database...
create_pool
identifier_name