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 |
|---|---|---|---|---|
extract_cats_dogs.py | """One-time script for extracting all the cat and dog images from CIFAR-10."""
import cPickle
import numpy as np
from PIL import Image
TRAIN_FILES = ['cifar-10-batches-py/data_batch_%d' % i for i in range(1,6)]
TEST_FILE = 'test_batch'
CAT_INPUT_LABEL = 3
DOG_INPUT_LABEL = 5
CAT_OUTPUT_LABEL = 1
DOG_OUTPUT_LABEL = ... | # Data is stored in B x 3072 format, convert to B' x 32 x 32 x 3
images[index, :, :, :] = np.transpose(
np.reshape(data_batch['data'][batch_index, :],
newshape=(3, 32, 32)),
axes=(1, 2, 0))
if label == CAT_INPUT_LABEL:
labels[index] = CAT_OUTPUT_LABEL
else:
... |
for data_batch in data:
for batch_index, label in enumerate(data_batch['labels']):
if label == CAT_INPUT_LABEL or label == DOG_INPUT_LABEL: | random_line_split |
ipc_perftest.py | #!/usr/bin/python3
# @begin:license
#
# Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de>
#
# 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 y... | (ipc_test.IPCPerfTestBase):
async def test_small_messages(self):
request = ipc_test_pb2.TestRequest()
request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2))
await self.run_test(request, 5000)
async def test_large_messages(self):
request = ipc_test_pb2.Te... | IPCPerfTest | identifier_name |
ipc_perftest.py | #!/usr/bin/python3
# @begin:license
#
# Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de>
#
# 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 y... |
await self.run_test(request, 100)
| request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2)) | conditional_block |
ipc_perftest.py | #!/usr/bin/python3
# @begin:license
#
# Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de>
#
# 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 y... | request = ipc_test_pb2.TestRequest()
for _ in range(10000):
request.t.add(numerator=random.randint(0, 4), denominator=random.randint(1, 2))
await self.run_test(request, 100) | identifier_body | |
ipc_perftest.py | #!/usr/bin/python3
# @begin:license
#
# Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de>
#
# 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 y... | await self.run_test(request, 100) | random_line_split | |
locations.spec.ts | 'use strict';
import { Location } from '../../src/models/location';
describe('Location', () => {
let mockLocation: Location = new Location({
"id": 178,
"timestamp": "2018-04-09T16:17:26.464000-07:00",
"target": "d--0000-0000-0000-0532",
"lat": "37.406246",
"lon": "-122.109423",
"user": "kay... | expect(mockLocation.getPosition()).toEqual({ lat: 37.406246, lng: -122.109423 });
});
}); | expect(mockLocation.target).toBe("d--0000-0000-0000-0532");
expect(mockLocation.timestamp).toEqual("2018-04-09T16:17:26.464000-07:00");
expect(mockLocation.lat).toBe("37.406246");
expect(mockLocation.lon).toBe("-122.109423"); | random_line_split |
inherited_table.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True,... |
}
}
match (first, second) {
(None, None) => Err(()),
(Some(length), None) => {
Ok(SpecifiedValue {
horizontal: length.clone(),
vertical: length,
})
}
(Some(horizontal), So... | {
second = Some(len);
} | conditional_block |
inherited_table.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True,... | fn from_computed_value(computed: &computed_value::T) -> Self {
SpecifiedValue {
horizontal: ToComputedValue::from_computed_value(&computed.horizontal),
vertical: ToComputedValue::from_computed_value(&computed.vertical),
}
}
}
pub fn parse(... | #[inline] | random_line_split |
inherited_table.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("InheritedTable", inherited=True,... | <W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
try!(self.horizontal.to_css(dest));
try!(dest.write_str(" "));
self.vertical.to_css(dest)
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write... | to_css | identifier_name |
write.component.ts | import {Component, EventEmitter, OnInit, Output} from '@angular/core'
import {ChapterService} from '../chapter.service'
import {ActivatedRoute, Router} from '@angular/router'
import {Chapter} from '../../models/chapter'
import {UserService} from '../user.service'
import {isString} from 'util'
import {NotificationServic... | implements OnInit {
parentChapter: Chapter
newChapter: Chapter = new Chapter()
@Output() draftSaved = new EventEmitter();
tags: any = []
loaded = false
constructor(private _chapterService: ChapterService,
private route: ActivatedRoute,
private router: Router,
p... | WriteComponent | identifier_name |
write.component.ts | import {Component, EventEmitter, OnInit, Output} from '@angular/core'
import {ChapterService} from '../chapter.service'
import {ActivatedRoute, Router} from '@angular/router'
import {Chapter} from '../../models/chapter'
import {UserService} from '../user.service'
import {isString} from 'util'
import {NotificationServic... |
}
| {
this.newChapter.tags = []
this.tags.forEach(tag => {
if (tag.value) {
this.newChapter.tags.push(tag.value)
} else if (isString(tag)) {
this.newChapter.tags.push(tag)
}
})
} | identifier_body |
write.component.ts | import {Component, EventEmitter, OnInit, Output} from '@angular/core'
import {ChapterService} from '../chapter.service'
import {ActivatedRoute, Router} from '@angular/router'
import {Chapter} from '../../models/chapter'
import {UserService} from '../user.service'
import {isString} from 'util'
import {NotificationServic... | else {
this.loaded = true;
this.verifyDraftSave()
}
})
}
verifyDraftSave(){
this.draftSaved.emit()
this.snackbar.open('Draft successfully saved', 'Dismiss', {
duration: 4000
})
}
updateReadingHistory(bookId: string, newChapterId: string) {
this._readingHistory... | {
const newEdge = new Edge()
newEdge.bookId = this.parentChapter.book
newEdge.source = this.parentChapter._id
newEdge.target = chapterId
this._edgeService.createEdge(newEdge).subscribe(() => {
this.loaded = true
if (draft) {
this.verifyDraftSave()
... | conditional_block |
write.component.ts | import {Component, EventEmitter, OnInit, Output} from '@angular/core'
import {ChapterService} from '../chapter.service'
import {ActivatedRoute, Router} from '@angular/router'
import {Chapter} from '../../models/chapter'
import {UserService} from '../user.service'
import {isString} from 'util'
import {NotificationServic... | import {ReadingHistoryService} from "../reading-history.service";
@Component({
selector: 'wn-write',
templateUrl: './write.component.html',
styleUrls: ['./write.component.css']
})
export class WriteComponent implements OnInit {
parentChapter: Chapter
newChapter: Chapter = new Chapter()
@Output() draftSav... | import {Edge} from '../../models/edge'
import {MatSnackBar} from '@angular/material' | random_line_split |
os.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
impl Rng for OSRng {
fn next_u32(&mut self) -> u32 {
let mut v = [0u8, .. 4];
self.fill_bytes(v);
unsafe { cast::transmute(v) }
}
fn next_u64(&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(v);
... | {
Ok(OSRng { hcryptprov: hcp })
} | conditional_block |
os.rs | // Copyright 2013 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 ... |
}
}
#[cfg(test)]
mod test {
use super::OSRng;
use Rng;
use std::task;
#[test]
fn test_os_rng() {
let mut r = OSRng::new().unwrap();
r.next_u32();
r.next_u64();
let mut v = [0u8, .. 1000];
r.fill_bytes(v);
}
#[test]
fn test_os_rng_tasks() ... | {
let ret = unsafe {
CryptReleaseContext(self.hcryptprov, 0)
};
if ret == 0 {
fail!("couldn't release context: {}", os::last_os_error());
}
} | identifier_body |
os.rs | // Copyright 2013 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 ... | txs.push(tx);
task::spawn(proc() {
// wait until all the tasks are ready to go.
rx.recv();
// deschedule to attempt to interleave things as much
// as possible (XXX: is this a good test?)
let mut r = OSRng::new().un... | let mut txs = vec!();
for _ in range(0, 20) {
let (tx, rx) = channel(); | random_line_split |
os.rs | // Copyright 2013 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 ... | (&mut self) -> u64 {
let mut v = [0u8, .. 8];
self.fill_bytes(v);
unsafe { cast::transmute(v) }
}
fn fill_bytes(&mut self, v: &mut [u8]) {
let ret = unsafe {
CryptGenRandom(self.hcryptprov, v.len() as DWORD,
v... | next_u64 | identifier_name |
app.js | var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Connect to DB
var dbConfig = require('./config/db');
var mongoose = require('mongoose');
mo... |
else {
if ( res === undefined ) console.log('connected to ' + dbConfig.url );
else { console.log('ERROR connecting to : ' + dbConfig.url + '. ' + res.errmsg); process.exit(0);}
}
});
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');... | { console.log('ERROR connecting to : ' + dbConfig.url + '. ' + err); process.exit(0);} | conditional_block |
app.js | var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// Connect to DB
var dbConfig = require('./config/db');
var mongoose = require('mongoose');
mo... | var expressSession = require('express-session');
app.use(expressSession({
secret: 'mySecretKey',
resave: true,
saveUninitialized: true})
);
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displayin... | var passport = require('passport'); | random_line_split |
websocket.rs | => {
return Err(Error::InvalidState);
},
WebSocketRequestState::Open => false,
WebSocketRequestState::Closing | WebSocketRequestState::Closed => true,
};
let address = Trusted::new(self);
match data_byte_len.checked_add(self.buffered_amount.... | name | identifier_name | |
websocket.rs | .send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_thread)).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = box MessageReceivedTask {
address: moved_address.clone(),
... | {
// Do nothing if already closed.
return;
} | conditional_block | |
websocket.rs | sender.send(CommonScriptMsg::RunnableMsg(WebSocketEvent, open_thread)).unwrap();
},
WebSocketNetworkEvent::MessageReceived(message) => {
let message_thread = box MessageReceivedTask {
address: moved_address.clone(),
... | random_line_split | ||
dbquery.py | TABLES")
except:
pass
return app
def _db_conn():
current_app.teardown_appcontext_funcs.append(unlock_all)
out = {}
out[cfg['CFG_DATABASE_HOST']] = {}
out[cfg['CFG_DATABASE_SLAVE']] = {}
return out
connect = DBConnect()
_DB_CONN = LazyDict(_db_conn)
class Invenio... | Useful to be able to have the website up while MySQL database
is down for maintenance, hot copies, table repairs, etc.
@note: In case of problems, exceptions are returned according to
the Python DB API 2.0. The client code can import them from
this file and catch them.
"""
if cfg['CFG_ACCE... | """Run SQL on the server with PARAM and return result.
@param param: tuple of string params to insert in the query (see
notes below)
@param n: number of tuples in result (0 for unbounded)
@param with_desc: if True, will return a DB API 7-tuple describing
columns in query.
@param with_dict: if Tr... | identifier_body |
dbquery.py | =None, n=0, with_desc=False, with_dict=False, run_on_slave=False):
"""Run SQL on the server with PARAM and return result.
@param param: tuple of string params to insert in the query (see
notes below)
@param n: number of tuples in result (0 for unbounded)
@param with_desc: if True, will return a DB A... | update_times.append(str(row[11]))
return max(update_times)
| random_line_split | |
dbquery.py | (self, *args, **kwargs):
return self._connect(*args, **kwargs)
@cached_property
def _connect(self):
if cfg['CFG_MISCUTIL_SQL_USE_SQLALCHEMY']:
try:
import sqlalchemy.pool as pool
import MySQLdb as mysqldb
mysqldb = pool.manage(mysqldb,... | __call__ | identifier_name | |
dbquery.py | TABLES")
except:
pass
return app
def _db_conn():
current_app.teardown_appcontext_funcs.append(unlock_all)
out = {}
out[cfg['CFG_DATABASE_HOST']] = {}
out[cfg['CFG_DATABASE_SLAVE']] = {}
return out
connect = DBConnect()
_DB_CONN = LazyDict(_db_conn)
class Invenio... | i += limit
return r
def run_sql_with_limit(query, param=None, n=0, with_desc=False, wildcard_limit=0, run_on_slave=False):
"""This function should be used in some cases, instead of run_sql function, in order
to protect the db from queries that might take a log time to respond
Ex: searc... | try:
db = _db_login(dbhost)
cur = db.cursor()
gc.disable()
rc = cur.executemany(query, params[i:i + limit])
gc.enable()
except (OperationalError, InterfaceError):
try:
db = _db_login(dbhost, relogin=1)
cur = ... | conditional_block |
std-panic-locations.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// revisions: default mir-opt
//[mir-opt] compile-flags: -Zmir-opt-level=4
#![allow(unconditional_panic)]
//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.
use std::cell::RefCell;
use std... |
}));
fn assert_panicked(f: impl FnOnce() + UnwindSafe) {
std::panic::catch_unwind(f).unwrap_err();
}
let nope: Option<()> = None;
assert_panicked(|| nope.unwrap());
assert_panicked(|| nope.expect(""));
let oops: Result<(), ()> = Err(());
assert_panicked(|| oops.unwrap());
... | {
eprintln!("expected a location in the test file, found {:?}", actual);
panic!();
} | conditional_block |
std-panic-locations.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// revisions: default mir-opt
//[mir-opt] compile-flags: -Zmir-opt-level=4
#![allow(unconditional_panic)]
//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.
use std::cell::RefCell;
use std... |
let nope: Option<()> = None;
assert_panicked(|| nope.unwrap());
assert_panicked(|| nope.expect(""));
let oops: Result<(), ()> = Err(());
assert_panicked(|| oops.unwrap());
assert_panicked(|| oops.expect(""));
let fine: Result<(), ()> = Ok(());
assert_panicked(|| fine.unwrap_err());
... | {
std::panic::catch_unwind(f).unwrap_err();
} | identifier_body |
std-panic-locations.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// revisions: default mir-opt
//[mir-opt] compile-flags: -Zmir-opt-level=4
#![allow(unconditional_panic)]
//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.
use std::cell::RefCell;
use std... | (f: impl FnOnce() + UnwindSafe) {
std::panic::catch_unwind(f).unwrap_err();
}
let nope: Option<()> = None;
assert_panicked(|| nope.unwrap());
assert_panicked(|| nope.expect(""));
let oops: Result<(), ()> = Err(());
assert_panicked(|| oops.unwrap());
assert_panicked(|| oops.expect("... | assert_panicked | identifier_name |
std-panic-locations.rs | // run-pass
// ignore-wasm32-bare compiled with panic=abort by default
// revisions: default mir-opt
//[mir-opt] compile-flags: -Zmir-opt-level=4
#![allow(unconditional_panic)]
//! Test that panic locations for `#[track_caller]` functions in std have the correct
//! location reported.
use std::cell::RefCell;
use std... | std::panic::catch_unwind(f).unwrap_err();
}
let nope: Option<()> = None;
assert_panicked(|| nope.unwrap());
assert_panicked(|| nope.expect(""));
let oops: Result<(), ()> = Err(());
assert_panicked(|| oops.unwrap());
assert_panicked(|| oops.expect(""));
let fine: Result<(), ()>... | fn assert_panicked(f: impl FnOnce() + UnwindSafe) { | random_line_split |
settings.py | """
Django settings for figexample project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)... | 'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.Ses... | 'django.contrib.sessions',
'django.contrib.messages', | random_line_split |
item.js | import React from 'react';
import PropTypes from 'prop-types';
import { FetchedData, Param } from '../fetched';
import * as globals from '../globals';
import { ObjectPicker } from '../inputs';
const ItemBlockView = (props) => {
const ViewComponent = globals.contentViews.lookup(props.context);
return <ViewComp... | extends React.Component {
shouldComponentUpdate(nextProps) {
return (nextProps.value.item !== this.props.value.item);
}
render() {
const context = this.props.value.item;
if (typeof context === 'object') {
return <ItemBlockView context={context} />;
}
if ... | FetchedItemBlockView | identifier_name |
item.js | import React from 'react';
import PropTypes from 'prop-types';
import { FetchedData, Param } from '../fetched';
import * as globals from '../globals';
import { ObjectPicker } from '../inputs';
const ItemBlockView = (props) => {
const ViewComponent = globals.contentViews.lookup(props.context);
return <ViewComp... |
return null;
}
}
FetchedItemBlockView.propTypes = {
value: PropTypes.object,
};
FetchedItemBlockView.defaultProps = {
value: null,
};
globals.blocks.register({
label: 'item block',
icon: 'icon icon-paperclip',
schema: {
type: 'object',
properties: {
item:... | {
return (
<FetchedData>
<Param name="context" url={context} />
<ItemBlockView />
</FetchedData>
);
} | conditional_block |
item.js | import React from 'react';
import PropTypes from 'prop-types';
import { FetchedData, Param } from '../fetched';
import * as globals from '../globals';
import { ObjectPicker } from '../inputs';
const ItemBlockView = (props) => {
const ViewComponent = globals.contentViews.lookup(props.context);
return <ViewComp... |
}
FetchedItemBlockView.propTypes = {
value: PropTypes.object,
};
FetchedItemBlockView.defaultProps = {
value: null,
};
globals.blocks.register({
label: 'item block',
icon: 'icon icon-paperclip',
schema: {
type: 'object',
properties: {
item: {
title: '... | {
const context = this.props.value.item;
if (typeof context === 'object') {
return <ItemBlockView context={context} />;
}
if (typeof context === 'string') {
return (
<FetchedData>
<Param name="context" url={context} />
... | identifier_body |
item.js | import React from 'react';
import PropTypes from 'prop-types';
import { FetchedData, Param } from '../fetched';
import * as globals from '../globals';
import { ObjectPicker } from '../inputs';
const ItemBlockView = (props) => {
const ViewComponent = globals.contentViews.lookup(props.context);
return <ViewComp... | properties: {
item: {
title: 'Item',
type: 'string',
formInput: <ObjectPicker />,
},
className: {
title: 'CSS Class',
type: 'string',
},
},
},
view: FetchedItemBlockVie... | globals.blocks.register({
label: 'item block',
icon: 'icon icon-paperclip',
schema: {
type: 'object', | random_line_split |
providers.rs | // Copyright 2020 The Kythe 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 required by appli... |
}
impl FileProvider for ProxyFileProvider {
/// Given a file path and digest, returns whether the proxy can find the
/// file.
fn exists(&mut self, path: &str, digest: &str) -> Result<bool, KytheError> {
// Submit the file request to the proxy
let request = proxyrequests::file(path.to_stri... | {
Self::new()
} | identifier_body |
providers.rs | // Copyright 2020 The Kythe 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 required by appli... | (&mut self, path: &str, digest: &str) -> Result<bool, KytheError> {
// Submit the file request to the proxy
let request = proxyrequests::file(path.to_string(), digest.to_string())?;
println!("{}", request);
io::stdout().flush().map_err(|err| {
KytheError::IndexerError(format!... | exists | identifier_name |
providers.rs | // Copyright 2020 The Kythe 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 required by appli... | // Retrieve base64 content and convert to a Vec<u8>
let content_option = args["content"].as_str();
if content_option.is_none() {
return Ok(vec![]);
}
let content_base64: &str = content_option.unwrap();
let content: Vec<u8> = base64:... | } else {
let args: Value = response["args"].clone(); | random_line_split |
providers.rs | // Copyright 2020 The Kythe 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 required by appli... |
}
}
| {
let args: Value = response["args"].clone();
// Retrieve base64 content and convert to a Vec<u8>
let content_option = args["content"].as_str();
if content_option.is_none() {
return Ok(vec![]);
}
let content_base64: &str = content_o... | conditional_block |
fixtures.py | import copy
import json
import os
import asyncio
import pytest
import webdriver
from urllib.parse import urlunsplit
from tests.support import defaults
from tests.support.helpers import cleanup_session, deep_update
from tests.support.inline import build_inline
from tests.support.http_request import HTTPRequest
# Th... | ():
with open(os.environ.get("WD_SERVER_CONFIG_FILE"), "r") as f:
return json.load(f)
@pytest.fixture(scope="session")
def configuration():
host = os.environ.get("WD_HOST", defaults.DRIVER_HOST)
port = int(os.environ.get("WD_PORT", str(defaults.DRIVER_PORT)))
capabilities = json.loads(os.envir... | server_config | identifier_name |
fixtures.py | import copy
import json
import os
import asyncio
import pytest
import webdriver
from urllib.parse import urlunsplit
from tests.support import defaults
from tests.support.helpers import cleanup_session, deep_update
from tests.support.inline import build_inline
from tests.support.http_request import HTTPRequest
# Th... | This file also acts as a wptserve handler (see the main function
below) which configures the HTTP response using query parameters.
This function returns a URL to the wptserve handler, which in turn
will serve an HTTP response with the requested source extract
inlined in a well-formed document, and ... | are not universally supported (or indeed standardised!) across
browsers, it now delegates the serving of the document to wptserve. | random_line_split |
fixtures.py | import copy
import json
import os
import asyncio
import pytest
import webdriver
from urllib.parse import urlunsplit
from tests.support import defaults
from tests.support.helpers import cleanup_session, deep_update
from tests.support.inline import build_inline
from tests.support.http_request import HTTPRequest
# Th... | configuration["port"],
capabilities=caps)
_current_session.start()
# Enforce a fixed default window size and position
if _current_session.capabilities.get("setWindowRect"):
_current_session.window.size = defaults.WINDOW_SIZE
_current_session.window.position = defaul... | """Create and start a session for a test that does not itself test session creation.
By default the session will stay open after each test, but we always try to start a
new one and assume that if that fails there is already a valid session. This makes it
possible to recover from some errors that might leav... | identifier_body |
fixtures.py | import copy
import json
import os
import asyncio
import pytest
import webdriver
from urllib.parse import urlunsplit
from tests.support import defaults
from tests.support.helpers import cleanup_session, deep_update
from tests.support.inline import build_inline
from tests.support.http_request import HTTPRequest
# Th... |
_current_session.start()
await _current_session.bidi_session.start()
# Enforce a fixed default window size and position
if _current_session.capabilities.get("setWindowRect"):
_current_session.window.size = defaults.WINDOW_SIZE
_current_session.window.position = defaults.WINDOW_POSITIO... | _current_session = webdriver.Session(
configuration["host"],
configuration["port"],
capabilities=caps,
enable_bidi=True) | conditional_block |
gpg.py | cmdtable = {}
command = cmdutil.command(cmdtable)
testedwith = 'internal'
class gpg(object):
def __init__(self, path, key=None):
self.path = path
self.key = (key and " --local-user \"%s\"" % key) or ""
def sign(self, data):
gpgcmd = "%s --sign --detach-sign%s" % (self.path, self.key)
... |
def keystr(ui, key):
"""associate a string to a key (username, comment)"""
keyid, user, fingerprint = key
comment = ui.config("gpg", fingerprint, None)
if comment:
return "%s (%s)" % (user, comment)
else:
return user
@command("sign",
[('l', 'local', None, _('make the signa... | random_line_split | |
gpg.py | cmdtable = {}
command = cmdutil.command(cmdtable)
testedwith = 'internal'
class gpg(object):
def __init__(self, path, key=None):
self.path = path
self.key = (key and " --local-user \"%s\"" % key) or ""
def sign(self, data):
gpgcmd = "%s --sign --detach-sign%s" % (self.path, self.key)
... |
if not nodes:
nodes = [repo.changelog.tip()]
for n in nodes:
hexnode = hgnode.hex(n)
ui.write(_("signing %d:%s\n") % (repo.changelog.rev(n),
hgnode.short(n)))
# build data
data = node2txt(repo, n, sigver)
sig = my... | raise util.Abort(_('uncommitted merge - please provide a '
'specific revision')) | conditional_block |
gpg.py | pgcmd)
finally:
for f in (sigfile, datafile):
try:
if f:
os.unlink(f)
except OSError:
pass
keys = []
key, fingerprint = None, None
err = ""
for l in ret.splitlines():
... | """map a manifest into some text"""
if ver == "0":
return "%s\n" % hgnode.hex(node)
else:
raise util.Abort(_("unknown signature version")) | identifier_body | |
gpg.py | cmdtable = {}
command = cmdutil.command(cmdtable)
testedwith = 'internal'
class gpg(object):
def __init__(self, path, key=None):
self.path = path
self.key = (key and " --local-user \"%s\"" % key) or ""
def sign(self, data):
gpgcmd = "%s --sign --detach-sign%s" % (self.path, self.key)
... | (ui, repo, rev):
"""verify all the signatures there may be for a particular revision"""
mygpg = newgpg(ui)
rev = repo.lookup(rev)
hexrev = hgnode.hex(rev)
keys = []
for data, context in sigwalk(repo):
node, version, sig = data
if node == hexrev:
k = getkeys(ui, repo,... | check | identifier_name |
binary.rs | u32 {
((buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32))
}
#[inline]
fn be_u64(buf: &[u8]) -> u64 {
((buf[0] as u64) << 56 | (buf[1] as u64) << 48 | (buf[2] as u64) << 40 |
(buf[3] as u64) << 32 | (buf[4] as u64) << 24 | (buf[5] as u64) << 16 |
(buf[6] as u64) <... | <R: Read>(input: &mut R, size: u8, count: usize) -> Result<Vec<u64>> {
let len = size as usize * count;
let mut buf = Vec::with_capacity(len);
try!(input.take(len as u64).read_to_end(&mut buf));
Ok(buf.chunks(size as usize)
.map(|x| sized_int(x, size))
.collect())
}
#[inline]
fn read_si... | sized_ints | identifier_name |
binary.rs | -> u32 {
((buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32))
}
#[inline]
fn be_u64(buf: &[u8]) -> u64 {
((buf[0] as u64) << 56 | (buf[1] as u64) << 48 | (buf[2] as u64) << 40 |
(buf[3] as u64) << 32 | (buf[4] as u64) << 24 | (buf[5] as u64) << 16 |
(buf[6] as u64... | try!(input.read_exact(&mut len));
let size = try!(validate_size(1u8 << (len[0] & 0xF)));
try!(input.read_exact(&mut buf[0..size as usize]));
Ok((buf, size))
}
#[inline]
fn read_int<R: Read>(input: &mut R) -> Result<u64> {
let mut buf = [0; 1];
try!(input.read_exact(&mut buf));
if (buf[0] &... | let mut len = [0; 1];
let mut buf = [0; 8]; | random_line_split |
binary.rs | u32 |
#[inline]
fn be_u64(buf: &[u8]) -> u64 {
((buf[0] as u64) << 56 | (buf[1] as u64) << 48 | (buf[2] as u64) << 40 |
(buf[3] as u64) << 32 | (buf[4] as u64) << 24 | (buf[5] as u64) << 16 |
(buf[6] as u64) << 8 | (buf[7] as u64))
}
#[allow(unsafe_code)]
#[inline]
fn be_f32(buf: &[u8]) -> f32 {
unsafe {... | {
((buf[0] as u32) << 24 | (buf[1] as u32) << 16 | (buf[2] as u32) << 8 | (buf[3] as u32))
} | identifier_body |
pubsub-async-io.rs | use async_lapin::*;
use lapin::{
message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
BasicProperties, Connection, ConnectionProperties, Result,
};
use tracing::info;
fn main() -> Result<()> | "hello",
QueueDeclareOptions::default(),
FieldTable::default(),
)
.await?;
info!(?queue, "Declared queue");
let consumer = channel_b
.basic_consume(
"hello",
"my_consumer",
... | {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
async_io::block_on(async {
let conn =
Connection::connect(&... | identifier_body |
pubsub-async-io.rs | use async_lapin::*;
use lapin::{
message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
BasicProperties, Connection, ConnectionProperties, Result,
};
use tracing::info;
fn main() -> Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", ... |
});
let payload = b"Hello world!";
loop {
let confirm = channel_a
.basic_publish(
"",
"hello",
BasicPublishOptions::default(),
payload.to_vec(),
BasicProperties::def... | {
delivery
.ack(BasicAckOptions::default())
.await
.expect("failed to ack");
} | conditional_block |
pubsub-async-io.rs | use async_lapin::*;
use lapin::{
message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
BasicProperties, Connection, ConnectionProperties, Result,
};
use tracing::info;
fn main() -> Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", ... |
let payload = b"Hello world!";
loop {
let confirm = channel_a
.basic_publish(
"",
"hello",
BasicPublishOptions::default(),
payload.to_vec(),
BasicProperties::default(),
... | }); | random_line_split |
pubsub-async-io.rs | use async_lapin::*;
use lapin::{
message::DeliveryResult, options::*, publisher_confirm::Confirmation, types::FieldTable,
BasicProperties, Connection, ConnectionProperties, Result,
};
use tracing::info;
fn | () -> Result<()> {
if std::env::var("RUST_LOG").is_err() {
std::env::set_var("RUST_LOG", "info");
}
tracing_subscriber::fmt::init();
let addr = std::env::var("AMQP_ADDR").unwrap_or_else(|_| "amqp://127.0.0.1:5672/%2f".into());
async_io::block_on(async {
let conn =
Conn... | main | identifier_name |
generate-messages-header.py | #!/usr/bin/env python
# | # Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary fo... | # Copyright (C) 2010 Apple Inc. All rights reserved.
# | random_line_split |
generate-messages-header.py | #!/usr/bin/env python
#
# Copyright (C) 2010 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list... |
if __name__ == '__main__':
sys.exit(main(sys.argv))
| if not argv:
argv = sys.argv
input_path = argv[1]
with open(input_path) as input_file:
# Python 3, change to: print(webkit.messages.generate_messages_header(input_file), end='')
sys.stdout.write(webkit.messages.generate_messages_header(input_file))
return 0 | identifier_body |
generate-messages-header.py | #!/usr/bin/env python
#
# Copyright (C) 2010 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list... | sys.exit(main(sys.argv)) | conditional_block | |
generate-messages-header.py | #!/usr/bin/env python
#
# Copyright (C) 2010 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list... | (argv=None):
if not argv:
argv = sys.argv
input_path = argv[1]
with open(input_path) as input_file:
# Python 3, change to: print(webkit.messages.generate_messages_header(input_file), end='')
sys.stdout.write(webkit.messages.generate_messages_header(input_file))
return 0
if __na... | main | identifier_name |
gamestate.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import constants
from construct import Byte, Struct, Enum, Bytes, Const, Array, Renamed, Int16ul
Short = Int16ul
RobotInfo = "robot_info" / Struct(
"penalty" / Enum(Byte, constants.SPLPenalty),
"secs_till_unpenalised" / Byte,
"number_of_yellow_cards" / Byte,
... | "version" / Const(constants.GAMECONTROLLER_RESPONSE_VERSION, Byte),
"team" / Byte,
"player" / Byte,
"message" / Byte
) | "header" / Const(b"RGrt", Bytes(4)), | random_line_split |
events.server.controller.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Event = mongoose.model('Event'),
Testrun = mongoose.model('Testrun'),
testruns = require('./testruns.server.controller'),
_ = require('lodash');
/**
* Create a Event
*/
export... | testRun.buildResultKey = event.buildResultKey
testRun.eventIds.push(startEvent._id, event._id);
testruns.persistTestRunById(testRun.productName, testRun.dashboardName, testRun, function(storedTestrun){
console.log("test run stored");
})
}
});
}
}
});
};
/**
* Show th... | {
res.jsonp(event);
/* if "end" event, check if corresponding "start" event exist and add to test runs */
if (event.eventDescription === "end"){
Event.findOne({$and:[{testRunId: event.testRunId}, {eventDescription: "start"}]}).exec(function(err, startEvent) {
if (err) {
return res.status(400).... | conditional_block |
events.server.controller.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Event = mongoose.model('Event'),
Testrun = mongoose.model('Testrun'),
testruns = require('./testruns.server.controller'),
_ = require('lodash');
/**
* Create a Event
*/
export... | return res.status(403).send('User is not authorized');
}
next();
}; | random_line_split | |
constants.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apac... | 'router': L3_ROUTER_NAT
}
# TODO(salvatore-orlando): Move these (or derive them) from conf file
ALLOWED_SERVICES = [CORE, DUMMY, LOADBALANCER, FIREWALL, VPN, METERING,
L3_ROUTER_NAT]
COMMON_PREFIXES = {
CORE: "",
DUMMY: "/dummy_svc",
LOADBALANCER: "/lb",
FIREWALL: "/fw",
VP... | 'lbaas': LOADBALANCER,
'fwaas': FIREWALL,
'vpnaas': VPN,
'metering': METERING, | random_line_split |
closure.rs | bad dream.
//
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pub struct EnvValue {
action: freevars::CaptureMode,
datum: Datum<Lvalue>
}
impl EnvValue {
pub fn | (&self, ccx: &CrateContext) -> String {
format!("{}({})", self.action, self.datum.to_string(ccx))
}
}
// Given a closure ty, emits a corresponding tuple ty
pub fn mk_closure_tys(tcx: &ty::ctxt,
bound_values: &[EnvValue])
-> ty::t {
// determine the types of the ... | to_string | identifier_name |
closure.rs | cx, llenv, [0, i]);
let def_id = freevar.def.def_id();
bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
}
bcx
}
fn fill_fn_pair(bcx: &Block, pair: ValueRef, llfn: ValueRef, llenvptr: ValueRef) {
Store(bcx, llfn, GEPi(bcx, pair, [0u, abi::fn_field_code]));
let llenvptr = Po... | {
// Don't regenerate the wrapper, just reuse the original one.
return llfn;
} | conditional_block | |
closure.rs | Datum<Lvalue>
}
impl EnvValue {
pub fn to_string(&self, ccx: &CrateContext) -> String {
format!("{}({})", self.action, self.datum.to_string(ccx))
}
}
// Given a closure ty, emits a corresponding tuple ty
pub fn mk_closure_tys(tcx: &ty::ctxt,
bound_values: &[EnvValue])
... | {
let _icx = push_ctxt("closure::load_environment");
if freevars.len() == 0 {
return bcx
}
let llenv = bcx.fcx.llenv.unwrap();
for (i, freevar) in freevars.iter().enumerate() {
let upvar_ptr = GEPi(bcx, llenv, [0, i]);
let def_id = freevar.def.def_id();
bcx.fcx.llup... | identifier_body | |
closure.rs | use middle::trans::machine::llsize_of;
use middle::trans::type_of::*;
use middle::trans::type_::Type;
use middle::ty;
use util::ppaux::Repr;
use util::ppaux::ty_to_string;
use arena::TypedArena;
use syntax::ast;
use syntax::ast_util;
// ___Good to know (tm)__________________________________________________
//
// The ... | random_line_split | ||
writer.rs | use std::io::{Write, Result};
use std::path::Path;
use std::fs::File;
use std::iter;
use std::collections::HashMap;
use inflections::Inflect;
use types::{Section, Documentation, Type};
macro_rules! w {
($w:ident) => { writeln!($w) };
($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent)... | New(String, Type),
}
fn write_complex_type<W: Write>(w: &mut W, type_name: String, typ: Type, indent: usize) -> Result<Vec<Todo>> {
let mut todos = Vec::new();
match typ {
Type::Enum(variants) => {
w!(w, indent, "#[derive(Deserialize, Debug, PartialEq, Clone)]")?;
w!(w, inde... | enum Todo {
Existing(String), | random_line_split |
writer.rs | use std::io::{Write, Result};
use std::path::Path;
use std::fs::File;
use std::iter;
use std::collections::HashMap;
use inflections::Inflect;
use types::{Section, Documentation, Type};
macro_rules! w {
($w:ident) => { writeln!($w) };
($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent)... | <P: AsRef<Path>>(path: P, sections: Vec<Section>, mut types: HashMap<String, Type>) -> Result<()> {
let mut file = File::create(path).expect("Unknown path");
write_internal(&mut file, sections, &mut types, 0)
}
fn write_internal<W: Write>(w: &mut W, sections: Vec<Section>, types: &mut HashMap<String, Type>, i:... | write | identifier_name |
writer.rs | use std::io::{Write, Result};
use std::path::Path;
use std::fs::File;
use std::iter;
use std::collections::HashMap;
use inflections::Inflect;
use types::{Section, Documentation, Type};
macro_rules! w {
($w:ident) => { writeln!($w) };
($w:ident, $indent:expr, $s:expr) => { writeln!($w, "{}{}", indent($indent)... | }
}
fn indent(indent: usize) -> String {
iter::repeat(" ").take(indent).collect()
}
| {
match typ {
Type::Bool => Some("bool".to_string()),
Type::F64 => Some("f64".to_string()),
Type::I8 => Some("i8".to_string()),
Type::I16 => Some("i16".to_string()),
Type::I32 => Some("i32".to_string()),
Type::I64 => Some("i64".to_string()),
Type::U8 => Some("... | identifier_body |
kernel_kmeans.py | """Kernel K-means"""
# Author: Mathieu Blondel <mathieu@mblondel.org>
# License: BSD 3 clause
import logging
import numpy as np
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.utils import check_random_state
logger = logging.getLogger(__name__)... | self.labels_ = rs.randint(self.n_clusters, size=n_samples)
dist = np.zeros((n_samples, self.n_clusters))
self.within_distances_ = np.zeros(self.n_clusters)
for it in xrange(self.max_iter):
dist.fill(0)
self._compute_dist(K, dist, self.within_distances_,
... | self.sample_weight_ = sw
rs = check_random_state(self.random_state) | random_line_split |
kernel_kmeans.py | """Kernel K-means"""
# Author: Mathieu Blondel <mathieu@mblondel.org>
# License: BSD 3 clause
import logging
import numpy as np
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.utils import check_random_state
logger = logging.getLogger(__name__)... | from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=1000, centers=5, random_state=0)
km = KernelKMeans(n_clusters=5, max_iter=100, random_state=0, verbose=1)
print km.fit_predict(X)[:10]
print km.predict(X[:10]) | conditional_block | |
kernel_kmeans.py | """Kernel K-means"""
# Author: Mathieu Blondel <mathieu@mblondel.org>
# License: BSD 3 clause
import logging
import numpy as np
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.utils import check_random_state
logger = logging.getLogger(__name__)... |
@property
def _pairwise(self):
return self.kernel == "precomputed"
def _get_kernel_approx(self, X, Y=None):
n = Nystroem(kernel=self.kernel, n_components=self.nystroem, kernel_params=self.kernel_params).fit(X)
z_transformed = n.transform(X)
return np.dot(z_transfo... | self.n_clusters = n_clusters
self.max_iter = max_iter
self.tol = tol
self.random_state = random_state
self.kernel = kernel
self.gamma = gamma
self.degree = degree
self.coef0 = coef0
self.kernel_params = kernel_params
self.verbose = verbose
... | identifier_body |
kernel_kmeans.py | """Kernel K-means"""
# Author: Mathieu Blondel <mathieu@mblondel.org>
# License: BSD 3 clause
import logging
import numpy as np
from sklearn.base import BaseEstimator, ClusterMixin
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.utils import check_random_state
logger = logging.getLogger(__name__)... | (self, K, dist, within_distances, update_within):
"""Compute a n_samples x n_clusters distance matrix using the
kernel trick."""
sw = self.sample_weight_
for j in xrange(self.n_clusters):
mask = self.labels_ == j
if np.sum(mask) == 0:
raise Valu... | _compute_dist | identifier_name |
encoding_support.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Parsing stylesheets from bytes (not `&str`).
extern crate encoding;
use context::QuirksMode;
use cssparser::... | let (string, _) = decode_stylesheet_bytes(
bytes, protocol_encoding_label, environment_encoding);
Self::update_from_str(existing,
&string,
url_data,
stylesheet_loader,
erro... | url_data: UrlExtraData,
stylesheet_loader: Option<&StylesheetLoader>,
error_reporter: &ParseErrorReporter) { | random_line_split |
encoding_support.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Parsing stylesheets from bytes (not `&str`).
extern crate encoding;
use context::QuirksMode;
use cssparser::... | (encoding: &Self::Encoding) -> bool {
matches!(encoding.name(), "utf-16be" | "utf-16le")
}
fn from_label(ascii_label: &[u8]) -> Option<Self::Encoding> {
str::from_utf8(ascii_label).ok().and_then(encoding::label::encoding_from_whatwg_label)
}
}
fn decode_stylesheet_bytes(css: &[u8], protoco... | is_utf16_be_or_le | identifier_name |
multivariateFunction.ts | /// <reference path="../kg.ts" />
module KG {
import MathFunction = KG.MathFunction;
export interface MultivariateFunctionDefinition extends MathFunctionDefinition {
fn: string;
domainCondition?: string;
}
export interface IMultivariateFunction extends IMathFunction {
inDomai... | () {
const fn = this;
return function (emit, x, y) {
emit(y, fn.evaluate(x, y), x);
};
}
contour(level, xScale, yScale, bounds?) {
const fn = this;
bounds = setDefaults(bounds || {}, {
xMin: xScale.domainMin,
... | mathboxFn | identifier_name |
multivariateFunction.ts | /// <reference path="../kg.ts" />
module KG {
import MathFunction = KG.MathFunction;
export interface MultivariateFunctionDefinition extends MathFunctionDefinition {
fn: string;
domainCondition?: string;
}
export interface IMultivariateFunction extends IMathFunction {
inDomai... | yMax: yScale.domainMax
});
let n = 100, m = 100, values = new Array(n * m);
for (let j = 0.5, k = 0; j < m; ++j) {
for (let i = 0.5; i < n; ++i, ++k) {
let x = bounds.xMin + i * (bounds.xMax - bounds.xMin) / n,
... | random_line_split | |
multivariateFunction.ts | /// <reference path="../kg.ts" />
module KG {
import MathFunction = KG.MathFunction;
export interface MultivariateFunctionDefinition extends MathFunctionDefinition {
fn: string;
domainCondition?: string;
}
export interface IMultivariateFunction extends IMathFunction {
inDomai... |
contour(level, xScale, yScale, bounds?) {
const fn = this;
bounds = setDefaults(bounds || {}, {
xMin: xScale.domainMin,
xMax: xScale.domainMax,
yMin: yScale.domainMin,
yMax: yScale.domainMax
});
l... | {
const fn = this;
return function (emit, x, y) {
emit(y, fn.evaluate(x, y), x);
};
} | identifier_body |
multivariateFunction.ts | /// <reference path="../kg.ts" />
module KG {
import MathFunction = KG.MathFunction;
export interface MultivariateFunctionDefinition extends MathFunctionDefinition {
fn: string;
domainCondition?: string;
}
export interface IMultivariateFunction extends IMathFunction {
inDomai... |
let transform = ({type, value, coordinates}) => {
return {
type, value, coordinates: coordinates.map(rings => {
return rings.map(points => {
return points.map(([x, y]) => ([xScale.scale(bounds.xMin ... | {
for (let i = 0.5; i < n; ++i, ++k) {
let x = bounds.xMin + i * (bounds.xMax - bounds.xMin) / n,
y = bounds.yMin + j * (bounds.yMax - bounds.yMin) / m;
values[k] = fn.evaluate(x, y);
}
} | conditional_block |
utils.js | /* -*- indent-tabs-mode:nil; coding: utf-8 -*-
Copyright (C) 2015
"Mu Lei" known as "NalaGinrut" <NalaGinrut@gmail.com>
Grandis is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License by the Free
Software Foundation, either version 3 of the License, o... | (data) {
var ret = [];
for (var k in data) {
ret.push(k + '=' + data[k]);
}
return ret.join('&');
}
// (let ((cnt 0))
// ...)
// ==> (function () { var cnt = 0; ... }) ();
| data2url | identifier_name |
utils.js | /* -*- indent-tabs-mode:nil; coding: utf-8 -*-
Copyright (C) 2015
"Mu Lei" known as "NalaGinrut" <NalaGinrut@gmail.com>
Grandis is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License by the Free
Software Foundation, either version 3 of the License, o... |
function data2url(data) {
var ret = [];
for (var k in data) {
ret.push(k + '=' + data[k]);
}
return ret.join('&');
}
// (let ((cnt 0))
// ...)
// ==> (function () { var cnt = 0; ... }) ();
| {
return ((x !== 'undefined') && x);
} | identifier_body |
utils.js | /* -*- indent-tabs-mode:nil; coding: utf-8 -*-
Copyright (C) 2015
"Mu Lei" known as "NalaGinrut" <NalaGinrut@gmail.com>
Grandis is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License by the Free
Software Foundation, either version 3 of the License, o... | // ==> (function () { var cnt = 0; ... }) (); | random_line_split | |
index.ts | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... | templateUrl: 'index.html',
})
export class AddonModQuizIndexPage {
@ViewChild(AddonModQuizIndexComponent) quizComponent: AddonModQuizIndexComponent;
title: string;
module: any;
courseId: number;
constructor(navParams: NavParams) {
this.module = navParams.get('module') || {};
th... | * Page that displays the quiz entry page.
*/
@IonicPage({ segment: 'addon-mod-quiz-index' })
@Component({
selector: 'page-addon-mod-quiz-index', | random_line_split |
index.ts | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... |
/**
* User left the page.
*/
ionViewDidLeave(): void {
this.quizComponent.ionViewDidLeave();
}
}
| {
this.quizComponent.ionViewDidEnter();
} | identifier_body |
index.ts | // (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agre... | (navParams: NavParams) {
this.module = navParams.get('module') || {};
this.courseId = navParams.get('courseId');
this.title = this.module.name;
}
/**
* Update some data based on the quiz instance.
*
* @param {any} quiz Quiz instance.
*/
updateData(quiz: any): voi... | constructor | identifier_name |
play_20170606134526.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... | function onOut (sprite) {
sprite.tint = 0xff8800;
// sprite.tint = Math.random() * 0xffffff;
}
},
update: function(){
},
start: function(int: id){
groupCidade.children[1].tint = 0x000000;
groupCidade.children[2].tint = 0x000000;
... | function onOver (sprite) {
sprite.tint = 0xffff00;
}
| random_line_split |
play_20170606134526.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... | (sprite) {
sprite.tint = 0x00ff00;
}
function onOver (sprite) {
sprite.tint = 0xffff00;
}
function onOut (sprite) {
sprite.tint = 0xff8800;
// sprite.tint = Math.random() * 0xffffff;
}
},
update: function(){
... | nDown | identifier_name |
play_20170606134526.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... |
},
update: function(){
},
start: function(int: id){
groupCidade.children[1].tint = 0x000000;
groupCidade.children[2].tint = 0x000000;
gato.tint = 0x000000;
passaro.tint = 0x000000;
background.tint = 0x888888;
},
Win: function(){
game.... |
sprite.tint = 0xff8800;
// sprite.tint = Math.random() * 0xffffff;
}
| identifier_body |
play_20170606134526.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... | graphics.destroy();
var cachorro = game.add.sprite(110, 210, 'cachorro');
cachorro.width = 300;
cachorro.height = 170;
// Desenha o gato e a borda da box
var gato = game.add.sprite(510, 210, 'gato');
gato.width = 300;
gato.height = 170;
... | {
// Gera os retangulos que ficarão atras das imagens
graphics.beginFill(0xFFFFFF);
graphics.lineStyle(3, 0x05005e, 1);
graphics.drawRoundedRect(x, 200, 315, 190, 10);
graphics.endFill();
var button = groupCidade.create(x, 200, graphics.generateTe... | conditional_block |
exclude_list_dialog.py | # 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/gpl-3.0.html
import re
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import (
QPushButton,
QLineEdit... |
compiled = None
try:
compiled = re.compile(input_regex)
except re.error:
self.reset_input_style()
return
if self.model.is_match(input_text, compiled):
self.inputLine.setStyleSheet("background-color: rgb(10, 200, 10);")
self._in... | self.reset_input_style()
return | conditional_block |
exclude_list_dialog.py | # 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/gpl-3.0.html
import re
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import (
QPushButton,
QLineEdit... | hheader.setSectionResizeMode(QHeaderView.Fixed)
hheader.setStretchLastSection(True)
hheader.setHighlightSections(False)
hheader.setVisible(True)
gridlayout.addWidget(self.inputLine, 0, 0)
gridlayout.addWidget(self.buttonAdd, 0, 1, Qt.AlignLeft)
gridlayout.addWidge... | vheader = self.tableView.verticalHeader()
vheader.setSectionsMovable(True)
vheader.setVisible(False)
hheader = self.tableView.horizontalHeader()
hheader.setSectionsMovable(False) | random_line_split |
exclude_list_dialog.py | # 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/gpl-3.0.html
import re
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import (
QPushButton,
QLineEdit... | (QDialog):
def __init__(self, app, parent, model, **kwargs):
flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
super().__init__(parent, flags, **kwargs)
self.app = app
self.specific_actions = frozenset()
self._setupUI()
self.model = model ... | ExcludeListDialog | identifier_name |
exclude_list_dialog.py | # 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/gpl-3.0.html
import re
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtWidgets import (
QPushButton,
QLineEdit... | self.testLine.textEdited.connect(self.reset_table_style)
def _setupUI(self):
layout = QVBoxLayout(self)
gridlayout = QGridLayout()
self.buttonAdd = QPushButton(tr("Add"))
self.buttonRemove = QPushButton(tr("Remove Selected"))
self.buttonRestore = QPushButton(tr("Rest... | def __init__(self, app, parent, model, **kwargs):
flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
super().__init__(parent, flags, **kwargs)
self.app = app
self.specific_actions = frozenset()
self._setupUI()
self.model = model # ExcludeListDi... | identifier_body |
noise_traits.rs | //! Noise sampling.
use crate::{P2, P3};
use noise::NoiseFn;
/// A trait for types which are sources of noise, samplable by type `P`.
pub trait NoiseSrc<P> {
/// Samples noise.
fn noise(&self, p: P) -> f32;
}
impl<N> NoiseSrc<P2> for N
where
N: NoiseFn<[f64; 2]>,
{
fn noise(&self, p: P2) -> f32 {
... | (&self, p: P3) -> f32 {
self.get([p.x as f64, p.y as f64, p.z as f64]) as f32
}
}
| noise | identifier_name |
noise_traits.rs | //! Noise sampling.
use crate::{P2, P3};
use noise::NoiseFn;
/// A trait for types which are sources of noise, samplable by type `P`. | fn noise(&self, p: P) -> f32;
}
impl<N> NoiseSrc<P2> for N
where
N: NoiseFn<[f64; 2]>,
{
fn noise(&self, p: P2) -> f32 {
self.get([p.x as f64, p.y as f64]) as f32
}
}
impl<N> NoiseSrc<P3> for N
where
N: NoiseFn<[f64; 3]>,
{
fn noise(&self, p: P3) -> f32 {
self.get([p.x as f64, ... | pub trait NoiseSrc<P> {
/// Samples noise. | random_line_split |
noise_traits.rs | //! Noise sampling.
use crate::{P2, P3};
use noise::NoiseFn;
/// A trait for types which are sources of noise, samplable by type `P`.
pub trait NoiseSrc<P> {
/// Samples noise.
fn noise(&self, p: P) -> f32;
}
impl<N> NoiseSrc<P2> for N
where
N: NoiseFn<[f64; 2]>,
{
fn noise(&self, p: P2) -> f32 |
}
impl<N> NoiseSrc<P3> for N
where
N: NoiseFn<[f64; 3]>,
{
fn noise(&self, p: P3) -> f32 {
self.get([p.x as f64, p.y as f64, p.z as f64]) as f32
}
}
| {
self.get([p.x as f64, p.y as f64]) as f32
} | identifier_body |
admin_generation.py | from corrdb.common.models import UserModel
from corrdb.common.models import ProfileModel
from corrdb.common import get_or_create
import hashlib
import datetime
import simplejson as json
import os
import re
def password_check(password):
"""
Verify the strength of 'password'
Returns a dict indicating the wro... |
content = {}
# Loading admin user account information.
# The instance admin should make sure to securely backup this file.
if os.path.isfile("/home/corradmin/credentials/tmp_admin.json"):
with open("/home/corradmin/credentials/tmp_admin.json", "r") as admin_stuff:
content = json.loads(admin_stuff.read())
... | hash_pwd = hashlib.sha256(('CoRRPassword_%s'%password).encode("ascii")).hexdigest()
(account, created) = get_or_create(document=UserModel, created_at=str(datetime.datetime.utcnow()), email=email, group='admin', api_token=hashlib.sha256(('CoRRToken_%s_%s'%(email, str(datetime.datetime.utcnow()))).encode("ascii")... | conditional_block |
admin_generation.py | from corrdb.common.models import UserModel
from corrdb.common.models import ProfileModel
from corrdb.common import get_or_create
import hashlib
import datetime
import simplejson as json
import os
import re
def password_check(password):
"""
Verify the strength of 'password'
Returns a dict indicating the wro... | (email=None):
"""
Check that admin account does not already exist
Returns boolean to indicate if it is true or false
"""
if email:
account = UserModel.objects(email=email).first()
if account and account.group == "admin":
return True
else:
admin = UserM... | check_admin | identifier_name |
admin_generation.py | from corrdb.common.models import UserModel
from corrdb.common.models import ProfileModel
from corrdb.common import get_or_create
import hashlib
import datetime
import simplejson as json
import os
import re
def password_check(password):
"""
Verify the strength of 'password'
Returns a dict indicating the wro... |
content = {}
# Loading admin user account information.
# The instance admin should make sure to securely backup this file.
if os.path.isfile("/home/corradmin/credentials/tmp_admin.json"):
with open("/home/corradmin/credentials/tmp_admin.json", "r") as admin_stuff:
content = json.loads(admin_stuff.read())
... | """
Creates the first admin user
Returns boolean to indicate if the account was created or not
"""
if not password_check(password):
return False
else:
hash_pwd = hashlib.sha256(('CoRRPassword_%s'%password).encode("ascii")).hexdigest()
(account, created) = get_or_create(docume... | identifier_body |
admin_generation.py | from corrdb.common.models import UserModel
from corrdb.common.models import ProfileModel
from corrdb.common import get_or_create
import hashlib
import datetime
import simplejson as json
import os
import re
def password_check(password):
"""
Verify the strength of 'password'
Returns a dict indicating the wro... | return False
content = {}
# Loading admin user account information.
# The instance admin should make sure to securely backup this file.
if os.path.isfile("/home/corradmin/credentials/tmp_admin.json"):
with open("/home/corradmin/credentials/tmp_admin.json", "r") as admin_stuff:
content = json.lo... | return True
else:
return False
else: | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.