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 |
|---|---|---|---|---|
mod.rs | //! # database
//! This module holds necessary structs and functions to accomplish database tasks.
mod read;
mod insert;
mod update;
mod delete;
pub mod query_api;
pub mod errors;
use serde_json;
use slog::Logger;
use configuration;
use weld::ROOT_LOGGER;
use std::vec::Vec;
use std::fs::File;
use std::io::Read;
use ... | (val: &String) -> i64 {
match i64::from_str_radix(val.as_str(), 10) {
Ok(parsed) => parsed,
Err(_) => -1,
}
}
/// This is the main access function to reach the desired data from the whole database.
/// Tries to find the keys provided in the database recursively.
... | decide_id | identifier_name |
mod.rs | //! # database
//! This module holds necessary structs and functions to accomplish database tasks.
mod read;
mod insert;
mod update;
mod delete;
pub mod query_api;
pub mod errors;
use serde_json;
use slog::Logger;
use configuration;
use weld::ROOT_LOGGER;
use std::vec::Vec;
use std::fs::File;
use std::io::Read;
use ... |
/// This is the main access function to reach the desired data from the whole database.
/// Tries to find the keys provided in the database recursively.
/// Returns mutable references to allow manipulation.
pub fn get_object<'per_req>(
keys: &mut Vec<String>,
json_object: &'per_req mut... | {
match i64::from_str_radix(val.as_str(), 10) {
Ok(parsed) => parsed,
Err(_) => -1,
}
} | identifier_body |
mod.rs | //! # database
//! This module holds necessary structs and functions to accomplish database tasks.
mod read; | mod insert;
mod update;
mod delete;
pub mod query_api;
pub mod errors;
use serde_json;
use slog::Logger;
use configuration;
use weld::ROOT_LOGGER;
use std::vec::Vec;
use std::fs::File;
use std::io::Read;
use std::io::Write;
use std::fs::OpenOptions;
use serde_json::Value;
use serde_json::Value::{Array, Object};
use s... | random_line_split | |
proxy.py | } and d={3}
AND fulluri = '{4}'
""").format(db,date.year,date.month,date.day,uri)
connections = ImpalaEngine.execute_query(p_query)
# add score to connections
insert_command = ("""
INSERT INTO {0}.proxy_threat_investigation PARTITION (y={1},m={2},d={3})
VALUES (""") \
.format(db,date.y... | if item["p_threat"] == uri:
item["title"] = title
item["text"] = text
saved = True | conditional_block | |
proxy.py | \
"network_context","hash"])
ap_file = False
HDFSClient.put_file_csv(fb_data,feedback_path,"ml_feedback.csv",append_file=ap_file)
return True
"""
--------------------------------------------------------------------------
Get expanded search from raw table.
-------------------------------------... | app_path = Configuration.spot()
hdfs_path = "{0}/proxy/oa/storyboard/{1}/{2}/{3}".format(app_path,\
date.year,date.month,date.day)
hash_name = md5.new(str(uri)).hexdigest()
file_name = "incident-progression-{0}.json".format(hash_name)
if HDFSClient.file_exists(hdfs_path,file_name):
ret... | identifier_body | |
proxy.py | fb_data.append([row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7] \
,row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15] \
,row[16],row[17],row[18],row[19],score,row[20],row[21],row[22], \
row[23],hash_field])
insert_command += "{0}{1}".format("," if not first else "", threat_da... | story_board | identifier_name | |
proxy.py | list(dict) of all the connectios details for one request.
--------------------------------------------------------------------------
"""
def details(date,uri,ip):
if not uri and not ip:
return None
db = Configuration.db()
p_details = ("""
SELECT
tdate,time,clientIp,host,webcat,respcode,re... | def score_request(date,score,uri):
if not score and not uri:
return None
db = Configuration.db()
p_query = ("""
SELECT
tdate,time,clientip,host,reqmethod,useragent,resconttype
,duration,username,webcat,referer,respcode,uriport
,uripath,uriquery,serverip,scbytes,csbytes,fulluri
,... | """ | random_line_split |
page-widget-chart.js | Array([])
crt.fiscalYear = ko.observable(rpt.value.FiscalYear())
crt.modecustom = ko.observable(false)
crt.dataplmodel = ko.observableArray([])
crt.valueplmodel = ko.observableArray(["PL8A", "PL94C"])
crt.convertCurrency = (labelValue) => {
let res = Math.abs(Number(labelValue)) >= 1.0e+9 ? Math.abs(Number(labelValu... |
return config
}
crt.render = () => {
let data = _.sortBy(crt.data(), (d) => toolkit.redefine(d[toolkit.replace(crt.categoryAxisField(), '.', '_')], ''))
crt.data(data)
let series = ko.mapping.toJS(crt.series)
.filter((d) => (d.field != ''))
.map((d) => {
if (app.isUndefined(d.name)) {
d.name = d.fi... | {
delete config.valueAxis.max
} | conditional_block |
page-widget-chart.js | Array([]) | crt.valueplmodel = ko.observableArray(["PL8A", "PL94C"])
crt.convertCurrency = (labelValue) => {
let res = Math.abs(Number(labelValue)) >= 1.0e+9 ? Math.abs(Number(labelValue)) / 1.0e+9 + " B"
: Math.abs(Number(labelValue)) >= 1.0e+6 ? Math.abs(Number(labelValue)) / 1.0e+6 + " M"
: Math.abs(Number(labelValue)) >... | crt.fiscalYear = ko.observable(rpt.value.FiscalYear())
crt.modecustom = ko.observable(false)
crt.dataplmodel = ko.observableArray([]) | random_line_split |
msnodesql.d.ts | // Type definitions for msnodesql 0.2
// Project: https://github.com/WindowsAzure/node-sqlserver
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path='../node/node.d.ts' />
declare module "msnodesql" {
export ... | close(immediately: boolean, callback?: ErrorCallback);
}
interface StreamEvents extends EventEmitter { }
} | close(callback?: ErrorCallback);
| random_line_split |
index.d.ts | // Type definitions for swagger-express-mw 0.7
// Project: https://github.com/apigee-127/swagger-express#readme
// Definitions by: Michael Mrowetz <https://github.com/micmro/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
/* =================== USAGE ===================
... | appRoot: __dirname
};
SwaggerExpress.create(config, (err, middleware) => {
if (err) {
throw err; // or handle error
}
middleware.register(app);
const port = process.env.PORT || 10010;
app.listen(port);
});
=============================================== */
import { Config, ConnectMi... | import * as express from "express";
let app = express();
let config: SwaggerExpress.Config = { | random_line_split |
htmlfontelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::b... | (local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLFontElement {
HTMLFontElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Pre... | new_inherited | identifier_name |
htmlfontelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::b... |
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<HTMLFontElement> {
Node::reflect_node(Box::new(HTMLFontElement::new_inherited(local_name, prefix, document)),
document,
... | {
HTMLFontElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
} | identifier_body |
htmlfontelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::b... | match size {
Some(&AttrValue::UInt(_, s)) => Some(s),
_ => None,
}
}
}
/// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size>
fn parse_size(mut input: &str) -> AttrValue {
let original_input = input;
// Steps 1 & 2 are not relevant
//... | }; | random_line_split |
SignupForm.1.js | import React from 'react';
import { PropTypes } from 'prop-types';
import timezones from '../../data/timezones';
import map from 'lodash/map';
import classnames from 'classnames';
import validateInput from '../../validations/signup';
import TextFieldGroup from '../Form/TextFieldGroup';
import signUp from '../../utils/s... | else {
errors[field] = '';
invalid = false;
}
this.setState({ errors, invalid });
});
}
}
onSubmit(e) {
e.preventDefault();
if (this.isValid()) {
this.setState({ errors: {}, isLoading: true });
// console.log("Here is this.props.userSignupRequest:... | {
errors[field] = 'There is user with such ' + field;
invalid = true;
} | conditional_block |
SignupForm.1.js | import React from 'react';
import { PropTypes } from 'prop-types';
import timezones from '../../data/timezones';
import map from 'lodash/map';
import classnames from 'classnames';
import validateInput from '../../validations/signup';
import TextFieldGroup from '../Form/TextFieldGroup';
import signUp from '../../utils/s... |
onSubmit(e) {
e.preventDefault();
if (this.isValid()) {
this.setState({ errors: {}, isLoading: true });
// console.log("Here is this.props.userSignupRequest:");
// console.log(this.props.userSignupRequest);
// console.log(this.state);
// this.props.userSignupRequest(this.state... | {
const field = e.target.name;
const val = e.target.value;
if (val !== '') {
// this.props.isUserExists(val).then(res => {
signUp.isUserExists(val).then(res => {
let errors = this.state.errors;
let invalid;
if (res.data.user) {
errors[field] = 'There is user wit... | identifier_body |
SignupForm.1.js | import React from 'react';
import { PropTypes } from 'prop-types';
import timezones from '../../data/timezones';
import map from 'lodash/map';
import classnames from 'classnames';
import validateInput from '../../validations/signup';
import TextFieldGroup from '../Form/TextFieldGroup';
import signUp from '../../utils/s... | (props) {
super(props);
this.state = {
username: '',
email: '',
password: '',
passwordConfirmation: '',
timezone: '',
errors: {},
isLoading: false,
invalid: false
}
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
... | constructor | identifier_name |
SignupForm.1.js | import React from 'react';
import { PropTypes } from 'prop-types';
import timezones from '../../data/timezones';
import map from 'lodash/map';
import classnames from 'classnames';
import validateInput from '../../validations/signup';
import TextFieldGroup from '../Form/TextFieldGroup';
import signUp from '../../utils/s... | this.context.router.history.push('/');
},
(err) => this.setState({ errors: err.response.data, isLoading: false })
);
}
}
render() {
const { errors } = this.state;
const options = map(timezones, (val, key) =>
<option key={val} value={val}>{key}</option>
);
r... | // this.props.addFlashMessage({
flashM.addFlashMessage({
type: 'success',
text: 'You signed up successfully. Welcome!'
}); | random_line_split |
scheduler.py | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of pyspades.
# pyspades is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... |
self.calls = WeakSet()
self.loops = WeakSet() | if loop.running:
loop.stop() | conditional_block |
scheduler.py | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of pyspades.
# pyspades is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... | (self, *arg, **kw):
call = reactor.callLater(*arg, **kw)
self.calls.add(call)
return call
def call_end(self, *arg, **kw):
call = self.protocol.call_end(*arg, **kw)
self.calls.add(call)
return call
def loop_call(self, delay, func, *arg, **kw):
... | call_later | identifier_name |
scheduler.py | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of pyspades.
# pyspades is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... | def __init__(self, protocol):
self.protocol = protocol
self.calls = WeakSet()
self.loops = WeakSet()
def call_later(self, *arg, **kw):
call = reactor.callLater(*arg, **kw)
self.calls.add(call)
return call
def call_end(self, *arg, **kw):
... | random_line_split | |
scheduler.py | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of pyspades.
# pyspades is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versi... |
def __len__(self):
return len(self._dict)
class Scheduler(object):
def __init__(self, protocol):
self.protocol = protocol
self.calls = WeakSet()
self.loops = WeakSet()
def call_later(self, *arg, **kw):
call = reactor.callLater(*arg, **kw)
... | return other in self._dict | identifier_body |
aggregations.ts | import { Aggregation } from "v2/Components/ArtworkFilter/ArtworkFilterContext"
export const artistAggregation: Aggregation = {
slice: "ARTIST",
counts: [
{
count: 483,
name: "Massimo Listri",
value: "massimo-listri",
},
],
}
export const partnerAggregation: Aggregation = {
slice: "PA... | ],
}
export const materialsTermsAggregation: Aggregation = {
slice: "MATERIALS_TERMS",
counts: [
{
name: "Canvas",
value: "canvas",
count: 17,
},
],
}
export const artistNationalityAggregation: Aggregation = {
slice: "ARTIST_NATIONALITY",
counts: [
{
name: "American",
... | value: "painting",
count: 472023,
}, | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (CMakePackage):
"""C++ utility collection. Provides various facilities of common use in
modern codebases like dynamic linking helpers, loadable plugins facilities
and misc patterns."""
homepage = "https://github.com/alalazo/modern_wheel"
url = "https://github.com/alalazo/modern_wheel/archive/1... | ModernWheel | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | # This issue will be probably fixed in CMake >= 3.11.0:
# https://gitlab.kitware.com/cmake/cmake/issues/17575
# Until then, just assume that we cannot correctly configure
# ModernWheel with Boost >= 1.66.0.
depends_on('boost +system +filesystem', when='@:1.1.999')
depends_on('boost@:1.... | """C++ utility collection. Provides various facilities of common use in
modern codebases like dynamic linking helpers, loadable plugins facilities
and misc patterns."""
homepage = "https://github.com/alalazo/modern_wheel"
url = "https://github.com/alalazo/modern_wheel/archive/1.2.tar.gz"
vers... | identifier_body |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
version('1.2', 'dc440099c52b6af3b8ddff6fd7730aff')
version('1.1', '289455239ad19497b7db55aacb299ca8')
version('1.0', '503dc3e7da2b422c4295e4afcba09dfb')
variant('shared', default=True,
description='Enables the build of shared libraries')
# Test implementation files cause some issues on... | homepage = "https://github.com/alalazo/modern_wheel"
url = "https://github.com/alalazo/modern_wheel/archive/1.2.tar.gz" | random_line_split |
test_io.py | # encoding: utf-8
"""Tests for io.py"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import io as stdlib_io
import os.path
import stat
import sys
from io import StringIO
from subprocess import Popen, PIPE
import unittest
import nose.tools as nt
from IPython.... |
def test_capture_output():
"""capture_output() context works"""
with capture_output() as io:
print('hi, stdout')
print('hi, stderr', file=sys.stderr)
nt.assert_equal(io.stdout, 'hi, stdout\n')
nt.assert_equal(io.stderr, 'hi, stderr\n')
| """IOStream initializes from a file-like object missing attributes. """
# Cause a failure from getattr and dir(). (Issue #6386)
class BadStringIO(StringIO):
def __dir__(self):
attrs = super(StringIO, self).__dir__()
attrs.append('name')
return attrs
iostream = IO... | identifier_body |
test_io.py | # encoding: utf-8
"""Tests for io.py"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import io as stdlib_io
import os.path
import stat
import sys
from io import StringIO
from subprocess import Popen, PIPE
import unittest
import nose.tools as nt
from IPython.... | (unittest.TestCase):
def tchan(self, channel, check='close'):
trap = StringIO()
chan = StringIO()
text = 'Hello'
std_ori = getattr(sys, channel)
setattr(sys, channel, trap)
tee = Tee(chan, channel=channel)
print(text, end='', file=chan)
seta... | TeeTestCase | identifier_name |
test_io.py | # encoding: utf-8
"""Tests for io.py"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import io as stdlib_io
import os.path
import stat
import sys
from io import StringIO
from subprocess import Popen, PIPE
import unittest
import nose.tools as nt
from IPython.... |
def test_IOStream_init():
"""IOStream initializes from a file-like object missing attributes. """
# Cause a failure from getattr and dir(). (Issue #6386)
class BadStringIO(StringIO):
def __dir__(self):
attrs = super(StringIO, self).__dir__()
attrs.append('name')
... | cmd = doctest_refactor_print("from IPython.utils import io;print io.%s.__class__"%name)
p = Popen([sys.executable, '-c', cmd],
stdout=PIPE)
p.wait()
classname = p.stdout.read().strip().decode('ascii')
# __class__ is a reference to the class object in Python 3, so we c... | conditional_block |
test_io.py | # encoding: utf-8
"""Tests for io.py"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import io as stdlib_io
import os.path
import stat
import sys
from io import StringIO
from subprocess import Popen, PIPE
import unittest
import nose.tools as nt
from IPython.... | self.tchan(chan, check)
def test_io_init():
"""Test that io.stdin/out/err exist at startup"""
for name in ('stdin', 'stdout', 'stderr'):
cmd = doctest_refactor_print("from IPython.utils import io;print io.%s.__class__"%name)
p = Popen([sys.executable, '-c', cmd],
... | random_line_split | |
ui.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified types for UI properties.
use cssparser::Parser;
use parser::{Parse, ParserContext};
use std::fmt::{... |
/// auto | <color>
pub type ColorOrAuto = Either<Color, Auto>;
/// A specified value for the `cursor` property.
pub type Cursor = generics::Cursor<CursorImage>;
/// A specified value for item of `image cursors`.
pub type CursorImage = generics::CursorImage<SpecifiedImageUrl, Number>;
impl Parse for Cursor {
///... | use values::specified::url::SpecifiedImageUrl; | random_line_split |
ui.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified types for UI properties.
use cssparser::Parser;
use parser::{Parse, ParserContext};
use std::fmt::{... |
}
| {
if input.try(|i| i.expect_ident_matching("auto")).is_ok() {
return Ok(generics::ScrollbarColor::Auto);
}
Ok(generics::ScrollbarColor::Colors {
thumb: Color::parse(context, input)?,
track: Color::parse(context, input)?,
})
} | identifier_body |
ui.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Specified types for UI properties.
use cssparser::Parser;
use parser::{Parse, ParserContext};
use std::fmt::{... | (pub bool);
impl MozForceBrokenImageIcon {
/// Return initial value of -moz-force-broken-image-icon which is false.
#[inline]
pub fn false_value() -> MozForceBrokenImageIcon {
MozForceBrokenImageIcon(false)
}
}
impl Parse for MozForceBrokenImageIcon {
fn parse<'i, 't>(
_context: &P... | MozForceBrokenImageIcon | identifier_name |
15.4.5.1.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
function | () {
return Object.defineProperty([1, 2, 3, 4], 2, {configurable: false});
}
assertEq(testLenientAndStrict('var a = arr(); a.length = 2; a',
returnsCopyOf([1, 2, 3]),
raisesException(TypeError)),
true);
// Internally, SpiderMonkey has two represen... | arr | identifier_name |
15.4.5.1.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* | * http://creativecommons.org/licenses/publicdomain/
*/
function arr() {
return Object.defineProperty([1, 2, 3, 4], 2, {configurable: false});
}
assertEq(testLenientAndStrict('var a = arr(); a.length = 2; a',
returnsCopyOf([1, 2, 3]),
raisesException(Type... | * Any copyright is dedicated to the Public Domain. | random_line_split |
15.4.5.1.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
function arr() {
return Object.defineProperty([1, 2, 3, 4], 2, {configurable: false});
}
assertEq(testLenientAndStrict('var... |
assertEq(testLenientAndStrict('var a = addx(arr()); a.length = 2; a',
returnsCopyOf(addx([1, 2, 3])),
raisesException(TypeError)),
true);
reportCompare(true, true);
| {
obj.x = 5;
return obj;
} | identifier_body |
prismjs-loader.js | /*
* modified version of https://github.com/valor-software/prismjs-loader
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 Valor Software
* Copyright (c) 2015-2016 Dmitriy Shekhovtsov<valorkin@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software an... |
const lang = Prism.languages[query.lang];
const value = Prism.highlight(content, lang);
const str = JSON.stringify(value);
return `module.exports = ${str}`;
};
module.exports.seperable = true;
| {
/* eslint-disable */
require(`prismjs/components/prism-${query.lang}.js`);
/* eslint-enable */
} | conditional_block |
prismjs-loader.js | /*
* modified version of https://github.com/valor-software/prismjs-loader
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 Valor Software
* Copyright (c) 2015-2016 Dmitriy Shekhovtsov<valorkin@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software an... | }
if (!Prism.languages[query.lang]) {
/* eslint-disable */
require(`prismjs/components/prism-${query.lang}.js`);
/* eslint-enable */
}
const lang = Prism.languages[query.lang];
const value = Prism.highlight(content, lang);
const str = JSON.stringify(value);
return `module.exports = ${str}`... | module.exports = function loader(content) {
const query = this.query;
if (!query.lang) {
throw new Error("You need to provide `lang` query parameter"); | random_line_split |
render.js | function paintSprite(ctx,x,y,sprite)
{
try
{
ctx.drawImage(sprite,x,y);
} catch(e)
{
ctx.restore();
}
}
function paintSpriteMir(ctx,x,y,sprite)
{
ctx.save();
ctx.scale(-1,1);
try{
ctx.drawImage(sprite,-x,y);
}
catch (e)
{
}
ctx.restore();
}
... | gameState="play";
}
}
function redraw()
{
ctx.drawImage(bg,0,0);
ctx.translate(300-player.x,height-256-player.y);
//Платформы
//
//ctx.fillStyle = "#abf";
for (var i = 0;i < platforms.length; i++)
{
p = platforms[i];
if (
(p.x>player.x-400)&&(p.y>player.y-300)&&
(p.x<player.x+400)&&(p.y<player.... | {
sceneCounter=0; | random_line_split |
render.js |
function paintSprite(ctx,x,y,sprite)
{
try
{
ctx.drawImage(sprite,x,y);
} catch(e)
{
ctx.restore();
}
}
function paintSpriteMir(ctx,x,y,sprite)
|
var deathSprite = true;
function preDraw()
{
if (sceneCounter<320)
{
sceneCounter++;
ctx.drawImage(imgLevel,0,0);
ctx.fillStyle="#d00";
ctx.font = "normal 32pt VT323";
ctx.fillText(lvlMsg,320-(lvlMsg.length*8),32);
}
else
{
sceneCounter=0;
gameState="play";
}
}
function redraw()
{
ctx.drawImage(bg,0,0);
ctx.transla... | {
ctx.save();
ctx.scale(-1,1);
try{
ctx.drawImage(sprite,-x,y);
}
catch (e)
{
}
ctx.restore();
} | identifier_body |
render.js |
function paintSprite(ctx,x,y,sprite)
{
try
{
ctx.drawImage(sprite,x,y);
} catch(e)
{
ctx.restore();
}
}
function paintSpriteMir(ctx,x,y,sprite)
{
ctx.save();
ctx.scale(-1,1);
try{
ctx.drawImage(sprite,-x,y);
}
catch (e)
{
}
ctx.restore();
... | ()
{
if (sceneCounter<320)
{
sceneCounter++;
ctx.drawImage(imgLevel,0,0);
ctx.fillStyle="#d00";
ctx.font = "normal 32pt VT323";
ctx.fillText(lvlMsg,320-(lvlMsg.length*8),32);
}
else
{
sceneCounter=0;
gameState="play";
}
}
function redraw()
{
ctx.drawImage(bg,0,0);
ctx.translate(300-player.x,height-256-player.y);
//Плат... | preDraw | identifier_name |
metadata-inlining.ts | import {readFileSync, writeFileSync} from 'fs';
import {basename} from 'path';
import {sync as glob} from 'glob';
import {join} from 'path';
/**
* Recurse through a parsed metadata.json file and inline all html and css.
* Note: this assumes that all html and css files have a unique name.
*/
export function inlineMe... | {
// Create a map of fileName -> fullFilePath. This is needed because the templateUrl and
// styleUrls for each component use just the filename because, in the source, the component
// and the resources live in the same directory.
const componentResources = new Map<string, string>();
glob(join(packagePath, '... | identifier_body | |
metadata-inlining.ts | import {readFileSync, writeFileSync} from 'fs';
import {basename} from 'path';
import {sync as glob} from 'glob';
import {join} from 'path';
/**
* Recurse through a parsed metadata.json file and inline all html and css.
* Note: this assumes that all html and css files have a unique name.
*/
export function | (metadata: any, componentResources: Map<string, string>) {
// Convert `templateUrl` to `template`
if (metadata.templateUrl) {
const fullResourcePath = componentResources.get(basename(metadata.templateUrl));
metadata.template = readFileSync(fullResourcePath, 'utf-8');
delete metadata.templateUrl;
}
... | inlineMetadataResources | identifier_name |
metadata-inlining.ts | import {readFileSync, writeFileSync} from 'fs';
import {basename} from 'path';
import {sync as glob} from 'glob';
import {join} from 'path';
/**
* Recurse through a parsed metadata.json file and inline all html and css. | export function inlineMetadataResources(metadata: any, componentResources: Map<string, string>) {
// Convert `templateUrl` to `template`
if (metadata.templateUrl) {
const fullResourcePath = componentResources.get(basename(metadata.templateUrl));
metadata.template = readFileSync(fullResourcePath, 'utf-8');
... | * Note: this assumes that all html and css files have a unique name.
*/ | random_line_split |
metadata-inlining.ts | import {readFileSync, writeFileSync} from 'fs';
import {basename} from 'path';
import {sync as glob} from 'glob';
import {join} from 'path';
/**
* Recurse through a parsed metadata.json file and inline all html and css.
* Note: this assumes that all html and css files have a unique name.
*/
export function inlineMe... |
}
}
}
/** Inlines HTML and CSS resources into `metadata.json` files. */
export function inlinePackageMetadataFiles(packagePath: string) {
// Create a map of fileName -> fullFilePath. This is needed because the templateUrl and
// styleUrls for each component use just the filename because, in the source, the... | {
inlineMetadataResources(metadata[property], componentResources);
} | conditional_block |
tests.bundle.ts | import 'core-js';
import 'core-js/es7/reflect';
import 'zone.js/dist/zone';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/proxy';
import 'zone.js/dist/jasmine-patch';
// Unfortunately there's n... | System.import('@angular/platform-browser-dynamic/testing')
])
// First, initialize the Angular testing environment.
.then(([testing, testingBrowser]: any) => {
testing.getTestBed().initTestEnvironment(
testingBrowser.BrowserDynamicTestingModule,
testingBrowser.platformBrowserDynamicTesting()
);
})
// Then... | __karma__.loaded = function () {};
Promise.all([
System.import('@angular/core/testing'), | random_line_split |
test.js | var vertexShader = function(attribute, uniforms){
var v = vec4.fromValues(
attribute.vertex[0],
attribute.vertex[1],
attribute.vertex[2],
1.0
);
vec4.transformMat4(v, v, uniforms.modelviewMatrix);
v[2] -= 4.0;
vec4.transformMat4(v, v, uniforms.projectionMatrix);
/* Important! Make a deep copy which the... | jsRasterPosition: new Float32Array(v) //Must write this special property which represents the vertex positions!
};
return retAttr;
};
var fragmentShader = function(varyings, uniforms){
var color = vec4.fromValues(varyings["color"][2], varyings["color"][2], varyings["color"][2], 1.0);
return color;
};
window.o... | color: new Float32Array(attribute.color), | random_line_split |
test.js | var vertexShader = function(attribute, uniforms){
var v = vec4.fromValues(
attribute.vertex[0],
attribute.vertex[1],
attribute.vertex[2],
1.0
);
vec4.transformMat4(v, v, uniforms.modelviewMatrix);
v[2] -= 4.0;
vec4.transformMat4(v, v, uniforms.projectionMatrix);
/* Important! Make a deep copy which the... |
mat4.identity(uniforms.modelviewMatrix);
mat4.rotate(uniforms.modelviewMatrix, uniforms.modelviewMatrix, Math.PI*2.0*rot, [0, 1.0, 0]);
r.clear();
r.render(data, ["vertex", "color"], uniforms, ["projectionMatrix", "modelviewMatrix"], vertexShader, fragmentShader);
r.flip();
window.requestAnimationFrame(red... | {
rot -= 1.0;
} | conditional_block |
metrics.rs | // Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
use prometheus::*;
use prometheus_static_metric::*;
make_auto_flush_static_metric! {
pub label_enum SnapType {
generate,
apply,
}
pub label_enum SnapStatus {
all,
success,
abort,
fail,
... | "tikv_raftstore_snapshot_total",
"Total number of raftstore snapshot processed.",
&["type", "status"]
)
.unwrap();
pub static ref SNAP_COUNTER: SnapCounter = auto_flush_from!(SNAP_COUNTER_VEC, SnapCounter);
pub static ref CHECK_SPILT_COUNTER_VEC: IntCounterVec = register_int_coun... | }
}
lazy_static! {
pub static ref SNAP_COUNTER_VEC: IntCounterVec = register_int_counter_vec!( | random_line_split |
plugin.py | your option)
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of th... | (item):
if item[0] == uncategorized:
return '\xff' * 10
return xl.unicode.strxfrm(item[0])
plugins_dict = sorted(plugins_dict.iteritems(), key=categorykey)
for category, plugins_list in plugins_dict:
plugins_list.sort(key=lambda x: xl.unicode.strxfrm... | categorykey | identifier_name |
plugin.py | your option)
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of th... |
self.list.set_model(None)
self.model.clear()
def categorykey(item):
if item[0] == uncategorized:
return '\xff' * 10
return xl.unicode.strxfrm(item[0])
plugins_dict = sorted(plugins_dict.iteritems(), key=categorykey)
for category, plugi... | plugins_dict[uncategorized].append(plugin_data) | conditional_block |
plugin.py | your option)
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of th... | self.message.show_error(_('Could not disable plugin!'), str(e))
return
| """
Called when the checkbox is toggled
"""
path = Gtk.TreePath.new_from_string(path)
plugin_name = self.filter_model[path][0]
if plugin_name is None:
return
enable = not self.filter_model[path][3]
if enable:
try:
self... | identifier_body |
plugin.py | your option)
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of th... | Reloads a plugin from scratch
"""
plugin_name = self.filter_model[path][0]
enabled = self.filter_model[path][3]
if enabled:
try:
self.plugins.disable_plugin(plugin_name)
except Exception as e:
self.message.show_error(_(... | random_line_split | |
neon.rs | fn get_coordinator_channel(&self) -> Option<CoordinatorChannels> {
self.coordinator_channels.as_ref().map(|x| x.1.clone())
}
#[cfg(test)]
pub fn get_blocks_processed_arc(&self) -> std::sync::Arc<std::sync::atomic::AtomicU64> {
self.blocks_processed.clone()
}
#[cfg(not(test))]
... | (&self) {}
#[cfg(test)]
fn bump_blocks_processed(&self) {
self.blocks_processed
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
#[cfg(not(test))]
fn bump_blocks_processed(&self) {}
/// Starts the testnet runloop.
///
/// This function will block by looping in... | get_microblocks_processed_arc | identifier_name |
neon.rs | fn get_coordinator_channel(&self) -> Option<CoordinatorChannels> {
self.coordinator_channels.as_ref().map(|x| x.1.clone())
}
#[cfg(test)]
pub fn get_blocks_processed_arc(&self) -> std::sync::Arc<std::sync::atomic::AtomicU64> {
self.blocks_processed.clone()
}
#[cfg(not(test))]
... | keep_running_writer.store(false, Ordering::SeqCst);
}
});
if let Err(e) = install {
// integration tests can do this
if cfg!(test) {
} else {
panic!("FATAL: error setting termination handler - {}", e);
}
... | {
let (coordinator_receivers, coordinator_senders) = self
.coordinator_channels
.take()
.expect("Run loop already started, can only start once after initialization.");
let should_keep_running = Arc::new(AtomicBool::new(true));
let keep_running_writer = should... | identifier_body |
neon.rs | fn get_coordinator_channel(&self) -> Option<CoordinatorChannels> {
self.coordinator_channels.as_ref().map(|x| x.1.clone())
}
#[cfg(test)]
pub fn get_blocks_processed_arc(&self) -> std::sync::Arc<std::sync::atomic::AtomicU64> {
self.blocks_processed.clone()
}
#[cfg(not(test))]
... | }
let utxos =
burnchain.get_utxos(&keychain.generate_op_signer().get_public_key(), 1, None, 0);
if utxos.is_none() {
if self.config.node.mock_mining {
info!("No UTXOs found, but configured to mock mine");
true
... | match burnchain.create_wallet_if_dne() {
Err(e) => warn!("Error when creating wallet: {:?}", e),
_ => {} | random_line_split |
main.rs | extern crate rand;
use rand::{SeedableRng, StdRng};
mod grasp;
mod data_parser;
mod read_file;
use read_file::{create_reader, read_data};
fn euc2d(c1: [f32; 2], c2: [f32; 2]) -> f32 {
((c1[0] - c2[0]).powi(2) + (c1[1] - c2[1]).powi(2)).sqrt()
}
fn main() {
// Read the needed data to run this program.
//
... | group, // the problem data itself (which I still
// do not fully understand what it is)
max_iters, // maximum number of iterations to do
// when searching for the best solution
... | // solving the actual problem
println!("{:?}",
grasp::search( | random_line_split |
main.rs | extern crate rand;
use rand::{SeedableRng, StdRng};
mod grasp;
mod data_parser;
mod read_file;
use read_file::{create_reader, read_data};
fn | (c1: [f32; 2], c2: [f32; 2]) -> f32 {
((c1[0] - c2[0]).powi(2) + (c1[1] - c2[1]).powi(2)).sqrt()
}
fn main() {
// Read the needed data to run this program.
//
// These functions will make sure that, if nothing is passed as an argument
// in the command line to this program, it will still try to rea... | euc2d | identifier_name |
main.rs | extern crate rand;
use rand::{SeedableRng, StdRng};
mod grasp;
mod data_parser;
mod read_file;
use read_file::{create_reader, read_data};
fn euc2d(c1: [f32; 2], c2: [f32; 2]) -> f32 |
fn main() {
// Read the needed data to run this program.
//
// These functions will make sure that, if nothing is passed as an argument
// in the command line to this program, it will still try to read the data
// from the standard input.
let mut input = create_reader();
let data = read_da... | {
((c1[0] - c2[0]).powi(2) + (c1[1] - c2[1]).powi(2)).sqrt()
} | identifier_body |
versioncheck.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]
#![allow(clippy::single_match_else)]
use rustc_tools_util::VersionInfo;
#[test]
fn | () {
// do not run this test inside the upstream rustc repo:
// https://github.com/rust-lang/rust-clippy/issues/6683
if option_env!("RUSTC_TEST_SUITE").is_some() {
return;
}
let clippy_meta = cargo_metadata::MetadataCommand::new()
.no_deps()
.exec()
.expect("could no... | check_that_clippy_lints_and_clippy_utils_have_the_same_version_as_clippy | identifier_name |
versioncheck.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]
#![allow(clippy::single_match_else)]
use rustc_tools_util::VersionInfo;
#[test]
fn check_that_clippy_lints_and_clippy_utils_have_the_same_version_as_clippy() {
// do not run this test inside the upstream rustc rep... | ,
};
}
| {
panic!("Failed to parse rustc version: {:?}", vsplit);
} | conditional_block |
versioncheck.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]
#![allow(clippy::single_match_else)]
use rustc_tools_util::VersionInfo;
#[test]
fn check_that_clippy_lints_and_clippy_utils_have_the_same_version_as_clippy() {
// do not run this test inside the upstream rustc rep... | }
}
}
#[test]
fn check_that_clippy_has_the_same_major_version_as_rustc() {
// do not run this test inside the upstream rustc repo:
// https://github.com/rust-lang/rust-clippy/issues/6683
if option_env!("RUSTC_TEST_SUITE").is_some() {
return;
}
let clippy_version = rustc_tools_u... | assert!(package.req.matches(&krate_meta.packages[0].version));
break;
} | random_line_split |
versioncheck.rs | #![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![warn(rust_2018_idioms, unused_lifetimes)]
#![allow(clippy::single_match_else)]
use rustc_tools_util::VersionInfo;
#[test]
fn check_that_clippy_lints_and_clippy_utils_have_the_same_version_as_clippy() {
// do not run this test inside the upstream rustc rep... | .stdout,
)
.unwrap();
// extract "1 XX 0" from "rustc 1.XX.0-nightly (<commit> <date>)"
let vsplit: Vec<&str> = rustc_version
.split(' ')
.nth(1)
.unwrap()
.split('-')
.next()
.unwrap()
.split('.')
.collect();
match vsplit.a... | {
// do not run this test inside the upstream rustc repo:
// https://github.com/rust-lang/rust-clippy/issues/6683
if option_env!("RUSTC_TEST_SUITE").is_some() {
return;
}
let clippy_version = rustc_tools_util::get_version_info!();
let clippy_major = clippy_version.major;
let clippy_... | identifier_body |
new-testRunner.js | /* @flow */
import {join, relative, resolve} from 'path';
import {format} from 'util';
import {exec, exists, mkdirp, readFile, unlink, writeFile} from '../async';
import {getTestsDir, defaultFlowConfigName} from '../constants';
import type {Args} from './new-testCommand';
async function newTest(bin: string, suiteNa... |
const dest = join(getTestsDir(), suiteName);
const alreadyExists = await exists(dest);
if (alreadyExists) {
log("There is already a test with that name. Skipping...");
return;
}
await mkdirp(dest);
const testFile = join(dest, 'test.js');
const testerLoc = relative(dest, resolve(__dirname, ".... | {
console.log("[%s]\t\t%s", suiteName, format(...args));
} | identifier_body |
new-testRunner.js | /* @flow */
import {join, relative, resolve} from 'path';
import {format} from 'util';
import {exec, exists, mkdirp, readFile, unlink, writeFile} from '../async';
import {getTestsDir, defaultFlowConfigName} from '../constants';
import type {Args} from './new-testCommand';
async function newTest(bin: string, suiteNa... | log(...args: any) {
console.log("[%s]\t\t%s", suiteName, format(...args));
}
const dest = join(getTestsDir(), suiteName);
const alreadyExists = await exists(dest);
if (alreadyExists) {
log("There is already a test with that name. Skipping...");
return;
}
await mkdirp(dest);
const testFil... | function | identifier_name |
new-testRunner.js | /* @flow */
import {join, relative, resolve} from 'path';
import {format} from 'util';
import {exec, exists, mkdirp, readFile, unlink, writeFile} from '../async';
import {getTestsDir, defaultFlowConfigName} from '../constants';
import type {Args} from './new-testCommand';
async function newTest(bin: string, suiteNa... |
export default suite(({addFile, addFiles, addCode}) => [
test('TestName', [
]),
]);
`
);
await exec(format('%s init --options "all=true" %s', bin, dest));
// Rename .flowconfig to _flowconfig
const config = await readFile(join(dest, ".flowconfig"));
await Promise.all([
writeFile(join(dest, defaultF... | random_line_split | |
palindrome_subsequence.js | /**
* Given: A sequence of string.
* Objective: To find longest subsequence which is palindrome.
* Reference: http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
* Created by gaurav on 6/7/15.
*/
var sequence = null,
subSequence = '';
var findLP = function(i, j, subSeque... |
(function(){
console.log(find("GEEKSFORGEEKS"));
console.log(subSequence);
})();
| {
sequence = str;
var start = 0,
end = sequence.length -1;
return findLP(start, end, "");
} | identifier_body |
palindrome_subsequence.js | /**
* Given: A sequence of string.
* Objective: To find longest subsequence which is palindrome.
* Reference: http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
* Created by gaurav on 6/7/15.
*/
var sequence = null,
subSequence = '';
var findLP = function(i, j, subSeque... |
if( (i==(j+1)) && (sequence[i]==sequence[j])){
return "";
}
if(sequence[i]==sequence[j]){
var f = sequence[i] + findLP(i+1, j-1, subSequence) + sequence[j];
console.log('(%d, %d)\tSubsequence: %s',i,j, f);
return f;
}
if(sequence[i]!==sequence[j]){
var t = fi... | {
return "";
} | conditional_block |
palindrome_subsequence.js | /**
* Given: A sequence of string.
* Objective: To find longest subsequence which is palindrome.
* Reference: http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
* Created by gaurav on 6/7/15.
*/
var sequence = null,
subSequence = '';
var findLP = function(i, j, subSeque... | return findLP(start, end, "");
}
(function(){
console.log(find("GEEKSFORGEEKS"));
console.log(subSequence);
})(); | sequence = str;
var start = 0,
end = sequence.length -1; | random_line_split |
palindrome_subsequence.js | /**
* Given: A sequence of string.
* Objective: To find longest subsequence which is palindrome.
* Reference: http://www.geeksforgeeks.org/dynamic-programming-set-12-longest-palindromic-subsequence/
* Created by gaurav on 6/7/15.
*/
var sequence = null,
subSequence = '';
var findLP = function(i, j, subSeque... | (str){
sequence = str;
var start = 0,
end = sequence.length -1;
return findLP(start, end, "");
}
(function(){
console.log(find("GEEKSFORGEEKS"));
console.log(subSequence);
})();
| find | identifier_name |
modal_body_view.js | /** | @extends Discourse.View
@namespace Discourse
@module Discourse
**/
Discourse.ModalBodyView = Discourse.View.extend({
// Focus on first element
didInsertElement: function() {
var modalBodyView = this;
Em.run.next(function() { modalBodyView.$('form input:first').focus(); });
},
// Pass the errors ... | A base class for helping us display modal content
@class ModalBodyView | random_line_split |
dkekeg.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import RPi.GPIO as GPIO
import MFRC522
import signal
import DBAccessor
import Login
import time
from Login import findPayments
from lcd_i2c import lcd_string, lcd_byte, LCD_LINE_1, LCD_LINE_2, LCD_CMD, lcd_init
GPIO.setmode(GPIO.BOARD)
continue_reading = True
current_uid ... | break
time.sleep(.5)
current_balance -= DELTA_BALANCE
lcd_string(str(current_balance),LCD_LINE_2)
login_counter = LOGIN_COUNTER_START
safety_counter -= 1
beer_counter -= 1
VALVE_OUT_VALUE = False
GPIO.output(VALVE_OU... | GPIO.output(VALVE_OUT,VALVE_OUT_VALUE) | random_line_split |
dkekeg.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import RPi.GPIO as GPIO
import MFRC522
import signal
import DBAccessor
import Login
import time
from Login import findPayments
from lcd_i2c import lcd_string, lcd_byte, LCD_LINE_1, LCD_LINE_2, LCD_CMD, lcd_init
GPIO.setmode(GPIO.BOARD)
continue_reading = True
current_uid ... | (signal,frame):
global continue_reading
print "Ctrl+C captured, ending read."
lcd_byte(0x01, LCD_CMD)
continue_reading = False
GPIO.cleanup()
dbaccessor.closeConnection()
def logout():
print "Logged Out"
global current_uid
global current_balance
global current_name
global VA... | end_read | identifier_name |
dkekeg.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import RPi.GPIO as GPIO
import MFRC522
import signal
import DBAccessor
import Login
import time
from Login import findPayments
from lcd_i2c import lcd_string, lcd_byte, LCD_LINE_1, LCD_LINE_2, LCD_CMD, lcd_init
GPIO.setmode(GPIO.BOARD)
continue_reading = True
current_uid ... |
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()
dbaccessor = DBAccessor.DBAccessor()
default_display()
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
if (log... | print "Logged Out"
global current_uid
global current_balance
global current_name
global VALVE_OUT_VALUE
VALVE_OUT_VALUE = False
GPIO.output(VALVE_OUT,VALVE_OUT_VALUE)
current_uid="0"
current_balance = 0.0
current_name = "THOMAS LYNN"
default_display() | identifier_body |
dkekeg.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import RPi.GPIO as GPIO
import MFRC522
import signal
import DBAccessor
import Login
import time
from Login import findPayments
from lcd_i2c import lcd_string, lcd_byte, LCD_LINE_1, LCD_LINE_2, LCD_CMD, lcd_init
GPIO.setmode(GPIO.BOARD)
continue_reading = True
current_uid ... |
else:
VALVE_OUT_VALUE = False
time.sleep(.5)
login_counter -= 1
| VALVE_OUT_VALUE=True
while GPIO.input(BUTTON_IN):
GPIO.output(VALVE_OUT,VALVE_OUT_VALUE)
if current_balance <=0:
VALVE_OUT_VALUE = False
GPIO.output(VALVE_OUT,VALVE_OUT_VALUE)
break
time.sleep(.5)
current_balance -= ... | conditional_block |
project.js | var _ = require( 'lodash' );
var machina = require( 'machina' );
var when = require( 'when' );
var Monologue = require( 'monologue.js' )( _ );
var drudgeon = require( 'drudgeon' );
var debug = require( 'debug' )( 'nonstop:project' );
var packager = require( 'nonstop-pack' );
var path = require( 'path' );
var platform =... |
debug( 'build failed for %s %s with %s', name, this.version, err.stack ? err.stack : err );
this.emit( 'project.failed', { step: 'build', error: err } );
}
},
'packaging': {
_onEnter: function() {
this._pack( this.packageInfo );
},
'package-done': function( packageInfo ) {
deb... | {
err = err[ err.failedStep ].join( '\n' ) || 'build step "' + err.failedStep + '" exited with a non-zero code';
} | conditional_block |
project.js | var _ = require( 'lodash' );
var machina = require( 'machina' );
var when = require( 'when' );
var Monologue = require( 'monologue.js' )( _ );
var drudgeon = require( 'drudgeon' );
var debug = require( 'debug' )( 'nonstop:project' );
var packager = require( 'nonstop-pack' );
var path = require( 'path' );
var platform =... | ( name, config, repInfo ) {
var Machine = machina.Fsm.extend( {
_handler: function( ev ) {
return function( result ) {
this.handle( ev, result );
}.bind( this );
},
_handlers: function( op ) {
return {
progress: function( data ) { this.emit( op + '.data', data ); }.bind( this ),
success: th... | createProjectMachine | identifier_name |
project.js | var _ = require( 'lodash' );
var machina = require( 'machina' );
var when = require( 'when' );
var Monologue = require( 'monologue.js' )( _ );
var drudgeon = require( 'drudgeon' );
var debug = require( 'debug' )( 'nonstop:project' );
var packager = require( 'nonstop-pack' );
var path = require( 'path' );
var platform =... | .catch( handles.failure );
},
_upload: function( packageInfo ) {
this._promise( 'upload', packager.upload, packageInfo );
},
build: function( noPack ) {
this.noPack = noPack || !( config.pack && config.pack.pattern );
return when.promise( function( resolve, reject, notify ) {
var eventSubscri... | promise.apply( null, args )
.progress( handles.progress )
.then( handles.success )
.then( null, handles.failure ) | random_line_split |
project.js | var _ = require( 'lodash' );
var machina = require( 'machina' );
var when = require( 'when' );
var Monologue = require( 'monologue.js' )( _ );
var drudgeon = require( 'drudgeon' );
var debug = require( 'debug' )( 'nonstop:project' );
var packager = require( 'nonstop-pack' );
var path = require( 'path' );
var platform =... | },
_getPackageInfo: function() {
this._promise( 'packageInfo', packager.getInfo, name, config, repInfo );
},
_pack: function( packageInfo ) {
this._promise( 'package', packager.create, packageInfo );
},
_promise: function( op, promise ) {
var args = Array.prototype.slice.call( arguments, 2 );
... | {
var Machine = machina.Fsm.extend( {
_handler: function( ev ) {
return function( result ) {
this.handle( ev, result );
}.bind( this );
},
_handlers: function( op ) {
return {
progress: function( data ) { this.emit( op + '.data', data ); }.bind( this ),
success: this._handler( op + '-done' ... | identifier_body |
ScoreTransfer.js | #pragma strict
var playerFinalScore: int;
var Users: List.< GameObject >;
var userData: GameObject[];
var maxPlayers: int;
var gameManager: GameObject;
var currentPlayer: int;
var currentName: String;
function Awake () {
//var users :GameObject = GameObject.Find("_UserControllerFB");
userData = GameObject.FindGameObje... | function Update () {
if(Users.Count>0)
playerFinalScore = Users[0].GetComponent(_GameManager).playerFinalScore;
}
function PlayerChanger()
{
currentPlayer++;
for(var i: int; i<Users.Count; i++)
{
if(i!=currentPlayer)Users[i].SetActive(false);
else Users[i].SetActive(true);
}
print("Change Player");
... | function Start()
{
gameManager = GameObject.Find("__GameManager");
NotificationCenter.DefaultCenter().AddObserver(this, "PlayerChanger");
} | random_line_split |
16878_H2.rs | 0.160 4.3761320E-002 4.3570550E-002 4.3445530E-002 4.3206240E-002 4.2161500E-002 4.1216940E-002
0.170 4.3996000E-002 4.4919430E-002 4.4792980E-002 4.4369930E-002 4.2842430E-002 4.1665050E-002
0.180 5.1370830E-002 4.7977580E-002 4.6887720E-002 4.5761710E-002 4.3470720E-002 4.2072230E-002
0.190 5.2597260E-002 4.933258... | 0.150 4.2383010E-002 4.2630480E-002 4.2601680E-002 4.2383550E-002 4.1479710E-002 4.0745470E-002
| random_line_split | |
gridOptionsWrapper.d.ts | // Type definitions for ag-grid v7.1.0
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ceolter/>
import { RowNode } from "./entities/rowNode";
import { GridOptions, NodeChildDetails, GetContextMenuItems, GetMainMenuItems, ProcessRowParams, ProcessCellForExportParams, GetRowNodeId... | {
private static MIN_COL_WIDTH;
static PROP_HEADER_HEIGHT: string;
private gridOptions;
private columnController;
private eventService;
private enterprise;
private frameworkFactory;
private propertyEventService;
private fullWidthCellRenderer;
private groupRowRenderer;
privat... | GridOptionsWrapper | identifier_name |
gridOptionsWrapper.d.ts | // Type definitions for ag-grid v7.1.0
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ceolter/>
import { RowNode } from "./entities/rowNode";
import { GridOptions, NodeChildDetails, GetContextMenuItems, GetMainMenuItems, ProcessRowParams, ProcessCellForExportParams, GetRowNodeId... | isSingleClickEdit(): boolean;
isSuppressClickEdit(): boolean;
getGroupDefaultExpanded(): number;
getAutoSizePadding(): number;
getMaxConcurrentDatasourceRequests(): number;
getMaxPagesInCache(): number;
getPaginationOverflowSize(): number;
getPaginationPageSize(): number;
getPaginati... | getColumnApi(): ColumnApi;
isEnableColResize(): boolean; | random_line_split |
hnusers.py | """
A simple script for downloading user data.
"""
import argparse
import csv
import json
import os
from dataclasses import dataclass
from shutil import move
import requests as r
from common import convert, limit_rate, max_request_per_hour, pid_run
users_file_name = "users"
users_data_file_name = "users.data.csv"
te... | f __name__ == "__main__":
args = parse_arguments()
if not os.path.isdir(args.data_path):
os.makedirs(args.data_path)
pid_run(lambda: run(args))
| Parses arguments and returns parsed version.
"""
parser = argparse.ArgumentParser(description='Downloads Hackernews users data')
parser.add_argument("--data-path", required=True, help="path to the data directory")
parser.add_argument("--create-users-file", action='store_true',
... | identifier_body |
hnusers.py | """
A simple script for downloading user data.
"""
import argparse
import csv
import json
import os
from dataclasses import dataclass
from shutil import move
import requests as r
from common import convert, limit_rate, max_request_per_hour, pid_run
users_file_name = "users"
users_data_file_name = "users.data.csv"
te... | = parse_arguments()
if not os.path.isdir(args.data_path):
os.makedirs(args.data_path)
pid_run(lambda: run(args))
| conditional_block | |
hnusers.py | """
A simple script for downloading user data.
"""
import argparse
import csv
import json
import os
from dataclasses import dataclass
from shutil import move
import requests as r
from common import convert, limit_rate, max_request_per_hour, pid_run
users_file_name = "users"
users_data_file_name = "users.data.csv"
te... |
for f in os.listdir(args.data_path):
if not f.endswith(".data.csv"):
continue
fname = os.path.join(args.data_path, f)
print(f"Reading file {fname}")
with open(fname) as csvfile:
reader = csv.reader(csvfile)
# read the header first
he... | users = set() | random_line_split |
hnusers.py | """
A simple script for downloading user data.
"""
import argparse
import csv
import json
import os
from dataclasses import dataclass
from shutil import move
import requests as r
from common import convert, limit_rate, max_request_per_hour, pid_run
users_file_name = "users"
users_data_file_name = "users.data.csv"
te... | s: ProgramArguments):
"""Creates a csv file with unique and sorted user data from all the data csv files.
The file is saved to args.data_path/users_data_file_name
"""
print("Downloading users data")
users_file_path = os.path.join(args.data_path, users_file_name)
users_data_file_path = os.path.jo... | users_data(arg | identifier_name |
xmlrpcclient.py | #============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope th... | (self, uri, transport=None, encoding=None, verbose=0,
allow_none=1):
if transport == None:
(protocol, rest) = uri.split(':', 1)
if protocol == 'httpu':
uri = 'http:' + rest
transport = UnixTransport()
elif protocol == 'https':
... | __init__ | identifier_name |
xmlrpcclient.py | #============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope th... |
elif protocol == 'https':
transport = HTTPSTransport()
elif protocol == 'ssh':
global ssh_enabled
if ssh_enabled:
(transport, uri) = SSHTransport.getHTTPURI(uri)
else:
raise ValueError(
... | uri = 'http:' + rest
transport = UnixTransport() | conditional_block |
xmlrpcclient.py | #============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope th... |
# We need our own transport for HTTPS, because xmlrpclib.SafeTransport is
# broken -- it does not handle ERROR_ZERO_RETURN properly.
class HTTPSTransport(xmlrpclib.SafeTransport):
def _parse_response(self, file, sock):
p, u = self.getparser()
while 1:
try:
if sock:
... | if hexversion < 0x02070000:
# python 2.6 or earlier
return HTTPUnix(self.__handler)
else:
# xmlrpclib.Transport changed in python 2.7
return HTTPUnixConnection(self.__handler) | identifier_body |
xmlrpcclient.py | #============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope th... | # See xmlrpclib2.TCPXMLRPCServer._marshalled_dispatch.
def conv_string(x):
if isinstance(x, StringTypes):
s = string.replace(x, "'", r"\047")
exec "s = '" + s + "'"
return s
else:
return x
class ServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, enc... | random_line_split | |
lc587-erect-the-fence.py | # coding=utf-8
import unittest
"""587. Erect the Fence
https://leetcode.com/problems/erect-the-fence/description/
There are some trees, where each tree is represented by (x,y) coordinate in a
two-dimensional garden. Your job is to fence the entire garden using the
**minimum length** of rope as it is expensive. The ga... | unittest.main() | conditional_block | |
lc587-erect-the-fence.py | # coding=utf-8
import unittest
"""587. Erect the Fence
https://leetcode.com/problems/erect-the-fence/description/
There are some trees, where each tree is represented by (x,y) coordinate in a
two-dimensional garden. Your job is to fence the entire garden using the
**minimum length** of rope as it is expensive. The ga... | (self, points):
"""
:type points: List[Point]
:rtype: List[Point]
"""
def test(self):
pass
if __name__ == "__main__":
unittest.main()
| outerTrees | identifier_name |
lc587-erect-the-fence.py | # coding=utf-8
import unittest
"""587. Erect the Fence
https://leetcode.com/problems/erect-the-fence/description/ | if all the trees are enclosed. Your task is to help find the coordinates of
trees which are exactly located on the fence perimeter.
**Example 1:**
**Input:** [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
**Output:** [[1,1],[2,0],[4,2],[3,3],[2,4]]
**Explanation:**
 coordinate in a
two-dimensional garden. Your job is to fence the entire garden using the
**minimum length** of rope as it is expensive. The garden is well fenced only | random_line_split |
lc587-erect-the-fence.py | # coding=utf-8
import unittest
"""587. Erect the Fence
https://leetcode.com/problems/erect-the-fence/description/
There are some trees, where each tree is represented by (x,y) coordinate in a
two-dimensional garden. Your job is to fence the entire garden using the
**minimum length** of rope as it is expensive. The ga... |
if __name__ == "__main__":
unittest.main()
| def outerTrees(self, points):
"""
:type points: List[Point]
:rtype: List[Point]
"""
def test(self):
pass | identifier_body |
repl.rs | //! This module implements the todr REPL logic.
use dirs;
use rustyline::error::ReadlineError;
use rustyline::Editor;
use std::path::Path;
// Use our internal handlers module.
use completer::CustomCompletion;
use handlers;
// On unix platforms you can use ANSI escape sequences
#[cfg(unix)]
static PROMPT: &'static st... |
/// Executes the main process loop.
pub fn process_command_loop(&mut self) {
// If loading failed, that's fine, just ignore it.
let _ = self.readline_editor.load_history(&self.history_file);
loop {
// Handle graceful exit request.
if self.should_exit {
... | {
let home = dirs::home_dir().expect("Home Dir couldn't be found");
let history_file = Path::new(&home)
.join(DEFAULT_HISTORY_FILE)
.to_string_lossy()
.to_string();
let mut editor = Editor::<CustomCompletion>::new();
let completer = CustomCompletion:... | identifier_body |
repl.rs | //! This module implements the todr REPL logic.
use dirs;
use rustyline::error::ReadlineError;
use rustyline::Editor;
use std::path::Path;
// Use our internal handlers module.
use completer::CustomCompletion;
use handlers;
// On unix platforms you can use ANSI escape sequences
#[cfg(unix)]
static PROMPT: &'static st... |
self.readline_editor
.save_history(&self.history_file)
.expect("Failed to save repl history file");
}
/// Processes a single line for a command.
fn process_line(&mut self, line: &str) {
self.readline_editor.add_history_entry(line);
match line {
... | }
} | random_line_split |
repl.rs | //! This module implements the todr REPL logic.
use dirs;
use rustyline::error::ReadlineError;
use rustyline::Editor;
use std::path::Path;
// Use our internal handlers module.
use completer::CustomCompletion;
use handlers;
// On unix platforms you can use ANSI escape sequences
#[cfg(unix)]
static PROMPT: &'static st... | (&mut self) {
// If loading failed, that's fine, just ignore it.
let _ = self.readline_editor.load_history(&self.history_file);
loop {
// Handle graceful exit request.
if self.should_exit {
break;
}
let readline = self.readline_ed... | process_command_loop | identifier_name |
option_unwrap.rs | // The commoner has seen it all, and can handle any gift well.
// All gifts are handled explicitly using `match`.
fn give_commoner(gift: Option<&str>) {
// Specify a course of action for each case.
match gift {
Some("snake") => println!("Yuck! I'm throwing that snake in a fire."),
Some(inner) ... |
fn main() {
let food = Some("cabbage");
let snake = Some("snake");
let void = None;
give_commoner(food);
give_commoner(snake);
give_commoner(void);
let bird = Some("robin");
let nothing = None;
give_princess(bird);
give_princess(nothing);
}
| {
// `unwrap` returns a `panic` when it receives a `None`.
let inside = gift.unwrap();
if inside == "snake" { panic!("AAAaaaaa!!!!"); }
println!("I love {}s!!!!!", inside);
} | identifier_body |
option_unwrap.rs | // The commoner has seen it all, and can handle any gift well.
// All gifts are handled explicitly using `match`.
fn give_commoner(gift: Option<&str>) {
// Specify a course of action for each case.
match gift {
Some("snake") => println!("Yuck! I'm throwing that snake in a fire."),
Some(inner) ... | () {
let food = Some("cabbage");
let snake = Some("snake");
let void = None;
give_commoner(food);
give_commoner(snake);
give_commoner(void);
let bird = Some("robin");
let nothing = None;
give_princess(bird);
give_princess(nothing);
}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.