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 |
|---|---|---|---|---|
cache.rs | use crate::{
Context, ExecuteProcessRequest, ExecuteProcessRequestMetadata,
FallibleExecuteProcessResultWithPlatform, MultiPlatformExecuteProcessRequest, Platform,
};
use std::sync::Arc;
use bincode;
use bytes::Bytes;
use futures01::{future, Future};
use log::{debug, warn};
use protobuf::Message;
use boxfuture::{... | use serde::{Deserialize, Serialize};
use sharded_lmdb::ShardedLmdb;
use store::Store;
#[allow(dead_code)]
#[derive(Serialize, Deserialize)]
struct PlatformAndResponseBytes {
platform: Platform,
response_bytes: Vec<u8>,
}
#[derive(Clone)]
pub struct CommandRunner {
underlying: Arc<dyn crate::CommandRunner>,
pr... | random_line_split | |
cache.rs | use crate::{
Context, ExecuteProcessRequest, ExecuteProcessRequestMetadata,
FallibleExecuteProcessResultWithPlatform, MultiPlatformExecuteProcessRequest, Platform,
};
use std::sync::Arc;
use bincode;
use bytes::Bytes;
use futures01::{future, Future};
use log::{debug, warn};
use protobuf::Message;
use boxfuture::{... | .file_store
.store_file_bytes(result.stdout.clone(), true)
.join(
self
.file_store
.store_file_bytes(result.stderr.clone(), true),
)
.and_then(move |(stdout_digest, stderr_digest)| {
let action_result = execute_response.mut_result();
action_resul... | {
let mut execute_response = bazel_protos::remote_execution::ExecuteResponse::new();
execute_response.set_cached_result(true);
let action_result = execute_response.mut_result();
action_result.set_exit_code(result.exit_code);
action_result.mut_output_directories().push({
let mut directory = baz... | identifier_body |
cache.rs | use crate::{
Context, ExecuteProcessRequest, ExecuteProcessRequestMetadata,
FallibleExecuteProcessResultWithPlatform, MultiPlatformExecuteProcessRequest, Platform,
};
use std::sync::Arc;
use bincode;
use bytes::Bytes;
use futures01::{future, Future};
use log::{debug, warn};
use protobuf::Message;
use boxfuture::{... | (
&self,
fingerprint: Fingerprint,
result: &FallibleExecuteProcessResultWithPlatform,
) -> impl Future<Item = (), Error = String> {
let mut execute_response = bazel_protos::remote_execution::ExecuteResponse::new();
execute_response.set_cached_result(true);
let action_result = execute_response.... | store | identifier_name |
cache.rs | use crate::{
Context, ExecuteProcessRequest, ExecuteProcessRequestMetadata,
FallibleExecuteProcessResultWithPlatform, MultiPlatformExecuteProcessRequest, Platform,
};
use std::sync::Arc;
use bincode;
use bytes::Bytes;
use futures01::{future, Future};
use log::{debug, warn};
use protobuf::Message;
use boxfuture::{... |
},
)
}
fn store(
&self,
fingerprint: Fingerprint,
result: &FallibleExecuteProcessResultWithPlatform,
) -> impl Future<Item = (), Error = String> {
let mut execute_response = bazel_protos::remote_execution::ExecuteResponse::new();
execute_response.set_cached_result(true);
le... | {
future::ok(None).to_boxed()
} | conditional_block |
test__socket_timeout.py | import sys
import gevent
from gevent import socket
import greentest
class Test(greentest.TestCase):
def start(self):
self.server = socket.socket()
self.server.bind(('127.0.0.1', 0))
self.server.listen(1)
self.server_port = self.server.getsockname()[1]
self.acceptor = geven... | greentest.main() | conditional_block | |
test__socket_timeout.py | import sys
import gevent
from gevent import socket
import greentest
class Test(greentest.TestCase):
def start(self):
self.server = socket.socket()
self.server.bind(('127.0.0.1', 0))
self.server.listen(1)
self.server_port = self.server.getsockname()[1]
self.acceptor = geven... |
def test(self):
self.start()
try:
sock = socket.socket()
sock.connect(('127.0.0.1', self.server_port))
try:
sock.settimeout(0.1)
try:
result = sock.recv(1024)
raise AssertionError('Expected t... | self.server.close()
self.acceptor.kill()
del self.acceptor
del self.server | random_line_split |
test__socket_timeout.py | import sys
import gevent
from gevent import socket
import greentest
class Test(greentest.TestCase):
def start(self):
self.server = socket.socket()
self.server.bind(('127.0.0.1', 0))
self.server.listen(1)
self.server_port = self.server.getsockname()[1]
self.acceptor = geven... | (self):
self.server.close()
self.acceptor.kill()
del self.acceptor
del self.server
def test(self):
self.start()
try:
sock = socket.socket()
sock.connect(('127.0.0.1', self.server_port))
try:
sock.settimeout(0.1)
... | stop | identifier_name |
test__socket_timeout.py | import sys
import gevent
from gevent import socket
import greentest
class Test(greentest.TestCase):
def start(self):
self.server = socket.socket()
self.server.bind(('127.0.0.1', 0))
self.server.listen(1)
self.server_port = self.server.getsockname()[1]
self.acceptor = geven... |
def test(self):
self.start()
try:
sock = socket.socket()
sock.connect(('127.0.0.1', self.server_port))
try:
sock.settimeout(0.1)
try:
result = sock.recv(1024)
raise AssertionError('Expected ... | self.server.close()
self.acceptor.kill()
del self.acceptor
del self.server | identifier_body |
setgroup.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/setgroup.ui'
#
# Created: Sun Mar 30 10:19:30 2014
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
exc... | (context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setO... | _translate | identifier_name |
setgroup.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/setgroup.ui'
#
# Created: Sun Mar 30 10:19:30 2014
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
exc... | self.label.setText(_("Move cards to deck:")) | def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_("Anki")) | random_line_split |
setgroup.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/setgroup.ui'
#
# Created: Sun Mar 30 10:19:30 2014
# by: PyQt4 UI code generator 4.10.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
exc... |
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
cla... | return s | identifier_body |
zip_longest.rs | use std::cmp::Ordering::{Equal, Greater, Less};
use super::size_hint;
use std::iter::Fuse;
use crate::either_or_both::EitherOrBoth;
// ZipLongest originally written by SimonSapin,
// and dedicated to itertools https://github.com/rust-lang/rust/pull/19283 | /// This iterator is *fused*.
///
/// See [`.zip_longest()`](../trait.Itertools.html#method.zip_longest) for more information.
#[derive(Clone, Debug)]
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct ZipLongest<T, U> {
a: Fuse<T>,
b: Fuse<U>,
}
/// Create a new `ZipLongest` ... |
/// An iterator which iterates two other iterators simultaneously
/// | random_line_split |
zip_longest.rs | use std::cmp::Ordering::{Equal, Greater, Less};
use super::size_hint;
use std::iter::Fuse;
use crate::either_or_both::EitherOrBoth;
// ZipLongest originally written by SimonSapin,
// and dedicated to itertools https://github.com/rust-lang/rust/pull/19283
/// An iterator which iterates two other iterators simultaneou... | <T, U>(a: T, b: U) -> ZipLongest<T, U>
where T: Iterator,
U: Iterator
{
ZipLongest {
a: a.fuse(),
b: b.fuse(),
}
}
impl<T, U> Iterator for ZipLongest<T, U>
where T: Iterator,
U: Iterator
{
type Item = EitherOrBoth<T::Item, U::Item>;
#[inline]
fn next(&m... | zip_longest | identifier_name |
zip_longest.rs | use std::cmp::Ordering::{Equal, Greater, Less};
use super::size_hint;
use std::iter::Fuse;
use crate::either_or_both::EitherOrBoth;
// ZipLongest originally written by SimonSapin,
// and dedicated to itertools https://github.com/rust-lang/rust/pull/19283
/// An iterator which iterates two other iterators simultaneou... |
}
impl<T, U> ExactSizeIterator for ZipLongest<T, U>
where T: ExactSizeIterator,
U: ExactSizeIterator
{}
| {
match self.a.len().cmp(&self.b.len()) {
Equal => match (self.a.next_back(), self.b.next_back()) {
(None, None) => None,
(Some(a), Some(b)) => Some(EitherOrBoth::Both(a, b)),
// These can only happen if .len() is inconsistent with .next_back()
... | identifier_body |
panic-recover-propagate.rs | // Copyright 2015 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 ... | {
panic::set_hook(Box::new(|_| {
A.fetch_add(1, Ordering::SeqCst);
}));
let result = thread::spawn(|| {
let result = panic::catch_unwind(|| {
panic!("hi there");
});
panic::resume_unwind(result.unwrap_err());
}).join();
let msg = *result.unwrap_err().do... | identifier_body | |
panic-recover-propagate.rs | // Copyright 2015 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 ... | () {
panic::set_hook(Box::new(|_| {
A.fetch_add(1, Ordering::SeqCst);
}));
let result = thread::spawn(|| {
let result = panic::catch_unwind(|| {
panic!("hi there");
});
panic::resume_unwind(result.unwrap_err());
}).join();
let msg = *result.unwrap_err()... | main | identifier_name |
panic-recover-propagate.rs | // Copyright 2015 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// igno... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
test-issue1438-t.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# Copyright (c) Mercurial Contributors.
#
# This software may be used and distributed according to the terms of the |
from testutil.dott import feature, sh, testtmp # noqa: F401
feature.require(["symlink"])
# https://bz.mercurial-scm.org/1438
sh % "hg init repo"
sh % "cd repo"
sh % "ln -s foo link"
sh % "hg add link"
sh % "hg ci -mbad link"
sh % "hg rm link"
sh % "hg ci -mok"
sh % "hg diff -g -r '0:1'" > "bad.patch"
sh % "hg u... | # GNU General Public License version 2 or any later version.
from __future__ import absolute_import | random_line_split |
test_models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.test import TestCase
from models import Student, StudyGroup, Task, Lab, Subject, GroupSubject
class PortalTest(TestCase):
def setUp(self):
| )
self.lab1 = Lab.objects.create(name="Кольца ньютона", subject=self.subject1)
self.lab2 = Lab.objects.create(name="Атвуд", subject=self.subject2)
def test_task_create(self):
has_error = False
try:
task = Task(student=self.student1, lab=self.lab1)
ta... | self.study_group1 = StudyGroup.objects.create(name="10А")
self.study_group2 = StudyGroup.objects.create(name="11Б")
self.subject1 = Subject.objects.create(name="Оптика")
self.subject2 = Subject.objects.create(name="Механика")
self.group_subject11 = GroupSubject.objects.create(
... | identifier_body |
test_models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.test import TestCase
from models import Student, StudyGroup, Task, Lab, Subject, GroupSubject
class PortalTest(TestCase):
def | (self):
self.study_group1 = StudyGroup.objects.create(name="10А")
self.study_group2 = StudyGroup.objects.create(name="11Б")
self.subject1 = Subject.objects.create(name="Оптика")
self.subject2 = Subject.objects.create(name="Механика")
self.group_subject11 = GroupSubject.objects.... | setUp | identifier_name |
test_models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.test import TestCase
from models import Student, StudyGroup, Task, Lab, Subject, GroupSubject
class PortalTest(TestCase):
def setUp(self):
self.study_group1 = StudyGroup.objects.... | self.student1 = Student.objects.create_user(
username="ivan", email=None, password="123456", study_group=self.study_group1
)
self.student2 = Student.objects.create_user(
username="pavel", email=None, password="123456", study_group=self.study_group2
)
sel... | study_group=self.study_group2, subject=self.subject2
)
| random_line_split |
manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask_script import Manager, Shell, Server
from flask_script.commands import Clean, ShowUrls
from flask_migrate import MigrateCommand
from inspectors.app import create_app
from inspectors.settings import DevConfig, ProdConfig
from inspectors.database import ... | manager.run() | conditional_block | |
manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask_script import Manager, Shell, Server
from flask_script.commands import Clean, ShowUrls
from flask_migrate import MigrateCommand
from inspectors.app import create_app
from inspectors.settings import DevConfig, ProdConfig
from inspectors.database import ... |
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
manager.add_command("urls", ShowUrls())
manager.add_command("clean", Clean())
if __name__ == '__main__':
manager.run()
| """Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code | identifier_body |
manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask_script import Manager, Shell, Server
from flask_script.commands import Clean, ShowUrls
from flask_migrate import MigrateCommand
from inspectors.app import create_app
from inspectors.settings import DevConfig, ProdConfig
from inspectors.database import ... | manager.add_command("urls", ShowUrls())
manager.add_command("clean", Clean())
if __name__ == '__main__':
manager.run() | manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand) | random_line_split |
manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask_script import Manager, Shell, Server
from flask_script.commands import Clean, ShowUrls
from flask_migrate import MigrateCommand
from inspectors.app import create_app
from inspectors.settings import DevConfig, ProdConfig
from inspectors.database import ... | ():
"""Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
manager.add_command("urls", ShowUrls())
manager.ad... | test | identifier_name |
datasource.ts | : timeRange.from.valueOf() * NS_IN_MS, end: timeRange.to.valueOf() * NS_IN_MS };
}
async importFromAbstractQueries(abstractQueries: AbstractQuery[]): Promise<LokiQuery[]> {
await this.languageProvider.start();
const existingKeys = this.languageProvider.labelKeys;
if (existingKeys && existingKeys.lengt... | {
return [];
} | conditional_block | |
datasource.ts | .to, true);
const queryLimit = isMetricsQuery(target.expr) ? options.maxDataPoints : target.maxLines;
const query = {
query: target.expr,
time: `${timeNs + (1e9 - (timeNs % 1e9))}`,
limit: Math.min(queryLimit || Infinity, this.maxLines),
};
/** Used only for results of metrics instant... | {
const params = this.getTimeRangeParams();
const url = `${LOKI_ENDPOINT}/label/${label}/values`;
const result = await this.metadataRequest(url, params);
return result.map((value: string) => ({ text: value }));
} | identifier_body | |
datasource.ts | AdHocFilters(target.expr);
return {
...target,
expr: this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr),
};
});
for (const target of filteredTargets) {
if (target.instant || target.queryType === LokiQueryType.Instant) {
subQueries.push(this... | this.adjustInterval((options as DataQueryRequest<LokiQuery>).intervalMs || 1000, resolution, rangeMs) / 1000;
// We want to ceil to 3 decimal places
const step = Math.ceil(adjustedInterval * 1000) / 1000;
range = {
start: startNs,
end: endNs,
step,
};
}
... | random_line_split | |
datasource.ts | Please check JS console logs.',
status: err.status,
statusText: err.statusText,
};
throw error;
}),
switchMap((res) =>
of({
data: res.data
? res.data.data.result.map((stream: LokiStreamResult) => lokiStreamResultToDataFrame... | lokiSpecialRegexEscape | identifier_name | |
caller-location-fnptr-rt-ctfe-equiv.rs | // Ensure that a `#[track_caller]` function, returning `caller_location()`,
// which coerced (to a function pointer) and called, inside a `const fn`,
// in turn called, results in the same output irrespective of whether
// we're in a const or runtime context.
// run-pass
// compile-flags: -Z unleash-the-miri-inside-of... | type L = &'static std::panic::Location<'static>;
#[track_caller]
const fn attributed() -> L {
std::intrinsics::caller_location()
}
const fn calling_attributed() -> L {
// We need `-Z unleash-the-miri-inside-of-you` for this as we don't have `const fn` pointers.
let ptr: fn() -> L = attributed;
ptr()
}... | random_line_split | |
caller-location-fnptr-rt-ctfe-equiv.rs | // Ensure that a `#[track_caller]` function, returning `caller_location()`,
// which coerced (to a function pointer) and called, inside a `const fn`,
// in turn called, results in the same output irrespective of whether
// we're in a const or runtime context.
// run-pass
// compile-flags: -Z unleash-the-miri-inside-of... |
fn main() {
const CONSTANT: L = calling_attributed();
let runtime = calling_attributed();
assert_eq!(
(runtime.file(), runtime.line(), runtime.column()),
(CONSTANT.file(), CONSTANT.line(), CONSTANT.column()),
);
}
| {
// We need `-Z unleash-the-miri-inside-of-you` for this as we don't have `const fn` pointers.
let ptr: fn() -> L = attributed;
ptr()
} | identifier_body |
caller-location-fnptr-rt-ctfe-equiv.rs | // Ensure that a `#[track_caller]` function, returning `caller_location()`,
// which coerced (to a function pointer) and called, inside a `const fn`,
// in turn called, results in the same output irrespective of whether
// we're in a const or runtime context.
// run-pass
// compile-flags: -Z unleash-the-miri-inside-of... | () -> L {
// We need `-Z unleash-the-miri-inside-of-you` for this as we don't have `const fn` pointers.
let ptr: fn() -> L = attributed;
ptr()
}
fn main() {
const CONSTANT: L = calling_attributed();
let runtime = calling_attributed();
assert_eq!(
(runtime.file(), runtime.line(), runtim... | calling_attributed | identifier_name |
Gruntfile.js | module.exports = function(grunt) {
require("matchdep").filterDev("grunt-*").forEach(grunt.loadNpmTasks);
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
copy: {
main: {
expand: true,
cwd: "src/",
src: ["**", "!css/**/*.scss", "!css/**/*.less"],
dest: "dis... | less: {
files: ["src/css/**/*.less"],
tasks: ["less"]
},
sass: {
files: ["src/css/**/*.scss"],
tasks: ["sass"]
},
copy: {
files: ["src/**"],
tasks: ["copy:main"]
}
}
});
grunt.registerTask("default", ["watch"]);
}; | watch: {
options: {
nospawn: true,
livereload: true
}, | random_line_split |
cms_tags.py | get_page_by_untyped_arg(page_lookup, request, site_id)
if page:
url = page.get_absolute_url(language=lang)
cache.set(cache_key, url, settings.CMS_CACHE_DURATIONS['content'])
if url:
return {'content': url}
return {'content': ''}
register.tag(PageUr... | kwargs = super(ShowUncachedPlaceholderById, self).get_kwargs(*args, **kwargs)
kwargs['cache_result'] = False
return kwargs | identifier_body | |
cms_tags.py | , Page):
page_key = str(page_lookup.pk)
else:
page_key = str(page_lookup)
page_key = _clean_key(page_key)
return name+'__page_lookup:'+page_key+'_site:'+str(site_id)+'_lang:'+str(lang)
def _get_page_by_untyped_arg(page_lookup, request, site_id):
"""
The `page_lookup` argument can be... |
class PageAttribute(Tag):
"""
This template node is used to output attribute from a page such
as its title or slug.
Synopsis
{% page_attribute "field-name" %}
{% page_attribute "field-name" page_lookup %}
Example
{# Output current page's page_title attribute: #}
... | random_line_split | |
cms_tags.py | , Page):
page_key = str(page_lookup.pk)
else:
page_key = str(page_lookup)
page_key = _clean_key(page_key)
return name+'__page_lookup:'+page_key+'_site:'+str(site_id)+'_lang:'+str(lang)
def _get_page_by_untyped_arg(page_lookup, request, site_id):
"""
The `page_lookup` argument can be... | (current_page, page, context, name):
placeholder_cache = getattr(current_page, '_tmp_placeholders_cache', {})
if page.pk in placeholder_cache:
return placeholder_cache[page.pk].get(name, None)
placeholder_cache[page.pk] = {}
placeholders = page.placeholders.all()
for placeholder in placehold... | _get_placeholder | identifier_name |
cms_tags.py |
return site_id
def has_permission(page, request):
return page.has_change_permission(request)
register.filter(has_permission)
CLEAN_KEY_PATTERN = re.compile(r'[^a-zA-Z0-9_-]')
def _clean_key(key):
return CLEAN_KEY_PATTERN.sub('-', key)
def _get_cache_key(name, page_lookup, lang, site_id):
if isinsta... | site_id = settings.SITE_ID | conditional_block | |
pc_report-summary_counts.py | #!/usr/bin/env python
import sys
import os
import glob
import json
import re
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
def init_report_dir(metadata_dir, report_name):
report_dir = metadata_dir + '/reports/' + report_name
if not os.path.exists(report_dir):
os... | report_dir = init_report_dir(metadata_dir, report_name)
[dates, metadata_dirs] = get_metadata_dirs(metadata_dir)
data = [["Date", "To be called", "Called"]]
counts = []
today_donors = []
for ctype in count_types:
donor_counts = []
for md in metadata_dirs:
donors = set(... | random_line_split | |
pc_report-summary_counts.py | #!/usr/bin/env python
import sys
import os
import glob
import json
import re
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
def init_report_dir(metadata_dir, report_name):
report_dir = metadata_dir + '/reports/' + report_name
if not os.path.exists(report_dir):
os... |
# today's counts
with open(report_dir + '/summary_site_counts.json', 'w') as o: o.write(json.dumps(site_summary))
# get all previous days counts
[dates, metadata_dirs] = get_metadata_dirs(metadata_dir, '2015-03-07')
site_summary_report = []
for i, md in reversed(list(enumerate(metadata_dirs)... | site_summary[c] = len(completed_donors.get(c)) | conditional_block |
pc_report-summary_counts.py | #!/usr/bin/env python
import sys
import os
import glob
import json
import re
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
def init_report_dir(metadata_dir, report_name):
report_dir = metadata_dir + '/reports/' + report_name
if not os.path.exists(report_dir):
os... |
return 0
if __name__ == "__main__":
sys.exit(main())
| if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
parser = ArgumentParser(description="PCAWG Report Generator Gathering Counts",
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("-m", "--metadata_dir", dest="metadata_dir",
help="Directory... | identifier_body |
pc_report-summary_counts.py | #!/usr/bin/env python
import sys
import os
import glob
import json
import re
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
def init_report_dir(metadata_dir, report_name):
report_dir = metadata_dir + '/reports/' + report_name
if not os.path.exists(report_dir):
os... | (argv=None):
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
parser = ArgumentParser(description="PCAWG Report Generator Gathering Counts",
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("-m", "--metadata_dir", dest="metadata_dir",
... | main | identifier_name |
main.rs | // Copyright 2014-2016 Martin Kojtal (0xc0170)
//
// 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... | {
use kl25z_map::*;
let sim = Sim::get();
sim.scgc5.bitwise_inc_or(0x400);
let portb = Port::get(1);
portb.pcr[18].set(1 << 8);
let ptb = Gpio::get(1);
ptb.pddr.set(1 << 18);
ptb.psor.set(1 << 18);
loop {
delay(500000);
ptb.ptor.set(1 << 18);
}
} | identifier_body | |
main.rs | // Copyright 2014-2016 Martin Kojtal (0xc0170)
//
// 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
// | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![no_std]
#![crate_type = "rlib"]
#![feature(lang_items, asm)]
#![feature(core_intrinsics)]
#![allow(dead_code)]
#![allow(non_snake_case... | // Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
main.rs | // Copyright 2014-2016 Martin Kojtal (0xc0170)
//
// 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... | (mut cycles: u32)
{
while cycles > 0 {
unsafe {
asm!("nop" :::: "volatile");
}
cycles -= 1;
}
}
#[no_mangle]
pub fn main()
{
use kl25z_map::*;
let sim = Sim::get();
sim.scgc5.bitwise_inc_or(0x400);
let portb = Port::get(1);
portb.pcr[18].set(1 << 8);
... | delay | identifier_name |
sparc64.rs | // Copyright 2014-2016 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-MI... | <'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>)
-> Option<Uniform>
where Ty: TyLayoutMethods<'a, C> + Copy,
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
arg.layout.homogeneous_aggregate(cx).and_then(|unit| {
// Ensure we have at most e... | is_homogeneous_aggregate | identifier_name |
sparc64.rs | // Copyright 2014-2016 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-MI... | })
}
fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'a, Ty>)
where Ty: TyLayoutMethods<'a, C> + Copy,
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
if !ret.layout.is_aggregate() {
ret.extend_integer_width_to(64);
return;
}
if let Some(unifor... | None
} | random_line_split |
sparc64.rs | // Copyright 2014-2016 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-MI... |
// don't return aggregates in registers
ret.make_indirect();
}
fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>)
where Ty: TyLayoutMethods<'a, C> + Copy,
C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout
{
if !arg.layout.is_aggregate() {
arg.extend_int... | {
if !ret.layout.is_aggregate() {
ret.extend_integer_width_to(64);
return;
}
if let Some(uniform) = is_homogeneous_aggregate(cx, ret) {
ret.cast_to(uniform);
return;
}
let size = ret.layout.size;
let bits = size.bits();
if bits <= 256 {
let unit = Reg... | identifier_body |
method-ufcs-2.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 ... |
fn annot_reference_any_lifetime() {
let a = 22;
let b = 44;
let c = 66;
<_ as Bazoom<&u32>>::method(a, &b, c); // OK
}
fn annot_reference_static_lifetime() {
let a = 22;
let b = 44;
let c = 66;
let x = <&'static u32 as Bazoom<_>>::method;
x(&a, b, c); //~ ERROR
}
fn annot_referen... | {
let a = 22;
let b = 44;
let c = 66;
<_ as Bazoom<_>>::method(a, &b, c); // OK
} | identifier_body |
method-ufcs-2.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 ... | () {
let a = 22;
let b = 44;
let c = 66;
<_ as Bazoom<&u32>>::method(a, &b, c); // OK
}
fn annot_reference_static_lifetime() {
let a = 22;
let b = 44;
let c = 66;
let x = <&'static u32 as Bazoom<_>>::method;
x(&a, b, c); //~ ERROR
}
fn annot_reference_named_lifetime<'a>(_d: &'a u32... | annot_reference_any_lifetime | identifier_name |
method-ufcs-2.rs | // Copyright 2017 The Rust Project Developers. See the 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Unit test for... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | random_line_split |
StartView.js | // StartView.js
// -------
define(["jquery", "backbone", "mustache", "text!templates/trulyAnswer/Start.html", "text!templates/trulyAnswer/StartSuccess.html", "models/Question", "Utils", "views/trulyAnswer/Configs"],
function ($, Backbone, Mustache, template, successTemplate, Question, Utils, Configs) {
v... | // Returns the View class
return StartView;
}
); | });
| random_line_split |
StartView.js | // StartView.js
// -------
define(["jquery", "backbone", "mustache", "text!templates/trulyAnswer/Start.html", "text!templates/trulyAnswer/StartSuccess.html", "models/Question", "Utils", "views/trulyAnswer/Configs"],
function ($, Backbone, Mustache, template, successTemplate, Question, Utils, Configs) {
v... | lse {
return false;
}
},
onFocusInput: function(ev) {
this.$el.find(".form-group").removeClass("has-error");
this.$el.find(".control-label").text("我承诺在以下时间内,朋友问我什么我都回答");
},
onBlurInput: ... | return true;
} e | conditional_block |
ColorMatrix.ts | 1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
0, 0, 0, 0, 1
];
const DELTA_INDEX = [
0, 0.01, 0.02, 0.04, 0.05, 0.06, 0.07, 0.08, 0.1, 0.11,
0.12, 0.14, 0.15, 0.16, 0.17, 0.18, 0.20, 0.21, 0.22, 0.24,
0.25, 0.27, 0.28, 0.30, 0.32, 0.34, 0.36, 0.38, 0.40, 0.42,
0.44, 0.46, 0.48, 0.5, 0.5... | for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
col[j] = matrix2[j + i * 5];
}
for (let j = 0; j < 5; j++) {
val = 0;
for (let k = 0; k < 5; k++) {
val += matrix1[j + k * 5] * col[k];
}
out[j + i * 5] = val;
}
}
return out;
};
const adjust = (... | random_line_split | |
compute_squared_distance.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use animate::AnimationVariantAttrs;
use cg;
use quote::Tokens;
use syn::{DeriveInput, Path};
pub fn derive(input:... | ;
Some(quote! {
(&#this_pattern, &#other_pattern) => {
Ok(#sum)
}
})
}));
if append_error_clause {
if let Some(fallback) = input_attrs.fallback {
match_body.append(quote! {
(this, other) => #fallback(this, other)
... | {
let mut sum = quote!();
sum.append_separated(this_info.iter().zip(&other_info).map(|(this, other)| {
where_clause.add_trait_bound(&this.field.ty);
quote! {
::values::distance::ComputeSquaredDistance::compute_squared_distance(#this, #other)?
... | conditional_block |
compute_squared_distance.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use animate::AnimationVariantAttrs;
use cg;
use quote::Tokens;
use syn::{DeriveInput, Path};
pub fn | (input: DeriveInput) -> Tokens {
let name = &input.ident;
let trait_path = &["values", "distance", "ComputeSquaredDistance"];
let (impl_generics, ty_generics, mut where_clause) =
cg::trait_parts(&input, trait_path);
let input_attrs = cg::parse_input_attrs::<DistanceInputAttrs>(&input);
let ... | derive | identifier_name |
compute_squared_distance.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use animate::AnimationVariantAttrs;
use cg;
use quote::Tokens;
use syn::{DeriveInput, Path};
pub fn derive(input:... | let attrs = cg::parse_variant_attrs::<AnimationVariantAttrs>(variant);
if attrs.error {
append_error_clause = true;
return None;
}
let name = cg::variant_ctor(&input, variant);
let (this_pattern, this_info) = cg::ref_pattern(&name, &variant, "this");
... | let mut match_body = quote!();
let mut append_error_clause = variants.len() > 1;
match_body.append_all(variants.iter().map(|variant| { | random_line_split |
streamUrlValidator.directive.js | 'use strict';
(function(app) {
/**
* Stream URL validator directive validates that a model is a valid stream URL depending on type.
*
* Available attributes are:
* - [Boolean] **opa-stream-url-validator** An AngularJS expression evaluating to true if validator is active,
* false otherwise
* ... |
app.directive('opaStreamUrlValidator', opaStreamUrlValidator);
})(angular.module('opa'));
| {
return {
restrict: 'A',
require: ['^ngModel'],
controller: 'OpaStreamUrlValidatorController',
controllerAs: 'ctrl',
bindToController: true,
scope: {
opaStreamUrlValidator: '<',
opaType: '<'
}
};
} | identifier_body |
streamUrlValidator.directive.js | 'use strict';
(function(app) {
/**
* Stream URL validator directive validates that a model is a valid stream URL depending on type.
*
* Available attributes are:
* - [Boolean] **opa-stream-url-validator** An AngularJS expression evaluating to true if validator is active,
* false otherwise
* ... | * with:
* - **[ID]** the id of the stream
*
* The registered name of the validator is "opaStreamUrl".
*
* @example
* <script>
* function Controller($scope) {
* $scope.validates = true;
* $scope.streamType = 'youtube';
* }
* </script>
* <form name="myForm">
... | * - **[WOWZA_IP_ADDRESS]** Wowza streaming engine IP address
* - **[WOWZA_PORT]** Wowza streaming engine port
* - **[WOWZA_APPLICATION_NAME]** Wowza live application name
* - **[WOWZA_STREAM_NAME]** Wowza live stream name (could be a SMIL name)
* - **vodalys** Validate that th... | random_line_split |
streamUrlValidator.directive.js | 'use strict';
(function(app) {
/**
* Stream URL validator directive validates that a model is a valid stream URL depending on type.
*
* Available attributes are:
* - [Boolean] **opa-stream-url-validator** An AngularJS expression evaluating to true if validator is active,
* false otherwise
* ... | () {
return {
restrict: 'A',
require: ['^ngModel'],
controller: 'OpaStreamUrlValidatorController',
controllerAs: 'ctrl',
bindToController: true,
scope: {
opaStreamUrlValidator: '<',
opaType: '<'
}
};
}
app.directive('opaStreamUrlValidator', opaStrea... | opaStreamUrlValidator | identifier_name |
icon.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | else {
const mode = this.config.get('iconMode');
this.newElement.classList.add('icon');
this.newElement.classList.add('icon-' + mode);
this.newElement.classList.add('ion-' + mode + '-' + this.name);
}
!this.ariaLabel && this.newElement.setAttribute('aria... | {
this.newElement.classList.add('icon');
this.newElement.classList.add('fa');
this.newElement.classList.add(this.name);
if (this.isTrueProperty(this.fixedWidth)) {
this.newElement.classList.add('fa-fw');
}
if (this.color) {
... | conditional_block |
icon.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | this.newElement.classList.add('icon');
this.newElement.classList.add('fa');
this.newElement.classList.add(this.name);
if (this.isTrueProperty(this.fixedWidth)) {
this.newElement.classList.add('fa-fw');
}
if (this.color) {
... | if (this.name.startsWith('fa-')) { | random_line_split |
icon.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (changes: {[name: string]: SimpleChange}): void {
if (!changes.name || !this.name) {
return;
}
const oldElement = this.newElement ? this.newElement : this.element;
// Use a new created element to avoid ion-icon working.
// This is necessary to make the FontAwesome s... | ngOnChanges | identifier_name |
icon.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
/**
* Component destroyed.
*/
ngOnDestroy(): void {
if (this.newElement) {
this.newElement.remove();
}
}
}
| {
if (typeof val === 'string') {
val = val.toLowerCase().trim();
return (val === 'true' || val === 'on' || val === '');
}
return !!val;
} | identifier_body |
setup.py | from __future__ import unicode_literals
import os.path
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-aloha-edit',
version='0.4.0',
description='Django Aloha Edit',
author='Nathaniel Tucker',
... | 'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language... | random_line_split | |
setup.py | from __future__ import unicode_literals
import os.path
from setuptools import setup, find_packages
def | (fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(name='django-aloha-edit',
version='0.4.0',
description='Django Aloha Edit',
author='Nathaniel Tucker',
author_email='me@ntucker.me',
url='https://github.com/ntucker/django-aloha-edit',
packages=fin... | read | identifier_name |
setup.py | from __future__ import unicode_literals
import os.path
from setuptools import setup, find_packages
def read(fname):
|
setup(name='django-aloha-edit',
version='0.4.0',
description='Django Aloha Edit',
author='Nathaniel Tucker',
author_email='me@ntucker.me',
url='https://github.com/ntucker/django-aloha-edit',
packages=find_packages(),
include_package_data=True,
install_requires=['django>... | return open(os.path.join(os.path.dirname(__file__), fname)).read() | identifier_body |
async_pipe.d.ts | /**
* @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 { ChangeDetectorRef, OnDestroy } from '@angular/core';
import { EventEmitter, Observable } from '../facade/asy... | transform(obj: Observable<any> | Promise<any> | EventEmitter<any>): any;
} | random_line_split | |
async_pipe.d.ts | /**
* @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 { ChangeDetectorRef, OnDestroy } from '@angular/core';
import { EventEmitter, Observable } from '../facade/asy... | implements OnDestroy {
private _strategy;
constructor(_ref: ChangeDetectorRef);
ngOnDestroy(): void;
transform(obj: Observable<any> | Promise<any> | EventEmitter<any>): any;
}
| AsyncPipe | identifier_name |
app_softhangup.py | # AsteriskLint -- an Asterisk PBX config syntax checker
# Copyright (C) 2019 Walter Doekes, OSSO B.V.
#
# 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 version 3 of the License, or
# (at... | app_loader.register(SoftHangup()) | identifier_body | |
app_softhangup.py | # AsteriskLint -- an Asterisk PBX config syntax checker
# Copyright (C) 2019 Walter Doekes, OSSO B.V.
#
# 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 version 3 of the License, or
# (at... | (AppBase):
pass
def register(app_loader):
app_loader.register(SoftHangup())
| SoftHangup | identifier_name |
app_softhangup.py | # AsteriskLint -- an Asterisk PBX config syntax checker
# Copyright (C) 2019 Walter Doekes, OSSO B.V.
#
# 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 version 3 of the License, or
# (at... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from ..base import AppBase
class SoftHangup(AppBase):
pass
... | # but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.js | var struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n =
[
[ "BasePriority", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a83350567ec26fc4723ac14b5864ae4f9", null ],
[ "ClientId", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a5f4ab183c0202edb1e4b9a2be1ace0db", nul... | [ "UserTime", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a860336a48384d8088ffd8c0abe38d170", null ],
[ "WaitReason", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a250406522090d84f67d275aff60e6079", null ],
[ "WaitTime", "struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_... | random_line_split | |
transifex.py | #!/usr/bin/env python
import os, sys
from polib import pofile
from config import CONFIGURATION
from extract import SOURCE_WARN
from execute import execute
TRANSIFEX_HEADER = 'Translations in this file have been downloaded from %s'
TRANSIFEX_URL = 'https://www.transifex.com/projects/p/edx-studio/'
def push():
exe... | (file):
"""
Strips out the warning from a translated po file about being an English source file.
Replaces warning with a note about coming from Transifex.
"""
po = pofile(file)
if po.header.find(SOURCE_WARN) != -1:
new_header = get_new_header(po)
new = po.header.replace(SOURCE_WA... | clean_file | identifier_name |
transifex.py | #!/usr/bin/env python
import os, sys
from polib import pofile
from config import CONFIGURATION
from extract import SOURCE_WARN
from execute import execute
TRANSIFEX_HEADER = 'Translations in this file have been downloaded from %s'
TRANSIFEX_URL = 'https://www.transifex.com/projects/p/edx-studio/'
def push():
exe... |
if __name__ == '__main__':
if len(sys.argv)<2:
raise Exception("missing argument: push or pull")
arg = sys.argv[1]
if arg == 'push':
push()
elif arg == 'pull':
pull()
else:
raise Exception("unknown argument: (%s)" % arg)
| return TRANSIFEX_HEADER % team | conditional_block |
transifex.py | #!/usr/bin/env python
import os, sys
from polib import pofile
from config import CONFIGURATION
from extract import SOURCE_WARN
from execute import execute
TRANSIFEX_HEADER = 'Translations in this file have been downloaded from %s'
TRANSIFEX_URL = 'https://www.transifex.com/projects/p/edx-studio/'
def push():
exe... |
if __name__ == '__main__':
if len(sys.argv)<2:
raise Exception("missing argument: push or pull")
arg = sys.argv[1]
if arg == 'push':
push()
elif arg == 'pull':
pull()
else:
raise Exception("unknown argument: (%s)" % arg) | return TRANSIFEX_HEADER % TRANSIFEX_URL
else:
return TRANSIFEX_HEADER % team | random_line_split |
transifex.py | #!/usr/bin/env python
import os, sys
from polib import pofile
from config import CONFIGURATION
from extract import SOURCE_WARN
from execute import execute
TRANSIFEX_HEADER = 'Translations in this file have been downloaded from %s'
TRANSIFEX_URL = 'https://www.transifex.com/projects/p/edx-studio/'
def push():
exe... |
def clean_file(file):
"""
Strips out the warning from a translated po file about being an English source file.
Replaces warning with a note about coming from Transifex.
"""
po = pofile(file)
if po.header.find(SOURCE_WARN) != -1:
new_header = get_new_header(po)
new = po.header.r... | """
Strips out the warning from all of a locale's translated po files
about being an English source file.
Iterates over machine-generated files.
"""
dirname = CONFIGURATION.get_messages_dir(locale)
for filename in ('django-partial.po', 'djangojs.po', 'mako.po'):
clean_file(dirname.joinpa... | identifier_body |
expected.js | var sheet = cssx();
(function () {
var _1 = {},
_2 = {},
_3 = {};
_2['color'] = '#000';
_3['color'] = '#F00'; | ;
sheet.add((function () {
var _5 = {},
_6 = {},
_7 = {};
_6['font-size'] = '10px';
_6['line-height'] = '12px';
_7['margin'] = 0;
_7['padding'] = '2em';
_5['p'] = _6;
_5['ul > foo'] = _7;
return _5;
}.apply(this)));
var test = (function () {
var _9 = {};
_9['border'] = 'solid 1px #000'... | _1['body'] = _2;
_1['body.error'] = _3;
return _1;
}.apply(this)) | random_line_split |
index.js | /**
* Main JS file for Jasper behaviours
*/
if (typeof jQuery == 'undefined') |
(function ($) {
"use strict";
// Header Parallax and Fade
$(window).on('scroll', function() {
var scroll_top = $(this).scrollTop();
var top_offset = 600;
$('#site-head-content').css({
'opacity' : (1-scroll_top/top_offset),
'top' : (scroll_top*... | {
document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></' + 'script>');
} | conditional_block |
index.js | /**
* Main JS file for Jasper behaviours
*/
if (typeof jQuery == 'undefined') {
document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></' + 'script>');
}
(function ($) {
"use strict";
// Header Parallax and Fade
$(window).on('scroll', functio... | 'opacity' : (1-scroll_top/top_offset),
'top' : (scroll_top*-.2)
});
/*
// Background Image Parallax
$('#site-head').css({
'background-position' : 'center ' + (scroll_top*-.07) + 'px'
});
*/
});
// Shameless self-p... |
$('#site-head-content').css({ | random_line_split |
submit_v2.py | #!/usr/bin/env python
import lib_v2 as lib
import sys
import os
def main(argv=None):
"""
Usage is:
submit.py [--account <chargecode>] [--url <url>] -- <commandline>
Run from the working dir of the job which must contain (in addition
to the job files) a file named scheduler.conf with scheduler prop... | try:
cmdline_options, cmdline = parser.parse_known_args(argv)
cmdline = cmdline[1:] if not ('--' in cmdline) else cmdline[cmdline.index('--')+1:]
except Exception as e:
print "There was a problem submitting your job"
print e
sys.exit(1)
account = cmdline_options.... | random_line_split | |
submit_v2.py | #!/usr/bin/env python
import lib_v2 as lib
import sys
import os
def | (argv=None):
"""
Usage is:
submit.py [--account <chargecode>] [--url <url>] -- <commandline>
Run from the working dir of the job which must contain (in addition
to the job files) a file named scheduler.conf with scheduler properties for the job.
<chargecode>, if present, gives the project ... | main | identifier_name |
submit_v2.py | #!/usr/bin/env python
import lib_v2 as lib
import sys
import os
def main(argv=None):
|
parser.add_argument('--url', metavar="URL", dest="URL", type=str,
help="Notification URL")
try:
cmdline_options, cmdline = parser.parse_known_args(argv)
cmdline = cmdline[1:] if not ('--' in cmdline) else cmdline[cmdline.index('--')+1:]
except Exception as e:
... | """
Usage is:
submit.py [--account <chargecode>] [--url <url>] -- <commandline>
Run from the working dir of the job which must contain (in addition
to the job files) a file named scheduler.conf with scheduler properties for the job.
<chargecode>, if present, gives the project to charge the job... | identifier_body |
submit_v2.py | #!/usr/bin/env python
import lib_v2 as lib
import sys
import os
def main(argv=None):
"""
Usage is:
submit.py [--account <chargecode>] [--url <url>] -- <commandline>
Run from the working dir of the job which must contain (in addition
to the job files) a file named scheduler.conf with scheduler prop... |
# I'm backing out the workaround by setting useLocalDisk to false.
useLocalDisk = False
# Write the command line to a file, batch_command.cmdline.
rfile = open(lib.cmdfile, "w")
rfile.write("#!/bin/sh\n")
rfile.writelines((" ".join(cmdline), "\n"))
rfile.close()
os.chmod(lib.c... | useLocalDisk = True | conditional_block |
storage.rs | _pv(mapper, level, id, pv);
}
}
else
{
apply_mapper_to_pv(mapper, level, id, pv);
},
}
}
}
/// Apply the passed mapper to the provided physical volume
fn apply_mapper_to_pv(mapper: &'static Mapper, level: usize, pv_id: usize, pvi: &mut PhysicalVolumeInfo)
{
// - Can't compare fat raw pointers (... | drop | identifier_name | |
storage.rs | {
let mappers = S_MAPPERS.lock();
for &mapper in mappers.iter()
{
match mapper.handles_pv(&*dev)
{
Err(e) => log_error!("IO Error in mapper detection: {:?}", e),
Ok(0) => {}, // Ignore (doesn't handle)
Ok(level) =>
if level < best_mapper_level
{
// Ignore (weaker handle)
}
els... | {
let ret_count = ::core::cmp::min(
v.block_count as u64 - idx_rem,
count as u64
) as usize;
return Some( (v.volume, v.first_block + idx_rem, ret_count) );
} | conditional_block | |
storage.rs | for &mapper in mappers.iter()
{
match mapper.handles_pv(&*dev)
{
Err(e) => log_error!("IO Error in mapper detection: {:?}", e),
Ok(0) => {}, // Ignore (doesn't handle)
Ok(level) =>
if level < best_mapper_level
{
// Ignore (weaker handle)
}
else if level == best_mapper_level
{
... | return Some( (v.volume, v.first_block + idx_rem, ret_count) );
}
else {
idx_rem -= v.block_count as u64; | random_line_split | |
storage.rs | ///
/// Lower values are weaker handles, 0 means unhandled.
/// Typical values are: 1=MBR, 2=GPT, 3=LVM etc
fn handles_pv(&self, pv: &PhysicalVolume) -> Result<usize,IoError>;
/// Enumerate volumes
fn enum_volumes(&self, pv: &PhysicalVolume, f: &mut FnMut(String, u64, u64)) -> Result<(),IoError>;
}
/// A singl... |
/// Register a physical volume
pub fn register_pv(dev: Box<PhysicalVolume>) -> PhysicalVolumeReg
{
log_trace!("register_pv(pv = \"{}\")", dev.name());
let pv_id = S_NEXT_PV_IDX.fetch_add(1, ::core::sync::atomic::Ordering::Relaxed);
// Now that a new PV has been inserted, handlers should be informed
let mut best_... | {
S_PHYSICAL_VOLUMES.init( || VecMap::new() );
S_LOGICAL_VOLUMES.init( || VecMap::new() );
S_MAPPERS.init( || Vec::new() );
// Default mapper just exposes the PV as a single LV
//S_MAPPERS.lock().push_back(&default_mapper::Mapper);
} | identifier_body |
Sockets.js | import WebSocket from 'ws';
import querystring from 'querystring';
import Socket from './Socket.js';
/**
* Websocket server that creates and host all {@link server.Socket} instance.
*
* (@note - could be usefull for broadcasting messages, creating rooms, etc.
*
* @memberof server
*/
class Sockets {
constructor... | if (socket.ws.readyState === WebSocket.OPEN) {
if (excludeSocket !== null) {
if (socket !== excludeSocket) {
socket[method](channel, ...args);
}
} else {
socket[method](channel, ...args);
}
}
});
}
/**
* Add a socket to a room
... | {
const method = binary ? 'sendBinary' : 'send';
let targets = new Set();
if (typeof roomIds === 'string' || Array.isArray(roomIds)) {
if (typeof roomIds === 'string') {
roomIds = [roomIds];
}
roomIds.forEach(roomId => {
if (this._rooms.has(roomId)) {
const room... | identifier_body |
Sockets.js | import WebSocket from 'ws';
import querystring from 'querystring';
import Socket from './Socket.js';
/**
* Websocket server that creates and host all {@link server.Socket} instance.
*
* (@note - could be usefull for broadcasting messages, creating rooms, etc.
*
* @memberof server
*/
class Sockets {
constructor... |
} else {
socket[method](channel, ...args);
}
}
});
}
/**
* Add a socket to a room
*
* @param {server.Socket} socket - Socket to add to the room.
* @param {String} roomId - Id of the room
*/
addToRoom(socket, roomId) {
socket.addToRoom(roomId);
}
/**
... | {
socket[method](channel, ...args);
} | conditional_block |
Sockets.js | import WebSocket from 'ws';
import querystring from 'querystring';
import Socket from './Socket.js';
/**
* Websocket server that creates and host all {@link server.Socket} instance.
*
* (@note - could be usefull for broadcasting messages, creating rooms, etc.
*
* @memberof server
*/
class Sockets {
constructor... | (socket, roomId) {
socket.addToRoom(roomId);
}
/**
* Remove a socket from a room
*
* @param {server.Socket} socket - Socket to remove from the room.
* @param {String} [roomId=null] - Id of the room
*/
removeFromRoom(socket, roomId) {
socket.removeFromRoom(roomId);
}
/**
* Send a st... | addToRoom | identifier_name |
Sockets.js | import WebSocket from 'ws';
import querystring from 'querystring';
import Socket from './Socket.js';
/**
* Websocket server that creates and host all {@link server.Socket} instance.
*
* (@note - could be usefull for broadcasting messages, creating rooms, etc.
*
* @memberof server
*/
class Sockets {
constructor... | });
} else {
targets = this._rooms.get('*');
}
targets.forEach(socket => {
if (socket.ws.readyState === WebSocket.OPEN) {
if (excludeSocket !== null) {
if (socket !== excludeSocket) {
socket[method](channel, ...args);
}
} else {
so... | room.forEach(socket => targets.add(socket));
} | random_line_split |
plugins.js | *Math.PI)/p )*.5 + c + b;
},
easeInBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (x, t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (x, t, b, c, ... | fx.elem.style.top = css.top;
fx.elem.style.left = css.left; | random_line_split | |
app.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
import { RegisterComponent } from './register.component';
import {AppModule} from './app.module';
import { AppComponent} from './app.component';
import { RouterTestingModule } from '@angular/route... |
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should be AppValue', () => {
let fixture = TestBed.createComponent(AppC... | imports: [RouterTestingModule,FormsModule,HttpModule],
declarations: [ AppComponent]
})
.compileComponents(); | random_line_split |
export.ts | import { unparse } from "papaparse";
import { Collection, Record } from "./data";
import { MemorySource, EncryptedSource } from "./source";
function recordsToTable(records: Record[]) {
// Array of column names
let cols = ["name", "category"];
// Column indizes associated with field/column names
let col... | // Fill up columns array with distinct field names
for (let rec of records) {
for (let field of rec.fields) {
if (!colInds[field.name]) {
colInds[field.name] = cols.length;
cols.push(field.name);
}
}
}
// Creates an array of empty ... | random_line_split | |
export.ts | import { unparse } from "papaparse";
import { Collection, Record } from "./data";
import { MemorySource, EncryptedSource } from "./source";
function recordsToTable(records: Record[]) {
// Array of column names
let cols = ["name", "category"];
// Column indizes associated with field/column names
let col... | (records: Record[]): string {
return unparse(recordsToTable(records));
}
export async function toPadlock(records: Record[], password: string): Promise<string> {
const coll = new Collection(records);
const memSource = new MemorySource();
const encSource = new EncryptedSource(memSource);
encSource.pa... | toCSV | identifier_name |
export.ts | import { unparse } from "papaparse";
import { Collection, Record } from "./data";
import { MemorySource, EncryptedSource } from "./source";
function recordsToTable(records: Record[]) {
// Array of column names
let cols = ["name", "category"];
// Column indizes associated with field/column names
let col... |
return row;
}
// Add a row for each record
records.forEach(function(rec) {
// Create an empty row to be filled with record name, category and field values
var row = emptyRow();
// Record name and category are always the first and second column respectively
row[0] = ... | {
row.push("");
} | conditional_block |
export.ts | import { unparse } from "papaparse";
import { Collection, Record } from "./data";
import { MemorySource, EncryptedSource } from "./source";
function recordsToTable(records: Record[]) | // Creates an array of empty strings with the length of the `cols` array
function emptyRow() {
var l = cols.length;
var row: string[] = [];
while (l--) {
row.push("");
}
return row;
}
// Add a row for each record
records.forEach(function(rec) {
... | {
// Array of column names
let cols = ["name", "category"];
// Column indizes associated with field/column names
let colInds = {};
// Two dimensional array, starting with column names
let table = [cols];
// Filter out removed items
records = records.filter(function(rec) { return !rec.rem... | identifier_body |
configureStore.ts | declare const module: { hot: any };
import * as Raven from "raven-js";
const createRavenMiddleware = require("raven-for-redux");
import thunkMiddleware from "redux-thunk";
import * as createLogger from "redux-logger";
import { createStore, applyMiddleware } from "redux";
import rootReducer from "reducers";
import { ... |
return store;
}
| {
store.subscribe(() => {
thunderCall('/channels/state/', {
method: "post",
body: JSON.stringify({
state: store.getState()
})
});
});
} | conditional_block |
configureStore.ts | declare const module: { hot: any };
import * as Raven from "raven-js";
const createRavenMiddleware = require("raven-for-redux");
import thunkMiddleware from "redux-thunk";
import * as createLogger from "redux-logger";
import { createStore, applyMiddleware } from "redux";
import rootReducer from "reducers";
import { ... | }
return store;
}
| {
const store = createStoreWithMiddleware(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept("reducers", () => {
const nextRootReducer = require("reducers");
store.replaceReducer(nextRootReducer);
... | identifier_body |
configureStore.ts | declare const module: { hot: any };
import * as Raven from "raven-js";
const createRavenMiddleware = require("raven-for-redux");
import thunkMiddleware from "redux-thunk";
import * as createLogger from "redux-logger";
import { createStore, applyMiddleware } from "redux";
import rootReducer from "reducers";
import { ... | (initialState: any = {}) {
const store = createStoreWithMiddleware(rootReducer, initialState);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept("reducers", () => {
const nextRootReducer = require("reducers");
store.replaceReducer(... | configureStore | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.