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 |
|---|---|---|---|---|
runescapecompare.py | import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffl... |
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def com... | self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
""" | identifier_body |
runescapecompare.py | import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffl... | (self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
... | compare_overall | identifier_name |
runescapecompare.py | import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffl... |
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
| comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher ... | conditional_block |
test_opsgenie_alert.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | (self):
hook = OpsgenieAlertHook(opsgenie_conn_id=self.conn_id)
api_key = hook._get_api_key()
self.assertEqual('eb243592-faa2-4ba2-a551q-1afdf565c889', api_key)
def test_get_conn_defaults_host(self):
hook = OpsgenieAlertHook()
hook.get_conn()
self.assertEqual('https:... | test_get_api_key | identifier_name |
test_opsgenie_alert.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | def test_get_conn_defaults_host(self):
hook = OpsgenieAlertHook()
hook.get_conn()
self.assertEqual('https://api.opsgenie.com', hook.base_url)
@requests_mock.mock()
def test_call_with_success(self, m):
hook = OpsgenieAlertHook(opsgenie_conn_id=self.conn_id)
m.post(
... | hook = OpsgenieAlertHook(opsgenie_conn_id=self.conn_id)
api_key = hook._get_api_key()
self.assertEqual('eb243592-faa2-4ba2-a551q-1afdf565c889', api_key)
| random_line_split |
test_opsgenie_alert.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
@requests_mock.mock()
def test_api_key_not_set(self, m):
hook = OpsgenieAlertHook()
m.post(
self.opsgenie_alert_endpoint,
status_code=202,
json=self._mock_success_response_body
)
with self.assertRaises(AirflowException):
hook.exec... | hook = OpsgenieAlertHook(opsgenie_conn_id=self.conn_id)
m.post(
self.opsgenie_alert_endpoint,
status_code=202,
json=self._mock_success_response_body
)
resp = hook.execute(payload=self._payload)
self.assertEqual(resp.request.headers.get('Authorization')... | identifier_body |
structutils.py | '" + member[1] + "' is not valid for a single member.")
formatString += member[1]
return formatString
def dataSizeForMembers(members):
return struct.calcsize(formatStringForMembers(members))
def dataBlobFormatString(members):
formatString = formatStringForMembers(members)
length = struct.calcsize(formatStrin... |
class DataStructMemberGroupInfo:
"""Analyses members of a data struct and computes which items should be
grouped together (eg. vectors, strings, etc.)."""
# Assumes that the format strings have been validated as per data struct requirements.
def __init__(self, members):
self.__members = members
# Number ... | return repr(self.__data) | identifier_body |
structutils.py | string '" + member[1] + "' is not valid for a single member.")
formatString += member[1]
return formatString
def dataSizeForMembers(members):
return struct.calcsize(formatStringForMembers(members))
def dataBlobFormatString(members):
formatString = formatStringForMembers(members)
length = struct.calcsize(form... | # Member format strings have been validated so that they only reference one data type.
# Therefore, if the string contains a number > 1, this means it references an aggregate
# type (eg. | # If this member requires a group, use the coerced list.
# Otherwise, use the raw value (which should be singular).
data[index] = coercedValue if isGrouped else value
def __generateMemberGroupInfo(self): | random_line_split |
structutils.py | '" + member[1] + "' is not valid for a single member.")
formatString += member[1]
return formatString
def dataSizeForMembers(members):
return struct.calcsize(formatStringForMembers(members))
def dataBlobFormatString(members):
formatString = formatStringForMembers(members)
length = struct.calcsize(formatStrin... | (self, binaryData, offset=0):
if not isinstance(binaryData, bytes):
raise TypeError("Binary data is not in byte format.")
data = list(struct.unpack_from(self.__format, binaryData, offset))
self.__data = self._processParsedData(data)
def exportBinaryData(self):
if len(self.__data) < 1:
raise ValueError(... | parseBinaryData | identifier_name |
structutils.py | '" + member[1] + "' is not valid for a single member.")
formatString += member[1]
return formatString
def dataSizeForMembers(members):
return struct.calcsize(formatStringForMembers(members))
def dataBlobFormatString(members):
formatString = formatStringForMembers(members)
length = struct.calcsize(formatStrin... |
if formatString is None:
formatString = formatStringForMembers(members)
# This will do most of the validation, so we don't have to below.
# If we start zeroed, this must be done later after the members have been initialised.
super().__init__(formatString, False)
self.__rawMembers = members
self.__mem... | raise TypeError("Members must be specified as a list of 2-tuples.") | conditional_block |
wxglvideo.py | import wx
import wx.glcanvas
import pyglet
import pyglet.gl as gl
import pyglet.gl
import motmot.wxvideo.wxvideo as wxvideo
# XXX TODO:
# check off-by-one error in width/coordinate settings (e.g. glOrtho call)
# allow sharing of OpenGL context between instances
NewImageReadyEvent = wx.NewEventType() # use to trigge... |
self.OnDraw()
def InitGL(self):
self.wxcontext.SetCurrent()
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
self._reset_projection()
self.extra_initgl()
def extra_initgl(self):
pass
def _reset_projection(self):
... | self.InitGL()
self.init = True | conditional_block |
wxglvideo.py | import wx
import wx.glcanvas
import pyglet
import pyglet.gl as gl
import pyglet.gl
import motmot.wxvideo.wxvideo as wxvideo
# XXX TODO:
# check off-by-one error in width/coordinate settings (e.g. glOrtho call)
# allow sharing of OpenGL context between instances
NewImageReadyEvent = wx.NewEventType() # use to trigge... | if not self.init:
self.InitGL()
self.init = True
self.OnDraw()
def InitGL(self):
self.wxcontext.SetCurrent()
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
self._reset_projection()
self.extra_initgl... | self.wxcontext.SetCurrent() | random_line_split |
wxglvideo.py | import wx
import wx.glcanvas
import pyglet
import pyglet.gl as gl
import pyglet.gl
import motmot.wxvideo.wxvideo as wxvideo
# XXX TODO:
# check off-by-one error in width/coordinate settings (e.g. glOrtho call)
# allow sharing of OpenGL context between instances
NewImageReadyEvent = wx.NewEventType() # use to trigge... | (self, image):
"""update the image to be displayed"""
self.wxcontext.SetCurrent()
self._pygimage.view_new_array( image )
event = wx.CommandEvent(NewImageReadyEvent)
event.SetEventObject(self)
wx.PostEvent(self, event)
def core_draw(self):
if self._pygimage is... | update_image | identifier_name |
wxglvideo.py | import wx
import wx.glcanvas
import pyglet
import pyglet.gl as gl
import pyglet.gl
import motmot.wxvideo.wxvideo as wxvideo
# XXX TODO:
# check off-by-one error in width/coordinate settings (e.g. glOrtho call)
# allow sharing of OpenGL context between instances
NewImageReadyEvent = wx.NewEventType() # use to trigge... |
class DynamicImageCanvas(wx.glcanvas.GLCanvas):
"""Display image data to OpenGL using as few resources as possible"""
def _setcurrent(self,hack_ok=True):
self.wxcontext.SetCurrent()
def __init__(self, *args, **kw):
attribList = kw.get('attribList',None)
if attribList is None:
... | self.glcanvas.GetParent().Show()
if pyglet.version[:3] >= '1.1':
# tested on 1.1beta1
pyglet.gl.current_context = self
else:
# tested on 1.0
pyglet.gl._current_context = self
self.glcanvas.SetCurrent() | identifier_body |
draw_a_clock_vpython.py | # -*- coding: utf-8 -*-
import os
"""Clock for VPython - Complex (cx@cx.hu) 2003. - Licence: Python
Usage:
from visual import *
from cxvp_clock import *
clk=Clock3D()
while 1:
rate(1)
clk.update()
See doc strings for more.
Run this module to test clocks.
TODO: More types of clocks, such as 3D digital,
ch... | ():
scene.title = 'cx_clock test'
tl = [('analog', 0, 0, -pi / 6)]
clk = []
for t, x, y, r in tl:
frm = frame(pos=(x, y, -0.3), axis=(1, 0, 0),
up=rotate((0, 1, 0), axis=(1, 0, 0), angle=r), visible=0)
clk.append(Clock3D(t, frame=frm))
while 1:
rate(1)
... | TestClocks | identifier_name |
draw_a_clock_vpython.py | # -*- coding: utf-8 -*-
import os
"""Clock for VPython - Complex (cx@cx.hu) 2003. - Licence: Python
Usage:
from visual import *
from cxvp_clock import *
clk=Clock3D()
while 1:
rate(1)
clk.update()
See doc strings for more.
Run this module to test clocks.
TODO: More types of clocks, such as 3D digital,
ch... | if unixtime == None:
unixtime = time()
if gmt:
tm = gmtime(unixtime)
else:
tm = localtime(unixtime)
h, m, s = tm[3:6]
ts = h * 3600 + m * 60 + s
aml = [2.0 / 86400.0, 1.0 / 3600.0, 1.0 / 60.0]
for am, f in zip(aml, [self.hf, sel... | use GMT time if gmt is true""" | random_line_split |
draw_a_clock_vpython.py | # -*- coding: utf-8 -*-
import os
"""Clock for VPython - Complex (cx@cx.hu) 2003. - Licence: Python
Usage:
from visual import *
from cxvp_clock import *
clk=Clock3D()
while 1:
rate(1)
clk.update()
See doc strings for more.
Run this module to test clocks.
TODO: More types of clocks, such as 3D digital,
ch... |
class AnalogClock(Base):
"""Analog clock, keyword arguments:
frame=reference frame to use (default: None),
pointers=pointers to display, cobination of characters 'h', 'm' and 's' (default: 'hms')
ring_color=color of ring around the clock (default: color.yellow)
back_color=color of clock's back pl... | """Base class to pass specific keyword
arguments with convenient defaults"""
def __init__(self, kwlist=[], *args, **kw):
self.kwlist = kwlist
for k, v in kwlist.items():
if kw.has_key(k):
v = kw[k]
del kw[k]
self.__dict__[k] = v
self.a... | identifier_body |
draw_a_clock_vpython.py | # -*- coding: utf-8 -*-
import os
"""Clock for VPython - Complex (cx@cx.hu) 2003. - Licence: Python
Usage:
from visual import *
from cxvp_clock import *
clk=Clock3D()
while 1:
rate(1)
clk.update()
See doc strings for more.
Run this module to test clocks.
TODO: More types of clocks, such as 3D digital,
ch... |
h, m, s = tm[3:6]
ts = h * 3600 + m * 60 + s
aml = [2.0 / 86400.0, 1.0 / 3600.0, 1.0 / 60.0]
for am, f in zip(aml, [self.hf, self.mf, self.sf]):
if not f:
continue
a = 2 * pi * ts * am
f.axis = ax = rotate((0, 1, 0), angle=-a, axis=(0,... | tm = localtime(unixtime) | conditional_block |
test_data.ts | import { commentTaskSpec } from '../rpc-mock';
import { Comment } from '../rpc';
export const taskspecComments = (() => {
const ret: Array<Comment> = [];
ret.push(JSON.parse(JSON.stringify(commentTaskSpec)) as Comment);
ret[0].message = 'Flakiness caused by the widget.';
ret[0].user = 'alice@google.com';
ret... | })(); | random_line_split | |
variables_7.js | var searchData=
[
['has_5fcustom_5fcertificate',['has_custom_certificate',['../structtelebot__webhook__info.html#aa826fadf8fb74137e9ab6d61f3e54153',1,'telebot_webhook_info']]],
['height',['height',['../structtelebot__sticker.html#ac09ff20853c0a90dfcbf397441dd7c65',1,'telebot_sticker::height()'],['../structtelebot__... | ]; | random_line_split | |
players.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
i... | { }
| PlayersModule | identifier_name |
players.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
i... | export class PlayersModule { } | ],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
}) | random_line_split |
matrix3x3.js | module = module.exports = (function () {
var _ = {};
_.extract3x3 = function (model, screen, oldpos) {
function getValue(offset) {
var
x = oldpos.col + offset.x,
y = oldpos.row + offset.y;
if (x < 0 || y < 0 || x >= model.gridCols || y >= model.gridRows)
return ' ';
... |
for(var x = 0; x < 3; x++) {
for(var y = 0; y < 3; y++) {
setValue({x: x-1, y: y-1}, matrix[y][x]);
}
}
};
return _;
})();
| {
var
x = oldpos.col + offset.x,
y = oldpos.row + offset.y;
if (x < 0 || y < 0 || x >= model.gridCols || y >= model.gridRows)
return;
screen.lines[y][x] = value;
} | identifier_body |
matrix3x3.js | module = module.exports = (function () {
var _ = {};
_.extract3x3 = function (model, screen, oldpos) {
function getValue(offset) {
var
x = oldpos.col + offset.x,
y = oldpos.row + offset.y;
if (x < 0 || y < 0 || x >= model.gridCols || y >= model.gridRows)
return ' ';
... | (offset, value) {
var
x = oldpos.col + offset.x,
y = oldpos.row + offset.y;
if (x < 0 || y < 0 || x >= model.gridCols || y >= model.gridRows)
return;
screen.lines[y][x] = value;
}
for(var x = 0; x < 3; x++) {
for(var y = 0; y < 3; y++) {
setValue({x: x-... | setValue | identifier_name |
matrix3x3.js | module = module.exports = (function () {
var _ = {};
_.extract3x3 = function (model, screen, oldpos) {
function getValue(offset) {
var
x = oldpos.col + offset.x,
y = oldpos.row + offset.y;
if (x < 0 || y < 0 || x >= model.gridCols || y >= model.gridRows)
return ' ';
... |
};
return _;
})();
| {
for(var y = 0; y < 3; y++) {
setValue({x: x-1, y: y-1}, matrix[y][x]);
}
} | conditional_block |
matrix3x3.js | module = module.exports = (function () {
var _ = {};
_.extract3x3 = function (model, screen, oldpos) {
function getValue(offset) {
var
x = oldpos.col + offset.x,
y = oldpos.row + offset.y;
if (x < 0 || y < 0 || x >= model.gridCols || y >= model.gridRows)
return ' ';
... |
return _;
})(); | random_line_split | |
polyfills.ts | require('./assets/lib/bootstrap/css/bootstrap.min.css').toString();
require('./assets/css/app.css').toString(); | import 'es6-shim';
// (these modules are what are in 'angular2/bundles/angular2-polyfills' so don't use that here)
import 'es6-promise';
import 'es7-reflect-metadata';
import 'zone.js/dist/zone-microtask';
if ('production' === process.env.ENV) {
// Production
// RxJS
// In production manually include the operat... | // Polyfills
// import 'ie-shim'; | random_line_split |
polyfills.ts | require('./assets/lib/bootstrap/css/bootstrap.min.css').toString();
require('./assets/css/app.css').toString();
// Polyfills
// import 'ie-shim';
import 'es6-shim';
// (these modules are what are in 'angular2/bundles/angular2-polyfills' so don't use that here)
import 'es6-promise';
import 'es7-reflect-metadata';
import... |
// For vendors for example jQuery, Lodash, angular2-jwt just import them anywhere in your app
// Also see custom-typings.d.ts as you also need to do `typings install x` where `x` is your module
require('./assets/lib/bootstrap/js/bootstrap.min.js');
| {
// Development
Error['stackTraceLimit'] = Infinity;
require('zone.js/dist/long-stack-trace-zone');
// RxJS
// to include every operator uncomment
// require('rxjs/Rx');
require('rxjs/add/operator/map');
require('rxjs/add/operator/mergeMap');
} | conditional_block |
space_map_disk.rs | use anyhow::Result;
use crate::pdata::btree_builder::*;
use crate::pdata::space_map::*;
use crate::pdata::space_map_common::*;
use crate::write_batcher::*;
//------------------------------------------
pub fn write_disk_sm(w: &mut WriteBatcher, sm: &dyn SpaceMap) -> Result<SMRoot> {
let (index_entries, ref_count_... | w.flush()?;
Ok(SMRoot {
nr_blocks: sm.get_nr_blocks()?,
nr_allocated: sm.get_nr_allocated()?,
bitmap_root,
ref_count_root,
})
}
//------------------------------------------ |
let bitmap_root = index_builder.complete(w)?; | random_line_split |
structure.rs | // Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | }
}
}
}
}
#[macro_export]
macro_rules! gfx_vertex_struct {
($root:ident {
$( $field:ident: $ty:ty = $name:expr, )*
}) => (gfx_impl_struct!{
$crate::format::Format : $crate::format::Formatted =
$root {
$( $field: $ty = $name, )*
... | stride: stride,
}),
)*
_ => None, | random_line_split |
hu-HU.js | export default {
uiv: {
datePicker: {
clear: 'Törlés',
today: 'Ma',
month: 'Hónap',
month1: 'január',
month2: 'február',
month3: 'március',
month4: 'április',
month5: 'május',
month6: 'június',
month7: 'július',
month8: 'augusztus',
month9: '... | }
} | filterPlaceholder: 'Keresés...'
} | random_line_split |
UptoboxCom.py | # -*- coding: utf-8 -*-
import re
import urlparse
from ..internal.misc import json
from ..internal.XFSAccount import XFSAccount
class | (XFSAccount):
__name__ = "UptoboxCom"
__type__ = "account"
__version__ = "0.21"
__status__ = "testing"
__description__ = """Uptobox.com account plugin"""
__license__ = "GPLv3"
__authors__ = [("benbox69", "dev@tollet.me")]
PLUGIN_DOMAIN = "uptobox.com"
PLUGIN_URL = "http://uptobox.c... | UptoboxCom | identifier_name |
UptoboxCom.py | # -*- coding: utf-8 -*-
import re
import urlparse
from ..internal.misc import json
from ..internal.XFSAccount import XFSAccount
class UptoboxCom(XFSAccount):
__name__ = "UptoboxCom"
__type__ = "account"
__version__ = "0.21"
__status__ = "testing"
__description__ = """Uptobox.com account plugin"... |
html = self.load(urlparse.urljoin(self.LOGIN_URL, "logarithme"),
post={'op': "login",
'redirect': self.PLUGIN_URL,
'login': user,
'password': password},
cookies=self.C... | self.skip_login() | conditional_block |
UptoboxCom.py | # -*- coding: utf-8 -*-
import re
import urlparse
from ..internal.misc import json
from ..internal.XFSAccount import XFSAccount
class UptoboxCom(XFSAccount):
__name__ = "UptoboxCom"
__type__ = "account"
__version__ = "0.21"
__status__ = "testing"
__description__ = """Uptobox.com account plugin"... | html = self.load(self.LOGIN_URL, cookies=self.COOKIES)
if re.search(self.LOGIN_SKIP_PATTERN, html):
self.skip_login()
html = self.load(urlparse.urljoin(self.LOGIN_URL, "logarithme"),
post={'op': "login",
'redirect': self.PLUGIN_URL,
... | identifier_body | |
UptoboxCom.py | # -*- coding: utf-8 -*-
import re
import urlparse
from ..internal.misc import json
from ..internal.XFSAccount import XFSAccount
class UptoboxCom(XFSAccount):
__name__ = "UptoboxCom"
__type__ = "account"
__version__ = "0.21"
__status__ = "testing"
__description__ = """Uptobox.com account plugin"... | 'login': user,
'password': password},
cookies=self.COOKIES)
if json.loads(html).get('error'):
self.fail_login() | post={'op': "login",
'redirect': self.PLUGIN_URL, | random_line_split |
package.js | /*
Agora Forum Software
Copyright (C) 2016 Gregory Sartucci
License: AGPL-3.0, Check file LICENSE
*/
Package.describe({
name: 'agoraforum:core',
version: '0.1.3',
summary: 'Graph-based forum',
git: 'https://github.com/Agora-Project/agora-meteor',
documentation: 'README.md'
});
Npm.depe... | 'utilities:avatar',
'spacebars',
'email',
'http'
], both);
api.use([
'mrest:restivus',
'percolate:migrations'
], 'server');
api.addFiles([
'lib/identity_collections/identity_collections.js',
'lib/grapher/layered_grapher.js',
'lib/... | 'iron:router',
'useraccounts:iron-routing',
'matb33:collection-hooks',
'accounts-base',
'alanning:roles', | random_line_split |
Element.ts | import { Collection } from './Collection';
import { Util } from './Util';
import { AjaxPromise } from './Ajax';
import { Snapshot } from './Snapshot';
import { PreElement } from './PreElement';
import { Fields } from './Helpers/Element/Fields';
import { Relations } from './Helpers/Element/Relations';
import { Actions,... | // }
} | random_line_split | |
Element.ts | import { Collection } from './Collection';
import { Util } from './Util';
import { AjaxPromise } from './Ajax';
import { Snapshot } from './Snapshot';
import { PreElement } from './PreElement';
import { Fields } from './Helpers/Element/Fields';
import { Relations } from './Helpers/Element/Relations';
import { Actions,... |
export interface Fields {
[field_key: string]: any;
}
export type RelationFunction = () => Element|Element[]|null|undefined;
export interface Relations {
[relation_function_name: string]: RelationFunction;
}
export type ActionFunction = (action_options?: ActionOptions) => AjaxPromise;
export interface Actions... | {
return (!!v || v === 0 || v === '') && (typeof v === 'string' || typeof v === 'number');
} | identifier_body |
Element.ts | import { Collection } from './Collection';
import { Util } from './Util';
import { AjaxPromise } from './Ajax';
import { Snapshot } from './Snapshot';
import { PreElement } from './PreElement';
import { Fields } from './Helpers/Element/Fields';
import { Relations } from './Helpers/Element/Relations';
import { Actions,... | else {
return false;
}
}
}
merge(pre_element: PreElement): this {
let collection_config = this.collection().configuration();
let selector_key = this.collection().scheme().configuration().selector;
Util.forEach(collection_config.fields, (field_config: FieldConfiguration, field_key: st... | {
throw new ElpongError(ElpongErrorType.ELESNE);
} | conditional_block |
Element.ts | import { Collection } from './Collection';
import { Util } from './Util';
import { AjaxPromise } from './Ajax';
import { Snapshot } from './Snapshot';
import { PreElement } from './PreElement';
import { Fields } from './Helpers/Element/Fields';
import { Relations } from './Helpers/Element/Relations';
import { Actions,... | () {
const selector_value: SelectorValue|undefined = this.selector();
if (selector_value !== undefined) {
return this.actions.delete().then(() => {
let elements = this.collection().elements;
elements.delete(selector_value);
});
} else {
Util.removeFromArray(this.collection(... | remove | identifier_name |
tangram.js | /* GCompris - tangram.js
*
* Copyright (C) 2016 Bruno Coudoin <bruno.coudoin@gcompris.net>
*
* Authors:
* Yves Combe / Philippe Banwarth (GTK+ version)
* Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port)
*
* This program is free software; you can redistribute it and/or modify
* it under the te... |
if(closestDist < 0.1)
return [closestItem.x, closestItem.y]
return
}
function check() {
var nbpiece = items.currentTans.pieces.length
var userTans = items.userList.asTans()
for(var i = 0; i < nbpiece; i++) {
var p1 = items.currentTans.pieces[i]
var ok = false
for(v... | {
var p1 = items.currentTans.pieces[i]
var dist = getDistance(p1.x, p1.y, point[0], point[1])
if(dist < closestDist) {
closestDist = dist
closestItem = p1
}
} | conditional_block |
tangram.js | /* GCompris - tangram.js
*
* Copyright (C) 2016 Bruno Coudoin <bruno.coudoin@gcompris.net>
*
* Authors:
* Yves Combe / Philippe Banwarth (GTK+ version)
* Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port)
*
* This program is free software; you can redistribute it and/or modify
* it under the te... |
function dumpTans(tans) {
console.log("== tans ==")
for(var i = 0; i < tans.length; i++) {
console.log(tans[i].img, tans[i].x, tans[i].y, tans[i].rotation, tans[i].flipping)
}
}
/* Returns the [x, y] coordinate of the closest point */
function getClosest(point) {
var nbpiece = items.currentTa... | {
return Math.sqrt(Math.pow((ix - jx), 2) + Math.pow((iy - jy), 2))
} | identifier_body |
tangram.js | /* GCompris - tangram.js
*
* Copyright (C) 2016 Bruno Coudoin <bruno.coudoin@gcompris.net>
*
* Authors:
* Yves Combe / Philippe Banwarth (GTK+ version)
* Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port)
*
* This program is free software; you can redistribute it and/or modify
* it under the te... | } | } | random_line_split |
tangram.js | /* GCompris - tangram.js
*
* Copyright (C) 2016 Bruno Coudoin <bruno.coudoin@gcompris.net>
*
* Authors:
* Yves Combe / Philippe Banwarth (GTK+ version)
* Bruno Coudoin <bruno.coudoin@gcompris.net> (Qt Quick port)
*
* This program is free software; you can redistribute it and/or modify
* it under the te... | () {
if(items.numberOfLevel <= ++currentLevel ) {
currentLevel = 0
}
initLevel();
}
function previousLevel() {
if(--currentLevel < 0) {
currentLevel = items.numberOfLevel - 1
}
initLevel();
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1... | nextLevel | identifier_name |
examples.routes.ts | import { Routes, RouterModule } from '@angular/router';
import { ExamplesComponent } from './examples.component';
const routes: Routes = [
{
path: '', component: ExamplesComponent, children: [
{ path: 'animationexamples', loadChildren: './animations/animations.module#AnimationsModule' }, | { path: 'jquery', loadChildren: './jquery/jquery.module#JqueryModule' },
{ path: 'googlemaps', loadChildren: './google-maps/google-maps.module#GoogleMapsModule' },
{ path: 'texteditor', loadChildren: './text-editor/text-editor.module#TextEditorModule' },
{ path: 'markdown... | { path: 'reactiveforms', loadChildren: './reactive-forms/product.module#ReactiveFormsExampleModules' },
{ path: 'components', loadChildren: './component/component-home.module#ComponentModule' },
{ path: 'directives', loadChildren: './directives/directives.module#DirectivesModule' },
... | random_line_split |
renderSegmentationOutline.test.js | 5] += m[1] * x + m[3] * y;
}
function rotate(rad) {
const c = Math.cos(rad);
const s = Math.sin(rad);
const m11 = m[0] * c + m[2] * s;
const m12 = m[1] * c + m[3] * s;
const m21 = m[0] * -s + m[2] * c;
const m22 = m[1] * -s + m[3] * c;
m[0] = m11;
... | metadata: [],
activeSegmentIndex: 0,
segmentsHidden: [],
};
labelmap2D = {
pixelData: new Uint16Array(labelmap3D.buffer, 0, length),
segmentsOnLabelmap: [0, 1, 2],
};
const pixelData = labelmap2D.pixelData;
const cols = eventData.image.width;
// Add segment 1 as an L shape, so should ... | random_line_split | |
renderSegmentationOutline.test.js | 5] += m[1] * x + m[3] * y;
}
function rotate(rad) {
const c = Math.cos(rad);
const s = Math.sin(rad);
const m11 = m[0] * c + m[2] * s;
const m12 = m[1] * c + m[3] * s;
const m21 = m[0] * -s + m[2] * c;
const m22 = m[1] * -s + m[3] * c;
m[0] = m11;
... |
if (options.vflip) {
viewport.vflip = options.vflip;
}
}
describe('renderSegmentationOutline.js', () => {
beforeEach(() => {
resetEvents();
});
describe('Initialization', () => {
it('should have a test image of 256 x 256 pixels.', () => {
const { width, height } = eventData.image;
... | {
viewport.hflip = options.hflip;
} | conditional_block |
renderSegmentationOutline.test.js | 5] += m[1] * x + m[3] * y;
}
function rotate(rad) {
const c = Math.cos(rad);
const s = Math.sin(rad);
const m11 = m[0] * c + m[2] * s;
const m12 = m[1] * c + m[3] * s;
const m21 = m[0] * -s + m[2] * c;
const m22 = m[1] * -s + m[3] * c;
m[0] = m11;
... | () {
const width = 256;
const length = width * width;
const currentImageIdIndex = 0;
const canvasScale = 1.0;
lineWidth = 1;
eventData = {
element: null,
image: {
width: 256,
height: 256,
},
viewport: {
rotation: 0,
scale: canvasScale,
translation: { x: 0, y:... | resetEvents | identifier_name |
renderSegmentationOutline.test.js | 5] += m[1] * x + m[3] * y;
}
function rotate(rad) {
const c = Math.cos(rad);
const s = Math.sin(rad);
const m11 = m[0] * c + m[2] * s;
const m12 = m[1] * c + m[3] * s;
const m21 = m[0] * -s + m[2] * c;
const m22 = m[1] * -s + m[3] * c;
m[0] = m11;
... | viewport.translation = options.translation;
}
if (options.hflip) {
viewport.hflip = options.hflip;
}
if (options.vflip) {
viewport.vflip = options.vflip;
}
}
describe('renderSegmentationOutline.js', () => {
beforeEach(() => {
resetEvents();
});
describe('Initialization', () => {
... | {
const viewport = eventData.viewport;
if (options.scale) {
const { scale } = options;
const { width, height } = eventData.image;
eventData.viewport.scale = scale;
eventData.canvasContext.canvas = {
width: scale * width,
height: scale * height,
};
}
if (options.rotation) {
... | identifier_body |
robot.js | ._detectWall, // wall
this._detectWheelDrop // wheeldrop
];
// call all the functions with our sensor data values and collect results
var emittedEvents = _.map(emitFunctions, function (emitFunction) {
return emitFunction.call(this, this._sensorData, newSensorData);
}, this);
// if any ... |
return data;
};
// emit | {
data = extend({}, newSensorData.state.mode);
this.emit('mode', data);
} | conditional_block |
robot.js | data = null;
if ((leftCmp.changed && leftCmp.value) ||
(frontLeftCmp.changed && frontLeftCmp.value) ||
(frontRightCmp.changed && frontRightCmp.value) ||
(rightCmp.changed && rightCmp.value)) {
data = extend({}, newSensorData.cliff_sensors);
this.emit('cliff', data);
}
return data;
};
... | // toggle the play or advance LED by name. defaults the 'enable' value to the
// inverse of the last set value.
Robot.prototype._toggleLED = function (name, enable) {
enable = _.isUndefined(enable) ? !this._ledState[name] : enable; | random_line_split | |
setup.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from codecs import open
from os import path
import re
import ast
here = path.abspath(path.dirname(__file__))
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('radmyarchive/__init__.py', 'rb') as vf:
version = ... | "Programming Language :: Python :: 3.4",
"Topic :: Utilities",
),
) | "Environment :: Console",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent", | random_line_split |
owned_stack.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// See the LICENSE file included in this distribution.
extern crate alloc;
use core::slice;
use self::alloc::heap;
use self::alloc::boxed::Box;
/// OwnedStack holds a non-guarded, heap-alloc... | (size: usize) -> OwnedStack {
unsafe {
let ptr = heap::allocate(size, ::STACK_ALIGNMENT);
OwnedStack(Box::from_raw(slice::from_raw_parts_mut(ptr, size)))
}
}
}
impl ::stack::Stack for OwnedStack {
#[inline(always)]
fn base(&self) -> *mut u8 {
// The slice can... | new | identifier_name |
owned_stack.rs | // This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// See the LICENSE file included in this distribution.
extern crate alloc;
use core::slice;
use self::alloc::heap;
use self::alloc::boxed::Box;
/// OwnedStack holds a non-guarded, heap-alloc... | pub fn new(size: usize) -> OwnedStack {
unsafe {
let ptr = heap::allocate(size, ::STACK_ALIGNMENT);
OwnedStack(Box::from_raw(slice::from_raw_parts_mut(ptr, size)))
}
}
}
impl ::stack::Stack for OwnedStack {
#[inline(always)]
fn base(&self) -> *mut u8 {
//... |
impl OwnedStack {
/// Allocates a new stack with exactly `size` accessible bytes and alignment appropriate
/// for the current platform using the default Rust allocator. | random_line_split |
User.ts | import * as bcrypt from 'bcrypt';
import { Exclude } from 'class-transformer';
import { IsNotEmpty } from 'class-validator';
import { BeforeInsert, Column, Entity, OneToMany, PrimaryColumn } from 'typeorm';
import { Pet } from './Pet';
@Entity()
export class User {
public static hashPassword(password: string): P... |
resolve(hash);
});
});
}
public static comparePassword(user: User, password: string): Promise<boolean> {
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, res) => {
resolve(res === true);
... | {
return reject(err);
} | conditional_block |
User.ts | import * as bcrypt from 'bcrypt';
import { Exclude } from 'class-transformer';
import { IsNotEmpty } from 'class-validator';
import { BeforeInsert, Column, Entity, OneToMany, PrimaryColumn } from 'typeorm';
import { Pet } from './Pet';
@Entity()
export class User {
public static hashPassword(password: string): P... |
}
| {
this.password = await User.hashPassword(this.password);
} | identifier_body |
User.ts | import * as bcrypt from 'bcrypt';
import { Exclude } from 'class-transformer';
import { IsNotEmpty } from 'class-validator';
import { BeforeInsert, Column, Entity, OneToMany, PrimaryColumn } from 'typeorm';
import { Pet } from './Pet';
@Entity()
export class User {
public static hashPassword(password: string): P... | (): string {
return `${this.firstName} ${this.lastName} (${this.email})`;
}
@BeforeInsert()
public async hashPassword(): Promise<void> {
this.password = await User.hashPassword(this.password);
}
}
| toString | identifier_name |
User.ts | import * as bcrypt from 'bcrypt';
import { Exclude } from 'class-transformer';
import { IsNotEmpty } from 'class-validator';
import { BeforeInsert, Column, Entity, OneToMany, PrimaryColumn } from 'typeorm';
import { Pet } from './Pet';
@Entity()
export class User {
public static hashPassword(password: string): P... | });
});
}
public static comparePassword(user: User, password: string): Promise<boolean> {
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, res) => {
resolve(res === true);
});
});
}
@Prim... | bcrypt.hash(password, 10, (err, hash) => {
if (err) {
return reject(err);
}
resolve(hash); | random_line_split |
component.ts | import {Component, Inject} from '@angular/core';
import {TodoStore, Todo} from './services/store';
@Component({
moduleId: __moduleName,
selector: 'ng2-todo',
templateUrl: 'template.html',
styleUrls: ['style.css'],
providers: [TodoStore]
})
export class Ng2Todo {
todoStore: TodoStore;
newTod... | (todo: Todo, editedTitle: string) {
todo.title = editedTitle;
todo.editing = false;
}
cancelEditingTodo(todo: Todo) {
todo.editing = false;
}
updateEditingTodo(todo: Todo, editedTitle: string) {
editedTitle = editedTitle.trim();
todo.editing = false;
if... | stopEditing | identifier_name |
component.ts | import {Component, Inject} from '@angular/core';
import {TodoStore, Todo} from './services/store';
@Component({
moduleId: __moduleName,
selector: 'ng2-todo',
templateUrl: 'template.html',
styleUrls: ['style.css'],
providers: [TodoStore]
})
export class Ng2Todo {
todoStore: TodoStore;
newTod... |
stopEditing(todo: Todo, editedTitle: string) {
todo.title = editedTitle;
todo.editing = false;
}
cancelEditingTodo(todo: Todo) {
todo.editing = false;
}
updateEditingTodo(todo: Todo, editedTitle: string) {
editedTitle = editedTitle.trim();
todo.editing = f... | {
this.todoStore = todoStore;
} | identifier_body |
component.ts | import {Component, Inject} from '@angular/core';
import {TodoStore, Todo} from './services/store';
@Component({
moduleId: __moduleName,
selector: 'ng2-todo',
templateUrl: 'template.html',
styleUrls: ['style.css'],
providers: [TodoStore]
})
export class Ng2Todo {
todoStore: TodoStore;
newTod... | this.todoStore.removeCompleted();
}
toggleCompletion(todo: Todo) {
this.todoStore.toggleCompletion(todo);
}
remove(todo: Todo){
this.todoStore.remove(todo);
}
addTodo() {
if (this.newTodoText.trim().length) {
this.todoStore.add(this.newTodoText);
... | todo.editing = true;
}
removeCompleted() { | random_line_split |
component.ts | import {Component, Inject} from '@angular/core';
import {TodoStore, Todo} from './services/store';
@Component({
moduleId: __moduleName,
selector: 'ng2-todo',
templateUrl: 'template.html',
styleUrls: ['style.css'],
providers: [TodoStore]
})
export class Ng2Todo {
todoStore: TodoStore;
newTod... |
todo.title = editedTitle;
}
editTodo(todo: Todo) {
todo.editing = true;
}
removeCompleted() {
this.todoStore.removeCompleted();
}
toggleCompletion(todo: Todo) {
this.todoStore.toggleCompletion(todo);
}
remove(todo: Todo){
this.todoStore.remov... | {
return this.todoStore.remove(todo);
} | conditional_block |
application_configuration.py | # Copyright 2017 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
def GetPreIncludes(self):
"""Get a list of absolute paths to gypi files to include in order.
These files will be included by GYP before any processed .gyp file. The
files returned by this function will be included by GYP before any other
gypi files.
Returns:
An ordered list containing ab... | """Gets the directory of the application configuration."""
return self._application_directory | identifier_body |
application_configuration.py | # Copyright 2017 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | (object):
"""Base build configuration class for all Starboard applications.
Should be derived by application configurations.
"""
def __init__(self, platform_configuration, application_name,
application_directory):
"""Initialize ApplicationConfiguration.
Args:
platform_configurati... | ApplicationConfiguration | identifier_name |
application_configuration.py | # Copyright 2017 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
return []
def GetEnvironmentVariables(self):
"""Get a Mapping of environment variable overrides.
The environment variables returned by this function are set before calling
GYP or GN and can be used to manipulate their behavior. They will override
any environment variables of the same name in th... | return [standard_gypi_path] | conditional_block |
application_configuration.py | # Copyright 2017 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
def __init__(self, platform_configuration, application_name,
application_directory):
"""Initialize ApplicationConfiguration.
Args:
platform_configuration: An instance of StarboardBuildConfiguration for the
platform being built.
application_name: The n... | """Base build configuration class for all Starboard applications.
Should be derived by application configurations.
""" | random_line_split |
crypto.rs | use argon2::{self, Config, ThreadMode, Variant, Version};
use errors::Error;
// hash encodes plaintext with a salt vector slice. Returns encoded string or
// fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html)
pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> {
/... | // For optimal security, cost parameters should be fine tuned to machine
// CPU and memory specs.
//
// ref: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
let cfg = Config {
variant: Variant::Argon2id,
version: Version::Version13,
mem_cost: 512,
... | random_line_split | |
crypto.rs | use argon2::{self, Config, ThreadMode, Variant, Version};
use errors::Error;
// hash encodes plaintext with a salt vector slice. Returns encoded string or
// fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html)
pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> {
/... |
// generate_salt creates salt vector of a usize parameter.
pub fn generate_salt(size: usize) -> Vec<u8> {
nonce(size).as_bytes().to_vec()
}
// nonce takes a usize parameter for length
fn nonce(take: usize) -> String {
use rand::{self, Rng};
rand::thread_rng()
.gen_ascii_chars()
.take(tak... | {
let is_valid = argon2::verify_encoded(encoded_hash, password)?;
Ok(is_valid)
} | identifier_body |
crypto.rs | use argon2::{self, Config, ThreadMode, Variant, Version};
use errors::Error;
// hash encodes plaintext with a salt vector slice. Returns encoded string or
// fails with [argon2::Error](https://docs.rs/rust-argon2/0.3.0/argon2/enum.Error.html)
pub fn hash(password: &str, salt: Vec<u8>) -> Result<String, Error> {
/... | () {
let salt = generate_salt(24);
assert_eq!(24, salt.len());
}
#[test]
fn hash_and_validate() {
let salt = generate_salt(16);
let digest = hash(&PWD, salt).unwrap();
let verified = verify(&digest, &PWD.as_bytes()).unwrap();
let should_eq_false = verify(&dig... | gen_salt | identifier_name |
data_manipulation.py | import pandas
import numpy
import operator
from sklearn.preprocessing import OneHotEncoder
from typing import Mapping
def one_hot_encode(vector, dtype='float32', categories=None, index=None):
if isinstance(vector, pandas.Series):
index = vector.index
vector = vector.values
encoder = OneHotEncoder(
categorie... | 12 OP
13 OP
14 OP
15 PM
16 PM
17 PM
18 PM
19 OP
20 OP
21 OP
22 OP
dtype: category
Categories (3, object): ['AM', 'OP', 'PM']
"""
if mapping is None:
mapping = []
if isinstance(mapping, Mapping):
mapping = list(mapping.items())
mapping.extend(kwargs.items())
if i... | 8 AM
9 OP
10 OP
11 OP | random_line_split |
data_manipulation.py |
import pandas
import numpy
import operator
from sklearn.preprocessing import OneHotEncoder
from typing import Mapping
def one_hot_encode(vector, dtype='float32', categories=None, index=None):
|
def periodize(
values,
mapping=None,
default=None,
right=True,
left=True,
**kwargs,
):
"""
Label sections of a continuous variable.
This function contrasts with `pandas.cut` in that
there can be multiple non-contiguous sections of the
underlying continuous interval that obtain the same
categorical ... | if isinstance(vector, pandas.Series):
index = vector.index
vector = vector.values
encoder = OneHotEncoder(
categories='auto' if categories is None else [categories,],
sparse=False,
dtype=dtype,
).fit(vector.reshape(-1,1))
return pandas.DataFrame(
data = encoder.transform(vector.reshape(-1,1)),
column... | identifier_body |
data_manipulation.py |
import pandas
import numpy
import operator
from sklearn.preprocessing import OneHotEncoder
from typing import Mapping
def one_hot_encode(vector, dtype='float32', categories=None, index=None):
if isinstance(vector, pandas.Series):
index = vector.index
vector = vector.values
encoder = OneHotEncoder(
categori... | (
values,
mapping=None,
default=None,
right=True,
left=True,
**kwargs,
):
"""
Label sections of a continuous variable.
This function contrasts with `pandas.cut` in that
there can be multiple non-contiguous sections of the
underlying continuous interval that obtain the same
categorical value.
Parame... | periodize | identifier_name |
data_manipulation.py |
import pandas
import numpy
import operator
from sklearn.preprocessing import OneHotEncoder
from typing import Mapping
def one_hot_encode(vector, dtype='float32', categories=None, index=None):
if isinstance(vector, pandas.Series):
index = vector.index
vector = vector.values
encoder = OneHotEncoder(
categori... |
else:
rop = operator.lt
if left:
lop = operator.ge
else:
lop = operator.gt
for k,(lowerbound,upperbound) in mapping:
if lowerbound is None:
lowerbound = -numpy.inf
if upperbound is None:
upperbound = numpy.inf
x[lop(values,lowerbound) & rop(values,upperbound)] = k
if isinstance(x, pandas.Seri... | rop = operator.le | conditional_block |
into_matcher.rs | use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn from(s: &'a str) -> Matcher {
From::from(s.to_string())
... | // There should only ever be one match (after subgroup 0)
let c = captures.iter().skip(1).next().unwrap();
format!("(?P<{}>[,a-zA-Z0-9%_-]*)", c.unwrap())
});
let line_regex = format!("^{}{}$", named_captures, REGEX_PARAM_SEQ);
let regex = Regex::new(&line_re... | {
let with_format = if s.contains(FORMAT_VAR) {
s
} else {
format!("{}(\\.{})?", s, FORMAT_VAR)
};
// First mark all double wildcards for replacement. We can't directly
// replace them since the replacement does contain the * symbol as well,
// wh... | identifier_body |
into_matcher.rs | use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn | (s: &'a str) -> Matcher {
From::from(s.to_string())
}
}
lazy_static! {
static ref REGEX_VAR_SEQ: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap();
}
pub static FORMAT_PARAM: &'static str = "format";
// FIXME: Once const fn lands this could be defined in terms of the above
static FORMAT_VAR: ... | from | identifier_name |
into_matcher.rs | use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn from(s: &'a str) -> Matcher {
From::from(s.to_string())
... | else {
format!("{}(\\.{})?", s, FORMAT_VAR)
};
// First mark all double wildcards for replacement. We can't directly
// replace them since the replacement does contain the * symbol as well,
// which would get overwritten with the next replace call
let with_placehold... | {
s
} | conditional_block |
into_matcher.rs | use super::Matcher;
use regex::{Regex, Captures};
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
let path = regex.as_str().to_string();
Matcher::new(path, regex)
}
}
impl<'a> From<&'a str> for Matcher {
fn from(s: &'a str) -> Matcher {
From::from(s.to_string())
... | static FORMAT_VAR: &'static str = ":format";
static VAR_SEQ: &'static str = "[,a-zA-Z0-9_-]*";
static VAR_SEQ_WITH_SLASH: &'static str = "[,/a-zA-Z0-9_-]*";
// matches request params (e.g. ?foo=true&bar=false)
static REGEX_PARAM_SEQ: &'static str = "(\\?[a-zA-Z0-9%_=&-]*)?";
impl From... | static ref REGEX_VAR_SEQ: Regex = Regex::new(r":([,a-zA-Z0-9_-]*)").unwrap();
}
pub static FORMAT_PARAM: &'static str = "format";
// FIXME: Once const fn lands this could be defined in terms of the above | random_line_split |
App.tsx | 'use strict';
import Logger = require('./logger');
window.onerror = (errorMsg: string, url, line, col, error) => {
Logger.error(errorMsg, {url: url, lineNumber: line, colNumber: col, error: error});
return true;
};
import React = require('react');
import ReactDOM = require('react-dom');
import Backbone = require... | import event = require('./event');
ReactDOM.render(<Header />, $('header')[0]);
Router.on('route:default', (url: string) => {
var store;
if (url) {
var urlparts: string[] = url.split('/');
store = <Store action={urlparts[0]} args={urlparts.slice(1)} />;
} else {
store = <Store />;
}
ReactDOM.ren... |
import Router = require('./router'); | random_line_split |
datepicker-inner.component.ts | ];
/*
const KEYS = {
13: 'enter',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
*/
@Component({
selector: 'datepicker-inner',
template: `
<div *ngIf="datepickerMode" class="well well-sm bg-faded p-a card" role="application" ><!-... | direction = direction || 1;
if ((this.datepickerMode === this.maxMode && direction === 1) ||
(this.datepickerMode === this.minMode && direction === -1)) { | random_line_split | |
datepicker-inner.component.ts | {
13: 'enter',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
*/
@Component({
selector: 'datepicker-inner',
template: `
<div *ngIf="datepickerMode" class="well well-sm bg-faded p-a card" role="application" ><!--<!–ng-keyd... | {
return;
} | conditional_block | |
datepicker-inner.component.ts | 0;
// const MIN_DATE:Date = void 0;
// const MAX_DATE:Date = void 0;
const SHORTCUT_PROPAGATION = false;
// const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
/*
const KEYS = {
13: 'enter',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'righ... |
public select(date:Date):void {
if (this.datepickerMode === this.minMode) {
if (!this.activeDate) {
this.activeDate = new Date(0, 0, 0, 0, 0, 0, 0);
}
this.activeDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
this.selectionDone.emit(this.activeDate);
}... | {
let hours = date.getHours();
return new Date(date.getFullYear(), date.getMonth(), date.getDate(), hours === 23 ? hours + 2 : 0);
} | identifier_body |
datepicker-inner.component.ts | 20;
// const MIN_DATE:Date = void 0;
// const MAX_DATE:Date = void 0;
const SHORTCUT_PROPAGATION = false;
// const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
/*
const KEYS = {
13: 'enter',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'rig... | (date1:Date, date2:Date):number {
if (date1 === undefined || date2 === undefined) {
return undefined;
}
if (this.datepickerMode === 'day' && this.compareHandlerDay) {
return this.compareHandlerDay(date1, date2);
}
if (this.datepickerMode === 'month' && this.compareHandlerMonth) {
... | compare | identifier_name |
Password.js | import PropTypes from 'prop-types';
import React from 'react';
import Input from 'mcs-lite-ui/lib/Input';
import Button from 'mcs-lite-ui/lib/Button';
import MobileFixedFooter from 'mcs-lite-ui/lib/MobileFixedFooter';
import MobileHeader from 'mcs-lite-ui/lib/MobileHeader';
import validators from 'mcs-lite-ui/lib/utils... | kind={isNew1Error ? 'error' : 'primary'}
/>
{isNew1Error && (
<StyledP color="error">{t('lengthError')}</StyledP>
)}
</div>
<div>
<Label htmlFor="new2">{t('newPasswordAgain.label')}</Label>
... | required | random_line_split |
Password.js | import PropTypes from 'prop-types';
import React from 'react';
import Input from 'mcs-lite-ui/lib/Input';
import Button from 'mcs-lite-ui/lib/Button';
import MobileFixedFooter from 'mcs-lite-ui/lib/MobileFixedFooter';
import MobileHeader from 'mcs-lite-ui/lib/MobileHeader';
import validators from 'mcs-lite-ui/lib/utils... | extends React.Component {
static propTypes = {
// Redux Action
changePassword: PropTypes.func.isRequired,
// React-intl I18n
getMessages: PropTypes.func.isRequired,
};
state = { new1: '', new2: '' };
onChange = e => this.setState({ [e.target.name]: e.target.value });
onSubmit = e => {
th... | Password | identifier_name |
mod.rs | use crate::fx::FxHashMap;
use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog};
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops;
pub use crate::undo_log::Snapshot;
#[cfg(test)]
mod tests;
pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, ... | pub fn get(&self, key: &K) -> Option<&V> {
self.map.borrow().get(key)
}
}
impl<K, V> SnapshotMap<K, V>
where
K: Hash + Clone + Eq,
{
pub fn snapshot(&mut self) -> Snapshot {
self.undo_log.start_snapshot()
}
pub fn commit(&mut self, snapshot: Snapshot) {
self.undo_log.co... | }
| random_line_split |
mod.rs | use crate::fx::FxHashMap;
use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog};
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops;
pub use crate::undo_log::Snapshot;
#[cfg(test)]
mod tests;
pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, ... |
UndoLog::Purged => {}
}
}
}
| {
self.insert(key, old_value);
} | conditional_block |
mod.rs | use crate::fx::FxHashMap;
use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog};
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops;
pub use crate::undo_log::Snapshot;
#[cfg(test)]
mod tests;
pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, ... |
pub fn remove(&mut self, key: K) -> bool {
match self.map.borrow_mut().remove(&key) {
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
true
}
None => false,
}
}
pub fn get(&self, key: &K) -> Op... | {
match self.map.borrow_mut().insert(key.clone(), value) {
None => {
self.undo_log.push(UndoLog::Inserted(key));
true
}
Some(old_value) => {
self.undo_log.push(UndoLog::Overwrite(key, old_value));
false
... | identifier_body |
mod.rs | use crate::fx::FxHashMap;
use crate::undo_log::{Rollback, Snapshots, UndoLogs, VecLog};
use std::borrow::{Borrow, BorrowMut};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops;
pub use crate::undo_log::Snapshot;
#[cfg(test)]
mod tests;
pub type SnapshotMapStorage<K, V> = SnapshotMap<K, V, FxHashMap<K, ... | <L2>(&mut self, undo_log: L2) -> SnapshotMap<K, V, &mut M, L2> {
SnapshotMap { map: &mut self.map, undo_log, _marker: PhantomData }
}
}
impl<K, V, M, L> SnapshotMap<K, V, M, L>
where
K: Hash + Clone + Eq,
M: BorrowMut<FxHashMap<K, V>> + Borrow<FxHashMap<K, V>>,
L: UndoLogs<UndoLog<K, V>>,
{
... | with_log | identifier_name |
menu.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::vec::Vec;
use gfx::GameDisplay;
use super::{UiBox, UiFont, draw_text_box, c... | formatted_entries: Vec::new(),
bg_color: (0,0,0),
selected_prefix: "".to_string(),
unselected_prefix: "".to_string(),
curr_selected: 0,
coords: (0,0),
box_size: (0,0),
text_gap: 2
}
}
pub fn move_down(&mut se... | VertTextMenu {
entries: Vec::new(), | random_line_split |
menu.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::vec::Vec;
use gfx::GameDisplay;
use super::{UiBox, UiFont, draw_text_box, c... | (&mut self, coords: (int, int), ui_font: &TFont, ui_box: &TBox) {
// figure out width, in pixels, of the text (based on longest entry line)
self.formatted_entries = Vec::new();
for v in range(0, self.entries.len()) {
let formatted = self.get_formatted(v);
self.formatted_e... | update_bounds | identifier_name |
menu.rs | // Copyright 2013-2014 Jeffery Olson
//
// Licensed under the 3-Clause BSD License, see LICENSE.txt
// at the top-level of this repository.
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::vec::Vec;
use gfx::GameDisplay;
use super::{UiBox, UiFont, draw_text_box, c... | else {
&self.unselected_prefix
};
format!("{} {}", *prefix, entry)
}
pub fn update_bounds(&mut self, coords: (int, int), ui_font: &TFont, ui_box: &TBox) {
// figure out width, in pixels, of the text (based on longest entry line)
self.formatted_entries = Vec::new();
... | {
&self.selected_prefix
} | conditional_block |
test.py | # Copyright (C) 2016 VIB/BEG/UGent - Tim Diels <tim@diels.me>
#
# This file is part of pytil.
#
# pytil 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 opt... | (path, ignore=()):
'''
Assert dir unchanged after code block.
Parameters
----------
path : ~pathlib.Path
Dir to assert for changes.
ignore : ~typing.Collection[~pathlib.Path]
Paths to ignore in comparison.
Examples
--------
>>> with assert_dir_unchanged(Path('input'... | assert_dir_unchanged | identifier_name |
test.py | # Copyright (C) 2016 VIB/BEG/UGent - Tim Diels <tim@diels.me>
#
# This file is part of pytil.
#
# pytil is free software: you can redistribute it and/or modify | #
# pytil 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 License... | # 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 |
test.py | # Copyright (C) 2016 VIB/BEG/UGent - Tim Diels <tim@diels.me>
#
# This file is part of pytil.
#
# pytil 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 opt... |
# Used by cedalion
@contextmanager
def assert_dir_unchanged(path, ignore=()):
'''
Assert dir unchanged after code block.
Parameters
----------
path : ~pathlib.Path
Dir to assert for changes.
ignore : ~typing.Collection[~pathlib.Path]
Paths to ignore in comparison.
Example... | '''
pytest fixture which sets current working directory to a temporary
directory.
'''
original_cwd = Path.cwd()
os.chdir(str(tmpdir))
yield tmpdir
# ensure the user has full permissions on temp dir (so that pytest can remove it later)
path_.chmod(Path(str(tmpdir)), 0o700, '+', recursive... | identifier_body |
index.ts | import {
MapExt,
SetExt,
targetStore,
getProtoChain,
isFunction,
Constructor,
TDMModel,
TDMModelBase,
TDMCollection,
MetaClass
} from '@tdm/core/tdm';
import {
ActionMetadata,
ExecuteContext,
AdapterStatic,
PluginStore,
ActionController,
ResourceControl
} from '@tdm/data';
/**
* Retur... | return self.execute(ctx.clone(this), { args }, 'instance');
});
}
}
else {
if (action.isCollection) {
throw new Error(
'An action with a collection response must be a static level member'
);
}
if (override || !isFunction(this.target.prototype[action.name])) {
... | {
if (override || !isFunction(this.target[action.name])) {
composeAction(this.target, action, function(
this: AdapterStatic<any, any>,
...args: any[]
) {
return self.execute(ctx.clone(), { args }, 'instance');
});
}
if (
action.isCollection &&
action.co... | conditional_block |
index.ts | import {
MapExt,
SetExt,
targetStore,
getProtoChain,
isFunction,
Constructor,
TDMModel,
TDMModelBase,
TDMCollection,
MetaClass
} from '@tdm/core/tdm';
import {
ActionMetadata,
ExecuteContext,
AdapterStatic,
PluginStore,
ActionController,
ResourceControl
} from '@tdm/data';
/**
* Retur... | () {
return ResourceControl.get(this);
}
// extend TDMModel
Object.defineProperty(TDMModelBase.prototype, propertyName, {
configurable: true,
get: getThisCtrl
});
// extend TDMCollection
function StatefulActiveRecordCollection() {}
Object.defineProperty(
StatefulActiveRecordCollection.pr... | getThisCtrl | identifier_name |
index.ts | import {
MapExt,
SetExt,
targetStore,
getProtoChain,
isFunction,
Constructor,
TDMModel,
TDMModelBase,
TDMCollection,
MetaClass
} from '@tdm/core/tdm';
import {
ActionMetadata,
ExecuteContext,
AdapterStatic,
PluginStore,
ActionController,
ResourceControl
} from '@tdm/data';
/**
* Retur... |
function composeAction(
obj: any,
action: ActionMetadata,
fn: (...args: any[]) => any
): void {
obj[action.name] = fn;
if (action.alias) {
action.alias.forEach(alias => (obj[alias] = obj[action.name]));
}
}
function registerAction(
this: ActionController,
action: ActionMetadata,
collProto: any,... | {
const chain = getProtoChain(target);
const actions = new Map<TdmPropertyKey, ActionMetadata>();
for (let i = 0, len = chain.length; i < len; i++) {
if (targetStore.hasTarget(chain[i])) {
const adapterMeta = targetStore.getAdapter(adapterClass);
const mixins = SetExt.asArray(
targetStore... | identifier_body |
index.ts | import {
MapExt,
SetExt,
targetStore,
getProtoChain,
isFunction,
Constructor,
TDMModel,
TDMModelBase,
TDMCollection,
MetaClass
} from '@tdm/core/tdm';
import {
ActionMetadata,
ExecuteContext,
AdapterStatic,
PluginStore,
ActionController,
ResourceControl
} from '@tdm/data';
/**
* Retur... | * declare module '@tdm/core/tdm/src/model/tdm-collection' {
* interface TDMCollection<T> {
* readonly $rc: ResourceControl<StatefulActiveRecordCollection<T>>;
* }
* }
* ```
*
* If not set (falsy expression) the resource control instance can not be accessed directly from the model instanc... | * export interface StatefulActiveRecordCollection<T> extends TDMCollection<T>, TDMModel<StatefulActiveRecordCollection<T>> { }
* | random_line_split |
semantic.ts | //
// Copyright 2015-21 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (expr: string): SemanticTree {
const mml = DomUtil.parseInput(expr);
return getTree(mml);
}
| getTreeFromString | identifier_name |
semantic.ts | //
// Copyright 2015-21 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | {
const mml = DomUtil.parseInput(expr);
return getTree(mml);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.