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 |
|---|---|---|---|---|
offer-card.ts | /**
* The card widget used to display single offer or post
*/
import { Component, Input } from '@angular/core';
import { ChangeDetectionStrategy } from '@angular/core';
import { Entity } from "../core/models";
import { Helper } from "../core/helper";
import {
trigger,
... |
@Component ({
selector: 'offer-card',
templateUrl: './offer-card.html',
changeDetection: ChangeDetectionStrategy.OnPush,
animations: [
trigger('fadeIn', [
state('in', style({ opacity: '1'})),
transition(':enter', [
style({ opacity: '0'}),
... | transition
} from '@angular/animations';
| random_line_split |
offer-card.ts |
/**
* The card widget used to display single offer or post
*/
import { Component, Input } from '@angular/core';
import { ChangeDetectionStrategy } from '@angular/core';
import { Entity } from "../core/models";
import { Helper } from "../core/helper";
import {
trigger,
... | (private helper: Helper) { }
@Input() title: string;
@Input() topics: Entity[];
@Input() category: string; // Category slug
// Will deprecate these
@Input() topic: Entity; // Topic object
}
| constructor | identifier_name |
tree.rs | /// Async server-side trees
use std::{ops, fmt, mem};
use dbus::tree::{Factory, Tree, MethodType, DataType, MTFn, Method, MethodInfo, MethodErr};
use dbus::{Member, Message, Connection};
use std::marker::PhantomData;
use std::cell::RefCell;
use futures::{IntoFuture, Future, Poll, Stream, Async};
use std::ffi::CString;... | () -> Self { Default::default() }
fn push(&self, a: AMethodResult) {
let mut z = self.0.borrow_mut();
assert!(z.is_none(), "Same message handled twice");
*z = Some(a);
}
}
impl<D: ADataType> DataType for ATree<D> {
type Tree = ATree<D>;
type ObjectPath = D::ObjectPath;
type ... | new | identifier_name |
tree.rs | /// Async server-side trees
use std::{ops, fmt, mem};
use dbus::tree::{Factory, Tree, MethodType, DataType, MTFn, Method, MethodInfo, MethodErr};
use dbus::{Member, Message, Connection};
use std::marker::PhantomData;
use std::cell::RefCell;
use futures::{IntoFuture, Future, Poll, Stream, Async};
use std::ffi::CString;... | else { return Ok(Async::Ready(Some(m))) }
} else { return z }
}
}
}
| {
self.spawn_method_results(m);
for msg in v { self.conn.send(msg)?; }
// We consumed the message. Poll again
} | conditional_block |
tree.rs | /// Async server-side trees
use std::{ops, fmt, mem};
use dbus::tree::{Factory, Tree, MethodType, DataType, MTFn, Method, MethodInfo, MethodErr};
use dbus::{Member, Message, Connection};
use std::marker::PhantomData;
use std::cell::RefCell;
use futures::{IntoFuture, Future, Poll, Stream, Async};
use std::ffi::CString; | type ObjectPath: fmt::Debug;
type Property: fmt::Debug;
type Interface: fmt::Debug + Default;
type Method: fmt::Debug + Default;
type Signal: fmt::Debug;
}
#[derive(Debug, Default)]
/// A Tree that allows both synchronous and asynchronous methods.
pub struct ATree<D: ADataType>(RefCell<Option<A... |
pub trait ADataType: fmt::Debug + Sized + Default { | random_line_split |
delaybot.py | #This bot was written by /u/GoldenSights for /u/FourMakesTwoUNLESS on behalf of /r/pkmntcgtrades. Uploaded to GitHub with permission.
import praw
import time
import datetime
import sqlite3
'''USER CONFIGURATION'''
APP_ID = ""
APP_SECRET = ""
APP_URI = ""
APP_REFRESH = ""
# https://www.reddit.com/comments/3cm1p8/how_t... | ():
print('Scanning ' + SUBREDDIT)
subreddit = r.get_subreddit(SUBREDDIT)
posts = subreddit.get_new(limit=MAXPOSTS)
for post in posts:
try:
pauthor = post.author.name
except Exception:
pauthor = '[deleted]'
pid = post.id
plink = post.short_link
ptime = post.created_utc
cur.execute('SELECT * FROM o... | scan | identifier_name |
delaybot.py | #This bot was written by /u/GoldenSights for /u/FourMakesTwoUNLESS on behalf of /r/pkmntcgtrades. Uploaded to GitHub with permission.
import praw
import time
import datetime
import sqlite3
'''USER CONFIGURATION'''
APP_ID = ""
APP_SECRET = ""
APP_URI = ""
APP_REFRESH = ""
# https://www.reddit.com/comments/3cm1p8/how_t... |
cur.execute('INSERT INTO oldposts VALUES(?)', [pid])
sql.commit()
while True:
try:
scan()
except Exception as e:
print('An error has occured:', e)
print('Running again in ' + WAITS + ' seconds.\n')
time.sleep(WAIT)
| cur.execute('SELECT * FROM users WHERE name=?', [pauthor])
fetch = cur.fetchone()
print('Found post by known user: ' + pauthor)
previousid = fetch[1]
previous = r.get_info(thing_id='t3_'+previousid)
previoustime = previous.created_utc
if ptime > previoustime:
curtime = getTime(True)
di... | conditional_block |
delaybot.py | #This bot was written by /u/GoldenSights for /u/FourMakesTwoUNLESS on behalf of /r/pkmntcgtrades. Uploaded to GitHub with permission.
import praw
import time
import datetime
import sqlite3
'''USER CONFIGURATION'''
APP_ID = ""
APP_SECRET = ""
APP_URI = ""
APP_REFRESH = ""
# https://www.reddit.com/comments/3cm1p8/how_t... |
def scan():
print('Scanning ' + SUBREDDIT)
subreddit = r.get_subreddit(SUBREDDIT)
posts = subreddit.get_new(limit=MAXPOSTS)
for post in posts:
try:
pauthor = post.author.name
except Exception:
pauthor = '[deleted]'
pid = post.id
plink = post.short_link
ptime = post.created_utc
cur.execute('SELEC... | timeNow = datetime.datetime.now(datetime.timezone.utc)
timeUnix = timeNow.timestamp()
if bool == False:
return timeNow
else:
return timeUnix | identifier_body |
delaybot.py | #This bot was written by /u/GoldenSights for /u/FourMakesTwoUNLESS on behalf of /r/pkmntcgtrades. Uploaded to GitHub with permission.
import praw
import time
import datetime
import sqlite3
'''USER CONFIGURATION'''
APP_ID = ""
APP_SECRET = ""
APP_URI = ""
APP_REFRESH = ""
# https://www.reddit.com/comments/3cm1p8/how_t... | sql.commit()
print('\t' + pauthor + "'s database info has been reset.")
else:
differences = '%.0f' % (DELAY - difference)
timestring = str(datetime.timedelta(seconds=float(differences)))
timestring = timestring.replace(':', ' hours, and ', 1)
timestring = timestring.replace(':',... | cur.execute('INSERT INTO users VALUES(?, ?)', (pauthor, pid)) | random_line_split |
oauth.js | 'use strict';
const app = require('APP')
, debug = require('debug')(`${app.name}:oauth`)
, {STRING, JSON} = require('sequelize');
module.exports = db => {
const OAuth = db.define('oauths', {
uid: STRING,
provider: STRING,
// OAuth v2 fields
accessToken: STRING,
refreshToken: STRING,
... | // 1. Sequelize and indexes: http://docs.sequelizejs.com/en/2.0/docs/models-definition/#indexes
// 2. Postgres documentation: https://www.postgresql.org/docs/9.1/static/indexes.html
indexes: [{fields: ['uid'], unique: true}],
});
// OAuth.V2 is a default argument for the OAuth.setupStrategy method - it... |
// The whole profile as JSON
profileJson: JSON,
}, {
// Further reading on indexes: | random_line_split |
oauth.js | 'use strict';
const app = require('APP')
, debug = require('debug')(`${app.name}:oauth`)
, {STRING, JSON} = require('sequelize');
module.exports = db => {
const OAuth = db.define('oauths', {
uid: STRING,
provider: STRING,
// OAuth v2 fields
accessToken: STRING,
refreshToken: STRING,
... |
debug('initializing provider:%s', provider);
passport.use(new strategy(config, oauth));
};
return OAuth;
};
module.exports.associations = (OAuth, {User}) => {
// Create a static association between the OAuth and User models.
// This lets us refer to OAuth.User above, when we need to create
// a u... | {
for (const key in config) {
if (!config[key]) debug('provider:%s: needs environment var %s', provider, key);
}
debug('provider:%s will not initialize', provider);
return;
} | conditional_block |
positionMessage.js | // function fn_moveElement(elementID,finalX,finalY,interval){
// if (!document.getElementById && !document.getElementById("elementID")) {
// return false;
// }
// var elem=document.getElementById(elementID);
// var xPos=parseInt(elem.style.left);
// var yPos=parseInt(elem.style.top);
// if (xPos===finalX&&yPos=... | // if (yPos<finalY) {
// yPos++;
// }
// if (yPos>finalY) {
// yPos--;
// }
// elem.style.left=xPos+"px";
// elem.style.top=yPos+"px";
// var repeat="moveElement('"+elementID+"',"+finalX+","+finalY+","+interval+")";
// movement=setTimeout(repeat,interval);
// }
//
function fn_positionMessage() {
// body.... | // xPos++;
// }
// if (xPos>finalX) {
// xPos--;
// } | random_line_split |
positionMessage.js | // function fn_moveElement(elementID,finalX,finalY,interval){
// if (!document.getElementById && !document.getElementById("elementID")) {
// return false;
// }
// var elem=document.getElementById(elementID);
// var xPos=parseInt(elem.style.left);
// var yPos=parseInt(elem.style.top);
// if (xPos===finalX&&yPos=... | {
if (!document.getElementById && !document.getElementById("elementID")) {
return false;
}
var elem=document.getElementById(elementID);
var xPos=parseInt(elem.style.left);
var yPos=parseInt(elem.style.top);
if (xPos===finalX&&yPos===finalY) {
return true;
}
if (xPos<finalX) {
xPos++;
}
if (xPos>finalX) ... | identifier_body | |
positionMessage.js | // function fn_moveElement(elementID,finalX,finalY,interval){
// if (!document.getElementById && !document.getElementById("elementID")) {
// return false;
// }
// var elem=document.getElementById(elementID);
// var xPos=parseInt(elem.style.left);
// var yPos=parseInt(elem.style.top);
// if (xPos===finalX&&yPos=... | (elementID,finalX,finalY,interval){
if (!document.getElementById && !document.getElementById("elementID")) {
return false;
}
var elem=document.getElementById(elementID);
var xPos=parseInt(elem.style.left);
var yPos=parseInt(elem.style.top);
if (xPos===finalX&&yPos===finalY) {
return true;
}
if (xPos<finalX)... | moveElement | identifier_name |
positionMessage.js | // function fn_moveElement(elementID,finalX,finalY,interval){
// if (!document.getElementById && !document.getElementById("elementID")) {
// return false;
// }
// var elem=document.getElementById(elementID);
// var xPos=parseInt(elem.style.left);
// var yPos=parseInt(elem.style.top);
// if (xPos===finalX&&yPos=... |
if (yPos<finalY) {
yPos++;
}
if (yPos>finalY) {
yPos--;
}
elem.style.left=xPos+"px";
elem.style.top=yPos+"px";
var repeat="moveElement('"+elementID+"',"+finalX+","+finalY+","+interval+")";
movement=setTimeout(repeat,interval);
} | {
xPos--;
} | conditional_block |
repeat.test.ts | import { repeat, repeatValue, Sequence } from '../src'
describe('repeat', () => {
it('accepts a Collection as argument', () => {
expect(repeat([1, 2, 3])).toBeInstanceOf(Sequence)
expect(repeat({ 0: 1, length: 1 })).toBeInstanceOf(Sequence)
expect(repeat(function* () { yield 1 })).toBeInstanceOf(Sequence... | })
})
describe('repeatValue', () => {
it('creates an Sequence with the value repeated', () => {
const value = repeatValue(1, 5).toArray()
expect(value).toEqual([1, 1, 1, 1, 1])
})
it('will work with a single argument', () => {
const value = repeatValue(1)
expect(value).toBeInstanceOf(Sequence)... | expect(value1).toBeInstanceOf(Sequence)
expect(value2).toBeInstanceOf(Sequence) | random_line_split |
importHelpersWithLocalCollisions(module=amd).js | //// [tests/cases/compiler/importHelpersWithLocalCollisions.ts] ////
//// [a.ts]
declare var dec: any, __decorate: any;
@dec export class | {
}
const o = { a: 1 };
const y = { ...o };
//// [tslib.d.ts]
export declare function __extends(d: Function, b: Function): void;
export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any;
export declare function __param(paramIndex: number, decorator: Function)... | A | identifier_name |
importHelpersWithLocalCollisions(module=amd).js | //// [tests/cases/compiler/importHelpersWithLocalCollisions.ts] ////
//// [a.ts]
declare var dec: any, __decorate: any;
@dec export class A {
}
const o = { a: 1 };
const y = { ...o };
//// [tslib.d.ts]
export declare function __extends(d: Function, b: Function): void;
export declare function __decorate(decorat... | ], A);
exports.A = A;
const o = { a: 1 };
const y = Object.assign({}, o);
}); | let A = class A {
};
A = (0, tslib_1.__decorate)([
dec
| random_line_split |
watch.test.ts | import * as Vue from 'vue'
import { expect } from 'chai'
import * as Utils from './_testutils'
import { Watch } from '../src/watch'
import { VueComponent } from '../src/vuecomponent'
describe('Watch', function(){
@VueComponent
class WatchTest{
watchedOne:string = 'watch one';
@Watch('onWatc... |
onWatchedTwoChange(){
this.twoChanged();
}
oneChanged(){
this.done()
}
twoChanged(){
this.done()
}
}
var component = Utils.component('watch-test');
it('should have property in data', function(){
expect... | {
this.oneChanged();
} | identifier_body |
watch.test.ts | import * as Vue from 'vue'
import { expect } from 'chai'
import * as Utils from './_testutils'
import { Watch } from '../src/watch'
import { VueComponent } from '../src/vuecomponent'
describe('Watch', function(){
@VueComponent
class WatchTest{
watchedOne:string = 'watch one';
@Watch('onWatc... | }
}
var component = Utils.component('watch-test');
it('should have property in data', function(){
expect(component).to.have.property('watchedOne').that.equals('watch one');
});
it('should have options when provided', function(){
expect(component.$options.watch.watchedTwo)... |
twoChanged(){
this.done() | random_line_split |
watch.test.ts | import * as Vue from 'vue'
import { expect } from 'chai'
import * as Utils from './_testutils'
import { Watch } from '../src/watch'
import { VueComponent } from '../src/vuecomponent'
describe('Watch', function(){
@VueComponent
class WatchTest{
watchedOne:string = 'watch one';
@Watch('onWatc... | (){
this.done()
}
twoChanged(){
this.done()
}
}
var component = Utils.component('watch-test');
it('should have property in data', function(){
expect(component).to.have.property('watchedOne').that.equals('watch one');
});
it('should... | oneChanged | identifier_name |
searchUsers.component.ts | import { Component, OnInit } from '@angular/core'
import { APIService } from '../../services/APIService'
import { Title } from '@angular/platform-browser'
import {Router, ActivatedRoute, Params} from '@angular/router'
@Component({
selector: 'app-root',
templateUr... | (user, page) {
/*
Get search results from user with page id
*/
this._apiService.searchUsers(user, page).subscribe(
data => {
this.queryList = this.queryList.concat(data.items)
this.page += 1
},
err => console.error(err),
() => {
console.log("Query data",... | getSearchResults | identifier_name |
searchUsers.component.ts | import { Component, OnInit } from '@angular/core'
import { APIService } from '../../services/APIService'
import { Title } from '@angular/platform-browser'
import {Router, ActivatedRoute, Params} from '@angular/router'
@Component({
selector: 'app-root',
templateUr... |
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
this.user = params['user']
this.titleService.setTitle( this.user + " results - Git App" )
console.log(this.user)
})
/*
Get search results from user with page id
*/
this.getSearchResults(this.user, ... | {
this.titleService.setTitle( "Git App - Search" )
} | identifier_body |
searchUsers.component.ts | import { Component, OnInit } from '@angular/core'
import { APIService } from '../../services/APIService'
import { Title } from '@angular/platform-browser'
import {Router, ActivatedRoute, Params} from '@angular/router'
@Component({
selector: 'app-root',
templateUr... |
goBack() {
window.history.back()
}
} | userDetails(user) {
this.router.navigate(['./user/details/' + encodeURI(user.login)])
} | random_line_split |
DefaultRouteExecutor.ts | /// <reference path="../links.d.ts" />
import {} from "bluebird";
import extend = require("extend");
import superagent = require("superagent");
import {SuperAgentRequest, Request, Response} from "superagent";
import {ErrorRouteExecute} from "../exceptions/ErrorRouteExecute";
import {Route} from "../Route";
import {Ro... |
private toObject(kvp: collections.Dictionary<string, string>): any {
let values = {};
kvp.forEach((key, value) => {
values[key] = value;
});
return values;
}
} | {
for (let header in headers) {
let value: string = headers[header];
if (value) {
if (header.toLowerCase() === "content-type") {
// BUG: Fixes a bug in browsers where the content-type is sent
// twice, i.e. "application/json, application/json".
http.type(value);
... | identifier_body |
DefaultRouteExecutor.ts | /// <reference path="../links.d.ts" />
import {} from "bluebird";
import extend = require("extend");
import superagent = require("superagent");
import {SuperAgentRequest, Request, Response} from "superagent";
import {ErrorRouteExecute} from "../exceptions/ErrorRouteExecute";
import {Route} from "../Route";
import {Ro... | implements RouteExecutor {
private _route: Route;
public constructor(route: Route) {
}
public get route(): Route {
return this._route;
}
public execute();
public execute(request?: Object, values?: RouteParamValues): Promise<Response> {
if (request && this.route.method === RouteMethod.Get) {
... | DefaultRouteExecutor | identifier_name |
DefaultRouteExecutor.ts | /// <reference path="../links.d.ts" />
import {} from "bluebird";
import extend = require("extend");
import superagent = require("superagent");
import {SuperAgentRequest, Request, Response} from "superagent";
import {ErrorRouteExecute} from "../exceptions/ErrorRouteExecute";
import {Route} from "../Route";
import {Ro... | values[key] = value;
});
return values;
}
} | kvp.forEach((key, value) => { | random_line_split |
DefaultRouteExecutor.ts | /// <reference path="../links.d.ts" />
import {} from "bluebird";
import extend = require("extend");
import superagent = require("superagent");
import {SuperAgentRequest, Request, Response} from "superagent";
import {ErrorRouteExecute} from "../exceptions/ErrorRouteExecute";
import {Route} from "../Route";
import {Ro... |
}
}
private toObject(kvp: collections.Dictionary<string, string>): any {
let values = {};
kvp.forEach((key, value) => {
values[key] = value;
});
return values;
}
} | {
if (header.toLowerCase() === "content-type") {
// BUG: Fixes a bug in browsers where the content-type is sent
// twice, i.e. "application/json, application/json".
http.type(value);
} else {
http.set(header, value);
}
} | conditional_block |
env.rs | use std::cell::RefCell;
use analysis;
use config::Config;
use config::gobjects::GStatus;
use library::*;
use version::Version;
pub struct | {
pub library: Library,
pub config: Config,
pub namespaces: analysis::namespaces::Info,
pub symbols: RefCell<analysis::symbols::Info>,
pub class_hierarchy: analysis::class_hierarchy::Info,
}
impl Env {
#[inline]
pub fn type_(&self, tid: TypeId) -> &Type {
self.library.type_(tid)
... | Env | identifier_name |
env.rs | use std::cell::RefCell;
use analysis;
use config::Config;
use config::gobjects::GStatus; | pub library: Library,
pub config: Config,
pub namespaces: analysis::namespaces::Info,
pub symbols: RefCell<analysis::symbols::Info>,
pub class_hierarchy: analysis::class_hierarchy::Info,
}
impl Env {
#[inline]
pub fn type_(&self, tid: TypeId) -> &Type {
self.library.type_(tid)
}... | use library::*;
use version::Version;
pub struct Env { | random_line_split |
env.rs | use std::cell::RefCell;
use analysis;
use config::Config;
use config::gobjects::GStatus;
use library::*;
use version::Version;
pub struct Env {
pub library: Library,
pub config: Config,
pub namespaces: analysis::namespaces::Info,
pub symbols: RefCell<analysis::symbols::Info>,
pub class_hierarchy: ... |
pub fn type_status_sys(&self, name: &str) -> GStatus {
self.config.objects.get(name).map(|o| o.status)
.unwrap_or(GStatus::Generate)
}
pub fn is_totally_deprecated(&self, deprecated_version: Option<Version>) -> bool {
match deprecated_version {
Some(version) if vers... | {
self.config.objects.get(name).map(|o| o.status)
.unwrap_or(Default::default())
} | identifier_body |
accordion.d.ts | import { QueryList, TemplateRef, EventEmitter, AfterContentChecked } from '@angular/core';
import { NgbAccordionConfig } from './accordion-config';
/**
* This directive should be used to wrap accordion panel titles that need to contain HTML markup or other directives.
*/
export declare class NgbPanelTitle {
templ... | {
/**
* A flag determining whether the panel is disabled or not.
* When disabled, the panel cannot be toggled.
*/
disabled: boolean;
/**
* An optional id for the panel. The id should be unique.
* If not provided, it will be auto-generated.
*/
id: string;
/**
*... | NgbPanel | identifier_name |
accordion.d.ts | import { QueryList, TemplateRef, EventEmitter, AfterContentChecked } from '@angular/core';
import { NgbAccordionConfig } from './accordion-config';
/**
* This directive should be used to wrap accordion panel titles that need to contain HTML markup or other directives.
*/
export declare class NgbPanelTitle {
templ... | */
id: string;
/**
* The title for the panel.
*/
title: string;
/**
* Panel type (CSS class). Bootstrap 4 recognizes the following types: "success", "info", "warning" and "danger".
*/
type: string;
contentTpl: NgbPanelContent;
titleTpl: NgbPanelTitle;
}
/**
* The ... | disabled: boolean;
/**
* An optional id for the panel. The id should be unique.
* If not provided, it will be auto-generated. | random_line_split |
AppleAuthentication.types.ts | import { StyleProp, ViewStyle } from 'react-native';
export type AppleAuthenticationButtonProps = {
onPress: () => void;
buttonType: AppleAuthenticationButtonType;
buttonStyle: AppleAuthenticationButtonStyle;
cornerRadius?: number;
style?: StyleProp<ViewStyle>;
};
/**
* The options you can supply when maki... |
/**
* An arbitrary string that your app provided as `state` in the request that generated the
* credential. Used to verify that the response was from the request you made. Can be used to
* avoid replay attacks.
*/
state: string | null;
/**
* The user's name. May be `null` or contain `null` values... | * development team. The same user will have a different identifier for apps released by other
* developers.
*/
user: string; | random_line_split |
templateLiteralTypes3.ts | // @strict: true
// @declaration: true
// Inference from template literal type to template literal type
type Foo1<T> = T extends `*${infer U}*` ? U : never;
type T01 = Foo1<'hello'>;
type T02 = Foo1<'*hello*'>;
type T03 = Foo1<'**hello**'>;
type T04 = Foo1<`*${string}*`>;
type T05 = Foo1<`*${number}*`>;
... | let x: `*${string}*`;
x = 'hello'; // Error
x = '*hello*';
x = '**hello**';
x = `*${s}*` as const;
x = `*${n}*` as const;
x = `*${b}*` as const;
x = `*${t}*` as const;
x = `**${s}**` as const;
}
function f4<T extends number>(s: string, n: number, b: boolean, t: T) {
... | random_line_split | |
templateLiteralTypes3.ts | // @strict: true
// @declaration: true
// Inference from template literal type to template literal type
type Foo1<T> = T extends `*${infer U}*` ? U : never;
type T01 = Foo1<'hello'>;
type T02 = Foo1<'*hello*'>;
type T03 = Foo1<'**hello**'>;
type T04 = Foo1<`*${string}*`>;
type T05 = Foo1<`*${number}*`>;
... |
if (x === z) { // Error
}
}
function ff2<T extends string>(x: `foo-${T}`, y: `${T}-bar`, z: `baz-${T}`) {
if (x === y) {
x; // `foo-${T}`
}
if (x === z) { // Error
}
}
function ff3(x: string, y: `foo-${string}` | 'bar') {
if (x === y) {
x; // `foo-${stri... | {
x; // `foo-${string}`
} | conditional_block |
templateLiteralTypes3.ts | // @strict: true
// @declaration: true
// Inference from template literal type to template literal type
type Foo1<T> = T extends `*${infer U}*` ? U : never;
type T01 = Foo1<'hello'>;
type T02 = Foo1<'*hello*'>;
type T03 = Foo1<'**hello**'>;
type T04 = Foo1<`*${string}*`>;
type T05 = Foo1<`*${number}*`>;
... | (action: Action) {
if (action.type === 'FOO_SUCCESS') {
action.type;
action.response;
}
}
// Repro from #46768
type DotString = `${string}.${string}.${string}`;
declare function noSpread<P extends DotString>(args: P[]): P;
declare function spread<P extends DotString>(...args: P[])... | reducer | identifier_name |
templateLiteralTypes3.ts | // @strict: true
// @declaration: true
// Inference from template literal type to template literal type
type Foo1<T> = T extends `*${infer U}*` ? U : never;
type T01 = Foo1<'hello'>;
type T02 = Foo1<'*hello*'>;
type T03 = Foo1<'**hello**'>;
type T04 = Foo1<`*${string}*`>;
type T05 = Foo1<`*${number}*`>;
... |
// Repro from #43060
type A<T> = T extends `${infer U}.${infer V}` ? U | V : never
type B = A<`test.1024`>; // "test" | "1024"
type C = A<`test.${number}`>; // "test" | `${number}`
type D<T> = T extends `${infer U}.${number}` ? U : never
type E = D<`test.1024`>; // "test"
type F = D<`test.${number}`>; ... | {
let x: `*${number}*`;
x = '123'; // Error
x = '*123*';
x = '**123**'; // Error
x = `*${s}*` as const; // Error
x = `*${n}*` as const;
x = `*${b}*` as const; // Error
x = `*${t}*` as const;
} | identifier_body |
conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CherryMusic documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 1 23:32:37 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# ... | # If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'CherryMusic', 'CherryMusi... | random_line_split | |
espree.js | /**
* @fileoverview Main Espree file that converts Acorn into Esprima output.
*
* This file contains code from the following MIT-licensed projects:
* 1. Acorn
* 2. Babylon
* 3. Babel-ESLint
*
* This file also contains code from Esprima, which is BSD licensed.
*
* Acorn is Copyright 2012-2015 Acorn Contributor... | ,
get(options) {
const useJsx = Boolean(
options &&
options.ecmaFeatures &&
options.ecmaFeatures.jsx
);
return useJsx ? this.jsx : this.regular;
}
};
//------------------------------------------------------------------------------
// Tokenizer
//---... | {
if (this._jsx === null) {
this._jsx = acorn.Parser.extend(jsx(), espree());
}
return this._jsx;
} | identifier_body |
espree.js | /**
* @fileoverview Main Espree file that converts Acorn into Esprima output.
*
* This file contains code from the following MIT-licensed projects:
* 1. Acorn
* 2. Babylon
* 3. Babel-ESLint
*
* This file also contains code from Esprima, which is BSD licensed.
*
* Acorn is Copyright 2012-2015 Acorn Contributor... | (code, options) {
const Parser = parsers.get(options);
return new Parser(options, code).parse();
}
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
export const version = espreeVersion;
... | parse | identifier_name |
espree.js | /**
* @fileoverview Main Espree file that converts Acorn into Esprima output.
*
* This file contains code from the following MIT-licensed projects:
* 1. Acorn
* 2. Babylon
* 3. Babel-ESLint
*
* This file also contains code from Esprima, which is BSD licensed.
*
* Acorn is Copyright 2012-2015 Acorn Contributor... | options.ecmaFeatures &&
options.ecmaFeatures.jsx
);
return useJsx ? this.jsx : this.regular;
}
};
//------------------------------------------------------------------------------
// Tokenizer
//------------------------------------------------------------------------------
... | get(options) {
const useJsx = Boolean(
options && | random_line_split |
espree.js | /**
* @fileoverview Main Espree file that converts Acorn into Esprima output.
*
* This file contains code from the following MIT-licensed projects:
* 1. Acorn
* 2. Babylon
* 3. Babel-ESLint
*
* This file also contains code from Esprima, which is BSD licensed.
*
* Acorn is Copyright 2012-2015 Acorn Contributor... |
return types;
}());
export const latestEcmaVersion = getLatestEcmaVersion();
export const supportedEcmaVersions = getSupportedEcmaVersions();
| {
Object.freeze(types);
} | conditional_block |
order_material_form.py | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#########################################################################... |
_form_model = "crm.lead"
_form_model_fields = ["partner_id", "description"]
_form_required_fields = ["flyer_german", "flyer_french"]
partner_id = fields.Many2one("res.partner", readonly=False)
event_id = fields.Many2one("crm.event.compassion", readonly=False)
form_id = fields.Char()
flyer... | class OrderMaterialForm(models.AbstractModel):
_name = "cms.form.order.material.mixin"
_inherit = "cms.form" | random_line_split |
order_material_form.py | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#########################################################################... |
@property
def form_widgets(self):
# Hide fields
res = super(OrderMaterialForm, self).form_widgets
res.update(
{
"form_id": "cms_form_compassion.form.widget.hidden",
"partner_id": "cms_form_compassion.form.widget.hidden",
"even... | return _(
"Thank you for your request. You will hear back from us "
"within the next days."
) | identifier_body |
order_material_form.py | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#########################################################################... | (self, fname, field, value, **req_values):
"""Invalidate the form if they order 0 flyers"""
is_valid = super().form_check_empty_value(fname, field, value, **req_values)
is_valid |= int(req_values["flyer_french"]) + int(req_values["flyer_german"]) <= 0
return is_valid
def _form_creat... | form_check_empty_value | identifier_name |
order_material_form.py | ##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#########################################################################... |
description = f"<ul>{''.join(lines)}</ul>"
return description
def form_init(self, request, main_object=None, **kw):
form = super(OrderMaterialForm, self).form_init(request, main_object, **kw)
# Set default values
registration = kw.get("registration")
form.partner_id... | lines.append(f"<li>{values[f'flyer_{lang}']} <b>{material}</b> in {lang}</li>") | conditional_block |
admin.py | # Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This ... | @post('/delete_role')
def delete_role():
try:
shared_state.auth.delete_role(post_get('role'))
return dict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.message)
def postd():
return bottle.request.forms
def post_get(name, default=''):
return bottle.request.... | return dict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.message)
| random_line_split |
admin.py | # Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This ... |
@route('/admin')
@view('admin_page')
def admin():
"""Only admin users can see this"""
shared_state.auth.require(role='admin', fail_redirect='/unauth')
return dict(
current_user=shared_state.auth.current_user,
users=shared_state.auth.list_users(),
roles=shared_state.auth.list_roles... | shared_state.auth.logout(success_redirect='/unauth') | identifier_body |
admin.py | # Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This ... |
@route('/logout')
def logout():
shared_state.auth.logout(success_redirect='/unauth')
@route('/admin')
@view('admin_page')
def admin():
"""Only admin users can see this"""
shared_state.auth.require(role='admin', fail_redirect='/unauth')
return dict(
current_user=shared_state.auth.current_use... | return HTTPError(401, 'Invalid credentials') | conditional_block |
admin.py | # Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This ... | ():
try:
shared_state.auth.delete_role(post_get('role'))
return dict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.message)
def postd():
return bottle.request.forms
def post_get(name, default=''):
return bottle.request.POST.get(name, default).strip() | delete_role | identifier_name |
Outline.py | # coding=utf8
import sublime
from .Base import Base
from ...utils import Debug
from ...utils.uiutils import get_prefix
class Outline(Base):
regions = {}
ts_view = None
def __init__(self, t3sviews):
super(Outline, self).__init__('Typescript : Outline View', t3sviews)
# SET TEXT | """
This function takes the tss.js members structure instead of a string.
"""
# this will process the outline, even if the view is closed
self.ts_view = ts_view
if type(members) == list:
self._tssjs_2_outline_format(members)
elif type(members) == s... | def set_text(self, edit_token, members, ts_view): | random_line_split |
Outline.py | # coding=utf8
import sublime
from .Base import Base
from ...utils import Debug
from ...utils.uiutils import get_prefix
class Outline(Base):
regions = {}
ts_view = None
def __init__(self, t3sviews):
super(Outline, self).__init__('Typescript : Outline View', t3sviews)
# SET TEXT
def set_... |
def _tssjs_2_outline_format(self, members):
text = []
line = 0
self.regions = {}
for member in members:
start_line = member['min']['line']
end_line = member['lim']['line']
left = member['min']['character']
right = member['lim']['char... | if ts_view is None or self.ts_view is None:
return
return ts_view.id() == self.ts_view.id() | identifier_body |
Outline.py | # coding=utf8
import sublime
from .Base import Base
from ...utils import Debug
from ...utils.uiutils import get_prefix
class Outline(Base):
regions = {}
ts_view = None
def __init__(self, t3sviews):
super(Outline, self).__init__('Typescript : Outline View', t3sviews)
# SET TEXT
def set_... |
if line in self.regions:
draw = sublime.DRAW_NO_FILL
self.ts_view.add_regions('typescript-definition', [self.regions[line]], 'comment', 'dot', draw)
self._focus_member_in_view(self.regions[line])
def _focus_member_in_view(self, region):
if self.ts_view.is_loadin... | Debug('focus', 'Outline.on_click: is just focusing other view > ignore')
return | conditional_block |
Outline.py | # coding=utf8
import sublime
from .Base import Base
from ...utils import Debug
from ...utils.uiutils import get_prefix
class | (Base):
regions = {}
ts_view = None
def __init__(self, t3sviews):
super(Outline, self).__init__('Typescript : Outline View', t3sviews)
# SET TEXT
def set_text(self, edit_token, members, ts_view):
"""
This function takes the tss.js members structure instead of a string... | Outline | identifier_name |
index.ts | function easeInOutQuad(t: number) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
}
const TIMEOUT_MIN = 50
const TIMEOUT_DEFAULT = 100
const DURATION_DEFAULT = 300
const THRESHOLD_DEFAULT = 0.2
const SNAPSTOP_DEFAULT = false
const EASING_DEFAULT = easeInOutQuad
const NOOP = () => {}
interface Settings {
/**
... |
const duration = settings.duration || DURATION_DEFAULT
if (
settings.threshold &&
(isNaN(settings.threshold) || typeof settings.threshold === 'boolean')
) {
throw new Error(
`Optional settings property 'threshold' is not valid, expected NUMBER but found ${(typeof settings.threshold).toUpperCas... | {
throw new Error(
`Optional settings property 'duration' is not valid, expected NUMBER but found ${(typeof settings.duration).toUpperCase()}`
)
} | conditional_block |
index.ts | function easeInOutQuad(t: number) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
}
const TIMEOUT_MIN = 50
const TIMEOUT_DEFAULT = 100
const DURATION_DEFAULT = 300
const THRESHOLD_DEFAULT = 0.2
const SNAPSTOP_DEFAULT = false
const EASING_DEFAULT = easeInOutQuad
const NOOP = () => {}
interface Settings {
/**
... | () {
speedDeltaX = checkScrollSpeed(target.scrollLeft, 'x')
speedDeltaY = checkScrollSpeed(target.scrollTop, 'y')
if (animating || (speedDeltaX === 0 && speedDeltaY === 0)) {
return
}
handler(target)
}
/**
* scroll handler
* this is the callback for scroll events.
*/
function... | startAnimation | identifier_name |
index.ts | function easeInOutQuad(t: number) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
}
const TIMEOUT_MIN = 50
const TIMEOUT_DEFAULT = 100
const DURATION_DEFAULT = 300
const THRESHOLD_DEFAULT = 0.2
const SNAPSTOP_DEFAULT = false
const EASING_DEFAULT = easeInOutQuad
const NOOP = () => {}
interface Settings {
/**
... | element: HTMLElement,
settings: Settings = {},
callback?: () => void
) {
const onAnimationEnd = typeof callback === 'function' ? callback : NOOP
let listenerElement: HTMLElement | Window
let target: HTMLElement
let animating = false
let scrollHandlerTimer: number
let scrollSpeedTimer: number
let s... | }
export default function createScrollSnap( | random_line_split |
index.ts | function easeInOutQuad(t: number) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
}
const TIMEOUT_MIN = 50
const TIMEOUT_DEFAULT = 100
const DURATION_DEFAULT = 300
const THRESHOLD_DEFAULT = 0.2
const SNAPSTOP_DEFAULT = false
const EASING_DEFAULT = easeInOutQuad
const NOOP = () => {}
interface Settings {
/**
... |
function getNextSnapPoint(target: HTMLElement, direction: Coordinates) {
// get snap length
const snapLength = {
y: Math.round(getYSnapLength(target, snapLengthUnit.y)),
x: Math.round(getXSnapLength(target, snapLengthUnit.x)),
}
const top = target.scrollTop
const left = target.scroll... | {
// if we don't move a thing, we can ignore the timeout: if we did, there'd be another timeout added for scrollStart+1.
if (scrollStart.y === target.scrollTop && scrollStart.x === target.scrollLeft) {
// ignore timeout
return
}
// detect direction of scroll. negative is up, positive is dow... | identifier_body |
untitledEditorModel.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): void {
super.dispose();
if (this.textModelChangeListener) {
this.textModelChangeListener();
this.textModelChangeListener = null;
}
if (this.configurationChangeListener) {
this.configurationChangeListener.dispose();
this.configurationChangeListener = null;
}
this.eventService.emit(Workbenc... | dispose | identifier_name |
untitledEditorModel.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
public isDirty(): boolean {
return this.dirty;
}
public load(): TPromise<EditorModel> {
return super.load().then((model) => {
const configuration = this.configurationService.getConfiguration<IFilesConfiguration>();
// Encoding
this.configuredEncoding = configuration && configuration.files && conf... | {
this.eventService.emit(WorkbenchEventType.RESOURCE_ENCODING_CHANGED, new ResourceEvent(this.resource));
} | conditional_block |
untitledEditorModel.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
} | random_line_split | |
untitledEditorModel.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public getValue(): string {
if (this.textEditorModel) {
return this.textEditorModel.getValue(EndOfLinePreference.TextDefined, true /* Preserve BOM */);
}
return null;
}
public getModeId(): string {
if (this.textEditorModel) {
return this.textEditorModel.getModeId();
}
return null;
}
public ... | {
this.configuredEncoding = configuration && configuration.files && configuration.files.encoding;
} | identifier_body |
vulcanup.js | /**
* jQuery object.
* @external jQuery
* @see {@link http://api.jquery.com/jQuery/}
*/
/**
* The jQuery plugin namespace.
* @external "jQuery.fn"
* @see {@link http://docs.jquery.com/Plugins/Authoring The jQuery Plugin Guide}
*/
/**
* The plugin global configuration object.
* @external "jQuery.vulcanup"
*... | return false;
});
//
// CREATING AND SETTING
//
$input.fileupload(conf.fileupload);
if (conf.url) {
methods.setUploaded.call(this, {
url: conf.url,
name: conf.name,
initial: true
});
} else {
methods.setUpload.call(this);
}
return this;
};
module.exports = jQuer... | random_line_split | |
vulcanup.js | /**
* jQuery object.
* @external jQuery
* @see {@link http://api.jquery.com/jQuery/}
*/
/**
* The jQuery plugin namespace.
* @external "jQuery.fn"
* @see {@link http://docs.jquery.com/Plugins/Authoring The jQuery Plugin Guide}
*/
/**
* The plugin global configuration object.
* @external "jQuery.vulcanup"
*... |
if (conf.canRemove) {
$container.addClass('vulcanup_canremove');
}
//
// EVENTS
//
$input.
// On click.
on('click', function (e) {
if (conf._uploading || (conf._url && !conf.enableReupload)) {
e.preventDefault();
return false;
}
}).
// On user error.
o... | {
$container.addClass('vulcanup_noreupload');
} | conditional_block |
copy.js | 'use strict';
var commentLineExp = /^[\s]*<!-- (\/|#) (CE|EE)/;
var requireConfExp = /require-conf.js$/;
module.exports = function(config, copyConf) {
var grunt = config.grunt;
var path = require('path');
var now = (new Date()).getTime();
var version = grunt.file.readJSON(path.resolve(__dirname, '../../../... | (content, srcpath) {
if (srcpath.slice(-4) !== 'html') { return content; }
return content.split('$GRUNT_CACHE_BUST').join(prod() ? version : now);
}
function fileProcessing(content, srcpath) {
if(prod()) {
// removes the template comments
content = content
.split('\n').filte... | cacheBust | identifier_name |
copy.js | 'use strict';
var commentLineExp = /^[\s]*<!-- (\/|#) (CE|EE)/;
var requireConfExp = /require-conf.js$/;
module.exports = function(config, copyConf) {
var grunt = config.grunt;
var path = require('path');
var now = (new Date()).getTime();
var version = grunt.file.readJSON(path.resolve(__dirname, '../../../... | function prod () {
return grunt.config('buildMode') === 'prod';
}
function cacheBust(content, srcpath) {
if (srcpath.slice(-4) !== 'html') { return content; }
return content.split('$GRUNT_CACHE_BUST').join(prod() ? version : now);
}
function fileProcessing(content, srcpath) {
if(prod()) {
... | random_line_split | |
copy.js | 'use strict';
var commentLineExp = /^[\s]*<!-- (\/|#) (CE|EE)/;
var requireConfExp = /require-conf.js$/;
module.exports = function(config, copyConf) {
var grunt = config.grunt;
var path = require('path');
var now = (new Date()).getTime();
var version = grunt.file.readJSON(path.resolve(__dirname, '../../../... |
copyConf.cockpit_index = {
options: {
process: fileProcessing
},
files: [
{
expand: true,
cwd: '<%= pkg.gruntConfig.cockpitSourceDir %>/scripts/',
src: [
'index.html',
'camunda-cockpit-bootstrap.js'
],
dest: ... | {
if(prod()) {
// removes the template comments
content = content
.split('\n').filter(function(line) {
return !commentLineExp.test(line);
}).join('\n');
}
content = cacheBust(content, srcpath);
return content;
} | identifier_body |
copy.js | 'use strict';
var commentLineExp = /^[\s]*<!-- (\/|#) (CE|EE)/;
var requireConfExp = /require-conf.js$/;
module.exports = function(config, copyConf) {
var grunt = config.grunt;
var path = require('path');
var now = (new Date()).getTime();
var version = grunt.file.readJSON(path.resolve(__dirname, '../../../... |
content = cacheBust(content, srcpath);
return content;
}
copyConf.cockpit_index = {
options: {
process: fileProcessing
},
files: [
{
expand: true,
cwd: '<%= pkg.gruntConfig.cockpitSourceDir %>/scripts/',
src: [
'index.html',
... | {
// removes the template comments
content = content
.split('\n').filter(function(line) {
return !commentLineExp.test(line);
}).join('\n');
} | conditional_block |
message_icon.ts | /**
* This file is part of Threema Web.
*
* Threema Web is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* This program... |
return 'ic_insert_drive_file_24px.svg';
case 'ballot':
return 'ic_poll_24px.svg';
default:
return null;
}
};
this.icon = getIcon(this.m... | {
return 'ic_image_24px.svg';
} | conditional_block |
message_icon.ts | /**
* This file is part of Threema Web.
*
* Threema Web is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
*/
export default [
function() {
retu... | * the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
includes_dotfiles.test.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import path from 'path';
import HasteMap from '../index';
const rootDir = path.join(__dirname, './test_dotfi... | }); | random_line_split | |
hamming_numbers_alt.rs | // Implements http://rosettacode.org/wiki/Hamming_numbers
// alternate version: uses a more efficient representation of Hamming numbers:
// instead of storing them as BigUint directly, it stores the three exponents
// i, j and k for 2^i * 3^j * 5 ^k and the logarithm of the number for comparisons
#![allow(unused_attri... | (&self) -> HammingTriple { *self }
}
impl PartialEq for HammingTriple {
fn eq(&self, other: &HammingTriple) -> bool {
self.pow_2 == other.pow_2 &&
self.pow_3 == other.pow_3 &&
self.pow_5 == other.pow_5
}
}
impl Eq for HammingTriple {}
impl PartialOrd for HammingTriple {
fn partial... | clone | identifier_name |
hamming_numbers_alt.rs | // Implements http://rosettacode.org/wiki/Hamming_numbers
// alternate version: uses a more efficient representation of Hamming numbers:
// instead of storing them as BigUint directly, it stores the three exponents
// i, j and k for 2^i * 3^j * 5 ^k and the logarithm of the number for comparisons
#![allow(unused_attri... |
}
impl HammingTriple {
fn new(pow_2: usize, pow_3: usize, pow_5: usize) -> HammingTriple {
HammingTriple {
pow_2: pow_2,
pow_3: pow_3,
pow_5: pow_5,
ln: (pow_2 as f64) * LN_2 + (pow_3 as f64) * LN_3 + (pow_5 as f64) * LN_5
}
}
}
impl Clone for H... | {
Some(pow(2u8.to_biguint().unwrap(), self.pow_2) *
pow(3u8.to_biguint().unwrap(), self.pow_3) *
pow(5u8.to_biguint().unwrap(), self.pow_5))
} | identifier_body |
hamming_numbers_alt.rs | // Implements http://rosettacode.org/wiki/Hamming_numbers
// alternate version: uses a more efficient representation of Hamming numbers:
// instead of storing them as BigUint directly, it stores the three exponents
// i, j and k for 2^i * 3^j * 5 ^k and the logarithm of the number for comparisons
#![allow(unused_attri... | }
}
impl One for HammingTriple {
// 1 as an HammingNumber is 2^0 * 3^0 * 5^0
// ln(1) = 0
fn one() -> HammingTriple {
HammingTriple::new(0, 0, 0)
}
}
impl HammingNumber for HammingTriple {
fn multipliers() -> (HammingTriple, HammingTriple, HammingTriple) {
(HammingTriple { pow_... | pow_3: self.pow_3 + other.pow_3,
pow_5: self.pow_5 + other.pow_5,
ln: self.ln + other.ln } | random_line_split |
app-insights.ts | import * as appInsights from 'applicationinsights'
import { PingService } from '../services/ping.service'
import config from '../config'
import * as parser from './parsing'
const pingService = new PingService()
const appInsightsHelper = {
startInsightsIfConfigured: async () => {
if (parser.propertyExists(proces... | }
appInsights.defaultClient.commonProperties = {
buildNumber
}
appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.cloudRole] = 'Pupil-Auth-Api'
appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.cloudRoleInstance] = config.Loggi... | random_line_split | |
app-insights.ts | import * as appInsights from 'applicationinsights'
import { PingService } from '../services/ping.service'
import config from '../config'
import * as parser from './parsing'
const pingService = new PingService()
const appInsightsHelper = {
startInsightsIfConfigured: async () => {
if (parser.propertyExists(proces... |
}
}
export = appInsightsHelper
| {
appInsights.setup()
.setAutoDependencyCorrelation(true)
.setAutoCollectRequests(true)
.setAutoCollectPerformance(true)
.setAutoCollectExceptions(config.Logging.ApplicationInsights.CollectExceptions)
.setAutoCollectDependencies(true)
.setAutoCollectConsole(false)
... | conditional_block |
filter_bar.py | # Created By: Virgil Dupras
# Created On: 2009-11-27
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | (FilterBar):
BUTTONS = [
(tr("All"), None),
(tr("Income"), FilterType.Income),
(tr("Expenses"), FilterType.Expense),
(tr("Transfers"), FilterType.Transfer),
(tr("Unassigned"), FilterType.Unassigned),
(tr("Reconciled"), FilterType.Reconciled),
(tr("Not Reconcil... | TransactionFilterBar | identifier_name |
filter_bar.py | # Created By: Virgil Dupras
# Created On: 2009-11-27
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | (tr("Income"), FilterType.Income),
(tr("Expenses"), FilterType.Expense),
(tr("Transfers"), FilterType.Transfer),
(tr("Unassigned"), FilterType.Unassigned),
(tr("Reconciled"), FilterType.Reconciled),
(tr("Not Reconciled"), FilterType.NotReconciled),
] | BUTTONS = [
(tr("All"), None), | random_line_split |
filter_bar.py | # Created By: Virgil Dupras
# Created On: 2009-11-27
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | BUTTONS = [
(tr("All"), None),
(tr("Income"), FilterType.Income),
(tr("Expenses"), FilterType.Expense),
(tr("Transfers"), FilterType.Transfer),
(tr("Unassigned"), FilterType.Unassigned),
(tr("Reconciled"), FilterType.Reconciled),
(tr("Not Reconciled"), FilterType.... | identifier_body | |
unboxed-closures-wrong-trait.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let z: int = 7;
assert_eq!(c(|&mut: x: int, y| x + y + z), 10);
//~^ ERROR not implemented
}
| main | identifier_name |
unboxed-closures-wrong-trait.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(lang_items, overloaded_calls, unboxed_closures)]
fn c<F:Fn(int, int) -> int>(f: F) -> int {
f(5, 6)
}
fn main() {
let z: int = 7;
assert_eq!(c(|&mut: x: int, y| x + y + z), 10);
//~^ ERROR ... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
unboxed-closures-wrong-trait.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let z: int = 7;
assert_eq!(c(|&mut: x: int, y| x + y + z), 10);
//~^ ERROR not implemented
}
| {
f(5, 6)
} | identifier_body |
bench_acquire.rs | //! Benchmark the overhead that the synchronization of `OnceCell::get` causes.
//! We do some other operations that write to memory to get an imprecise but somewhat realistic
//! measurement.
use once_cell::sync::OnceCell;
use std::sync::atomic::{AtomicUsize, Ordering};
const N_THREADS: usize = 16;
const N_ROUNDS: us... | *j = (*j).wrapping_add(accum);
accum = accum.wrapping_add(k);
}
}
} | for j in data.iter_mut() { | random_line_split |
bench_acquire.rs | //! Benchmark the overhead that the synchronization of `OnceCell::get` causes.
//! We do some other operations that write to memory to get an imprecise but somewhat realistic
//! measurement.
use once_cell::sync::OnceCell;
use std::sync::atomic::{AtomicUsize, Ordering};
const N_THREADS: usize = 16;
const N_ROUNDS: us... | {
// The operations we do here don't really matter, as long as we do multiple writes, and
// everything is messy enough to prevent the compiler from optimizing the loop away.
let mut data = [i; 128];
let mut accum = 0usize;
for _ in 0..N_ROUNDS {
let _value = CELL.get_or_init(|| i + 1);
... | identifier_body | |
bench_acquire.rs | //! Benchmark the overhead that the synchronization of `OnceCell::get` causes.
//! We do some other operations that write to memory to get an imprecise but somewhat realistic
//! measurement.
use once_cell::sync::OnceCell;
use std::sync::atomic::{AtomicUsize, Ordering};
const N_THREADS: usize = 16;
const N_ROUNDS: us... | (i: usize) {
// The operations we do here don't really matter, as long as we do multiple writes, and
// everything is messy enough to prevent the compiler from optimizing the loop away.
let mut data = [i; 128];
let mut accum = 0usize;
for _ in 0..N_ROUNDS {
let _value = CELL.get_or_init(|| i... | thread_main | identifier_name |
workflow.gift.card.e2e.spec.js | describe('GiftCard Purchase Workflow', function () {
'use strict';
function | (urlRegex) {
var currentUrl;
return browser.getCurrentUrl().then(function storeCurrentUrl (url) {
currentUrl = url;
}
).then(function waitForUrlToChangeTo () {
return browser.wait(function waitForUrlToChangeTo () {
return browser.getCurrentUrl().then(function compareCurrentUrl ... | waitForUrlToChangeTo | identifier_name |
workflow.gift.card.e2e.spec.js | describe('GiftCard Purchase Workflow', function () {
'use strict';
function waitForUrlToChangeTo (urlRegex) {
var currentUrl;
return browser.getCurrentUrl().then(function storeCurrentUrl (url) {
currentUrl = url;
}
).then(function waitForUrlToChangeTo () {
return browser.wait(function... | }
);
}
it('should load first screen', function () {
browser.get('#/cadeau/vinibar/formule?test=true');
expect(browser.getTitle()).toEqual('Cadeau | vinibar');
});
it('should choose gift_card and add some credit', function () {
element(by.css('#init-card')).click();
element(by.model('g... | });
}); | random_line_split |
workflow.gift.card.e2e.spec.js | describe('GiftCard Purchase Workflow', function () {
'use strict';
function waitForUrlToChangeTo (urlRegex) |
it('should load first screen', function () {
browser.get('#/cadeau/vinibar/formule?test=true');
expect(browser.getTitle()).toEqual('Cadeau | vinibar');
});
it('should choose gift_card and add some credit', function () {
element(by.css('#init-card')).click();
element(by.model('gift.order.credits'... | {
var currentUrl;
return browser.getCurrentUrl().then(function storeCurrentUrl (url) {
currentUrl = url;
}
).then(function waitForUrlToChangeTo () {
return browser.wait(function waitForUrlToChangeTo () {
return browser.getCurrentUrl().then(function compareCurrentUrl (url) {
... | identifier_body |
table-attribute-suggestions.component.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either ... | OnDestroy,
OnInit,
SimpleChanges,
ViewChild,
} from '@angular/core';
import {select, Store} from '@ngrx/store';
import {BehaviorSubject, combineLatest, Observable} from 'rxjs';
import {filter, first, map, switchMap, take, tap} from 'rxjs/operators';
import {AppState} from '../../../../../../../core/store/app.st... | ElementRef,
Input,
OnChanges, | random_line_split |
table-attribute-suggestions.component.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either ... |
public bindAllAttributes(): Observable<LinkedAttribute[]> {
return combineLatest([this.store$.pipe(select(selectAllCollections)), this.lastName$]).pipe(
map(([collections, lastName]) =>
collections.reduce<LinkedAttribute[]>((filtered, collection) => {
if (filtered.length >= MAX_SUGGESTIO... | {
return combineLatest([this.collection$, this.lastName$]).pipe(
filter(([collection]) => !!collection),
switchMap(([collection, lastName]) =>
combineLatest([
this.store$.select(selectLinkTypesByCollectionId(collection.id)),
this.store$.select(selectCollectionsDictionary),
... | identifier_body |
table-attribute-suggestions.component.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either ... | () {
if (this.dropdown) {
this.dropdown.close();
}
}
public createAttribute() {
const attribute: Attribute = {
name: this.attributeName,
};
this.renameUninitializedTableColumn(attribute);
if (this.collection) {
this.createCollectionAttribute(attribute);
} else if (this... | close | identifier_name |
table-attribute-suggestions.component.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either ... |
}
public ngAfterViewInit() {
this.open();
}
public open() {
if (this.dropdown) {
this.dropdown.open();
}
}
public ngOnDestroy() {
this.close();
}
public close() {
if (this.dropdown) {
this.dropdown.close();
}
}
public createAttribute() {
const attribute:... | {
this.cursor$.next(this.cursor);
} | conditional_block |
sensor_form.tsx | import * as React from "react";
import { SensorFormProps } from "./interfaces";
import { sortResourcesById } from "../util";
import { Row, Col } from "../ui";
import { DeleteButton } from "../ui/delete_button";
import { NameInputBox, PinDropdown, ModeDropdown } from "../controls/pin_form_fields";
export const SensorFo... | </div>; | </Col>
</Row>)} | random_line_split |
test_events.py | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
from pida.core.events import EventsConfig
import unittest
class MockCallback(object):
def __init__(self):
self.calls = []
def __call__(self, **kw):
self.calls.append(kw)
class MockService(object):
"""used... | (self):
self.e.emit('initial')
self.assertEqual(len(self.c.calls), 1)
self.assertEqual(self.c.calls[0], {})
def test_emit_event_multiple(self):
self.e.emit('initial')
self.e.emit('initial')
self.e.emit('initial')
self.assertEqual(len(self.c.calls), 3)
de... | test_emit_event | identifier_name |
test_events.py | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
from pida.core.events import EventsConfig
import unittest
class MockCallback(object):
def __init__(self):
|
def __call__(self, **kw):
self.calls.append(kw)
class MockService(object):
"""used instead of None cause weakref proxy cant handle None"""
class EventTestCase(unittest.TestCase):
def setUp(self):
self.e = EventsConfig(MockService())
self.c = MockCallback()
self.e.publish... | self.calls = [] | identifier_body |
test_events.py | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
from pida.core.events import EventsConfig
import unittest
class MockCallback(object):
def __init__(self): | self.calls = []
def __call__(self, **kw):
self.calls.append(kw)
class MockService(object):
"""used instead of None cause weakref proxy cant handle None"""
class EventTestCase(unittest.TestCase):
def setUp(self):
self.e = EventsConfig(MockService())
self.c = MockCallback()... | random_line_split | |
test_storage.py | from nose.plugins.skip import SkipTest
from oyster.conf import settings
from oyster.core import Kernel
from oyster.storage.gridfs import GridFSStorage
from oyster.storage.dummy import DummyStorage
def _simple_storage_test(StorageCls):
kernel = Kernel(mongo_db='oyster_test')
kernel.doc_classes['default'] = {}... |
def test_dummy():
_simple_storage_test(DummyStorage) | random_line_split | |
test_storage.py | from nose.plugins.skip import SkipTest
from oyster.conf import settings
from oyster.core import Kernel
from oyster.storage.gridfs import GridFSStorage
from oyster.storage.dummy import DummyStorage
def _simple_storage_test(StorageCls):
kernel = Kernel(mongo_db='oyster_test')
kernel.doc_classes['default'] = {}... |
from oyster.storage.s3 import S3Storage
_simple_storage_test(S3Storage)
def test_gridfs():
_simple_storage_test(GridFSStorage)
def test_dummy():
_simple_storage_test(DummyStorage)
| raise SkipTest('S3 not configured') | conditional_block |
test_storage.py | from nose.plugins.skip import SkipTest
from oyster.conf import settings
from oyster.core import Kernel
from oyster.storage.gridfs import GridFSStorage
from oyster.storage.dummy import DummyStorage
def _simple_storage_test(StorageCls):
kernel = Kernel(mongo_db='oyster_test')
kernel.doc_classes['default'] = {}... | ():
_simple_storage_test(DummyStorage)
| test_dummy | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.