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 |
|---|---|---|---|---|
log-json-syntax-tree.js | const csound = require('bindings')('csound-api.node');
const stringify = require('json-stable-stringify');
const Csound = csound.Create();
const ASTRoot = csound.ParseOrc(Csound, `
0dbfs = 1
giFunctionTableID ftgen 0, 0, 16384, 10, 1
instr A440
outc oscili(0.5 * 0dbfs, 440, giFunctionTableID)
endin
`);
//... |
let result = compareKeys(a.key, b.key);
if (result !== null) return result;
result = compareKeys(b.key, a.key);
return (result !== null) ? -result : a.key.localeCompare(b.key);
},
replacer: (key, value) => (key === 'next') ? undefined : value,
space: ' '
}));
| {
switch (key1) {
case 'left': if (key2 === 'right') return -1; /* falls through */
case 'right': if (key2 === 'nextNodes') return -1; /* falls through */
case 'nextNodes': return (key1 === key2) ? 0 : 1;
}
return null;
} | identifier_body |
index.ts | import { Module } from 'vuex'
import RootState from '@vue-storefront/core/types/RootState'
import PaymentState from '../../types/PaymentState'
import { Logger } from '@vue-storefront/core/lib/logger'
// @deprecated
export const paymentModule: Module<PaymentState, RootState> = {
namespaced: true,
actions: {
add... |
},
getters: {
// @deprecated
paymentMethods: (state, getters, rootState, rootGetters) => rootGetters['checkout/getPaymentMethods'],
// @deprecated
getDefaultPaymentMethod: (state, getters, rootState, rootGetters) => rootGetters['checkout/getDefaultPaymentMethod'],
// @deprecated
getNotServe... | {
Logger.error('The action payment/replaceMethods has been deprecated please change to checkout/replacePaymentMethods')()
dispatch('checkout/replacePaymentMethods', paymentMethods, { root: true })
} | identifier_body |
index.ts | import { Module } from 'vuex'
import RootState from '@vue-storefront/core/types/RootState'
import PaymentState from '../../types/PaymentState'
import { Logger } from '@vue-storefront/core/lib/logger'
// @deprecated
export const paymentModule: Module<PaymentState, RootState> = {
namespaced: true,
actions: {
| ({ dispatch }, paymentMethod) {
Logger.error('The action payment/addMethod has been deprecated please change to checkout/addPaymentMethod')()
dispatch('checkout/addPaymentMethod', paymentMethod, { root: true })
},
replaceMethods ({ dispatch }, paymentMethods) {
Logger.error('The action payme... | addMethod | identifier_name |
index.ts | import { Module } from 'vuex'
import RootState from '@vue-storefront/core/types/RootState'
import PaymentState from '../../types/PaymentState'
import { Logger } from '@vue-storefront/core/lib/logger'
// @deprecated
export const paymentModule: Module<PaymentState, RootState> = {
namespaced: true,
actions: {
add... | getDefaultPaymentMethod: (state, getters, rootState, rootGetters) => rootGetters['checkout/getDefaultPaymentMethod'],
// @deprecated
getNotServerPaymentMethods: (state, getters, rootState, rootGetters) => rootGetters['checkout/getNotServerPaymentMethods']
}
} | random_line_split | |
test_base.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 use ... | class BaseStorageTests(unittest.TestCase):
def setUp(self):
self.send_called = 0
StorageDriver.connectionCls.conn_class = BaseMockRawResponse
self.driver1 = StorageDriver('username', 'key', host='localhost')
self.driver1.supports_chunked_encoding = True
self.driver2 = Stor... | random_line_split | |
test_base.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 use ... | (self):
self.driver1.hash_type = 'md5'
func = self.driver1._get_hash_function()
self.assertTrue(func)
self.driver1.hash_type = 'sha1'
func = self.driver1._get_hash_function()
self.assertTrue(func)
try:
self.driver1.hash_type = 'invalid-hash-function'... | test__get_hash_function | identifier_name |
test_base.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 use ... | self.driver1.strict_mode = True
expected_msg = ('File content-type could not be guessed and no'
' content_type value is provided')
self.assertRaisesRegexp(AttributeError, expected_msg,
self.driver1._upload_object,
... | iterator = StringIO()
upload_func = Mock()
upload_func.return_value = True, '', 0
# strict_mode is disabled, default content type should be used
self.driver1.connection = Mock()
self.driver1._upload_object(object_name='test',
content_type=No... | identifier_body |
test_base.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 use ... | sys.exit(unittest.main()) | conditional_block | |
StartScreen.tsx | type GameStateStartProps = {
onStart: () => void |
// The first game state. It just shows an introduction and a button that the player can click
// when they're ready.
export default function GameStateStart({ onStart }: GameStateStartProps) {
return (
<>
<header className="page-header">
<h1>
So Puzzled!! <br /> {' '}
<small>
... | } | random_line_split |
StartScreen.tsx | type GameStateStartProps = {
onStart: () => void
}
// The first game state. It just shows an introduction and a button that the player can click
// when they're ready.
export default function GameStateStart({ onStart }: GameStateStartProps) | <li>Piece the image back together</li>
<li>.. profit?</li>
</ol>
<p>
<button
type="button"
className="btn btn-success btn-lg"
onClick={onStart}
>
Start Puzzling
</button>
</p>
</main>
</>... | {
return (
<>
<header className="page-header">
<h1>
So Puzzled!! <br /> {' '}
<small>
A little puzzle game for practice, written in React and jQueryUI
</small>
</h1>
</header>
<main className="jumbotron text-center">
<h2>How to ... | identifier_body |
StartScreen.tsx | type GameStateStartProps = {
onStart: () => void
}
// The first game state. It just shows an introduction and a button that the player can click
// when they're ready.
export default function | ({ onStart }: GameStateStartProps) {
return (
<>
<header className="page-header">
<h1>
So Puzzled!! <br /> {' '}
<small>
A little puzzle game for practice, written in React and jQueryUI
</small>
</h1>
</header>
<main className="jumbotro... | GameStateStart | identifier_name |
jspdf.plugin.png_support.js | 1 Sub
2 Up
3 Average
4 Paeth
*/
var doesNotHavePngJS = function() {
return typeof PNG !== 'function' || typeof FlateStream !== 'function';
}
, canCompress = function(value) {
return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
}
, hasC... |
return ind;
}
, absSum = function(array) {
var i = 0,
len = array.length,
sum = 0;
while(i < len)
sum += Math.abs(array[i++]);
return sum;
}
, logImg = function(img) {
console.log("width: " + img.width);
console.log("height: " + img.height);
console.log("bits: " + i... | {
sum = absSum(arrays[i].slice(1));
if(sum < min || !min) {
min = sum;
ind = i;
}
i++;
} | conditional_block |
jspdf.plugin.png_support.js | 1 Sub
2 Up
3 Average
4 Paeth
*/
var doesNotHavePngJS = function() {
return typeof PNG !== 'function' || typeof FlateStream !== 'function';
}
, canCompress = function(value) {
return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();
}
, hasC... | } while (--tlen);
s1 %= 65521;
s2 %= 65521;
}
return ((s2 << 16) | s1) >>> 0;
}
, applyPngFilterMethod = function(bytes, lineLength, colorsPerPixel, filter_method) {
var lines = bytes.length / lineLength,
result = new Uint8Array(bytes.length + lines),
filter_methods... | s2 += s1;
| random_line_split |
capabilities.js | function safeMatchMedia(query) {
var m = window.matchMedia(query);
return !!m && m.matches;
}
define('capabilities', [], function() {
var capabilities = {
'JSON': window.JSON && typeof JSON.parse == 'function',
'debug': (('' + document.location).indexOf('dbg') >= 0),
'debug_in_page'... | capabilities.sessionStorage = true;
}
} catch (e) {
}
return capabilities;
});
z.capabilities = require('capabilities'); | if ('sessionStorage' in window && window.sessionStorage !== null) { | random_line_split |
capabilities.js | function safeMatchMedia(query) {
var m = window.matchMedia(query);
return !!m && m.matches;
}
define('capabilities', [], function() {
var capabilities = {
'JSON': window.JSON && typeof JSON.parse == 'function',
'debug': (('' + document.location).indexOf('dbg') >= 0),
'debug_in_page'... |
} catch (e) {
}
return capabilities;
});
z.capabilities = require('capabilities');
| {
capabilities.sessionStorage = true;
} | conditional_block |
capabilities.js | function safeMatchMedia(query) |
define('capabilities', [], function() {
var capabilities = {
'JSON': window.JSON && typeof JSON.parse == 'function',
'debug': (('' + document.location).indexOf('dbg') >= 0),
'debug_in_page': (('' + document.location).indexOf('dbginpage') >= 0),
'console': window.console && (typeof ... | {
var m = window.matchMedia(query);
return !!m && m.matches;
} | identifier_body |
capabilities.js | function | (query) {
var m = window.matchMedia(query);
return !!m && m.matches;
}
define('capabilities', [], function() {
var capabilities = {
'JSON': window.JSON && typeof JSON.parse == 'function',
'debug': (('' + document.location).indexOf('dbg') >= 0),
'debug_in_page': (('' + document.locat... | safeMatchMedia | identifier_name |
test_pep8.py | from __future__ import with_statement
import unittest
import re
import os
import sys
import cStringIO as StringIO
from distutils.version import LooseVersion
import pep8
PEP8_VERSION = LooseVersion(pep8.__version__)
PEP8_MAX_OLD_VERSION = LooseVersion('1.0.1')
PEP8_MIN_NEW_VERSION = LooseVersion('1.3.3')
# Check for ... |
# Populate pep8 test methods, one per non-skipped .py file found.
ROOT = os.getcwd()
for (dirpath, dirnames, filenames) in os.walk(ROOT, followlinks=True):
for regex in NAMES_TO_SKIP:
paths = dirnames[:] # lame list copy
for path in paths:
if regex.match(path):
dirname... | self.options = None | conditional_block |
test_pep8.py | from __future__ import with_statement
import unittest
import re
import os
import sys
import cStringIO as StringIO
from distutils.version import LooseVersion
import pep8
PEP8_VERSION = LooseVersion(pep8.__version__)
PEP8_MAX_OLD_VERSION = LooseVersion('1.0.1')
PEP8_MIN_NEW_VERSION = LooseVersion('1.3.3')
# Check for ... | def closure(self, fullpath=fullpath):
pep8.process_options([
'--first', fullpath,
'--ignore', ','.join(PEP8_IGNORE)],
)
pep8.input_file(fullpath)
if len(pep8.get_statistics()):
sel... | fullpath = os.path.join(dirpath, filename)
if PEP8_VERSION < PEP8_MIN_NEW_VERSION: | random_line_split |
test_pep8.py | from __future__ import with_statement
import unittest
import re
import os
import sys
import cStringIO as StringIO
from distutils.version import LooseVersion
import pep8
PEP8_VERSION = LooseVersion(pep8.__version__)
PEP8_MAX_OLD_VERSION = LooseVersion('1.0.1')
PEP8_MIN_NEW_VERSION = LooseVersion('1.3.3')
# Check for ... | (self):
# set up newer pep8 options
if PEP8_VERSION >= PEP8_MIN_NEW_VERSION:
self.options = pep8.StyleGuide().options
self.options.ignore = self.options.ignore + PEP8_IGNORE
else:
self.options = None
# Populate pep8 test methods, one per non-skipped .py file ... | setUpClass | identifier_name |
test_pep8.py | from __future__ import with_statement
import unittest
import re
import os
import sys
import cStringIO as StringIO
from distutils.version import LooseVersion
import pep8
PEP8_VERSION = LooseVersion(pep8.__version__)
PEP8_MAX_OLD_VERSION = LooseVersion('1.0.1')
PEP8_MIN_NEW_VERSION = LooseVersion('1.3.3')
# Check for ... |
class Pep8TestCase(unittest.TestCase):
@classmethod
def setUpClass(self):
# set up newer pep8 options
if PEP8_VERSION >= PEP8_MIN_NEW_VERSION:
self.options = pep8.StyleGuide().options
self.options.ignore = self.options.ignore + PEP8_IGNORE
else:
se... | '''Contextmanager to redirect stdout/stderr.'''
def __init__(self, stdout=None, stderr=None):
self._stdout = stdout or sys.stdout
self._stderr = stderr or sys.stderr
def __enter__(self):
sys.stdout.flush()
sys.stderr.flush()
self.old_stdout, self.old_stderr = sys.stdout,... | identifier_body |
Heavy Hitters.py | #!/usr/bin/env python
import sys
from collections import defaultdict
import itertools
import operator
from operator import itemgetter
counters = defaultdict(int)
trueCounters = defaultdict(int)
fr = open('allworks','r')
wc = 0
for line in fr:
line = line.strip()
words = ''.join(c for c in line if c.isalpha(... |
else:
delCounters = []
for key in counters:
counters[key] -= 1
if counters[key] == 0:
delCounters.append(key)
for word in delCounters:
del counters[word]
# 2nd Pass: True count, Delete by thresold
fr.seek(0... | counters[word] = 1 | conditional_block |
Heavy Hitters.py | #!/usr/bin/env python
import sys
from collections import defaultdict
import itertools
import operator
from operator import itemgetter
counters = defaultdict(int)
trueCounters = defaultdict(int)
fr = open('allworks','r')
wc = 0
for line in fr:
line = line.strip()
words = ''.join(c for c in line if c.isalpha(... | for word in words:
if word in counters:
counters[word] += 1
elif len(counters) < 99:
counters[word] = 1
else:
delCounters = []
for key in counters:
counters[key] -= 1
if counters[key] == 0:
de... | for line in fr:
line = line.strip()
words = ''.join(c for c in line if c.isalpha() or c.isspace()).split()
| random_line_split |
toolbar.js | );
if(this.frm.doc.__islocal) {
this.appframe.set_title_sub("");
} else {
this.appframe.set_title_sub("#" + this.frm.docname);
}
} else {
var title = __(this.frm.docname);
}
var me = this;
this.appframe.set_title(title + this.get_lock_status());
if(this.frm.meta.issingle) {
this.appfra... | })
},
show_title_as_dirty: function() {
if(this.frm.save_disabled)
return; | random_line_split | |
all_3.js | ['delete',['delete',['../namespacetincr_1_1cells.html#a96e3e0042c39e66cb031e57c2f20a62c',1,'tincr::cells::delete()'],['../namespacetincr_1_1macros.html#a172e882d075748714bd3a653658f09ca',1,'tincr::macros::delete()'],['../namespacetincr_1_1nets.html#a1566703d16d7d5d3495dce6b67905b32',1,'tincr::nets::delete()'],['../na... | var searchData=
[ | random_line_split | |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2020 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... | // The function returns an iterator...
{
iterNegativeIntegersSeq(); // $ExpectType Iterator
iterNegativeIntegersSeq( {} ); // $ExpectType Iterator
iterNegativeIntegersSeq( { 'iter': 10 } ); // $ExpectType Iterator
}
// The compiler throws an error if the function is provided a first argument which is not an options... | // TESTS //
| random_line_split |
Filters_Glow.ts | import { Laya } from "Laya";
import { Sprite } from "laya/display/Sprite";
import { GlowFilter } from "laya/filters/GlowFilter";
import { Texture } from "laya/resource/Texture";
import { Browser } from "laya/utils/Browser";
import { Handler } from "laya/utils/Handler";
import { WebGL } from "laya/webgl/WebGL";
import {... | private setup(tex: Texture): void {
this.createApe();
this.applayFilter();
}
private createApe(): void {
this.ape = new Sprite();
this.ape.loadImage(this.apePath);
var texture: Texture = Laya.loader.getRes(this.apePath);
this.ape.x = (Laya.stage.width - texture.width) / 2;
this.ape.y = (Laya.stage.he... | random_line_split | |
Filters_Glow.ts | import { Laya } from "Laya";
import { Sprite } from "laya/display/Sprite";
import { GlowFilter } from "laya/filters/GlowFilter";
import { Texture } from "laya/resource/Texture";
import { Browser } from "laya/utils/Browser";
import { Handler } from "laya/utils/Handler";
import { WebGL } from "laya/webgl/WebGL";
import {... | ape = new Sprite();
this.ape.loadImage(this.apePath);
var texture: Texture = Laya.loader.getRes(this.apePath);
this.ape.x = (Laya.stage.width - texture.width) / 2;
this.ape.y = (Laya.stage.height - texture.height) / 2;
this.Main.box2D.addChild(this.ape);
}
private applayFilter(): void {
//创建一个发光滤镜
va... | {
this. | identifier_name |
Filters_Glow.ts | import { Laya } from "Laya";
import { Sprite } from "laya/display/Sprite";
import { GlowFilter } from "laya/filters/GlowFilter";
import { Texture } from "laya/resource/Texture";
import { Browser } from "laya/utils/Browser";
import { Handler } from "laya/utils/Handler";
import { WebGL } from "laya/webgl/WebGL";
import {... | ex: Texture): void {
this.createApe();
this.applayFilter();
}
private createApe(): void {
this.ape = new Sprite();
this.ape.loadImage(this.apePath);
var texture: Texture = Laya.loader.getRes(this.apePath);
this.ape.x = (Laya.stage.width - texture.width) / 2;
this.ape.y = (Laya.stage.height - texture.h... | {
this.Main = maincls;
// 不支持WebGL时自动切换至Canvas
Laya.init(Browser.clientWidth, Browser.clientHeight, WebGL);
// Laya.stage.alignV = Stage.ALIGN_MIDDLE;
// Laya.stage.alignH = Stage.ALIGN_CENTER;
Laya.stage.scaleMode = "showall";
Laya.stage.bgColor = "#232628";
Laya.loader.load(this.apePath, Handl... | identifier_body |
views.py | #-*-*- encoding: utf-8 -*-*-
from django.shortcuts import render
from django.template import RequestContext, loader, Context
from django.http import JsonResponse
from .models import Airburst
def index(request):
return render(request, 'NextGenThreat/index.html', {})
def radar(request):
latest_airburst_list = Airbu... | rburst_list = Airburst.objects.all()
response = {}
for airburst in airburst_list:
response[airburst.id] = {'radiated_energy': airburst.radiated_energy,
'impact_energy': airburst.impact_energy,
'latitude': airburst.latitude,
'longitude': airburst.longitude,
'date': airburst.date.isofo... | identifier_body | |
views.py | #-*-*- encoding: utf-8 -*-*-
from django.shortcuts import render
from django.template import RequestContext, loader, Context
from django.http import JsonResponse
from .models import Airburst
def index(request):
return render(request, 'NextGenThreat/index.html', {})
def radar(request):
latest_airburst_list = Airbu... | return JsonResponse(response)
| sponse[airburst.id] = {'radiated_energy': airburst.radiated_energy,
'impact_energy': airburst.impact_energy,
'latitude': airburst.latitude,
'longitude': airburst.longitude,
'date': airburst.date.isoformat(),
'altitude': airburst.altitude,
}
| conditional_block |
views.py | #-*-*- encoding: utf-8 -*-*-
from django.shortcuts import render
from django.template import RequestContext, loader, Context
from django.http import JsonResponse
from .models import Airburst
def | (request):
return render(request, 'NextGenThreat/index.html', {})
def radar(request):
latest_airburst_list = Airburst.objects.all()
context = {'latest_airburst_list': latest_airburst_list}
return render(request, 'NextGenThreat/radar.html', context)
def credits(request):
context = {'contributors': [
{'name': '... | index | identifier_name |
views.py | #-*-*- encoding: utf-8 -*-*-
|
def index(request):
return render(request, 'NextGenThreat/index.html', {})
def radar(request):
latest_airburst_list = Airburst.objects.all()
context = {'latest_airburst_list': latest_airburst_list}
return render(request, 'NextGenThreat/radar.html', context)
def credits(request):
context = {'contributors': [
... | from django.shortcuts import render
from django.template import RequestContext, loader, Context
from django.http import JsonResponse
from .models import Airburst | random_line_split |
test_tag_show.py | import pytest
from cli_config.tag import tag
from utility.nix_error import NixError
def test_tag_show_no_tag(capsys):
with pytest.raises(SystemExit) as _excinfo:
tag.tag("nixconfig", ["show"])
_out, _err = capsys.readouterr()
assert "2" in str(_excinfo.value), "Exception doesn't contain expecte... | tag.tag("nixconfig", ["show", "badtag"])
_out, _err = capsys.readouterr()
assert "Unknown tag: badtag" in str(_excinfo.value)
assert len(_out) == 0, "StdOut should be empty, contains: {}".format(_out)
assert len(_err) is 0, "StdErr should be empty, contains: {}".format(_err)
def test_tag_sho... |
def test_tag_show_invalid_tag(capsys):
with pytest.raises(NixError) as _excinfo: | random_line_split |
test_tag_show.py | import pytest
from cli_config.tag import tag
from utility.nix_error import NixError
def test_tag_show_no_tag(capsys):
with pytest.raises(SystemExit) as _excinfo:
tag.tag("nixconfig", ["show"])
_out, _err = capsys.readouterr()
assert "2" in str(_excinfo.value), "Exception doesn't contain expecte... | (capsys):
tag.tag("nixconfig", ["show", "tag1"])
_out, _err = capsys.readouterr()
assert "script1" in _out, "'script1' should be in output"
assert "script2" in _out, "'script2' should be in output"
assert "script3" not in _out, "'script2' should be in output"
assert len(_err) is 0, "StdErr shou... | test_tag_show_good_tag | identifier_name |
test_tag_show.py | import pytest
from cli_config.tag import tag
from utility.nix_error import NixError
def test_tag_show_no_tag(capsys):
with pytest.raises(SystemExit) as _excinfo:
tag.tag("nixconfig", ["show"])
_out, _err = capsys.readouterr()
assert "2" in str(_excinfo.value), "Exception doesn't contain expecte... |
def test_tag_show_good_tag(capsys):
tag.tag("nixconfig", ["show", "tag1"])
_out, _err = capsys.readouterr()
assert "script1" in _out, "'script1' should be in output"
assert "script2" in _out, "'script2' should be in output"
assert "script3" not in _out, "'script2' should be in output"
assert... | with pytest.raises(NixError) as _excinfo:
tag.tag("nixconfig", ["show", "badtag"])
_out, _err = capsys.readouterr()
assert "Unknown tag: badtag" in str(_excinfo.value)
assert len(_out) == 0, "StdOut should be empty, contains: {}".format(_out)
assert len(_err) is 0, "StdErr should be empty, con... | identifier_body |
cpu.rs | extern crate rand;
use self::rand::ThreadRng;
use self::rand::Rng;
pub struct Cpu {
pub registers: Reg,
rng: ThreadRng,
}
impl Cpu {
pub fn init() -> Self {
Cpu {
registers: Reg::default(),
rng: rand::thread_rng(),
}
}
/// Generates a random byte
pub f... | ,
0x3 => {self.v3 = value},
0x4 => {self.v4 = value},
0x5 => {self.v5 = value},
0x6 => {self.v6 = value},
0x7 => {self.v7 = value},
0x8 => {self.v8 = value},
0x9 => {self.v9 = value},
0xa => {self.va = value},
... | {self.v2 = value} | conditional_block |
cpu.rs | extern crate rand;
use self::rand::ThreadRng;
use self::rand::Rng;
pub struct Cpu {
pub registers: Reg,
rng: ThreadRng,
} |
pub fn init() -> Self {
Cpu {
registers: Reg::default(),
rng: rand::thread_rng(),
}
}
/// Generates a random byte
pub fn random_byte(&mut self) -> u8 {
self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX)
}
}
#[derive(Default)]
pub struct Reg {
pub... |
impl Cpu { | random_line_split |
cpu.rs | extern crate rand;
use self::rand::ThreadRng;
use self::rand::Rng;
pub struct | {
pub registers: Reg,
rng: ThreadRng,
}
impl Cpu {
pub fn init() -> Self {
Cpu {
registers: Reg::default(),
rng: rand::thread_rng(),
}
}
/// Generates a random byte
pub fn random_byte(&mut self) -> u8 {
self.rng.gen_range(::std::u8::MIN, ::std::... | Cpu | identifier_name |
cpu.rs | extern crate rand;
use self::rand::ThreadRng;
use self::rand::Rng;
pub struct Cpu {
pub registers: Reg,
rng: ThreadRng,
}
impl Cpu {
pub fn init() -> Self {
Cpu {
registers: Reg::default(),
rng: rand::thread_rng(),
}
}
/// Generates a random byte
pub f... |
}
#[derive(Default)]
pub struct Reg {
pub v0: u8, pub v1: u8, pub v2: u8, pub v3: u8,
pub v4: u8, pub v5: u8, pub v6: u8, pub v7: u8,
pub v8: u8, pub v9: u8, pub va: u8, pub vb: u8,
pub vc: u8, pub vd: u8, pub ve: u8, pub vf: u8,
pub i: u16, pub pc: u16, pub sp: u8,
}
impl Reg {
#[inline]
... | {
self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX)
} | identifier_body |
simple.js | "use strict";
var config = require('../config');
var routermgr = require('../lib/routermgr');
//<--require Begin
//<--require End
const URLROOT = '{{currouter.urlroot}}';
const URL = {{{currouter.urlstr}}};
const HTTPTYPE = routermgr.HTTP_{{currouter.http}};
const NEEDLOGIN = {{currouter.needlogin}};
class Router_{... |
onProc(req, res, next) {
super.onProc(req, res, function () {
//<--onProc Begin
res.resret.renderJade('views/{{currouter.name_lc}}/{{currouter.name_lc}}.jade');
res.resret.param = {};
res.resret.render(res);
//<--onProc End
});
}
};
routermgr.singleton.addR... | {
super(HTTPTYPE, URLROOT, URL, NEEDLOGIN);
} | identifier_body |
simple.js | "use strict";
var config = require('../config');
var routermgr = require('../lib/routermgr');
//<--require Begin
//<--require End
const URLROOT = '{{currouter.urlroot}}';
const URL = {{{currouter.urlstr}}};
const HTTPTYPE = routermgr.HTTP_{{currouter.http}}; | constructor() {
super(HTTPTYPE, URLROOT, URL, NEEDLOGIN);
}
onProc(req, res, next) {
super.onProc(req, res, function () {
//<--onProc Begin
res.resret.renderJade('views/{{currouter.name_lc}}/{{currouter.name_lc}}.jade');
res.resret.param = {};
res.resret.... | const NEEDLOGIN = {{currouter.needlogin}};
class Router_{{currouter.name}} extends routermgr.Router{ | random_line_split |
simple.js | "use strict";
var config = require('../config');
var routermgr = require('../lib/routermgr');
//<--require Begin
//<--require End
const URLROOT = '{{currouter.urlroot}}';
const URL = {{{currouter.urlstr}}};
const HTTPTYPE = routermgr.HTTP_{{currouter.http}};
const NEEDLOGIN = {{currouter.needlogin}};
class Router_{... | () {
super(HTTPTYPE, URLROOT, URL, NEEDLOGIN);
}
onProc(req, res, next) {
super.onProc(req, res, function () {
//<--onProc Begin
res.resret.renderJade('views/{{currouter.name_lc}}/{{currouter.name_lc}}.jade');
res.resret.param = {};
res.resret.render(res);
//... | constructor | identifier_name |
index.d.ts | // Type definitions for react-helmet 5.0
// Project: https://github.com/nfl/react-helmet
// Definitions by: Evan Bremer <https://github.com/evanbb>, Isman Usoh <https://github.com/isman-usoh>, François Nguyen <https://github.com/lith-light-g>, Kok Sam <https://github.com/sammkj>, Yui T. <https://github.com/yuit>
// Def... | extends React.Component<HelmetProps> {
static peek(): HelmetData;
static rewind(): HelmetData;
static renderStatic(): HelmetData;
static canUseDOM: boolean;
}
export interface HelmetData {
base: HelmetDatum;
bodyAttributes: HelmetHTMLBodyDatum;
htmlAttributes: HelmetHTMLElementDatum;
li... | elmet | identifier_name |
index.d.ts | // Type definitions for react-helmet 5.0
// Project: https://github.com/nfl/react-helmet
// Definitions by: Evan Bremer <https://github.com/evanbb>, Isman Usoh <https://github.com/isman-usoh>, François Nguyen <https://github.com/lith-light-g>, Kok Sam <https://github.com/sammkj>, Yui T. <https://github.com/yuit>
// Def... | export interface HelmetDatum {
toString(): string;
toComponent(): React.Component<any>;
}
export interface HelmetHTMLBodyDatum {
toString(): string;
toComponent(): React.HTMLAttributes<HTMLBodyElement>;
}
export interface HelmetHTMLElementDatum {
toString(): string;
toComponent(): React.HTMLAt... | random_line_split | |
kendo.culture.mn.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ ret... | M: "MMMM d.",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "yyyy 'оны' MMMM",
Y: "yyyy 'оны' MMMM"
... | D: "yyyy 'оны' M'-р сарын' d. dddd 'гариг'.",
F: "yyyy 'оны' M'-р сарын' d. dddd 'гариг'. HH:mm:ss",
g: "yyyy-MM-dd HH:mm",
G: "yyyy-MM-dd HH:mm:ss",
m: "MMMM d.", | random_line_split |
kendo.culture.mn.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) | /******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
... | {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ ... | identifier_body |
kendo.culture.mn.js | module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function | (moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId... | __webpack_require__ | identifier_name |
access_control_firerole.py |
def compile_role_definition(firerole_def_src):
""" Given a text in which every row contains a rule it returns the compiled
object definition.
Rules have the following syntax:
allow|deny [not] field {list of one or more (double)quoted string or regexp}
or allow|deny any
Every row may contain a #... | from invenio.access_control_config import CFG_ACC_EMPTY_ROLE_DEFINITION_SRC, \
CFG_ACC_EMPTY_ROLE_DEFINITION_SER, CFG_ACC_EMPTY_ROLE_DEFINITION_OBJ
# INTERFACE | random_line_split | |
access_control_firerole.py | .
Rules have the following syntax:
allow|deny [not] field {list of one or more (double)quoted string or regexp}
or allow|deny any
Every row may contain a # sign followed by a comment which are discarded.
Field could be any key contained in a user_info dictionary. If the key does
not exist in the... |
def store_role_definition(role_id, firerole_def_ser, firerole_def_src):
""" Store a compiled serialized definition and its source in the database
alongside the role to which it belong.
@param role_id: the role_id
@param firerole_def_ser: the serialized compiled definition
@param firerole_def_src: ... | """ Try to rebuild compiled serialized definitions from their respectives
sources. This is needed in case Python break back compatibility.
"""
definitions = run_sql("SELECT id, firerole_def_src FROM accROLE")
for role_id, firerole_def_src in definitions:
run_sql("UPDATE accROLE SET firerole_def_... | identifier_body |
access_control_firerole.py | ioWebAccessFireroleError("Syntax error while compiling rule %s (line %s): %s is not a valid date with format YYYY-MM-DD because %s!" % (row, line, expr, msg))
elif expr[0] == '/':
try:
expressions_list.append((True, re.compile(expr[1:-1], re.I)))
... | deserialize | identifier_name | |
access_control_firerole.py | .sub('', row)
if clean_row:
g = _any_rule_re.match(clean_row)
if g:
default_allow_p = g.group('command').lower() == 'allow'
break
g = _rule_re.match(clean_row)
if g:
allow_p = g.group('command').lower() == 'allow'
... | if not_p: # If must not match
break # let's skip to next expr
else:
return allow_p # ok! | conditional_block | |
index.d.ts | // Type definitions for mysql-query-util 0.2
// Project: https://github.com/uchennaemeruche/mysql-util#readme
// Definitions by: Uchenna Emeruche <https://github.com/uchennaemeruche>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare function _delete(options: Ite... | /**
* Name of the database to use for this connection
*/
database: string;
/**
* The maximum number of connections to create at once. (Default: 10)
*/
connectionLimit?: number | undefined;
} | random_line_split | |
implicit_infer.rs | >) {}
fn visit_foreign_item(&mut self, _foreign_item: &'tcx hir::ForeignItem<'tcx>) {}
}
fn insert_required_predicates_to_be_wf<'tcx>(
tcx: TyCtxt<'tcx>,
field_ty: Ty<'tcx>,
field_span: Span,
global_inferred_outlives: &FxHashMap<DefId, RequiredPredicates<'tcx>>,
required_predicates: &mut Requi... | debug!("skipping self ty = {:?}", &ty);
continue;
}
} | random_line_split | |
implicit_infer.rs | lives,
predicates_added: &mut predicates_added,
explicit_map,
};
// Visit all the crates and infer predicates
tcx.hir().visit_all_item_likes(&mut visitor);
}
global_inferred_outlives
}
pub struct InferVisitor<'cx, 'tcx> {
tcx: TyCtxt<'tcx>,
global_infer... |
match *ty.kind() {
// The field is of type &'a T which means that we will have
// a predicate requirement of T: 'a (T outlives 'a).
//
// We also want to calculate potential predicates for the T
ty::Ref(region, rty, _) => {
debug!("Ref... | {
// We must not look into the default substs of consts
// as computing those depends on the results of `predicates_of`.
//
// Luckily the only types contained in default substs are type
// parameters which don't matter here.
//
// FIXME(adt_const_params): Once complex const parameter types
... | identifier_body |
implicit_infer.rs | lives,
predicates_added: &mut predicates_added,
explicit_map,
};
// Visit all the crates and infer predicates
tcx.hir().visit_all_item_likes(&mut visitor);
}
global_inferred_outlives
}
pub struct InferVisitor<'cx, 'tcx> {
tcx: TyCtxt<'tcx>,
global_infer... | (&mut self, _trait_item: &'tcx hir::TraitItem<'tcx>) {}
fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem<'tcx>) {}
fn visit_foreign_item(&mut self, _foreign_item: &'tcx hir::ForeignItem<'tcx>) {}
}
fn insert_required_predicates_to_be_wf<'tcx>(
tcx: TyCtxt<'tcx>,
field_ty: Ty<'tcx>,
f... | visit_trait_item | identifier_name |
test_api_ban.py | # 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 agreed to in writing, software
# distributed under the Li... | (BaseTest):
def test_ban_user_exists(self):
self.create_and_join_room()
self.set_owner()
self.create_user(BaseTest.OTHER_USER_ID, BaseTest.OTHER_USER_NAME)
json = self.activity_for_ban()
json['object']['id'] = ApiBanTest.OTHER_USER_ID
response_code, _ = api.on_ban(j... | ApiBanTest | identifier_name |
test_api_ban.py | # 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 agreed to in writing, software
# distributed under the Li... | } | random_line_split | |
test_api_ban.py | # 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 agreed to in writing, software
# distributed under the Li... |
if room_name is None:
room_name = ApiBanTest.ROOM_NAME
environ.env.storage.redis.hset(RedisKeys.rooms(BaseTest.CHANNEL_ID), room_id, room_name)
def activity_for_ban(self):
return {
'actor': {
'id': ApiBanTest.USER_ID,
'content': ApiB... | room_id = ApiBanTest.ROOM_ID | conditional_block |
test_api_ban.py | # 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 agreed to in writing, software
# distributed under the Li... | return {
'actor': {
'id': ApiBanTest.USER_ID,
'content': ApiBanTest.USER_NAME
},
'verb': 'ban',
'object': {
'content': ApiBanTest.OTHER_USER_NAME,
'objectType': 'user',
'summary': '30m',
... | identifier_body | |
LocalStorageTodoRepository.ts | import { LocalStorage, setItem } from '@motorcycle/local-storage'
import { Stream, map, skipRepeats } from 'most'
import {
Todo,
TodoRepository,
TodoRepositorySinks,
TodoRepositorySources,
} from '../../domain/model'
import { hold } from '@most/hold'
export const LocalStorageTodoRepository: TodoRepository =
... | {
const localStorage$ =
map(setItem(TODO_DB), skipRepeats(map(JSON.stringify, sinks.todos$)))
const { localStorage: { getItem } } = LocalStorage({ localStorage$ })
const todos$: Stream<ReadonlyArray<Todo>> =
hold(map(toTodos, getItem(TODO_DB)))
return { todos$ }
} | identifier_body | |
LocalStorageTodoRepository.ts | import { LocalStorage, setItem } from '@motorcycle/local-storage'
import { Stream, map, skipRepeats } from 'most'
import {
Todo,
TodoRepository,
TodoRepositorySinks,
TodoRepositorySources,
} from '../../domain/model'
import { hold } from '@most/hold'
export const LocalStorageTodoRepository: TodoRepository =
... |
const todos$: Stream<ReadonlyArray<Todo>> =
hold(map(toTodos, getItem(TODO_DB)))
return { todos$ }
} | const { localStorage: { getItem } } = LocalStorage({ localStorage$ }) | random_line_split |
LocalStorageTodoRepository.ts | import { LocalStorage, setItem } from '@motorcycle/local-storage'
import { Stream, map, skipRepeats } from 'most'
import {
Todo,
TodoRepository,
TodoRepositorySinks,
TodoRepositorySources,
} from '../../domain/model'
import { hold } from '@most/hold'
export const LocalStorageTodoRepository: TodoRepository =
... | (sinks: TodoRepositorySinks): TodoRepositorySources {
const localStorage$ =
map(setItem(TODO_DB), skipRepeats(map(JSON.stringify, sinks.todos$)))
const { localStorage: { getItem } } = LocalStorage({ localStorage$ })
const todos$: Stream<ReadonlyArray<Todo>> =
hold(map(toTodos, getItem(TODO_DB)))
retu... | LocalStorageTodoRepostioryFn | identifier_name |
Results.js | import React from 'react'
import { IndexLink, Link } from 'react-router'
import './HomeView.scss'
const styles = {};
let data = require('../assets/data.json');
class Results extends React.Component {
constructor (props) {
super(props);
this.state = {
heroImage: require(`../../../img/... | };
export default Results | random_line_split | |
Results.js | import React from 'react'
import { IndexLink, Link } from 'react-router'
import './HomeView.scss'
const styles = {};
let data = require('../assets/data.json');
class | extends React.Component {
constructor (props) {
super(props);
this.state = {
heroImage: require(`../../../img/${data.results[0].hero}`),
}
}
componentDidMount() {}
componentWillReceiveProps(nextProps) {}
render() {
return(
<div className={... | Results | identifier_name |
test_adcps_jln_stc_recovered_driver.py |
__author__ = 'Mark Worden'
from mi.core.log import get_logger
log = get_logger()
from mi.idk.config import Config
import unittest
import os
from mi.dataset.driver.adcps_jln.stc.adcps_jln_stc_recovered_driver import parse
from mi.dataset.dataset_driver import ParticleDataHandler
class SampleTest(unittest.TestCase... | test = SampleTest('test_one')
test.test_one() | conditional_block | |
test_adcps_jln_stc_recovered_driver.py | __author__ = 'Mark Worden'
from mi.core.log import get_logger
log = get_logger()
from mi.idk.config import Config
| from mi.dataset.driver.adcps_jln.stc.adcps_jln_stc_recovered_driver import parse
from mi.dataset.dataset_driver import ParticleDataHandler
class SampleTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_one(self):
sourceFilePath = os.path.join('mi'... | import unittest
import os | random_line_split |
test_adcps_jln_stc_recovered_driver.py |
__author__ = 'Mark Worden'
from mi.core.log import get_logger
log = get_logger()
from mi.idk.config import Config
import unittest
import os
from mi.dataset.driver.adcps_jln.stc.adcps_jln_stc_recovered_driver import parse
from mi.dataset.dataset_driver import ParticleDataHandler
class SampleTest(unittest.TestCase... | (self):
sourceFilePath = os.path.join('mi', 'dataset', 'driver',
'adcps_jln', 'stc', 'resource',
'adcpt_20130929_091817.DAT')
particle_data_hdlr_obj = ParticleDataHandler()
particle_data_hdlr_obj = parse(Config().base... | test_one | identifier_name |
test_adcps_jln_stc_recovered_driver.py |
__author__ = 'Mark Worden'
from mi.core.log import get_logger
log = get_logger()
from mi.idk.config import Config
import unittest
import os
from mi.dataset.driver.adcps_jln.stc.adcps_jln_stc_recovered_driver import parse
from mi.dataset.dataset_driver import ParticleDataHandler
class SampleTest(unittest.TestCase... |
def test_one(self):
sourceFilePath = os.path.join('mi', 'dataset', 'driver',
'adcps_jln', 'stc', 'resource',
'adcpt_20130929_091817.DAT')
particle_data_hdlr_obj = ParticleDataHandler()
particle_data_hdlr_obj = p... | pass | identifier_body |
version.py | # Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import __version__
from ansible.errors import AnsibleError
from distutils.version import LooseVersion
from operator import eq, ge, gt
from sys import version_info
try:
from __main__ ... | def get_vars(self, loader, path, entities, cache=True):
return {} | identifier_body | |
version.py | # Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import __version__
from ansible.errors import AnsibleError
from distutils.version import LooseVersion
from operator import eq, ge, gt
from sys import version_info
try:
from __main__ ... |
if not ge(LooseVersion(__version__), LooseVersion(version_requirement)):
raise AnsibleError(('Trellis no longer supports Ansible {}.\n'
'Please upgrade to Ansible {} or higher.').format(__version__, version_requirement))
elif gt(LooseVersion(__version__), LooseVersion(version_tested_max)):
display.war... | raise AnsibleError(('Ansible >= {} is required when using Python 3.\n'
'Either downgrade to Python 2 or update your Ansible version to {}.').format(python3_required_version, python3_required_version)) | conditional_block |
version.py | # Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import __version__
from ansible.errors import AnsibleError
from distutils.version import LooseVersion
from operator import eq, ge, gt
from sys import version_info
try:
from __main__ ... | version_requirement = '2.5.0.0'
version_tested_max = '2.7.5'
python3_required_version = '2.5.3'
if version_info[0] == 3 and not ge(LooseVersion(__version__), LooseVersion(python3_required_version)):
raise AnsibleError(('Ansible >= {} is required when using Python 3.\n'
'Either downgrade to Python 2 or upda... | random_line_split | |
version.py | # Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import __version__
from ansible.errors import AnsibleError
from distutils.version import LooseVersion
from operator import eq, ge, gt
from sys import version_info
try:
from __main__ ... | (self, loader, path, entities, cache=True):
return {}
| get_vars | identifier_name |
setup.py | import os
from setuptools import setup
import sys
if sys.version_info < (2, 6):
raise Exception('Wiggelen requires Python 2.6 or higher.')
install_requires = []
# Python 2.6 does not include the argparse module.
try:
import argparse
except ImportError:
install_requires.append('argparse')
# Python 2.6 do... | continue
if field == '__version_info__':
value = value.strip('[]()')
value = '.'.join(x.strip(' \'"') for x in value.split(','))
else:
value = value.strip('\'"')
distmeta[field] = value
setup(
name='wiggelen',
version=distmeta['__version_info__'],
description='Wo... | distmeta = {}
for line in open(os.path.join('wiggelen', '__init__.py')):
try:
field, value = (x.strip() for x in line.split('='))
except ValueError: | random_line_split |
setup.py | import os
from setuptools import setup
import sys
if sys.version_info < (2, 6):
raise Exception('Wiggelen requires Python 2.6 or higher.')
install_requires = []
# Python 2.6 does not include the argparse module.
try:
import argparse
except ImportError:
install_requires.append('argparse')
# Python 2.6 do... |
setup(
name='wiggelen',
version=distmeta['__version_info__'],
description='Working with wiggle tracks in Python',
long_description=long_description,
author=distmeta['__author__'],
author_email=distmeta['__contact__'],
url=distmeta['__homepage__'],
license='MIT License',
platforms=[... | try:
field, value = (x.strip() for x in line.split('='))
except ValueError:
continue
if field == '__version_info__':
value = value.strip('[]()')
value = '.'.join(x.strip(' \'"') for x in value.split(','))
else:
value = value.strip('\'"')
distmeta[field] = value | conditional_block |
serializers.py | """Serializers for authentication views.
"""
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class | (serializers.Serializer):
"""
Serializer for obtaining an auth token.
The actual generation of the auth token is intended to be handled by
the view that utilizes this serializer.
"""
email = serializers.EmailField(help_text="The user's email address.")
password = serializers.CharField(
... | TokenSerializer | identifier_name |
serializers.py | """Serializers for authentication views.
"""
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class TokenSerializer(serializers.Serializer):
"""
Serializer for obtaining an auth token.
The actual generation of th... | """
email = serializers.EmailField(help_text="The user's email address.")
password = serializers.CharField(
help_text="The user's password", style={"input_type": "password"}
)
def validate(self, data):
"""
Ensure that the requesting user is allowed to obtain a token.
... | the view that utilizes this serializer. | random_line_split |
serializers.py | """Serializers for authentication views.
"""
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class TokenSerializer(serializers.Serializer):
"""
Serializer for obtaining an auth token.
The actual generation of th... |
data["user"] = user
return data
| raise serializers.ValidationError(
_(
"Invalid credentials. Check your email and password and "
"try again."
)
) | conditional_block |
serializers.py | """Serializers for authentication views.
"""
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class TokenSerializer(serializers.Serializer):
"""
Serializer for obtaining an auth token.
The actual generation of th... | "try again."
)
)
data["user"] = user
return data
| """
Ensure that the requesting user is allowed to obtain a token.
Returns:
dict:
The validated data.
Raises:
ValidationError:
If the provided credentials are invalid.
ValidationError:
If the requesting user doe... | identifier_body |
ext-lang-lt.js | GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public Licen... |
Contact: http://www.sencha.com/contact
| random_line_split | |
compiletest.rs | outputs", "PATH"),
reqopt("", "aux-base", "directory to find auxiliary test files", "PATH"),
reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET"),
reqopt("", "mode", "which sort of compile tests to run",
"(compile-fail|run-fail|run-pass|pretty|debug-info... | make_tests | identifier_name | |
compiletest.rs | to host shared libraries", "PATH"),
reqopt("", "run-lib-path", "path to target shared libraries", "PATH"),
reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"),
optopt("", "clang-path", "path to executable for codegen tests", "PATH"),
optopt("", "llvm-bin-path... |
pub fn str_mode(s: ~str) -> mode {
match s {
~"compile-fail" => mode_compile_fail,
~"run-fail" => mode_run_fail,
~"run-pass" => mode_run_pass,
~"pretty" => mode_pretty,
~"debug-info" => mode_debug_info,
~"codegen" => mode_codegen,
_ => fail!("invalid mode")
}
}
pub f... | {
match maybestr { None => ~"(none)", Some(s) => { s } }
} | identifier_body |
compiletest.rs | path to host shared libraries", "PATH"),
reqopt("", "run-lib-path", "path to target shared libraries", "PATH"),
reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH"),
optopt("", "clang-path", "path to executable for codegen tests", "PATH"),
optopt("", "llvm-bin-... | mode_run_pass => ~"run-pass",
mode_pretty => ~"pretty",
mode_debug_info => ~"debug-info",
mode_codegen => ~"codegen",
}
}
pub fn run_tests(config: &config) {
if config.target == ~"arm-linux-androideabi" {
match config.mode{
mode_debug_info => {
printl... | random_line_split | |
scroll.js | /**
* Created by DaisyCream on 15/10/13.
*/
/*****************************set the element Height**********************************/
var SCROLLWHEEL = function(){};
var screenHeight = document.documentElement.clientHeight;
SCROLLWHEEL.target = document.getElementsByTagName('div');
body = document.getElementsByTagName... |
};
SCROLLWHEEL.goDown = function(){
if(SCROLLWHEEL.nowLong > -(SCROLLWHEEL.target.length - 1)){
SCROLLWHEEL.nowLong--;
}
body.style.top = SCROLLWHEEL.nowLong * screenHeight + 'px';
};
SCROLLWHEEL.goUp = function(){
if(SCROLLWHEEL.nowLong < 0){
SCROLLWHEEL.nowLong++;
}
body.sty... | {//fireFox
if(e.detail>0){
SCROLLWHEEL.goDown();
}
else{
SCROLLWHEEL.goUp();
}
} | conditional_block |
scroll.js | /**
* Created by DaisyCream on 15/10/13.
*/
/*****************************set the element Height**********************************/
var SCROLLWHEEL = function(){};
var screenHeight = document.documentElement.clientHeight;
SCROLLWHEEL.target = document.getElementsByTagName('div');
body = document.getElementsByTagName... | // else if(e.detail){
// if(e.detail>0){
// goTo();
// }
// else{
// goBack();
// }
// }
// isMoreWheel = true;
// console.log(isMoreWheel);
//};
//
//var goTo = function(){
// if(topNow>-(div.length-1)){
// topNow--;
// }
// body.style.top =... | // } | random_line_split |
Block.js | import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime"; | d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z"
}), 'Block'); | export default createSvgIcon( /*#__PURE__*/_jsx("path", { | random_line_split |
goforward.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import easyiceconfig as EasyIce
import jderobotComm as comm
import sys, signal
sys.path.append('/usr/local/share/jderobot/python/visualHFSM_py')
import traceback, threading, time
from automatagui import AutomataGui, QtGui, GuiSubautomata
from jderobot import MotorsPrx
from jd... | (self):
self.lock = threading.Lock()
self.displayGui = False
self.StatesSub1 = [
"GoForward",
"GoBack",
]
self.sub1 = "GoForward"
self.run1 = True
def calculate_obstacle(self):
self.laserData = self.KobukiLaser.getLaserData()
min_dist = 1000
for i in range(len(self.laserData.values)):
if s... | __init__ | identifier_name |
goforward.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import easyiceconfig as EasyIce
import jderobotComm as comm
import sys, signal
sys.path.append('/usr/local/share/jderobot/python/visualHFSM_py')
import traceback, threading, time
from automatagui import AutomataGui, QtGui, GuiSubautomata
from jderobot import MotorsPrx
from jd... |
# Actuation if
if(self.sub1 == "GoForward"):
self.KobukiMotors.sendV(0.5)
self.KobukiMotors.sendW(0.0)
elif(self.sub1 == "GoBack"):
self.KobukiMotors.sendV(-0.3)
self.KobukiMotors.sendW(0.2)
totalb = time.time() * 1000000
msecs = (totalb - totala) / 1000;
if(msecs < 0 or msecs > cy... | if(not self.calculate_obstacle()):
self.sub1 = "GoForward"
if self.displayGui:
self.automataGui.notifySetNodeAsActive('GoForward') | conditional_block |
goforward.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import easyiceconfig as EasyIce
import jderobotComm as comm
import sys, signal
sys.path.append('/usr/local/share/jderobot/python/visualHFSM_py')
import traceback, threading, time
from automatagui import AutomataGui, QtGui, GuiSubautomata
from jderobot import MotorsPrx
from jd... |
def readArgs(self):
for arg in sys.argv:
splitedArg = arg.split('=')
if splitedArg[0] == '--displaygui':
if splitedArg[1] == 'True' or splitedArg[1] == 'true':
self.displayGui = True
print('runtime gui enabled')
else:
self.displayGui = False
print('runtime gui disabled')
if __n... | if self.displayGui:
self.guiThread.join()
self.t1.join() | identifier_body |
goforward.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import easyiceconfig as EasyIce
import jderobotComm as comm
import sys, signal
sys.path.append('/usr/local/share/jderobot/python/visualHFSM_py')
import traceback, threading, time | from jderobot import LaserPrx
class Automata():
def __init__(self):
self.lock = threading.Lock()
self.displayGui = False
self.StatesSub1 = [
"GoForward",
"GoBack",
]
self.sub1 = "GoForward"
self.run1 = True
def calculate_obstacle(self):
self.laserData = self.KobukiLaser.getLaserData()
min_di... | from automatagui import AutomataGui, QtGui, GuiSubautomata
from jderobot import MotorsPrx | random_line_split |
profile_detail_view_test.py | import json
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import force_authenticate
from rest_framework import status
from rest_framework.authtoken.models import Token
from core.models import Profile, User
from api.views import ProfileDetail
from api.se... |
def test_delete_profile(self):
"""Test delete profile"""
request = self.factory.delete('/core/api/profile/',
content_type='application/json')
force_authenticate(request, user=self.admin_user, token=self.admin_user.auth_token)
response = self.vi... | """Test update profile data"""
new_email = 'just@some.test'
data = json.dumps({'user': {'email': new_email}})
request = self.factory.patch('/core/api/profile/',
data=data,
content_type='application/json')
force_au... | identifier_body |
profile_detail_view_test.py | import json
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import force_authenticate
from rest_framework import status
from rest_framework.authtoken.models import Token
from core.models import Profile, User
from api.views import ProfileDetail
from api.se... | self.assertFalse(Profile.objects.filter(pk=self.test_profile.id).exists()) | self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) | random_line_split |
profile_detail_view_test.py | import json
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import force_authenticate
from rest_framework import status
from rest_framework.authtoken.models import Token
from core.models import Profile, User
from api.views import ProfileDetail
from api.se... |
user = User.objects.create(username='testuser1', email='test@user1.com', password='sometestpass')
self.test_profile = Profile.objects.create(user=user)
self.factory = APIRequestFactory()
self.view = ProfileDetail.as_view()
def test_dont_get_profile_data_without_authorization(sel... | self.admin_user = User.objects.create_superuser(username='testadmin', password='123', email='')
Token.objects.create(user=self.admin_user) | conditional_block |
profile_detail_view_test.py | import json
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import force_authenticate
from rest_framework import status
from rest_framework.authtoken.models import Token
from core.models import Profile, User
from api.views import ProfileDetail
from api.se... | (self):
"""Test dont get profile data without authorization"""
request = self.factory.get('/core/api/profile/')
response = self.view(request, pk=self.test_profile.id)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_get_profile_data(self):
"""Te... | test_dont_get_profile_data_without_authorization | identifier_name |
diffWithRevisionFrom.ts | import { TextDocumentShowOptions, TextEditor, Uri } from 'vscode';
import { Commands, GlyphChars, quickPickTitleMaxChars } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitReference, GitRevision } from '../git/models';
import { Messages } from '../m... | extends ActiveEditorCommand {
constructor(private readonly container: Container) {
super(Commands.DiffWithRevisionFrom);
}
async execute(editor?: TextEditor, uri?: Uri, args?: DiffWithRevisionFromCommandArgs) {
uri = getCommandUri(uri, editor);
if (uri == null) return;
const gitUri = await GitUri.fromUri(... | DiffWithRevisionFromCommand | identifier_name |
diffWithRevisionFrom.ts | import { TextDocumentShowOptions, TextEditor, Uri } from 'vscode';
import { Commands, GlyphChars, quickPickTitleMaxChars } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitReference, GitRevision } from '../git/models';
import { Messages } from '../m... | if (args?.stash) {
const title = `Open Changes with Stash${pad(GlyphChars.Dot, 2, 2)}`;
const pick = await StashPicker.show(
this.container.git.getStash(gitUri.repoPath),
`${title}${gitUri.getFormattedFileName({ truncateTo: quickPickTitleMaxChars - title.length })}`,
'Choose a stash to compare with'... | {
uri = getCommandUri(uri, editor);
if (uri == null) return;
const gitUri = await GitUri.fromUri(uri);
if (!gitUri.repoPath) {
void Messages.showNoRepositoryWarningMessage('Unable to open file compare');
return;
}
args = { ...args };
if (args.line == null) {
args.line = editor?.selection.activ... | identifier_body |
diffWithRevisionFrom.ts | import { TextDocumentShowOptions, TextEditor, Uri } from 'vscode';
import { Commands, GlyphChars, quickPickTitleMaxChars } from '../constants';
import type { Container } from '../container';
import { GitUri } from '../git/gitUri';
import { GitReference, GitRevision } from '../git/models';
import { Messages } from '../m... | renamedTitle = `${basename(rename.originalPath)} (${GitRevision.shorten(ref)})`;
}
}
void (await executeCommand<DiffWithCommandArgs>(Commands.DiffWith, {
repoPath: gitUri.repoPath,
lhs: {
sha: sha,
uri: renamedUri ?? gitUri,
title: renamedTitle ?? `${basename(gitUri.fsPath)} (${GitRevision... | const files = await this.container.git.getDiffStatus(gitUri.repoPath, 'HEAD', ref, { filters: ['R', 'C'] });
if (files != null) {
const rename = files.find(s => s.path === path);
if (rename?.originalPath != null) {
renamedUri = this.container.git.getAbsoluteUri(rename.originalPath, gitUri.repoPath); | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration): | ]
operations = [
migrations.CreateModel(
name='Billing',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
],
),
migrations.CreateModel(
name='Plan',
fie... |
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('trans', '0045_auto_20150916_1007'), | random_line_split |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('trans', '0045_auto_20150916_1007'),
]
operations = [
migrations.CreateModel(
name='Billing',
fields=[
('id', models.AutoField(verbose_name='... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
| ('limit_repositories', models.IntegerField()),
('limit_projects', models.IntegerField()),
],
options={
'ordering': ['name'],
},
),
migrations.AddField(
model_name='billing',
name='plan',
... | dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('trans', '0045_auto_20150916_1007'),
]
operations = [
migrations.CreateModel(
name='Billing',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_cr... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.