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 |
|---|---|---|---|---|
globs.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | f //~ ERROR cannot find function `f` in this scope
}
super::n_with_super! {
f
}
}
}
} | random_line_split | |
PropertyGrid.ts | declare namespace Serenity {
class PropertyGrid extends Widget<PropertyGridOptions> {
constructor(div: JQuery, opt: PropertyGridOptions);
load(source: any): void;
static loadEditorValue(editor: Serenity.Widget<any>, item: PropertyItem, source: any): void;
save(target: any): voi... |
static getPropertyItemsFor(type: Function): PropertyItem[];
}
} | opertyItemHelper { | identifier_name |
PropertyGrid.ts | declare namespace Serenity {
class PropertyGrid extends Widget<PropertyGridOptions> {
constructor(div: JQuery, opt: PropertyGridOptions);
load(source: any): void;
static loadEditorValue(editor: Serenity.Widget<any>, item: PropertyItem, source: any): void;
save(target: any): voi... | mode?: PropertyGridMode;
}
class PropertyItemHelper {
static getPropertyItemsFor(type: Function): PropertyItem[];
}
} | defaultCategory?: string;
localTextPrefix?: string;
| random_line_split |
window.d.ts | import * as EventEmitter from 'eventemitter3';
import * as I18n from 'i18n-js';
import { Store } from 'redux';
import { Fundraiser } from './plugins/fundraiser';
import { Petition } from './plugins/petition';
import Plugin, { IPluginConfig } from './plugins/plugin';
import { IReCaptchaInstance } from './shared/recaptch... |
interface IChampaignMember {
id: number;
email: string;
country: string;
consented: boolean | null | undefined;
consented_updated_at: string | null | undefined;
name: string;
first_name: string;
last_name: string;
full_name: string;
welcome_name: string;
postal: string;
actionkit_user_id: strin... | } | random_line_split |
rng.js | // Random number generator - requires a PRNG backend, e.g. prng4.js
// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.
var rng_state;
var rng_pool;
var rng_pptr;
// Mix in a 32-bit integer into the pool
function rng_seed_int(x) {
rng... |
function rng_get_bytes(ba) {
var i;
for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
}
function SecureRandom() {}
SecureRandom.prototype.nextBytes = rng_get_bytes;
| {
if(rng_state == null) {
rng_seed_time();
rng_state = prng_newstate();
rng_state.init(rng_pool);
for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
rng_pool[rng_pptr] = 0;
rng_pptr = 0;
//rng_pool = null;
}
// TODO: allow reseeding after first request
return rng_state.next(... | identifier_body |
rng.js | // Random number generator - requires a PRNG backend, e.g. prng4.js
// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.
var rng_state;
var rng_pool;
var rng_pptr;
// Mix in a 32-bit integer into the pool
function rng_seed_int(x) {
rng... | if(rng_state == null) {
rng_seed_time();
rng_state = prng_newstate();
rng_state.init(rng_pool);
for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
rng_pool[rng_pptr] = 0;
rng_pptr = 0;
//rng_pool = null;
}
// TODO: allow reseeding after first request
return rng_state.next();... | function rng_get_byte() { | random_line_split |
rng.js | // Random number generator - requires a PRNG backend, e.g. prng4.js
// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.
var rng_state;
var rng_pool;
var rng_pptr;
// Mix in a 32-bit integer into the pool
function rng_seed_int(x) {
rng... | () {
rng_seed_int(new Date().getTime());
}
// Initialize the pool with junk if needed.
if(rng_pool == null) {
rng_pool = new Array();
rng_pptr = 0;
var t;
if(window.crypto && window.crypto.getRandomValues) {
// Use webcrypto if available
var ua = new Uint8Array(32);
window.crypto.getRandomValues(... | rng_seed_time | identifier_name |
rng.js | // Random number generator - requires a PRNG backend, e.g. prng4.js
// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.
var rng_state;
var rng_pool;
var rng_pptr;
// Mix in a 32-bit integer into the pool
function rng_seed_int(x) {
rng... |
if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) {
// Extract entropy (256 bits) from NS4 RNG if available
var z = window.crypto.random(32);
for(t = 0; t < z.length; ++t)
rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
}
while(rng_pptr < rng_psize) { // extrac... | {
// Use webcrypto if available
var ua = new Uint8Array(32);
window.crypto.getRandomValues(ua);
for(t = 0; t < 32; ++t)
rng_pool[rng_pptr++] = ua[t];
} | conditional_block |
slice.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a>(&'a mut self, _from: &Foo) -> &'a mut Foo {
unsafe { COUNT += 1; }
self
}
fn slice_to_mut_<'a>(&'a mut self, _to: &Foo) -> &'a mut Foo {
unsafe { COUNT += 1; }
self
}
fn slice_mut_<'a>(&'a mut self, _from: &Foo, _to: &Foo) -> &'a mut Foo {
unsafe { COUNT += 1... | slice_from_mut_ | identifier_name |
slice.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn as_slice_<'a>(&'a self) -> &'a Foo {
unsafe { COUNT += 1; }
self
}
fn slice_from_<'a>(&'a self, _from: &Foo) -> &'a Foo {
unsafe { COUNT += 1; }
self
}
fn slice_to_<'a>(&'a self, _to: &Foo) -> &'a Foo {
unsafe { COUNT += 1; }
self
}
fn slice... | struct Foo;
impl Slice<Foo, Foo> for Foo { | random_line_split |
slice.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn slice_from_<'a>(&'a self, _from: &Foo) -> &'a Foo {
unsafe { COUNT += 1; }
self
}
fn slice_to_<'a>(&'a self, _to: &Foo) -> &'a Foo {
unsafe { COUNT += 1; }
self
}
fn slice_<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo {
unsafe { COUNT += 1; }
s... | {
unsafe { COUNT += 1; }
self
} | identifier_body |
test_actions.py | import io
from django.test import TestCase
from explorer.actions import generate_report_action
from explorer.tests.factories import SimpleQueryFactory
from explorer.utils import csv_report
from zipfile import ZipFile
class testSqlQueryActions(TestCase):
def test_simple_query_runs(self):
expected_csv = ... | self.assertEqual(len(z.namelist()), 2)
self.assertEqual(z.namelist()[0], '%s.csv' % q.title)
self.assertEqual(got_csv.lower().decode('utf-8'), expected_csv)
# if commas are not removed from the filename, then Chrome throws "duplicate headers received from server"
def test_packaging_remo... | res = fn(None, None, [q,q2])
z = ZipFile(io.BytesIO(res.content))
got_csv = z.read(z.namelist()[0])
| random_line_split |
test_actions.py | import io
from django.test import TestCase
from explorer.actions import generate_report_action
from explorer.tests.factories import SimpleQueryFactory
from explorer.utils import csv_report
from zipfile import ZipFile
class testSqlQueryActions(TestCase):
def test_simple_query_runs(self):
expected_csv = ... | (self):
expected_csv = 'two\r\n2\r\n'
q = SimpleQueryFactory()
q2 = SimpleQueryFactory()
fn = generate_report_action()
res = fn(None, None, [q,q2])
z = ZipFile(io.BytesIO(res.content))
got_csv = z.read(z.namelist()[0])
self.assertEqual(len(z.namelist()... | test_multiple_queries_are_zip_file | identifier_name |
test_actions.py | import io
from django.test import TestCase
from explorer.actions import generate_report_action
from explorer.tests.factories import SimpleQueryFactory
from explorer.utils import csv_report
from zipfile import ZipFile
class testSqlQueryActions(TestCase):
def test_simple_query_runs(self):
|
def test_single_query_is_csv_file(self):
expected_csv = b'two\r\n2\r\n'
r = SimpleQueryFactory()
fn = generate_report_action()
result = fn(None, None, [r, ])
self.assertEqual(result.content.lower(), expected_csv)
def test_multiple_queries_are_zip_file(self):
... | expected_csv = 'two\r\n2\r\n'
r = SimpleQueryFactory()
result = csv_report(r).getvalue()
self.assertIsNotNone(result, "Query '%s' returned None." % r.title)
self.assertEqual(result.lower(), expected_csv) | identifier_body |
diff.tsx | import * as React from "react";
import {
MonacoDiffEditor,
DiffEditorDidMount,
DiffChangeHandler,
DiffEditorWillMount
} from "../..";
type AppState = {
original: string;
code: string;
};
class | extends React.Component<{}, AppState> {
state = {
original: "// original code",
code: "// new code"
};
editorWillMount: DiffEditorWillMount = monaco => {
console.log("editorWillMount", monaco);
};
editorDidMount: DiffEditorDidMount = (editor, monaco) => {
console.log("editorDidMount", edito... | App | identifier_name |
diff.tsx | import * as React from "react";
import {
MonacoDiffEditor,
DiffEditorDidMount, | original: string;
code: string;
};
class App extends React.Component<{}, AppState> {
state = {
original: "// original code",
code: "// new code"
};
editorWillMount: DiffEditorWillMount = monaco => {
console.log("editorWillMount", monaco);
};
editorDidMount: DiffEditorDidMount = (editor, mon... | DiffChangeHandler,
DiffEditorWillMount
} from "../..";
type AppState = { | random_line_split |
types.documentarray.test.js |
/**
* Module dependencies.
*/
var mongoose = require('./common').mongoose
, MongooseArray = mongoose.Types.Array
, MongooseDocumentArray = mongoose.Types.DocumentArray
, EmbeddedDocument = require('../lib/types/embedded')
, DocumentArray = require('../lib/types/documentarray')
, Schema = mongoose.Schema
... |
return Subdocument;
}
/**
* Test.
*/
module.exports = {
'test that a mongoose array behaves and quacks like an array': function(){
var a = new MongooseDocumentArray();
a.should.be.an.instanceof(Array);
a.should.be.an.instanceof(MongooseArray);
a.should.be.an.instanceof(MongooseDocumentArray)... | {
var Subdocument = function () {
EmbeddedDocument.call(this, {}, new DocumentArray);
};
/**
* Inherits from EmbeddedDocument.
*/
Subdocument.prototype.__proto__ = EmbeddedDocument.prototype;
/**
* Set schema.
*/
var SubSchema = new Schema({
title: { type: String }
});
Subdocu... | identifier_body |
types.documentarray.test.js | /**
* Module dependencies.
*/
var mongoose = require('./common').mongoose
, MongooseArray = mongoose.Types.Array
, MongooseDocumentArray = mongoose.Types.DocumentArray
, EmbeddedDocument = require('../lib/types/embedded')
, DocumentArray = require('../lib/types/documentarray')
, Schema = mongoose.Schema
/... |
'#id': function () {
var Subdocument = TestDoc();
var sub1 = new Subdocument();
sub1.title = 'Hello again to all my friends';
var id = sub1.id;
var a = new MongooseDocumentArray([sub1]);
a.id(id).title.should.equal('Hello again to all my friends');
a.id(sub1._id).title.should.equal('Hel... | 'object'.should.eql(typeof b);
Object.keys(b.toObject()).length.should.equal(4);
}, | random_line_split |
types.documentarray.test.js |
/**
* Module dependencies.
*/
var mongoose = require('./common').mongoose
, MongooseArray = mongoose.Types.Array
, MongooseDocumentArray = mongoose.Types.DocumentArray
, EmbeddedDocument = require('../lib/types/embedded')
, DocumentArray = require('../lib/types/documentarray')
, Schema = mongoose.Schema
... | (schema) {
var Subdocument = function () {
EmbeddedDocument.call(this, {}, new DocumentArray);
};
/**
* Inherits from EmbeddedDocument.
*/
Subdocument.prototype.__proto__ = EmbeddedDocument.prototype;
/**
* Set schema.
*/
var SubSchema = new Schema({
title: { type: String }
});
... | TestDoc | identifier_name |
writer.py | import cbor
import hashlib
import logging
import zlib
from .common import * # NOQA
LOG = logging.getLogger(__name__)
default_hashalgo = 'sha256'
state_bos = 0
state_metadata = 1
state_data = 2
state_eos = 3
class MuxError(Exception):
pass
class InvalidState(MuxError):
pass
class StreamWriter(object):... |
- version: the mux format version
- name (optional): name of this stream
- hashalgo (optional): hash algorithm used for checksums
- compress (optional): true if data is compressed
'''
if self.state != state_bos:
raise InvalidState()
header = {'versio... | def _write_header(self):
'''Writes out a header block. The header block contains
information about the stream: | random_line_split |
writer.py | import cbor
import hashlib
import logging
import zlib
from .common import * # NOQA
LOG = logging.getLogger(__name__)
default_hashalgo = 'sha256'
state_bos = 0
state_metadata = 1
state_data = 2
state_eos = 3
class MuxError(Exception):
|
class InvalidState(MuxError):
pass
class StreamWriter(object):
'''Writes one part to a mux stream.
A mux stream is a series for cbor-encoded dictionaries. Each
chunk has a 'type' attribute that identifies the chunk type. A
part has the following format:
+----------------------------... | pass | identifier_body |
writer.py | import cbor
import hashlib
import logging
import zlib
from .common import * # NOQA
LOG = logging.getLogger(__name__)
default_hashalgo = 'sha256'
state_bos = 0
state_metadata = 1
state_data = 2
state_eos = 3
class MuxError(Exception):
pass
class InvalidState(MuxError):
pass
class StreamWriter(object):... | (self, fh,
name=None, hashalgo=None, writehash=False,
compress=False):
self.fh = fh
self.name = name
self.hashalgo = hashalgo if hashalgo else default_hashalgo
self.writehash = writehash
self.compress = compress
self.state = state_bos
... | __init__ | identifier_name |
writer.py | import cbor
import hashlib
import logging
import zlib
from .common import * # NOQA
LOG = logging.getLogger(__name__)
default_hashalgo = 'sha256'
state_bos = 0
state_metadata = 1
state_data = 2
state_eos = 3
class MuxError(Exception):
pass
class InvalidState(MuxError):
pass
class StreamWriter(object):... |
if self.metadata:
self._write_block(blktype_metadata,
metadata=self.metadata)
self.state = state_data
def _write_block(self, blktype, **kwargs):
LOG.debug('writing block: type=%s, content=%s',
blktype, repr(kwargs))
cbo... | raise InvalidState() | conditional_block |
__init__.py | # Copyright 2014 Tesora, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | (replication_driver, ns=__name__):
LOG.debug("Getting replication strategy: %s.", replication_driver)
return Strategy.get_strategy(replication_driver, ns)
| get_replication_strategy | identifier_name |
__init__.py | # Copyright 2014 Tesora, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | LOG.debug("Getting replication strategy: %s.", replication_driver)
return Strategy.get_strategy(replication_driver, ns) | identifier_body | |
__init__.py | # Copyright 2014 Tesora, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# | #
from trove.guestagent.strategy import Strategy
from trove.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def get_replication_strategy(replication_driver, ns=__name__):
LOG.debug("Getting replication strategy: %s.", replication_driver)
return Strategy.get_strategy(replication_driv... | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under th... | random_line_split |
__init__.py | # Copyright 2013 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | try:
return importlib.import_module(CONF.jobqueue.worker_module)
except Exception as err:
LOG.exception(err)
raise Exception("Failed to import worker module") | identifier_body | |
__init__.py | # Copyright 2013 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | try:
return importlib.import_module(CONF.jobqueue.worker_module)
except Exception as err:
LOG.exception(err)
raise Exception("Failed to import worker module") | random_line_split | |
__init__.py | # Copyright 2013 Cloudbase Solutions Srl
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | ():
try:
return importlib.import_module(CONF.jobqueue.worker_module)
except Exception as err:
LOG.exception(err)
raise Exception("Failed to import worker module")
| get_worker_module | identifier_name |
__init__.py | lnow import RTLnowIE
from .rtl2 import RTL2IE
from .rtp import RTPIE
from .rts import RTSIE
from .rtve import RTVEALaCartaIE, RTVELiveIE
from .ruhd import RUHDIE
from .rutube import (
RutubeIE,
RutubeChannelIE,
RutubeEmbedIE,
RutubeMovieIE,
RutubePersonIE,
)
from .rutv import RUTVIE
from .sapo impor... | get_info_extractor | identifier_name | |
__init__.py | from .brightcove import BrightcoveIE
from .buzzfeed import BuzzFeedIE
from .byutv import BYUtvIE
from .c56 import C56IE
from .canal13cl import Canal13clIE
from .canalplus import CanalplusIE
from .canalc2 import Canalc2IE
from .cbs import CBSIE
from .cbsnews import CBSNewsIE
from .ceskatelevize import CeskaTelevizeIE
fr... | from .bpb import BpbIE
from .br import BRIE
from .breakcom import BreakIE | random_line_split | |
__init__.py | from .ro220 import Ro220IE
from .rottentomatoes import RottenTomatoesIE
from .roxwel import RoxwelIE
from .rtbf import RTBFIE
from .rte import RteIE
from .rtlnl import RtlXlIE
from .rtlnow import RTLnowIE
from .rtl2 import RTL2IE
from .rtp import RTPIE
from .rts import RTSIE
from .rtve import RTVEALaCartaIE, RTVELiveIE... | """ Return a list of an instance of every supported extractor.
The order does matter; the first extractor matched is the one handling the URL.
"""
return [klass() for klass in _ALL_CLASSES] | identifier_body | |
vacancyDateVal.js | $(document).ready(function() { | onSet: function( arg ){
if ( 'select' in arg ){ //prevent closing on selecting month/year
this.close();
}
var d1 = $('#startdate').val();
var d2 = $('#enddate').val();
var date1 = new Date(d1);
var date2 = new Date(d2);
var date1... | $('.datepicker').pickadate({
selectMonths: true,
selectYears:true,
//format: 'yyyy-mm-dd', | random_line_split |
vacancyDateVal.js |
$(document).ready(function() {
$('.datepicker').pickadate({
selectMonths: true,
selectYears:true,
//format: 'yyyy-mm-dd',
onSet: function( arg ){
if ( 'select' in arg ) |
var d1 = $('#startdate').val();
var d2 = $('#enddate').val();
var date1 = new Date(d1);
var date2 = new Date(d2);
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
if((date2_ms -date1_ms ) <0 )
{
this.clear();... | { //prevent closing on selecting month/year
this.close();
} | conditional_block |
sass-nested-renderer.js | "use strict";
var SassExpandedRenderer = require('./sass-expanded-renderer');
/**
* @class SassNestedRenderer
* Nested style is the default Sass style, because it reflects the structure of
* the document in much the same way Sass does. Each rule is indented based on
* how deeply it's nested. Each property h... | var SassNestedRenderer = module.exports = SassExpandedRenderer.extend({
/**
* Renders the brace at the end of the rule
* @returns string the brace between the rule and its properties
*/
end: function() {
return " }\n";
},
/**
* Returns the indent string for the node
* @param {Sass... | random_line_split | |
index.ts | import * as dotenv from 'dotenv';
dotenv.config();
import { SlackBot } from './src/slackbot';
// import { CloseIssueCommand } from './src/commands/issues/close.command';
import { GetIssueInfoCommand } from './src/commands/issues/get-info.command';
import { GrantPermissionsCommand } from './src/commands/admin/grant-per... | const firebaseDatabaseUrl = process.env.FIREBASE_DATABASE_URL;
const slackbot = new SlackBot(slackToken);
const slackMessenger = new SlackMessenger(slackToken);
const githubRepository = new GotGitHubRepository(githubToken, githubProject);
const firebaseContext = createFirebaseContext(
firebaseDatabaseUrl, firebase... | const firebaseClientCertUrl = process.env.FIREBASE_CLIENT_X509_CERT_URL || ''; | random_line_split |
variant_ref_mut.rs | use vtable::VTable;
use variant_ref::VariantRef;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
pub struct VariantRefMut<'a> {
data: &'a mut (),
vtable: &'a VTable,
}
impl<'a> VariantRefMut<'a> {
pub fn new<T: Any>(value: &'a mut T, vtable: &'a VTable) -> Self {
... | <T: Any>(&self) -> &T {
debug_assert!(self.is::<T>());
&*(self.data as *const _ as *const T)
}
#[inline]
pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
debug_assert!(self.is::<T>());
&mut *(self.data as *mut _ as *mut T)
}
}
impl<'a> AsRef<VariantRef<'a>> for... | downcast_ref_unchecked | identifier_name |
variant_ref_mut.rs | use vtable::VTable;
use variant_ref::VariantRef;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
pub struct VariantRefMut<'a> {
data: &'a mut (),
vtable: &'a VTable,
}
impl<'a> VariantRefMut<'a> {
pub fn new<T: Any>(value: &'a mut T, vtable: &'a VTable) -> Self {
... | }
}
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
unsafe { Some(&mut *(self.data as *mut _ as *mut T)) }
} else {
None
}
}
#[inline]
pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
debug_assert!(se... | random_line_split | |
variant_ref_mut.rs | use vtable::VTable;
use variant_ref::VariantRef;
use std::any::{Any, TypeId};
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
pub struct VariantRefMut<'a> {
data: &'a mut (),
vtable: &'a VTable,
}
impl<'a> VariantRefMut<'a> {
pub fn new<T: Any>(value: &'a mut T, vtable: &'a VTable) -> Self {
... |
}
#[inline]
pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
debug_assert!(self.is::<T>());
&*(self.data as *const _ as *const T)
}
#[inline]
pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
debug_assert!(self.is::<T>());
&mut *(self.data as *... | {
None
} | conditional_block |
connections.ui.js | const showLoadingImage = require('../../../../../base/utility').showLoadingImage;
const showLocalTimeOnHover = require('../../../../../base/clock').Clock.showLocalTimeOnHover;
const localize = require('../../../../../base/localize').localize;
const Button = require('../../../../../common_functions/... |
});
return $buttonSpan;
};
const createTable = function(data) {
if (flexTable) {
return flexTable.replace(data);
}
const headers = ['Provider', 'Action'];
const columns = ['provider', 'action'];
flexTable = new FlexTableUI({
conta... | {
ConnectionsData.del(connect);
container.css({ opacity: 0.5 });
} | conditional_block |
connections.ui.js | const showLoadingImage = require('../../../../../base/utility').showLoadingImage;
const showLocalTimeOnHover = require('../../../../../base/clock').Clock.showLocalTimeOnHover;
const localize = require('../../../../../base/localize').localize;
const Button = require('../../../../../common_functions/... | $title.text(localize($title.text()));
$desc.text(localize($desc.text()));
};
const clean = function() {
$(containerSelector + ' .error-msg').text('');
flexTable.clear();
flexTable = null;
};
return {
init : init,
clean : clean,
... | random_line_split | |
index.js | import Queue from 'bull';
import logger from 'lib/logger';
import { isString, values } from 'lodash';
import * as redis from 'lib/connections/redis';
import { Promise } from 'bluebird';
const Bull = {
queues: {}
};
const logError = queueName => (error) => {
logger.error(`QUEUE ERROR: ${queueName}`, error);
};
co... | handler,
onProcessed = () => { },
deadLetter
}, done) => {
getQueue(queueName, (err, queue) => {
if (err) return done(err);
queue.on('completed', (job) => {
onProcessed({
Body: JSON.stringify(job.data)
});
});
if (deadLetter) {
queue.on('failed', (job) => {
se... | };
export const subscribe = ({
queueName, | random_line_split |
index.js | import Queue from 'bull';
import logger from 'lib/logger';
import { isString, values } from 'lodash';
import * as redis from 'lib/connections/redis';
import { Promise } from 'bluebird';
const Bull = {
queues: {}
};
const logError = queueName => (error) => {
logger.error(`QUEUE ERROR: ${queueName}`, error);
};
co... |
return done(null, Bull.queues[queueName]);
};
export const publish = ({
queueName,
payload
}, done) => {
getQueue(queueName, (err, queue) => {
if (err) return done(err);
return queue.add(payload, {
removeOnFail: false,
removeOnComplete: false // Doesn't work ? :(
}).then(() => {
... | {
Bull.queues[queueName] = new Queue(
queueName,
{ createClient: redis.createClient }
)
.on('error', logError(queueName))
.on('completed', (job) => {
logger.debug(`COMPLETED JOB ${job.id}`);
removeJob(job);
})
.on('failed', (job, err) => {
const queue ... | conditional_block |
config.exceptionHandler.ts | module App {
"use strict";
angular.module("knowledgeCenterApp")
.config([
"$provide", ($provide: ng.auto.IProvideService): void => {
$provide.decorator("$exceptionHandler",
["$delegate", "config", "logger", extendExceptionHandler]);
}
]);... | delegate: Function, config: App.IConfigProvider, logger: Common.ILoggerService): Function {
var appErrorPrefix: string = config.appErrorPrefix;
return (exception: Error, cause: string): void => {
$delegate(exception, cause);
if (appErrorPrefix && exception.message.indexOf(appErro... | tendExceptionHandler($ | identifier_name |
config.exceptionHandler.ts | module App {
"use strict";
angular.module("knowledgeCenterApp")
.config([
"$provide", ($provide: ng.auto.IProvideService): void => {
$provide.decorator("$exceptionHandler",
["$delegate", "config", "logger", extendExceptionHandler]);
}
]);... | } | random_line_split | |
config.exceptionHandler.ts | module App {
"use strict";
angular.module("knowledgeCenterApp")
.config([
"$provide", ($provide: ng.auto.IProvideService): void => {
$provide.decorator("$exceptionHandler",
["$delegate", "config", "logger", extendExceptionHandler]);
}
]);... | var appErrorPrefix: string = config.appErrorPrefix;
return (exception: Error, cause: string): void => {
$delegate(exception, cause);
if (appErrorPrefix && exception.message.indexOf(appErrorPrefix) === 0) { return; }
var errorData: any = { exception: exception, cause:... | identifier_body | |
config.exceptionHandler.ts | module App {
"use strict";
angular.module("knowledgeCenterApp")
.config([
"$provide", ($provide: ng.auto.IProvideService): void => {
$provide.decorator("$exceptionHandler",
["$delegate", "config", "logger", extendExceptionHandler]);
}
]);... | var errorData: any = { exception: exception, cause: cause };
var msg: string = appErrorPrefix + exception.message;
logger.logError(msg, errorData, "knowledgeCenterApp", true);
};
}
} | return; }
| conditional_block |
graphics.rs | use super::*;
use redox::*;
impl Editor {
/// Redraw the window
pub fn redraw(&mut self) {
// TODO: Only draw when relevant for the window
let x = self.x();
let y = self.y();
// Redraw window
self.window.set([0, 0, 0, 255]);
self.window.rect(8 * (x - self.scroll... | file: String::new(),
cmd: String::new(),
msg: String::new(),
}
}
} |
impl StatusBar {
pub fn new() -> Self {
StatusBar {
mode: String::new(), | random_line_split |
graphics.rs | use super::*;
use redox::*;
impl Editor {
/// Redraw the window
pub fn redraw(&mut self) {
// TODO: Only draw when relevant for the window
let x = self.x();
let y = self.y();
// Redraw window
self.window.set([0, 0, 0, 255]);
self.window.rect(8 * (x - self.scroll... | else {
self.status_bar.mode.chars().collect()
}).into_iter().enumerate() {
self.window.char(n as isize * 8, h as isize - 16 - 1, c, [255, 255, 255, 255]);
}
self.window.sync();
}
}
pub struct StatusBar {
pub mode: String,
pub file: String,
pub cmd: Stri... | {
self.status_bar.mode.chars().take(w / (8 * 4) - 5).chain(vec!['.', '.', '.']).collect::<Vec<_>>()
} | conditional_block |
graphics.rs | use super::*;
use redox::*;
impl Editor {
/// Redraw the window
pub fn redraw(&mut self) {
// TODO: Only draw when relevant for the window
let x = self.x();
let y = self.y();
// Redraw window
self.window.set([0, 0, 0, 255]);
self.window.rect(8 * (x - self.scroll... | {
pub mode: String,
pub file: String,
pub cmd: String,
pub msg: String,
}
impl StatusBar {
pub fn new() -> Self {
StatusBar {
mode: String::new(),
file: String::new(),
cmd: String::new(),
msg: String::new(),
}
}
}
| StatusBar | identifier_name |
graphics.rs | use super::*;
use redox::*;
impl Editor {
/// Redraw the window
pub fn redraw(&mut self) | } else {
self.window.char(8 * (x - self.scroll_y) as isize,
16 * (y - self.scroll_x) as isize,
*c,
[255, 255, 255, 255]);
}
}
}
l... | {
// TODO: Only draw when relevant for the window
let x = self.x();
let y = self.y();
// Redraw window
self.window.set([0, 0, 0, 255]);
self.window.rect(8 * (x - self.scroll_y) as isize,
16 * (y - self.scroll_x) as isize,
... | identifier_body |
picklemain.py | """
Extensions to pickle allowing items in __main__ to be saved.
"""
# CEBALERT: move into snapshots.py?
import new
import pickle
import types
import __main__
from StringIO import StringIO
import copy
def _name_is_main(obj):
# CEBALERT: see IPython hack in commandline.py
return obj.__module__ == "__main__" ... |
self.pickler.dump(bytecode)
return {'pickled_bytecode':self.pickled_bytecode}
def __setstate__(self,state):
bytecode = pickle.load(StringIO(state['pickled_bytecode'].getvalue()))
for name,obj in bytecode.items():
print "%s restored from bytecode into __main__"%name
... | if isinstance(obj,types.FunctionType) or isinstance(obj,type):
# (could be extended to other types, I guess
if _name_is_main(obj):
#CB: how do I print out info via Parameterized?
print "%s is defined in __main__: saving bytecode."%n... | conditional_block |
picklemain.py | """
Extensions to pickle allowing items in __main__ to be saved.
"""
# CEBALERT: move into snapshots.py?
import new
import pickle
import types
import __main__
from StringIO import StringIO
import copy
def _name_is_main(obj):
# CEBALERT: see IPython hack in commandline.py
|
class PickleMain(object):
"""
Pickle support for types and functions defined in __main__.
When pickled, saves types and functions defined in __main__ by
value (i.e. as bytecode). When unpickled, loads previously saved
types and functions back into __main__.
"""
def _create_pickler(self)... | return obj.__module__ == "__main__" or obj.__module__ == "__mynamespace__" | identifier_body |
picklemain.py | """
Extensions to pickle allowing items in __main__ to be saved.
"""
# CEBALERT: move into snapshots.py?
import new
import pickle
import types
import __main__
from StringIO import StringIO
import copy
def _name_is_main(obj):
# CEBALERT: see IPython hack in commandline.py
return obj.__module__ == "__main__" ... | if getattr(new, obj.__name__, None) is obj:
# Types in 'new' module claim their module is '__builtin__' but are not actually there
save_global_byname(self, obj, 'new', obj.__name__)
elif _name_is_main(obj):
# Types in __main__ are saved by value
# Make sure we have a reference t... | random_line_split | |
picklemain.py | """
Extensions to pickle allowing items in __main__ to be saved.
"""
# CEBALERT: move into snapshots.py?
import new
import pickle
import types
import __main__
from StringIO import StringIO
import copy
def _name_is_main(obj):
# CEBALERT: see IPython hack in commandline.py
return obj.__module__ == "__main__" ... | (self, obj, main_dict=vars(__import__('__main__'))):
""" Special-case __main__.__dict__. Useful for a function's func_globals member. """
if obj is main_dict:
save_global_byname(self, obj, '__main__', '__dict__')
else:
return self.save_dict(obj)
#return pickle.Pickler.save_dict(self,... | save_module_dict | identifier_name |
ChartRequestPage.tsx | import * as React from 'react'
import { Lite, JavascriptMessage } from '@framework/Signum.Entities'
import { parseLite } from '@framework/Signum.Entities'
import * as AppContext from '@framework/AppContext'
import { ChartRequestModel, UserChartEntity } from '../Signum.Entities.Chart'
import * as ChartClient from '... | (cr: ChartRequestModel, uc?: Lite<UserChartEntity>) {
ChartClient.Encoder.chartPathPromise(cr, uc)
.then(path => AppContext.history.replace(path))
.done();
}
if (pair == null)
return null;
return (
<div>
{pair == null && <h2>
<span className="sf-entity-title">{J... | changeUrl | identifier_name |
ChartRequestPage.tsx | import * as React from 'react'
import { Lite, JavascriptMessage } from '@framework/Signum.Entities'
import { parseLite } from '@framework/Signum.Entities'
import * as AppContext from '@framework/AppContext'
import { ChartRequestModel, UserChartEntity } from '../Signum.Entities.Chart'
import * as ChartClient from '... | import { QueryString } from '@framework/QueryString'
interface ChartRequestPageProps extends RouteComponentProps<{ queryName: string; }> {
}
export default React.memo(function ChartRequestPage(p: ChartRequestPageProps) {
const [pair, setPair] = useStateWithPromise<{ chartRequest: ChartRequestModel; userCh... | import ChartRequestView from './ChartRequestView'
import { RouteComponentProps } from 'react-router'
import { useStateWithPromise } from '@framework/Hooks'
| random_line_split |
ChartRequestPage.tsx | import * as React from 'react'
import { Lite, JavascriptMessage } from '@framework/Signum.Entities'
import { parseLite } from '@framework/Signum.Entities'
import * as AppContext from '@framework/AppContext'
import { ChartRequestModel, UserChartEntity } from '../Signum.Entities.Chart'
import * as ChartClient from '... |
if (pair == null)
return null;
return (
<div>
{pair == null && <h2>
<span className="sf-entity-title">{JavascriptMessage.loading.niceToString()}</span>
</h2 >}
{pair &&
<ChartRequestView
chartRequest={pair.chartRequest}
userChart={pair.us... | {
ChartClient.Encoder.chartPathPromise(cr, uc)
.then(path => AppContext.history.replace(path))
.done();
} | identifier_body |
populate_healer.rs | PRESERVE_STATE_RATIO: usize = 10_000;
/// PRESERVE_STATE_RATIO should be divisible by CHUNK_SIZE as otherwise progress
/// reporting will be broken
const INIT_COUNT_VALUE: usize = 0;
const FLAT_NAMESPACE_PREFIX: &str = "flat/";
/// Configuration options
struct Config {
db_address: String,
mysql_options: Mysq... | (fb: FacebookInit) -> Result<Config, Error> {
let app = args::MononokeAppBuilder::new("populate healer queue")
.build()
.about("Populate blobstore queue from existing key source")
.arg(
Arg::with_name("storage-id")
.long("storage-id")
.short("S")
... | parse_args | identifier_name |
populate_healer.rs | ERVE_STATE_RATIO: usize = 10_000;
/// PRESERVE_STATE_RATIO should be divisible by CHUNK_SIZE as otherwise progress
/// reporting will be broken
const INIT_COUNT_VALUE: usize = 0;
const FLAT_NAMESPACE_PREFIX: &str = "flat/";
/// Configuration options
struct Config {
db_address: String,
mysql_options: MysqlOpti... |
}
fn parse_args(fb: FacebookInit) -> Result<Config, Error> {
let app = args::MononokeAppBuilder::new("populate healer queue")
.build()
.about("Populate blobstore queue from existing key source")
.arg(
Arg::with_name("storage-id")
.long("storage-id")
... | {
Self {
init_range: (*state.init_range).clone(),
current_range: (*state.current_range).clone(),
}
} | identifier_body |
populate_healer.rs | PRESERVE_STATE_RATIO: usize = 10_000;
/// PRESERVE_STATE_RATIO should be divisible by CHUNK_SIZE as otherwise progress
/// reporting will be broken
const INIT_COUNT_VALUE: usize = 0;
const FLAT_NAMESPACE_PREFIX: &str = "flat/";
/// Configuration options
struct Config {
db_address: String,
mysql_options: Mysq... | started_at: Instant,
readonly_storage: bool,
}
/// State used to resume iteration in case of restart
#[derive(Debug, Clone)]
struct State {
count: usize,
init_range: Arc<BlobstoreKeyParam>,
current_range: Arc<BlobstoreKeyParam>,
}
impl State {
fn from_init(init_range: Arc<BlobstoreKeyParam>) -... | ctx: CoreContext,
state_key: Option<String>,
dry_run: bool, | random_line_split |
mbcharsetprober.py | # ####################### BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All ... |
def get_charset_name(self):
pass
def feed(self, aBuf):
aLen = len(aBuf)
for i in range(0, aLen):
codingState = self._mCodingSM.next_state(aBuf[i])
if codingState == constants.eError:
if constants._debug:
sys.stderr.write(self... | CharSetProber.reset(self)
if self._mCodingSM:
self._mCodingSM.reset()
if self._mDistributionAnalyzer:
self._mDistributionAnalyzer.reset()
self._mLastChar = [0, 0] | identifier_body |
mbcharsetprober.py | # ####################### BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All ... |
elif codingState == constants.eStart:
charLen = self._mCodingSM.get_current_charlen()
if i == 0:
self._mLastChar[1] = aBuf[0]
self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
else:
self._mD... | self._mState = constants.eFoundIt
break | conditional_block |
mbcharsetprober.py | # ####################### BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All ... | (self):
pass
def feed(self, aBuf):
aLen = len(aBuf)
for i in range(0, aLen):
codingState = self._mCodingSM.next_state(aBuf[i])
if codingState == constants.eError:
if constants._debug:
sys.stderr.write(self.get_charset_name()
... | get_charset_name | identifier_name |
mbcharsetprober.py | # ####################### BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All ... | from .charsetprober import CharSetProber
class MultiByteCharSetProber(CharSetProber):
def __init__(self):
CharSetProber.__init__(self)
self._mDistributionAnalyzer = None
self._mCodingSM = None
self._mLastChar = [0, 0]
def reset(self):
CharSetProber.reset(self)
... | random_line_split | |
player.ts | import { fwi } from "./fwi_core";
import { TextFormatVariable } from "./models/TextFormatVariable"
import { EmailMessage } from "./models/EmailMessage";
/**
* This is the Player class. It will probably be the most used class. It contains all player functions.
* It should be noted that all methods in this class are... | *
* @static
* @param {string} command_name The main command, sometimes includes folder path
* @param {string[]} arg_array Array of args to be submitted to the command
* @memberof Player
*/
static Command(command_name: string, arg_array: string[]): void {
let command = 'Player.Command(' + command... | /**
* Runs a shell command | random_line_split |
player.ts | import { fwi } from "./fwi_core";
import { TextFormatVariable } from "./models/TextFormatVariable"
import { EmailMessage } from "./models/EmailMessage";
/**
* This is the Player class. It will probably be the most used class. It contains all player functions.
* It should be noted that all methods in this class are... | (name: string): void {
fwi.RunScript('Player.ToggleVariable(' + name + ');');
}
/**
* Plays a template
*
* @static
* @param {string} name The name of the template to play
* @param {number} templateIndex The position of the desired template instance in the network overview
* @memberof Playe... | ToggleVariable | identifier_name |
player.ts | import { fwi } from "./fwi_core";
import { TextFormatVariable } from "./models/TextFormatVariable"
import { EmailMessage } from "./models/EmailMessage";
/**
* This is the Player class. It will probably be the most used class. It contains all player functions.
* It should be noted that all methods in this class are... |
/**
* Runs a shell command
*
* @static
* @param {string} command_name The main command, sometimes includes folder path
* @param {string[]} arg_array Array of args to be submitted to the command
* @memberof Player
*/
static Command(command_name: string, arg_array: string[]): void {
let com... | {
fwi.RunScript('Player.PlayTemplate(' + name + (templateIndex ? ', ' + templateIndex.toString() : '') + ');');
} | identifier_body |
client.py | #-*-coding: utf-8-*-
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest
from tornado.options import options
from functools import wraps
from tornado import escape
import tornado.ioloop
import base64
import time
import datetime
import json
from math import exp
AsyncHTTPClien... |
return wrap_func
return wrap_loop
class TornadoDataRequest(HTTPRequest):
def __init__(self, url, **kwargs):
super(TornadoDataRequest, self).__init__(url, **kwargs)
self.auth_username = options.username
self.auth_password = options.password
self.user_agent = "Tornado-da... | options.logger.info("function %r start at %d" %
(func.__name__, int(time.time())))
try:
yield func(*args, **kwargs)
except Exception, e:
options.logger.error("function %r error: %s" %
(func.__nam... | identifier_body |
client.py | #-*-coding: utf-8-*-
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest
from tornado.options import options
from functools import wraps
from tornado import escape
import tornado.ioloop
import base64
import time
import datetime
import json
from math import exp
AsyncHTTPClien... |
else:
raise gen.Return(resp)
@gen.coroutine
def update_file(gist_url, filename, data):
try:
body = json.dumps({
"description": "update file at utctime %s" %
datetime.datetime.utcfromtimestamp(time.time()),
"files": {
filename:... | resp = escape.json_decode(resp.body)
sha = resp["sha"]
body = json.dumps({
"message": message,
"content": base64.b64encode(json.dumps(data)),
"committer": {"name": "cloudaice", "email": "cloudaice@163.com"},
"sha": sha
})
resp = yield PutPa... | conditional_block |
client.py | #-*-coding: utf-8-*-
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest
from tornado.options import options
from functools import wraps
from tornado import escape
import tornado.ioloop
import base64
import time
import datetime
import json
from math import exp
AsyncHTTPClien... | (func):
@wraps(func)
def wrap_func(*args, **kwargs):
func(*args, **kwargs)
tornado.ioloop.IOLoop.instance().add_timeout(
datetime.timeelta(milliseconds=delta),
wrap_func)
return wrap_func
return wrap_loop
def sync_loop_call(delta=60 *... | wrap_loop | identifier_name |
client.py | #-*-coding: utf-8-*-
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError, HTTPRequest
from tornado.options import options
from functools import wraps
from tornado import escape
import tornado.ioloop
import base64
import time
import datetime
import json
from math import exp
AsyncHTTPClien... | tornado.ioloop.IOLoop.instance().add_timeout(
datetime.timedelta(milliseconds=delta),
wrap_func)
return wrap_func
return wrap_loop
class TornadoDataRequest(HTTPRequest):
def __init__(self, url, **kwargs):
super(TornadoDataRequest, self).__init__(url,... | options.logger.error("function %r error: %s" %
(func.__name__, e))
options.logger.info("function %r end at %d" %
(func.__name__, int(time.time()))) | random_line_split |
UtilsFileManager.js | $('#modalUploader').on('show.bs.modal', function (event) {
var uploader = new qq.FileUploaderBasic({
element: document.getElementById('file-uploader-demo1'),
button: document.getElementById('areaSubir'), | multiple: false,
onComplete: function (id, fileName, responseJSON) {
$.gritter.add({
title: 'Upload file',
text: responseJSON.message
});
},
onSubmit: function (id, fileName) {
var strHtml = "<li>" + fileName + "</li>";... | action: '/Files/Upload',
params: { ruta: $('#RutaActual').val() },
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'], | random_line_split |
UtilsFileManager.js | $('#modalUploader').on('show.bs.modal', function (event) {
var uploader = new qq.FileUploaderBasic({
element: document.getElementById('file-uploader-demo1'),
button: document.getElementById('areaSubir'),
action: '/Files/Upload',
params: { ruta: $('#RutaActual').val() },
allo... | Ruta) {
if (confirm("Are you sure that want to delete this file?")) {
$.gritter.add({
title: 'Delete file',
text: "File deleted"
});
$("#ArchivoParaEliminar").val(pRuta);
AbrirCarpeta($("#RutaActual").val());
}
}
function SubirNivel() {
if ($("#Tien... | iminarArchivo(p | identifier_name |
UtilsFileManager.js | $('#modalUploader').on('show.bs.modal', function (event) {
var uploader = new qq.FileUploaderBasic({
element: document.getElementById('file-uploader-demo1'),
button: document.getElementById('areaSubir'),
action: '/Files/Upload',
params: { ruta: $('#RutaActual').val() },
allo... |
function SubirNivel() {
if ($("#TieneSuperior").val() == "1") {
var strRutaAnterior = $("#RutaSuperior").val();
AbrirRuta(strRutaAnterior);
}
}
function IrInicio() {
AbrirRuta($("#RutaRaiz").val());
}
function AbrirDialogoArchivo() {
$("#modalUploader").modal();
}
function getPar... | $.gritter.add({
title: 'Delete file',
text: "File deleted"
});
$("#ArchivoParaEliminar").val(pRuta);
AbrirCarpeta($("#RutaActual").val());
}
} | conditional_block |
UtilsFileManager.js | $('#modalUploader').on('show.bs.modal', function (event) {
var uploader = new qq.FileUploaderBasic({
element: document.getElementById('file-uploader-demo1'),
button: document.getElementById('areaSubir'),
action: '/Files/Upload',
params: { ruta: $('#RutaActual').val() },
allo... | unction IrInicio() {
AbrirRuta($("#RutaRaiz").val());
}
function AbrirDialogoArchivo() {
$("#modalUploader").modal();
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
... | if ($("#TieneSuperior").val() == "1") {
var strRutaAnterior = $("#RutaSuperior").val();
AbrirRuta(strRutaAnterior);
}
}
f | identifier_body |
stats.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (self) -> f64 {
if self.len() == 0 {
0.0
} else {
let mean = self.mean();
let mut v = 0.0;
for self.each |s| {
let x = *s - mean;
v += x*x;
}
v/(self.len() as f64)
}
}
fn std_dev(self... | var | identifier_name |
stats.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn median_abs_dev(self) -> f64 {
let med = self.median();
let abs_devs = self.map(|v| num::abs(med - *v));
abs_devs.median()
}
fn median_abs_dev_pct(self) -> f64 {
(self.median_abs_dev() / self.median()) * 100.0
}
}
| {
(self.std_dev() / self.mean()) * 100.0
} | identifier_body |
stats.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
let mean = self.mean();
let mut v = 0.0;
for self.each |s| {
let x = *s - mean;
v += x*x;
}
v/(self.len() as f64)
}
}
fn std_dev(self) -> f64 {
f64::sqrt(self.var())
}
fn std_dev_pct(sel... | {
0.0
} | conditional_block |
stats.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | } |
fn median_abs_dev_pct(self) -> f64 {
(self.median_abs_dev() / self.median()) * 100.0
} | random_line_split |
configuration.py | # coding:utf-8
"""
Author : qbeenslee
Created : 2014/12/12
"""
import re
# 客户端ID号
CLIENT_ID = "TR5kVmYeMEh9M"
'''
传输令牌格式
加密方式$迭代次数$盐$结果串
举个栗子:
====start====
md5$23$YUXQ_-2GfwhzVpt5IQWp$3ebb6e78bf7d0c1938578855982e2b1c
====end====
'''
MATCH_PWD = r"md5\$(\d\d)\$([a-zA-Z0-9_\-]{20})\$([a-f0-9]{32}... | THUMB_SIZE_NORMAL = {'w': 480, 'h': 480, 'thumb': 'n'}
THUMB_SIZE_LARGE = {'w': 3000, 'h': 3000, 'thumb': 'l'}
THUMB_SIZE_ORIGIN = {'w': 0, 'h': 0, 'thumb': 'r'}
MAX_SHARE_DESCRIPTION_SIZE = 140
NOW_ANDROID_VERSION_CODE = 7
NOW_VERSION_DOWNLOAD_URL = "/static/download/nepenthes-beta0.9.3.apk"
MAX_RAND_EMAIL... | THUMB_SIZE_SMALL = {'w': 100, 'h': 100, 'thumb': 's'}
| random_line_split |
token.rs | #[derive(Clone, Debug, PartialEq)]
pub enum Token {
UseKeyword,
LetKeyword,
ForKeyword,
InKeyword,
BindKeyword,
AsKeyword,
WhereKeyword,
ToKeyword,
QueryKeyword,
SetKeyword,
DeleteKeyword,
UniqueKeyword,
AndKeyword,
ComponentKeyword,
RouteKeyword,
Store... | OpenParen,
CloseParen,
Dot,
Comma,
Equals,
Colon,
Semi,
Bang,
Plus,
Minus,
Mul,
Div,
Identifier(String),
LiteralNumber(i32),
LiteralString(String),
LiteralBool(bool),
VariableReference(String),
} | Pipe,
OpenBrace,
CloseBrace,
OpenBracket,
CloseBracket, | random_line_split |
token.rs | #[derive(Clone, Debug, PartialEq)]
pub enum | {
UseKeyword,
LetKeyword,
ForKeyword,
InKeyword,
BindKeyword,
AsKeyword,
WhereKeyword,
ToKeyword,
QueryKeyword,
SetKeyword,
DeleteKeyword,
UniqueKeyword,
AndKeyword,
ComponentKeyword,
RouteKeyword,
StoreKeyword,
ActionKeyword,
ExternKeyword,
... | Token | identifier_name |
hash.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | setString(key: string, value: string, options?: SetStringOption): void {
this.tfStorage.tf_storage.setString(key, value, options);
}
getPluginId(): string {
return this.getString(TAB);
}
setPluginId(pluginId: string, options?: SetStringOption): void {
this.setString(TAB, pluginId, options);
}
... | getString(key: string): string {
return this.tfStorage.tf_storage.getString(key);
}
| random_line_split |
hash.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | implements DeepLinkerInterface {
private readonly tfStorage: TfStorageElement;
constructor() {
this.tfStorage = document.createElement('tf-storage');
const tfGlobals = document.createElement('tf-globals');
// Note: `migrateLegacyURLScheme()` must be called before `setUseHash`, so
// that tfStorag... | HashDeepLinker | identifier_name |
hash.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... |
setString(key: string, value: string, options?: SetStringOption): void {
this.tfStorage.tf_storage.setString(key, value, options);
}
getPluginId(): string {
return this.getString(TAB);
}
setPluginId(pluginId: string, options?: SetStringOption): void {
this.setString(TAB, pluginId, options);
... | {
return this.tfStorage.tf_storage.getString(key);
} | identifier_body |
category_test.ts | /**
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... | }); | Got Response 200: Ok.
Class Distillery: Did not add [(source https://github.com/schemaorg/schemaorg/issues/743),(category \\"issue-743\\"),(label \\"Distillery\\")]
"
`); | random_line_split |
20160603120209_c9218e757bc_rename_admin_role_from_ggrc_admin_to_.py | # Copyright (C) 2017 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Rename admin role from gGRC Admin to Administrator.
Create Date: 2016-06-03 12:02:09.438599
"""
from alembic import op
import sqlalchemy as sa
from sqlalch... | ():
op.execute(roles_table.update()
.where(roles_table.c.name == 'Administrator')
.values(name='gGRC Admin',
description='gGRC System Administrator with super-user '
'privileges'))
| downgrade | identifier_name |
20160603120209_c9218e757bc_rename_admin_role_from_ggrc_admin_to_.py | # Copyright (C) 2017 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Rename admin role from gGRC Admin to Administrator.
Create Date: 2016-06-03 12:02:09.438599
"""
from alembic import op
import sqlalchemy as sa
from sqlalch... |
def downgrade():
op.execute(roles_table.update()
.where(roles_table.c.name == 'Administrator')
.values(name='gGRC Admin',
description='gGRC System Administrator with super-user '
'privileges')) | description='System Administrator with super-user '
'privileges'))
| random_line_split |
20160603120209_c9218e757bc_rename_admin_role_from_ggrc_admin_to_.py | # Copyright (C) 2017 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Rename admin role from gGRC Admin to Administrator.
Create Date: 2016-06-03 12:02:09.438599
"""
from alembic import op
import sqlalchemy as sa
from sqlalch... | op.execute(roles_table.update()
.where(roles_table.c.name == 'Administrator')
.values(name='gGRC Admin',
description='gGRC System Administrator with super-user '
'privileges')) | identifier_body | |
runner.js | /*
* grunt-phantomcss
* https://github.com/micahgodbolt/grunt-phantomcss
*
* Copyright (c) 2013 Chris Gladd
* Copyright (c) since 2014 Anselm Hannemann
* Copyright (c) since 2015 Micah Godbolt
*
* Licensed under the MIT license.
*/
'use-strict';
// Get node fileSystem module and define the separator module
var fs = r... | onPass: function(test) {
sendMessage('onPass', test);
},
onTimeout: function(test) {
sendMessage('onTimeout', test);
},
onComplete: function(allTests, noOfFails, noOfErrors) {
sendMessage('onComplete', allTests, noOfFails, noOfErrors);
},
fileNameGetter: function(root, filename) {
var name... | mismatchTolerance: args.mismatchTolerance, // defaults to 0.05
onFail: function(test) {
sendMessage('onFail', test);
}, | random_line_split |
runner.js | /*
* grunt-phantomcss
* https://github.com/micahgodbolt/grunt-phantomcss
*
* Copyright (c) 2013 Chris Gladd
* Copyright (c) since 2014 Anselm Hannemann
* Copyright (c) since 2015 Micah Godbolt
*
* Licensed under the MIT license.
*/
'use-strict';
// Get node fileSystem module and define the separator module
var fs = r... | else {
return name + '.png';
}
},
});
casper.start();
// Run the test scenarios
args.test.forEach(function(testSuite) {
phantom.casperTest = true;
phantom.rootUrl = args.rootUrl;
casper.then(function() {
phantomcss.pathToTest = path.dirname(testSuite) + '/';
});
require(testSuite);
casper.... | {
return name + '.diff.png';
} | conditional_block |
NodeContent.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) | } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsShallo... | { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } | conditional_block |
NodeContent.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va... | key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props;
var node = _props.node;
var metadata = _props.metadata;
var depth = _props.depth;
var type = node.type;
var name = node.name;
var path = node.path;
var expanded = metadata... | random_line_split | |
NodeContent.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va... | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn'... | _interopRequireDefault | identifier_name |
NodeContent.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("va... |
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enum... | { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } | identifier_body |
OnSelect.tsx | import React, { ReactText, useState } from 'react';
import { Grommet, Box, DataTable, Meter, Text } from 'grommet';
import { grommet } from 'grommet/themes';
import { ColumnConfig } from '../..';
// This story uses TypeScript
const amountFormatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: '... | }; |
export default {
title: 'Visualizations/DataTable/OnSelect', | random_line_split |
bilock.rs | #![feature(test)]
#[cfg(feature = "bilock")]
mod bench {
use futures::executor::LocalPool;
use futures::task::{Context, Waker};
use futures_util::lock::BiLock;
use futures_util::lock::BiLockAcquire;
use futures_util::lock::BiLockAcquired;
use futures_util::task::ArcWake;
use std::sync::Arc... | y.release_lock(y_guard);
}
(x, y)
})
}
} | let y_guard = match y.poll_next(&mut waker) {
Ok(Poll::Ready(Some(guard))) => guard,
_ => panic!(),
};
| random_line_split |
bilock.rs | #![feature(test)]
#[cfg(feature = "bilock")]
mod bench {
use futures::executor::LocalPool;
use futures::task::{Context, Waker};
use futures_util::lock::BiLock;
use futures_util::lock::BiLockAcquire;
use futures_util::lock::BiLockAcquired;
use futures_util::task::ArcWake;
use std::sync::Arc... | (b: &mut Bencher) {
let pool = LocalPool::new();
let mut exec = pool.executor();
let waker = notify_noop();
let mut map = task::LocalMap::new();
let mut waker = task::Context::new(&mut map, &waker, &mut exec);
b.iter(|| {
let (x, y) = BiLock::new(1);
... | lock_unlock | identifier_name |
xhr_backend.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Injectable } from '@angular/core';
import { __platform_browser_private__ } from '@angular/platform-browser';... | (_cookieName, _headerName) {
if (_cookieName === void 0) { _cookieName = 'XSRF-TOKEN'; }
if (_headerName === void 0) { _headerName = 'X-XSRF-TOKEN'; }
this._cookieName = _cookieName;
this._headerName = _headerName;
}
CookieXSRFStrategy.prototype.configureRequest = function (req) ... | CookieXSRFStrategy | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.