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 |
|---|---|---|---|---|
server.rs | use chrono::prelude::*;
use serde::{Deserialize, Serialize};
// use eyre::{
// // eyre,
// Result,
// // Context as _,
// };
use printspool_json_store::{ Record };
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Server {
pub id: crate::DbId,
pub version: i32,
pub created_at: DateTime... |
fn deleted_at(&self) -> Option<DateTime<Utc>> {
self.deleted_at
}
fn deleted_at_mut(&mut self) -> &mut Option<DateTime<Utc>> {
&mut self.deleted_at
}
}
| {
self.created_at
} | identifier_body |
Gruntfile.js | /*
* Copyright 2013 Mirantis, Inc.
*
* 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 agreed ... | }
},
replace: {
sha: {
src: 'static/index.html',
dest: staticDir + '/',
replacements: [{
from: '__COMMIT_SHA__',
to: function() {
return grunt.config.get('meta.revision... | },
options: {
files: false,
force: true | random_line_split |
setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
import glob
import sys
#VERSION="2.1dev4"
VERSION="2.6dev5"
# Taken from kennethreitz/requests/setup.py
package_directory = os.path.realpath(os.path.dirname(__file__))
def | (file_path):
"""Get the context of the file using full path name."""
content = ""
try:
full_path = os.path.join(package_directory, file_path)
content = open(full_path, 'r').read()
except:
print >> sys.stderr, "### could not open file %r" % file_path
return content
setup(
... | get_file_contents | identifier_name |
setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
import glob
import sys
#VERSION="2.1dev4"
VERSION="2.6dev5"
# Taken from kennethreitz/requests/setup.py
package_directory = os.path.realpath(os.path.dirname(__file__))
def get_file_contents(file_path):
|
setup(
name='privacyIDEA',
version=VERSION,
description='privacyIDEA: identity, multifactor authentication (OTP), '
'authorization, audit',
author='privacyidea.org',
license='AGPLv3',
author_email='cornelius@privacyidea.org',
url='http://www.privacyidea.org',
keywords=... | """Get the context of the file using full path name."""
content = ""
try:
full_path = os.path.join(package_directory, file_path)
content = open(full_path, 'r').read()
except:
print >> sys.stderr, "### could not open file %r" % file_path
return content | identifier_body |
setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os
import glob
import sys
#VERSION="2.1dev4"
VERSION="2.6dev5"
# Taken from kennethreitz/requests/setup.py
package_directory = os.path.realpath(os.path.dirname(__file__))
def get_file_contents(file_path):
"""Get the context of the file u... | "MySQL-python>=1.2.5",
"Pillow>=2.6.1",
"PyJWT>=1.3.0",
"PyYAML>=3.11",
"Pygments>=2.0.2",
"SQLAlchemy>=1.0.5",
"Werkzeug>=0.10.4",
"alembic>=0.... | "MarkupSafe>=0.23", | random_line_split |
unread.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { EventEmitter } from 'events';
import { LocalDataService } from '../services/local-data.service';
import { ApplicationViewModel, ListBody, ListPageViewModel } from '../services/viewmodel.types';
import { DataService } fro... | return this.getDataWithUnreadStatus().map((appViewModel: ApplicationViewModel) => {
const stats: UnreadStats = {changes: 0, messages: 0};
const changesPages = appViewModel.pages.filter((page) => page.viewId == 'page:changes');
if (changesPages.length == 1) {
const changesPage = (changesPag... | random_line_split | |
unread.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { EventEmitter } from 'events';
import { LocalDataService } from '../services/local-data.service';
import { ApplicationViewModel, ListBody, ListPageViewModel } from '../services/viewmodel.types';
import { DataService } fro... |
public async markPageRead(pageId: string, pageBody: ListBody) {
const currentReadViewIds = await this.getReadViewIds();
const modelIds = pageBody.items.filter((item) => item.viewId).map((item) => item.viewId);
// It's by design that IDs removed from the model are also removed
// from the list of rea... | {
} | identifier_body |
unread.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { EventEmitter } from 'events';
import { LocalDataService } from '../services/local-data.service';
import { ApplicationViewModel, ListBody, ListPageViewModel } from '../services/viewmodel.types';
import { DataService } fro... | (): Observable<UnreadStats> {
return this.getDataWithUnreadStatus().map((appViewModel: ApplicationViewModel) => {
const stats: UnreadStats = {changes: 0, messages: 0};
const changesPages = appViewModel.pages.filter((page) => page.viewId == 'page:changes');
if (changesPages.length == 1) {
c... | getUnreadStats | identifier_name |
unread.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { EventEmitter } from 'events';
import { LocalDataService } from '../services/local-data.service';
import { ApplicationViewModel, ListBody, ListPageViewModel } from '../services/viewmodel.types';
import { DataService } fro... |
});
}
}
| {
item.unread = !readIds.has(item.viewId);
} | conditional_block |
Cmd.js | var _ = require( "underscore" );
var Cmd = function (def) {
this.options = {};
this.def = def;
};
Cmd.prototype.ext = function(impl) {
if( !impl ) {
console.error( "couldn't extend command-implementation. because passed param:ext is NULL/undefined." );
return null;
}
this.exec = i... |
return;
}
};
Cmd.prototype.configure = function() {
console.log("skip cmd.configure(): " + this.def.name);
}
Cmd.prototype.exec = function () {
console.log("skip cmd.exec(): " + this.def.name);
};
exports.create = function (def) {
def.module = modulePath(def);
console.log("load comma... | this.config = require( path );
this.configure();
} catch( err ) {
console.error("for command '" + this.def.name + "' configuration is broken" );
console.error(err); | random_line_split |
Cmd.js | var _ = require( "underscore" );
var Cmd = function (def) {
this.options = {};
this.def = def;
};
Cmd.prototype.ext = function(impl) {
if( !impl ) {
console.error( "couldn't extend command-implementation. because passed param:ext is NULL/undefined." );
return null;
}
this.exec = i... |
});
return path;
};
Cmd.prototype.loadConfig = function() {
this.config = {};
var path = this.configPath(this.def);
if( !path ) {
console.log("couldn't load toolset-configuration.");
return;
}
console.log( "-- use toolset-config-path :" + path );
try {
this.... | {
path = selected.absolutePath;
} | conditional_block |
suggestions.js | var clientElasticsearch = require("../../../Elasticsearch/ElasticsearchClient");
var ElasticsearchParser = require("../../../Elasticsearch/ElasticsearchParser");
var Q = require('q');
| "index":"source",
"type":"zabbix_host",
"body":{
"query" : {
"term": { "haveMapping" : false}
},
"fields" : ["id","hostname"]
},
"from":0,
"size":999999999,
"scroll" : "1m"
}).then(function(body){
// Récuparation de la recherche en liste
return ElasticsearchParser.loadFromBodyFields(body... | var getSuggestions=function(){
return clientElasticsearch.search({ | random_line_split |
resize.js | var Rect = require("utils/rect");
/** Resize a window
*
* @param options Options for resize
* @param callback
*/
function resize(options,callback) {
var winId = options.window.id,
info = options.updateInfo,
os = options.os,
updateInfo = {};... |
lastSize = new Rect();
chrome.windows.update(winId, updateInfo , checker);
};
module.exports = resize;
| { // Check is the resize frozen?
chrome.windows.get(winId,function(result) {
newSize = new Rect(result);
// console.log("checker",winId,lastSize,newSize,targetSize);
if (lastSize.equal(newSize) || newSize.equal(targetSize)) {
// Done!
if (callback)
callback(result);
} else {
... | identifier_body |
resize.js | var Rect = require("utils/rect");
/** Resize a window
*
* @param options Options for resize
* @param callback
*/
function resize(options,callback) {
var winId = options.window.id,
info = options.updateInfo,
os = options.os,
updateInfo = {};... | (winId,updateInfo,callback){
var lastSize = new Rect();
var newSize = new Rect();
var targetSize = new Rect(updateInfo);
function checker() { // Check is the resize frozen?
chrome.windows.get(winId,function(result) {
newSize = new Rect(result);
// console.log("checker",winId,lastSize,newSize,targetSi... | _resizeOnLinux | identifier_name |
resize.js | var Rect = require("utils/rect");
/** Resize a window
*
* @param options Options for resize
* @param callback
*/
function resize(options,callback) {
var winId = options.window.id,
info = options.updateInfo,
os = options.os,
updateInfo = {};... |
updateInfo.state = "normal";
/* Remarks:
*
* Sometimes Chrome on Ubuntu/Unity may not report the current state correctly.
* So set to "normal" by default. Otherwise, it may not be able to resize maximized window
*
*/
if (os == "MacOS") {
delete updateInfo.state; // Don't set no... | random_line_split | |
resize.js | var Rect = require("utils/rect");
/** Resize a window
*
* @param options Options for resize
* @param callback
*/
function resize(options,callback) {
var winId = options.window.id,
info = options.updateInfo,
os = options.os,
updateInfo = {};... |
if (os == "Linux") {
_resizeOnLinux(winId,updateInfo,callback);
} else {
chrome.windows.update(winId, updateInfo , callback);
}
}
/** A special resize function for Linux due to the #72369 bug for Chrome on Linux
*
*/
function _resizeOnLinux(winId,updateInfo,callback){
va... | {
delete updateInfo.state; // Don't set normal in MacOS. The animation will be mad
} | conditional_block |
express.js | var express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
compress = require('compression'),
methodOverride = require('method-override'),
config = require('./config'),
path = require('path');
| res.locals.url = req.protocol + ':// ' + req.headers.host + req.url;
next();
});
app.use(compress({
filter: function (req, res) {
return (/json|text/).test(res.getHeader('Content-Type'));
},
level: 9
}));
// Showing stack errors
app.set('showStac... | module.exports = function () {
var app = express();
app.use(function (req, res, next) { | random_line_split |
delete.js | module.exports = require('eden-class').extend(function() {
/* Require
-------------------------------*/
/* Constants
-------------------------------*/
/* Public.Properties
-------------------------------*/
/* Protected Properties
-------------------------------*/
this._table = null;
this._where = [];
/* ... |
};
/* Public.Methods
-------------------------------*/
/**
* Set the table name in which you want to delete from
*
* @param string name
* @return this
*/
this.setTable = function(table) {
//argument test
this.argument().test(1, 'string');
this._table = table;
return this;
};
/**
* Ret... | {
this.setTable(table);
} | conditional_block |
delete.js | module.exports = require('eden-class').extend(function() {
/* Require
-------------------------------*/
/* Constants
-------------------------------*/
/* Public.Properties
-------------------------------*/
/* Protected Properties
-------------------------------*/
this._table = null;
this._where = [];
/* ... | *
* @param array|string where
* @return this
* @notes loads a where phrase into registry
*/
this.where = function(where) {
//Argument 1 must be a string or array
this.argument().test(1, 'string', 'array');
if(typeof where === 'string') {
where = [where];
}
this._where = this._where.concat(... | /**
* Where clause | random_line_split |
home.js | -- Global Variables -- //
$(function() {
// -- Auth Triggers & Functions -- //
var google_SignIn = function() {
hello.login("google", {
force: false, display : (singlePage || global.flags.page()) ? "page" : "popup",
scope : encodeURIComponent(GOOGLE_SCOPES.join(" ")),
}).then(function(a) {
global.flag... | }
var google_LoggedIn = function(auth) {
if (!global.google) {
// -- Load Customised Settings -- //
global.editor.loadSettings();
// -- Initialise Google Provider -- //
global.google = Google().initialise(auth.access_token, auth.token_type, auth.expires,
(function(s) {
return functio... | return session && session.access_token && new Date(session.expires * 1000) >= new Date();
};
var github_LoggedIn = function(auth) {
global.github = Github().initialise(auth.access_token, auth.token_type, auth.expires); | random_line_split |
home.js | -- Global Variables -- //
$(function() {
// -- Auth Triggers & Functions -- //
var google_SignIn = function() {
hello.login("google", {
force: false, display : (singlePage || global.flags.page()) ? "page" : "popup",
scope : encodeURIComponent(GOOGLE_SCOPES.join(" ")),
}).then(function(a) {
global.flag... | else {
resolve();
}
}, function(err) {reject(err)});
});
}
})(encodeURIComponent(GOOGLE_SCOPES.join(" ")))
);
// -- Get User Info for Display -- //
global.google.me().then(function(user) {
// -- Variables for Display -- //
var n = user.name, e = user.email;
... | {
resolve({
token : r.authResponse.access_token,
type : r.authResponse.token_type,
expires : r.authResponse.expires,
});
} | conditional_block |
SourceCode.tsx | import * as React from 'react';
import { highlight } from '../../utils';
import { SampleControls, SampleControlsWrap, StyledPre } from '../../common-elements';
import { CopyButtonWrapper } from '../../common-elements/CopyButtonWrapper';
export interface SourceCodeProps {
source: string;
lang: string;
}
export cl... |
}
| {
return (
<CopyButtonWrapper data={this.props.source}>
{({ renderCopyButton }) => (
<SampleControlsWrap>
<SampleControls>{renderCopyButton()}</SampleControls>
<SourceCode lang={this.props.lang} source={this.props.source} />
</SampleControlsWrap>
)}
... | identifier_body |
SourceCode.tsx | import * as React from 'react';
import { highlight } from '../../utils';
import { SampleControls, SampleControlsWrap, StyledPre } from '../../common-elements';
import { CopyButtonWrapper } from '../../common-elements/CopyButtonWrapper';
export interface SourceCodeProps {
source: string;
lang: string;
}
export cl... | () {
return (
<CopyButtonWrapper data={this.props.source}>
{({ renderCopyButton }) => (
<SampleControlsWrap>
<SampleControls>{renderCopyButton()}</SampleControls>
<SourceCode lang={this.props.lang} source={this.props.source} />
</SampleControlsWrap>
... | render | identifier_name |
SourceCode.tsx | import * as React from 'react';
import { highlight } from '../../utils';
import { SampleControls, SampleControlsWrap, StyledPre } from '../../common-elements';
import { CopyButtonWrapper } from '../../common-elements/CopyButtonWrapper';
export interface SourceCodeProps {
source: string;
lang: string;
}
export cl... | const { source, lang } = this.props;
return <StyledPre dangerouslySetInnerHTML={{ __html: highlight(source, lang) }} />;
}
}
export class SourceCodeWithCopy extends React.Component<SourceCodeProps> {
render() {
return (
<CopyButtonWrapper data={this.props.source}>
{({ renderCopyButton }) ... | random_line_split | |
Time.js | {
d -= 36e5;
}
} else {
d = new this.Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
}
return d;... | minDate, | random_line_split | |
Time.js | in to
* handle Jalali dates.
*
* @type {*}
* @since 4.0.4
* @product highcharts highstock gantt
* @apioption time.Date
*/
/**
* A callback to return the time zone offset for a given datetime. It
* takes the timestamp in terms of milliseconds since January 1 ... |
},
/**
* Make a time and returns milliseconds. Interprets the inputs as UTC time,
* local time or a specific timezone time depending on the current time
* settings.
*
* @function Highcharts.Time#makeTime
*
* @param {number} year
* The year
*
* @param {... | {
this.get = function (unit, date) {
return date['get' + unit]();
};
this.set = function (unit, date, value) {
return date['set' + unit](value);
};
} | conditional_block |
DataCryptMock.ts | import { User } from "./Api";
import { IDataCrypt } from "./DataCrypt";
import assert from "assert";
const prefix = "encrypted:";
// Mocking DataCrypt with simple encryption since jest testing does not support crypt functions yet
export class DataCryptMock implements IDataCrypt {
public async expandPassword(user: U... | (
wrappedDek: string,
user: User
): Promise<CryptoKey> {
assert(
wrappedDek.length > 0 &&
wrappedDek === prefix + user.username + user.password
);
return (prefix + user.username + user.password) as any;
}
public async encryptText(text: string, dek: CryptoKey): Promise<string> {
... | unwrapDataEncryptionKey | identifier_name |
DataCryptMock.ts | import { User } from "./Api";
import { IDataCrypt } from "./DataCrypt";
import assert from "assert";
const prefix = "encrypted:";
// Mocking DataCrypt with simple encryption since jest testing does not support crypt functions yet
export class DataCryptMock implements IDataCrypt {
public async expandPassword(user: U... |
private reverseString(text: string) {
return text.split("").reverse().join("");
}
}
| {
const dekText = dek as any as string;
assert(dekText.length > 0);
return this.reverseString(encryptedText.substring(dekText.length));
} | identifier_body |
DataCryptMock.ts | import { User } from "./Api";
import { IDataCrypt } from "./DataCrypt";
import assert from "assert";
const prefix = "encrypted:";
// Mocking DataCrypt with simple encryption since jest testing does not support crypt functions yet
export class DataCryptMock implements IDataCrypt {
public async expandPassword(user: U... | return text.split("").reverse().join("");
}
} | random_line_split | |
jinja_helpers.py | from allauth.account.utils import user_display
from allauth.socialaccount import providers
from allauth.socialaccount.templatetags.socialaccount import get_providers
from allauth.utils import get_request_param
from django.conf import settings
from django.contrib import admin
from django.utils.translation import ugettex... |
@library.global_function
def admin_link(user):
"""Returns a link to admin a user"""
url = reverse('admin:users_user_change', args=(user.id,),
current_app=admin.site.name)
link = ('<a href="%s" class="button neutral">%s'
'<i aria-hidden="true" class="icon-wrench"></i></a>' %
... | """Returns a link to ban a user"""
link = ''
if ban_user.id != banner_user.id and banner_user.has_perm('users.add_userban'):
active_ban = ban_user.active_ban
if active_ban:
url = reverse('admin:users_userban_change', args=(active_ban.id,))
title = ugettext('Banned on %(ba... | identifier_body |
jinja_helpers.py | from allauth.account.utils import user_display
from allauth.socialaccount import providers
from allauth.socialaccount.templatetags.socialaccount import get_providers
from allauth.utils import get_request_param
from django.conf import settings
from django.contrib import admin
from django.utils.translation import ugettex... | (context):
"""
{{ providers_media_js() }}
"""
request = context['request']
return Markup(u'\n'.join([p.media_js(request)
for p in providers.registry.get_list()]))
@library.global_function
def social_accounts(user):
"""
{% set accounts = social_accounts(user) %}... | providers_media_js | identifier_name |
jinja_helpers.py | from allauth.account.utils import user_display
from allauth.socialaccount import providers
from allauth.socialaccount.templatetags.socialaccount import get_providers
from allauth.utils import get_request_param
from django.conf import settings
from django.contrib import admin
from django.utils.translation import ugettex... |
for account in user.socialaccount_set.all().iterator():
providers = accounts.setdefault(account.provider, [])
providers.append(account)
return accounts
@library.global_function
@library.render_with('honeypot/honeypot_field.html')
def honeypot_field(field_name=None):
return render_honeypot... | return accounts | conditional_block |
jinja_helpers.py | from allauth.account.utils import user_display
from allauth.socialaccount import providers
from allauth.socialaccount.templatetags.socialaccount import get_providers
from allauth.utils import get_request_param
from django.conf import settings
from django.contrib import admin
from django.utils.translation import ugettex... | 'ban_admin': active_ban.by,
}
link = ('<a href="%s" class="button ban-link" title="%s">%s'
'<i aria-hidden="true" class="icon-ban"></i></a>'
% (url, title, ugettext('Banned')))
else:
url = reverse('users.ban_user', kwarg... | random_line_split | |
monitorCodeUse.js | /**
* Copyright 2014 Facebook, Inc.
*
* 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 agreed to ... | (eventName, data) {
(require('./React').__DEV__ === true ? invariant(
eventName && !/[^a-z0-9_]/.test(eventName),
'You must provide an eventName using only the characters [a-z0-9_]'
) : invariant(eventName && !/[^a-z0-9_]/.test(eventName)));
}
module.exports = monitorCodeUse;
| monitorCodeUse | identifier_name |
monitorCodeUse.js | /**
* Copyright 2014 Facebook, Inc.
*
* 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 agreed to ... | * See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule monitorCodeUse
*/
"use strict";
var invariant = require("./invariant");
/**
* Provides open-source compatible instrumentation for monitoring certain API
* uses before we're ready to issue... | random_line_split | |
monitorCodeUse.js | /**
* Copyright 2014 Facebook, Inc.
*
* 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 agreed to ... |
module.exports = monitorCodeUse;
| {
(require('./React').__DEV__ === true ? invariant(
eventName && !/[^a-z0-9_]/.test(eventName),
'You must provide an eventName using only the characters [a-z0-9_]'
) : invariant(eventName && !/[^a-z0-9_]/.test(eventName)));
} | identifier_body |
SearchOutlined.js | import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4... | }), 'SearchOutlined'); | random_line_split | |
data.rs | use std::fmt;
use std::rc::Rc;
use builtins::BuiltinFn;
use lambda::Lambda;
use scope::RcScope;
#[derive(Debug, PartialEq)]
pub enum Token
{
Lparen,
Rparen,
Quote,
Number(f64),
Ident(String),
String(String),
Error(ParseError),
End, // end of string
}
#[derive(Debug, Clone, PartialEq... | Cons{ ref car, cdr: List::Node(ref next) } => write!(f, "{} {}", car, next),
Cons{ ref car, cdr: List::End } => write!(f, "{}", car),
}
}
}
#[derive(Debug, PartialEq)]
pub enum ParseError
{
UnclosedString,
InvalidNumber,
UnclosedList,
UnexpectedRparen,
NoQuoteArg... | impl fmt::Display for Cons
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
match *self { | random_line_split |
data.rs | use std::fmt;
use std::rc::Rc;
use builtins::BuiltinFn;
use lambda::Lambda;
use scope::RcScope;
#[derive(Debug, PartialEq)]
pub enum Token
{
Lparen,
Rparen,
Quote,
Number(f64),
Ident(String),
String(String),
Error(ParseError),
End, // end of string
}
#[derive(Debug, Clone, PartialEq... |
{
Nil,
Bool(bool),
Number(f64),
Symbol(Rc<String>),
String(Rc<String>),
Builtin(Rc<BuiltinFn>),
Lambda(Rc<Lambda>),
List(List),
}
impl fmt::Display for Value
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
match *self {
Value::Nil => write!(f, "nil"... | Value | identifier_name |
tutorial-05.rs | #[macro_use]
extern crate glium;
fn main() {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new();
let display = glium::Display::new(wb, cb, &event_loo... | std::time::Duration::from_nanos(16_666_667);
*control_flow = glutin::event_loop::ControlFlow::WaitUntil(next_frame_time);
match event {
glutin::event::Event::WindowEvent { event, .. } => match event {
glutin::event::WindowEvent::CloseRequested => {
... |
let mut t = -0.5;
event_loop.run(move |event, _, control_flow| {
let next_frame_time = std::time::Instant::now() + | random_line_split |
tutorial-05.rs | #[macro_use]
extern crate glium;
fn | () {
#[allow(unused_imports)]
use glium::{glutin, Surface};
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
let cb = glutin::ContextBuilder::new();
let display = glium::Display::new(wb, cb, &event_loop).unwrap();
#[derive(Copy, Clone)]
... | main | identifier_name |
htmlreader.py | # Copyright 2008-2014 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | if self.current_row is None:
self.tr_start()
self.current_cell = []
def td_end(self):
if self.current_cell is not None and self.state != self.IGNORE:
cell = ''.join(self.current_cell)
self.current_row.append(cell)
self.current_cell = None
def... | self.current_row = None
def td_start(self, attrs=None):
if self.current_cell is not None:
self.td_end() | random_line_split |
htmlreader.py | # Copyright 2008-2014 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
def _get_encoding_from_meta(self, attrs):
valid_http_equiv = False
encoding = None
for name, value in attrs:
name = name.lower()
if name == 'charset': # html5
return value
if name == 'http-equiv' and value.lower() == 'content-type':
... | self._encoding = encoding | conditional_block |
htmlreader.py | # Copyright 2008-2014 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
def td_start(self, attrs=None):
if self.current_cell is not None:
self.td_end()
if self.current_row is None:
self.tr_start()
self.current_cell = []
def td_end(self):
if self.current_cell is not None and self.state != self.IGNORE:
cell = ''.j... | if self.current_row is None:
return
if self.current_cell is not None:
self.td_end()
if self.state == self.INITIAL:
accepted = self.populator.start_table(self.current_row)
self.state = self.PROCESS if accepted else self.IGNORE
elif self.state == sel... | identifier_body |
htmlreader.py | # Copyright 2008-2014 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | (self, htmlfile, populator):
self.populator = populator
self.state = self.IGNORE
self.current_row = None
self.current_cell = None
for line in htmlfile.readlines():
self.feed(self._decode(line))
# Calling close is required by the HTMLParser but may cause proble... | read | identifier_name |
game.rs | c_serialize;
use std::collections::VecDeque;
use std::fmt;
use ai::Ai;
use turn::Turn;
use turn::Direction;
use board::Board;
use board5::Board5;
use board_naive::NaiveBoard;
use piece::Player;
use piece::Stone;
use piece::Piece;
use point::Point;
#[derive(Clone, Debug, RustcDecodable, RustcEncodable)]
pub struct Gam... |
pub fn size(&self) -> usize {
self.board.size()
}
pub fn to_string(&self) -> String {
self.board.to_string()
}
pub fn play_simple(&mut self, turn: &str) -> Result<Option<Player>, String> {
let player = if self.history.len() % 2 == 0 {
Player::One
} else... | {
self.check_road_winner().or(self.check_flat_winner())
} | identifier_body |
game.rs | rustc_serialize;
use std::collections::VecDeque;
use std::fmt;
use ai::Ai;
use turn::Turn;
use turn::Direction;
use board::Board;
use board5::Board5;
use board_naive::NaiveBoard;
use piece::Player;
use piece::Stone;
use piece::Piece;
use point::Point;
#[derive(Clone, Debug, RustcDecodable, RustcEncodable)]
pub struc... | else {
Some(player.other())
};
self.play(turn, player, owner)
}
pub fn play(&mut self, turn: &str, player: Player, owner: Option<Player>) -> Result<Option<Player>, String> {
if self.next != player {
return Err("Not your turn".into());
}
match tur... | {
Some(player)
} | conditional_block |
game.rs | rustc_serialize;
use std::collections::VecDeque;
use std::fmt;
use ai::Ai;
use turn::Turn;
use turn::Direction;
use board::Board;
use board5::Board5;
use board_naive::NaiveBoard;
use piece::Player;
use piece::Stone;
use piece::Piece;
use point::Point;
#[derive(Clone, Debug, RustcDecodable, RustcEncodable)]
pub struc... | history: vec![],
}
}
pub fn turn_number(&self) -> usize {
self.history.len()
}
pub fn predict(&self, ai: Ai) -> Turn {
ai.next_move(self.turn_number(), &self.board)
}
fn check_winner(&self) -> Option<Player> {
self.check_road_winner().or(self.check_... | random_line_split | |
game.rs | rustc_serialize;
use std::collections::VecDeque;
use std::fmt;
use ai::Ai;
use turn::Turn;
use turn::Direction;
use board::Board;
use board5::Board5;
use board_naive::NaiveBoard;
use piece::Player;
use piece::Stone;
use piece::Piece;
use point::Point;
#[derive(Clone, Debug, RustcDecodable, RustcEncodable)]
pub struc... | (&mut self, turn: &str) -> Result<Option<Player>, String> {
let player = if self.history.len() % 2 == 0 {
Player::One
} else {
Player::Two
};
self.player_move(turn, player)
}
pub fn player_move(&mut self, turn: &str, player: Player) -> Result<Option<Playe... | play_simple | identifier_name |
Heuristic_Coeff.py | #-------------------------------------------------------------------------------
# Name: Heuristic_Coeff.py
# Purpose: Implements FIH algorithm found in "An Integer Linear Programming Scheme to Sanitize Sensitive Frequent Itemsets" by Kagklis et al.
# Author: Vasileios Kagklis
# Created: 20/03/2... | for i in xrange(lines):
for itemset in S:
if itemset.issubset(tid[i]):
sens_ind.append(i)
break
start_time = clock()
coeffs, rem = hcba_ext.calculateCoeffs(tid, sup, sens_ind, S, F, Rev_Fd)
# The initial objective => Elas... | random_line_split | |
Heuristic_Coeff.py | #-------------------------------------------------------------------------------
# Name: Heuristic_Coeff.py
# Purpose: Implements FIH algorithm found in "An Integer Linear Programming Scheme to Sanitize Sensitive Frequent Itemsets" by Kagklis et al.
# Author: Vasileios Kagklis
# Created: 20/03/2... |
###################################################
def Heuristic_Coeff_main(fname1, fname2, fname3, sup, mod_name):
change_raw_data = 0
L = []
solution = None
k =0
# Read dataset and identify discrete items
lines, tid = myiolib.readDataset(fname3)
I = hcba_ext.get_1itemsets(... | result = []
for itemset in rev_fd:
for item in itemset:
if isinstance(item, float):
temp = itemset - frozenset([item])
result.append(temp)
return(result) | identifier_body |
Heuristic_Coeff.py | #-------------------------------------------------------------------------------
# Name: Heuristic_Coeff.py
# Purpose: Implements FIH algorithm found in "An Integer Linear Programming Scheme to Sanitize Sensitive Frequent Itemsets" by Kagklis et al.
# Author: Vasileios Kagklis
# Created: 20/03/2... |
if flag:
result.append(S[i])
if len(result) == 0:
return(S)
else:
return(result)
###################################################
def convert2frozen(rev_fd):
result = []
for itemset in rev_fd:
for item in itemset:
... | if i == j:
continue
if len(S[i]) >= len(S[j]) and S[i].issuperset(S[j]):
flag = False
break
elif len(S[i]) < len(S[j]) and S[i].issubset(S[j]):
flag = True
elif len(S[i]) == len(S[j]):
flag = True | conditional_block |
Heuristic_Coeff.py | #-------------------------------------------------------------------------------
# Name: Heuristic_Coeff.py
# Purpose: Implements FIH algorithm found in "An Integer Linear Programming Scheme to Sanitize Sensitive Frequent Itemsets" by Kagklis et al.
# Author: Vasileios Kagklis
# Created: 20/03/2... | (rev_fd):
result = []
for itemset in rev_fd:
for item in itemset:
if isinstance(item, float):
temp = itemset - frozenset([item])
result.append(temp)
return(result)
###################################################
def Heuristic_Coeff_main(fname1, fnam... | convert2frozen | identifier_name |
passport.js | var mongoose = require('mongoose');
var User = mongoose.model('User');
// Estrategia de autenticación con Twitter
var TwitterStrategy = require('passport-twitter').Strategy;
// Estrategia de autenticación con Facebook
var FacebookStrategy = require('passport-facebook').Strategy;
// Fichero de configuración donde se enc... | passport.use(new TwitterStrategy({
consumerKey : config.twitter.key,
consumerSecret : config.twitter.secret,
callbackURL : '/auth/twitter/callback'
}, function(accessToken, refreshToken, profile, done) {
// Busca en la base de datos si el usuario ya se autenticó en otro
// momento y ya está almacenado e... | });
// Configuración del autenticado con Twitter | random_line_split |
client.rs | // This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
use futures::{Future, IntoFuture, Poll, Sink, StartSend, Stream};
use std::io::{Error, Result};
use std::net::Shutdow... |
pub fn new(inner: UnixStream) -> Self {
Authenticator { inner: inner.framed(AuthCodec) }
}
pub fn into_inner(self) -> UnixStream {
self.inner.into_inner()
}
pub fn into_bus(self) -> Bus {
Bus::new(self.into_inner())
}
pub fn prime(self) -> impl Future<Item = Self... | {
UnixStream::connect(path, handle)
.into_future()
.map(Self::new)
.and_then(Self::prime)
} | identifier_body |
client.rs | // This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
use futures::{Future, IntoFuture, Poll, Sink, StartSend, Stream};
use std::io::{Error, Result};
use std::net::Shutdow... | (&mut self, cmd: Self::Out, buf: &mut Vec<u8>) -> Result<()> {
commands::encode_client_cmd(&cmd, buf);
Ok(())
}
}
| encode | identifier_name |
client.rs | // This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
use futures::{Future, IntoFuture, Poll, Sink, StartSend, Stream};
use std::io::{Error, Result};
use std::net::Shutdow... |
pub fn into_inner(self) -> UnixStream {
self.inner.into_inner()
}
pub fn into_bus(self) -> Bus {
Bus::new(self.into_inner())
}
pub fn prime(self) -> impl Future<Item = Self, Error = Error> {
io::write_all(self.into_inner(), [0]).map(|(inner, _)| Authenticator::new(inner))
... | Authenticator { inner: inner.framed(AuthCodec) }
} | random_line_split |
seq.rs | use num::{One, Zero};
#[cfg(feature = "afserde")]
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::fmt;
use super::util::IndexableType;
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
#[repr(C... | (&self) -> T {
self.step
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "afserde")]
#[test]
fn seq_serde() {
use super::Seq;
use crate::seq;
// ANCHOR: seq_json_serde_snippet
let original = seq!(1:2:1);
let serd = match serde_json::to_string(&original) {
... | step | identifier_name |
seq.rs | use num::{One, Zero};
#[cfg(feature = "afserde")]
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::fmt;
use super::util::IndexableType;
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
#[repr(C... |
}
/// Enables use of `Seq` with `{}` format in print statements
impl<T> fmt::Display for Seq<T>
where
T: fmt::Display + IndexableType,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"[begin: {}, end: {}, step: {}]",
self.begin, self.end, self.st... | {
Self {
begin: One::one(),
end: One::one(),
step: Zero::zero(),
}
} | identifier_body |
seq.rs | use num::{One, Zero};
#[cfg(feature = "afserde")]
use serde::{Deserialize, Serialize};
use std::default::Default;
use std::fmt;
use super::util::IndexableType;
/// Sequences are used for indexing Arrays
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
#[repr(C... | /// Get step size of Seq
pub fn step(&self) -> T {
self.step
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "afserde")]
#[test]
fn seq_serde() {
use super::Seq;
use crate::seq;
// ANCHOR: seq_json_serde_snippet
let original = seq!(1:2:1);
let serd ... | /// Get end index of Seq
pub fn end(&self) -> T {
self.end
}
| random_line_split |
expo-constants_v4.x.x.js | declare module 'expo-constants' {
declare export type AppOwnership = 'standalone' | 'expo' | 'guest';
declare export type UserInterfaceIdiom = 'handset' | 'tablet' | 'unsupported';
declare export type IOSManifest = {
buildNumber: string,
platform: string,
model: string,
userInterfaceIdiom: UserI... | dev?: boolean,
strict?: boolean,
minify?: boolean,
urlType?: string,
urlRandomness?: string,
lanType?: string,
...
},
xde?: boolean,
developer?: { tool?: string, ... },
bundleUrl: string,
debuggerHost?: string,
mainModuleName?: string,
logUrl?: strin... | },
loading?: { icon?: string, ... },
entryPoint?: string,
packagerOpts?: {
hostType?: string, | random_line_split |
transfer_encoding.rs | use header::Encoding;
header! {
#[doc="`Transfer-Encoding` header, defined in"]
#[doc="[RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.1)"]
#[doc=""] | #[doc="will be) applied to the payload body in order to form the message"]
#[doc="body."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Transfer-Encoding = 1#transfer-coding"]
#[doc="```"]
(TransferEncoding, "Transfer-Encoding") => (Encoding)+
}
bench_header!(normal, TransferEncodi... | #[doc="The `Transfer-Encoding` header field lists the transfer coding names"]
#[doc="corresponding to the sequence of transfer codings that have been (or"] | random_line_split |
logdb_test.py | from diary import DiaryDB, Event
import unittest
import sqlite3
import os.path
class TestDiaryDB(unittest.TestCase):
TEMP_DB_PATH = os.path.join(os.path.dirname(__file__),
'testing_dir', 'temp.db')
SIMPLE_EVENT = Event("INFO", "LEVEL")
def setUp(self):
self.logdb ... | table = self.logdb.cursor.execute('''SELECT name FROM sqlite_master
WHERE type="table" AND name="logs"
''').fetchone()[0]
self.assertEquals(table, 'logs')
def test_creates_table_already_exists(self):
self... | self.assertIsInstance(self.logdb.conn, sqlite3.Connection)
self.assertIsInstance(self.logdb.cursor, sqlite3.Cursor)
def test_creates_table(self): | random_line_split |
logdb_test.py | from diary import DiaryDB, Event
import unittest
import sqlite3
import os.path
class TestDiaryDB(unittest.TestCase):
TEMP_DB_PATH = os.path.join(os.path.dirname(__file__),
'testing_dir', 'temp.db')
SIMPLE_EVENT = Event("INFO", "LEVEL")
def setUp(self):
self.logdb ... | (self):
self.assertIsInstance(self.logdb.conn, sqlite3.Connection)
self.assertIsInstance(self.logdb.cursor, sqlite3.Cursor)
def test_creates_table(self):
table = self.logdb.cursor.execute('''SELECT name FROM sqlite_master
WHERE type="table" AND n... | constructs_correctly | identifier_name |
logdb_test.py | from diary import DiaryDB, Event
import unittest
import sqlite3
import os.path
class TestDiaryDB(unittest.TestCase):
TEMP_DB_PATH = os.path.join(os.path.dirname(__file__),
'testing_dir', 'temp.db')
SIMPLE_EVENT = Event("INFO", "LEVEL")
def setUp(self):
self.logdb ... |
def test_creates_table_already_exists(self):
self.logdb.create_tables()
tables = self.logdb.cursor.execute('''SELECT name FROM sqlite_master
WHERE type="table" AND name="logs"
''').fetchall()
self.asse... | table = self.logdb.cursor.execute('''SELECT name FROM sqlite_master
WHERE type="table" AND name="logs"
''').fetchone()[0]
self.assertEquals(table, 'logs') | identifier_body |
logdb_test.py | from diary import DiaryDB, Event
import unittest
import sqlite3
import os.path
class TestDiaryDB(unittest.TestCase):
TEMP_DB_PATH = os.path.join(os.path.dirname(__file__),
'testing_dir', 'temp.db')
SIMPLE_EVENT = Event("INFO", "LEVEL")
def setUp(self):
self.logdb ... | unittest.main() | conditional_block | |
classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser.js | var classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser =
[ | [ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a4aec60f5df74f482b576f4e0dad0d5f6.html#a4aec60f5df74f482b576f4e0dad0d5f6", null ],
[ "Serialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a2362ae784859054bf5b9281dafeb37cd.html#a2362ae784859054bf5b9281dafeb37cd", null ],
[ ... | [ "Deserialize", "classCqrs_1_1MongoDB_1_1Serialisers_1_1TypeSerialiser_a5e8aa7ae1372033da215d02b79947b20.html#a5e8aa7ae1372033da215d02b79947b20", null ], | random_line_split |
Mongo.js | "use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(tar... | value: function moduleSetup() {
var self = this;
// Connect to the mongo db
var connect = Promise.promisify(mongodb.MongoClient.connect, { context: mongodb.MongoClient });
return connect(this.options.url, { promiseLibrary: Promise }).then(function (db) {
self._db = db;
});
}
/**
* Close the ... | */ | random_line_split |
Mongo.js | "use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(tar... |
_createClass(Mongo, [{
key: "moduleSetup",
/**
* Construct the Mongo extension
*/
value: function moduleSetup() {
var self = this;
// Connect to the mongo db
var connect = Promise.promisify(mongodb.MongoClient.connect, { context: mongodb.MongoClient });
return connect(this.options.url, { pro... | {
_classCallCheck(this, Mongo);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Mongo).apply(this, arguments));
} | identifier_body |
Mongo.js | "use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(tar... | (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "obje... | _classCallCheck | identifier_name |
ipython.py | # -*- coding: utf-8 -*-
#
# Copyright © 2011 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""IPython v0.11+ Plugin"""
from spyderlib.qt.QtGui import QHBoxLayout
# Local imports
from spyderlib.widgets.ipython import create_widget
from spyderlib.plu... | self):
"""
Return the widget to give focus to when
this plugin's dockwidget is raised on top-level
"""
return self.ipython_widget._control
def get_plugin_actions(self):
"""Return a list of actions related to plugin"""
return []
def reg... | et_focus_widget( | identifier_name |
ipython.py | # -*- coding: utf-8 -*-
#
# Copyright © 2011 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""IPython v0.11+ Plugin"""
from spyderlib.qt.QtGui import QHBoxLayout
# Local imports
from spyderlib.widgets.ipython import create_widget
from spyderlib.plu... |
#------ SpyderPluginWidget API ---------------------------------------------
def get_plugin_title(self):
"""Return widget title"""
return "IPython (%s) - Experimental!" % self.kernel_name
def get_focus_widget(self):
"""
Return the widget to give foc... | elf.dockwidget.setVisible(state)
| conditional_block |
ipython.py | # -*- coding: utf-8 -*-
#
# Copyright © 2011 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""IPython v0.11+ Plugin"""
from spyderlib.qt.QtGui import QHBoxLayout
# Local imports
from spyderlib.widgets.ipython import create_widget
from spyderlib.plu... | return True | random_line_split | |
ipython.py | # -*- coding: utf-8 -*-
#
# Copyright © 2011 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""IPython v0.11+ Plugin"""
from spyderlib.qt.QtGui import QHBoxLayout
# Local imports
from spyderlib.widgets.ipython import create_widget
from spyderlib.plu... |
def register_plugin(self):
"""Register plugin in Spyder's main window"""
self.main.add_dockwidget(self)
def refresh_plugin(self):
"""Refresh widget"""
pass
def closing_plugin(self, cancelable=False):
"""Perform actions before parent main ... | ""Return a list of actions related to plugin"""
return []
| identifier_body |
calc.py | from functools import reduce
# constants used in the multGF2 function
mask1 = mask2 = polyred = None
def setGF2(degree, irPoly):
"""Define parameters of binary finite field GF(2^m)/g(x)
- degree: extension degree of binary field
- irPoly: coefficients of irreducible polynomial g(x)
"""
def i... |
if __name__ == "__main__":
# Define binary field GF(2^3)/x^3 + x + 1
setGF2(127, 2**127 + 2**63 + 1)
# Evaluate the product (x^2 + x + 1)(x^2 + 1)
print("{:02x}".format(multGF2(0x3f7e0000000000000000000000000000L, 0x3f7e00000000000000000000L))) | """Multiply two polynomials in GF(2^m)/g(x)"""
p = 0
while p2:
if p2 & 1:
p ^= p1
p1 <<= 1
if p1 & mask1:
p1 ^= polyred
p2 >>= 1
return p & mask2 | identifier_body |
calc.py | from functools import reduce
# constants used in the multGF2 function
mask1 = mask2 = polyred = None
def setGF2(degree, irPoly):
"""Define parameters of binary finite field GF(2^m)/g(x)
- degree: extension degree of binary field
- irPoly: coefficients of irreducible polynomial g(x)
"""
def i... |
p2 >>= 1
return p & mask2
if __name__ == "__main__":
# Define binary field GF(2^3)/x^3 + x + 1
setGF2(127, 2**127 + 2**63 + 1)
# Evaluate the product (x^2 + x + 1)(x^2 + 1)
print("{:02x}".format(multGF2(0x3f7e0000000000000000000000000000L, 0x3f7e00000000000000000000L))) | p1 ^= polyred | conditional_block |
calc.py | from functools import reduce
# constants used in the multGF2 function
mask1 = mask2 = polyred = None
def setGF2(degree, irPoly):
"""Define parameters of binary finite field GF(2^m)/g(x)
- degree: extension degree of binary field
- irPoly: coefficients of irreducible polynomial g(x)
"""
def i... | """Convert an integer into a polynomial"""
return [(sInt >> i) & 1
for i in reversed(range(sInt.bit_length()))]
global mask1, mask2, polyred
mask1 = mask2 = 1 << degree
mask2 -= 1
polyred = reduce(lambda x, y: (x << 1) + y, i2P(irPoly)[1:])
def multGF2(p... | random_line_split | |
calc.py | from functools import reduce
# constants used in the multGF2 function
mask1 = mask2 = polyred = None
def | (degree, irPoly):
"""Define parameters of binary finite field GF(2^m)/g(x)
- degree: extension degree of binary field
- irPoly: coefficients of irreducible polynomial g(x)
"""
def i2P(sInt):
"""Convert an integer into a polynomial"""
return [(sInt >> i) & 1
for ... | setGF2 | identifier_name |
pio_uart_tx.py | # Example using PIO to create a UART TX interface
from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
UART_BAUD = 115200
PIN_BASE = 10
NUM_UARTS = 8
@asm_pio(sideset_init=PIO.OUT_HIGH, out_init=PIO.OUT_HIGH, out_shiftdir=PIO.SHIFT_RIGHT)
def uart_tx():
# fmt: off
# Block with TX deasserted un... |
# We can print characters from each UART by pushing them to the TX FIFO
def pio_uart_print(sm, s):
for c in s:
sm.put(ord(c))
# Print a different message from each UART
for i, u in enumerate(uarts):
pio_uart_print(u, "Hello from UART {}!\n".format(i))
| sm = StateMachine(
i, uart_tx, freq=8 * UART_BAUD, sideset_base=Pin(PIN_BASE + i), out_base=Pin(PIN_BASE + i)
)
sm.active(1)
uarts.append(sm) | conditional_block |
pio_uart_tx.py | # Example using PIO to create a UART TX interface
from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
UART_BAUD = 115200
PIN_BASE = 10
NUM_UARTS = 8
@asm_pio(sideset_init=PIO.OUT_HIGH, out_init=PIO.OUT_HIGH, out_shiftdir=PIO.SHIFT_RIGHT)
def uart_tx():
# fmt: off
# Block with TX deasserted un... | nop() .side(1) [6]
# fmt: on
# Now we add 8 UART TXs, on pins 10 to 17. Use the same baud rate for all of them.
uarts = []
for i in range(NUM_UARTS):
sm = StateMachine(
i, uart_tx, freq=8 * UART_BAUD, sideset_base=Pin(PIN_BASE + i), out_base=Pin(PIN_BASE + i)
)
sm.active(1)
... | # Shift out 8 data bits, 8 execution cycles per bit
label("bitloop")
out(pins, 1) [6]
jmp(x_dec, "bitloop")
# Assert stop bit for 8 cycles total (incl 1 for pull()) | random_line_split |
pio_uart_tx.py | # Example using PIO to create a UART TX interface
from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
UART_BAUD = 115200
PIN_BASE = 10
NUM_UARTS = 8
@asm_pio(sideset_init=PIO.OUT_HIGH, out_init=PIO.OUT_HIGH, out_shiftdir=PIO.SHIFT_RIGHT)
def uart_tx():
# fmt: off
# Block with TX deasserted un... |
# Print a different message from each UART
for i, u in enumerate(uarts):
pio_uart_print(u, "Hello from UART {}!\n".format(i))
| for c in s:
sm.put(ord(c)) | identifier_body |
pio_uart_tx.py | # Example using PIO to create a UART TX interface
from machine import Pin
from rp2 import PIO, StateMachine, asm_pio
UART_BAUD = 115200
PIN_BASE = 10
NUM_UARTS = 8
@asm_pio(sideset_init=PIO.OUT_HIGH, out_init=PIO.OUT_HIGH, out_shiftdir=PIO.SHIFT_RIGHT)
def | ():
# fmt: off
# Block with TX deasserted until data available
pull()
# Initialise bit counter, assert start bit for 8 cycles
set(x, 7) .side(0) [7]
# Shift out 8 data bits, 8 execution cycles per bit
label("bitloop")
out(pins, 1) [6]
jmp(x_dec, "bitloop")
# A... | uart_tx | identifier_name |
upload.controller.js | var path = require('path');
var Q = require('q');
var fs = require('fs');
var mv = require('mv');
var Upload = require('./upload.model');
exports.upload = function (req, res) {
var tmpPath = req.files[0].path;
var newFileName = Math.random().toString(36).substring(7)+path.extname(tmpPath);
var targetPath =... |
targetPath = targetPath.substring(targetPath.indexOf('upload'));
Upload.createUpload(targetPath).then(function(upload) {
defer.resolve(upload);
}, function(err) {
defer.reject(err);
});
});
defer.promise.then(function (upload) {
res.json... | {
return nextIteration.reject(err);
} | conditional_block |
upload.controller.js | var path = require('path');
var Q = require('q');
var fs = require('fs');
var mv = require('mv');
var Upload = require('./upload.model');
exports.upload = function (req, res) {
var tmpPath = req.files[0].path; | mv(tmpPath, targetPath, function (err) {
if (err) {
return nextIteration.reject(err);
}
targetPath = targetPath.substring(targetPath.indexOf('upload'));
Upload.createUpload(targetPath).then(function(upload) {
defer.resolve(upload);
}, function... | var newFileName = Math.random().toString(36).substring(7)+path.extname(tmpPath);
var targetPath = path.resolve(process.env.UPLOAD_PATH, newFileName);
var defer = Q.defer();
| random_line_split |
linux_net.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# <yamahata at valinux co jp>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with... |
port_no = _get_port_no(self.get_dev(network))
self.ryu_client.create_port(network['uuid'], self.datapath_id, port_no)
return ret
| def __init__(self):
super(LinuxOVSRyuInterfaceDriver, self).__init__()
LOG.debug('ryu rest host %s', FLAGS.linuxnet_ovs_ryu_api_host)
self.ryu_client = OFPClient(FLAGS.linuxnet_ovs_ryu_api_host)
self.datapath_id = _get_datapath_id(
FLAGS.linuxnet_ovs_integration_bridge)
... | identifier_body |
linux_net.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# <yamahata at valinux co jp>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with... |
LOG = logging.getLogger(__name__)
ryu_linux_net_opt = cfg.StrOpt('linuxnet_ovs_ryu_api_host',
default='127.0.0.1:8080',
help='Openflow Ryu REST API host:port')
FLAGS = flags.FLAGS
FLAGS.register_opt(ryu_linux_net_opt)
def _get_datapath_id(bridge_name):
... | from ryu.app.client import OFPClient | random_line_split |
linux_net.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# <yamahata at valinux co jp>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with... | (linux_net.LinuxOVSInterfaceDriver):
def __init__(self):
super(LinuxOVSRyuInterfaceDriver, self).__init__()
LOG.debug('ryu rest host %s', FLAGS.linuxnet_ovs_ryu_api_host)
self.ryu_client = OFPClient(FLAGS.linuxnet_ovs_ryu_api_host)
self.datapath_id = _get_datapath_id(
FL... | LinuxOVSRyuInterfaceDriver | identifier_name |
linux_net.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Isaku Yamahata <yamahata at private email ne jp>
# <yamahata at valinux co jp>
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with... |
def plug(self, network, mac_address, gateway=True):
LOG.debug("network %s mac_adress %s gateway %s",
network, mac_address, gateway)
ret = super(LinuxOVSRyuInterfaceDriver, self).plug(
network, mac_address, gateway)
port_no = _get_port_no(self.get_dev(network)... | for tables in [linux_net.iptables_manager.ipv4,
linux_net.iptables_manager.ipv6]:
tables['filter'].add_rule('FORWARD',
'--in-interface gw-+ --out-interface gw-+ -j DROP')
linux_net.iptables_manager.apply() | conditional_block |
learning_unit_specifications.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... |
def refresh_data(self):
language_iso = self.language[0]
texts_list = translated_text.search(entity=entity_name.LEARNING_UNIT_YEAR,
reference=self.learning_unit_year.id,
language=language_iso) \
.excl... | elf.learning_unit_year = learning_unit_year
self.language = language
self.refresh_data()
super(LearningUnitSpecificationsForm, self).__init__(*args, **kwargs)
| identifier_body |
learning_unit_specifications.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | value = translated_text.get_or_create(entity=entity_name.LEARNING_UNIT_YEAR,
reference=self.learning_unit_year.id,
language=self.language_iso,
text_label=self.text_label)
... | random_line_split | |
learning_unit_specifications.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | forms.Form):
learning_unit_year = language = None
def __init__(self, learning_unit_year, language, *args, **kwargs):
self.learning_unit_year = learning_unit_year
self.language = language
self.refresh_data()
super(LearningUnitSpecificationsForm, self).__init__(*args, **kwargs)
... | earningUnitSpecificationsForm( | identifier_name |
autocomplete-highlighters-accentfold.js | /*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 3.3.0
build: 3167
*/
YUI.add('autocomplete-highlighters-accentfold', function(Y) {
/**
* <p>
* Provides pre-built accent-folding result highlighters for AutoCom... | Y.mix(Y.namespace('AutoCompleteHighlighters'), {
/**
* Accent-folding version of <code>charMatch()</code>.
*
* @method charMatchFold
* @param {String} query Query to match
* @param {Array} results Results to highlight
* @return {Array} Highlighted results
* @static
*... | random_line_split | |
session.py | # Класс-помощник для работы с сессией
class SessionHelper:
def __init__(self, app):
self.app = app
# Функция входа на сайт
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_name("user").click()
wd.find_element_by_name... | conditional_block | ||
session.py | # Класс-помощник для работы с сессией
class SessionHelper:
def __init__(self, app):
self.app = app
# Функция входа на сайт
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_name("user").click()
wd.find_element_by_name... | стом "Logout", то пользователь вошел на сайт
return len(wd.find_elements_by_link_text("Logout")) > 0
# Функция проверки имени с которым произошел вход на сайт
def is_logged_in_as(self, username):
wd = self.app.wd
# Если на странице есть элемент с текстом который соответсвует имени польз... | f):
wd = self.app.wd
# Если на странице есть элемент с тек | identifier_body |
session.py | # Класс-помощник для работы с сессией
class SessionHelper:
def __init__(self, app): | self.app.open_home_page()
wd.find_element_by_name("user").click()
wd.find_element_by_name("user").clear()
wd.find_element_by_name("user").send_keys(username)
wd.find_element_by_name("pass").click()
wd.find_element_by_name("pass").clear()
wd.find_element_by_name("p... | self.app = app
# Функция входа на сайт
def login(self, username, password):
wd = self.app.wd | random_line_split |
session.py | # Класс-помощник для работы с сессией
class SessionHelper:
def __init__(self, app):
self.app = app
# Функция входа на сайт
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_name("user").click()
wd.find_element_by_name... | is_logged_in(self):
wd = self.app.wd
# Если на странице есть элемент с текстом "Logout", то пользователь вошел на сайт
return len(wd.find_elements_by_link_text("Logout")) > 0
# Функция проверки имени с которым произошел вход на сайт
def is_logged_in_as(self, username):
wd = self... | сайт
def | identifier_name |
hp_httpmanageable_mib.py | #
# Copyright (C) 2015 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | if isinstance(serial, bytes):
serial = serial.decode("utf-8")
defer.returnValue(serial) | conditional_block | |
hp_httpmanageable_mib.py | #
# Copyright (C) 2015 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | (MibRetriever):
"""HP-httpManageable-MIB (SEMI-MIB) MibRetriever"""
mib = get_mib('SEMI-MIB')
@defer.inlineCallbacks
def get_serial_number(self):
"""Tries to get a chassis serial number from old HP switches"""
serial = yield self.get_next('hpHttpMgSerialNumber')
if serial:
... | HPHTTPManageableMib | identifier_name |
hp_httpmanageable_mib.py | #
# Copyright (C) 2015 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details. You should have received a copy of the GNU General Public License
# along with NAV. If not, see <http://www.gnu.org/licenses/>.
#
from twisted.internet import defer
from nav.smidumps import get_mib
from nav.mibs.mibretriever import MibR... | # the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS | random_line_split |
hp_httpmanageable_mib.py | #
# Copyright (C) 2015 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | """HP-httpManageable-MIB (SEMI-MIB) MibRetriever"""
mib = get_mib('SEMI-MIB')
@defer.inlineCallbacks
def get_serial_number(self):
"""Tries to get a chassis serial number from old HP switches"""
serial = yield self.get_next('hpHttpMgSerialNumber')
if serial:
if isinstance... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.