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 |
|---|---|---|---|---|
date.rs | // Copyright 2016 LambdaStack 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 applicable law... |
fn update(&mut self, now: time::Timespec) {
self.amt = 0;
write!(LocalBuffer(self), "{}", time::at(now).rfc822()).unwrap();
self.next_update = now + Duration::seconds(1);
self.next_update.nsec = 0;
}
}
struct LocalBuffer<'a>(&'a mut LastRenderedNow);
impl<'a> fmt::Write for L... | {
str::from_utf8(&self.bytes[..self.amt]).unwrap()
} | identifier_body |
date.rs | // Copyright 2016 LambdaStack 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 applicable law... | (&self) -> &str {
str::from_utf8(&self.bytes[..self.amt]).unwrap()
}
fn update(&mut self, now: time::Timespec) {
self.amt = 0;
write!(LocalBuffer(self), "{}", time::at(now).rfc822()).unwrap();
self.next_update = now + Duration::seconds(1);
self.next_update.nsec = 0;
... | buffer | identifier_name |
date.rs | // Copyright 2016 LambdaStack 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 applicable law... |
f.write_str(cache.buffer())
})
}
}
impl LastRenderedNow {
fn buffer(&self) -> &str {
str::from_utf8(&self.bytes[..self.amt]).unwrap()
}
fn update(&mut self, now: time::Timespec) {
self.amt = 0;
write!(LocalBuffer(self), "{}", time::at(now).rfc822()).unwrap(... | {
cache.update(now);
} | conditional_block |
multiple-configs.ts | import { expectFileToExist } from '../../utils/fs';
import { ng } from '../../utils/process';
import { updateJsonFile } from '../../utils/project';
import { expectToFail } from '../../utils/utils'; | await updateJsonFile('angular.json', (workspaceJson) => {
const appArchitect = workspaceJson.projects['test-project'].architect;
// These are the default options, that we'll overwrite in subsequent configs.
// sourceMap defaults to true
appArchitect['build'] = {
...appArchitect['build'],
d... |
export default async function () { | random_line_split |
RxBaseClient.s-spec.ts | import "rxjs/add/operator/finally";
import { RxBaseClient } from "./RxBaseClient";
import proxyquire = require("proxyquire");
import { Subject } from "rxjs/Subject";
describe("RxBaseClient", () => {
let RxSocket;
let rxSocket;
let ClientConnector;
let clientConnector;
let client: RxBaseClient;
let socket;... |
expect(clientConnector.connect).toHaveBeenCalled();
});
});
}); | client = new RxBaseClientConstructor({ port: 1234 });
client.connect(); | random_line_split |
perf_http.py | #
# This file is part of Gruvi. Gruvi is free software available under the
# terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a
# complete list.
from __future__ import a... | (self):
transport = MockTransport()
protocol = HttpProtocol()
transport.start(protocol)
r = b'HTTP/1.1 200 OK\r\nContent-Length: 10000\r\n\r\n'
r += b'x' * 10000
reqs = 4 * r
nbytes = 0
t0 = t1 = time.time()
while t1 - t0 < 1.0:
protoco... | perf_parsing_speed | identifier_name |
perf_http.py | #
# This file is part of Gruvi. Gruvi is free software available under the
# terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a
# complete list.
from __future__ import a... | def perf_server_throughput(self):
server = HttpServer(hello_app)
server.listen(('localhost', 0))
addr = server.addresses[0]
client = HttpClient()
client.connect(addr)
nrequests = 0
pipeline = 10
t0 = t1 = time.time()
while t1 - t0 < 1.0:
... | random_line_split | |
perf_http.py | #
# This file is part of Gruvi. Gruvi is free software available under the
# terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a
# complete list.
from __future__ import a... |
if __name__ == '__main__':
unittest.defaultTestLoader.testMethodPrefix = 'perf'
unittest.main()
| server = HttpServer(hello_app)
server.listen(('localhost', 0))
addr = server.addresses[0]
client = HttpClient()
client.connect(addr)
nrequests = 0
pipeline = 10
t0 = t1 = time.time()
while t1 - t0 < 1.0:
for i in range(pipeline):
... | identifier_body |
perf_http.py | #
# This file is part of Gruvi. Gruvi is free software available under the
# terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2012-2014 the Gruvi authors. See the file "AUTHORS" for a
# complete list.
from __future__ import a... |
speed = nbytes / (t1 - t0) / (1024 * 1024)
self.add_result(speed)
def perf_server_throughput(self):
server = HttpServer(hello_app)
server.listen(('localhost', 0))
addr = server.addresses[0]
client = HttpClient()
client.connect(addr)
nrequests = 0
... | protocol.data_received(reqs)
del protocol._queue._heap[:]
nbytes += len(reqs)
t1 = time.time() | conditional_block |
project.config.ts | import { join } from 'path';
import { SeedConfig } from './seed.config';
// import { ExtendPackages } from './seed.config.interfaces';
/**
* This class extends the basic seed configuration, allowing for project specific overrides. A few examples can be found
* below.
*/
export class | extends SeedConfig {
PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');
constructor() {
super();
this.APP_TITLE = 'My Robinhood';
// this.GOOGLE_ANALYTICS_ID = 'Your site's ID';
/* Enable typeless compiler runs (faster) between typed compiler runs. *... | ProjectConfig | identifier_name |
project.config.ts | import { join } from 'path';
import { SeedConfig } from './seed.config';
// import { ExtendPackages } from './seed.config.interfaces';
/**
* This class extends the basic seed configuration, allowing for project specific overrides. A few examples can be found
* below.
*/
export class ProjectConfig extends SeedConfi... | defaultExtension: 'js'
}
}
];
this.addPackagesBundles(additionalPackages);
/* Add proxy middleware */
// this.PROXY_MIDDLEWARE = [
// require('http-proxy-middleware')('/api', { ws: false, target: 'http://localhost:3003' })
... | main: './index.js', | random_line_split |
ListUtils.ts | /**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/ |
const isChildOfBody = function (editor, elm) {
return editor.$.contains(editor.getBody(), elm);
};
const isTableCellNode = function (node) {
return node && /^(TH|TD)$/.test(node.nodeName);
};
const isListNode = function (editor) {
return function (node) {
return node && (/^(OL|UL|DL)$/).test(node.nodeName)... | */ | random_line_split |
EditableSlot.js | /**
* EditableSlot is an abstract class representing Slots that can have a value directly entered into them
* in addition to accepting Blocks.
* Subclasses must implement createInputSystem() and formatTextSummary()
* @param {Block} parent
* @param {string} key
* @param {number} inputType
* @param {number} snapTy... | this.changeText(this.dataToString(this.enteredData), updateDim);
};
/**
* Converts the Slot's data to a displayable string. Subclasses override this method to apply formatting.
* @param {Data} data
* @return {string}
*/
EditableSlot.prototype.dataToString = function(data) {
return data.asString().getValue();
};
... | if (data == null) return;
this.enteredData = data; | random_line_split |
EditableSlot.js | /**
* EditableSlot is an abstract class representing Slots that can have a value directly entered into them
* in addition to accepting Blocks.
* Subclasses must implement createInputSystem() and formatTextSummary()
* @param {Block} parent
* @param {string} key
* @param {number} inputType
* @param {number} snapTy... | (parent, key, inputType, snapType, outputType, data) {
Slot.call(this, parent, key, snapType, outputType);
this.inputType = inputType;
this.enteredData = data;
this.editing = false;
//TODO: make the slotShape be an extra argument
}
EditableSlot.prototype = Object.create(Slot.prototype);
EditableSlot.prototype.cons... | EditableSlot | identifier_name |
EditableSlot.js | /**
* EditableSlot is an abstract class representing Slots that can have a value directly entered into them
* in addition to accepting Blocks.
* Subclasses must implement createInputSystem() and formatTextSummary()
* @param {Block} parent
* @param {string} key
* @param {number} inputType
* @param {number} snapTy... |
EditableSlot.prototype = Object.create(Slot.prototype);
EditableSlot.prototype.constructor = EditableSlot;
EditableSlot.setConstants = function() {
/* The type of Data that can be directly entered into the Slot. */
EditableSlot.inputTypes = {};
EditableSlot.inputTypes.any = 0;
EditableSlot.inputTypes.num = 1;
Ed... | {
Slot.call(this, parent, key, snapType, outputType);
this.inputType = inputType;
this.enteredData = data;
this.editing = false;
//TODO: make the slotShape be an extra argument
} | identifier_body |
EditableSlot.js | /**
* EditableSlot is an abstract class representing Slots that can have a value directly entered into them
* in addition to accepting Blocks.
* Subclasses must implement createInputSystem() and formatTextSummary()
* @param {Block} parent
* @param {string} key
* @param {number} inputType
* @param {number} snapTy... |
};
/**
* Returns whether the Slot is being edited
* @return {boolean}
*/
EditableSlot.prototype.isEditing = function() {
return this.editing;
};
/**
* Assigns the Slot's Data and updates its text.w
* @param {Data} data - The Data to set to
* @param {boolean} sanitize - indicates whether the Data should be run... | {
this.setData(data, true, true); //Sanitize data, updateDims
this.slotShape.deselect();
this.editing = false;
SaveManager.markEdited();
} | conditional_block |
read.js | /* @flow */
'use strict'
/* ::
import type {CorsConfiguration} from '../../types.js'
*/
const projectMeta = require('../utils/project-meta.js')
const values = require('../values.js')
function | (
cwd /* : string */
) /* : Promise<CorsConfiguration | false> */ {
return projectMeta.read(cwd)
.then((config) => {
// Want to support two options here:
// 1. Falsey to disable CORS
if (!config.server || !config.server.cors) {
return false
}
// 2. Truthy to use default CO... | readCors | identifier_name |
read.js | /* @flow */
'use strict'
/* ::
import type {CorsConfiguration} from '../../types.js'
*/
const projectMeta = require('../utils/project-meta.js')
const values = require('../values.js')
function readCors (
cwd /* : string */
) /* : Promise<CorsConfiguration | false> */ {
return projectMeta.read(cwd)
.then((conf... |
// 2. Truthy to use default CORS and merge in any custom stuff
return Object.assign({
credentials: values.DEFAULT_CORS.CREDENTIALS,
exposedHeaders: values.DEFAULT_CORS.EXPOSED_HEADERS,
headers: values.DEFAULT_CORS.HEADERS,
maxAge: values.DEFAULT_CORS.MAX_AGE,
origins... | {
return false
} | conditional_block |
read.js | /* @flow */
'use strict'
/* ::
import type {CorsConfiguration} from '../../types.js'
*/ |
function readCors (
cwd /* : string */
) /* : Promise<CorsConfiguration | false> */ {
return projectMeta.read(cwd)
.then((config) => {
// Want to support two options here:
// 1. Falsey to disable CORS
if (!config.server || !config.server.cors) {
return false
}
// 2. Truthy... |
const projectMeta = require('../utils/project-meta.js')
const values = require('../values.js') | random_line_split |
read.js | /* @flow */
'use strict'
/* ::
import type {CorsConfiguration} from '../../types.js'
*/
const projectMeta = require('../utils/project-meta.js')
const values = require('../values.js')
function readCors (
cwd /* : string */
) /* : Promise<CorsConfiguration | false> */ |
module.exports = readCors
| {
return projectMeta.read(cwd)
.then((config) => {
// Want to support two options here:
// 1. Falsey to disable CORS
if (!config.server || !config.server.cors) {
return false
}
// 2. Truthy to use default CORS and merge in any custom stuff
return Object.assign({
... | identifier_body |
utils.py | import pygame, sys, random, math
from pygame.locals import *
import organisms
import globalVars
class Graphics:
def __init__(self):
self.screen = pygame.display.set_mode((1080, 820))
pygame.display.set_caption('Ecosystem Simulator')
class GUI:
def __init__(self):
self.sliderX = 150
... |
class World:
def __init__(self):
self.prey = []
self.predators = []
self.vegetation = []
self.water = []
self.shelter = []
self.time = 0
def addPrey(self, prey):
self.prey.append(prey)
def addVegetation(self, veg):
self.vegetation.append... | self.getTarget()
if self.target != False:
self.render() | identifier_body |
utils.py | import pygame, sys, random, math
from pygame.locals import *
import organisms
import globalVars
class Graphics:
def __init__(self):
self.screen = pygame.display.set_mode((1080, 820))
pygame.display.set_caption('Ecosystem Simulator')
class GUI:
def __init__(self):
self.sliderX = 150
... |
return inRadius
| inRadius.append(element2) | conditional_block |
utils.py | import pygame, sys, random, math
from pygame.locals import *
import organisms
import globalVars
class Graphics:
def __init__(self):
self.screen = pygame.display.set_mode((1080, 820))
pygame.display.set_caption('Ecosystem Simulator')
class GUI:
def __init__(self):
self.sliderX = 150
... | (self, veg):
self.vegetation.remove(veg)
def getDistance(self, element1, element2):
return math.hypot(element1.x - element2.x, element1.y - element2.y)
def collideByRadius(self, p1, p2):
dx = p1.x - p2.x
dy = p1.y - p2.y
distance = math.hypot(dx,... | removeVegetation | identifier_name |
utils.py | import pygame, sys, random, math
from pygame.locals import *
import organisms
import globalVars
class Graphics:
def __init__(self):
self.screen = pygame.display.set_mode((1080, 820))
pygame.display.set_caption('Ecosystem Simulator')
class GUI:
def __init__(self):
self.sliderX = 150
... | inRadius.append(element2)
return inRadius | random_line_split | |
TopicCommentItem.js | import React, { Component } from 'react';
import {
View,
Text,
Image,
StyleSheet,
Linking,
TouchableOpacity
} from 'react-native';
import HtmlRender from 'react-native-html-render';
import { parseImgUrl } from '../../utils';
import moment from 'moment';
class TopicCommentItem extends Component {
render()... | </View>
<View style={styles.dateWrapper}>
<Text style={styles.date}>
{date}
</Text>
</View>
</View>
<View style={styles.floorWrapper}>
<Text style={styles.floor}>
{floor}
</Text>
... | <View style={styles.usernameWrapper}>
<Text style={styles.username}>
{reply.member.username}
</Text> | random_line_split |
TopicCommentItem.js | import React, { Component } from 'react';
import {
View,
Text,
Image,
StyleSheet,
Linking,
TouchableOpacity
} from 'react-native';
import HtmlRender from 'react-native-html-render';
import { parseImgUrl } from '../../utils';
import moment from 'moment';
class TopicCommentItem extends Component {
render()... | </Text>
</View>
<View style={styles.dateWrapper}>
<Text style={styles.date}>
{date}
</Text>
</View>
</View>
<View style={styles.floorWrapper}>
<Text style={styles.floor}>
{floor}
... | {
const { reply, idx } = this.props;
const avatar = parseImgUrl(reply.member.avatar_normal);
const date = moment.unix(reply.created).fromNow();
const content = `<p>${reply.content_rendered}</p>`;
const floor = `#${idx + 1}`;
return (
<View style={styles.reply} key={reply.id}>
<Vie... | identifier_body |
TopicCommentItem.js | import React, { Component } from 'react';
import {
View,
Text,
Image,
StyleSheet,
Linking,
TouchableOpacity
} from 'react-native';
import HtmlRender from 'react-native-html-render';
import { parseImgUrl } from '../../utils';
import moment from 'moment';
class TopicCommentItem extends Component {
| () {
const { reply, idx } = this.props;
const avatar = parseImgUrl(reply.member.avatar_normal);
const date = moment.unix(reply.created).fromNow();
const content = `<p>${reply.content_rendered}</p>`;
const floor = `#${idx + 1}`;
return (
<View style={styles.reply} key={reply.id}>
<... | render | identifier_name |
scheduler.py | # coding=utf-8
import time
import math
import multiprocessing
import os
import random
import sys
import signal
try:
from setproctitle import getproctitle, setproctitle
except ImportError:
setproctitle = None
from diamond.utils.signals import signal_to_exception
from diamond.utils.signals import SIGALRMExcept... |
log.debug('Starting process %s', proc.name)
while(True):
metrics = metric_queue.get(block=True, timeout=None)
for metric in metrics:
for handler in handlers:
handler._process(metric)
for handler in handlers:
handler._flush()
| setproctitle('%s - %s' % (getproctitle(), proc.name)) | conditional_block |
scheduler.py | # coding=utf-8
import time
import math
import multiprocessing
import os
import random
import sys
import signal
try:
from setproctitle import getproctitle, setproctitle
except ImportError:
setproctitle = None
from diamond.utils.signals import signal_to_exception
from diamond.utils.signals import SIGALRMExcept... | proc = multiprocessing.current_process()
if setproctitle:
setproctitle('%s - %s' % (getproctitle(), proc.name))
log.debug('Starting process %s', proc.name)
while(True):
metrics = metric_queue.get(block=True, timeout=None)
for metric in metrics:
for handler in handlers:
... | identifier_body | |
scheduler.py | # coding=utf-8
import time
import math
import multiprocessing
import os
import random
import sys
import signal
try:
from setproctitle import getproctitle, setproctitle
except ImportError:
setproctitle = None
from diamond.utils.signals import signal_to_exception
from diamond.utils.signals import SIGALRMExcept... | (collector, metric_queue, log):
"""
"""
proc = multiprocessing.current_process()
if setproctitle:
setproctitle('%s - %s' % (getproctitle(), proc.name))
signal.signal(signal.SIGALRM, signal_to_exception)
signal.signal(signal.SIGHUP, signal_to_exception)
signal.signal(signal.SIGUSR2, ... | collector_process | identifier_name |
scheduler.py | # coding=utf-8
import time
import math
import multiprocessing
import os
import random
import sys
import signal
try:
from setproctitle import getproctitle, setproctitle
except ImportError:
setproctitle = None
from diamond.utils.signals import signal_to_exception
from diamond.utils.signals import SIGALRMExcept... | handler._flush() | for handler in handlers: | random_line_split |
index.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
/... | exports.BaseResource = msRestAzure.BaseResource;
exports.CloudError = msRestAzure.CloudError;
exports.PolicySku = require('./policySku');
exports.PolicyAssignment = require('./policyAssignment');
exports.ErrorResponse = require('./errorResponse');
exports.PolicyDefinitionReference = require('./policyDefinitionReference... |
'use strict';
var msRestAzure = require('ms-rest-azure');
| random_line_split |
ifletsource1.rs | fn | () {
// Toutes les variables sont de type `Option<i32>`.
let number = Some(7);
let letter: Option<i32> = None;
let emoticon: Option<i32> = None;
// L'ensemble `if let` se déroule de cette manière:
// `if let` déstructure `number` et assigne sa valeur à `i` et exécute
// le bloc (`{}`).
... | main | identifier_name |
ifletsource1.rs | fn main() {
// Toutes les variables sont de type `Option<i32>`.
let number = Some(7);
let letter: Option<i32> = None;
let emoticon: Option<i32> = None;
// L'ensemble `if let` se déroule de cette manière:
// `if let` déstructure `number` et assigne sa valeur à `i` et exécute |
// Si vous devez spécifier un cas d'erreur, utilisez un `else`:
if let Some(i) = letter {
println!("{:?} a été trouvé!", i);
} else {
// Déstructuration ratée. On exécute le `else`.
println!("Aucun nombre n'a été trouvé.
Cherchons une lettre!");
};
// Fournit une c... | // le bloc (`{}`).
if let Some(i) = number {
println!("{:?} a été trouvé!", i);
} | random_line_split |
ifletsource1.rs | fn main() | };
// Fournit une condition alternative.
let i_like_letters = false;
if let Some(i) = emoticon {
println!("{:?} a été trouvé!", i);
// Déstructuration ratée. Passe à une condition `else if` pour tester si
// la condition alternative est vraie.
} else if i_like_letters {
pr... | {
// Toutes les variables sont de type `Option<i32>`.
let number = Some(7);
let letter: Option<i32> = None;
let emoticon: Option<i32> = None;
// L'ensemble `if let` se déroule de cette manière:
// `if let` déstructure `number` et assigne sa valeur à `i` et exécute
// le bloc (`{}`).
i... | identifier_body |
ifletsource1.rs | fn main() {
// Toutes les variables sont de type `Option<i32>`.
let number = Some(7);
let letter: Option<i32> = None;
let emoticon: Option<i32> = None;
// L'ensemble `if let` se déroule de cette manière:
// `if let` déstructure `number` et assigne sa valeur à `i` et exécute
// le bloc (`{... | // Déstructuration ratée. On exécute le `else`.
println!("Aucun nombre n'a été trouvé.
Cherchons une lettre!");
};
// Fournit une condition alternative.
let i_like_letters = false;
if let Some(i) = emoticon {
println!("{:?} a été trouvé!", i);
// Déstructuration ratée.... | println!("{:?} a été trouvé!", i);
} else {
| conditional_block |
settings.py | """
Django settings for central_service 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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'central_service.urls'
WSGI_APPLICATION = 'central_service.wsgi.application'
# Templates
TEMPLATE_DIRS = (
os.path.join(PROJECT_PATH, 'templates'),
)
# Database
# https://do... | 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware', | random_line_split |
wiki.py | # coding: utf-8
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
"""
import xmlrpclib
from did.utils import item
from did.base import Config
from did.stats import Stats, StatsGroup
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | self.stats.append(WikiChanges(
option=wiki, parent=self, url=url,
name="Updates on {0}".format(wiki))) | conditional_block | |
wiki.py | # coding: utf-8
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
"""
import xmlrpclib
from did.utils import item
from did.base import Config
from did.stats import Stats, StatsGroup
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
def merge(self, other):
""" Merge another stats. """
Stats.merge(self, other)
self.changes += other.changes
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Stats Group
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
clas... | """ Show summary header. """
# Different header for wiki: Updates on xxx: x changes of y pages
item(
"{0}: {1} change{2} of {3} page{4}".format(
self.name, self.changes, "" if self.changes == 1 else "s",
len(self.stats), "" if len(self.stats) == 1 else "s"),
... | identifier_body |
wiki.py | # coding: utf-8
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
"""
import xmlrpclib
from did.utils import item
from did.base import Config
from did.stats import Stats, StatsGroup
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... |
def fetch(self):
for change in self.proxy.getRecentChanges(
self.options.since.datetime):
if (change["author"] == self.user.login
and change["lastModified"] < self.options.until.date):
self.changes += 1
url = self.url + change[... | self.proxy = xmlrpclib.ServerProxy("{0}?action=xmlrpc2".format(url))
Stats.__init__(self, option, name, parent) | random_line_split |
wiki.py | # coding: utf-8
"""
MoinMoin wiki stats about updated pages
Config example::
[wiki]
type = wiki
wiki test = http://moinmo.in/
"""
import xmlrpclib
from did.utils import item
from did.base import Config
from did.stats import Stats, StatsGroup
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | (self):
for change in self.proxy.getRecentChanges(
self.options.since.datetime):
if (change["author"] == self.user.login
and change["lastModified"] < self.options.until.date):
self.changes += 1
url = self.url + change["name"]
... | fetch | identifier_name |
lib.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/. */
#![cfg_attr(not(target_os = "windows"), feature(alloc_jemalloc))]
#![feature(box_syntax)]
#![feature(plugin)]
#![f... | pub mod trace_dump; | random_line_split | |
rv64f_instr.py |
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 in writing, software
distributed under the License is distri... | """
Copyright 2020 Google LLC
Copyright 2020 PerfectVIPs Inc. | random_line_split | |
views.py | ('format', 'treejson')
leaves_only = queryParamAsInt(queryParams, 'leavesOnly', 0)
local_only = queryParamAsInt(queryParams, 'local', 0)
wildcards = queryParamAsInt(queryParams, 'wildcards', 0)
tzinfo = pytz.timezone(settings.TIME_ZONE)
if 'tz' in queryParams:
try:
value = queryParams['tz']
t... | if node.name in found:
continue
found.add(node.name)
resultNode = {
'text' : unquote_plus(str(node.name)),
'id' : base_path + str(node.name),
}
if node.is_leaf:
resultNode.update(leafNode)
results_leaf.append(resultNode)
else:
resultNode.update(branchNode)
... | conditional_block | |
views.py | queryParams.get('local', 0) ),
'forwardHeaders': extractForwardHeaders(request),
}
matches = STORE.get_index(requestContext)
except Exception:
log.exception()
return json_response_for(request, [], jsonp=jsonp, status=500)
return json_response_for(request, matches, jsonp=jsonp)
def queryPa... |
def set_metadata_view(request):
results = {}
if request.method == 'GET':
metric = request.GET['metric']
key = request.GET['key']
value = request.GET['value']
try:
results[metric] = CarbonLink.set_metadata(metric, key, value)
except Exception:
log.exception()
results[metric]... | queryParams = request.GET.copy()
queryParams.update(request.POST)
key = queryParams.get('key')
metrics = queryParams.getlist('metric')
jsonp = queryParams.get('jsonp', False)
results = {}
for metric in metrics:
try:
results[metric] = CarbonLink.get_metadata(metric, key)
except Exception:
... | identifier_body |
views.py | from graphite.errors import InputParameterError, handleInputParameterError
from graphite.logger import log
from graphite.render.attime import parseATTime
from graphite.storage import STORE, extractForwardHeaders
from graphite.user_util import getProfile
from graphite.util import epoch, json, pickle, msgpack
def index... |
from graphite.carbonlink import CarbonLink
from graphite.compat import HttpResponse, HttpResponseBadRequest | random_line_split | |
views.py | queryParams.get('local', 0) ),
'forwardHeaders': extractForwardHeaders(request),
}
matches = STORE.get_index(requestContext)
except Exception:
log.exception()
return json_response_for(request, [], jsonp=jsonp, status=500)
return json_response_for(request, matches, jsonp=jsonp)
def queryPa... | (nodes, base_path, wildcards=False):
results = []
branchNode = {
'allowChildren': 1,
'expandable': 1,
'leaf': 0,
}
leafNode = {
'allowChildren': 0,
'expandable': 0,
'leaf': 1,
}
# | tree_json | identifier_name |
UserService.py | from datetime import datetime
import random
import string
from bson import ObjectId
class DuplicateUserException(Exception):
def __init__(self, message='User name/email already exits'):
Exception.__init__(self, message)
pass
class UserServiceException(Exception):
def __init__(self, message=None... | (self, email, id=None):
query = {}
if id is not None:
query = {"_id": {"$ne": ObjectId(id)}}
query['email'] = email
return self.users.find(query).count() > 0
| user_exists | identifier_name |
UserService.py | from datetime import datetime
import random
import string
from bson import ObjectId
class DuplicateUserException(Exception):
def __init__(self, message='User name/email already exits'):
Exception.__init__(self, message)
pass
class UserServiceException(Exception):
def __init__(self, message=None... |
query['email'] = email
return self.users.find(query).count() > 0
| query = {"_id": {"$ne": ObjectId(id)}} | conditional_block |
UserService.py | from datetime import datetime
import random
import string
from bson import ObjectId
class DuplicateUserException(Exception):
def __init__(self, message='User name/email already exits'):
Exception.__init__(self, message)
pass
class UserServiceException(Exception):
def __init__(self, message=None... | return self.users.find_one({"_id": ObjectId(id)})
def get_by_api_key(self, api_key):
return self.users.find_one({"api_key": api_key})
def update(self, item):
if item['_id'] is None:
return item
if self.user_exists(item['email'], str(item['_id'])):
raise ... | random_line_split | |
UserService.py | from datetime import datetime
import random
import string
from bson import ObjectId
class DuplicateUserException(Exception):
def __init__(self, message='User name/email already exits'):
Exception.__init__(self, message)
pass
class UserServiceException(Exception):
def __init__(self, message=None... | query = {}
if id is not None:
query = {"_id": {"$ne": ObjectId(id)}}
query['email'] = email
return self.users.find(query).count() > 0 | identifier_body | |
inputField.ts | import { CANVAS } from "../../../shared/const";
import { Shape } from "../../../shared/shape";
import { lineShape } from "../../../shared/shapeGenerator";
import { noop } from "../../../shared/util";
import { FRAME } from "../../const";
import { EventHandler } from "../../util/eventHandler";
import { State } from "../.... |
endpos = fontEndPos(this.prefix + values[0] + values[1], this.x, this.y, this.fontOptions);
shape.add(fontPixels(values[2], endpos[0], endpos[1]));
return shape;
}
private getSelectionSegments(): string[] {
const input = this.input;
let value = input.value;
le... | {
// Selection
endpos = fontEndPos(this.prefix + values[0], this.x, this.y, this.fontOptions);
shape.add(fontPixels(values[1], endpos[0], endpos[1], { invert: true }));
} | conditional_block |
inputField.ts | import { CANVAS } from "../../../shared/const";
import { Shape } from "../../../shared/shape";
import { lineShape } from "../../../shared/shapeGenerator";
import { noop } from "../../../shared/util";
import { FRAME } from "../../const";
import { EventHandler } from "../../util/eventHandler";
import { State } from "../.... | public fontOptions?: FontOptions,
) {
State.keysBlocked = true;
this.input = this.addInputToDom();
this.input.focus();
}
destruct(): void {
if (this.input && this.input.parentNode) {
this.input.parentNode.removeChild(this.input);
}
this.ev... |
constructor(
public x: number,
public y: number,
public prefix: string, | random_line_split |
inputField.ts | import { CANVAS } from "../../../shared/const";
import { Shape } from "../../../shared/shape";
import { lineShape } from "../../../shared/shapeGenerator";
import { noop } from "../../../shared/util";
import { FRAME } from "../../const";
import { EventHandler } from "../../util/eventHandler";
import { State } from "../.... |
private getInputValueShape(): Shape {
const values = this.getSelectionSegments();
const shape = new Shape();
let endpos;
shape.add(fontPixels(this.prefix + values[0], this.x, this.y, this.fontOptions));
if (values[1]) {
// Selection
endpos = fontEnd... | {
const segments = this.getSelectionSegments();
const untilCaretStr = segments[0] + segments[1];
const endPos = fontEndPos(this.prefix + untilCaretStr, this.x, this.y, this.fontOptions);
const caret = [endPos[0] - 1, endPos[1]];
const caretShape = lineShape(caret[0], caret[1] - ... | identifier_body |
inputField.ts | import { CANVAS } from "../../../shared/const";
import { Shape } from "../../../shared/shape";
import { lineShape } from "../../../shared/shapeGenerator";
import { noop } from "../../../shared/util";
import { FRAME } from "../../const";
import { EventHandler } from "../../util/eventHandler";
import { State } from "../.... | (): void {
this.eventHandler.on("keypress", () => {
State.audio.play("menu_alt");
});
this.eventHandler.on("keydown", this.updateShapes.bind(this));
this.eventHandler.on("keyup", this.updateShapes.bind(this));
}
setValue(value: string): void {
this.input.focu... | bindEvents | identifier_name |
check-instructions.py | #!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# Check opcodes in ARGUS assembly source
#
# A script that uses the arguscard classes to read ARGUS assembly format source
# and check for invalid opcodes.
#
# This is intended for debugging assembler development.
import sys
from optparse import OptionParser
from c... |
else:
for inst in sorted(instrtab.keys()):
if opts.unused and instrtab[inst] != 0 or not opts.unused:
print("%-8s %6d %6.2f%%" %
(inst, instrtab[inst],
100 * float(freqtab[inst])/float(instrcount)))
if op... | for inst in list(freqtab.keys()):
if opts.unused and freqtab[inst] != 0 or not opts.unused:
print("%-8s %6d %6.2f%%" %
(inst, freqtab[inst],
100 * float(freqtab[inst])/float(instrcount))) | conditional_block |
check-instructions.py | #!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# Check opcodes in ARGUS assembly source
#
# A script that uses the arguscard classes to read ARGUS assembly format source
# and check for invalid opcodes.
#
# This is intended for debugging assembler development.
import sys
from optparse import OptionParser
from c... | help="Print all opcodes found.")
parser.add_option('-s', '--sort',
dest='sort',
action='store_true',
default=False,
help="Sort by opcode frequency (if --count specified).")
parser.add_option('-u', '--un... | parser = OptionParser("usage: %prog filename [filename]...")
parser.add_option('-a', '--all',
dest='all',
action='store_true',
default=False,
help="Check for all errors.")
parser.add_option('-c', '--count',
... | identifier_body |
check-instructions.py | #!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# Check opcodes in ARGUS assembly source
#
# A script that uses the arguscard classes to read ARGUS assembly format source
# and check for invalid opcodes.
#
# This is intended for debugging assembler development.
import sys
from optparse import OptionParser
from c... | parser.add_option('-v', '--verbose',
dest='verbose',
action='store_true',
default=False,
help="Enable verbose output.")
(opts, args) = parser.parse_args()
if len(args) < 1:
parser.error("usage: %prog filename")
... | dest='unused',
action='store_true',
default=False,
help="Print unused instructions.") | random_line_split |
check-instructions.py | #!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# Check opcodes in ARGUS assembly source
#
# A script that uses the arguscard classes to read ARGUS assembly format source
# and check for invalid opcodes.
#
# This is intended for debugging assembler development.
import sys
from optparse import OptionParser
from c... | ():
parser = OptionParser("usage: %prog filename [filename]...")
parser.add_option('-a', '--all',
dest='all',
action='store_true',
default=False,
help="Check for all errors.")
parser.add_option('-c', '--count',
... | main | identifier_name |
lib.rs | use once_cell::sync::Lazy;
pub const TLD: &str = "org";
pub const SLD: &str = "fengalin";
// Remove "-application" from `CARGO_PKG_NAME`
pub static APP_NAME: Lazy<String> = Lazy::new(|| {
env!("CARGO_PKG_NAME") | });
pub static APP_ID: Lazy<String> = Lazy::new(|| format!("{}.{}.{}", TLD, SLD, *APP_NAME));
pub static APP_PATH: Lazy<String> = Lazy::new(|| format!("/{}/{}/{}", TLD, SLD, *APP_NAME));
mod command_line;
pub use self::command_line::{command_line, CommandLineArguments};
mod configuration;
pub use self::configuration... | .rsplitn(2, '-')
.last()
.unwrap()
.to_string() | random_line_split |
preprocess-tab-svgs.py | #!/usr/bin/env python
# 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/.
import buildconfig
from mozbuild.preprocessor import preprocess
# By default, the pre-processor... | (output_svg, input_svg_file):
return _do_preprocessing(output_svg, input_svg_file, {'TAB_SIDE': 'end'})
| tab_side_end | identifier_name |
preprocess-tab-svgs.py | #!/usr/bin/env python
# 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/.
import buildconfig
from mozbuild.preprocessor import preprocess
# By default, the pre-processor... |
def tab_side_start(output_svg, input_svg_file):
return _do_preprocessing(output_svg, input_svg_file, {'TAB_SIDE': 'start'})
def tab_side_end(output_svg, input_svg_file):
return _do_preprocessing(output_svg, input_svg_file, {'TAB_SIDE': 'end'})
| additional_defines.update(buildconfig.defines)
return preprocess(output=output_svg,
includes=[input_svg_file],
marker='%',
defines=additional_defines) | identifier_body |
preprocess-tab-svgs.py | #!/usr/bin/env python
# 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/.
import buildconfig
from mozbuild.preprocessor import preprocess
# By default, the pre-processor... | def tab_side_end(output_svg, input_svg_file):
return _do_preprocessing(output_svg, input_svg_file, {'TAB_SIDE': 'end'}) |
def tab_side_start(output_svg, input_svg_file):
return _do_preprocessing(output_svg, input_svg_file, {'TAB_SIDE': 'start'})
| random_line_split |
test_servlet_newpush.py | from contextlib import nested
from contextlib import contextmanager
import mock
import testing as T
import types
from core import db
from core.settings import Settings
from core.mail import MailQueue
from core.util import get_servlet_urlspec
from core.xmppclient import XMPPQueue
import servlets.newpush
from servlets.... | Settings['mail']['notifyall'],
mock.ANY, # msg
mock.ANY, # subject
)
T.assert_is(mocked_xmpp.called, False)
if __name__ == '__main__':
T.run() | Settings['irc']['nickname'],
Settings['irc']['channel'],
mock.ANY, # msg
])
mocked_mail.assert_called_once_with( | random_line_split |
test_servlet_newpush.py | from contextlib import nested
from contextlib import contextmanager
import mock
import testing as T
import types
from core import db
from core.settings import Settings
from core.mail import MailQueue
from core.util import get_servlet_urlspec
from core.xmppclient import XMPPQueue
import servlets.newpush
from servlets.... | T.run() | conditional_block | |
test_servlet_newpush.py | from contextlib import nested
from contextlib import contextmanager
import mock
import testing as T
import types
from core import db
from core.settings import Settings
from core.mail import MailQueue
from core.util import get_servlet_urlspec
from core.xmppclient import XMPPQueue
import servlets.newpush
from servlets.... |
def test_send_notifications(self):
"""New push sends notifications via IRC, XMPP and emails."""
self.people = ["fake_user1", "fake_user2"]
self.pushurl = "/fake_push_url?id=123"
self.pushtype = "fake_puth_type"
with self.mocked_notifications() as (mocked_call, mocked_mail,... | with mock.patch("%s.servlets.newpush.subprocess.call" % __name__) as mocked_call:
with mock.patch.object(MailQueue, "enqueue_user_email") as mocked_mail:
with mock.patch.object(XMPPQueue, "enqueue_user_xmpp") as mocked_xmpp:
yield mocked_call, mocked_mail, mocked_xmpp | identifier_body |
test_servlet_newpush.py | from contextlib import nested
from contextlib import contextmanager
import mock
import testing as T
import types
from core import db
from core.settings import Settings
from core.mail import MailQueue
from core.util import get_servlet_urlspec
from core.xmppclient import XMPPQueue
import servlets.newpush
from servlets.... | (self):
with mock.patch("%s.servlets.newpush.subprocess.call" % __name__) as mocked_call:
with mock.patch.object(MailQueue, "enqueue_user_email") as mocked_mail:
with mock.patch.object(XMPPQueue, "enqueue_user_xmpp") as mocked_xmpp:
yield mocked_call, mocked_mail,... | mocked_notifications | identifier_name |
main.py | using all epochs and then data/SN positions are "
"refit")
parser.add_argument("--mu_wave", default=0.07, type=float,
help="Wavelength regularization parameter. "
"Default is 0.07.")
parser.add_argument("--mu_xy", default=0.001, type=float,... | data = cubes[master_ref].data - skys[master_ref, :, None, None]
weight = cubes[master_ref].weight
logging.info("fitting galaxy to master ref [%d]", master_ref)
galaxy = fit_galaxy_single(galaxy, data, weight,
(yctr[master_ref], xctr[master_ref]),
... | random_line_split | |
main.py | ("setting up PSF for all %d epochs", nt)
psfs = [snfpsf(wave, cfg["psf_params"][i], cubes[i].header, args.psftype)
for i in range(nt)]
# -------------------------------------------------------------------------
# Initialize all model parameters to be fit
yctr0 = np.array(cfg["ycenters"])
... | datas = [cubes[i].data for i in nonrefs]
weights = [cubes[i].weight for i in nonrefs]
psfs_nonrefs = [psfs[i] for i in nonrefs]
fyctr, fxctr, snctr, fskys, fsne = fit_position_sky_sn_multi(
galaxy, datas, weights, yctr[nonrefs], xctr[nonrefs],
snctr, psfs_nonrefs, LBFGSB_... | conditional_block | |
main.py | # observation and wavelength and input these to the model.
# Correction to parallactic angle and airmass for 2nd-order effects
# such as MLA rotation, mechanical flexures or finite-exposure
# corrections. These values have been trained on faint-std star
# exposures.
#
# `predict_adr_params`... | """Create a 3-d PSF based on SNFactory-specific parameterization of
Gaussian + Moffat PSF parameters and ADR."""
# Get Gaussian+Moffat parameters at each wavelength.
relwave = wave / REFWAVE - 1.0
ellipticity = abs(psfparams[0]) * np.ones_like(wave)
alpha = np.abs(psfparams[1] +
... | identifier_body | |
main.py | alty, LBFGSB_FACTOR)
if args.diagdir:
fname = os.path.join(args.diagdir, 'step1.fits')
write_results(galaxy, skys, sn, snctr, yctr, xctr, yctr0, xctr0,
yctrbounds, xctrbounds, cubes, psfs, modelwcs, fname)
tsteps["fit galaxy to master ref"] = datetime.now()
# -------... | cubefit_subtract | identifier_name | |
readium_sdk.js | // LauncherOSX
//
// Created by Boris Schneiderman.
// Copyright (c) 2012-2013 The Readium Foundation.
//
// The Readium SDK 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 3 of the Lice... | * Top level ReadiumSDK namespace
* @class ReadiumSDK
* @static
*/
ReadiumSDK = {
/**
Current version of the JS SDK
@method version
@static
@return {string} version
*/
version: function() {
return "0.8.0";
},
Models : {
Smil: {}
... | /** | random_line_split |
write_a_ppm_file.rs | // http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
} | }
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size = 3 * height * width;
let buffer = vec![0; size as usize];
PPM {
height: height,
width: width,
data: buffer,
}
}
fn buffer_size(&self) -> u32 {
3 * self.height * s... |
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>, | random_line_split |
write_a_ppm_file.rs | // http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size =... | (&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = try!(File::create(&path));
let header = format!("P6 {} {} 255\n", self.width, self.height);
try!(file.write(header.as_bytes()));
try!(file.write(&self.data));
Ok(())
}
}
f... | write_file | identifier_name |
write_a_ppm_file.rs | // http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size =... |
None => None,
}
}
pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool {
match self.get_offset(x, y) {
Some(offset) => {
self.data[offset] = color.r;
self.data[offset + 1] = color.g;
self.data[offset + 2] = colo... | {
let r = self.data[offset];
let g = self.data[offset + 1];
let b = self.data[offset + 2];
Some(RGB { r: r, g: g, b: b })
} | conditional_block |
write_a_ppm_file.rs | // http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
use std::path::Path;
use std::io::Write;
use std::fs::File;
pub struct RGB {
r: u8,
g: u8,
b: u8,
}
pub struct PPM {
height: u32,
width: u32,
data: Vec<u8>,
}
impl PPM {
pub fn new(height: u32, width: u32) -> PPM {
let size =... |
}
fn main() {
let ppm = PPM::new(400, 300);
ppm.write_file("output.ppm").unwrap();
}
| {
let path = Path::new(filename);
let mut file = try!(File::create(&path));
let header = format!("P6 {} {} 255\n", self.width, self.height);
try!(file.write(header.as_bytes()));
try!(file.write(&self.data));
Ok(())
} | identifier_body |
ds.py | state of the
# system, and returns it.
#############################
def calculateRisk(data):
risk = computeRiskState(data[0], data[1], data[2], data[3], data[4], data[5], data[6])
return risk
#############################
# Function "computeRiskState"
# Given all the parameters required to use the DST, calls the... |
#############################
# Function "computeRiskDistribution"
# Given a riskIndex and the priority of the element in the system,
# computes the actual risk of the element.
#############################
def computeRiskDistribution(priority, riskIndex):
# Risk Distribution = Target Importance
#
# medium = [0,0.5... | riskIndex = computeRiskIndex(AK, CK0, BK, RS0, priority_IDS, IDS_name)
riskState = computeRiskDistribution(priority,riskIndex)
return riskState | identifier_body |
ds.py | of the
# system, and returns it.
#############################
def calculateRisk(data):
risk = computeRiskState(data[0], data[1], data[2], data[3], data[4], data[5], data[6])
return risk
#############################
# Function "computeRiskState"
# Given all the parameters required to use the DST, calls the funct... | (AK, CK0, BK, RS0, priority_IDS, IDS_name):
# Risk Index = Alert Amount [+] Alert Confidence [+] Alter Type Number
# [+] Alert Severity [+] Alert Relevance Score
#
if IDS_name == "snort":
PIDS0 = 3
else:
PIDS0 = 1
mu = calculateMu(AK, CK0, BK, RS0, priority_IDS)
mk = calculateMk(mu,PIDS0)
prob = mk[0]... | computeRiskIndex | identifier_name |
ds.py | state of the
# system, and returns it.
#############################
def calculateRisk(data):
risk = computeRiskState(data[0], data[1], data[2], data[3], data[4], data[5], data[6])
return risk
#############################
# Function "computeRiskState"
# Given all the parameters required to use the DST, calls the... |
else:
RS0 = 1. | RS0 = CK0 + alert_number/10.0 | conditional_block |
ds.py | state of the
# system, and returns it.
#############################
def calculateRisk(data):
risk = computeRiskState(data[0], data[1], data[2], data[3], data[4], data[5], data[6])
return risk
#############################
# Function "computeRiskState"
# Given all the parameters required to use the DST, calls the... | #----------------
if AK <= alpha2:
mu[0][0] = float((alpha2-AK) / alpha2)
else:
mu[0][0] = 0.0
if alpha1 >= AK:
mu[0][1] = 0.0
elif alpha3 < AK:
mu[0][1] = 1.0
else:
mu[0][1] = float((AK - alpha1) / (alpha3 - alpha1))
# CK0 [0,1]
mu[1][0] = 1.0 - CK0
mu[1][1] = float(CK0)
# lambda1 [1,5] ; lam... | alpha2 = 10
alpha3 = 15 | random_line_split |
index.js | /*
See README.md
*/
var Service, Characteristic, types;
var request = require('request');
// Handle registration with homebridge
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
types = homebridge.hapLegacyTypes;
homebridge.registerPl... | else {
that.log("Failed to update wireless tags");
}
// Hack as I was seeing issues with an undefined queryFrequency. Believe I have fixed it but keeping the
// minimum in to keep us from spamming the service. Also prevents values below 5000ms.
if(that.queryFrequency == und... | {
that.log("Updated wireless tag data");
} | conditional_block |
index.js | /*
See README.md
*/
var Service, Characteristic, types;
var request = require('request');
// Handle registration with homebridge
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
types = homebridge.hapLegacyTypes;
homebridge.registerPl... | WirelessTagAccessory.prototype.getServices = function() {
this.informationService = new Service.AccessoryInformation();
this.informationService
.setCharacteristic(Characteristic.Manufacturer, "SmartHome")
.setCharacteristic(Characteristic.Model, "Wireless Sensor Tag Type="+this.tagType)
.setC... | }
callback(null,isAway ? Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED : Characteristic.OccupancyDetected.OCCUPANCY_DETECTED);
}
// Sets up the information, temperature and occupancy services. | random_line_split |
index.js | /*
See README.md
*/
var Service, Characteristic, types;
var request = require('request');
// Handle registration with homebridge
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
types = homebridge.hapLegacyTypes;
homebridge.registerPl... | (log,config) {
this.username = config.username;
this.password = config.password;
this.queryFrequency = config.queryFrequency;
this.log = log;
this.tagMap = {};
this.tagList = [];
this.ignoreList = (config.ignoreList == undefined) ? [] : config.ignoreList;
}
WirelessTagPlatform.prototype.shouldIgnore... | WirelessTagPlatform | identifier_name |
index.js | /*
See README.md
*/
var Service, Characteristic, types;
var request = require('request');
// Handle registration with homebridge
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
types = homebridge.hapLegacyTypes;
homebridge.registerPl... |
WirelessTagPlatform.prototype.shouldIgnore = function(deviceData) {
if(deviceData != undefined && deviceData.name != undefined) {
if(this.ignoreList.indexOf(deviceData.name) > -1) {
return true;
}
}
return false;
}
// Forms a valid request to authenticate against the wireless ... | {
this.username = config.username;
this.password = config.password;
this.queryFrequency = config.queryFrequency;
this.log = log;
this.tagMap = {};
this.tagList = [];
this.ignoreList = (config.ignoreList == undefined) ? [] : config.ignoreList;
} | identifier_body |
login.component.ts | import {Color} from "color";
import {View} from "ui/core/view";
import {Component, ElementRef, OnInit, ViewChild} from "@angular/core";
import {User} from "../../shared/user/user";
import {UserService} from "../../shared/user/user.service";
import {Router} from "@angular/router";
import {Page} from "ui/page";
@Compone... |
toggleDisplay() {
this.isLoggingIn = !this.isLoggingIn;
let container = <View>this.container.nativeElement;
container.animate({
backgroundColor: this.isLoggingIn ? new Color("white") : new Color("#301217"),
duration: 200
});
}
}
| {
this._userService.register(this.user)
.subscribe(
() => {
alert("Your account was successfully created.");
this.toggleDisplay();
},
() => alert("Unfortunately we were unable to create your account.")
);
} | identifier_body |
login.component.ts | import {Color} from "color";
import {View} from "ui/core/view";
import {Component, ElementRef, OnInit, ViewChild} from "@angular/core";
import {User} from "../../shared/user/user";
import {UserService} from "../../shared/user/user.service";
import {Router} from "@angular/router";
import {Page} from "ui/page";
@Compone... |
if (this.isLoggingIn) {
this.login();
} else {
this.signUp();
}
}
login() {
this._userService.login(this.user)
.subscribe(
() => this._router.navigate(["/list"]),
(error) => alert("Unfortunately we could not find your account.")
);
}
signUp() {
this._userService.... | {
alert("Enter a valid email address.");
return;
} | conditional_block |
login.component.ts | import {UserService} from "../../shared/user/user.service";
import {Router} from "@angular/router";
import {Page} from "ui/page";
@Component({
selector: "my-app",
providers: [UserService],
templateUrl: "pages/login/login.html",
styleUrls: ["pages/login/login-common.css", "pages/login/login.css"]
})
export cla... | import {Color} from "color";
import {View} from "ui/core/view";
import {Component, ElementRef, OnInit, ViewChild} from "@angular/core";
import {User} from "../../shared/user/user"; | random_line_split | |
login.component.ts | import {Color} from "color";
import {View} from "ui/core/view";
import {Component, ElementRef, OnInit, ViewChild} from "@angular/core";
import {User} from "../../shared/user/user";
import {UserService} from "../../shared/user/user.service";
import {Router} from "@angular/router";
import {Page} from "ui/page";
@Compone... | () {
this.isLoggingIn = !this.isLoggingIn;
let container = <View>this.container.nativeElement;
container.animate({
backgroundColor: this.isLoggingIn ? new Color("white") : new Color("#301217"),
duration: 200
});
}
}
| toggleDisplay | identifier_name |
lhcb.py | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2016 CERN.
#
# CERN Analysis Preservation Framework 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... | # as an Intergovernmental Organization or submit itself to any jurisdiction.
"""CAP LHCb permissions"""
from invenio_access import DynamicPermission
from cap.modules.experiments.permissions.common import get_collaboration_group_needs, get_superuser_needs
lhcb_group_need = set(
[g for g in get_collaboration_gr... | # waive the privileges and immunities granted to it by virtue of its status | random_line_split |
default.view.js | sap.ui.jsview("ui.default", {
getControllerName: function() {
return "ui.default";
},
createContent: function(oController) {
oController.oShell = new sap.ui.ux3.Shell("myShell", {
appIcon: "./ui/images/sap_18.png",
appIconTooltip: "SAP",
ap... |
// oController.oShell.attachLogout(oController.handleExitShell);
createShell(oController);
buildShellPersonalization(oController);
var oDataGenView = sap.ui.view({
id: "epm_datagen_view",
viewName: "ui.DataGen",
type: sap.ui.core.mvc.Vie... | key: "wi_home",
text: oBundle.getText("worklist")
})]
});
| random_line_split |
default.view.js | sap.ui.jsview("ui.default", {
getControllerName: function() {
return "ui.default";
},
createContent: function(oController) {
oController.oShell = new sap.ui.ux3.Shell("myShell", {
appIcon: "./ui/images/sap_18.png",
appIconTooltip: "SAP",
ap... | (oController) {
oController.oShell._getPersonalization().attachPersonalizationChange(
oController.handlePersonalizeShellChange);
// initialize settings
if (JSON && window["localStorage"]) { // only in browsers with native JSON
// and offline storage support
var sSettings = loca... | buildShellPersonalization | identifier_name |
default.view.js | sap.ui.jsview("ui.default", {
getControllerName: function() {
return "ui.default";
},
createContent: function(oController) {
oController.oShell = new sap.ui.ux3.Shell("myShell", {
appIcon: "./ui/images/sap_18.png",
appIconTooltip: "SAP",
ap... |
} | { // only in browsers with native JSON
// and offline storage support
var sSettings = localStorage.getItem("sapUiShellTestSettings");
if (sSettings) {
oController.oShell.initializePersonalization(JSON.parse(sSettings));
}
} | conditional_block |
default.view.js | sap.ui.jsview("ui.default", {
getControllerName: function() {
return "ui.default";
},
createContent: function(oController) {
oController.oShell = new sap.ui.ux3.Shell("myShell", {
appIcon: "./ui/images/sap_18.png",
appIconTooltip: "SAP",
ap... | text: oBundle.getText("help")
}), new sap.ui.commons.MenuItem("menuitem2", {
text: oBundle.getText("incident")
}), new sap.ui.commons.MenuItem("menuitem3", {
text: oBundle.getText("about")
})]
})
}));
}
function ... | {
var oUserTxt = new sap.ui.commons.TextView({
tooltip: oBundle.getText("welcome")
});
oController.oShell.addHeaderItem(oUserTxt);
oController.getSessionInfo(oController, oUserTxt);
oController.oShell.addHeaderItem(new sap.ui.commons.Button({
text: oBundle.getText("persona... | identifier_body |
faq.ts | import {Component} from '@angular/core';
import {ChatBoxComponent} from './chat-box';
import {LogoComponent} from './logo';
@Component({
template: `
<uhunt-chat-box width="550" height="245" style="float:right; padding-left:25px"
[user]="user">
</uhunt-chat-box>
<uhunt-logo active="faq" [user]="user"... | {
}
| FAQComponent | identifier_name |
faq.ts | import {Component} from '@angular/core';
import {ChatBoxComponent} from './chat-box';
import {LogoComponent} from './logo';
@Component({
template: `
<uhunt-chat-box width="550" height="245" style="float:right; padding-left:25px"
[user]="user">
</uhunt-chat-box>
<uhunt-logo active="faq" [user]="user"... | } | ],
})
export class FAQComponent { | random_line_split |
mod.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | //! and are often seen in trait bounds.
//! * `std::convert::`{
//! [`AsRef`](../convert/trait.AsRef.html),
//! [`AsMut`](../convert/trait.AsMut.html),
//! [`Into`](../convert/trait.Into.html),
//! [`From`](../convert/trait.From.html)
//! }.
//! Generic conversions, used by savvy API authors to cr... | //! The comparision traits, which implement the comparison operators | random_line_split |
cmd_whowas.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import durationToSeconds, ipAddressToShow, ircLower, now
from zope.interface import implementer
from... | (self) -> List[Tuple[str, int, Callable]]:
return [ ("quit", 10, self.addUserToWhowas),
("remotequit", 10, self.addUserToWhowas),
("localquit", 10, self.addUserToWhowas) ]
def userCommands(self) -> List[Tuple[str, int, Command]]:
return [ ("WHOWAS", 1, self) ]
def load(self) -> None:
i... | actions | identifier_name |
cmd_whowas.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import durationToSeconds, ipAddressToShow, ircLower, now
from zope.interface import implementer
from... |
whowasEntries.append({
"nick": user.nick,
"ident": user.ident,
"host": user.host(),
"realhost": user.realHost,
"ip": ipAddressToShow(user.ip),
"gecos": user.gecos,
"server": serverName,
"when": now()
})
whowasEntries = self.removeOldEntries(whowasEntries)
if whowasEntries:
allWhowas[... | serverName = self.ircd.servers[user.uuid[:3]].name | conditional_block |
cmd_whowas.py | from zope.interface import implementer
from datetime import datetime, timedelta
from typing import Any, Callable, Dict, List, Optional, Tuple
irc.RPL_WHOWASIP = "379"
@implementer(IPlugin, IModuleData, ICommand)
class WhowasCommand(ModuleData, Command):
name = "WhowasCommand"
core = True
def actions(self) -> Lis... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import durationToSeconds, ipAddressToShow, ircLower, now | random_line_split | |
cmd_whowas.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import durationToSeconds, ipAddressToShow, ircLower, now
from zope.interface import implementer
from... | "when": now()
})
whowasEntries = self.removeOldEntries(whowasEntries)
if whowasEntries:
allWhowas[lowerNick] = whowasEntries
elif lowerNick in allWhowas:
del allWhowas[lowerNick]
def parseParams(self, user: "IRCUser", params: List[str], prefix: str, tags: Dict[str, Optional[str]]) -> Optional[Dict[... | if not user.isRegistered():
# user never registered a nick, so no whowas entry to add
return
lowerNick = ircLower(user.nick)
allWhowas = self.ircd.storage["whowas"]
if lowerNick in allWhowas:
whowasEntries = allWhowas[lowerNick]
else:
whowasEntries = []
serverName = self.ircd.name
if user.uuid[:... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.