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 |
|---|---|---|---|---|
main.rs | #![allow(unused_variables)]
fn main() {
// Rust let bindings are immutable by default.
let z = 3;
// This will raise a compiler error:
// z += 2; //~ ERROR cannot assign twice to immutable variable `z`
// You must declare a variable mutable explicitly:
let mut x = 3;
// Similarly, referen... | } | random_line_split | |
main.rs | #![allow(unused_variables)]
fn main() | // y = &mut z; //~ ERROR re-assignment of immutable variable `y`
}
| {
// Rust let bindings are immutable by default.
let z = 3;
// This will raise a compiler error:
// z += 2; //~ ERROR cannot assign twice to immutable variable `z`
// You must declare a variable mutable explicitly:
let mut x = 3;
// Similarly, references are immutable by default e.g.
/... | identifier_body |
tabbarrenderer.js | // Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless requ... | else {
goog.ui.TabBarRenderer.superClass_.setStateFromClassName.call(this, tabBar,
className, baseClass);
}
};
/**
* Returns all CSS class names applicable to the tab bar, based on its state.
* Overrides the superclass implementation by appending the location-specific
* class name to the list.
* @p... | {
tabBar.setLocation(location);
} | conditional_block |
tabbarrenderer.js | // Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless requ... | goog.ui.TabBarRenderer.CSS_CLASS = goog.getCssName('goog-tab-bar');
/**
* Returns the CSS class name to be applied to the root element of all tab bars
* rendered or decorated using this renderer.
* @return {string} Renderer-specific CSS class name.
* @override
*/
goog.ui.TabBarRenderer.prototype.getCssClass = fu... | * Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/ | random_line_split |
user-video-settings.component.ts | import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive, FormValidatorService } from ... | templateUrl: './user-video-settings.component.html',
styleUrls: [ './user-video-settings.component.scss' ]
})
export class UserVideoSettingsComponent extends FormReactive implements OnInit, OnDestroy {
@Input() user: User = null
@Input() reactiveUpdate = false
@Input() notifyOnUpdate = true
@Input() userInf... | import { UserUpdateMe } from '@shared/models'
import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
@Component({
selector: 'my-user-video-settings', | random_line_split |
user-video-settings.component.ts | import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive, FormValidatorService } from ... |
let details: UserUpdateMe = {
nsfwPolicy,
p2pEnabled,
autoPlayVideo,
autoPlayNextVideo,
videoLanguages
}
if (videoLanguages) {
details = Object.assign(details, videoLanguages)
}
if (onlyKeys) details = pick(details, onlyKeys)
if (this.authService.isLogged... | {
if (videoLanguages.length > 20) {
this.notifier.error($localize`Too many languages are enabled. Please enable them all or stay below 20 enabled languages.`)
return
}
} | conditional_block |
user-video-settings.component.ts | import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive, FormValidatorService } from ... | (details: UserUpdateMe) {
this.userService.updateMyProfile(details)
.subscribe({
next: () => {
this.authService.refreshUserInformation()
if (this.notifyOnUpdate) this.notifier.success($localize`Video settings updated.`)
},
error: err => this.notifier.error(err.me... | updateLoggedProfile | identifier_name |
user-video-settings.component.ts | import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive, FormValidatorService } from ... |
}
| {
this.userService.updateMyAnonymousProfile(details)
if (this.notifyOnUpdate) this.notifier.success($localize`Display/Video settings updated.`)
} | identifier_body |
ordered.rs | use std::fmt;
use std::collections::VecMap;
use std::collections::vec_map::Entry;
use std::sync::atomic::{AtomicUsize,Ordering};
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Category
{ TOKEN = 0,
RULE = 1,
STATE = 2 }
pub trait Ordered {
fn get_order(&self) -> usize;
}
pub struct Manager {
ne... | (&mut self, c: Category) -> usize
{
match self.next_order.entry(c as usize) {
Entry::Vacant(entry) => { entry.insert(AtomicUsize::new(1));
0 },
Entry::Occupied(mut entry) => { let val = entry.get_mut();
... | next_order | identifier_name |
ordered.rs | use std::fmt;
use std::collections::VecMap;
use std::collections::vec_map::Entry;
use std::sync::atomic::{AtomicUsize,Ordering};
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Category
{ TOKEN = 0,
RULE = 1,
STATE = 2 }
pub trait Ordered {
fn get_order(&self) -> usize;
}
pub struct Manager {
ne... | } | random_line_split | |
ordered.rs | use std::fmt;
use std::collections::VecMap;
use std::collections::vec_map::Entry;
use std::sync::atomic::{AtomicUsize,Ordering};
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Category
{ TOKEN = 0,
RULE = 1,
STATE = 2 }
pub trait Ordered {
fn get_order(&self) -> usize;
}
pub struct Manager {
ne... |
}
impl fmt::Debug for Manager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ordered::Manager{{}}")
}
}
| {
match self.next_order.entry(c as usize) {
Entry::Vacant(entry) => { entry.insert(AtomicUsize::new(1));
0 },
Entry::Occupied(mut entry) => { let val = entry.get_mut();
val.fetch_add(1, Ordering::SeqCst) }
... | identifier_body |
ordered.rs | use std::fmt;
use std::collections::VecMap;
use std::collections::vec_map::Entry;
use std::sync::atomic::{AtomicUsize,Ordering};
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Category
{ TOKEN = 0,
RULE = 1,
STATE = 2 }
pub trait Ordered {
fn get_order(&self) -> usize;
}
pub struct Manager {
ne... | ,
Entry::Occupied(mut entry) => { let val = entry.get_mut();
val.fetch_add(1, Ordering::SeqCst) }
}
}
}
impl fmt::Debug for Manager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ordered::Manager{{}}")
}
}
| { entry.insert(AtomicUsize::new(1));
0 } | conditional_block |
production.py | # -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use mailgun to send emails
- Use redis
'''
from __future__ import absolute_import, unicode_literals
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# ---------------------------------------------------------... | {% endif %}
{% if cookiecutter.use_sentry %}
# SENTRY CONFIGURATION
# ------------------------------------------------------------------------------
RAVEN_CONFIG = {
'dsn': env("SENTRY_URL"),
}
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
{% endif %}
# Your production stuff: Bel... |
{% if cookiecutter.use_celery %}
# CELERY BROKER CONFIGURATION
# ------------------------------------------------------------------------------
BROKER_URL = "amqp://guest:guest@rabbitmq:5672//" | random_line_split |
github-label-manager.js | // ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @requi... |
function deleteAllLabels() {
const labels = Array.from(findAll('.labels-list-item'))
for(const label of labels) {
deleteLabel(label)
}
}
/* jshint ignore:start */
]]></>).toString();
var c = babel.transform(inline_src);
eval(c.code);
/* jshint ignore:end */
| {
find('.labels-list-actions button.js-details-target', element).click()
find('.label-delete button[type=submit]', element).click()
} | identifier_body |
github-label-manager.js | // ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @requi... | }
}
reader.readAsText(importInput.files[0])
})
exportButton.addEventListener('click', exportLabels)
}
function rgb2hex(rgb) {
const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2)
return "#" + ... | }
for(const label of labels) {
addLabel(label) | random_line_split |
github-label-manager.js | // ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @requi... | (label, element) {
find('.js-edit-label', element).click()
find('.label-edit-name', element).value = label.name
find('.color-editor-input', element).value = label.color
find('.new-label-actions .btn-primary', element).click()
}
function addLabel(label) {
find('input.label-edit-name', newLabelForm).... | updateLabel | identifier_name |
github-label-manager.js | // ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @requi... |
for(const label of labels) {
addLabel(label)
}
}
reader.readAsText(importInput.files[0])
})
exportButton.addEventListener('click', exportLabels)
}
function rgb2hex(rgb) {
const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
const... | {
deleteAllLabels()
} | conditional_block |
vn_char.py | import lxml.html as l
import requests
def | (char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.cssselect('.mainbox .charimg img')[0].attrib['src']
gen... | key_char_parse | identifier_name |
vn_char.py | import lxml.html as l
import requests
def key_char_parse(char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.c... |
except IndexError:
value = row[1].text
if key == 'Visual novels':
value = []
for span in row[1]:
if span.tag == 'span':
value.append(span.text + span[0].text)
desc = root... | if 'charspoil_1' in span.classes:
tag = 'minor spoiler'
elif 'charspoil_2' in span.classes:
tag = 'spoiler'
elif 'sexual' in span.classes:
tag = 'sexual trait'
... | conditional_block |
vn_char.py | import lxml.html as l
import requests
def key_char_parse(char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.c... | value.append({'value': span[1].text, 'tag': tag})
except IndexError:
value = row[1].text
if key == 'Visual novels':
value = []
for span in row[1]:
if span.tag == 'span':
... | tag = None
| random_line_split |
vn_char.py | import lxml.html as l
import requests
def key_char_parse(char_id):
| key = row[0].text
value = None
try:
if row[1][0].tag == 'a':
value = row[1][0].text
else:
value = []
for span in row[1]:
if 'ch... | url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.cssselect('.mainbox .charimg img')[0].attrib['src']
gender = root.csss... | identifier_body |
frame-source.ts | import path from 'path';
import execa from 'execa';
import {
FFMPEG_EXE,
SCRUB_FRAMES,
SCRUB_HEIGHT,
SCRUB_SPRITE_DIRECTORY,
SCRUB_WIDTH,
} from './constants';
import { FrameReadError } from './errors';
import { IExportOptions } from '.';
export class FrameSource {
writeBuffer = Buffer.allocUnsafe(this.opt... |
if (this.error) {
throw new FrameReadError(this.sourcePath);
}
// The stream was closed, so resolve that a frame could not be read.
if (this.finished) {
resolve(false);
return;
}
this.onFrameComplete = frameRead => {
this.error ? reject(new FrameRe... | {
console.log('Cannot read next frame while frame read is in progress');
resolve(false);
return;
} | conditional_block |
frame-source.ts | import path from 'path';
import execa from 'execa';
import {
FFMPEG_EXE,
SCRUB_FRAMES,
SCRUB_HEIGHT,
SCRUB_SPRITE_DIRECTORY,
SCRUB_WIDTH,
} from './constants';
import { FrameReadError } from './errors';
import { IExportOptions } from '.';
export class FrameSource {
writeBuffer = Buffer.allocUnsafe(this.opt... | () {
/* eslint-disable */
const args = [
'-ss', this.startTrim.toString(),
'-i', this.sourcePath,
'-t', (this.duration - this.startTrim - this.endTrim).toString(),
'-vf', `fps=${this.options.fps},scale=${this.options.width}:${this.options.height}`,
'-map', 'v:0',
'-vcodec', '... | startFfmpeg | identifier_name |
frame-source.ts | import path from 'path';
import execa from 'execa';
import {
FFMPEG_EXE,
SCRUB_FRAMES,
SCRUB_HEIGHT,
SCRUB_SPRITE_DIRECTORY,
SCRUB_WIDTH,
} from './constants';
import { FrameReadError } from './errors';
import { IExportOptions } from '.';
export class FrameSource {
writeBuffer = Buffer.allocUnsafe(this.opt... |
private startFfmpeg() {
/* eslint-disable */
const args = [
'-ss', this.startTrim.toString(),
'-i', this.sourcePath,
'-t', (this.duration - this.startTrim - this.endTrim).toString(),
'-vf', `fps=${this.options.fps},scale=${this.options.width}:${this.options.height}`,
'-map', 'v... | {
const parsed = path.parse(this.sourcePath);
this.scrubJpg = path.join(SCRUB_SPRITE_DIRECTORY, `${parsed.name}-scrub.jpg`);
/* eslint-disable */
const args = [
'-i', this.sourcePath,
'-vf', `scale=${SCRUB_WIDTH}:${SCRUB_HEIGHT},fps=${SCRUB_FRAMES / this.duration},tile=${SCRUB_FRAMES}x1`,
... | identifier_body |
frame-source.ts | import path from 'path';
import execa from 'execa';
import {
FFMPEG_EXE,
SCRUB_FRAMES,
SCRUB_HEIGHT,
SCRUB_SPRITE_DIRECTORY,
SCRUB_WIDTH,
} from './constants';
import { FrameReadError } from './errors';
import { IExportOptions } from '.';
export class FrameSource {
writeBuffer = Buffer.allocUnsafe(this.opt... | this.ffmpeg = execa(FFMPEG_EXE, args, {
encoding: null,
buffer: false,
stdin: 'ignore',
stdout: 'pipe',
stderr: process.stderr,
});
this.ffmpeg.on('exit', code => {
console.debug(
`Highlighter Frame Count: Expected: ${this.nFrames} Actual: ${this.currentFrame}`,
... | random_line_split | |
js-themes-registry.service.d.ts | import 'rxjs/add/operator/publish';
import { NbJSThemeOptions } from './js-themes/theme.options';
export declare const BUILT_IN_THEMES: NbJSThemeOptions[];
/**
* Js Themes registry - provides access to the JS themes' variables.
* Usually shouldn't be used directly, but through the NbThemeService class methods (getJsT... | constructor(builtInThemes: NbJSThemeOptions[], newThemes?: NbJSThemeOptions[]);
/**
* Registers a new JS theme
* @param config any
* @param themeName string
* @param baseTheme string
*/
register(config: any, themeName: string, baseTheme: string): void;
/**
* Checks whether ... | export declare class NbJSThemesRegistry {
private builtInThemes;
private newThemes;
private themes; | random_line_split |
js-themes-registry.service.d.ts | import 'rxjs/add/operator/publish';
import { NbJSThemeOptions } from './js-themes/theme.options';
export declare const BUILT_IN_THEMES: NbJSThemeOptions[];
/**
* Js Themes registry - provides access to the JS themes' variables.
* Usually shouldn't be used directly, but through the NbThemeService class methods (getJsT... | {
private builtInThemes;
private newThemes;
private themes;
constructor(builtInThemes: NbJSThemeOptions[], newThemes?: NbJSThemeOptions[]);
/**
* Registers a new JS theme
* @param config any
* @param themeName string
* @param baseTheme string
*/
register(config: any, th... | NbJSThemesRegistry | identifier_name |
imgLiquid.js | check resize in milliseconds
>js callBakcs
onStart: function(){},
onFinish: function(){},
onItemResize: function(index, container, img){},
onItemStart: function(index, container, img){},
onItemFinish: function(index, container, img){}
>css (set useCssAligns: true) (overwrite js)
tex... | ($imgBoxCont, $img, $i){
//RESIZE
var w,h;
if ($img.data('owidth') === undefined) $img.data('owidth', $img[0].width);
if ($img.data('oheight') === undefined) $img.data('oheight', $img[0].height);
if (settings.fill === ($imgBoxCont.width() / $imgBoxCont.height()) >= ($img.data('owidth') ... | process | identifier_name |
imgLiquid.js | check resize in milliseconds
>js callBakcs
onStart: function(){},
onFinish: function(){},
onItemResize: function(index, container, img){},
onItemStart: function(index, container, img){},
onItemFinish: function(index, container, img){}
>css (set useCssAligns: true) (overwrite js)
tex... |
if (settings.responsive) settings.hardPixels = true;
if (settings.responsive || settings.onItemResize !== null) checkElementSize();
//SAVE FIRST TIME SETTINGS
self.data('settings', settings);
//LOAD
$img.on('load', onLoad).on('error', onError);
if($img[0].complete)$img.load();
... | {
//UPDATE SETTINGS
settings = $.extend(self.data('settings'));
$imgBoxCont.actualSize = $imgBoxCont.get(0).offsetWidth + ($imgBoxCont.get(0).offsetHeight/100000);
if ($imgBoxCont.actualSize !== $imgBoxCont.sizeOld){
if ($img.data('ILprocessed') && $imgBoxCont.sizeOld !== undefined){
... | identifier_body |
imgLiquid.js | check resize in milliseconds
>js callBakcs
onStart: function(){},
onFinish: function(){},
onItemResize: function(index, container, img){},
onItemStart: function(index, container, img){},
onItemFinish: function(index, container, img){}
>css (set useCssAligns: true) (overwrite js)
tex... | if (e) e.preventDefault();
}
function onError(){
$img.ILerror = true;
checkFinish($imgBoxCont, $img, $i);
$imgBoxCont.css('visibility', 'hidden');
}
function checkProcess(){
if ($img.data('ILprocessed')) return;
setTimeout(function() {
if ($imgBoxCont.is(':v... | setTimeout(function() {
process($imgBoxCont, $img, $i);
}, $i * settings.delay);
}
}
| random_line_split |
pipeline.js | /**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files, and the ! prefix for excluding files.)... | ];
// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(transformPath);
module.exports.jsFilesToInject = jsFilesToInject.map(... | var templateFilesToInject = [
'templates/**/*.html' | random_line_split |
pipeline.js | /**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files, and the ! prefix for excluding files.)... | {
return (path.substring(0,1) == '!') ? ('!' + tmpPath + path.substring(1)) : (tmpPath + path);
} | identifier_body | |
pipeline.js | /**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files, and the ! prefix for excluding files.)... | (path) {
return (path.substring(0,1) == '!') ? ('!' + tmpPath + path.substring(1)) : (tmpPath + path);
}
| transformPath | identifier_name |
GroupView.js | var GroupView = function(json) {
"use strict";
var template;
if (!json.$t) | Fave.register(albums[i].songs[j]);
Rating.register(albums[i].songs[j]);
if (albums[i].songs[j].requestable) {
Requests.make_clickable(albums[i].songs[j].$t.title, albums[i].songs[j].id);
}
SongsTableDetail(albums[i].songs[j], ((i == albums.length - 1) && (j > albums[i].songs.length - 4)));
}... | {
var albums = [];
var a, album_id, i;
for (album_id in json.all_songs_for_sid) {
a = json.all_songs_for_sid[album_id][0].albums[0];
// cut off a circular memory reference quick-like
json.all_songs_for_sid[album_id][0].albums = null;
a.songs = json.all_songs_for_sid[album_id].sort(SongsTableSorting);
... | conditional_block |
GroupView.js | var GroupView = function(json) {
"use strict";
var template;
if (!json.$t) {
var albums = [];
var a, album_id, i;
for (album_id in json.all_songs_for_sid) {
a = json.all_songs_for_sid[album_id][0].albums[0];
// cut off a circular memory reference quick-like
json.all_songs_for_sid[album_id][0].albums =... | albums.push(a);
}
albums.sort(SongsTableAlbumSort);
template = RWTemplates.detail.group({ "group": json, "albums": albums }, MOBILE ? null : document.createElement("div"));
var j;
for (i = 0; i < albums.length; i++) {
for (j = 0; j < albums[i].songs.length; j++) {
Fave.register(albums[i].songs[j])... | a.songs = json.all_songs_for_sid[album_id].sort(SongsTableSorting);
for (i = 0; i < a.songs.length; i++) {
a.songs[i].artists = JSON.parse(a.songs[i].artist_parseable);
} | random_line_split |
errors.spec.ts | import { expect } from "chai";
import { basename } from "path";
import { coerceAsError, ErrorWithCause } from "df/common/errors/errors";
import { suite, test } from "df/testing";
suite(basename(__filename), () => {
suite("ErrorWithCause", () => {
for (const testCase of [
{ name: "with message", message: "... | expect(errorWithCause.stack.endsWith(cause.stack)).eql(true);
});
});
suite("coerceAsError", () => {
test("preserves original error", () => {
const originalError = new ErrorWithCause(new Error("cause"));
const coercedError = coerceAsError(originalError);
expect(coercedError).equals... | const errorWithCause = new ErrorWithCause("top-level error", cause);
// Full stacktrace should be double the length of a single Error's stacktrace.
expect(errorWithCause.stack.split("\n").length).eql(cause.stack.split("\n").length * 2);
expect(errorWithCause.stack.startsWith("Error: top-level e... | random_line_split |
transitiveExportImports.ts | /// <reference path='fourslash.ts'/>
// @Filename: a.ts
////class [|{| "isWriteAccess": true, "isDefinition": true |}A|] {
| ////}
////export = [|A|];
// @Filename: b.ts
////export import [|{| "isWriteAccess": true, "isDefinition": true |}b|] = require('./a');
// @Filename: c.ts
////import [|{| "isWriteAccess": true, "isDefinition": true |}b|] = require('./b');
////var a = new [|b|]./**/[|b|]();
goTo.marker();
verify.quickInfoE... | random_line_split | |
trends.ts | export default [
"cats",
"dogs",
"birth-control",
"the police",
"teachers",
"babies",
"white people",
"purple people",
"fire fighters",
"hamsters",
"macaroni",
"kangaroos",
"politicians",
"hospitals",
"girlfriends",
"boyfriends",
"exercises",
"eati... | "skateboards",
"apples",
"oranges",
"hotdogs",
"hamburgers",
"fat people",
"skinny people",
"doors",
"houses",
"cigars",
"marijuanas",
"bands",
"popcorn",
"sodas",
"movies",
"blind people",
"elephants",
"shoes",
"hippies",
"beards",
"ey... | random_line_split | |
librarylogger.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
def trace(msg, html=False):
write(msg, 'TRACE', html)
def debug(msg, html=False):
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
write(msg, 'WARN', html)
def error(msg, html... | if callable(msg):
msg = unic(msg)
if level.upper() not in ('TRACE', 'DEBUG', 'INFO', 'HTML', 'WARN', 'ERROR'):
raise DataError("Invalid log level '%s'." % level)
if threading.currentThread().getName() in LOGGING_THREADS:
LOGGER.log_message(Message(msg, level, html)) | identifier_body |
librarylogger.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
def trace(msg, html=False):
write(msg, 'TRACE', html)
def debug(msg, html=False):
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
write(msg, 'WARN', html)
def error(msg, html... | LOGGER.log_message(Message(msg, level, html)) | conditional_block |
librarylogger.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | # http://code.google.com/p/robotframework/issues/detail?id=1505
if callable(msg):
msg = unic(msg)
if level.upper() not in ('TRACE', 'DEBUG', 'INFO', 'HTML', 'WARN', 'ERROR'):
raise DataError("Invalid log level '%s'." % level)
if threading.currentThread().getName() in LOGGING_THREADS:
... |
def write(msg, level, html=False):
# Callable messages allow lazy logging internally, but we don't want to
# expose this functionality publicly. See the following issue for details: | random_line_split |
librarylogger.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | (msg, html=False):
write(msg, 'TRACE', html)
def debug(msg, html=False):
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
write(msg, 'WARN', html)
def error(msg, html=False):
... | trace | identifier_name |
conditional-compile.rs | // xfail-fast
// 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
// <... | {
i: int,
}
fn r(i:int) -> r {
r {
i: i
}
}
#[cfg(bogus)]
mod m {
// This needs to parse but would fail in typeck. Since it's not in
// the current config it should not be typechecked.
pub fn bogus() { return 0; }
}
mod m {
// Submodules have slightly different code paths than the ... | r | identifier_name |
conditional-compile.rs | // xfail-fast
// 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
// <... | impl Fooable for Foo {
#[cfg(bogus)]
fn what(&self) { }
fn what(&self) { }
#[cfg(bogus)]
fn the(&self) { }
fn the(&self) { }
}
trait Fooable {
#[cfg(bogus)]
fn what(&self);
fn what(&self);
#[cfg(bogus)]
fn the(&sel... | mod test_methods {
struct Foo {
bar: uint
}
| random_line_split |
conditional-compile.rs | // xfail-fast
// 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
// <... |
#[cfg(bogus)]
fn the(&self) { }
fn the(&self) { }
}
trait Fooable {
#[cfg(bogus)]
fn what(&self);
fn what(&self);
#[cfg(bogus)]
fn the(&self);
fn the(&self);
}
}
| { } | identifier_body |
unused_async.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_session::{d... | (
&mut self,
cx: &LateContext<'tcx>,
fn_kind: FnKind<'tcx>,
fn_decl: &'tcx FnDecl<'tcx>,
body: &Body<'tcx>,
span: Span,
hir_id: HirId,
) {
if let FnKind::ItemFn(_, _, FnHeader { asyncness, .. }, _) = &fn_kind {
if matches!(asyncness, IsAsyn... | check_fn | identifier_name |
unused_async.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_session::{d... | } | random_line_split | |
unused_async.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_session::{d... |
}
}
| {
if matches!(asyncness, IsAsync::Async) {
let mut visitor = AsyncFnVisitor { cx, found_await: false };
walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id);
if !visitor.found_await {
span_lint_and_help(
... | conditional_block |
unused_async.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_session::{d... |
}
| {
if let FnKind::ItemFn(_, _, FnHeader { asyncness, .. }, _) = &fn_kind {
if matches!(asyncness, IsAsync::Async) {
let mut visitor = AsyncFnVisitor { cx, found_await: false };
walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id);
if !visito... | identifier_body |
views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask... | """Base class for admin pages."""
def __init__(self, rh, active_menu_item=None, **kwargs):
kwargs['active_menu_item'] = active_menu_item or self.sidemenu_option
WPDecorated.__init__(self, rh, **kwargs)
def _get_breadcrumbs(self):
menu_item = get_menu_item('admin-sidemenu', self._kwargs... | identifier_body | |
views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask... | (self, params):
return self._get_page_content(params)
| _get_body | identifier_name |
views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask... |
return render_breadcrumbs(*items)
def _get_body(self, params):
return self._get_page_content(params)
| items.append(menu_item.title) | conditional_block |
views.py | # This file is part of Indico. | # Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask.util import url_for
from indic... | random_line_split | |
semioticGraph.tsx | import * as React from 'react';
import ContainerDimensions from 'react-container-dimensions';
import BoxPlot from './boxplot';
import Histogram from './histogram';
import { GraphType, IMetricSetPairGraphProps } from '../metricSetPairGraph.service';
import NoValidDataSign from './noValidDataSign';
import TimeSeries fro... | return (
<div className="semiotic-graph">
<ContainerDimensions>{({ width }: { width: number }) => this.fetchChart(width)}</ContainerDimensions>
</div>
);
}
} | };
public render() { | random_line_split |
semioticGraph.tsx | import * as React from 'react';
import ContainerDimensions from 'react-container-dimensions';
import BoxPlot from './boxplot';
import Histogram from './histogram';
import { GraphType, IMetricSetPairGraphProps } from '../metricSetPairGraph.service';
import NoValidDataSign from './noValidDataSign';
import TimeSeries fro... | () {
return (
<div className="semiotic-graph">
<ContainerDimensions>{({ width }: { width: number }) => this.fetchChart(width)}</ContainerDimensions>
</div>
);
}
}
| render | identifier_name |
semioticGraph.tsx | import * as React from 'react';
import ContainerDimensions from 'react-container-dimensions';
import BoxPlot from './boxplot';
import Histogram from './histogram';
import { GraphType, IMetricSetPairGraphProps } from '../metricSetPairGraph.service';
import NoValidDataSign from './noValidDataSign';
import TimeSeries fro... |
switch (type) {
case GraphType.TimeSeries:
return <TimeSeries {...chartProps} />;
case GraphType.Histogram:
return <Histogram {...chartProps} />;
case GraphType.BoxPlot:
return <BoxPlot {...chartProps} />;
default:
return null;
}
};
public render() ... | {
return <NoValidDataSign />;
} | conditional_block |
math_improved.py | # We try to improve the previous 'math_operation.py' by reduce the code
# here we introduce a concept named list-comprehensive
# Knowledge points:
# 1. list-comprehensive, the [x for x in a-list]
# 2. dir() function to get the current environment variable names in space.
# 3. "in" check, we never user string.search() i... | env_variables = dir()
for var in env_variables:
if "_numbers" in var:
print var, ":", eval(var) | # use the function "dir()" | random_line_split |
math_improved.py | # We try to improve the previous 'math_operation.py' by reduce the code
# here we introduce a concept named list-comprehensive
# Knowledge points:
# 1. list-comprehensive, the [x for x in a-list]
# 2. dir() function to get the current environment variable names in space.
# 3. "in" check, we never user string.search() i... | print var, ":", eval(var) | conditional_block | |
dump_dependency_json.py | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
generator_supports_multiple_toolsets = True
g... |
# Queue of targets to visit.
targets_to_visit = target_list[:]
while len(targets_to_visit) > 0:
target = targets_to_visit.pop()
if target in edges:
continue
edges[target] = []
for dep in target_dicts[target].get('dependencies', []):
edges[target].append(dep)
targets_to_visit.a... | edges = {} | random_line_split |
dump_dependency_json.py | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
generator_supports_multiple_toolsets = True
g... | (target_list, target_dicts, _, params):
# Map of target -> list of targets it depends on.
edges = {}
# Queue of targets to visit.
targets_to_visit = target_list[:]
while len(targets_to_visit) > 0:
target = targets_to_visit.pop()
if target in edges:
continue
edges[target] = []
for dep ... | GenerateOutput | identifier_name |
dump_dependency_json.py | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
generator_supports_multiple_toolsets = True
g... |
def GenerateOutput(target_list, target_dicts, _, params):
# Map of target -> list of targets it depends on.
edges = {}
# Queue of targets to visit.
targets_to_visit = target_list[:]
while len(targets_to_visit) > 0:
target = targets_to_visit.pop()
if target in edges:
continue
edges[target... | """Calculate the generator specific info that gets fed to input (called by
gyp)."""
generator_flags = params.get('generator_flags', {})
if generator_flags.get('adjust_static_libraries', False):
global generator_wants_static_library_dependencies_adjusted
generator_wants_static_library_dependencies_adjusted... | identifier_body |
dump_dependency_json.py | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
generator_supports_multiple_toolsets = True
g... |
def CalculateVariables(default_variables, params):
generator_flags = params.get('generator_flags', {})
for key, val in generator_flags.items():
default_variables.setdefault(key, val)
default_variables.setdefault('OS', gyp.common.GetFlavor(params))
flavor = gyp.common.GetFlavor(params)
if flavor =='win... | generator_default_variables[unused] = '' | conditional_block |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
| #![allow(non_snake_case)]
extern crate lua;
use std::io::{self, Write};
use std::path::Path;
use std::process;
fn main() {
let mut L = lua::State::new();
L.openlibs(); // Load Lua libraries
// Load the file containing the script we are going to run
let path = Path::new("simpleapi.lua");
match L.... | random_line_split | |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
#![allow(non_snake_case)]
exte... | */
L.newtable(); // We will pass a table
/*
* To put values into the table, we first push the index, then the
* value, and then call rawset() with the index of the table in the
* stack. Let's see why it's -3: In Lua, the value -1 always refers to
* the top of the stack. When you create... | {
let mut L = lua::State::new();
L.openlibs(); // Load Lua libraries
// Load the file containing the script we are going to run
let path = Path::new("simpleapi.lua");
match L.loadfile(Some(&path)) {
Ok(_) => (),
Err(_) => {
// If something went wrong, error message is at... | identifier_body |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
#![allow(non_snake_case)]
exte... | () {
let mut L = lua::State::new();
L.openlibs(); // Load Lua libraries
// Load the file containing the script we are going to run
let path = Path::new("simpleapi.lua");
match L.loadfile(Some(&path)) {
Ok(_) => (),
Err(_) => {
// If something went wrong, error message is... | main | identifier_name |
keyboardEvent.ts | Break); // VK_CANCEL 0x03 Control-break processing
define(8, KeyCode.Backspace);
define(9, KeyCode.Tab);
define(13, KeyCode.Enter);
define(16, KeyCode.Shift);
define(17, KeyCode.Ctrl);
define(18, KeyCode.Alt);
define(19, KeyCode.PauseBreak);
define(20, KeyCode.CapsLock);
define(27, KeyCode.Escape);
define(32,... |
export function printStandardKeyboardEvent(e: StandardKeyboardEvent): string {
let modifiers: string[] = [];
if (e.ctrlKey) {
modifiers.push(`ctrl`);
}
if (e.shiftKey) {
modifiers.push(`shift`);
}
if (e.altKey) {
modifiers.push(`alt`);
}
if (e.metaKey) {
modifiers.push(`meta`);
}
return `modifiers: ... | {
let modifiers: string[] = [];
if (e.ctrlKey) {
modifiers.push(`ctrl`);
}
if (e.shiftKey) {
modifiers.push(`shift`);
}
if (e.altKey) {
modifiers.push(`alt`);
}
if (e.metaKey) {
modifiers.push(`meta`);
}
return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}... | identifier_body |
keyboardEvent.ts | Break); // VK_CANCEL 0x03 Control-break processing
define(8, KeyCode.Backspace);
define(9, KeyCode.Tab);
define(13, KeyCode.Enter);
define(16, KeyCode.Shift);
define(17, KeyCode.Ctrl);
define(18, KeyCode.Alt);
define(19, KeyCode.PauseBreak);
define(20, KeyCode.CapsLock);
define(27, KeyCode.Escape);
define(32,... | implements IKeyboardEvent {
readonly _standardKeyboardEventBrand = true;
public readonly browserEvent: KeyboardEvent;
public readonly target: HTMLElement;
public readonly ctrlKey: boolean;
public readonly shiftKey: boolean;
public readonly altKey: boolean;
public readonly metaKey: boolean;
public readonly k... | StandardKeyboardEvent | identifier_name |
keyboardEvent.ts | Break); // VK_CANCEL 0x03 Control-break processing
define(8, KeyCode.Backspace);
define(9, KeyCode.Tab);
define(13, KeyCode.Enter);
define(16, KeyCode.Shift);
define(17, KeyCode.Ctrl);
define(18, KeyCode.Alt);
define(19, KeyCode.PauseBreak);
define(20, KeyCode.CapsLock);
define(27, KeyCode.Escape);
define(32,... |
const ctrlKeyMod = (platform.isMacintosh ? KeyMod.WinCtrl : KeyMod.CtrlCmd);
const altKeyMod = KeyMod.Alt;
const shiftKeyMod = KeyMod.Shift;
const metaKeyMod = (platform.isMacintosh ? KeyMod.CtrlCmd : KeyMod.WinCtrl);
export function printKeyboardEvent(e: KeyboardEvent): string {
let modifiers: string[] = [];
if (e... | stopPropagation(): void;
} | random_line_split |
compiler.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 {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, Injectable, Optional, PLATFORM_INITIAL... | () {
reflector.reflectionCapabilities = new ReflectionCapabilities();
}
/**
* A platform that included corePlatform and the compiler.
*
* @experimental
*/
export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [
{provide: COMPILER_OPTIONS, useValue: {}, multi: true},
{provide: ... | _initReflector | identifier_name |
compiler.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 {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, Injectable, Optional, PLATFORM_INITIAL... | */
export const COMPILER_PROVIDERS: Array<any|Type<any>|{[k: string]: any}|any[]> = [
{provide: Reflector, useValue: reflector},
{provide: ReflectorReader, useExisting: Reflector},
{provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER},
Console,
Lexer,
Parser,
HtmlParser,
{
provide: i18n.I18NHtml... | random_line_split | |
compiler.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 {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, Injectable, Optional, PLATFORM_INITIAL... |
function _lastDefined<T>(args: T[]): T {
for (var i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}
function _mergeArrays(parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => part && result.push(...part));
return res... | {
return {
useDebug: _lastDefined(optionsArr.map(options => options.useDebug)),
useJit: _lastDefined(optionsArr.map(options => options.useJit)),
defaultEncapsulation: _lastDefined(optionsArr.map(options => options.defaultEncapsulation)),
providers: _mergeArrays(optionsArr.map(options => options.provid... | identifier_body |
compiler.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 {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, Injectable, Optional, PLATFORM_INITIAL... |
}
return undefined;
}
function _mergeArrays(parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => part && result.push(...part));
return result;
}
| {
return args[i];
} | conditional_block |
route-list.rs | extern crate neli;
use std::error::Error;
use std::net::IpAddr;
use neli::consts::*;
use neli::err::NlError;
use neli::nl::Nlmsghdr;
use neli::rtnl::*;
use neli::socket::*;
fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>) | Rta::Dst => dst = to_addr(&attr.rta_payload),
Rta::Prefsrc => src = to_addr(&attr.rta_payload),
Rta::Gateway => gateway = to_addr(&attr.rta_payload),
_ => (),
}
}
if let Some(dst) = dst {
print!("{}/{} ", dst, rtm.n... | {
// This sample is only interested in the main table.
if rtm.nl_payload.rtm_table == RtTable::Main {
let mut src = None;
let mut dst = None;
let mut gateway = None;
for attr in rtm.nl_payload.rtattrs.iter() {
fn to_addr(b: &[u8]) -> Option<IpAddr> {
... | identifier_body |
route-list.rs | extern crate neli;
use std::error::Error;
use std::net::IpAddr;
use neli::consts::*;
use neli::err::NlError;
use neli::nl::Nlmsghdr;
use neli::rtnl::*;
use neli::socket::*;
fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>) {
// This sample is only interested in the main table.
if rtm.nl_payload.rtm_table == Rt... | () -> Result<(), Box<dyn Error>> {
let mut socket = NlSocket::connect(NlFamily::Route, None, None, true).unwrap();
let rtmsg = Rtmsg {
rtm_family: RtAddrFamily::Inet,
rtm_dst_len: 0,
rtm_src_len: 0,
rtm_tos: 0,
rtm_table: RtTable::Unspec,
rtm_protocol: Rtprot::Un... | main | identifier_name |
route-list.rs | extern crate neli;
use std::error::Error;
use std::net::IpAddr;
use neli::consts::*;
use neli::err::NlError;
use neli::nl::Nlmsghdr;
use neli::rtnl::*;
use neli::socket::*;
fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>) {
// This sample is only interested in the main table.
if rtm.nl_payload.rtm_table == Rt... | }
}
}
}
Ok(())
} | nl_payload: nl.nl_payload,
};
// Some other message type, so let's try to deserialize as a Rtm.
parse_route_table(rtm) | random_line_split |
handlebars.items-stored.js | (function() {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; | templates['items-stored'] = template({"1":function(container,depth0,helpers,partials,data) {
var helper, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
return "<tr>\n <td><i class=\"icon-"
+ alias4(((helper = (helper = helpers.smiling ... | random_line_split | |
rte.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(s... |
if mg.get('hls_server') and mg.get('hls_url'):
formats.extend(self._extract_m3u8_formats(
mg['hls_server'] + mg['hls_url'], item_id, 'mp4',
entry_protocol='m3u8_native', m3u8_id='hls', fatal=False))
if mg.get('hds_server') and mg.get('hds_url'):
formats.extend(self._extract_f4m_formats(
... | m = m.groupdict()
formats.append({
'url': m['url'] + '/' + m['app'],
'app': m['app'],
'play_path': m['playpath'],
'player_url': url,
'ext': 'flv',
'format_id': 'rtmp',
}) | conditional_block |
rte.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(s... | if not info_dict:
title = unescapeHTML(show['title'])
description = unescapeHTML(show.get('description'))
thumbnail = show.get('thumbnail')
duration = float_or_none(show.get('duration'), 1000)
timestamp = parse_iso8601(show.get('published'))
info_dict = {
'id': item_id,
'title': tit... | random_line_split | |
rte.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(s... | 'upload_date': '20151227',
'duration': 7230.0,
},
}, {
# New-style player URL; RTMPE formats only
'url': 'http://rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=b16_3250678_8861_06-04-2012_',
'info_dict': {
'id': '3250678',
'ext': 'flv',
'title': 'The Lyric Concert with Paul Herriott',
'... | NAME = 'rte:radio'
IE_DESC = 'Raidió Teilifís Éireann radio'
# Radioplayer URLs have two distinct specifier formats,
# the old format #!rii=<channel_id>:<id>:<playable_item_id>:<date>:
# the new format #!rii=b<channel_id>_<id>_<playable_item_id>_<date>_
# where the IDs are int/empty, the date is DD-MM-YYYY, and th... | identifier_body |
rte.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class | (InfoExtractor):
def _real_extract(self, url):
item_id = self._match_id(url)
info_dict = {}
formats = []
ENDPOINTS = (
'https://feeds.rasset.ie/rteavgen/player/playlist?type=iptv&format=json&showId=',
'http://www.rte.ie/rteavgen/getplaylist/?type=web&format=json&id=',
)
for num, ep_url in enumerat... | RteBaseIE | identifier_name |
proto.rs |
use bytes::{BufMut, BytesMut};
use futures::Future;
use std::{io, str};
use std::net::SocketAddr;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_proto::TcpClient;
use tokio_proto::multiplex::{ClientPr... |
}
| {
Ok(io.framed(MultiplexedCodec { header: None }))
} | identifier_body |
proto.rs |
use bytes::{BufMut, BytesMut};
use futures::Future;
use std::{io, str};
use std::net::SocketAddr;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_proto::TcpClient;
use tokio_proto::multiplex::{ClientPr... | else {
let header = buffer.split_to(header_length);
let mut reader = io::Cursor::new(header);
let header = DataFrameHeader::from_bytes(&mut reader)?;
self.decode_frame(header, buffer)
}
}
}
}
impl Encoder for MultiplexedCodec {
... | {
Ok(None)
} | conditional_block |
proto.rs | use bytes::{BufMut, BytesMut};
use futures::Future;
use std::{io, str};
use std::net::SocketAddr;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_proto::TcpClient;
use tokio_proto::multiplex::{ClientProt... |
fn bind_transport(&self, io: T) -> Self::BindTransport {
Ok(io.framed(MultiplexedCodec { header: None }))
}
} | type Transport = Framed<T, MultiplexedCodec>;
type BindTransport = Result<Self::Transport, io::Error>; | random_line_split |
proto.rs |
use bytes::{BufMut, BytesMut};
use futures::Future;
use std::{io, str};
use std::net::SocketAddr;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_proto::TcpClient;
use tokio_proto::multiplex::{ClientPr... | {
inner: ClientService<TcpStream, MultiplexedProto>,
}
impl MultiplexedClient {
pub fn connect(
addr: &SocketAddr,
handle: &Handle,
) -> Box<Future<Item = MultiplexedClient, Error = io::Error>> {
Box::new(TcpClient::new(MultiplexedProto).connect(addr, handle).map(
|serv... | MultiplexedClient | identifier_name |
conf.py | the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to doc... | #
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '4.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "langu... | # |version| and |release|, also used in various other places throughout the
# built documents. | random_line_split |
create_profile.py | #!/usr/local/bin/python2.7
# encoding: utf-8
from __future__ import division
from argparse import ArgumentParser
import logging
import sys
from expertfinding import ExpertFinding
from collections import Counter
def main():
'''Command line options.'''
parser = ArgumentParser()
parser.add_argument("-n", "... | print u"{} freq={:.1%} importance={:.2f} entity_rarity={:.2f} max_rho={:.3f} years={}".format(entity, freq, ef_iaf*100, iaf, max_rho, years_freq)
print
return 0
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
sys.exit(main()) | random_line_split | |
create_profile.py | #!/usr/local/bin/python2.7
# encoding: utf-8
from __future__ import division
from argparse import ArgumentParser
import logging
import sys
from expertfinding import ExpertFinding
from collections import Counter
def | ():
'''Command line options.'''
parser = ArgumentParser()
parser.add_argument("-n", "--names", required=True, action="store", nargs="+", help="Names of people to profile")
parser.add_argument("-s", "--storage_db", required=True, action="store", help="Storage DB file")
args = parser.parse_args()
... | main | identifier_name |
create_profile.py | #!/usr/local/bin/python2.7
# encoding: utf-8
from __future__ import division
from argparse import ArgumentParser
import logging
import sys
from expertfinding import ExpertFinding
from collections import Counter
def main():
|
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
sys.exit(main())
| '''Command line options.'''
parser = ArgumentParser()
parser.add_argument("-n", "--names", required=True, action="store", nargs="+", help="Names of people to profile")
parser.add_argument("-s", "--storage_db", required=True, action="store", help="Storage DB file")
args = parser.parse_args()
exf = E... | identifier_body |
create_profile.py | #!/usr/local/bin/python2.7
# encoding: utf-8
from __future__ import division
from argparse import ArgumentParser
import logging
import sys
from expertfinding import ExpertFinding
from collections import Counter
def main():
'''Command line options.'''
parser = ArgumentParser()
parser.add_argument("-n", "... |
print
return 0
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
sys.exit(main())
| years_freq = ", ".join("{}{}".format(y, "(x{})".format(freq) if freq > 1 else "") for y, freq in sorted(Counter(years).items(), key=lambda p: p[0]))
print u"{} freq={:.1%} importance={:.2f} entity_rarity={:.2f} max_rho={:.3f} years={}".format(entity, freq, ef_iaf*100, iaf, max_rho, years_freq) | conditional_block |
OperatorEncodeEvent.ts | import * as events from 'events';
import { inject, injectable } from 'inversify';
import ILogger from '../ILogger';
import ILoggerModel from '../ILoggerModel';
import IOperatorEncodeEvent, { OperatorFinishEncodeInfo } from './IOperatorEncodeEvent';
@injectable()
class OperatorEncodeEvent implements IOperatorEncodeEven... |
/**
* エンコード完了イベント発行
* @param info: OperatorFinishEncodeInfo
*/
public emitFinishEncode(info: OperatorFinishEncodeInfo): void {
this.emitter.emit(OperatorEncodeEvent.FINISH_ENCODE_EVENT, info);
}
/**
* エンコード完了イベント登録
* @param callback: (info: OperatorFinishEncodeInfo) =... | {
this.log = logger.getLogger();
} | identifier_body |
OperatorEncodeEvent.ts | import * as events from 'events';
import { inject, injectable } from 'inversify';
import ILogger from '../ILogger';
import ILoggerModel from '../ILoggerModel';
import IOperatorEncodeEvent, { OperatorFinishEncodeInfo } from './IOperatorEncodeEvent';
@injectable()
class OperatorEncodeEvent implements IOperatorEncodeEven... |
namespace OperatorEncodeEvent {
export const FINISH_ENCODE_EVENT = 'finishEncodeEvent';
}
export default OperatorEncodeEvent; | }
});
}
} | random_line_split |
OperatorEncodeEvent.ts | import * as events from 'events';
import { inject, injectable } from 'inversify';
import ILogger from '../ILogger';
import ILoggerModel from '../ILoggerModel';
import IOperatorEncodeEvent, { OperatorFinishEncodeInfo } from './IOperatorEncodeEvent';
@injectable()
class OperatorEncodeEvent implements IOperatorEncodeEven... | : void {
this.emitter.on(OperatorEncodeEvent.FINISH_ENCODE_EVENT, async (info: OperatorFinishEncodeInfo) => {
try {
await callback(info);
} catch (err: any) {
this.log.system.error(err);
}
});
}
}
namespace OperatorEncodeEvent {
... | eInfo) => void) | identifier_name |
webSocketMiddleware.ts | Websocket from 'reconnecting-websocket';
import {Dispatch, Middleware} from 'redux';
import {authConnected, error} from "../connectionActions";
import {Item} from "../../graph/interfaces/item";
import {
liveReceive,
searchReceive,
setSearchTotal
} from "../../search/searchActions";
import {requestCompleted} from "..... |
case REQUEST_COMPLETED:
dispatch(requestCompleted(data['request-id']));
break;
case 'ERROR':
console.error(data);
dispatch(error(data.message, data['request-id']));
}
}
function onClose(event: CloseEvent, dispatch: Dispatch<any>) {
let reason = get... | }));
break; | random_line_split |
webSocketMiddleware.ts | Websocket from 'reconnecting-websocket';
import {Dispatch, Middleware} from 'redux';
import {authConnected, error} from "../connectionActions";
import {Item} from "../../graph/interfaces/item";
import {
liveReceive,
searchReceive,
setSearchTotal
} from "../../search/searchActions";
import {requestCompleted} from "..... | item.datasourceId = datasourceId
});
let results = debouncedItems[requestId] || [];
for (let i = 0; i < newItems.length; i++ ) {
let result = newItems[i];
let index = results.findIndex((item) => item.id === result.id);
if (index === -1) {
results.push(result);
... | {
if (fields) {
Object.keys(fields).forEach(datasource => {
if (!debouncedFields[datasource]) {
debouncedFields[datasource] = {};
}
Object.keys(fields[datasource]).forEach(field => {
const type: string = fields[datasource][field];
debouncedFields[datasource][field] = type;
});
});
}
... | identifier_body |
webSocketMiddleware.ts | Websocket from 'reconnecting-websocket';
import {Dispatch, Middleware} from 'redux';
import {authConnected, error} from "../connectionActions";
import {Item} from "../../graph/interfaces/item";
import {
liveReceive,
searchReceive,
setSearchTotal
} from "../../search/searchActions";
import {requestCompleted} from "..... | (dispatch: Dispatch<any>) {
dispatch(authConnected(true, null));
dispatch(receiveWorkspaceDescriptions([
{
id: '1',
title: 'Research',
version: 7
},
{
id: '2',
title: 'Malware',
version: 7
}
]));
}
function onMessage(event: MessageEvent, dispatch: Dispatch<any>) {
const data = J... | onOpen | identifier_name |
FlagView.js | 'use strict';
angular.module('cbt')
.directive('flagView', function(){
return {
restrict: 'E',
template: '{{title}}'+
'<a class="led" ng-repeat="led in values track by $index" ng-class="{\'active\':values[$index]}" title="{{info[title.toLowerCase()][$index]}}"></a>',
link: fun... |
}); | } | random_line_split |
ManifestRDFUtils.py | #!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed ... |
for statement in graphB:
if not graphContains(graphA, statement) : return False
subjectA = graphA.value(None,RDF.type, oxdsGroupingUri)
subjectB = graphB.value(None,RDF.type, oxdsGroupingUri)
for elementUri in elementUriListToCompare :
if graphA.value(subjectA,elemen... | return False | conditional_block |
ManifestRDFUtils.py | #!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed ... | if subject == None :
subject = BNode()
for index in range(len(elementUriList)):
rdfGraph.set((subject, elementUriList[index], Literal(elementValueList[index])))
saveToManifestFile(rdfGraph,manifestPath)
return rdfGraph
def saveToManifestFile(rdfGraph, manifestPath):
"""
Save... | # Read the manifest file and update the title and the description
rdfGraph = readManifestFile(manifestPath)
subject = rdfGraph.value(None,RDF.type, oxdsGroupingUri) | random_line_split |
ManifestRDFUtils.py | #!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed ... | (manifestPath, elementUriList):
"""
Gets the dictionary of Field-Values from the manifest RDF
manifestPath path of the manifest file
elementList Element Names List whose values need to be to be updated in the manifest files
"""
file = None
elementValueList = []
e... | getDictionaryFromManifest | identifier_name |
ManifestRDFUtils.py | #!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed ... |
def saveToManifestFile(rdfGraph, manifestPath):
"""
Save the RDF Graph into a manifest file.
rdfGraph RDF Graph to be serialised into the manifest file
manifestPath manifest file path
"""
# Serialise the RDf Graph into manifest.rdf file
rdfGraph.serialize(destinatio... | """
Update the manifest file.
manifestPath manifest file path
elementUriList Element Uri List whose values need to be to be updated in the manifest files
elementValueList Element Values List to be updated into the manifest files
"""
# Read the manifest file and update the title... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.