file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
ng_module.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 {ApplicationRef} from '../application_ref';
import {InjectorType, ɵɵdefineInjector} from '../di/interface/def... | *
* ### Example
*
* The following example allows MainModule to use anything exported by
* `CommonModule`:
*
* ```javascript
* @NgModule({
* imports: [CommonModule]
* })
* class MainModule {
* }
* ```
*
*/
imports?: Array<Type<any>|ModuleWithProviders<{}>|any[]>;
/**
... | random_line_split | |
ng_module.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 {ApplicationRef} from '../application_ref';
import {InjectorType, ɵɵdefineInjector} from '../di/interface/def... | eType: Type<any>, metadata?: NgModule): void {
let imports = (metadata && metadata.imports) || [];
if (metadata && metadata.exports) {
imports = [...imports, metadata.exports];
}
(moduleType as InjectorType<any>).ɵinj = ɵɵdefineInjector({
factory: convertInjectableProviderToFactory(moduleType, {useClas... | gModuleCompile(modul | identifier_name |
ng_module.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 {ApplicationRef} from '../application_ref';
import {InjectorType, ɵɵdefineInjector} from '../di/interface/def... | const SWITCH_COMPILE_NGMODULE__POST_R3__ = render3CompileNgModule;
const SWITCH_COMPILE_NGMODULE__PRE_R3__ = preR3NgModuleCompile;
const SWITCH_COMPILE_NGMODULE: typeof render3CompileNgModule = SWITCH_COMPILE_NGMODULE__PRE_R3__;
| t imports = (metadata && metadata.imports) || [];
if (metadata && metadata.exports) {
imports = [...imports, metadata.exports];
}
(moduleType as InjectorType<any>).ɵinj = ɵɵdefineInjector({
factory: convertInjectableProviderToFactory(moduleType, {useClass: moduleType}),
providers: metadata && metadat... | identifier_body |
ng_module.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 {ApplicationRef} from '../application_ref';
import {InjectorType, ɵɵdefineInjector} from '../di/interface/def... | oduleType as InjectorType<any>).ɵinj = ɵɵdefineInjector({
factory: convertInjectableProviderToFactory(moduleType, {useClass: moduleType}),
providers: metadata && metadata.providers,
imports: imports,
});
}
export const SWITCH_COMPILE_NGMODULE__POST_R3__ = render3CompileNgModule;
const SWITCH_COMPILE_NGM... | imports = [...imports, metadata.exports];
}
(m | conditional_block |
paper-action-button-option.js | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import contrast from 'contrast';
import Icon from './icon';
export default class PaperActionButtonOption extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(th... |
}
PaperActionButtonOption.defaultProps = {
onClick: () => {},
__close: () => {}
};
PaperActionButtonOption.propTypes = {
__badgeStyle: PropTypes.object,
color: PropTypes.string,
iconName: PropTypes.string.isRequired,
__labelStyle: PropTypes.object,
label: PropTypes.string.isRequired,
onClick: PropTyp... | {
const {
label,
color,
__badgeStyle,
__labelStyle,
onClick,
iconName,
__close,
...props
} = this.props;
const bgColorShade = color ? contrast(color) : 'light';
return (
<div className="paper-action-button__option" {...props}>
<label style={... | identifier_body |
paper-action-button-option.js | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import contrast from 'contrast';
import Icon from './icon';
export default class PaperActionButtonOption extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(th... | >
<Icon>{iconName}</Icon>
</button>
</div>
);
}
}
PaperActionButtonOption.defaultProps = {
onClick: () => {},
__close: () => {}
};
PaperActionButtonOption.propTypes = {
__badgeStyle: PropTypes.object,
color: PropTypes.string,
iconName: PropTypes.string.isRequired,
__l... | onClick={this.handleClick}
onMouseUp={() => this.myRef.blur()}
ref={myRef => {
this.myRef = myRef;
}} | random_line_split |
paper-action-button-option.js | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import contrast from 'contrast';
import Icon from './icon';
export default class PaperActionButtonOption extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(th... | (e) {
this.props.onClick(e);
this.props.__close();
}
render() {
const {
label,
color,
__badgeStyle,
__labelStyle,
onClick,
iconName,
__close,
...props
} = this.props;
const bgColorShade = color ? contrast(color) : 'light';
return (
<div... | handleClick | identifier_name |
values.test.js | const StitchMongoFixture = require('../fixtures/stitch_mongo_fixture');
import {getAuthenticatedClient} from '../testutil';
describe('Values V2', ()=>{
let test = new StitchMongoFixture();
let apps;
let app;
beforeAll(() => test.setup({createApp: false}));
afterAll(() => test.teardown());
beforeEach(async... | expect(deepValue.value).toEqual('foo');
delete deepValue.value;
expect(value).toEqual(deepValue);
});
it('can update a value', async () => {
let value = await appValues.create({name: testValueName, value: 'foo'});
value.value = '"abcdefgh"';
await appValues.value(value._id).update(value);
... | let value = await appValues.create({name: testValueName, value: 'foo'});
const deepValue = await appValues.value(value._id).get(); | random_line_split |
NetTest.js | var numberOfPagesToOpen = 10;
var url = '';
var system = require('system');
var args = system.args;
var failures = 0;
if (args.length === 1) {
console.log('Usage:\nphantomjs http://url 100\nReturns how long it takes to load url 100 times.');
phantom.exit(0);
} else {
var url = args[1] || 'https://google.co... | var getElapsedTime = function(date) {
return date - startTime;
};
var startTest = function() {
startTime = new Date();
console.log('Testing ' + url + ' ' + numberOfPagesToOpen + ' times.');
openPage();
};
var continueTest = function() {
console.log('page ' + numberOfPagesOpened + ': ' + getElapse... | random_line_split | |
NetTest.js | var numberOfPagesToOpen = 10;
var url = '';
var system = require('system');
var args = system.args;
var failures = 0;
if (args.length === 1) | else {
var url = args[1] || 'https://google.com/';
numberOfPagesToOpen = args[2] ? args[2] : 10;
}
var page = require('webpage').create();
var startTime = new Date();
var numberOfPagesOpened = 0;
var getElapsedTime = function(date) {
return date - startTime;
};
var startTest = function() {
startTime... | {
console.log('Usage:\nphantomjs http://url 100\nReturns how long it takes to load url 100 times.');
phantom.exit(0);
} | conditional_block |
turkish.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="tr">
<context>
<name>U2::OpenCLSupportPlugin</name>
<message>
<location filename="../src/OpenCLSupportPlugin.cpp" line="52"/>
<source>Problem occurred loading the OpenCL driver. Please try to update drivers if ... | </context>
<context>
<name>U2::OpenCLSupportSettingsPageController</name>
<message>
<location filename="../src/OpenCLSupportSettingsController.cpp" line="36"/>
<source>OpenCL</source>
<translation>OpenCL</translation>
</message>
</context>
</TS> | </message> | random_line_split |
pickadate.tr_TR.js | // Turkish
$.extend( $.fn.pickadate.defaults, {
monthsFull: [ 'Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık' ],
monthsShort: [ 'Oca', 'Şub', 'Mar', 'Nis', 'May', 'Haz', 'Tem', 'Ağu', 'Eyl', 'Eki', 'Kas', 'Ara' ],
weekdaysFull: [ 'Pazar', 'Pazar... | formatSubmit: 'yyyy/mm/dd'
}) | format: 'dd mmmm yyyy dddd', | random_line_split |
index.d.ts | // Type definitions for watchify 3.11
// Project: https://github.com/substack/watchify
// Definitions by: TeamworkGuy2 <https://github.com/TeamworkGuy2>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
import Browserify = requ... | * Enables polling to monitor for changes. If set to `true`, then a polling interval of 100 ms is used.
* If set to a number, then that amount of milliseconds will be the polling interval. For more info see
* Chokidar's documentation on "usePolling" and "interval".
* This option is us... | /** | random_line_split |
roger.py | #!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n... |
def getScriptCall(root, command, command_args):
script_call = "roger_{}.py".format(command)
for command_arg in command_args:
script_call = script_call + " {}".format(command_arg)
return script_call
def main():
root = ''
utilsObj = Utils()
own_dir = os.path.dirname(os.path.realpath(... | commands = set()
for filename in files:
if filename.startswith("roger_"):
commands.add(re.split("roger_|\.", filename)[1])
return sorted(commands) | identifier_body |
roger.py | #!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n... | (files):
commands = set()
for filename in files:
if filename.startswith("roger_"):
commands.add(re.split("roger_|\.", filename)[1])
return sorted(commands)
def getScriptCall(root, command, command_args):
script_call = "roger_{}.py".format(command)
for command_arg in command_ar... | getCommands | identifier_name |
roger.py | #!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n... | main() | conditional_block | |
roger.py | #!/usr/bin/python
from __future__ import print_function
import os
import sys
import subprocess
import re
import importlib
from cli.utils import Utils
def print_help_opt(opt, desc):
print(" {} {}".format(opt.ljust(13), desc))
def roger_help(root, commands):
print("usage: roger [-h] [-v] command [arg...]\n... | if command in commands:
print("root: {} command: {} args: {}".format(
root, command, command_args
))
script_call = getScriptCall(root, command, command_args)
os.system(script_call)
else:
raise Sys... | command_args = sys.argv[2:] | random_line_split |
maptune.GoogleV2.js | /**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter... |
/**
* Is called to set event handler
*/
function _map_addEventListner(map,szEvent,callback,mapUp){
if (map){
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
... |
/* tbd */
}
| identifier_body |
maptune.GoogleV2.js | /**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter... |
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if (map){
var mapCenter = { lon: (bBox[0] + (bBox[1]-bBox[0])/2) , lat: (bBox[2] + (bBox[3]-bBox[2])/2) };
var mapZoo... |
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
| conditional_block |
maptune.GoogleV2.js | /**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter... | map,szEvent,callback,mapUp){
if (map){
GEvent.addListener(map, szEvent, GEvent.callback(map,callback,mapUp) );
}
}
/**
* Is called 'onunload' to clear objects
*/
function _map_unloadMap(map){
if (map){
GUnload();
}
}
// set map center and zoom
//
function _map_setMapExtension(map,bBox){
if ... | map_addEventListner( | identifier_name |
maptune.GoogleV2.js | /**********************************************************************
map_GoogleV2.js
$Comment: provides JavaScript for Google Api V2 calls
$Source :map_GoogleV2.js,v $
$InitialAuthor: guenter richter $
$InitialDate: 2011/01/03 $
$Author: guenter richter $
$Id:map_GoogleV2.js 1 2011-01-03 10:30:35Z Guenter... | //
function _map_setZoom(map,nZoom){
if (map){
map.setZoom(nZoom);
}
}
// set map center
//
function _map_setCenter(map,center){
if (map){
map.setCenter(center);
}
}
// set map center and zoom
//
function _map_setCenterAndZoom(map,center,nZoom){
if (map){
map.setCenter(center,nZoom);
}
}... | }
return null;
}
// set map zoom
| random_line_split |
plot_ticpe_accises.py | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 17 15:48:31 2015
@author: thomas.douenne
"""
# L'objectif est de décrire l'évolution des montants des accises de la TICPE depuis 1993 |
# Recherche des paramètres de la législation
liste = ['ticpe_gazole', 'ticpe_super9598', 'super_plombe_ticpe']
df_accises = get_accise_ticpe_majoree()
# Réalisation des graphiques
graph_builder_bar_list(df_accises['accise majoree sans plomb'], 1, 1)
graph_builder_bar_list(df_accises['accise majoree diesel'], 1, 1)
gr... |
# Import de fonctions spécifiques à Openfisca Indirect Taxation
from openfisca_france_indirect_taxation.examples.utils_example import graph_builder_bar_list
from openfisca_france_indirect_taxation.examples.dataframes_from_legislation.get_accises import \
get_accise_ticpe_majoree | random_line_split |
canvaslayerrenderer.test.js | goog.provide('ol.test.renderer.canvas.Layer');
describe('ol.renderer.canvas.Layer', function() {
describe('#composeFrame()', function() {
it('clips to layer extent and draws image', function() {
var layer = new ol.layer.Image({
extent: [1, 2, 3, 4]
});
var renderer = new ol.renderer.c... | save: sinon.spy(),
restore: sinon.spy(),
translate: sinon.spy(),
rotate: sinon.spy(),
beginPath: sinon.spy(),
moveTo: sinon.spy(),
lineTo: sinon.spy(),
clip: sinon.spy(),
drawImage: sinon.spy()
};
renderer.composeFrame(frameState, layer... | };
ol.renderer.Map.prototype.calculateMatrices2D(frameState);
var layerState = layer.getLayerState();
var context = { | random_line_split |
2_3_Spec.js | require('../../test_helper');
describe('2.3 #FindMiddle', function () {
describe('return middle Node', function () {
var sll;
beforeEach(function() {
sll = new MyLinkedList();
for(var i=1; i < 6; i++) {
sll.addNode( i + 'Node', null);
}
});
| });
it('should return correct length of LinkedList', function () {
expect(sll).length.to.be(5);
});
it('should remove the middle node with aceess to the head of SLL', function () {
sll.findMiddleAndRemove(sll.head);
expect(sll).length.to.be(4);
});
it('should remove the midd... | afterEach(function() {
sll = null; | random_line_split |
2_3_Spec.js | require('../../test_helper');
describe('2.3 #FindMiddle', function () {
describe('return middle Node', function () {
var sll;
beforeEach(function() {
sll = new MyLinkedList();
for(var i=1; i < 6; i++) |
});
afterEach(function() {
sll = null;
});
it('should return correct length of LinkedList', function () {
expect(sll).length.to.be(5);
});
it('should remove the middle node with aceess to the head of SLL', function () {
sll.findMiddleAndRemove(sll.head);
expect(sll).l... | {
sll.addNode( i + 'Node', null);
} | conditional_block |
setup.py | import os
from setuptools import setup
from setuptools import find_packages | shortdesc = "Klarna Payment for bda.plone.shop"
setup(
name='bda.plone.klarnapayment',
version=version,
description=shortdesc,
classifiers=[
'Environment :: Web Environment',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
... |
version = '0.1' | random_line_split |
views.py | from django.core import serializers
from rest_framework.response import Response
from django.http import JsonResponse
try:
from urllib import quote_plus # python 2
except:
pass
try:
from urllib.parse import quote_plus # python 3
except:
pass
from django.contrib import messages
from django.contrib.co... |
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instan... |
def post_create(request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404 | random_line_split |
views.py | from django.core import serializers
from rest_framework.response import Response
from django.http import JsonResponse
try:
from urllib import quote_plus # python 2
except:
pass
try:
from urllib.parse import quote_plus # python 3
except:
pass
from django.contrib import messages
from django.contrib.co... |
context = {
"form": form,
}
return render(request, "post_form.html", context)
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_super... | instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
messages.success(request, "Successfully Created")
return HttpResponseRedirect(instance.get_absolute_url()) | conditional_block |
views.py | from django.core import serializers
from rest_framework.response import Response
from django.http import JsonResponse
try:
from urllib import quote_plus # python 2
except:
pass
try:
from urllib.parse import quote_plus # python 3
except:
pass
from django.contrib import messages
from django.contrib.co... |
def post_update(request, slug=None):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None,
request.FILES or None, instance=instance)
if form.is_valid():
insta... | today = timezone.now().date()
queryset_list = Post.objects.active() # .order_by("-timestamp")
if request.user.is_staff or request.user.is_superuser:
queryset_list = Post.objects.all()
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icon... | identifier_body |
views.py | from django.core import serializers
from rest_framework.response import Response
from django.http import JsonResponse
try:
from urllib import quote_plus # python 2
except:
pass
try:
from urllib.parse import quote_plus # python 3
except:
pass
from django.contrib import messages
from django.contrib.co... | (request):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
form = PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
# message success
... | post_create | identifier_name |
LogRowContext.tsx | import React, { useRef, useState, useLayoutEffect, useEffect } from 'react';
import { GrafanaTheme, DataQueryError, LogRowModel, textUtil } from '@grafana/data';
import { css, cx } from '@emotion/css';
import { Alert } from '../Alert/Alert';
import { LogRowContextRows, LogRowContextQueryErrors, HasMoreContextRows } fr... |
};
document.addEventListener('keydown', handleEscKeyDown, false);
return () => {
document.removeEventListener('keydown', handleEscKeyDown, false);
};
}, [onOutsideClick]);
const theme = useTheme();
const { afterContext, beforeContext } = getLogRowContextStyles(theme, wrapLogMessage);
ret... | {
onOutsideClick();
} | conditional_block |
LogRowContext.tsx | import React, { useRef, useState, useLayoutEffect, useEffect } from 'react';
import { GrafanaTheme, DataQueryError, LogRowModel, textUtil } from '@grafana/data';
import { css, cx } from '@emotion/css';
import { Alert } from '../Alert/Alert';
import { LogRowContextRows, LogRowContextQueryErrors, HasMoreContextRows } fr... |
interface LogRowContextProps {
row: LogRowModel;
context: LogRowContextRows;
wrapLogMessage: boolean;
errors?: LogRowContextQueryErrors;
hasMoreContextRows?: HasMoreContextRows;
onOutsideClick: () => void;
onLoadMoreContext: () => void;
}
const getLogRowContextStyles = (theme: GrafanaTheme, wrapLogMessa... | random_line_split | |
debuggerEventsProtocol.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | const message = packet.toString('utf-8', 0, packet.length - 1);
return JSON.parse(message);
}
} | random_line_split | |
debuggerEventsProtocol.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
} | {
// Verify the message ends in a newline
if (packet[packet.length - 1] != 10 /*\n*/) {
throw new Error("Unexpected message received from debugger.");
}
const message = packet.toString('utf-8', 0, packet.length - 1);
return JSON.parse(message);
} | identifier_body |
debuggerEventsProtocol.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (packet: Buffer): DebuggerEvent {
// Verify the message ends in a newline
if (packet[packet.length - 1] != 10 /*\n*/) {
throw new Error("Unexpected message received from debugger.");
}
const message = packet.toString('utf-8', 0, packet.length - 1);
return JSON.parse(... | decodePacket | identifier_name |
debuggerEventsProtocol.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
const message = packet.toString('utf-8', 0, packet.length - 1);
return JSON.parse(message);
}
} | {
throw new Error("Unexpected message received from debugger.");
} | conditional_block |
ScratchPad.py | import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .subli... | : # class to delegate the data to
def __init__(self, file):
self.file = file;
self.file_name = file.name;
def set_file(self, file):
self.file = file;
def unlink(self):
try:
os.unlink(self.file_name);
except OSError, e:
print("Couldn't remove file %s, %i, %s" % (self.file_name, e.errorno, e.strerror... | ScratchpadFile | identifier_name |
ScratchPad.py | import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .subli... | def __get_filetype(self):
syntaxpath = os.path.join( os.path.split( os.path.normcase(sublime.packages_path()) )[0], os.path.normcase(self.view.settings().get('syntax')) ); # obtain the absolute path to the syntax file
# so now we have a path where the last 3 entries are: packages / syntax folder / syntax.tmlanguag... | print("Couldn't remove file %s, %i, %s" % (self.file_name, e.errorno, e.strerror));
class ScratchpadCommand(sublime_plugin.TextCommand): | random_line_split |
ScratchPad.py | import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .subli... |
def __get_selection(self):
selection = self.view.sel()[0]; # only the first selection, for now...
selectedText = "";
if selection.empty():
selectedText = self.view.substr(sublime.Region(0, self.view.size())); # grab entire file
else:
selectedText = self.view.substr(selection); # grab just the selected... | syntaxpath = os.path.join( os.path.split( os.path.normcase(sublime.packages_path()) )[0], os.path.normcase(self.view.settings().get('syntax')) ); # obtain the absolute path to the syntax file
# so now we have a path where the last 3 entries are: packages / syntax folder / syntax.tmlanguage
# splitpath = syntaxpath.... | identifier_body |
ScratchPad.py | import sublime, sublime_plugin, tempfile, os, re;
global g_current_file;
global g_last_view;
g_current_file = None;
g_last_view = None;
# Two methods that could be used here:
# get language name
# check if .sublime-build exists for language name
# if it doesn't, somehow get the file extension
# check for .subli... |
g_last_view = None;
g_current_file = None;
| window.focus_view(g_last_view); | conditional_block |
parser.rs | use std::error::Error;
use std::fmt;
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum AST {
Output,
Input,
Loop(Vec<AST>),
Right,
Left,
Inc,
Dec,
}
#[derive(Debug)]
pub enum ParseErrorType {
UnclosedLoop,
ExtraCloseLoop,
}
use ParseErrorType::*;
#[derive(Debug)]
pub s... | b'<' => tokens.push(AST::Left),
b'[' => tokens.push(AST::Loop(_parse(code, i, level + 1)?)),
b']' => {
return if level == 0 {
Err(ParseError::new(ExtraCloseLoop, code, *i - 1))
} else {
Ok(tokens)
... |
match c {
b'+' => tokens.push(AST::Inc),
b'-' => tokens.push(AST::Dec),
b'>' => tokens.push(AST::Right), | random_line_split |
parser.rs | use std::error::Error;
use std::fmt;
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum AST {
Output,
Input,
Loop(Vec<AST>),
Right,
Left,
Inc,
Dec,
}
#[derive(Debug)]
pub enum ParseErrorType {
UnclosedLoop,
ExtraCloseLoop,
}
use ParseErrorType::*;
#[derive(Debug)]
pub s... | {
err: ParseErrorType,
line: Vec<u8>,
linenum: usize,
offset: usize,
}
impl ParseError {
fn new(err: ParseErrorType, code: &[u8], i: usize) -> Self {
let (line, linenum, offset) = find_line(code, i);
Self {
err,
line: line.into(),
linenum,
... | ParseError | identifier_name |
parser.rs | use std::error::Error;
use std::fmt;
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum AST {
Output,
Input,
Loop(Vec<AST>),
Right,
Left,
Inc,
Dec,
}
#[derive(Debug)]
pub enum ParseErrorType {
UnclosedLoop,
ExtraCloseLoop,
}
use ParseErrorType::*;
#[derive(Debug)]
pub s... |
}
fn find_line(code: &[u8], i: usize) -> (&[u8], usize, usize) {
let offset = code[0..i].iter().rev().take_while(|x| **x != b'\n').count();
let end = i + code[i..].iter().take_while(|x| **x != b'\n').count();
let linenum = code[0..(i - offset)]
.iter()
.filter(|x| **x == b'\n')
.co... | {
Ok(tokens)
} | conditional_block |
parser.rs | use std::error::Error;
use std::fmt;
use unicode_width::UnicodeWidthStr;
#[derive(Clone)]
pub enum AST {
Output,
Input,
Loop(Vec<AST>),
Right,
Left,
Inc,
Dec,
}
#[derive(Debug)]
pub enum ParseErrorType {
UnclosedLoop,
ExtraCloseLoop,
}
use ParseErrorType::*;
#[derive(Debug)]
pub s... |
fn _parse(code: &[u8], i: &mut usize, level: u32) -> Result<Vec<AST>, ParseError> {
// Starting [ of the loop
let start = i.saturating_sub(1);
let mut tokens = Vec::new();
while let Some(c) = code.get(*i) {
*i += 1;
match c {
b'+' => tokens.push(AST::Inc),
b'-... | {
let mut i = 0;
_parse(code, &mut i, 0)
} | identifier_body |
RealdebridCom.py | # -*- coding: utf-8 -*-
from module.plugins.internal.MultiHook import MultiHook
class RealdebridCom(MultiHook):
__name__ = "RealdebridCom"
__type__ = "hook"
__version__ = "0.46"
__config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"),
... | https = "https" if self.getConfig("ssl") else "http"
html = self.getURL(https + "://real-debrid.com/api/hosters.php").replace("\"", "").strip()
return [x.strip() for x in html.split(",") if x.strip()] | identifier_body | |
RealdebridCom.py | # -*- coding: utf-8 -*-
from module.plugins.internal.MultiHook import MultiHook
class | (MultiHook):
__name__ = "RealdebridCom"
__type__ = "hook"
__version__ = "0.46"
__config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"),
("pluginlist" , "str" , "Plugin list (comma separated)" , "" ),
... | RealdebridCom | identifier_name |
RealdebridCom.py | # -*- coding: utf-8 -*-
from module.plugins.internal.MultiHook import MultiHook
class RealdebridCom(MultiHook):
__name__ = "RealdebridCom"
__type__ = "hook"
__version__ = "0.46" | ("retry" , "int" , "Number of retries before revert" , 10 ),
("retryinterval" , "int" , "Retry interval in minutes" , 1 ),
("reload" , "bool" , "Reload plugin list" , True... |
__config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"),
("pluginlist" , "str" , "Plugin list (comma separated)" , "" ),
("revertfailed" , "bool" , "Revert to standard download if fails", Tru... | random_line_split |
widgets.py | import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFo... | tree.draw();
}
""")
]
template = """
<div xmlns:py="http://purl.org/kid/ns#"
py:strip="True">
<div id="${id}" />
<script type="text/javascript">
yui_tree_init('${id}', ${entries});
</script>
</div>
"""
entries = {'expanded': ... | tree = new YAHOO.widget.TreeView(id);
yui_add_branch(tree.getRoot(), entries); | random_line_split |
widgets.py | import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFo... |
def skinned(pth, resource_name):
if not skin:
return [
CSSLink("TGYUI", '%s/assets/%s' % (pth, resource_name)),
]
base, ext = resource_name.rsplit('.', 1)
skin_methods = {
'minimized': [
CSSLink("TGYUI", '%s/assets/skins/%s/%s' % (pth, skin, resource_nam... | """This function lets us have a new unique id each time a widget is rendered,
to be used by generated css & javascript snippets (e.g. initializing functions,
or instance-specific appearance).
If you have no widgets that are fetched by XMLHttpRequest and inserted into
the document at runtime (e.g. with ... | identifier_body |
widgets.py | import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFo... |
else:
raise ValueError("app.yui.skin_method must be one of '%s'" % "', '".join(skin_methods.keys()))
class YUIBaseCSS(Widget):
css = [CSSLink("TGYUI", "base/base-min.css")]
yuibasecss = YUIBaseCSS()
class YUIResetCSS(Widget):
css = [CSSLink("TGYUI", "reset/reset-min.css")]... | return skin_methods[skin_method] | conditional_block |
widgets.py | import os.path
import itertools
import pkg_resources
from turbogears.widgets import Widget, TextField
from turbogears.widgets import CSSSource, JSSource, register_static_directory
from turbogears import config
from turbojson import jsonify
from util import CSSLink, JSLink
__all__ = ['YUIBaseCSS', 'YUIResetCSS', 'YUIFo... | (self, entries=None, *args, **kw):
super(YUIMenuBar, self).__init__(*args, **kw)
if entries:
self.entries = entries
class YUIMenuLeftNav(YUIMenuBar):
as_bar = False
class YUIAutoComplete(TextField):
"A standard, single-line text field with YUI AutoComplete enhancements."
... | __init__ | identifier_name |
tocfilter.py | import os
import finder
import re
import sys
def makefilter(name, xtrapath=None):
typ, nm, fullname = finder.identify(name, xtrapath)
if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE):
return ModFilter([os.path.splitext(nm)[0]])
if typ == finder.PACKAGE:
return PkgFilter([fullname])
... |
if typ in (finder.BINARY, finder.PBINARY):
return FileFilter([nm])
return FileFilter([fullname])
class _Filter:
def __repr__(self):
return '<'+self.__class__.__name__+' '+repr(self.elements)+'>'
class _NameFilter(_Filter):
""" A filter mixin that matches (exactly) on name """
... | return DirFilter([fullname]) | conditional_block |
tocfilter.py | import os
import finder
import re
import sys
def makefilter(name, xtrapath=None):
typ, nm, fullname = finder.identify(name, xtrapath)
if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE):
return ModFilter([os.path.splitext(nm)[0]])
if typ == finder.PACKAGE:
return PkgFilter([fullname])
... |
class ModFilter(_NameFilter):
""" A filter for Python modules.
ModFilter(modlist) where modlist is eg ['macpath', 'dospath'] """
def __init__(self, modlist):
self.elements = {}
for mod in modlist:
self.elements[mod] = 1
class DirFilter(_PathFilter... | """ A filter for data files """
def __init__(self, filelist):
self.elements = {}
for f in filelist:
self.elements[f] = 1 | identifier_body |
tocfilter.py | import os
import finder
import re
import sys
def makefilter(name, xtrapath=None):
typ, nm, fullname = finder.identify(name, xtrapath)
if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE):
return ModFilter([os.path.splitext(nm)[0]])
if typ == finder.PACKAGE:
return PkgFilter([fullname])
... | self.elements.append(re.compile(pat)) | random_line_split | |
tocfilter.py | import os
import finder
import re
import sys
def makefilter(name, xtrapath=None):
typ, nm, fullname = finder.identify(name, xtrapath)
if typ in (finder.SCRIPT, finder.GSCRIPT, finder.MODULE):
return ModFilter([os.path.splitext(nm)[0]])
if typ == finder.PACKAGE:
return PkgFilter([fullname])
... | (_ExtFilter):
""" A file extension filter.
ExtFilter(extlist, include=0)
where extlist is a list of file extensions """
def __init__(self, extlist, include=0):
self.elements = {}
for ext in extlist:
if ext[0:1] != '.':
ext = '.'+ext
self.el... | ExtFilter | identifier_name |
vi.js | /*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'table', 'vi', {
border: 'Kích thước đường viền',
caption: 'Đầu đề',
cell: {
menu: 'Ô',
insertBefore: 'Chèn ô Phía trước',
insertAfter: 'Chèn... | invalidCellSpacing: 'Khoảng cách giữa các ô phải là một số nguyên.',
invalidCols: 'Số lượng cột phải là một số lớn hơn 0.',
invalidHeight: 'Chiều cao của bảng phải là một số nguyên.',
invalidRows: 'Số lượng hàng phải là một số lớn hơn 0.',
invalidWidth: 'Chiều rộng của bảng phải là một số nguyên.',
menu: 'Thuộc t... | random_line_split | |
StreamService.ts | "use strict"
import * as request from 'request';
import * as ytdl from 'ytdl-core';
import { SpotifyTrack, BotConfig, Track } from "../../typings/index";
import { Users } from "../../models/Users";
import { YoutubeAPI } from "../api/YoutubeAPI";
import { Readable } from "stream";
export class StreamService... | (private users: Users, private config: BotConfig) {
this.ytApi = new YoutubeAPI(config.tokens.youtube);
}
public getTrackStream(track: Track, cb: (stream: Readable) => void) {
if (track.src === 'sc') return cb(request(`${track.url}?client_id=${this.config.tokens.soundcloud}`) as any);
else if (track.sr... | constructor | identifier_name |
StreamService.ts | "use strict"
import * as request from 'request';
import * as ytdl from 'ytdl-core';
import { SpotifyTrack, BotConfig, Track } from "../../typings/index";
import { Users } from "../../models/Users";
import { YoutubeAPI } from "../api/YoutubeAPI";
import { Readable } from "stream";
export class StreamService... |
return cb(ytdl(track.url, { filter : 'audioonly' }));
}
private async loadAndUpdateTrack(track: SpotifyTrack) {
const youtubeTracks = await this.ytApi.searchForVideo(`${track.title} ${track.poster}`);
track.url = youtubeTracks[0].url;
track.loaded = true;
await this.users.updateAllUsersSpotify... | {
return this.loadAndUpdateTrack(track as SpotifyTrack).then( (newTrack) => {
cb(ytdl(newTrack.url, { filter : 'audioonly' }));
});
} | conditional_block |
StreamService.ts | "use strict"
import * as request from 'request';
import * as ytdl from 'ytdl-core';
import { SpotifyTrack, BotConfig, Track } from "../../typings/index";
import { Users } from "../../models/Users";
import { YoutubeAPI } from "../api/YoutubeAPI";
import { Readable } from "stream";
export class StreamService... |
private async loadAndUpdateTrack(track: SpotifyTrack) {
const youtubeTracks = await this.ytApi.searchForVideo(`${track.title} ${track.poster}`);
track.url = youtubeTracks[0].url;
track.loaded = true;
await this.users.updateAllUsersSpotifyTrack(track);
return track;
}
} | {
if (track.src === 'sc') return cb(request(`${track.url}?client_id=${this.config.tokens.soundcloud}`) as any);
else if (track.src === 'spot' && !(track as SpotifyTrack).loaded) {
return this.loadAndUpdateTrack(track as SpotifyTrack).then( (newTrack) => {
cb(ytdl(newTrack.url, { filter : 'audioonl... | identifier_body |
StreamService.ts | "use strict"
import * as request from 'request'; | import { SpotifyTrack, BotConfig, Track } from "../../typings/index";
import { Users } from "../../models/Users";
import { YoutubeAPI } from "../api/YoutubeAPI";
import { Readable } from "stream";
export class StreamService {
private ytApi: YoutubeAPI;
constructor(private users: Users, private config: Bot... | import * as ytdl from 'ytdl-core';
| random_line_split |
reducer.spec.ts | import { FormGroup } from '@angular/forms';
import { Reset } from '~/actions/root.actions';
import { IUser } from '~/interfaces/user';
import { SetAuthorized } from './actions';
import { authReducer } from './reducer';
import { ResetError, SigninError, SigninRequest, SigninSuccess } from './signin/actions';
import { Si... | });
it('RESET', () => {
expect(authReducer({}, new Reset())).toEqual({});
});
it('default', () => {
expect(authReducer({}, { type: null })).toEqual({});
});
}); | random_line_split | |
SkillTree.js | angular.module('starter.controllers')
.controller('skillTreeControl', function ($scope, $storageServices, $ionicModal, $analytics, $window) {
$scope.showSkillMap = true;
$analytics.trackView('Skill Tree');
$scope.ratings = 0;
$scope.isInfinite = false;
$scope.learnedSkills = [];
$scope.modal... |
});
});
| {
$scope.showSkillMap = false;
} | conditional_block |
SkillTree.js | angular.module('starter.controllers')
.controller('skillTreeControl', function ($scope, $storageServices, $ionicModal, $analytics, $window) {
$scope.showSkillMap = true;
$analytics.trackView('Skill Tree');
$scope.ratings = 0;
$scope.isInfinite = false;
$scope.learnedSkills = [];
$scope.modal... |
angular.forEach(ALL_SKILLS, function (skills, index) {
var skillFlareChild = {};
angular.forEach(skills, function (skill) {
$storageServices.get(skill.text, function (result) {
var rating = parseInt(result);
if (rating) {
$scope.showSkillMap = true;... |
var flareChild = {}; | random_line_split |
Paper.ts | import { Margin } from "./Margin";
import { PageFormat } from "./PageFormat";
import { StandardizedPageFormat } from "./StandardizedPageFormat";
/**
* Represents a document-layout.
*/
export class |
{
/**
* The margin of the paper.
*/
private margin: Margin = new Margin("1cm");
/**
* The format of the paper.
*/
private format: PageFormat = new StandardizedPageFormat();
/**
* Initializes a new instance of the {@link Paper `Paper`} class.
*
* @param format
... | Paper | identifier_name |
Paper.ts | import { Margin } from "./Margin";
import { PageFormat } from "./PageFormat";
import { StandardizedPageFormat } from "./StandardizedPageFormat";
/**
* Represents a document-layout.
*/
export class Paper
{
/**
* The margin of the paper.
*/
private margin: Margin = new Margin("1cm");
/**
* ... |
if (margin)
{
this.margin = margin;
}
}
/**
* Gets or sets the margin of the paper.
*/
public get Margin(): Margin
{
return this.margin;
}
/**
* @inheritdoc
*/
public set Margin(value: Margin)
{
this.margin = val... | {
this.format = format;
} | conditional_block |
Paper.ts | import { Margin } from "./Margin";
import { PageFormat } from "./PageFormat";
import { StandardizedPageFormat } from "./StandardizedPageFormat";
/**
* Represents a document-layout.
*/
export class Paper
{
/**
* The margin of the paper.
*/
private margin: Margin = new Margin("1cm");
/**
* ... | public set Margin(value: Margin)
{
this.margin = value;
}
/**
* Gets or sets the format of the paper.
*/
public get Format(): PageFormat
{
return this.format;
}
/**
* @inheritdoc
*/
public set Format(value: PageFormat)
{
this.format =... | random_line_split | |
Paper.ts | import { Margin } from "./Margin";
import { PageFormat } from "./PageFormat";
import { StandardizedPageFormat } from "./StandardizedPageFormat";
/**
* Represents a document-layout.
*/
export class Paper
{
/**
* The margin of the paper.
*/
private margin: Margin = new Margin("1cm");
/**
* ... |
}
| {
this.format = value;
} | identifier_body |
FeatureHeader_feature.graphql.ts | /* tslint:disable */
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type FeatureHeader_feature = {
readonly name: string;
readonly subheadline: string | null;
readonly image: { | readonly url: string | null;
} | null;
} | null;
readonly " $refType": "FeatureHeader_feature";
};
export type FeatureHeader_feature$data = FeatureHeader_feature;
export type FeatureHeader_feature$key = {
readonly " $data"?: FeatureHeader_feature$data;
readonly " $fragmentRefs": Frag... | readonly cropped: { | random_line_split |
test_cisco_auto_enabled_switch.py | import unittest
from flexmock import flexmock_teardown
from tests.util.global_reactor import cisco_switch_ip, \
cisco_auto_enabled_switch_ssh_port, cisco_auto_enabled_switch_telnet_port
from tests.util.protocol_util import SshTester, TelnetTester, with_protocol
class TestCiscoAutoEnabledSwitchProtocol(unittest.T... |
def tearDown(self):
flexmock_teardown()
@with_protocol
def test_enable_command_requires_a_password(self, t):
t.write("enable")
t.read("my_switch#")
t.write("terminal length 0")
t.read("my_switch#")
t.write("terminal width 0")
t.read("my_switch#")
... | self.protocol = self.create_client() | identifier_body |
test_cisco_auto_enabled_switch.py | import unittest
from flexmock import flexmock_teardown
from tests.util.global_reactor import cisco_switch_ip, \
cisco_auto_enabled_switch_ssh_port, cisco_auto_enabled_switch_telnet_port
from tests.util.protocol_util import SshTester, TelnetTester, with_protocol
class TestCiscoAutoEnabledSwitchProtocol(unittest.T... | (self):
return SshTester("ssh", cisco_switch_ip, cisco_auto_enabled_switch_ssh_port, 'root', 'root')
class TestCiscoSwitchProtocolTelnet(TestCiscoAutoEnabledSwitchProtocol):
__test__ = True
def create_client(self):
return TelnetTester("telnet", cisco_switch_ip, cisco_auto_enabled_switch_telne... | create_client | identifier_name |
test_cisco_auto_enabled_switch.py | import unittest
from flexmock import flexmock_teardown |
class TestCiscoAutoEnabledSwitchProtocol(unittest.TestCase):
__test__ = False
def setUp(self):
self.protocol = self.create_client()
def tearDown(self):
flexmock_teardown()
@with_protocol
def test_enable_command_requires_a_password(self, t):
t.write("enable")
t.re... | from tests.util.global_reactor import cisco_switch_ip, \
cisco_auto_enabled_switch_ssh_port, cisco_auto_enabled_switch_telnet_port
from tests.util.protocol_util import SshTester, TelnetTester, with_protocol | random_line_split |
htmllinkelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::Attr;
use dom::bindings::cell::D... | self.handle_favicon_url(rel.as_ref().unwrap(), &attr.value(), &sizes);
}
},
&atom!("sizes") => {
if is_favicon(&rel) {
if let Some(ref href) = get_attr(self.upcast(), &atom!("href")) {
self.handle_fav... | &atom!("href") => {
if string_is_stylesheet(&rel) {
self.handle_stylesheet_url(&attr.value());
} else if is_favicon(&rel) {
let sizes = get_attr(self.upcast(), &atom!("sizes")); | random_line_split |
htmllinkelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::Attr;
use dom::bindings::cell::D... |
impl VirtualMethods for HTMLLinkElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
... | {
match *value {
Some(ref value) => {
value.split(HTML_SPACE_CHARACTERS)
.any(|s| s.eq_ignore_ascii_case("icon") || s.eq_ignore_ascii_case("apple-touch-icon"))
},
None => false,
}
} | identifier_body |
htmllinkelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser as CssParser;
use document_loader::LoadType;
use dom::attr::Attr;
use dom::bindings::cell::D... | (&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
let element = self.upcast();
let rel = get_attr(element, &atom!("rel"));
let href = get_attr(element, &atom!("href"));
... | bind_to_tree | identifier_name |
test_msgs.py | # -*- coding: utf-8 -*-
import unittest |
class MessagesTests(unittest.TestCase):
def test_messages(self):
""""""
self.assertEqual(EmailMsg.missing.value, 'emails.missing')
self.assertEqual(EmailMsg.dupe.value, 'emails.duplicated')
self.assertEqual(EmailMsg.get_success.value, 'emails.get-success')
self.assertEqual(... |
from eduid_webapp.email.helpers import EmailMsg | random_line_split |
test_msgs.py | # -*- coding: utf-8 -*-
import unittest
from eduid_webapp.email.helpers import EmailMsg
class MessagesTests(unittest.TestCase):
| def test_messages(self):
""""""
self.assertEqual(EmailMsg.missing.value, 'emails.missing')
self.assertEqual(EmailMsg.dupe.value, 'emails.duplicated')
self.assertEqual(EmailMsg.get_success.value, 'emails.get-success')
self.assertEqual(EmailMsg.throttled.value, 'emails.throttled')
... | identifier_body | |
test_msgs.py | # -*- coding: utf-8 -*-
import unittest
from eduid_webapp.email.helpers import EmailMsg
class | (unittest.TestCase):
def test_messages(self):
""""""
self.assertEqual(EmailMsg.missing.value, 'emails.missing')
self.assertEqual(EmailMsg.dupe.value, 'emails.duplicated')
self.assertEqual(EmailMsg.get_success.value, 'emails.get-success')
self.assertEqual(EmailMsg.throttled.va... | MessagesTests | identifier_name |
speedtest.py | import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subpro... | run_all(number, childprocess_param, virtual_only=virtual_only, bbox=bbox)
if virtual_display:
from pyvirtualdisplay import Display
with Display(visible=0):
f(virtual_only=True)
else:
f(virtual_only=False) | random_line_split | |
speedtest.py | import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subpro... | (n, childprocess_param, virtual_only=True, bbox=None):
debug = True
print("")
print("n=%s" % n)
print("------------------------------------------------------")
if bbox:
x1, y1, x2, y2 = map(str, bbox)
bbox = ":".join(map(str, (x1, y1, x2, y2)))
bboxpar = ["--bbox", bbox]
... | run_all | identifier_name |
speedtest.py | import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subpro... |
else:
bbox = None
def f(virtual_only):
if backend:
try:
run(backend, number, childprocess, bbox=bbox)
except pyscreenshot.FailedBackendError:
pass
else:
run_all(number, childprocess_param, virtual_only=virtual_only, bb... | x1, y1, x2, y2 = map(int, bbox.split(":"))
bbox = x1, y1, x2, y2 | conditional_block |
speedtest.py | import sys
import time
from entrypoint2 import entrypoint
import pyscreenshot
from pyscreenshot.plugins.gnome_dbus import GnomeDBusWrapper
from pyscreenshot.plugins.gnome_screenshot import GnomeScreenshotWrapper
from pyscreenshot.plugins.kwin_dbus import KwinDBusWrapper
from pyscreenshot.util import run_mod_as_subpro... |
if virtual_display:
from pyvirtualdisplay import Display
with Display(visible=0):
f(virtual_only=True)
else:
f(virtual_only=False)
| if backend:
try:
run(backend, number, childprocess, bbox=bbox)
except pyscreenshot.FailedBackendError:
pass
else:
run_all(number, childprocess_param, virtual_only=virtual_only, bbox=bbox) | identifier_body |
dropout.py | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import sys
sys.path.append('./MNIST_data')
import os.path
from download import download
have_data = os.path.exists('MNIST_data/train-images-idx3-ubyte.gz')
if not have_data:
download('./MNIST_data')
# load data
mnist = input_data.r... | x = tf.placeholder(tf.float32, [None,784])
y = tf.placeholder(tf.float32, [None,10])
keep_prob = tf.placeholder(tf.float32)
# 神经网络结构 784-1000-500-10
w1 = tf.Variable(tf.truncated_normal([784,1000], stddev=0.1))
b1 = tf.Variable(tf.zeros([1000]) + 0.1)
l1 = tf.nn.tanh(tf.matmul(x, w1) + b1)
l1_drop = tf.nn.dropout(l1, ... | n_batch = mnist.train.num_examples // batch_size
# in [60000, 28 * 28] out [60000, 10] | random_line_split |
dropout.py | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import sys
sys.path.append('./MNIST_data')
import os.path
from download import download
have_data = os.path.exists('MNIST_data/train-images-idx3-ubyte.gz')
if not have_data:
download('./MNIST_data')
# load data
mnist = input_data.r... | ges, y:mnist.test.labels, keep_prob:1.0})
train_acc = sess.run(accuracy, feed_dict={x:mnist.train.images, y:mnist.train.labels, keep_prob:1.0})
print("Iter " + str(epoch + 1) + ", Testing Accuracy " + str(acc) + ", Training Accuracy " + str(train_acc))
| sess.run(train, feed_dict={x:batch_x, y:batch_y, keep_prob:0.5})
acc = sess.run(accuracy, feed_dict={x:mnist.test.ima | conditional_block |
message.js | var Message = function() {
this._data = {
'push_type': 1,
'android': {
'doings': 1
}
};
return this;
};
/*
* Notification bar上显示的标题
* 必须
*/
Message.prototype.title = function(title) {
return this.setAndroid('notification_title', title);
};
/*
* Notification bar上显示的内容
* 必须
*/
Message.p... | };
Message.prototype.getAndroidData = function() {
return this._data;
};
Message.prototype.getData = function() {
return this._data;
};
Message.prototype.toString = function() {
return JSON.stringify(this._data);
};
module.exports = Message; |
Message.prototype.set = function(key, value) {
this._data[key] = value;
return this; | random_line_split |
message.js | var Message = function() {
this._data = {
'push_type': 1,
'android': {
'doings': 1
}
};
return this;
};
/*
* Notification bar上显示的标题
* 必须
*/
Message.prototype.title = function(title) {
return this.setAndroid('notification_title', title);
};
/*
* Notification bar上显示的内容
* 必须
*/
Message.p... | 无需指定tokens,tags,exclude_tags
* 3:一群人,必须指定tags或者exclude_tags字段
*/
Message.prototype.push_type = function(push_type) {
return this.set('push_type', push_type);
};
/*
* 用户标签,目前仅对android用户生效
* 样例:{"tags":[{"location":["ShangHai","GuangZhou"]},}"age":["20","30"]}]}
* 含义:在广州或者上海,并且年龄为20或30岁的用户
*/
Message.prototype.t... | ){
var v = {};
v[key] = extras[key];
extraArray.push(v)
})
extras = extraArray
}
return this.setAndroid('extras', extras);
};
/*
* 推送范围
* 1:指定用户,必须指定tokens字段
* 2:所有人, | conditional_block |
asteroid-calendar.ja.ts | <?xml version="1.0" encoding="utf-8"?> | <message id="id-new-event">
<location filename="../src/EventDialog.qml" line="43"/>
<source>New Event</source>
<translation>新しいイベント</translation>
</message>
<message id="id-edit-event">
<location filename="../src/EventDialog.qml" line="45"/>
<source>Edit Event</source... | <!DOCTYPE TS>
<TS version="2.1" language="ja">
<context>
<name></name> | random_line_split |
tests.py | """
Tests for course_info
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.test... |
def test_handouts(self):
url = reverse('course-handouts-list', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_updates(self):
url = reverse('course-updates-list', kwargs={'course_id': unicode(s... | url = reverse('course-about-detail', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTrue('overview' in response.data) # pylint: disable=E1103 | identifier_body |
tests.py | """
Tests for course_info
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.test... | self.course = CourseFactory.create(mobile_available=True)
self.client.login(username=self.user.username, password='test')
def test_about(self):
url = reverse('course-about-detail', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqua... | def setUp(self):
super(TestVideoOutline, self).setUp()
self.user = UserFactory.create() | random_line_split |
tests.py | """
Tests for course_info
"""
from django.test.utils import override_settings
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from courseware.test... | (self):
url = reverse('course-about-detail', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertTrue('overview' in response.data) # pylint: disable=E1103
def test_handouts(self):
url = revers... | test_about | identifier_name |
timer_scheduler.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 ipc_channel::ipc::{self, IpcSender};
use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg};
us... |
}
impl Eq for ScheduledEvent {}
impl PartialEq for ScheduledEvent {
fn eq(&self, other: &ScheduledEvent) -> bool {
self as *const ScheduledEvent == other as *const ScheduledEvent
}
}
impl TimerScheduler {
pub fn start() -> IpcSender<TimerSchedulerMsg> {
let (req_ipc_sender, req_ipc_receiv... | {
Some(self.cmp(other))
} | identifier_body |
timer_scheduler.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 ipc_channel::ipc::{self, IpcSender};
use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg};
us... | ;
struct ScheduledEvent {
request: TimerEventRequest,
for_time: Instant,
}
impl Ord for ScheduledEvent {
fn cmp(&self, other: &ScheduledEvent) -> cmp::Ordering {
self.for_time.cmp(&other.for_time).reverse()
}
}
impl PartialOrd for ScheduledEvent {
fn partial_cmp(&self, other: &ScheduledEv... | TimerScheduler | identifier_name |
timer_scheduler.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 ipc_channel::ipc::{self, IpcSender};
use script_traits::{TimerEvent, TimerEventRequest, TimerSchedulerMsg};
us... | // We maintain a priority queue of future events, sorted by due time.
let mut scheduled_events = BinaryHeap::<ScheduledEvent>::new();
loop {
let now = Instant::now();
// Dispatch any events whose due time is past
... | random_line_split | |
karma.conf.js | (function() {
'use strict';
var bowerFiles = require('bower-files')();
var config = require('./gulp/config');
function listFiles() {
var files = []
.concat(bowerFiles.dev().ext('js').files)
.concat([
config.sourceDir + 'app/**/*.html',
config.sourceDir + 'app/**/*.js',
])... | karmaConfig.set({
files: listFiles(),
browsers: ['PhantomJS'],
frameworks: ['jasmine', 'angular-filesort'],
preprocessors: listPreprocessors(),
ngHtml2JsPreprocessor: {
stripPrefix: config.sourceDir,
moduleName: 'templateCache'
},
angularFilesort: {
... | random_line_split | |
karma.conf.js | (function() {
'use strict';
var bowerFiles = require('bower-files')();
var config = require('./gulp/config');
function | () {
var files = []
.concat(bowerFiles.dev().ext('js').files)
.concat([
config.sourceDir + 'app/**/*.html',
config.sourceDir + 'app/**/*.js',
]);
return files;
}
function listPreprocessors() {
var preprocessors = {};
preprocessors[config.sourceDir + 'app/**/*.htm... | listFiles | identifier_name |
karma.conf.js | (function() {
'use strict';
var bowerFiles = require('bower-files')();
var config = require('./gulp/config');
function listFiles() {
var files = []
.concat(bowerFiles.dev().ext('js').files)
.concat([
config.sourceDir + 'app/**/*.html',
config.sourceDir + 'app/**/*.js',
])... |
module.exports = function(karmaConfig) {
karmaConfig.set({
files: listFiles(),
browsers: ['PhantomJS'],
frameworks: ['jasmine', 'angular-filesort'],
preprocessors: listPreprocessors(),
ngHtml2JsPreprocessor: {
stripPrefix: config.sourceDir,
moduleName: 'template... | {
var preprocessors = {};
preprocessors[config.sourceDir + 'app/**/*.html'] = ['ng-html2js'];
preprocessors[config.sourceDir + 'app/**/!(*.spec|*.mock).js'] = ['coverage'];
return preprocessors;
} | identifier_body |
end-target.js | var BaseTween = require('tween-base')
var isArray = require('an-array')
var ownKeys = require('own-enumerable-keys')
var ignores = ownKeys(new BaseTween())
module.exports = function getTargets(element, opt) {
var targets = []
var optKeys = ownKeys(opt)
for (var k in opt) { | //copy properties as needed
if (optKeys.indexOf(k) >= 0 &&
k in element &&
ignores.indexOf(k) === -1) {
var startVal = element[k]
var endVal = opt[k]
if (typeof startVal === 'number'
&& typeof endVal === 'number') {
... | random_line_split | |
overlay.ts | /**
* @license
* Copyright Google LLC 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 {Directionality} from '@angular/cdk/bidi';
import {DomPortalOutlet} from '@angular/cdk/portal';
import {DOCUME... |
return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector);
}
}
| {
this._appRef = this._injector.get<ApplicationRef>(ApplicationRef);
} | conditional_block |
overlay.ts | /**
* @license
* Copyright Google LLC 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 {Directionality} from '@angular/cdk/bidi';
import {DomPortalOutlet} from '@angular/cdk/portal';
import {DOCUME... | (): HTMLElement {
const host = this._document.createElement('div');
this._overlayContainer.getContainerElement().appendChild(host);
return host;
}
/**
* Create a DomPortalOutlet into which the overlay content can be loaded.
* @param pane The DOM element to turn into a portal outlet.
* @returns... | _createHostElement | identifier_name |
overlay.ts | /**
* @license
* Copyright Google LLC 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 {Directionality} from '@angular/cdk/bidi';
import {DomPortalOutlet} from '@angular/cdk/portal';
import {DOCUME... |
/**
* Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
* used as a low-level building block for other components. Dialogs, tooltips, menus,
* selects, etc. can all be built using overlays. The service should primarily be used by authors
* of re-usable components rather ... | // it needs is different based on where OverlayModule is imported. | random_line_split |
overlay.ts | /**
* @license
* Copyright Google LLC 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 {Directionality} from '@angular/cdk/bidi';
import {DomPortalOutlet} from '@angular/cdk/portal';
import {DOCUME... |
/**
* Creates the DOM element for an overlay and appends it to the overlay container.
* @returns Newly-created pane element
*/
private _createPaneElement(host: HTMLElement): HTMLElement {
const pane = this._document.createElement('div');
pane.id = `cdk-overlay-${nextUniqueId++}`;
pane.classL... | {
return this._positionBuilder;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.