file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
network.py | # coding=utf-8
"""
The NetworkCollector class collects metrics on network interface usage
using /proc/net/dev.
#### Dependencies
* /proc/net/dev
"""
import diamond.collector
from diamond.collector import str_to_bool
import diamond.convertor
import os
import re
try:
import psutil
except ImportError:
psuti... | """
Collect network interface stats.
"""
# Initialize results
results = {}
if os.access(self.PROC, os.R_OK):
# Open File
file = open(self.PROC)
# Build Regular Expression
greed = ''
if str_to_bool(self.config['greedy'... | identifier_body | |
tut05_derived_objects.py | """
Tutorial - Object inheritance
You are free to derive your request handler classes from any base
class you wish. In most real-world applications, you will probably
want to create a central base class used for all your pages, which takes
care of things like printing a common page header and footer.
"""
import cherr... | (Page):
# Different title for this page
title = 'Tutorial 5'
def __init__(self):
# create a subpage
self.another = AnotherPage()
def index(self):
# Note that we call the header and footer methods inherited
# from the Page class!
return self.header() + ''... | HomePage | identifier_name |
tut05_derived_objects.py | """
Tutorial - Object inheritance
You are free to derive your request handler classes from any base
class you wish. In most real-world applications, you will probably
want to create a central base class used for all your pages, which takes
care of things like printing a common page header and footer.
"""
import cherr... |
index.exposed = True
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to Hell... | return self.header() + '''
<p>
And this is the amazing second page!
</p>
''' + self.footer() | identifier_body |
tut05_derived_objects.py | """
Tutorial - Object inheritance
You are free to derive your request handler classes from any base
class you wish. In most real-world applications, you will probably
want to create a central base class used for all your pages, which takes
care of things like printing a common page header and footer.
"""
import cherr... | # to call header or footer directly; instead, we'll call them from
# within the actually exposed handler methods defined in this
# class' subclasses.
class HomePage(Page):
# Different title for this page
title = 'Tutorial 5'
def __init__(self):
# create a subpage
self.anot... | random_line_split | |
tut05_derived_objects.py | """
Tutorial - Object inheritance
You are free to derive your request handler classes from any base
class you wish. In most real-world applications, you will probably
want to create a central base class used for all your pages, which takes
care of things like printing a common page header and footer.
"""
import cherr... | cherrypy.tree.mount(HomePage(), config=tutconf) | conditional_block | |
push.js | /* ----------------------------------
* PUSH v2.0.0
* Licensed under The MIT License
* inspired by chris's jquery.pjax.js
* http://opensource.org/licenses/MIT
* ---------------------------------- */
!function () {
var noop = function () {};
// Pushstate cacheing
// ==================
var isScrolling;
... | () {
swap.removeEventListener('webkitTransitionEnd', slideEnd);
swap.classList.remove('sliding', 'sliding-in');
swap.classList.remove(swapDirection);
container.parentNode.removeChild(container);
complete && complete();
}
}
};
var triggerStateChange = function () {
... | slideEnd | identifier_name |
push.js | /* ----------------------------------
* PUSH v2.0.0
* Licensed under The MIT License
* inspired by chris's jquery.pjax.js
* http://opensource.org/licenses/MIT
* ---------------------------------- */
!function () {
var noop = function () {};
// Pushstate cacheing
// ==================
var isScrolling;
... |
}
if (/slide/.test(transition)) {
container.offsetWidth; // force reflow
swapDirection = enter ? 'right' : 'left'
containerDirection = enter ? 'left' : 'right'
container.classList.add(containerDirection);
swap.classList.remove(swapDirection);
swap.addEventListener('web... | {
swap.removeEventListener('webkitTransitionEnd', fadeSwapEnd);
container.parentNode.removeChild(container);
swap.classList.remove('fade');
swap.classList.remove('in');
complete && complete();
} | identifier_body |
push.js | /* ----------------------------------
* PUSH v2.0.0
* Licensed under The MIT License
* inspired by chris's jquery.pjax.js
* http://opensource.org/licenses/MIT
* ---------------------------------- */
!function () {
var noop = function () {};
// Pushstate cacheing
// ==================
var isScrolling;
... |
if (xhr && xhr.readyState < 4) {
xhr.onreadystatechange = noop;
xhr.abort()
}
xhr = new XMLHttpRequest();
xhr.open('GET', options.url, true);
xhr.setRequestHeader('X-PUSH', 'true');
xhr.onreadystatechange = function () {
if (options._timeout) clearTimeout(options._timeout);
... | options.container = options.container || options.transition ? document.querySelector('.content') : document.body;
for (key in bars) {
options[key] = options[key] || document.querySelector(bars[key]);
} | random_line_split |
cluster_grasslands.py | import scipy as sp
import hdda
from multiprocessing import Pool
import pickle
import muesli_functions as mf
# Convenient function
def ClusterGrasslands(id_,DB,bands,C):
# Read samples
|
if __name__ == '__main__':
# Parameters
DB = "../Data/grassland_id_2m.sqlite"
data = sp.loadtxt("/media/Data/Data/MUESLI/spectresPrairies/Res/nc_grasslands.csv",delimiter=',',dtype=sp.int16)
bands = 'band_0'
for b in xrange(1,221):
bands += ", band_{}".format(b)
for b in xrange(259,3... | X = mf.readSamplesId(DB,id_,bands)
# L1 Normalization
X /= X.sum(axis=1)[:,sp.newaxis]
print("Process Grasslands {0}, number of samples {1}, number of classes {2}".format(id_,X.shape[0],C))
# Run HDDA
models, icl = [], []
for rep in xrange(1): # Do several init
param = {'th':0.1,'tol'... | identifier_body |
cluster_grasslands.py | import scipy as sp
import hdda
from multiprocessing import Pool
import pickle
import muesli_functions as mf
# Convenient function
def ClusterGrasslands(id_,DB,bands,C):
# Read samples
X = mf.readSamplesId(DB,id_,bands)
# L1 Normalization
X /= X.sum(axis=1)[:,sp.newaxis]
print("Process Grasslands ... |
# Iteration over the ID
pool = Pool(processes=4)
[pool.apply_async(ClusterGrasslands,(id_,DB,bands,C,)) for id_,C in data]
pool.close()
pool.join()
| bands += ", band_{}".format(b) | conditional_block |
cluster_grasslands.py | import scipy as sp
import hdda
from multiprocessing import Pool
import pickle
import muesli_functions as mf
# Convenient function
def ClusterGrasslands(id_,DB,bands,C): |
print("Process Grasslands {0}, number of samples {1}, number of classes {2}".format(id_,X.shape[0],C))
# Run HDDA
models, icl = [], []
for rep in xrange(1): # Do several init
param = {'th':0.1,'tol':0.0001,'random_state':rep,'C':C}
model_ = hdda.HDGMM(model='M4')
conv = model_.... | # Read samples
X = mf.readSamplesId(DB,id_,bands)
# L1 Normalization
X /= X.sum(axis=1)[:,sp.newaxis] | random_line_split |
cluster_grasslands.py | import scipy as sp
import hdda
from multiprocessing import Pool
import pickle
import muesli_functions as mf
# Convenient function
def | (id_,DB,bands,C):
# Read samples
X = mf.readSamplesId(DB,id_,bands)
# L1 Normalization
X /= X.sum(axis=1)[:,sp.newaxis]
print("Process Grasslands {0}, number of samples {1}, number of classes {2}".format(id_,X.shape[0],C))
# Run HDDA
models, icl = [], []
for rep in xrange(1): # Do seve... | ClusterGrasslands | identifier_name |
test__locale.py | from _locale import (setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error)
try:
from _locale import (RADIXCHAR, THOUSEP, nl_langinfo)
except ImportError:
nl_langinfo = None
import codecs
import locale
import sys
import unittest
from platform import uname
if uname().system == "Darwin":
maj, min, mic ... |
if __name__ == '__main__':
unittest.main()
| self.skipTest('no suitable locales') | conditional_block |
test__locale.py | from _locale import (setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error)
try:
from _locale import (RADIXCHAR, THOUSEP, nl_langinfo)
except ImportError:
nl_langinfo = None
import codecs
import locale
import sys
import unittest
from platform import uname
if uname().system == "Darwin":
maj, min, mic ... |
def tearDown(self):
setlocale(LC_ALL, self.oldlocale)
# Want to know what value was calculated, what it was compared against,
# what function was used for the calculation, what type of data was used,
# the locale that was supposedly set, and the actual locale that is set.
lc_numeric_err_m... | self.oldlocale = setlocale(LC_ALL) | identifier_body |
test__locale.py | from _locale import (setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error)
try:
from _locale import (RADIXCHAR, THOUSEP, nl_langinfo)
except ImportError:
nl_langinfo = None
import codecs
import locale
import sys
import unittest
from platform import uname
if uname().system == "Darwin":
maj, min, mic ... | finally:
locale.setlocale(locale.LC_ALL, old_locale)
# Workaround for MSVC6(debug) crash bug
if "MSC v.1200" in sys.version:
def accept(loc):
a = loc.split(".")
return not(len(a) == 2 and len(a[-1]) >= 9)
candidate_locales = [loc for loc in candidate_... | locales.append(loc)
candidate_locales = locales | random_line_split |
test__locale.py | from _locale import (setlocale, LC_ALL, LC_CTYPE, LC_NUMERIC, localeconv, Error)
try:
from _locale import (RADIXCHAR, THOUSEP, nl_langinfo)
except ImportError:
nl_langinfo = None
import codecs
import locale
import sys
import unittest
from platform import uname
if uname().system == "Darwin":
maj, min, mic ... | ():
global candidate_locales
# Issue #13441: Skip some locales (e.g. cs_CZ and hu_HU) on Solaris to
# workaround a mbstowcs() bug. For example, on Solaris, the hu_HU locale uses
# the locale encoding ISO-8859-2, the thousauds separator is b'\xA0' and it is
# decoded as U+30000020 (an invalid charact... | setUpModule | identifier_name |
delugePostProcess.py | #!/usr/bin/env python
import os
import sys
from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr, radarr
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
from deluge_client import DelugeRPCClient
import logging
from logging.config import fileConfig
logpath = '/var/log/sic... |
elif (category == categories[5]):
log.info("Bypassing any further processing as per category.")
if delete_dir:
if os.path.exists(delete_dir):
try:
os.rmdir(delete_dir)
log.debug("Successfully removed tempoary directory %s." % delete_dir)
except:
log.exceptio... | log.info("Passing %s directory to Sickrage." % path)
autoProcessTVSR.processEpisode(path, settings) | conditional_block |
delugePostProcess.py | #!/usr/bin/env python
import os
import sys
from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr, radarr
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
from deluge_client import DelugeRPCClient
import logging
from logging.config import fileConfig
logpath = '/var/log/sic... | delete_dir = settings.output_dir
converter = MkvtoMp4(settings)
for filename in files:
inputfile = os.path.join(path, filename)
if MkvtoMp4(settings).validSource(inputfile):
log.info("Converting file %s at location %s." % (inputfile, settings.output_dir))
try:
... | os.mkdir(settings.output_dir) | random_line_split |
main.js | #!/usr/bin/env node
'use strict'; | const path = require('path');
const assert = require('assert');
const utils = require('../utils.js');
const fetch = require('pkg-fetch');
assert(!module.parent);
assert(__dirname === process.cwd());
const host = 'node' + process.version.match(/^v(\d+)/)[1];
const target = process.argv[2] || host;
let right;
fetch.n... | random_line_split | |
models.py | from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from base.models import ModelloSemplice
from base.tratti import ConMarcaTemporale
class Giudizio(ModelloSemplice, ConMarcaTemporale):
"""
R... |
else: # Altrimenti, ne registro uno nuovo
g = Giudizio(
oggetto=self,
positivo=positivo,
autore=autore
)
g.save()
@property
def giudizi_positivi(self):
"""
Restituisce il numero di giudizi positivi associa... | g.positivo = positivo | conditional_block |
models.py | from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from base.models import ModelloSemplice
from base.tratti import ConMarcaTemporale
class Giudizio(ModelloSemplice, ConMarcaTemporale):
"""
R... | return Persona.objects.none() | from anagrafica.models import Persona | random_line_split |
models.py | from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from base.models import ModelloSemplice
from base.tratti import ConMarcaTemporale
class Giudizio(ModelloSemplice, ConMarcaTemporale):
"""
R... | """
Aggiunge la possibilita' di aggiungere commenti ad
un oggetto.
"""
class Meta:
abstract = True
commenti = GenericRelation(
Commento,
related_query_name='%(class)s',
content_type_field='oggetto_tipo',
object_id_field='oggetto_id'
)
def commento_n... | identifier_body | |
models.py | from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from base.models import ModelloSemplice
from base.tratti import ConMarcaTemporale
class Giudizio(ModelloSemplice, ConMarcaTemporale):
"""
R... | :
verbose_name_plural = "Commenti"
app_label = "social"
abstract = False
permissions = (
("view_commento", "Can view commento"),
)
autore = models.ForeignKey("anagrafica.Persona", db_index=True, related_name="commenti", on_delete=models.CASCADE)
commento = mo... | Meta | identifier_name |
bootstrap-datepicker.it.js | /**
* Italian translation for bootstrap-datepicker
* Enrico Rubboli <rubboli@gmail.com>
*/
;(function($){ | months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
today: "Oggi",
weekStart: 1,
format: "dd/mm/yyyy"
};
}(jQuery)); | $.fn.datepicker.dates['it'] = {
days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"],
daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"], | random_line_split |
admin.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Admin model views for records."""
import json
from flask import flash
from flask... | return True
record_adminview = dict(
modelview=RecordMetadataModelView,
model=RecordMetadata,
category=_('Records')) | random_line_split | |
admin.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Admin model views for records."""
import json
from flask import flash
from flask... |
record = Record(model.json, model=model)
record.delete()
db.session.commit()
except SQLAlchemyError as e:
if not self.handle_view_exception(e):
flash(_('Failed to delete record. %(error)s', error=str(e)),
category='error')
... | return True | conditional_block |
admin.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Admin model views for records."""
import json
from flask import flash
from flask... | (ModelView):
"""Records admin model view."""
filter_converter = FilterConverter()
can_create = False
can_edit = False
can_delete = True
can_view_details = True
column_list = ('id', 'version_id', 'updated', 'created',)
column_details_list = ('id', 'version_id', 'updated', 'created', 'jso... | RecordMetadataModelView | identifier_name |
admin.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Admin model views for records."""
import json
from flask import flash
from flask... |
record_adminview = dict(
modelview=RecordMetadataModelView,
model=RecordMetadata,
category=_('Records'))
| """Delete a record."""
try:
if model.json is None:
return True
record = Record(model.json, model=model)
record.delete()
db.session.commit()
except SQLAlchemyError as e:
if not self.handle_view_exception(e):
flash... | identifier_body |
reflect.py | # -*- coding: utf-8 -*-
"""
Program for generating plantuml or dot format
of a database tables by connection string
\n\nDatabase connection string - http://goo.gl/3GpnE
"""
import operator
import string
from optparse import OptionParser
from sqlalchemy import create_engine, MetaData
from tsadisplay import describe, re... | help='Database URL (connection string)',
)
parser.add_option(
'-r', '--render', dest='render', default='dot',
choices=['plantuml', 'dot'],
help='Output format - plantuml or dot',
)
parser.add_option(
'-l', '--list', dest='list', action='store_true',
help... |
parser.add_option(
'-u', '--url', dest='url', | random_line_split |
reflect.py | # -*- coding: utf-8 -*-
"""
Program for generating plantuml or dot format
of a database tables by connection string
\n\nDatabase connection string - http://goo.gl/3GpnE
"""
import operator
import string
from optparse import OptionParser
from sqlalchemy import create_engine, MetaData
from tsadisplay import describe, re... | """Command for reflection database objects"""
parser = OptionParser(
version=__version__, description=__doc__,
)
parser.add_option(
'-u', '--url', dest='url',
help='Database URL (connection string)',
)
parser.add_option(
'-r', '--render', dest='render', default='dot... | identifier_body | |
reflect.py | # -*- coding: utf-8 -*-
"""
Program for generating plantuml or dot format
of a database tables by connection string
\n\nDatabase connection string - http://goo.gl/3GpnE
"""
import operator
import string
from optparse import OptionParser
from sqlalchemy import create_engine, MetaData
from tsadisplay import describe, re... |
if options.exclude:
tables -= set(map(string.strip, options.exclude.split(',')))
desc = describe(map(lambda x: operator.getitem(meta.tables, x), tables))
print(getattr(render, options.render)(desc))
| tables &= set(map(string.strip, options.include.split(','))) | conditional_block |
reflect.py | # -*- coding: utf-8 -*-
"""
Program for generating plantuml or dot format
of a database tables by connection string
\n\nDatabase connection string - http://goo.gl/3GpnE
"""
import operator
import string
from optparse import OptionParser
from sqlalchemy import create_engine, MetaData
from tsadisplay import describe, re... | (l, i):
try:
return tables[i]
except IndexError:
return ''
for i in range(0, len(tables), 2):
print(' {0}{1}{2}'.format(
_g(tables, i),
' ' * (38 - len(_g(tables, i))),
_g(tables, i + 1),
... | _g | identifier_name |
main.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![feature(auto_traits)]
#![deny(warnings)]
use crate::sync::SyncResult;
/// Mononoke Cross Repo sync job
///
/// This is a special job us... |
if !skip {
let (stats, res) = sync_single_bookmark_update_log(
&ctx,
&commit_syncer,
entry,
source_skiplist_index,
target_skiplist_index,
&common_pushrebase_bookmarks,
... | {
if !regex.is_match(entry.bookmark_name.as_str()) {
skip = true;
}
} | conditional_block |
main.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![feature(auto_traits)]
#![deny(warnings)]
use crate::sync::SyncResult;
/// Mononoke Cross Repo sync job
///
/// This is a special job us... | commit_syncer,
scuba_sample,
source_skiplist_index,
target_skiplist_index,
maybe_target_bookmark,
common_bookmarks,
)
.await
}
(ARG_TAIL, Some(sub_m)) => {
add_common_field... | random_line_split | |
main.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![feature(auto_traits)]
#![deny(warnings)]
use crate::sync::SyncResult;
/// Mononoke Cross Repo sync job
///
/// This is a special job us... | <
M: SyncedCommitMapping + Clone + 'static,
C: MutableCounters + Clone + Sync + 'static,
>(
ctx: &CoreContext,
commit_syncer: &CommitSyncer<M>,
mutable_counters: &C,
mut scuba_sample: MononokeScubaSampleBuilder,
common_pushrebase_bookmarks: &HashSet<BookmarkName>,
source_skiplist_index: ... | tail | identifier_name |
main.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![feature(auto_traits)]
#![deny(warnings)]
use crate::sync::SyncResult;
/// Mononoke Cross Repo sync job
///
/// This is a special job us... |
struct BackpressureParams {
backsync_repos: Vec<BlobRepo>,
wait_for_target_repo_hg_sync: bool,
}
impl BackpressureParams {
async fn new<'a>(
ctx: &CoreContext,
matches: &'a MononokeMatches<'a>,
sub_m: &'a ArgMatches<'a>,
) -> Result<Self, Error> {
let backsync_repos_id... | {
let matches = app.get_matches(fb)?;
let logger = matches.logger();
let ctx = CoreContext::new_with_logger(fb, logger.clone());
Ok((ctx, matches))
} | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
# generated from catkin/cmake/template/__init__.py.in
# keep symbol table as clean as possible by deleting all unnecessary symbols
from os import path as os_path
from sys import path as sys_path
from pkgutil import extend_path
__extended_path = "/home/pi/Documents/desenvolvimentoRos/src/tf2_r... |
del sys_path
__path__ = extend_path(__path__, __name__)
del extend_path
__execfiles = []
for p in __extended_path:
src_init_file = os_path.join(p, __name__ + '.py')
if os_path.isfile(src_init_file):
__execfiles.append(src_init_file)
else:
src_init_file = os_path.join(p, __name__, '__init_... | sys_path.insert(0, p)
del p | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
# generated from catkin/cmake/template/__init__.py.in
# keep symbol table as clean as possible by deleting all unnecessary symbols
from os import path as os_path
from sys import path as sys_path
from pkgutil import extend_path
__extended_path = "/home/pi/Documents/desenvolvimentoRos/src/tf2_r... | del __extended_path
for __execfile in __execfiles:
with open(__execfile, 'r') as __fh:
exec(__fh.read())
del __fh
del __execfile
del __execfiles | __execfiles.append(src_init_file)
del src_init_file
del p
del os_path | random_line_split |
DrawerItems.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { NavigationActions, StackActions, DrawerActions } from 'react-navigation';
import { Title, Text, TouchableRipple } from 'react-native-paper';
import MaterialIcons from 'react-native-vector-icons/MaterialIc... | backgroundColor: COLOR_DARK_BACKGROUND,
paddingTop: StatusBar.currentHeight
},
drawerSection: {
flexGrow: 1,
paddingTop: 15
},
footer: {
flexGrow: 0
},
footerWrapper: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
flexGrow: 0,
paddingTop: 15... | random_line_split | |
DrawerItems.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { NavigationActions, StackActions, DrawerActions } from 'react-navigation';
import { Title, Text, TouchableRipple } from 'react-native-paper';
import MaterialIcons from 'react-native-vector-icons/MaterialIc... | else if (this.props.state.sync.isSyncing && !newProps.state.sync.isSyncing) {
this._stopAnimation();
}
}
componentWillUnmount() {
this._stopAnimation();
}
render() {
let statusLabel;
if (this.props.state.sync.isConnected === false) {
statusLabel = browser.i18n.getMessage('statusL... | {
this._startAnimation();
} | conditional_block |
DrawerItems.js | import * as React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { NavigationActions, StackActions, DrawerActions } from 'react-navigation';
import { Title, Text, TouchableRipple } from 'react-native-paper';
import MaterialIcons from 'react-native-vector-icons/MaterialIc... | (props) {
const resetAction = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'LoginPanel' })],
});
props.navigation.dispatch(resetAction);
trackEvent('webext-button-disconnect');
}
class DrawerItems extends React.Component {
constructor(props) {
super(props);
... | navigateToLogin | identifier_name |
ksana.js | jsonp_handler({
"version": "1",
"build": 804,
"title": "kage-glyph-sample",
"minruntime": 1,
"baseurl": "http://rawgit.com/ksanaforge/kage-glyph-sample/master/",
"description": "",
"browserify": {
"external": [
"react",
"react-dom",
"react-addons-update",
"react-addons-pure-render-mixin",
"boots... | "2015-11-19T09:38:59.184Z",
"2015-11-19T09:25:40.856Z"
],
"date": "2015-11-19T09:39:00.175Z"
}) | "2015-11-05T10:01:21.203Z",
"2015-09-26T14:20:45.107Z",
"2015-10-15T10:26:00.967Z",
"2015-10-15T10:25:56.627Z", | random_line_split |
2_6_attraction.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 2-6: Attraction
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
mover: Mover,
attractor: Attractor,
}
struct Mover {
position: Point2,
velocity: Vector2,
acceleratio... |
}
fn stop_dragging(&mut self) {
self.dragging = false;
}
fn drag(&mut self, mx: f32, my: f32) {
if self.dragging {
self.position.x = mx + self.drag_offset.x;
self.position.y = my + self.drag_offset.y;
}
}
}
impl Mover {
fn new() -> Self {
... | {
self.roll_over = false;
} | conditional_block |
2_6_attraction.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 2-6: Attraction
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
mover: Mover,
attractor: Attractor,
}
struct Mover {
position: Point2,
velocity: Vector2,
acceleratio... |
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
} | let draw = app.draw();
draw.background().color(WHITE);
m.attractor.display(&draw);
m.mover.display(&draw); | random_line_split |
2_6_attraction.rs | // The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 2-6: Attraction
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
struct Model {
mover: Mover,
attractor: Attractor,
}
struct Mover {
position: Point2,
velocity: Vector2,
acceleratio... | (&mut self, mx: f32, my: f32) {
if self.dragging {
self.position.x = mx + self.drag_offset.x;
self.position.y = my + self.drag_offset.y;
}
}
}
impl Mover {
fn new() -> Self {
let position = pt2(80.0, 130.0);
let velocity = vec2(1.0, 0.0);
let acce... | drag | identifier_name |
middleware.py | # Copyright (c) 2008 Mikeal Rogers
#
# 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 agre... | def process_request(self, request):
global requestcontext
requestcontext = RequestContext(request)
requestcontext['is_secure'] = request.is_secure()
requestcontext['site'] = request.get_host()
requestcontext['REVISION'] = git.revision | identifier_body | |
middleware.py | # Copyright (c) 2008 Mikeal Rogers
#
# 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
# | #
# Unless required by applicable law or agreed to in writing, software
# distribuetd 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 the L... | # http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
middleware.py | # Copyright (c) 2008 Mikeal Rogers
#
# 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 agre... | (self, request):
global requestcontext
requestcontext = RequestContext(request)
requestcontext['is_secure'] = request.is_secure()
requestcontext['site'] = request.get_host()
requestcontext['REVISION'] = git.revision
| process_request | identifier_name |
index.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk from 'chalk';
import {bind as bindEach} from 'jest-each';
import {formatExecError} from 'jest-me... | if (typeof testName !== 'string') {
asyncError.message = `Invalid first argument, ${testName}. It must be a string.`;
throw asyncError;
}
if (fn === undefined) {
asyncError.message =
'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for ... | ) => void,
timeout?: number,
) => {
const asyncError = new ErrorWithStack(undefined, testFn);
| random_line_split |
build-config.js | /**
* @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license/
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time to build CKEditor again.
*
* If you would ... | 'pastefromword' : 1,
'pastetext' : 1,
'removeformat' : 1,
'resize' : 1,
'scayt' : 1,
'showborders' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tableselection' : 1,
'tabletools' : 1,
'toolbar' : 1,
'undo' : 1,
'uploadimage' : 1,
'wysiwygarea' : ... | 'pastefromlibreoffice' : 1, | random_line_split |
placehold-it.js | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'img',
attributeBindings: ['src'],
height: 100,
width: 100, |
format: undefined, // gif, jpg, jpeg, png
text: undefined,
src: Ember.computed('height', 'width', 'backgroundColor', 'textColor', 'format', function() {
// build url for placeholder image
var base = 'http://placehold.it/';
var src = base + this.get('width') + 'x' + this.get('height') + '/';
src += this.... |
backgroundColor: 'aaa',
textColor: '555', | random_line_split |
placehold-it.js | import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'img',
attributeBindings: ['src'],
height: 100,
width: 100,
backgroundColor: 'aaa',
textColor: '555',
format: undefined, // gif, jpg, jpeg, png
text: undefined,
src: Ember.computed('height', 'width', 'backgroundColor', 'textColor'... |
// check for custom placeholder text
if (this.get('text')) {
src += '&text=' + this.get('text');
}
return src;
})
});
| {
src += '.' + this.get('format');
} | conditional_block |
actionbarIos.js |
var args = arguments[0] || {};
function closeView (){
if(args.vp) |
if(args.reset)
{
var win = Alloy.createController('feed', 1).getView();
var t = Ti.UI.iPhone.AnimationStyle.CURL_UP;
win.open({transition:t});
} //else {
args.ventana.close();
//}
}
var backArrow = Ti.UI.createLabel({
color:'Gray',
text: '\u25c3',
});
$.current.text = args.title;
$.backArrow.add(bac... | {
args.vp.hide();
args.vp.release();
args.vp = null;
} | conditional_block |
actionbarIos.js |
var args = arguments[0] || {};
function | (){
if(args.vp){
args.vp.hide();
args.vp.release();
args.vp = null;
}
if(args.reset)
{
var win = Alloy.createController('feed', 1).getView();
var t = Ti.UI.iPhone.AnimationStyle.CURL_UP;
win.open({transition:t});
} //else {
args.ventana.close();
//}
}
var backArrow = Ti.UI.createLabel({
color:'Gr... | closeView | identifier_name |
actionbarIos.js | var args = arguments[0] || {};
function closeView (){
if(args.vp){
args.vp.hide(); | }
if(args.reset)
{
var win = Alloy.createController('feed', 1).getView();
var t = Ti.UI.iPhone.AnimationStyle.CURL_UP;
win.open({transition:t});
} //else {
args.ventana.close();
//}
}
var backArrow = Ti.UI.createLabel({
color:'Gray',
text: '\u25c3',
});
$.current.text = args.title;
$.backArrow.add(b... | args.vp.release();
args.vp = null; | random_line_split |
actionbarIos.js |
var args = arguments[0] || {};
function closeView () |
var backArrow = Ti.UI.createLabel({
color:'Gray',
text: '\u25c3',
});
$.current.text = args.title;
$.backArrow.add(backArrow);
if(args.title == 'Login')
{
$.bottomLogin.hide();
};
$.textBottom.text = 'Login';
if(Ti.App.Properties.getString('user_id') > 0)
{
$.textBottom.text = 'Logout';
}
$.bottomLogin.ad... | {
if(args.vp){
args.vp.hide();
args.vp.release();
args.vp = null;
}
if(args.reset)
{
var win = Alloy.createController('feed', 1).getView();
var t = Ti.UI.iPhone.AnimationStyle.CURL_UP;
win.open({transition:t});
} //else {
args.ventana.close();
//}
} | identifier_body |
config-store.js | /**
* @license
* v1.2.10-1
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2019 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https://github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
import { mergeMaps, objectToMap, jsS, PnPClientStorage } from '@pnp/common... | (provider) {
return new Promise((resolve, reject) => {
provider.getConfiguration().then((value) => {
this._settings = mergeMaps(this._settings, objectToMap(value));
resolve();
}).catch(reject);
});
}
/**
* Gets a value from th... | load | identifier_name |
config-store.js | /**
* @license
* v1.2.10-1
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2019 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https://github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
import { mergeMaps, objectToMap, jsS, PnPClientStorage } from '@pnp/common... |
throw Error("Cannot create a caching configuration provider since cache is not available.");
}
}
/**
* A configuration provider which loads configuration values from a SharePoint list
*
*/
class SPListConfigurationProvider {
/**
* Creates a new SharePoint list based configuration prov... | {
return pnpCache.session;
} | conditional_block |
config-store.js | /**
* @license
* v1.2.10-1
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2019 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https://github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
import { mergeMaps, objectToMap, jsS, PnPClientStorage } from '@pnp/common... | });
}
/**
* Gets a value from the configuration
*
* @param {string} key The key whose value we want to return. Returns null if the key does not exist
* @return {string} string value from the configuration
*/
get(key) {
return this._settings.get(key) || null;... | this._settings = mergeMaps(this._settings, objectToMap(value));
resolve();
}).catch(reject);
| random_line_split |
config-store.js | /**
* @license
* v1.2.10-1
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2019 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https://github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
import { mergeMaps, objectToMap, jsS, PnPClientStorage } from '@pnp/common... |
}
/**
* A configuration provider which loads configuration values from a SharePoint list
*
*/
class SPListConfigurationProvider {
/**
* Creates a new SharePoint list based configuration provider
* @constructor
* @param {string} webUrl Url of the SharePoint site, where the configuration ... | {
const pnpCache = new PnPClientStorage();
if ((pnpCache.local) && (pnpCache.local.enabled)) {
return pnpCache.local;
}
if ((pnpCache.session) && (pnpCache.session.enabled)) {
return pnpCache.session;
}
throw Error("Cannot create a caching ... | identifier_body |
app.js | import $ from 'jquery';
import SC from 'soundcloud';
import SoundCloudAudio from 'soundcloud-audio';
$(document).ready(function () {
const client_id = '4a39a5fc90a81d598101eeaf122056bc';
SC.initialize({
client_id : client_id
});
// TODO find a better way to stream soundcloud tracks
var scPlayer = new S... | });
scPlayer.play({streamUrl : `https://api.soundcloud.com/tracks/${url}/stream`});
$(this).addClass('playing');
} else {
scPlayer.stop();
$(this).removeClass('playing');
}
});
});
}); | $trackIcon.removeClass('playing');
} | random_line_split |
app.js | import $ from 'jquery';
import SC from 'soundcloud';
import SoundCloudAudio from 'soundcloud-audio';
$(document).ready(function () {
const client_id = '4a39a5fc90a81d598101eeaf122056bc';
SC.initialize({
client_id : client_id
});
// TODO find a better way to stream soundcloud tracks
var scPlayer = new S... | else {
scPlayer.stop();
$(this).removeClass('playing');
}
});
});
});
| {
$trackIcon.each(function () {
if ($trackIcon.hasClass('playing')) {
$trackIcon.removeClass('playing');
}
});
scPlayer.play({streamUrl : `https://api.soundcloud.com/tracks/${url}/stream`});
$(this).addClass('playing');
} | conditional_block |
san_db.py | #!/usr/bin/env python3
import os
import logging
from datetime import datetime
from settings import JSONDIR
from defs import load_data
from san_env import get_apps
debug_records_flag = False
def | (appname, relations):
apps = get_apps()
for filename, modelname, filters in relations:
records = load_data(os.path.join(JSONDIR, filename), [])
model = apps.get_model(app_label=appname, model_name=modelname)
if filters.get('before_delete_all'):
model.objects.all().delete()
... | save | identifier_name |
san_db.py | #!/usr/bin/env python3
import os
import logging
from datetime import datetime
from settings import JSONDIR
from defs import load_data
from san_env import get_apps
debug_records_flag = False
def save(appname, relations):
apps = get_apps()
for filename, modelname, filters in relations:
records = load_... |
else:
for record in records:
try:
model(**record).save()
except:
print('== {} =='.format(modelname))
for key in sorted(record.keys()):
print(key, record[key] if key in record else '')... | model.objects.bulk_create([model(**record) for record in records]) | conditional_block |
san_db.py | #!/usr/bin/env python3
import os
import logging
from datetime import datetime
from settings import JSONDIR
from defs import load_data
from san_env import get_apps
debug_records_flag = False
def save(appname, relations):
| apps = get_apps()
for filename, modelname, filters in relations:
records = load_data(os.path.join(JSONDIR, filename), [])
model = apps.get_model(app_label=appname, model_name=modelname)
if filters.get('before_delete_all'):
model.objects.all().delete()
elif filters.get('be... | identifier_body | |
san_db.py | #!/usr/bin/env python3
import os
import logging
from datetime import datetime
from settings import JSONDIR
from defs import load_data
from san_env import get_apps
debug_records_flag = False
def save(appname, relations):
apps = get_apps()
for filename, modelname, filters in relations:
records = load_... | model.objects.all().delete()
elif filters.get('before_delete'):
model.objects.filter(**filters['before_delete']).delete()
if debug_records_flag is False:
model.objects.bulk_create([model(**record) for record in records])
else:
for record in records... | model = apps.get_model(app_label=appname, model_name=modelname)
if filters.get('before_delete_all'): | random_line_split |
instrument.js | import difference from 'lodash/difference';
export const ActionTypes = {
PERFORM_ACTION: 'PERFORM_ACTION',
RESET: 'RESET',
ROLLBACK: 'ROLLBACK',
COMMIT: 'COMMIT',
SWEEP: 'SWEEP',
TOGGLE_ACTION: 'TOGGLE_ACTION',
JUMP_TO_STATE: 'JUMP_TO_STATE',
IMPORT_STATE: 'IMPORT_STATE'
};
/**
* Action creators to c... | () {
return { type: ActionTypes.SWEEP };
},
toggleAction(id) {
return { type: ActionTypes.TOGGLE_ACTION, id };
},
jumpToState(index) {
return { type: ActionTypes.JUMP_TO_STATE, index };
},
importState(nextLiftedState) {
return { type: ActionTypes.IMPORT_STATE, nextLiftedState };
}
};
c... | sweep | identifier_name |
instrument.js | import difference from 'lodash/difference';
export const ActionTypes = {
PERFORM_ACTION: 'PERFORM_ACTION',
RESET: 'RESET',
ROLLBACK: 'ROLLBACK',
COMMIT: 'COMMIT',
SWEEP: 'SWEEP',
TOGGLE_ACTION: 'TOGGLE_ACTION',
JUMP_TO_STATE: 'JUMP_TO_STATE',
IMPORT_STATE: 'IMPORT_STATE'
};
/**
* Action creators to c... | break;
}
case ActionTypes.JUMP_TO_STATE: {
// Without recomputing anything, move the pointer that tell us
// which state is considered the current one. Useful for sliders.
currentStateIndex = liftedAction.index;
// Optimization: we know the history has not changed.
... | skippedActionIds = skippedActionIds.filter(id => id !== actionId);
}
// Optimization: we know history before this action hasn't changed
minInvalidatedStateIndex = stagedActionIds.indexOf(actionId); | random_line_split |
instrument.js | import difference from 'lodash/difference';
export const ActionTypes = {
PERFORM_ACTION: 'PERFORM_ACTION',
RESET: 'RESET',
ROLLBACK: 'ROLLBACK',
COMMIT: 'COMMIT',
SWEEP: 'SWEEP',
TOGGLE_ACTION: 'TOGGLE_ACTION',
JUMP_TO_STATE: 'JUMP_TO_STATE',
IMPORT_STATE: 'IMPORT_STATE'
};
/**
* Action creators to c... | ,
getState() {
const state = unliftState(liftedStore.getState());
if (state !== undefined) {
lastDefinedState = state;
}
return lastDefinedState;
},
replaceReducer(nextReducer) {
liftedStore.replaceReducer(liftReducer(nextReducer));
}
};
}
/**
* Redux instrume... | {
liftedStore.dispatch(liftAction(action));
return action;
} | identifier_body |
instrument.js | import difference from 'lodash/difference';
export const ActionTypes = {
PERFORM_ACTION: 'PERFORM_ACTION',
RESET: 'RESET',
ROLLBACK: 'ROLLBACK',
COMMIT: 'COMMIT',
SWEEP: 'SWEEP',
TOGGLE_ACTION: 'TOGGLE_ACTION',
JUMP_TO_STATE: 'JUMP_TO_STATE',
IMPORT_STATE: 'IMPORT_STATE'
};
/**
* Action creators to c... |
}
return {
state: nextState,
error: nextError
};
}
/**
* Runs the reducer on invalidated actions to get a fresh computation log.
*/
function recomputeStates(
computedStates,
minInvalidatedStateIndex,
reducer,
committedState,
actionsById,
stagedActionIds,
skippedActionIds
) {
// Optimi... | {
console.error(err);
} | conditional_block |
elided-lifetime.rs | // aux-build:elided-lifetime.rs
//
// rust-lang/rust#75225
//
// Since Rust 2018 we encourage writing out <'_> explicitly to make it clear
// that borrowing is occuring. Make sure rustdoc is following the same idiom. | pub struct Ref<'a>(&'a u32);
type ARef<'a> = Ref<'a>;
// @has foo/fn.test1.html
// @matches - "Ref</a><'_>"
pub fn test1(a: &u32) -> Ref {
Ref(a)
}
// @has foo/fn.test2.html
// @matches - "Ref</a><'_>"
pub fn test2(a: &u32) -> Ref<'_> {
Ref(a)
}
// @has foo/fn.test3.html
// @matches - "Ref</a><... |
#![crate_name = "foo"]
| random_line_split |
elided-lifetime.rs | // aux-build:elided-lifetime.rs
//
// rust-lang/rust#75225
//
// Since Rust 2018 we encourage writing out <'_> explicitly to make it clear
// that borrowing is occuring. Make sure rustdoc is following the same idiom.
#![crate_name = "foo"]
pub struct Ref<'a>(&'a u32);
type ARef<'a> = Ref<'a>;
// @has foo/fn.test1.ht... | (a: &u32) -> ARef<'_> {
Ref(a)
}
// Ensure external paths in inlined docs also display elided lifetime
// @has foo/bar/fn.test5.html
// @matches - "Ref</a><'_>"
// @has foo/bar/fn.test6.html
// @matches - "Ref</a><'_>"
#[doc(inline)]
pub extern crate bar;
| test4 | identifier_name |
event_test.js | import { getEvent, eventMap } from '../../src/module/moveRow/event';
import { EMPTY_TPL_KEY } from '../../src/common/constants';
describe('drag', () => {
describe('getEvent', () => {
let events = null;
beforeEach(() => {
});
afterEach(() => {
events = null;
});
... | });
}); | describe('eventMap', () => {
it('基础验证', () => {
expect(eventMap).toEqual({});
}); | random_line_split |
run_bash.py | #!/usr/bin/env python3
#
# Copyright 2021 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | logging_format = '[%(levelname)s:%(filename)s:%(lineno)s] %(message)s'
logging.basicConfig(
level=logging.INFO, format=logging_format, datefmt='%H:%M:%S')
logging.warning('Calling a bash process during GN build. '
'Avoid doing this whenever possible.')
sys.exit(subprocess.call(sys.argv[1:... | conditional_block | |
run_bash.py | #!/usr/bin/env python3
#
# Copyright 2021 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | import sys
if __name__ == '__main__':
logging_format = '[%(levelname)s:%(filename)s:%(lineno)s] %(message)s'
logging.basicConfig(
level=logging.INFO, format=logging_format, datefmt='%H:%M:%S')
logging.warning('Calling a bash process during GN build. '
'Avoid doing this whenever possible.'... | import logging
import subprocess | random_line_split |
__number.py | from sys import version_info
try:
from collections.abc import Iterable, Container
except ImportError:
from collections import Iterable, Container
from pyvalid import accepts
from pyvalid.validators import AbstractValidator
class NumberValidator(AbstractValidator):
number_types = (int, float)
if vers... | (cls, val, number_type):
"""Checks if the number is of required data type.
Args:
val (number):
Tensor whose type is to be validated.
number_type (type):
Expected data type of number.
Ex: int, float, long.
Returns (bool):
... | number_type_checker | identifier_name |
__number.py | from sys import version_info
try:
from collections.abc import Iterable, Container
except ImportError:
from collections import Iterable, Container
from pyvalid import accepts
from pyvalid.validators import AbstractValidator
class NumberValidator(AbstractValidator):
number_types = (int, float)
if vers... |
elif isinstance(in_range, Iterable):
for item in in_range:
if item == val:
is_valid = True
break
return is_valid
@classmethod
def not_in_range_checker(cls, val, not_in_range):
return not cls.in_range_checker(val, not_i... | is_valid = val in in_range | conditional_block |
__number.py | from sys import version_info
try:
from collections.abc import Iterable, Container
except ImportError:
from collections import Iterable, Container
from pyvalid import accepts
from pyvalid.validators import AbstractValidator
class NumberValidator(AbstractValidator):
number_types = (int, float)
if vers... |
@property
def checkers(self):
return self.__checkers
@accepts(
object, min_val=number_types, max_val=number_types,
in_range=[Iterable, Container], not_in_range=[Iterable, Container]
)
def __init__(self, **kwargs):
min_val = kwargs.get('min_val', None)
max_v... | return not cls.in_range_checker(val, not_in_range) | identifier_body |
__number.py | from sys import version_info
try:
from collections.abc import Iterable, Container
except ImportError:
from collections import Iterable, Container
from pyvalid import accepts
from pyvalid.validators import AbstractValidator
class NumberValidator(AbstractValidator):
number_types = (int, float)
if vers... | NumberValidator.not_in_range_checker: [not_in_range]
}
AbstractValidator.__init__(self, allowed_types=NumberValidator.number_types) | NumberValidator.number_type_checker: [number_type],
NumberValidator.in_range_checker: [in_range], | random_line_split |
file-attachment.model.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program 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 ... | uniqueName: string;
attachmentType: FileAttachmentType;
presignedUrl?: string;
size?: string;
createdBy?: string;
creationDate?: Date;
uploading?: boolean;
refreshTime?: Date;
}
export enum FileAttachmentType {
Document = 'DOCUMENT',
Link = 'LINK',
}
export const fileAttachmentTypesMap = {
[Fil... | linkInstanceId?: string;
attributeId: string;
fileName: string; | random_line_split |
test_project_releases.py | from __future__ import absolute_import
from datetime import datetime
from django.core.urlresolvers import reverse
from sentry.models import Release
from sentry.testutils import APITestCase
class ProjectReleaseListTest(APITestCase):
def | (self):
self.login_as(user=self.user)
team = self.create_team(owner=self.user)
project1 = self.create_project(team=team, name='foo')
project2 = self.create_project(team=team, name='bar')
release1 = Release.objects.create(
project=project1,
version='1',
... | test_simple | identifier_name |
test_project_releases.py | from __future__ import absolute_import
from datetime import datetime
from django.core.urlresolvers import reverse
from sentry.models import Release
from sentry.testutils import APITestCase
class ProjectReleaseListTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
team = sel... |
class ProjectReleaseCreateTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
team = self.create_team(owner=self.user)
project = self.create_project(team=team, name='foo')
url = reverse('sentry-api-0-project-releases', kwargs={
'project_id': projec... | assert response.data[0]['version'] == release2.version
assert response.data[1]['version'] == release1.version | random_line_split |
test_project_releases.py | from __future__ import absolute_import
from datetime import datetime
from django.core.urlresolvers import reverse
from sentry.models import Release
from sentry.testutils import APITestCase
class ProjectReleaseListTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
team = sel... | self.login_as(user=self.user)
team = self.create_team(owner=self.user)
project = self.create_project(team=team, name='foo')
url = reverse('sentry-api-0-project-releases', kwargs={
'project_id': project.id,
})
response = self.client.post(url, data={
'vers... | identifier_body | |
keywords_header.py | # vim:fileencoding=utf-8
# Copyright 2001-2010 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
__all__ = ['keywords_header']
from portage import settings as ports
from portage.output import colorize
from display_pretty import colorize_string
from display_pretty import align_string... |
def __formatAdditional(self, additional, align, length):
"""Align additional items properly"""
# % are used as separators for further split so we wont loose spaces and coloring
return ['%'.join(align_string(x, align, length)) for x in additional]
def __prepareExtra(self, extra, align, length):
content = []... | """Append colors and align keywords properly"""
tmp = []
for keyword in keywords:
tmp2 = keyword
keyword = align_string(keyword, align, length)
# % are used as separators for further split so we wont loose spaces and coloring
keyword = '%'.join(list(keyword))
if tmp2 in self.__IMPARCHS:
tmp.appen... | identifier_body |
keywords_header.py | # vim:fileencoding=utf-8
# Copyright 2001-2010 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
__all__ = ['keywords_header']
from portage import settings as ports
from portage.output import colorize
from display_pretty import colorize_string
from display_pretty import align_string... | (self, keywords, additional, align, length):
"""Parse keywords and additional fields into one list with proper separators"""
content = []
content.append(''.ljust(length, '-'))
content.extend(self.__formatKeywords(keywords, align, length))
content.append(''.ljust(length, '-'))
content.extend(self.__formatAdd... | __prepareResult | identifier_name |
keywords_header.py | # vim:fileencoding=utf-8
# Copyright 2001-2010 Gentoo Foundation | # Distributed under the terms of the GNU General Public License v2
__all__ = ['keywords_header']
from portage import settings as ports
from portage.output import colorize
from display_pretty import colorize_string
from display_pretty import align_string
class keywords_header:
__IMPARCHS = [ 'arm', 'amd64', 'x86' ]
... | random_line_split | |
keywords_header.py | # vim:fileencoding=utf-8
# Copyright 2001-2010 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
__all__ = ['keywords_header']
from portage import settings as ports
from portage.output import colorize
from display_pretty import colorize_string
from display_pretty import align_string... |
else:
tmp.append(keyword)
return tmp
def __formatAdditional(self, additional, align, length):
"""Align additional items properly"""
# % are used as separators for further split so we wont loose spaces and coloring
return ['%'.join(align_string(x, align, length)) for x in additional]
def __prepareExt... | tmp.append(colorize_string('darkyellow', keyword)) | conditional_block |
ObjectToImageTest.py | ##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... |
if __name__ == "__main__":
unittest.main()
| n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["o... | identifier_body |
ObjectToImageTest.py | ##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... |
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main... | n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() ) | random_line_split |
ObjectToImageTest.py | ##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | unittest.main() | conditional_block | |
ObjectToImageTest.py | ##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | ( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( ... | testHashVariesPerTileAndChannel | identifier_name |
java-contribution.ts | /*
* Copyright (C) 2017 TypeFox and others.
*
* 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
*/
import * as os from 'os';
import * as path from '... |
}
| {
const serverPath = path.resolve(__dirname, 'server');
const jarPaths = glob.sync('**/plugins/org.eclipse.equinox.launcher_*.jar', { cwd: serverPath });
if (jarPaths.length === 0) {
throw new Error('The java server launcher is not found.');
}
const jarPath = path.re... | identifier_body |
java-contribution.ts | /*
* Copyright (C) 2017 TypeFox and others.
*
* 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
*/
import * as os from 'os';
import * as path from '... | (clientConnection: IConnection): void {
const serverPath = path.resolve(__dirname, 'server');
const jarPaths = glob.sync('**/plugins/org.eclipse.equinox.launcher_*.jar', { cwd: serverPath });
if (jarPaths.length === 0) {
throw new Error('The java server launcher is not found.');
... | start | identifier_name |
java-contribution.ts | /*
* Copyright (C) 2017 TypeFox and others.
*
* 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
*/
import * as os from 'os';
import * as path from '... |
const jarPath = path.resolve(serverPath, jarPaths[0]);
const workspacePath = path.resolve(os.tmpdir(), '_ws_' + new Date().getTime());
const configuration = configurations.get(process.platform);
const configurationPath = path.resolve(serverPath, configuration);
const command = ... | {
throw new Error('The java server launcher is not found.');
} | conditional_block |
java-contribution.ts | /*
* Copyright (C) 2017 TypeFox and others.
*
* 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
*/
import * as os from 'os';
import * as path from '... | '-Dlog.level=ALL'
);
}
args.push(
'-jar', jarPath,
'-configuration', configurationPath,
'-data', workspacePath
)
Promise.all([
this.startSocketServer(), this.startSocketServer()
]).then(servers => {
... | '-Dlog.protocol=true', | random_line_split |
noInnerHtmlRule.ts | import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as tsutils from 'tsutils';
import { AstUtils } from './utils/AstUtils';
import { ExtendedMetadata } from './utils/ExtendedMetadata';
interface Options {
htmlLibExpressionRegex: RegExp;
}
const FAILURE_INNER: string = 'Writing a string to ... | {
const { htmlLibExpressionRegex } = ctx.options;
function cb(node: ts.Node): void {
if (tsutils.isBinaryExpression(node)) {
// look for assignments to property expressions where the
// left hand side is either innerHTML or outerHTML
if (node.operatorToken.kind === t... | identifier_body | |
noInnerHtmlRule.ts | import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as tsutils from 'tsutils';
import { AstUtils } from './utils/AstUtils';
import { ExtendedMetadata } from './utils/ExtendedMetadata';
interface Options {
htmlLibExpressionRegex: RegExp;
}
const FAILURE_INNER: string = 'Writing a string to ... | (ctx: Lint.WalkContext<Options>) {
const { htmlLibExpressionRegex } = ctx.options;
function cb(node: ts.Node): void {
if (tsutils.isBinaryExpression(node)) {
// look for assignments to property expressions where the
// left hand side is either innerHTML or outerHTML
... | walk | identifier_name |
noInnerHtmlRule.ts | import * as ts from 'typescript';
import * as Lint from 'tslint';
import * as tsutils from 'tsutils';
import { AstUtils } from './utils/AstUtils';
import { ExtendedMetadata } from './utils/ExtendedMetadata';
interface Options {
htmlLibExpressionRegex: RegExp;
}
const FAILURE_INNER: string = 'Writing a string to ... |
}
if (tsutils.isCallExpression(node)) {
const functionName = AstUtils.getFunctionName(node);
if (functionName === 'html') {
if (node.arguments.length > 0) {
const functionTarget = AstUtils.getFunctionTarget(node);
if (func... | {
if (tsutils.isPropertyAccessExpression(node.left)) {
const propAccess: ts.PropertyAccessExpression = node.left;
const propName: string = propAccess.name.text;
if (propName === 'innerHTML') {
ctx.addFailureAt(node.getSt... | conditional_block |
noInnerHtmlRule.ts | import * as ts from 'typescript';
import * as Lint from 'tslint'; |
import { AstUtils } from './utils/AstUtils';
import { ExtendedMetadata } from './utils/ExtendedMetadata';
interface Options {
htmlLibExpressionRegex: RegExp;
}
const FAILURE_INNER: string = 'Writing a string to the innerHTML property is insecure: ';
const FAILURE_OUTER: string = 'Writing a string to the outerHTM... | import * as tsutils from 'tsutils'; | random_line_split |
hud.js | (function (window) {
'use strict';
window.opspark = window.opspark || {};
var
draw = window.opspark.draw,
createjs = window.createjs;
/*
Create a heads-up display for our game showing a scoreand an
"integrity meter" which indicates our health. The returned objec... |
hud.setIntegrity = function (value) {
if (value >= 0 && value < 101) {
createjs.Tween.get(integrityMeter).to({scaleX:value}, 400);
if (value === 0) hud.kill();
}
};
hud.kill = function () {
createjs.Tween.get(i... | of += value;
txtScore.text = 'score : ' + score + ' / ' + of;
layout();
setPosition();
}; | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.