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 |
|---|---|---|---|---|
fontbox.py | import typecat.font2img as f2i
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class FontBox(Gtk.FlowBoxChild):
def set_text(self, arg1):
if type(arg1) is str:
self.text = arg1
if type(arg1) is int:
|
try:
self.box.destroy()
except AttributeError:
pass
self.box = Gtk.Box()
self.box.set_border_width(5)
self.image = Gtk.Image(halign=Gtk.Align.CENTER)
self.font.set_size(self.font_size)
self.image.set_from_pixbuf(f2i.multiline_gtk(self.text... | self.font_size = arg1 | conditional_block |
fontbox.py | import typecat.font2img as f2i
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class FontBox(Gtk.FlowBoxChild):
def set_text(self, arg1):
if type(arg1) is str:
self.text = arg1
if type(arg1) is int:
self.font_size = arg1
try:
... | (self, font, text="Handgloves", size=(200, 150), font_size=75):
Gtk.FlowBoxChild.__init__(self)
self.frame = Gtk.Frame()
self.set_border_width(5)
self.font = font
self.font_size = int(size[0]/9)
self.font.set_size(self.font_size)
self.text = text
self.siz... | __init__ | identifier_name |
fontbox.py | import typecat.font2img as f2i
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class FontBox(Gtk.FlowBoxChild):
def set_text(self, arg1):
if type(arg1) is str:
self.text = arg1
if type(arg1) is int:
self.font_size = arg1
try:
... |
self.title = self.font.name if len(self.font.name) < 30 else self.font.name[:27] + "..."
self.frame.set_label(self.title)
self.frame.set_label_align(.1, 0)
entry = Gtk.Entry()
self.bg = (255, 255, 255)
self.fg = (0, 0, 0)
self.set_text(text)
self.add(s... | random_line_split | |
gulpclass.ts | import {Gulpclass, Task, SequenceTask} from 'gulpclass/Decorators';
import * as gulp from 'gulp';
import * as tslint from 'gulp-tslint';
import * as ts from 'gulp-typescript';
import * as del from 'del';
import * as debug from 'gulp-debug';
@Gulpclass()
export class | {
config:any;
tsProject:ts.Project;
constructor() {
this.tsProject = ts.createProject('./tsconfig.json');
}
@Task()
clean(cb:Function) {
return del(['./dist/**'], cb);
}
@Task('ts::lint')
tslint() {
gulp.src(['./app/**/*.ts'])
.pipe(tslint())
.pipe(tslint.report('verbose'))
.pipe(debug());
... | Gulpfile | identifier_name |
gulpclass.ts | import {Gulpclass, Task, SequenceTask} from 'gulpclass/Decorators';
import * as gulp from 'gulp';
import * as tslint from 'gulp-tslint';
import * as ts from 'gulp-typescript';
import * as del from 'del';
import * as debug from 'gulp-debug';
@Gulpclass()
export class Gulpfile {
config:any;
tsProject:ts.Project; | }
@Task()
clean(cb:Function) {
return del(['./dist/**'], cb);
}
@Task('ts::lint')
tslint() {
gulp.src(['./app/**/*.ts'])
.pipe(tslint())
.pipe(tslint.report('verbose'))
.pipe(debug());
}
@Task('ts::compile')
src() {
let tsResult = this.tsProject.src()
.pipe(ts(this.tsProject));
return ts... |
constructor() {
this.tsProject = ts.createProject('./tsconfig.json'); | random_line_split |
gulpclass.ts | import {Gulpclass, Task, SequenceTask} from 'gulpclass/Decorators';
import * as gulp from 'gulp';
import * as tslint from 'gulp-tslint';
import * as ts from 'gulp-typescript';
import * as del from 'del';
import * as debug from 'gulp-debug';
@Gulpclass()
export class Gulpfile {
config:any;
tsProject:ts.Project;
co... |
}
| {
return ["build"];
} | identifier_body |
config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Configuration loader to support multi file types along with environmental
variable ``PYTHON_CLITOOL_ENV``. Default variable is
:const:`clitool.DEFAULT_RUNNING_MODE` (``development``).
Supported file types are:
* ini/cfg
* json
* yaml (if "pyyaml_" is installed)
.. _... | self.filetype = extension
self.config = None
def _load(self):
if self.config is not None:
return
self.config = {}
extension = self.filetype
# XXX: separate each logic using dispatcher dict.
if extension == ".json":
self.config = js... | fname = self.fp.name
_, extension = os.path.splitext(fname)
logging.debug("Configfile=%s, extension=%s",
os.path.abspath(fname), extension) | random_line_split |
config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Configuration loader to support multi file types along with environmental
variable ``PYTHON_CLITOOL_ENV``. Default variable is
:const:`clitool.DEFAULT_RUNNING_MODE` (``development``).
Supported file types are:
* ini/cfg
* json
* yaml (if "pyyaml_" is installed)
.. _... |
def _load(self):
if self.config is not None:
return
self.config = {}
extension = self.filetype
# XXX: separate each logic using dispatcher dict.
if extension == ".json":
self.config = json.load(self.fp)
elif extension == ".py":
# ... | self.fp = fp
if filetype:
if not filetype.startswith('.'):
filetype = '.' + filetype
self.filetype = filetype
else:
fname = self.fp.name
_, extension = os.path.splitext(fname)
logging.debug("Configfile=%s, extension=%s",
... | identifier_body |
config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Configuration loader to support multi file types along with environmental
variable ``PYTHON_CLITOOL_ENV``. Default variable is
:const:`clitool.DEFAULT_RUNNING_MODE` (``development``).
Supported file types are:
* ini/cfg
* json
* yaml (if "pyyaml_" is installed)
.. _... |
def load(self, env=None):
""" Load a section values of given environment.
If nothing to specified, use environmental variable.
If unknown environment was specified, warn it on logger.
:param env: environment key to load in a coercive manner
:type env: string
:rtype... | logging.warn('Unknown file type extension: %s', extension) | conditional_block |
config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Configuration loader to support multi file types along with environmental
variable ``PYTHON_CLITOOL_ENV``. Default variable is
:const:`clitool.DEFAULT_RUNNING_MODE` (``development``).
Supported file types are:
* ini/cfg
* json
* yaml (if "pyyaml_" is installed)
.. _... | (self):
""" Provide flip view to compare how key/value pair is defined in each
environment for administrative usage.
:rtype: dict
"""
self._load()
groups = self.config.keys()
tabular = {}
for g in groups:
config = self.config[g]
fo... | flip | identifier_name |
mehuge-chat.ts | /// <reference path="xmpp.ts" />
module MehugeChat {
var listeners = [];
// return the cooked channel name (base64 encoded channles are $_ prefixed)
function _channelName(name: string) {
// possible base64 encoded channel name without a $_ prefix, add the $_ prefix
// (for backward compat... | msg.from = room;
msg.iscse = ev.iscse;
msg.account = ev.from.split("/")[1];
msg.type = ev.type;
break;
case "chat":
msg = {
from: "IM",
a... | msg = { message: ev.body, id: ev.id };
}
| conditional_block |
mehuge-chat.ts | /// <reference path="xmpp.ts" />
module MehugeChat {
var listeners = [];
// return the cooked channel name (base64 encoded channles are $_ prefixed)
function _channelName(name: string) {
// possible base64 encoded channel name without a $_ prefix, add the $_ prefix
// (for backward compat... | export function listen(listener: any) {
listeners.push(listener);
};
export function join(room: string = undefined) {
if (room) room = _channelName(room);
Xmpp.join(room);
}
export function send(o: any, room: string = undefined) {
if (room) room = _channelName(room);
... | });
} | random_line_split |
mehuge-chat.ts | /// <reference path="xmpp.ts" />
module MehugeChat {
var listeners = [];
// return the cooked channel name (base64 encoded channles are $_ prefixed)
function _channelName(name: string) {
// possible base64 encoded channel name without a $_ prefix, add the $_ prefix
// (for backward compat... | : any, room: string = undefined) {
if (room) room = _channelName(room);
Xmpp.sendMessage(JSON.stringify(o), room);
}
export function sendIM(text: string, who: string) {
Xmpp.sendIM(text, who);
}
export function sendText(message: any, room: string = undefined) {
if (room) ... | nd(o | identifier_name |
mehuge-chat.ts | /// <reference path="xmpp.ts" />
module MehugeChat {
var listeners = [];
// return the cooked channel name (base64 encoded channles are $_ prefixed)
function _channelName(name: string) {
// possible base64 encoded channel name without a $_ prefix, add the $_ prefix
// (for backward compat... | export function disconnect() {
Xmpp.disconnect();
}
} | if (room) room = _channelName(room);
Xmpp.sendMessage(message, room);
}
| identifier_body |
Store2.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# 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 2 of the License, or
# (at your option) an... | return True | identifier_body | |
Store2.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# 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 2 of the License, or
# (at your option) an... | 'friendly_name' : friendly_name,
'proxy' : proxy,
'msnp_ver' : msnp_ver,
'build_ver' : build_ver,
'to_member_name' : to_member_name,
... | <MessageNumber>%(message_number)s</MessageNumber>
</Sequence>""" % { 'from_member_name' : from_member_name, | random_line_split |
Store2.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com>
#
# 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 2 of the License, or
# (at your option) an... | (message_type, message_content):
"""Returns the SOAP xml body"""
return """<MessageType xmlns="http://messenger.msn.com/ws/2004/09/oim/">
%s
</MessageType>
<Content xmlns="http://messenger.msn.com/ws/2004/09/oim/">
%s
</Content>""" % (message_type, me... | soap_body | identifier_name |
build-bak.js | process.env.NODE_ENV = 'production';
require('dotenv').config({silent: true});
var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var pathExists = require('path-exists');
var webpack = require('webpack');
var config = require('../../config/webview/webpack');
var paths = require('..... | (summary, errors) {
console.log(chalk.red(summary));
console.log();
errors.forEach(err => {
console.log(err.message || err);
console.log();
});
}
console.log('Clear old build directory...')
fs.emptyDirSync(paths.build);
// Create the production build and print the deployment instructions.
console.log(... | printErrors | identifier_name |
build-bak.js | process.env.NODE_ENV = 'production';
require('dotenv').config({silent: true});
var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var pathExists = require('path-exists');
var webpack = require('webpack');
var config = require('../../config/webview/webpack');
var paths = require('..... |
console.log(chalk.green('✓ Compiled successfully.'));
}); | {
printErrors('Failed to compile.', stats.compilation.warnings);
process.exit(1);
} | conditional_block |
build-bak.js | process.env.NODE_ENV = 'production';
require('dotenv').config({silent: true});
var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var pathExists = require('path-exists');
var webpack = require('webpack');
var config = require('../../config/webview/webpack');
var paths = require('..... |
console.log('Clear old build directory...')
fs.emptyDirSync(paths.build);
// Create the production build and print the deployment instructions.
console.log('Creating an optimized production build...');
webpack(config).run((err, stats) => {
if (err) {
printErrors('Failed to compile.', [err]);
process.exit(1... | {
console.log(chalk.red(summary));
console.log();
errors.forEach(err => {
console.log(err.message || err);
console.log();
});
} | identifier_body |
build-bak.js | process.env.NODE_ENV = 'production';
require('dotenv').config({silent: true});
var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var pathExists = require('path-exists');
var webpack = require('webpack');
var config = require('../../config/webview/webpack');
var paths = require('..... |
if (stats.compilation.errors.length) {
printErrors('Failed to compile.', stats.compilation.errors);
process.exit(1);
}
if (process.env.CI && stats.compilation.warnings.length) {
printErrors('Failed to compile.', stats.compilation.warnings);
process.exit(1);
}
console.log(chalk.green('✓ Comp... | if (err) {
printErrors('Failed to compile.', [err]);
process.exit(1);
} | random_line_split |
UserData.py | # -*- coding: utf-8 -*-
"""
InformationMachineAPILib.Models.UserData
"""
from InformationMachineAPILib.APIHelper import APIHelper
class UserData(object):
"""Implementation of the 'UserData' model.
TODO: type model description here.
Attributes:
email (string): TODO: type description her... |
def resolve_names(self):
"""Creates a dictionary representation of this object.
This method converts an object to a dictionary that represents the
format that the model should be in when passed into an API Request.
Because of this, the generated dictionary may have differe... | setattr(self, replace_names[key], kwargs[key]) | conditional_block |
UserData.py | # -*- coding: utf-8 -*-
"""
InformationMachineAPILib.Models.UserData
"""
from InformationMachineAPILib.APIHelper import APIHelper
class UserData(object):
"""Implementation of the 'UserData' model.
TODO: type model description here.
Attributes:
email (string): TODO: type description her... | self.zip = None
self.user_id = None
self.owner_app_id = None
self.created_at = None
# Create a mapping from API property names to Model property names
replace_names = {
"email": "email",
"zip": "zip",
"user_id": "user_id",
... | # Set all of the parameters to their default values
self.email = None | random_line_split |
UserData.py | # -*- coding: utf-8 -*-
"""
InformationMachineAPILib.Models.UserData
"""
from InformationMachineAPILib.APIHelper import APIHelper
class UserData(object):
"""Implementation of the 'UserData' model.
TODO: type model description here.
Attributes:
email (string): TODO: type description her... | (self):
"""Creates a dictionary representation of this object.
This method converts an object to a dictionary that represents the
format that the model should be in when passed into an API Request.
Because of this, the generated dictionary may have different
property nam... | resolve_names | identifier_name |
UserData.py | # -*- coding: utf-8 -*-
"""
InformationMachineAPILib.Models.UserData
"""
from InformationMachineAPILib.APIHelper import APIHelper
class UserData(object):
"""Implementation of the 'UserData' model.
TODO: type model description here.
Attributes:
email (string): TODO: type description her... | self.created_at = None
# Create a mapping from API property names to Model property names
replace_names = {
"email": "email",
"zip": "zip",
"user_id": "user_id",
"owner_app_id": "owner_app_id",
"created_at": "created_at",
}
... | """Constructor for the UserData class
Args:
**kwargs: Keyword Arguments in order to initialise the
object. Any of the attributes in this object are able to
be set through the **kwargs of the constructor. The values
that can be supplied and the... | identifier_body |
mypydoc.py | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
"""\
# Modifies the pydoc contained in Python to use the member function filelink
# for filelink generation, so it can be later overridden.
# See also http://bugs.python.org/issue902061
"""
#
# Copyright (C) 2009 Rene Liebscher
#
# This program is free software; you... | if __name__ == '__main__': pydoc.cli() |
# --------------------------------------- interactive interpreter interface
pydoc.html = MyHTMLDoc()
| random_line_split |
mypydoc.py | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
"""\
# Modifies the pydoc contained in Python to use the member function filelink
# for filelink generation, so it can be later overridden.
# See also http://bugs.python.org/issue902061
"""
#
# Copyright (C) 2009 Rene Liebscher
#
# This program is free software; you... |
def docmodule(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a module object."""
name = object.__name__ # ignore the passed-in name
try:
all = object.__all__
except AttributeError:
all = None
parts = split(name, '.')
... | """Create link to source file."""
return '<a href="file:%s">%s</a>' % (url, path) | identifier_body |
mypydoc.py | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
"""\
# Modifies the pydoc contained in Python to use the member function filelink
# for filelink generation, so it can be later overridden.
# See also http://bugs.python.org/issue902061
"""
#
# Copyright (C) 2009 Rene Liebscher
#
# This program is free software; you... | (pydoc.HTMLDoc):
"""Formatter class for HTML documentation."""
def filelink(self, url, path):
"""Create link to source file."""
return '<a href="file:%s">%s</a>' % (url, path)
def docmodule(self, object, name=None, mod=None, *ignored):
"""Produce HTML documentation for a module obj... | MyHTMLDoc | identifier_name |
mypydoc.py | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
"""\
# Modifies the pydoc contained in Python to use the member function filelink
# for filelink generation, so it can be later overridden.
# See also http://bugs.python.org/issue902061
"""
#
# Copyright (C) 2009 Rene Liebscher
#
# This program is free software; you... |
result = result + self.bigsection(
'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
if hasattr(object, '__author__'):
contents = self.markup(str(object.__author__), self.preformat)
result = result + self.bigsection(
'Author', '#ffffff',... | contents.append(self.document(value, key)) | conditional_block |
specialization-no-default.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 ... | (&self) {}
fn bar(&self) {}
}
impl Foo for u8 {}
impl Foo for u16 {
fn foo(&self) {} //~ ERROR E0520
}
impl Foo for u32 {
fn bar(&self) {} //~ ERROR E0520
}
////////////////////////////////////////////////////////////////////////////////
// Test 2: one layer of specialization, missing `default` on associa... | foo | identifier_name |
specialization-no-default.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 ... | }
impl<T: Clone> Baz for T {
fn baz(&self) {}
}
impl Baz for i32 {
fn baz(&self) {} //~ ERROR E0520
}
////////////////////////////////////////////////////////////////////////////////
// Test 3b: multiple layers of specialization, missing interior `default`,
// redundant `default` in bottom layer.
///////////... | default fn baz(&self) {} | random_line_split |
specialization-no-default.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 ... |
}
impl Foo for u8 {}
impl Foo for u16 {
fn foo(&self) {} //~ ERROR E0520
}
impl Foo for u32 {
fn bar(&self) {} //~ ERROR E0520
}
////////////////////////////////////////////////////////////////////////////////
// Test 2: one layer of specialization, missing `default` on associated type
//////////////////////... | {} | identifier_body |
main.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | () {
println!("Hello, world!");
let args: Vec<_> = std::env::args().collect();
if args.len() < 2 {
println!("Usage: {} <filename>", args[0]);
return;
}
let fname = std::path::Path::new(&*args[1]);
let file = fs::File::open(&fname).unwrap();
let mut archive = zip::ZipArchive... | main | identifier_name |
main.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | return;
}
let fname = std::path::Path::new(&*args[1]);
let file = fs::File::open(&fname).unwrap();
let mut archive = zip::ZipArchive::new(file).unwrap();
for i in 0..archive.len() {
let mut file = archive.by_index(i);
print_file(file);
}
}
fn print_file<'a>(
in_fil... | println!("Hello, world!");
let args: Vec<_> = std::env::args().collect();
if args.len() < 2 {
println!("Usage: {} <filename>", args[0]); | random_line_split |
main.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
let fname = std::path::Path::new(&*args[1]);
let file = fs::File::open(&fname).unwrap();
let mut archive = zip::ZipArchive::new(file).unwrap();
for i in 0..archive.len() {
let mut file = archive.by_index(i);
print_file(file);
}
}
fn print_file<'a>(
in_file: zip::result::ZipRe... | {
println!("Usage: {} <filename>", args[0]);
return;
} | conditional_block |
main.rs | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
fn print_file<'a>(
in_file: zip::result::ZipResult<zip::read::ZipFile>,
) -> zip::result::ZipResult<()> {
let file = in_file?;
println!("read file: {:?}", file.sanitized_name());
return Ok(());
}
| {
println!("Hello, world!");
let args: Vec<_> = std::env::args().collect();
if args.len() < 2 {
println!("Usage: {} <filename>", args[0]);
return;
}
let fname = std::path::Path::new(&*args[1]);
let file = fs::File::open(&fname).unwrap();
let mut archive = zip::ZipArchive::n... | identifier_body |
conf.py | # -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
... | #html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'pkgsetcompdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('let... | # will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served. | random_line_split |
gulpfile.js | /**
* Created by Deathnerd on 1/23/2015.
*/
var gulp = require('gulp');
var usemin = require('gulp-usemin');
var uglify = require('gulp-uglify');
var shell = require('gulp-shell');
var replace = require('gulp-replace');
gulp.task('usemin', function(){
gulp.src(['./src/template.html'])
.pipe(usemin({
... | 'ccjs dist/story.concat.js > dist/story.min.js'
]));
});
gulp.task('default', function(){
gulp.run('usemin');
gulp.run('closure');
}); | random_line_split | |
widgets.py | from django.core.files.uploadedfile import InMemoryUploadedFile
import re
import six
from django import forms
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.loader import render_to_string
from django.utils.encoding import force_... |
return format_html(u'<option value="{0}"{1}>{2}</option>',
option_value,
selected_html,
force_text(option_label))
| selected_html = '' | conditional_block |
widgets.py | from django.core.files.uploadedfile import InMemoryUploadedFile
import re
import six
from django import forms
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.loader import render_to_string
from django.utils.encoding import force_... | """
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
if not value or isinstance(value, InMemoryUploadedFile):
# can't display images that aren't stored
image_url = ''
else:
image_url = final_attrs['value'] = force_text(
... | in the context. | random_line_split |
widgets.py | from django.core.files.uploadedfile import InMemoryUploadedFile
import re
import six
from django import forms
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.loader import render_to_string
from django.utils.encoding import force_... | option_value = force_text(option_value)
if option_value in self.disabled_values:
selected_html = mark_safe(' disabled="disabled"')
elif option_value in selected_choices:
selected_html = mark_safe(' selected="selected"')
if not self.allow_multiple_selected:
... | identifier_body | |
widgets.py | from django.core.files.uploadedfile import InMemoryUploadedFile
import re
import six
from django import forms
from django.forms.util import flatatt
from django.forms.widgets import FileInput
from django.template import Context
from django.template.loader import render_to_string
from django.utils.encoding import force_... | (self, *args, **kwargs):
include_seconds = kwargs.pop('include_seconds', False)
super(DateTimePickerInput, self).__init__(*args, **kwargs)
if not include_seconds:
self.format = re.sub(':?%S', '', self.format)
add_js_formats(self)
class AdvancedSelect(forms.Select):
"""... | __init__ | identifier_name |
ApiClient.js | import superagent from 'superagent';
import config from '../config';
const { NODE_ENV } = process.env;
const methods = ['get', 'post', 'put', 'patch', 'del'];
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__ || NODE_ENV === 'production') {
return `${config.a... | () {
methods.forEach((method) =>
this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {
const request = superagent[method](formatUrl(path));
if (params) {
request.query(params);
}
// if (__SERVER__ && req.get('cookie')) {
// req... | constructor | identifier_name |
ApiClient.js | import superagent from 'superagent';
import config from '../config';
const { NODE_ENV } = process.env;
const methods = ['get', 'post', 'put', 'patch', 'del'];
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__ || NODE_ENV === 'production') {
return `${config.a... |
if (__CLIENT__ && window.localStorage.authToken) {
request.set('authorization', window.localStorage.authToken)
}
request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body));
}));
}
/*
* There's a V8 bug where, when using Babel, exporting classes with ... | {
request.send(data);
} | conditional_block |
ApiClient.js | import superagent from 'superagent';
import config from '../config';
const { NODE_ENV } = process.env;
const methods = ['get', 'post', 'put', 'patch', 'del'];
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__ || NODE_ENV === 'production') {
return `${config.a... |
request.end((err, { body } = {}) => err ? reject(body || err) : resolve(body));
}));
}
/*
* There's a V8 bug where, when using Babel, exporting classes with only
* constructors sometimes fails. Until it's patched, this is a solution to
* "ApiClient is not defined" from issue #14.
* https... | {
methods.forEach((method) =>
this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {
const request = superagent[method](formatUrl(path));
if (params) {
request.query(params);
}
// if (__SERVER__ && req.get('cookie')) {
// reques... | identifier_body |
ApiClient.js | import superagent from 'superagent';
import config from '../config';
const { NODE_ENV } = process.env;
const methods = ['get', 'post', 'put', 'patch', 'del'];
function formatUrl(path) {
const adjustedPath = path[0] !== '/' ? '/' + path : path;
if (__SERVER__ || NODE_ENV === 'production') { |
return '/api' + adjustedPath;
}
export default class ApiClient {
constructor() {
methods.forEach((method) =>
this[method] = (path, { params, data } = {}) => new Promise((resolve, reject) => {
const request = superagent[method](formatUrl(path));
if (params) {
request.query(para... | return `${config.apiHost}/v1${adjustedPath}`
} | random_line_split |
integration_spec.ts | declare var describe, it, expect, hot, cold, expectObservable, expectSubscriptions, console;
require('es6-shim');
import 'reflect-metadata';
import {provideStore, Store, Dispatcher, Action} from '../src/store';
import {Observable} from 'rxjs/Observable';
import {Injector, provide} from 'angular2/core';
import {counter... | expect(currentState.visibilityFilter).toEqual(VisibilityFilters.SHOW_ALL);
});
it('should add a todo', () => {
store.dispatch({ type: ADD_TODO, payload: { text: 'first todo' } });
expect(currentState.todos.length).toEqual(1);
expect(currentState.todos[0].text).toEqual('first todo');
... | });
it('should start with no todos and showing all filter', () => {
expect(currentState.todos.length).toEqual(0); | random_line_split |
playvideo.py | import urlparse
import sys,urllib
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
import urlresolver
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])
_addon = xbmcaddon.Addon()
_icon = _addon.getAddonInfo('icon')
def build_url(query):
return base_url + '?' + urlli... | (url):
duration=7500 #in milliseconds
message = "Cannot Play URL"
stream_url = urlresolver.HostedMediaFile(url=url).resolve()
# If urlresolver returns false then the video url was not resolved.
if not stream_url:
dialog = xbmcgui.Dialog()
dialog.notification("URL Resolver Error", m... | resolve_url | identifier_name |
playvideo.py | import urlparse
import sys,urllib
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
import urlresolver
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])
_addon = xbmcaddon.Addon()
_icon = _addon.getAddonInfo('icon')
def build_url(query):
return base_url + '?' + urlli... | # Create a playable item with a path to play.
play_item = xbmcgui.ListItem(path=path)
vid_url = play_item.getfilename()
stream_url = resolve_url(vid_url)
if stream_url:
play_item.setPath(stream_url)
# Pass the item to the Kodi player.
xbmcplugin.setResolvedUrl(addon_handle, True, lis... | :param path: str
""" | random_line_split |
playvideo.py | import urlparse
import sys,urllib
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
import urlresolver
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])
_addon = xbmcaddon.Addon()
_icon = _addon.getAddonInfo('icon')
def build_url(query):
return base_url + '?' + urlli... |
# addon kicks in
mode = args.get('mode', None)
if mode is None:
video_play_url = "http://www.vidsplay.com/wp-content/uploads/2017/04/alligator.mp4"
url = build_url({'mode' :'play', 'playlink' : video_play_url})
li = xbmcgui.ListItem('Play Video 1', iconImage='DefaultVideo.png')
li.setProperty('IsPl... | """
Play a video by the provided path.
:param path: str
"""
# Create a playable item with a path to play.
play_item = xbmcgui.ListItem(path=path)
vid_url = play_item.getfilename()
stream_url = resolve_url(vid_url)
if stream_url:
play_item.setPath(stream_url)
# Pass the item t... | identifier_body |
playvideo.py | import urlparse
import sys,urllib
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
import urlresolver
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])
_addon = xbmcaddon.Addon()
_icon = _addon.getAddonInfo('icon')
def build_url(query):
return base_url + '?' + urlli... | xbmcplugin.endOfDirectory(addon_handle)
elif mode[0] == 'play':
final_link = args['playlink'][0]
play_video(final_link)
| video_play_url = "http://www.vidsplay.com/wp-content/uploads/2017/04/alligator.mp4"
url = build_url({'mode' :'play', 'playlink' : video_play_url})
li = xbmcgui.ListItem('Play Video 1', iconImage='DefaultVideo.png')
li.setProperty('IsPlayable' , 'true')
xbmcplugin.addDirectoryItem(handle=addon_handle, ur... | conditional_block |
task-comm-16.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn test_str() {
let (tx, rx) = channel();
let s0 = ~"test";
tx.send(s0);
let s1 = rx.recv();
assert_eq!(s1[0], 't' as u8);
assert_eq!(s1[1], 'e' as u8);
assert_eq!(s1[2], 's' as u8);
assert_eq!(s1[3], 't' as u8);
}
#[deriving(Show)]
enum t {
tag1,
tag2(int),
tag3(int, u8, ... | {
let (tx, rx) = channel();
let v0: Vec<int> = vec!(0, 1, 2);
tx.send(v0);
let v1 = rx.recv();
assert_eq!(*v1.get(0), 0);
assert_eq!(*v1.get(1), 1);
assert_eq!(*v1.get(2), 2);
} | identifier_body |
task-comm-16.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {val0: int, val1: u8, val2: char}
let (tx, rx) = channel();
let r0: R = R {val0: 0, val1: 1u8, val2: '2'};
tx.send(r0);
let mut r1: R;
r1 = rx.recv();
assert_eq!(r1.val0, 0);
assert_eq!(r1.val1, 1u8);
assert_eq!(r1.val2, '2');
}
fn test_vec() {
let (tx, rx) = channel();
let v0... | R | identifier_name |
task-comm-16.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn eq(&self, other: &t) -> bool {
match *self {
tag1 => {
match (*other) {
tag1 => true,
_ => false
}
}
tag2(e0a) => {
match (*other) {
tag2(e0b) => e0a == e0b,
... | tag2(int),
tag3(int, u8, char)
}
impl cmp::Eq for t { | random_line_split |
uiSilentPref.js | /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
Components.utils.import("resource://testing-common/MockRegistrar.jsm");
/**
* Test that nsIUpdatePrompt doesn't display UI for showUpdateAvailable and
* showUpdateError when the app.update.silent preference ... | () {
do_throw("showUpdateAvailable should not have called openWindow!");
}
function check_showUpdateError() {
do_throw("showUpdateError should not have seen getNewPrompter!");
}
| check_showUpdateAvailable | identifier_name |
uiSilentPref.js | /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
Components.utils.import("resource://testing-common/MockRegistrar.jsm");
/**
* Test that nsIUpdatePrompt doesn't display UI for showUpdateAvailable and
* showUpdateError when the app.update.silent preference ... | do_throw("showUpdateError should not have seen getNewPrompter!");
} | random_line_split | |
uiSilentPref.js | /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
*/
Components.utils.import("resource://testing-common/MockRegistrar.jsm");
/**
* Test that nsIUpdatePrompt doesn't display UI for showUpdateAvailable and
* showUpdateError when the app.update.silent preference ... | STATE_FAILED);
let updates = getLocalUpdateString(patches);
writeUpdatesToXMLFile(getLocalUpdatesXMLString(updates), true);
writeStatusFile(STATE_FAILED);
reloadUpdateManagerData();
gCheckFunc = check_showUpdateAvailable;
let update = gUpdateManager.activeUpdate;
gUP.s... | {
setupTestCommon();
debugDump("testing nsIUpdatePrompt notifications should not be seen " +
"when the " + PREF_APP_UPDATE_SILENT + " preference is true");
Services.prefs.setBoolPref(PREF_APP_UPDATE_SILENT, true);
let windowWatcherCID =
MockRegistrar.register("@mozilla.org/embedcomp/window-wa... | identifier_body |
php4dvd_negative.py | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException... |
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
| alert.accept() | conditional_block |
php4dvd_negative.py | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException... | (self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
| tearDown | identifier_name |
php4dvd_negative.py | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException... |
def test_untitled(self):
driver = self.driver
driver.get(self.base_url + "/php4dvd/")
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys("admin")
driver.find_element_by_name("password").clear()
driver.find_element_by_na... | self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "http://localhost/"
self.verificationErrors = []
self.accept_next_alert = True | identifier_body |
php4dvd_negative.py | # -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException... | unittest.main() | self.assertEqual([], self.verificationErrors)
if __name__ == "__main__": | random_line_split |
lib.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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | }
macro_rules! reexport_computed_values {
( $( $name: ident )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_values {
$(
pub use properties::longhands::$name::computed... | #[allow(unsafe_code)]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/properties.rs")); | random_line_split |
weights.py | # Copyright (c) 2011-2012 OpenStack Foundation
# 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
#
# Un... |
class BaseWeigher(object):
"""Base class for pluggable weighers.
The attributes maxval and minval can be specified to set up the maximum
and minimum values for the weighed objects. These values will then be
taken into account in the normalization step, instead of taking the values
from the calcu... | """Object with weight information."""
def __init__(self, obj, weight):
self.obj = obj
self.weight = weight
def __repr__(self):
return "<WeighedObject '%s': %s>" % (self.obj, self.weight) | identifier_body |
weights.py | # Copyright (c) 2011-2012 OpenStack Foundation
# 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
#
# Un... | (self, weigher_classes, obj_list,
weighing_properties):
"""Return a sorted (descending), normalized list of WeighedObjects."""
if not obj_list:
return []
weighed_objs = [self.object_class(obj, 0.0) for obj in obj_list]
for weigher_cls in weigher_classes:
... | get_weighed_objects | identifier_name |
weights.py | # Copyright (c) 2011-2012 OpenStack Foundation
# 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
#
# Un... |
if maxval is None:
maxval = max(weight_list)
if minval is None:
minval = min(weight_list)
maxval = float(maxval)
minval = float(minval)
if minval == maxval:
return [0] * len(weight_list)
range_ = maxval - minval
return ((i - minval) / range_ for i in weight_list... | return () | conditional_block |
weights.py | # Copyright (c) 2011-2012 OpenStack Foundation
# 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
#
# Un... | def __init__(self, obj, weight):
self.obj = obj
self.weight = weight
def __repr__(self):
return "<WeighedObject '%s': %s>" % (self.obj, self.weight)
class BaseWeigher(object):
"""Base class for pluggable weighers.
The attributes maxval and minval can be specified to set up th... |
class WeighedObject(object):
"""Object with weight information.""" | random_line_split |
resto_druid_mastery.rs | URAS: &'static [u32] = &[
774, // Rejuv
155777, // Rejuv (Germ)
];
static LIVING_SEED_HEALS: &'static [u32] = &[5185, 8936, 18562];
const AURA_2PC: u32 = 232378;
const SPELL_REGROWTH: u32 = 8936;
const SPELL_TRANQ: u32 = 157982;
const MASTERY_2PC: u32 = 4000;
pub fn find_init_mastery<'a, I: Iterator<Item=... | // Only measure the contribution to other heals
if aura != id {
let added = (unmast as f64 * mastery) as u64;
*self.hot_mastery_healing_added.entry(aura).or_insert(0) += added;
}
... | for &aura in &entry.0 { | random_line_split |
resto_druid_mastery.rs | AS: &'static [u32] = &[
774, // Rejuv
155777, // Rejuv (Germ)
];
static LIVING_SEED_HEALS: &'static [u32] = &[5185, 8936, 18562];
const AURA_2PC: u32 = 232378;
const SPELL_REGROWTH: u32 = 8936;
const SPELL_TRANQ: u32 = 157982;
const MASTERY_2PC: u32 = 4000;
pub fn find_init_mastery<'a, I: Iterator<Item=En... | if log.base().is_none() {
return;
}
let base = log.base().unwrap();
if base.src.id != self.player_id {
return;
}
let entry = self.map.entry(log.base().unwrap().dst.id).or_insert((HashSet::new(), log.timestamp()));
let diff = log.timestamp()... | {
use wow_combat_log::Entry::*;
use wow_combat_log::AuraType::*;
if let Info { id, mastery, ref auras, .. } = *log {
let entry = self.map.entry(id).or_insert((HashSet::new(), log.timestamp()));
let player_id = self.player_id;
if player_id == id {
... | identifier_body |
resto_druid_mastery.rs | AS: &'static [u32] = &[
774, // Rejuv
155777, // Rejuv (Germ)
];
static LIVING_SEED_HEALS: &'static [u32] = &[5185, 8936, 18562];
const AURA_2PC: u32 = 232378;
const SPELL_REGROWTH: u32 = 8936;
const SPELL_TRANQ: u32 = 157982;
const MASTERY_2PC: u32 = 4000;
pub fn | <'a, I: Iterator<Item=Entry<'a>>>(iter: I, player: &str) -> Option<(&'a str, u32)> {
let mut map = HashMap::new();
let mut player_id = None;
for log in iter {
if player_id.is_none() {
if let Some(base) = log.base() {
let id;
if base.src.name == player {
... | find_init_mastery | identifier_name |
type_names.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 ... | push_type_params(cx, substs, output);
},
ty::TyTuple(ref component_types) => {
output.push('(');
for &component_type in component_types {
push_debuginfo_type_name(cx, component_type, true, output);
output.push_str(", ");
}
... | {
match t.sty {
ty::TyBool => output.push_str("bool"),
ty::TyChar => output.push_str("char"),
ty::TyStr => output.push_str("str"),
ty::TyInt(ast::TyIs) => output.push_str("isize"),
ty::TyInt(ast::TyI8) => output.push_str("i8"),
... | identifier_body |
type_names.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 ... | ty::TyFloat(ast::TyF64) => output.push_str("f64"),
ty::TyStruct(def_id, substs) |
ty::TyEnum(def_id, substs) => {
push_item_name(cx, def_id, qualified, output);
push_type_params(cx, substs, output);
},
ty::TyTuple(ref component_types) => {
outp... | ty::TyUint(ast::TyU64) => output.push_str("u64"),
ty::TyFloat(ast::TyF32) => output.push_str("f32"), | random_line_split |
type_names.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 ... | <'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
t: Ty<'tcx>,
qualified: bool)
-> String {
let mut result = String::with_capacity(64);
push_debuginfo_type_name(cx, t, qualified, &mut res... | compute_debuginfo_type_name | identifier_name |
type_names.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 ... |
let mut path_element_count = 0;
for path_element in path {
let name = token::get_name(path_element.name());
output.push_str(&name);
output.push_str("::");
path_element_count += 1;
}
... | {
output.push_str(crate_root_namespace(cx));
output.push_str("::");
} | conditional_block |
karrierevideos.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
fix_xml_ampersands,
float_or_none,
xpath_with_ns,
xpath_text,
)
class KarriereVideosIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?karrierevid... | 'description': 'md5:97092c6ad1fd7d38e9d6a5fdeb2bcc33',
'thumbnail': r're:^http://.*\.png',
},
'params': {
# rtmp download
'skip_download': True,
}
}]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = s... | 'title': 'Väterkarenz und neue Chancen für Mütter - "Baby - was nun?"', | random_line_split |
karrierevideos.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
fix_xml_ampersands,
float_or_none,
xpath_with_ns,
xpath_text,
)
class KarriereVideosIE(InfoExtractor):
| 'title': 'Väterkarenz und neue Chancen für Mütter - "Baby - was nun?"',
'description': 'md5:97092c6ad1fd7d38e9d6a5fdeb2bcc33',
'thumbnail': r're:^http://.*\.png',
},
'params': {
# rtmp download
'skip_download': True,
}
}]
def _... | _VALID_URL = r'https?://(?:www\.)?karrierevideos\.at(?:/[^/]+)+/(?P<id>[^/]+)'
_TESTS = [{
'url': 'http://www.karrierevideos.at/berufsvideos/mittlere-hoehere-schulen/altenpflegerin',
'info_dict': {
'id': '32c91',
'ext': 'flv',
'title': 'AltenpflegerIn',
... | identifier_body |
karrierevideos.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
fix_xml_ampersands,
float_or_none,
xpath_with_ns,
xpath_text,
)
class KarriereVideosIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?karrierevid... | lf, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
title = (self._html_search_meta('title', webpage, default=None) or
self._search_regex(r'<h1 class="title">([^<]+)</h1>', webpage, 'video title'))
video_id = self._search_regex(
... | al_extract(se | identifier_name |
karrierevideos.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
fix_xml_ampersands,
float_or_none,
xpath_with_ns,
xpath_text,
)
class KarriereVideosIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?karrierevid... | return {
'id': video_id,
'url': streamer.replace('rtmpt', 'rtmp'),
'play_path': 'mp4:%s' % video_file,
'ext': 'flv',
'title': title,
'description': description,
'thumbnail': thumbnail,
'uploader': uploader,
... | mbnail = compat_urlparse.urljoin(url, thumbnail)
| conditional_block |
serializer.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... |
else:
raise Exception("Serializer for '%s' does not exist!" % dformat)
def getMIMEType(self):
return self._mime
def set_headers(self, response):
response.content_type = self.getMIMEType()
def __call__(self, obj, *args, **kwargs):
self._obj = obj
self._... | return serializer(query_params, **kwargs) | conditional_block |
serializer.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | (self, query_params, pretty=False, **kwargs):
self.pretty = pretty
self._query_params = query_params
self._fileName = None
self._lastModified = None
self._extra_args = kwargs
@classmethod
def register(cls, tag, serializer):
cls.registry[tag] = serializer
@cl... | __init__ | identifier_name |
serializer.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... |
@classmethod
def register(cls, tag, serializer):
cls.registry[tag] = serializer
@classmethod
def getAllFormats(cls):
return list(cls.registry)
@classmethod
def create(cls, dformat, query_params=None, **kwargs):
"""
A serializer factory
"""
que... | self.pretty = pretty
self._query_params = query_params
self._fileName = None
self._lastModified = None
self._extra_args = kwargs | identifier_body |
serializer.py | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | """
query_params = query_params or {}
serializer = cls.registry.get(dformat)
if serializer:
return serializer(query_params, **kwargs)
else:
raise Exception("Serializer for '%s' does not exist!" % dformat)
def getMIMEType(self):
return self.... | A serializer factory | random_line_split |
setup.py | from distutils.core import setup, Extension
setup (name = 'krbV',
version = '1.0.90',
description = 'Kerberos V Bindings for Python',
long_description = """
python-krbV allows python programs to use Kerberos 5 authentication/security
""",
author = 'Test',
author_email = 'mikeb@redhat.com',
classifiers = [... | libraries = ['krb5', 'com_err']
)
]
) | random_line_split | |
RainGeometry.js | import THREE from 'three';
const simplex = new(require('simplex-noise'))
const random = require('random-float')
const randomInt = require('random-int')
import NewtonParticle from '../Helpers/NewtonParticle'
const NUM_PARTICLES = 30
const MAX_HEIGHT = 4
/**
* CubeGeometry class
*/
class RainGeometry extends THREE.B... | /**
* Update function
* @param {number} time Time
*/
update(time) {
this.updateMover()
this.attributes.position.needsUpdate = true;
this.attributes.vertexOpacity.needsUpdate = true;
this.attributes.size.needsUpdate = true;
this.attributes.customColor.needsUpdate = true;
}
getInit... | random_line_split | |
RainGeometry.js | import THREE from 'three';
const simplex = new(require('simplex-noise'))
const random = require('random-float')
const randomInt = require('random-int')
import NewtonParticle from '../Helpers/NewtonParticle'
const NUM_PARTICLES = 30
const MAX_HEIGHT = 4
/**
* CubeGeometry class
*/
class RainGeometry extends THREE.B... | this.positions[i * 3 + 0] = mover.getPosition().x;
this.positions[i * 3 + 1] = mover.getPosition().y;
this.positions[i * 3 + 2] = mover.getPosition().z;
color.toArray(this.colors, i * 3);
this.opacities[i] = mover.getAlpha()
this.sizes[i] = mover.getSize()
}
this.addAttrib... | {
const mover = new NewtonParticle()
mover.setPosition(this.getInitialPosition())
var h = randomInt(0, 45);
var s = randomInt(60, 90);
var color = new THREE.Color('hsl(' + h + ', ' + s + '%, 50%)');
color.setHSL((180+Math.random()*40)/360, 1.0, 0.5 + Math.random() * 0.2);
... | conditional_block |
RainGeometry.js | import THREE from 'three';
const simplex = new(require('simplex-noise'))
const random = require('random-float')
const randomInt = require('random-int')
import NewtonParticle from '../Helpers/NewtonParticle'
const NUM_PARTICLES = 30
const MAX_HEIGHT = 4
/**
* CubeGeometry class
*/
class RainGeometry extends THREE.B... | () {
return new THREE.Vector3(random(-2, 2), random(3, 5), random(-1, 1))
}
getInitialVelocity() {
const vel = new THREE.Vector3(random(-0.01, 0.01), random(-0.1, -0.2), random(-0.01, 0.01))
vel.divideScalar(10)
return vel
}
setRaining(raining) {
for (var i = 0; i < this.particles.length;... | getInitialPosition | identifier_name |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | () {
let service = IoService::<MyMessage>::start().expect("Error creating network service");
service.register_handler(Arc::new(MyHandler)).unwrap();
}
}
| test_service_register_handler | identifier_name |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | //!
//! fn main () {
//! let mut service = IoService::<MyMessage>::start().expect("Error creating network service");
//! service.register_handler(Arc::new(MyHandler)).unwrap();
//!
//! // Wait for quit condition
//! // ...
//! // Drop the service
//! }
//! ```
extern crate mio;
#[macro_use]
extern crate log as rl... | //! }
//! } | random_line_split |
lib.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
/// Register a new stream with the event loop
fn register_stream(&self, _stream: StreamToken, _reg: Token, _event_loop: &mut EventLoop<IoManager<Message>>) {}
/// Re-register a stream with the event loop
fn update_stream(&self, _stream: StreamToken, _reg: Token, _event_loop: &mut EventLoop<IoManager<Message>>) {}
... | {} | identifier_body |
digest_spec.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 {computeMsgId, digest, sha1} from '../../src/i18n/digest';
export function main(): void | it('should returns the sha1 of "hello world"',
() => { expect(sha1('abc')).toEqual('a9993e364706816aba3e25717850c26c9cd0d89d'); });
it('should returns the sha1 of unicode strings',
() => { expect(sha1('你好,世界')).toEqual('3becb03b015ed48050611c8d7afe4b88f70d5a20'); });
it('should sup... | {
describe('digest', () => {
describe('digest', () => {
it('must return the ID if it\'s explicit', () => {
expect(digest({
id: 'i',
nodes: [],
placeholders: {},
placeholderToMessage: {},
meaning: '',
description: '',
sources: [],
... | identifier_body |
digest_spec.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 {computeMsgId, digest, sha1} from '../../src/i18n/digest';
export function | (): void {
describe('digest', () => {
describe('digest', () => {
it('must return the ID if it\'s explicit', () => {
expect(digest({
id: 'i',
nodes: [],
placeholders: {},
placeholderToMessage: {},
meaning: '',
description: '',
sour... | main | identifier_name |
digest_spec.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 {computeMsgId, digest, sha1} from '../../src/i18n/digest';
export function main(): void {
describe('digest... | ).toEqual('2122606631351252558');
});
});
});
}
| Id(result, '');
while (result.length < size) {
result += result;
}
result = result.slice(-size);
}
expect(computeMsgId(result, '') | conditional_block |
digest_spec.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 {computeMsgId, digest, sha1} from '../../src/i18n/digest';
export function main(): void {
describe('digest... | });
it('should support arbitrary string size', () => {
const prefix = `你好,世界`;
let result = computeMsgId(prefix, '');
for (let size = prefix.length; size < 5000; size += 101) {
result = prefix + computeMsgId(result, '');
while (result.length < size) {
... |
Object.keys(fixtures).forEach(
id => { expect(computeMsgId(fixtures[id][0], fixtures[id][1])).toEqual(id); }); | random_line_split |
$_attr-linked.js | const regAttr = /="*'*\{*([_a-z\-0-9$]+)}*'*"*/;
const regStart = /^\[/;
const $ = window.rb.$;
/**
* Finds attribute linked elements on the first element in collection.
* @function external:"jQuery.fn".attrLinked
* @param {String} attributeSelector Attribute selector pattern to search for. ("[aria-controls="${id}"... | $.fn.attrLinked = function (attributeSelector) {
let newCollection;
let elem = this.get(0);
if (elem) {
const valueAttr = attributeSelector.match(regAttr);
if(valueAttr){
let value = elem[valueAttr[1]];
if(!value || typeof value != 'string'){
value ... | * $('#yo').attrLinked('data-target={id}'); // returns '[data-target="yo"]' elements.
* $('#yo').attrLinked('data-target={id}').attrLinked('id={data-target}'); // returns '[id="yo"]' elements.
*/ | random_line_split |
$_attr-linked.js | const regAttr = /="*'*\{*([_a-z\-0-9$]+)}*'*"*/;
const regStart = /^\[/;
const $ = window.rb.$;
/**
* Finds attribute linked elements on the first element in collection.
* @function external:"jQuery.fn".attrLinked
* @param {String} attributeSelector Attribute selector pattern to search for. ("[aria-controls="${id}"... |
}
return newCollection || $([]);
};
| {
let value = elem[valueAttr[1]];
if(!value || typeof value != 'string'){
value = elem.getAttribute(valueAttr[1]) || '';
}
if(!regStart.test(attributeSelector)){
attributeSelector = `[${attributeSelector}]`;
}
new... | conditional_block |
gallery.js | #!/usr/bin/env node
var sys = require('sys'), | core: '@2010.12.06',
gallery: '2010.09.22'
});
YUI3({
debug: true
}).use('node', 'gallery-yql', function(Y) {
new Y.yql('select * from github.user.info where (id = "davglass")', function(r) {
//Do something here.
Y.log(r.query, 'debug', 'yql');
});
console.log('Gallery: ... | yui3 = require("yui3");
var YUI = yui3.YUI;
var YUI3 = yui3.configure({ | random_line_split |
gae_settings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Sof... |
NETADMIN_APPS = (
'netadmin',
'netadmin.reportmeta',
'netadmin.webapi',
'netadmin.networks',
'netadmin.events',
'netadmin.users',
'netadmin.permissions',
'netadmin.notifier',
'netadmin.utils.charts',
'netadmin.plugins'
)
INSTALLED_APPS += NETADMIN_APPS
MIDDLEWARE_CLASSES = (
... | INSTALLED_APPS += ('django.contrib.staticfiles',) | conditional_block |
gae_settings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Sof... | 'netadmin.networks',
'netadmin.events',
'netadmin.users',
'netadmin.permissions',
'netadmin.notifier',
'netadmin.utils.charts',
'netadmin.plugins'
)
INSTALLED_APPS += NETADMIN_APPS
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middlewa... | NETADMIN_APPS = (
'netadmin',
'netadmin.reportmeta',
'netadmin.webapi', | random_line_split |
extract-config.ts | import * as fs from "fs-extra";
import * as lib from "../lib";
import * as oclif from "@oclif/command";
export default class ExtractConfig extends oclif.Command {
static description = "create a config file for 'eta init' based on the current eta setup";
async run() {
const moduleNames = ["eta"].concat... | config.github = `${shortUrl}#${branch}`;
} else {
if (!config.modules) config.modules = [];
config.modules.push({
name: moduleName,
github: `${shortUrl}#${branch}`
});
}
}
this... | if (moduleName === "eta") { | random_line_split |
extract-config.ts | import * as fs from "fs-extra";
import * as lib from "../lib";
import * as oclif from "@oclif/command";
export default class | extends oclif.Command {
static description = "create a config file for 'eta init' based on the current eta setup";
async run() {
const moduleNames = ["eta"].concat(await fs.readdir(lib.WORKING_DIR + "/modules"));
const name = (await lib.exec("basename `pwd`")).stdout.trim();
const conf... | ExtractConfig | identifier_name |
extract-config.ts | import * as fs from "fs-extra";
import * as lib from "../lib";
import * as oclif from "@oclif/command";
export default class ExtractConfig extends oclif.Command {
static description = "create a config file for 'eta init' based on the current eta setup";
async run() {
const moduleNames = ["eta"].concat... |
const branch = (await lib.exec("git symbolic-ref --short HEAD", { cwd })).stdout.trim();
const repoUrl = (await lib.exec("git config --get remote.origin.url", { cwd })).stdout.trim();
const match = repoUrl && repoUrl.match(/git@github\.com:(.*)/);
const shortUrl = (matc... | {
this.warn(`\tModule ${moduleName} does not exist.`);
continue;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.