file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a non-threadsafe
// fn. To mitigate the race condition, wrap it in a Once struct.
pub fn init() {
INIT_ZSYS.call_once(|| {
unsafe { czmq_sys::zsys_init() };
});
}
/// Create a pipe, which consists of two PAIR sockets connected
/// over inproc.
pub fn create_pipe() -> Result<(ZSock, ZSock)> {
let mut backend_raw: *mut czmq_sys::zsock_t = ptr::null_mut();
let frontend_raw = unsafe { czmq_sys::zsys_create_pipe(&mut backend_raw) };
if frontend_raw == ptr::null_mut() {
Err(Error::new(ErrorKind::NullPtr, ZSysError::CreatePipe))
} else {
Ok(unsafe { (ZSock::from_raw(frontend_raw as *mut c_void, true), ZSock::from_raw(backend_raw as *mut c_void, true)) })
}
}
pub fn is_interrupted() -> bool { | #[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description(&self) -> &str {
match *self {
ZSysError::CreatePipe => "Could not create pipe",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_pipe() {
ZSys::init();
let (frontend, backend) = ZSys::create_pipe().unwrap();
frontend.send_str("I changed my iPod’s name to Titanic...now it’s syncing.").unwrap();
assert_eq!(backend.recv_str().unwrap().unwrap(), "I changed my iPod’s name to Titanic...now it’s syncing.");
backend.send_str("My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!").unwrap();
assert_eq!(frontend.recv_str().unwrap().unwrap(), "My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!");
}
#[test]
fn test_is_interrupted() {
// This test is half hearted as we can't test the interrupt
// case.
assert!(!ZSys::is_interrupted());
}
} | unsafe { czmq_sys::zsys_interrupted == 1 }
}
}
| random_line_split |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a non-threadsafe
// fn. To mitigate the race condition, wrap it in a Once struct.
pub fn init() {
INIT_ZSYS.call_once(|| {
unsafe { czmq_sys::zsys_init() };
});
}
/// Create a pipe, which consists of two PAIR sockets connected
/// over inproc.
pub fn create_pipe() -> Result<(ZSock, ZSock)> {
let mut backend_raw: *mut czmq_sys::zsock_t = ptr::null_mut();
let frontend_raw = unsafe { czmq_sys::zsys_create_pipe(&mut backend_raw) };
if frontend_raw == ptr::null_mut() {
Err(Error::new(ErrorKind::NullPtr, ZSysError::CreatePipe))
} else {
Ok(unsafe { (ZSock::from_raw(frontend_raw as *mut c_void, true), ZSock::from_raw(backend_raw as *mut c_void, true)) })
}
}
pub fn is_interrupted() -> bool |
}
#[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description(&self) -> &str {
match *self {
ZSysError::CreatePipe => "Could not create pipe",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_create_pipe() {
ZSys::init();
let (frontend, backend) = ZSys::create_pipe().unwrap();
frontend.send_str("I changed my iPod’s name to Titanic...now it’s syncing.").unwrap();
assert_eq!(backend.recv_str().unwrap().unwrap(), "I changed my iPod’s name to Titanic...now it’s syncing.");
backend.send_str("My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!").unwrap();
assert_eq!(frontend.recv_str().unwrap().unwrap(), "My family laughed when I told them I was going to be a comedian. Well...they aren't laughing now!");
}
#[test]
fn test_is_interrupted() {
// This test is half hearted as we can't test the interrupt
// case.
assert!(!ZSys::is_interrupted());
}
}
| {
unsafe { czmq_sys::zsys_interrupted == 1 }
} | identifier_body |
actions.js | /*
* Minio Cloud Storage (C) 2018 Minio, 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 in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, | export const SET = "alert/SET"
export const CLEAR = "alert/CLEAR"
export let alertId = 0
export const set = alert => {
const id = alertId++
return (dispatch, getState) => {
if (alert.type !== "danger" || alert.autoClear) {
setTimeout(() => {
dispatch({
type: CLEAR,
alert: {
id
}
})
}, 5000)
}
dispatch({
type: SET,
alert: Object.assign({}, alert, {
id
})
})
}
}
export const clear = () => {
return { type: CLEAR }
} | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
| random_line_split |
actions.js | /*
* Minio Cloud Storage (C) 2018 Minio, 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 in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const SET = "alert/SET"
export const CLEAR = "alert/CLEAR"
export let alertId = 0
export const set = alert => {
const id = alertId++
return (dispatch, getState) => {
if (alert.type !== "danger" || alert.autoClear) |
dispatch({
type: SET,
alert: Object.assign({}, alert, {
id
})
})
}
}
export const clear = () => {
return { type: CLEAR }
}
| {
setTimeout(() => {
dispatch({
type: CLEAR,
alert: {
id
}
})
}, 5000)
} | conditional_block |
node.js | "use strict";
const utils = require("../../../utils/ast-utils");
/**
*
* Transform for node. Finds the node property from yeoman and creates a
* property based on what the user has given us.
*
* @param j — jscodeshift API
* @param ast - jscodeshift API
* @param {any} webpackProperties - transformation object to scaffold
* @param {String} action - action that indicates what to be done to the AST
* @returns ast - jscodeshift API
*/
module.exports = function nodeTransform(j, ast, webpackProperties, action) {
function createNodeProperty(p) {
| if (webpackProperties) {
if (action === "init") {
return ast
.find(j.ObjectExpression)
.filter(p => utils.isAssignment(null, p, createNodeProperty));
} else if (action === "add") {
const nodeNode = utils.findRootNodesByName(j, ast, "node");
if (nodeNode.size() !== 0) {
return ast
.find(j.ObjectExpression)
.filter(p => utils.pushObjectKeys(j, p, webpackProperties, "node"));
} else {
return nodeTransform(j, ast, webpackProperties, "init");
}
} else if (action === "remove") {
// TODO
} else if (action === "update") {
// TODO
}
} else {
return ast;
}
};
| utils.pushCreateProperty(j, p, "node", j.objectExpression([]));
return utils.pushObjectKeys(j, p, webpackProperties, "node");
}
| identifier_body |
node.js | "use strict";
const utils = require("../../../utils/ast-utils");
/**
*
* Transform for node. Finds the node property from yeoman and creates a
* property based on what the user has given us.
*
* @param j — jscodeshift API
* @param ast - jscodeshift API
* @param {any} webpackProperties - transformation object to scaffold
* @param {String} action - action that indicates what to be done to the AST
* @returns ast - jscodeshift API
*/
module.exports = function nodeTransform(j, ast, webpackProperties, action) {
function cr | ) {
utils.pushCreateProperty(j, p, "node", j.objectExpression([]));
return utils.pushObjectKeys(j, p, webpackProperties, "node");
}
if (webpackProperties) {
if (action === "init") {
return ast
.find(j.ObjectExpression)
.filter(p => utils.isAssignment(null, p, createNodeProperty));
} else if (action === "add") {
const nodeNode = utils.findRootNodesByName(j, ast, "node");
if (nodeNode.size() !== 0) {
return ast
.find(j.ObjectExpression)
.filter(p => utils.pushObjectKeys(j, p, webpackProperties, "node"));
} else {
return nodeTransform(j, ast, webpackProperties, "init");
}
} else if (action === "remove") {
// TODO
} else if (action === "update") {
// TODO
}
} else {
return ast;
}
};
| eateNodeProperty(p | identifier_name |
node.js | "use strict";
const utils = require("../../../utils/ast-utils");
/**
*
* Transform for node. Finds the node property from yeoman and creates a
* property based on what the user has given us.
*
* @param j — jscodeshift API
* @param ast - jscodeshift API
* @param {any} webpackProperties - transformation object to scaffold
* @param {String} action - action that indicates what to be done to the AST
* @returns ast - jscodeshift API
*/
module.exports = function nodeTransform(j, ast, webpackProperties, action) {
function createNodeProperty(p) {
utils.pushCreateProperty(j, p, "node", j.objectExpression([]));
return utils.pushObjectKeys(j, p, webpackProperties, "node");
}
if (webpackProperties) {
if (action === "init") {
| lse if (action === "add") {
const nodeNode = utils.findRootNodesByName(j, ast, "node");
if (nodeNode.size() !== 0) {
return ast
.find(j.ObjectExpression)
.filter(p => utils.pushObjectKeys(j, p, webpackProperties, "node"));
} else {
return nodeTransform(j, ast, webpackProperties, "init");
}
} else if (action === "remove") {
// TODO
} else if (action === "update") {
// TODO
}
} else {
return ast;
}
};
| return ast
.find(j.ObjectExpression)
.filter(p => utils.isAssignment(null, p, createNodeProperty));
} e | conditional_block |
node.js | "use strict";
const utils = require("../../../utils/ast-utils");
/**
*
* Transform for node. Finds the node property from yeoman and creates a
* property based on what the user has given us.
*
* @param j — jscodeshift API
* @param ast - jscodeshift API
* @param {any} webpackProperties - transformation object to scaffold
* @param {String} action - action that indicates what to be done to the AST
* @returns ast - jscodeshift API
*/
module.exports = function nodeTransform(j, ast, webpackProperties, action) { | if (action === "init") {
return ast
.find(j.ObjectExpression)
.filter(p => utils.isAssignment(null, p, createNodeProperty));
} else if (action === "add") {
const nodeNode = utils.findRootNodesByName(j, ast, "node");
if (nodeNode.size() !== 0) {
return ast
.find(j.ObjectExpression)
.filter(p => utils.pushObjectKeys(j, p, webpackProperties, "node"));
} else {
return nodeTransform(j, ast, webpackProperties, "init");
}
} else if (action === "remove") {
// TODO
} else if (action === "update") {
// TODO
}
} else {
return ast;
}
}; | function createNodeProperty(p) {
utils.pushCreateProperty(j, p, "node", j.objectExpression([]));
return utils.pushObjectKeys(j, p, webpackProperties, "node");
}
if (webpackProperties) { | random_line_split |
Scheduler.ts | import { Errors } from './../utils/Errors'
import { FirebaseRedundancyService } from './FirebaseRedundancyService'
import { Handlers } from './../utils/Handlers'
import { IScheduler } from './../descriptors/IScheduler'
import { ITask } from './../descriptors/ITask'
import * as Firebase from 'firebase-admin'
import * as NodeSchedule from 'node-schedule'
/**
* This implementation of the scehduler object provides task management with a
* Firebase backbone.
*/
class Scheduler implements IScheduler {
// Maintains a list of local tasks.
private taskList: Map<string, NodeSchedule.Job>
// An instance of the Firebase redunancy service.
private redundancyService: FirebaseRedundancyService
// A handler that is executed when a task has completed.
private taskCompletionHandler: Handlers.TaskCompletionHandler
public constructor(reference: Firebase.database.Reference,
taskCompletionHandler: Handlers.TaskCompletionHandler) {
// Attach the redundancy service
this.redundancyService = new FirebaseRedundancyService(reference)
// Attach the jobCompletionHandler.
this.taskCompletionHandler = taskCompletionHandler
// Build the local mapping of jobs.
this.taskList = new Map<string, NodeSchedule.Job>()
// Reque the exsting tasks.
this.redundancyService.getAll().then((tasks: Array<ITask>) => {
this.queueExisting(tasks)
}).catch((error: Error) => {
// Error ocurred while fetching exisiting jobs. Re-throw
throw error
})
}
/**
* Generates a callback which is executed when the given job is
* scheduled.
*
* @param key The firebase key associated with the job.
* @return A function which acts as a callback for when a callback is
* issued.
*/
private getJobCallback(key: string): (() => void) {
return async () => {
if (!this.taskCompletionHandler) {
// There is no callback attached skip processing.
// TODO: Warn the user.
return
}
const task: ITask = await this.redundancyService.fetch(key)
// Ensure that the object exists.
if (!task) {
// Job does not exist. Nothin to do here.
return
}
// Notify the completion handler about the job if it exits.
if (this.taskCompletionHandler) {
this.taskCompletionHandler(key, task)
}
// We then delete the job from the referenced node.
await this.redundancyService.remove(key)
}
}
/**
* Leverage the NodeSchedule library to schedule a one time job.
*
* @param task The task that is being scheduled.
*/
private scheduleTask(task: ITask): void {
if (this.taskList.has(task.getKey())) {
// Skip scheduling job for a key that already exists.
return
}
// Create the scheduled task.
const scheduledJob: NodeSchedule.Job = NodeSchedule.scheduleJob(
task.getKey(),
task.getScheduledDateTime(),
this.getJobCallback(task.getKey())
)
// Add the new job to the list of tasks.
this.taskList.set(task.getKey(), scheduledJob);
}
/**
* Process tasks that may have not been started due to a server restart.
*
* @param tasks A collection of tasks that are to be queued.
* @return A Promise which resolves when all existing tasks have been
* queued.
*/
public async queueExisting(tasks: Array<ITask>): Promise<void> {
// If there are no existing tasks, theres nothing to do.
if (!tasks) {
return
}
tasks.forEach((task: ITask) => {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
// Cannot schedule a job to complete in a time that no
// longer exists. We notify on the callback so that the
// case can be handled.
this.taskCompletionHandler(task.getKey(), task)
this.redundancyService.remove(task.getKey())
} else {
// Delegate the job item to the actual job scheduler.
this.scheduleTask(task)
}
});
}
/**
* Fetch a given task by key.
*
* @see IScheduler#get(string)
*/
public async get(key: string): Promise<ITask> {
return await this.redundancyService.fetch(key)
}
/**
* Returns the number of pending tasks.
*
* @return The number of tasks that are queued.
*/
public getPendingCount(): number {
return this.taskList.size
}
/**
* Schedule a given task.
*
* @param task The task that is being scheduled.
*/
public async schedule(task: ITask): Promise<ITask> {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
throw new Error(Errors.SCHEDULED_IN_PAST)
}
// In the event that we are starting a job as a result of a server
// refresh, we enable this variable so that we don't waste cycles.
let shouldCreateLocallyOnly: boolean = false
// Fetch the task associated with that key.
const existingTask: ITask = await this.redundancyService
.fetch(task.getKey())
if (existingTask) {
// Check if we already have the job queued.
if (this.taskList.has(task.getKey())) {
// The job already exists; nothing to do here.
return existingTask
}
// Enable flag the allows the session to be created locally.
shouldCreateLocallyOnly = true
}
// Delegate the job item to the actual job scheduler.
this.scheduleTask(task)
if (!shouldCreateLocallyOnly) {
// Create job with the key in the jobItem and with the data being
// the data from the JobItem.
await this.redundancyService.commit(task)
}
return task
}
/**
* Cancel a pending task by key.
* | public async cancel(key: string): Promise<void> {
// Validate key
if (!this.taskList.has(key)) {
return
}
// Removed the serialized copy.
await this.redundancyService.remove(key)
// Fetch local copy.
const job: NodeSchedule.Job | undefined = this.taskList.get(key)
// Cancel keys
if (job) {
job.cancel()
}
this.taskList.delete(key)
}
}
export {
Scheduler
} | * @param key The key that identifies the task that is to be cancelled.
*/ | random_line_split |
Scheduler.ts | import { Errors } from './../utils/Errors'
import { FirebaseRedundancyService } from './FirebaseRedundancyService'
import { Handlers } from './../utils/Handlers'
import { IScheduler } from './../descriptors/IScheduler'
import { ITask } from './../descriptors/ITask'
import * as Firebase from 'firebase-admin'
import * as NodeSchedule from 'node-schedule'
/**
* This implementation of the scehduler object provides task management with a
* Firebase backbone.
*/
class Scheduler implements IScheduler {
// Maintains a list of local tasks.
private taskList: Map<string, NodeSchedule.Job>
// An instance of the Firebase redunancy service.
private redundancyService: FirebaseRedundancyService
// A handler that is executed when a task has completed.
private taskCompletionHandler: Handlers.TaskCompletionHandler
public constructor(reference: Firebase.database.Reference,
taskCompletionHandler: Handlers.TaskCompletionHandler) {
// Attach the redundancy service
this.redundancyService = new FirebaseRedundancyService(reference)
// Attach the jobCompletionHandler.
this.taskCompletionHandler = taskCompletionHandler
// Build the local mapping of jobs.
this.taskList = new Map<string, NodeSchedule.Job>()
// Reque the exsting tasks.
this.redundancyService.getAll().then((tasks: Array<ITask>) => {
this.queueExisting(tasks)
}).catch((error: Error) => {
// Error ocurred while fetching exisiting jobs. Re-throw
throw error
})
}
/**
* Generates a callback which is executed when the given job is
* scheduled.
*
* @param key The firebase key associated with the job.
* @return A function which acts as a callback for when a callback is
* issued.
*/
private getJobCallback(key: string): (() => void) {
return async () => {
if (!this.taskCompletionHandler) {
// There is no callback attached skip processing.
// TODO: Warn the user.
return
}
const task: ITask = await this.redundancyService.fetch(key)
// Ensure that the object exists.
if (!task) {
// Job does not exist. Nothin to do here.
return
}
// Notify the completion handler about the job if it exits.
if (this.taskCompletionHandler) {
this.taskCompletionHandler(key, task)
}
// We then delete the job from the referenced node.
await this.redundancyService.remove(key)
}
}
/**
* Leverage the NodeSchedule library to schedule a one time job.
*
* @param task The task that is being scheduled.
*/
private scheduleTask(task: ITask): void {
if (this.taskList.has(task.getKey())) {
// Skip scheduling job for a key that already exists.
return
}
// Create the scheduled task.
const scheduledJob: NodeSchedule.Job = NodeSchedule.scheduleJob(
task.getKey(),
task.getScheduledDateTime(),
this.getJobCallback(task.getKey())
)
// Add the new job to the list of tasks.
this.taskList.set(task.getKey(), scheduledJob);
}
/**
* Process tasks that may have not been started due to a server restart.
*
* @param tasks A collection of tasks that are to be queued.
* @return A Promise which resolves when all existing tasks have been
* queued.
*/
public async queueExisting(tasks: Array<ITask>): Promise<void> {
// If there are no existing tasks, theres nothing to do.
if (!tasks) {
return
}
tasks.forEach((task: ITask) => {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
// Cannot schedule a job to complete in a time that no
// longer exists. We notify on the callback so that the
// case can be handled.
this.taskCompletionHandler(task.getKey(), task)
this.redundancyService.remove(task.getKey())
} else {
// Delegate the job item to the actual job scheduler.
this.scheduleTask(task)
}
});
}
/**
* Fetch a given task by key.
*
* @see IScheduler#get(string)
*/
public async get(key: string): Promise<ITask> {
return await this.redundancyService.fetch(key)
}
/**
* Returns the number of pending tasks.
*
* @return The number of tasks that are queued.
*/
public | (): number {
return this.taskList.size
}
/**
* Schedule a given task.
*
* @param task The task that is being scheduled.
*/
public async schedule(task: ITask): Promise<ITask> {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
throw new Error(Errors.SCHEDULED_IN_PAST)
}
// In the event that we are starting a job as a result of a server
// refresh, we enable this variable so that we don't waste cycles.
let shouldCreateLocallyOnly: boolean = false
// Fetch the task associated with that key.
const existingTask: ITask = await this.redundancyService
.fetch(task.getKey())
if (existingTask) {
// Check if we already have the job queued.
if (this.taskList.has(task.getKey())) {
// The job already exists; nothing to do here.
return existingTask
}
// Enable flag the allows the session to be created locally.
shouldCreateLocallyOnly = true
}
// Delegate the job item to the actual job scheduler.
this.scheduleTask(task)
if (!shouldCreateLocallyOnly) {
// Create job with the key in the jobItem and with the data being
// the data from the JobItem.
await this.redundancyService.commit(task)
}
return task
}
/**
* Cancel a pending task by key.
*
* @param key The key that identifies the task that is to be cancelled.
*/
public async cancel(key: string): Promise<void> {
// Validate key
if (!this.taskList.has(key)) {
return
}
// Removed the serialized copy.
await this.redundancyService.remove(key)
// Fetch local copy.
const job: NodeSchedule.Job | undefined = this.taskList.get(key)
// Cancel keys
if (job) {
job.cancel()
}
this.taskList.delete(key)
}
}
export {
Scheduler
}
| getPendingCount | identifier_name |
Scheduler.ts | import { Errors } from './../utils/Errors'
import { FirebaseRedundancyService } from './FirebaseRedundancyService'
import { Handlers } from './../utils/Handlers'
import { IScheduler } from './../descriptors/IScheduler'
import { ITask } from './../descriptors/ITask'
import * as Firebase from 'firebase-admin'
import * as NodeSchedule from 'node-schedule'
/**
* This implementation of the scehduler object provides task management with a
* Firebase backbone.
*/
class Scheduler implements IScheduler {
// Maintains a list of local tasks.
private taskList: Map<string, NodeSchedule.Job>
// An instance of the Firebase redunancy service.
private redundancyService: FirebaseRedundancyService
// A handler that is executed when a task has completed.
private taskCompletionHandler: Handlers.TaskCompletionHandler
public constructor(reference: Firebase.database.Reference,
taskCompletionHandler: Handlers.TaskCompletionHandler) {
// Attach the redundancy service
this.redundancyService = new FirebaseRedundancyService(reference)
// Attach the jobCompletionHandler.
this.taskCompletionHandler = taskCompletionHandler
// Build the local mapping of jobs.
this.taskList = new Map<string, NodeSchedule.Job>()
// Reque the exsting tasks.
this.redundancyService.getAll().then((tasks: Array<ITask>) => {
this.queueExisting(tasks)
}).catch((error: Error) => {
// Error ocurred while fetching exisiting jobs. Re-throw
throw error
})
}
/**
* Generates a callback which is executed when the given job is
* scheduled.
*
* @param key The firebase key associated with the job.
* @return A function which acts as a callback for when a callback is
* issued.
*/
private getJobCallback(key: string): (() => void) {
return async () => {
if (!this.taskCompletionHandler) {
// There is no callback attached skip processing.
// TODO: Warn the user.
return
}
const task: ITask = await this.redundancyService.fetch(key)
// Ensure that the object exists.
if (!task) {
// Job does not exist. Nothin to do here.
return
}
// Notify the completion handler about the job if it exits.
if (this.taskCompletionHandler) {
this.taskCompletionHandler(key, task)
}
// We then delete the job from the referenced node.
await this.redundancyService.remove(key)
}
}
/**
* Leverage the NodeSchedule library to schedule a one time job.
*
* @param task The task that is being scheduled.
*/
private scheduleTask(task: ITask): void {
if (this.taskList.has(task.getKey())) {
// Skip scheduling job for a key that already exists.
return
}
// Create the scheduled task.
const scheduledJob: NodeSchedule.Job = NodeSchedule.scheduleJob(
task.getKey(),
task.getScheduledDateTime(),
this.getJobCallback(task.getKey())
)
// Add the new job to the list of tasks.
this.taskList.set(task.getKey(), scheduledJob);
}
/**
* Process tasks that may have not been started due to a server restart.
*
* @param tasks A collection of tasks that are to be queued.
* @return A Promise which resolves when all existing tasks have been
* queued.
*/
public async queueExisting(tasks: Array<ITask>): Promise<void> {
// If there are no existing tasks, theres nothing to do.
if (!tasks) {
return
}
tasks.forEach((task: ITask) => {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
// Cannot schedule a job to complete in a time that no
// longer exists. We notify on the callback so that the
// case can be handled.
this.taskCompletionHandler(task.getKey(), task)
this.redundancyService.remove(task.getKey())
} else {
// Delegate the job item to the actual job scheduler.
this.scheduleTask(task)
}
});
}
/**
* Fetch a given task by key.
*
* @see IScheduler#get(string)
*/
public async get(key: string): Promise<ITask> {
return await this.redundancyService.fetch(key)
}
/**
* Returns the number of pending tasks.
*
* @return The number of tasks that are queued.
*/
public getPendingCount(): number |
/**
* Schedule a given task.
*
* @param task The task that is being scheduled.
*/
public async schedule(task: ITask): Promise<ITask> {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
throw new Error(Errors.SCHEDULED_IN_PAST)
}
// In the event that we are starting a job as a result of a server
// refresh, we enable this variable so that we don't waste cycles.
let shouldCreateLocallyOnly: boolean = false
// Fetch the task associated with that key.
const existingTask: ITask = await this.redundancyService
.fetch(task.getKey())
if (existingTask) {
// Check if we already have the job queued.
if (this.taskList.has(task.getKey())) {
// The job already exists; nothing to do here.
return existingTask
}
// Enable flag the allows the session to be created locally.
shouldCreateLocallyOnly = true
}
// Delegate the job item to the actual job scheduler.
this.scheduleTask(task)
if (!shouldCreateLocallyOnly) {
// Create job with the key in the jobItem and with the data being
// the data from the JobItem.
await this.redundancyService.commit(task)
}
return task
}
/**
* Cancel a pending task by key.
*
* @param key The key that identifies the task that is to be cancelled.
*/
public async cancel(key: string): Promise<void> {
// Validate key
if (!this.taskList.has(key)) {
return
}
// Removed the serialized copy.
await this.redundancyService.remove(key)
// Fetch local copy.
const job: NodeSchedule.Job | undefined = this.taskList.get(key)
// Cancel keys
if (job) {
job.cancel()
}
this.taskList.delete(key)
}
}
export {
Scheduler
}
| {
return this.taskList.size
} | identifier_body |
Scheduler.ts | import { Errors } from './../utils/Errors'
import { FirebaseRedundancyService } from './FirebaseRedundancyService'
import { Handlers } from './../utils/Handlers'
import { IScheduler } from './../descriptors/IScheduler'
import { ITask } from './../descriptors/ITask'
import * as Firebase from 'firebase-admin'
import * as NodeSchedule from 'node-schedule'
/**
* This implementation of the scehduler object provides task management with a
* Firebase backbone.
*/
class Scheduler implements IScheduler {
// Maintains a list of local tasks.
private taskList: Map<string, NodeSchedule.Job>
// An instance of the Firebase redunancy service.
private redundancyService: FirebaseRedundancyService
// A handler that is executed when a task has completed.
private taskCompletionHandler: Handlers.TaskCompletionHandler
public constructor(reference: Firebase.database.Reference,
taskCompletionHandler: Handlers.TaskCompletionHandler) {
// Attach the redundancy service
this.redundancyService = new FirebaseRedundancyService(reference)
// Attach the jobCompletionHandler.
this.taskCompletionHandler = taskCompletionHandler
// Build the local mapping of jobs.
this.taskList = new Map<string, NodeSchedule.Job>()
// Reque the exsting tasks.
this.redundancyService.getAll().then((tasks: Array<ITask>) => {
this.queueExisting(tasks)
}).catch((error: Error) => {
// Error ocurred while fetching exisiting jobs. Re-throw
throw error
})
}
/**
* Generates a callback which is executed when the given job is
* scheduled.
*
* @param key The firebase key associated with the job.
* @return A function which acts as a callback for when a callback is
* issued.
*/
private getJobCallback(key: string): (() => void) {
return async () => {
if (!this.taskCompletionHandler) {
// There is no callback attached skip processing.
// TODO: Warn the user.
return
}
const task: ITask = await this.redundancyService.fetch(key)
// Ensure that the object exists.
if (!task) {
// Job does not exist. Nothin to do here.
return
}
// Notify the completion handler about the job if it exits.
if (this.taskCompletionHandler) {
this.taskCompletionHandler(key, task)
}
// We then delete the job from the referenced node.
await this.redundancyService.remove(key)
}
}
/**
* Leverage the NodeSchedule library to schedule a one time job.
*
* @param task The task that is being scheduled.
*/
private scheduleTask(task: ITask): void {
if (this.taskList.has(task.getKey())) {
// Skip scheduling job for a key that already exists.
return
}
// Create the scheduled task.
const scheduledJob: NodeSchedule.Job = NodeSchedule.scheduleJob(
task.getKey(),
task.getScheduledDateTime(),
this.getJobCallback(task.getKey())
)
// Add the new job to the list of tasks.
this.taskList.set(task.getKey(), scheduledJob);
}
/**
* Process tasks that may have not been started due to a server restart.
*
* @param tasks A collection of tasks that are to be queued.
* @return A Promise which resolves when all existing tasks have been
* queued.
*/
public async queueExisting(tasks: Array<ITask>): Promise<void> {
// If there are no existing tasks, theres nothing to do.
if (!tasks) {
return
}
tasks.forEach((task: ITask) => {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
// Cannot schedule a job to complete in a time that no
// longer exists. We notify on the callback so that the
// case can be handled.
this.taskCompletionHandler(task.getKey(), task)
this.redundancyService.remove(task.getKey())
} else {
// Delegate the job item to the actual job scheduler.
this.scheduleTask(task)
}
});
}
/**
* Fetch a given task by key.
*
* @see IScheduler#get(string)
*/
public async get(key: string): Promise<ITask> {
return await this.redundancyService.fetch(key)
}
/**
* Returns the number of pending tasks.
*
* @return The number of tasks that are queued.
*/
public getPendingCount(): number {
return this.taskList.size
}
/**
* Schedule a given task.
*
* @param task The task that is being scheduled.
*/
public async schedule(task: ITask): Promise<ITask> {
// Ensure that the job is in the future.
if (task.getScheduledDateTime().getTime() < Date.now()) {
throw new Error(Errors.SCHEDULED_IN_PAST)
}
// In the event that we are starting a job as a result of a server
// refresh, we enable this variable so that we don't waste cycles.
let shouldCreateLocallyOnly: boolean = false
// Fetch the task associated with that key.
const existingTask: ITask = await this.redundancyService
.fetch(task.getKey())
if (existingTask) {
// Check if we already have the job queued.
if (this.taskList.has(task.getKey())) {
// The job already exists; nothing to do here.
return existingTask
}
// Enable flag the allows the session to be created locally.
shouldCreateLocallyOnly = true
}
// Delegate the job item to the actual job scheduler.
this.scheduleTask(task)
if (!shouldCreateLocallyOnly) |
return task
}
/**
* Cancel a pending task by key.
*
* @param key The key that identifies the task that is to be cancelled.
*/
public async cancel(key: string): Promise<void> {
// Validate key
if (!this.taskList.has(key)) {
return
}
// Removed the serialized copy.
await this.redundancyService.remove(key)
// Fetch local copy.
const job: NodeSchedule.Job | undefined = this.taskList.get(key)
// Cancel keys
if (job) {
job.cancel()
}
this.taskList.delete(key)
}
}
export {
Scheduler
}
| {
// Create job with the key in the jobItem and with the data being
// the data from the JobItem.
await this.redundancyService.commit(task)
} | conditional_block |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare
// with `sha256sum_naive` which uses the IO primitives in the standard library.
use std::env;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use filebuffer::FileBuffer;
extern crate crypto;
extern crate filebuffer;
fn main() | {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}", hasher.result_str(), fname);
}
} | identifier_body | |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
// This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare
// with `sha256sum_naive` which uses the IO primitives in the standard library.
use std::env;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use filebuffer::FileBuffer;
extern crate crypto;
extern crate filebuffer;
fn | () {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}", hasher.result_str(), fname);
}
}
| main | identifier_name |
sha256sum_filebuffer.rs | // Filebuffer -- Fast and simple file reading
// Copyright 2016 Ruud van Asseldonk
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// A copy of the License has been included in the root of the repository.
|
use std::env;
use crypto::digest::Digest;
use crypto::sha2::Sha256;
use filebuffer::FileBuffer;
extern crate crypto;
extern crate filebuffer;
fn main() {
for fname in env::args().skip(1) {
let fbuffer = FileBuffer::open(&fname).expect("failed to open file");
let mut hasher = Sha256::new();
hasher.input(&fbuffer);
// Match the output format of `sha256sum`, which has two spaces between the hash and name.
println!("{} {}", hasher.result_str(), fname);
}
} | // This example implements the `sha256sum` program in Rust using the Filebuffer library. Compare
// with `sha256sum_naive` which uses the IO primitives in the standard library. | random_line_split |
__init__.py | from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
self.table = table
self.queries = []
self.debug = debug
def commit(self):
if len(self.queries) == 0:
return
stmts = "\n".join(self.queries)
query = "BEGIN;\n"
query += stmts
query += "COMMIT;\n"
if self.debug:
print query
resp = self.cl.sql(query)
if self.debug:
print resp
def _craft_insert(self, the_geom, event_type, happened_at, message):
if happened_at is None:
happened_at = ''
if message is None:
message = ''
def quote(s):
|
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
the_geom = "ST_SetSRID(ST_Point(%s,%s), 4326)" %(point.longitude, point.latitude)
insert = self._craft_insert(the_geom, "checkin", point.dateTime, point.message)
self.queries.append(insert)
def update_line(self, trip_id, coords):
geojson = json.dumps({ "type" : "MultiLineString", "coordinates": [coords] })
the_geom = "ST_SetSRID(ST_GeomFromGeoJSON('%s'), 4326)" % (geojson)
insert = self._craft_insert(the_geom, "track", str(datetime.datetime.now()), None)
self.queries.append(insert)
| return "'" + s + "'" | identifier_body |
__init__.py | from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
self.table = table
self.queries = []
self.debug = debug
def commit(self):
if len(self.queries) == 0:
return
stmts = "\n".join(self.queries)
query = "BEGIN;\n"
query += stmts
query += "COMMIT;\n"
if self.debug:
print query
resp = self.cl.sql(query)
if self.debug: | if happened_at is None:
happened_at = ''
if message is None:
message = ''
def quote(s):
return "'" + s + "'"
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
the_geom = "ST_SetSRID(ST_Point(%s,%s), 4326)" %(point.longitude, point.latitude)
insert = self._craft_insert(the_geom, "checkin", point.dateTime, point.message)
self.queries.append(insert)
def update_line(self, trip_id, coords):
geojson = json.dumps({ "type" : "MultiLineString", "coordinates": [coords] })
the_geom = "ST_SetSRID(ST_GeomFromGeoJSON('%s'), 4326)" % (geojson)
insert = self._craft_insert(the_geom, "track", str(datetime.datetime.now()), None)
self.queries.append(insert) | print resp
def _craft_insert(self, the_geom, event_type, happened_at, message): | random_line_split |
__init__.py | from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
self.table = table
self.queries = []
self.debug = debug
def commit(self):
if len(self.queries) == 0:
return
stmts = "\n".join(self.queries)
query = "BEGIN;\n"
query += stmts
query += "COMMIT;\n"
if self.debug:
print query
resp = self.cl.sql(query)
if self.debug:
print resp
def _craft_insert(self, the_geom, event_type, happened_at, message):
if happened_at is None:
happened_at = ''
if message is None:
message = ''
def | (s):
return "'" + s + "'"
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
the_geom = "ST_SetSRID(ST_Point(%s,%s), 4326)" %(point.longitude, point.latitude)
insert = self._craft_insert(the_geom, "checkin", point.dateTime, point.message)
self.queries.append(insert)
def update_line(self, trip_id, coords):
geojson = json.dumps({ "type" : "MultiLineString", "coordinates": [coords] })
the_geom = "ST_SetSRID(ST_GeomFromGeoJSON('%s'), 4326)" % (geojson)
insert = self._craft_insert(the_geom, "track", str(datetime.datetime.now()), None)
self.queries.append(insert)
| quote | identifier_name |
__init__.py | from cartodb import CartoDBAPIKey
import json
import datetime
class CartoTransaction(object):
_SQL_INSERT = "insert into %s ( the_geom, type, happened_at, message ) values( %s, %s, %s, %s);"
def __init__(self, api_key, domain, table, debug = False):
self.cl = CartoDBAPIKey(api_key, domain)
self.table = table
self.queries = []
self.debug = debug
def commit(self):
if len(self.queries) == 0:
return
stmts = "\n".join(self.queries)
query = "BEGIN;\n"
query += stmts
query += "COMMIT;\n"
if self.debug:
print query
resp = self.cl.sql(query)
if self.debug:
print resp
def _craft_insert(self, the_geom, event_type, happened_at, message):
if happened_at is None:
|
if message is None:
message = ''
def quote(s):
return "'" + s + "'"
return self._SQL_INSERT % (self.table, the_geom , quote(event_type), quote(happened_at), quote(message))
def insert_point(self, point):
the_geom = "ST_SetSRID(ST_Point(%s,%s), 4326)" %(point.longitude, point.latitude)
insert = self._craft_insert(the_geom, "checkin", point.dateTime, point.message)
self.queries.append(insert)
def update_line(self, trip_id, coords):
geojson = json.dumps({ "type" : "MultiLineString", "coordinates": [coords] })
the_geom = "ST_SetSRID(ST_GeomFromGeoJSON('%s'), 4326)" % (geojson)
insert = self._craft_insert(the_geom, "track", str(datetime.datetime.now()), None)
self.queries.append(insert)
| happened_at = '' | conditional_block |
LogPage.js | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2012 the ConQAT Project |
| |
| 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 distributed on an "AS IS" BASIS, |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| See the License for the specific language governing permissions and |
| limitations under the License. |
+-------------------------------------------------------------------------*/
goog.provide('conqat.config.LogPage');
goog.require('conqat.config.DashboardPageBase');
goog.require('conqat.config.UnitEditPart');
goog.require('conqat.config.TemplateUtils');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.dom.dataset');
goog.require('goog.dom.query');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.soy');
goog.require('goog.array');
goog.require('goog.style');
goog.require('goog.string');
goog.require('goog.object');
goog.require('goog.i18n.DateTimeFormat');
/**
* Base class that handles the workflow of the log page. Saves and manipulates
* the entries in the dashboard's log.
*
* @ConQAT.Rating GREEN Hash: 669B42C2D05EAF19026A09808629C09E
* @constructor
* @extends {conqat.config.DashboardPageBase}
*/
conqat.config.LogPage = function() {
goog.base(this);
/**
* The levels that are not filtered out by #isProcessorVisible().
*
* @private
* @type {Object.<string, boolean>}
*/
this.visibleLevels = {
'fatal' : true,
'error' : true,
'warn' : true
};
/**
* The processor id that is currently displayed. null, if all processors are
* shown.
*
* @type {?number}
*/
this.processorFilter = null;
};
goog.inherits(conqat.config.LogPage, conqat.config.DashboardPageBase);
/**
* The log singleton.
*
* @see conqat.config.LogPage.create()
*
* @private
* @type {conqat.config.LogPage}
*/
conqat.config.LogPage.instance;
/**
* Returns the Log singleton. Creates it if necessary.
*
* @private
* @returns {conqat.config.LogPage} The Log singleton.
*/
conqat.config.LogPage.getInstance = function() {
if (!conqat.config.LogPage.instance) {
conqat.config.LogPage.instance = new conqat.config.LogPage();
}
return conqat.config.LogPage.instance;
};
/**
* Opens the log page for the processor with the given ID.
*
* @public
* @param {number} id The ID of the processor for which to open the log page.
*/
conqat.config.LogPage.openForProcessor = function(id) {
location = 'log.html#' + id;
};
/**
* Creates a log page.
*
* @public
*/
conqat.config.LogPage.create = function() {
var log = conqat.config.LogPage.getInstance();
log.update();
};
/**
* Listens to click events on the last inserted checkbox and filters the log
* according to its state.
*
* @public
* @param {string} logLevel The level for which the checkbox is responsible.
*/
conqat.config.LogPage.setupFilterCheckbox = function(logLevel) {
var filterBoxes = goog.dom.getElementsByTagNameAndClass('input');
var checkBox = filterBoxes[filterBoxes.length - 1];
var log = conqat.config.LogPage.getInstance();
checkBox.checked = log.visibleLevels[logLevel];
goog.events.listen(checkBox, goog.events.EventType.CLICK, function() {
log.visibleLevels[logLevel] = checkBox.checked;
log.update();
});
};
/**
* @private
* @returns {Element} The log table of the current page.
*/
conqat.config.LogPage.getLogTable = function() {
return goog.dom.getElement('log-table');
};
/** @inheritDoc */
conqat.config.LogPage.prototype.onHistoryChanged = function(event) {
var token = goog.string.isEmptySafe(event.token) ? null : goog.string
.toNumber(event.token);
if (this.processorFilter != token) {
this.processorFilter = token;
this.update();
}
};
/**
* Checks whether the processor with the given id and log level should be shown.
*
* @private
*/
conqat.config.LogPage.prototype.isProcessorVisible = function(processorId,
logLevel) {
if (this.processorFilter && processorId != this.processorFilter) {
return false;
}
if (!this.visibleLevels[logLevel]) {
return false;
}
return true;
};
/**
* Updates the log page after settings have changed and when it is first
* created.
*
* @public
*/
conqat.config.LogPage.prototype.update = function() {
this.updateLogTable();
this.updateParametersTable();
this.updateSubtitle();
};
/**
* Updates the log table after settings have changed.
*
* @private
*/
conqat.config.LogPage.prototype.updateLogTable = function() {
var that = this;
var logTableHolder = goog.dom.getElement('log-table');
var dateFormat = new goog.i18n.DateTimeFormat('HH:mm:ss.SSS');
var data = {
rows : [],
tableHeaderClass : conqat.config.DashboardPageBase
.getCSSClass('tableHeader'),
evenRowClass : conqat.config.DashboardPageBase.getCSSClass('evenRow'),
oddRowClass : conqat.config.DashboardPageBase.getCSSClass('oddRow')
};
var processorIds = [];
goog.array.forEach(conqat.config.DashboardPageBase.log, function(logEntry,
index) {
var processorId = logEntry[0];
var level = logEntry[1];
if (!that.isProcessorVisible(processorId, level)) {
return;
}
var date = new Date(logEntry[3]);
var processor = new conqat.config.UnitEditPart(processorId);
var rowData = {
name : processor.getName(),
level : level,
message : logEntry[2],
time : dateFormat.format(date)
};
data.rows.push(rowData);
processorIds.push(processorId);
});
if (goog.array.isEmpty(data.rows)) {
goog.soy.renderElement(logTableHolder,
conqat.config.DashboardTemplate.emptyLogTable);
return;
}
goog.soy.renderElement(logTableHolder,
conqat.config.DashboardTemplate.logTable, data);
var rows = goog.dom.query('tbody tr', logTableHolder);
goog.array.forEach(rows, function(row, index) {
var processorId = processorIds[index];
var filterLink = goog.dom.getElementsByTagNameAndClass('a',
'processor', row)[0];
goog.events.listen(filterLink, goog.events.EventType.CLICK, function(
event) {
event.preventDefault();
that.setHistoryToken(processorId);
that.filterProcessor = processorId;
that.update();
});
});
}
/**
* Updates the parameters table after settings have changed.
*
* @private
*/
conqat.config.LogPage.prototype.updateParametersTable = function() {
var logTable = conqat.config.LogPage.getLogTable();
conqat.config.TemplateUtils.clearParametersTable();
if (this.processorFilter) {
var processor = new conqat.config.UnitEditPart(this.processorFilter);
conqat.config.TemplateUtils.renderParametersTable(this.processorFilter);
}
};
/**
* Updates the page subtitle after settings have changed.
*
* @private
*/
conqat.config.LogPage.prototype.updateSubtitle = function() {
var logTable = conqat.config.LogPage.getLogTable();
var subtitle;
if (this.processorFilter) | else {
subtitle = "All log messages generated during ConQAT run.";
}
var subtitleElement = goog.dom.getElement("caption-subtitle");
goog.dom.setTextContent(subtitleElement, subtitle);
};
| {
var processor = new conqat.config.UnitEditPart(this.processorFilter);
subtitle = "Log messages for processor " + processor.getName();
} | conditional_block |
LogPage.js | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2012 the ConQAT Project |
| |
| 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 distributed on an "AS IS" BASIS, |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| See the License for the specific language governing permissions and |
| limitations under the License. |
+-------------------------------------------------------------------------*/
goog.provide('conqat.config.LogPage');
goog.require('conqat.config.DashboardPageBase');
goog.require('conqat.config.UnitEditPart');
goog.require('conqat.config.TemplateUtils');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.dom.dataset');
goog.require('goog.dom.query');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.soy');
goog.require('goog.array');
goog.require('goog.style');
goog.require('goog.string');
goog.require('goog.object');
goog.require('goog.i18n.DateTimeFormat');
/**
* Base class that handles the workflow of the log page. Saves and manipulates
* the entries in the dashboard's log.
*
* @ConQAT.Rating GREEN Hash: 669B42C2D05EAF19026A09808629C09E
* @constructor
* @extends {conqat.config.DashboardPageBase}
*/
conqat.config.LogPage = function() {
goog.base(this);
/**
* The levels that are not filtered out by #isProcessorVisible().
*
* @private
* @type {Object.<string, boolean>}
*/
this.visibleLevels = {
'fatal' : true,
'error' : true,
'warn' : true
};
/**
* The processor id that is currently displayed. null, if all processors are
* shown.
*
* @type {?number}
*/
this.processorFilter = null;
};
goog.inherits(conqat.config.LogPage, conqat.config.DashboardPageBase);
/**
* The log singleton.
*
* @see conqat.config.LogPage.create()
*
* @private
* @type {conqat.config.LogPage}
*/
conqat.config.LogPage.instance;
/**
* Returns the Log singleton. Creates it if necessary.
*
* @private
* @returns {conqat.config.LogPage} The Log singleton.
*/
conqat.config.LogPage.getInstance = function() {
if (!conqat.config.LogPage.instance) {
conqat.config.LogPage.instance = new conqat.config.LogPage();
}
return conqat.config.LogPage.instance;
};
/**
* Opens the log page for the processor with the given ID.
*
* @public
* @param {number} id The ID of the processor for which to open the log page.
*/
conqat.config.LogPage.openForProcessor = function(id) {
location = 'log.html#' + id;
};
/**
* Creates a log page.
*
* @public
*/
conqat.config.LogPage.create = function() {
var log = conqat.config.LogPage.getInstance();
log.update();
};
/**
* Listens to click events on the last inserted checkbox and filters the log
* according to its state.
*
* @public
* @param {string} logLevel The level for which the checkbox is responsible.
*/
conqat.config.LogPage.setupFilterCheckbox = function(logLevel) {
var filterBoxes = goog.dom.getElementsByTagNameAndClass('input');
var checkBox = filterBoxes[filterBoxes.length - 1];
var log = conqat.config.LogPage.getInstance();
checkBox.checked = log.visibleLevels[logLevel];
goog.events.listen(checkBox, goog.events.EventType.CLICK, function() {
log.visibleLevels[logLevel] = checkBox.checked;
log.update();
});
};
/**
* @private
* @returns {Element} The log table of the current page.
*/
conqat.config.LogPage.getLogTable = function() {
return goog.dom.getElement('log-table');
};
/** @inheritDoc */
conqat.config.LogPage.prototype.onHistoryChanged = function(event) {
var token = goog.string.isEmptySafe(event.token) ? null : goog.string
.toNumber(event.token);
if (this.processorFilter != token) {
this.processorFilter = token;
this.update();
}
};
/**
* Checks whether the processor with the given id and log level should be shown.
*
* @private
*/
conqat.config.LogPage.prototype.isProcessorVisible = function(processorId,
logLevel) {
if (this.processorFilter && processorId != this.processorFilter) {
return false;
}
if (!this.visibleLevels[logLevel]) {
return false;
}
return true;
};
/**
* Updates the log page after settings have changed and when it is first
* created.
*
* @public
*/
conqat.config.LogPage.prototype.update = function() {
this.updateLogTable();
this.updateParametersTable();
this.updateSubtitle();
};
/**
* Updates the log table after settings have changed.
*
* @private
*/
conqat.config.LogPage.prototype.updateLogTable = function() {
var that = this;
var logTableHolder = goog.dom.getElement('log-table');
var dateFormat = new goog.i18n.DateTimeFormat('HH:mm:ss.SSS');
var data = {
rows : [],
tableHeaderClass : conqat.config.DashboardPageBase
.getCSSClass('tableHeader'),
evenRowClass : conqat.config.DashboardPageBase.getCSSClass('evenRow'),
oddRowClass : conqat.config.DashboardPageBase.getCSSClass('oddRow')
};
var processorIds = [];
goog.array.forEach(conqat.config.DashboardPageBase.log, function(logEntry,
index) {
var processorId = logEntry[0];
var level = logEntry[1];
if (!that.isProcessorVisible(processorId, level)) {
return;
}
var date = new Date(logEntry[3]);
var processor = new conqat.config.UnitEditPart(processorId);
var rowData = {
name : processor.getName(),
level : level,
message : logEntry[2],
time : dateFormat.format(date)
};
data.rows.push(rowData);
processorIds.push(processorId);
});
if (goog.array.isEmpty(data.rows)) {
goog.soy.renderElement(logTableHolder,
conqat.config.DashboardTemplate.emptyLogTable);
return;
}
goog.soy.renderElement(logTableHolder,
conqat.config.DashboardTemplate.logTable, data);
var rows = goog.dom.query('tbody tr', logTableHolder);
goog.array.forEach(rows, function(row, index) {
var processorId = processorIds[index];
var filterLink = goog.dom.getElementsByTagNameAndClass('a',
'processor', row)[0];
goog.events.listen(filterLink, goog.events.EventType.CLICK, function(
event) {
event.preventDefault();
that.setHistoryToken(processorId);
that.filterProcessor = processorId;
that.update();
});
});
}
/**
* Updates the parameters table after settings have changed.
* | conqat.config.TemplateUtils.clearParametersTable();
if (this.processorFilter) {
var processor = new conqat.config.UnitEditPart(this.processorFilter);
conqat.config.TemplateUtils.renderParametersTable(this.processorFilter);
}
};
/**
* Updates the page subtitle after settings have changed.
*
* @private
*/
conqat.config.LogPage.prototype.updateSubtitle = function() {
var logTable = conqat.config.LogPage.getLogTable();
var subtitle;
if (this.processorFilter) {
var processor = new conqat.config.UnitEditPart(this.processorFilter);
subtitle = "Log messages for processor " + processor.getName();
} else {
subtitle = "All log messages generated during ConQAT run.";
}
var subtitleElement = goog.dom.getElement("caption-subtitle");
goog.dom.setTextContent(subtitleElement, subtitle);
}; | * @private
*/
conqat.config.LogPage.prototype.updateParametersTable = function() {
var logTable = conqat.config.LogPage.getLogTable();
| random_line_split |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use ast;
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) |
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
let n = match substr.nonself_args {
[n] => n,
_ => cx.span_bug(trait_span, "incorrect number of arguments in `deriving(FromPrimitive)`")
};
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in enum_def.variants.iter() {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if !args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let variant = cx.expr_ident(span, variant.node.name);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant, ty);
let guard = cx.expr_binary(span, ast::BiEq, n, cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n, arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in deriving(FromPrimitive)")
}
}
| {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "num", "FromPrimitive")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("i64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
name: "from_u64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("u64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("u64", c, s, sub)
}),
})
};
trait_def.expand(cx, mitem, item, push)
} | identifier_body |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use ast;
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn | (cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "num", "FromPrimitive")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("i64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
name: "from_u64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("u64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("u64", c, s, sub)
}),
})
};
trait_def.expand(cx, mitem, item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
let n = match substr.nonself_args {
[n] => n,
_ => cx.span_bug(trait_span, "incorrect number of arguments in `deriving(FromPrimitive)`")
};
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in enum_def.variants.iter() {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if !args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let variant = cx.expr_ident(span, variant.node.name);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant, ty);
let guard = cx.expr_binary(span, ast::BiEq, n, cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n, arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in deriving(FromPrimitive)")
}
}
| expand_deriving_from_primitive | identifier_name |
primitive.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{MetaItem, Item, Expr};
use ast;
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "num", "FromPrimitive")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(), | MethodDef {
name: "from_i64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("i64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs.clone(),
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("i64", c, s, sub)
}),
},
MethodDef {
name: "from_u64",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: vec!(
Literal(Path::new(vec!("u64")))),
ret_ty: Literal(Path::new_(vec!("std", "option", "Option"),
None,
vec!(box Self),
true)),
// #[inline] liable to cause code-bloat
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_from("u64", c, s, sub)
}),
})
};
trait_def.expand(cx, mitem, item, push)
}
fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> @Expr {
let n = match substr.nonself_args {
[n] => n,
_ => cx.span_bug(trait_span, "incorrect number of arguments in `deriving(FromPrimitive)`")
};
match *substr.fields {
StaticStruct(..) => {
cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
return cx.expr_fail(trait_span, InternedString::new(""));
}
StaticEnum(enum_def, _) => {
if enum_def.variants.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums with no variants");
return cx.expr_fail(trait_span, InternedString::new(""));
}
let mut arms = Vec::new();
for variant in enum_def.variants.iter() {
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
if !args.is_empty() {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for \
enum variants with arguments");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
let span = variant.span;
// expr for `$n == $variant as $name`
let variant = cx.expr_ident(span, variant.node.name);
let ty = cx.ty_ident(span, cx.ident_of(name));
let cast = cx.expr_cast(span, variant, ty);
let guard = cx.expr_binary(span, ast::BiEq, n, cast);
// expr for `Some($variant)`
let body = cx.expr_some(span, variant);
// arm for `_ if $guard => $body`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(span)),
guard: Some(guard),
body: body,
};
arms.push(arm);
}
ast::StructVariantKind(_) => {
cx.span_err(trait_span,
"`FromPrimitive` cannot be derived for enums \
with struct variants");
return cx.expr_fail(trait_span,
InternedString::new(""));
}
}
}
// arm for `_ => None`
let arm = ast::Arm {
attrs: vec!(),
pats: vec!(cx.pat_wild(trait_span)),
guard: None,
body: cx.expr_none(trait_span),
};
arms.push(arm);
cx.expr_match(trait_span, n, arms)
}
_ => cx.span_bug(trait_span, "expected StaticEnum in deriving(FromPrimitive)")
}
} | methods: vec!( | random_line_split |
sync.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T:Send> Send for Packet<T> { }
unsafe impl<T:Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: uint, // capacity of this channel
/// A curious flag used to indicate whether a sender failed or succeeded in
/// blocking. This is used to transmit information back to the task that it
/// must dequeue its message from the buffer because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
/// Simple queue for threading tasks together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
//
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if !guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
//
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 && !waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn drop_port(&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap != 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else {
Vec::new()
};
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else {
match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> uint { self.size }
fn cap(&self) -> uint { self.buf.len() }
}
////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> |
}
| {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
} | identifier_body |
sync.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T:Send> Send for Packet<T> { }
unsafe impl<T:Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: uint, // capacity of this channel
/// A curious flag used to indicate whether a sender failed or succeeded in
/// blocking. This is used to transmit information back to the task that it
/// must dequeue its message from the buffer because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
/// Simple queue for threading tasks together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
//
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if !guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
//
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 && !waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn drop_port(&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap != 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else {
Vec::new()
};
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else { | BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> uint { self.size }
fn cap(&self) -> uint { self.buf.len() }
}
////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
}
} | match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(), | random_line_split |
sync.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T:Send> Send for Packet<T> { }
unsafe impl<T:Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: uint, // capacity of this channel
/// A curious flag used to indicate whether a sender failed or succeeded in
/// blocking. This is used to transmit information back to the task that it
/// must dequeue its message from the buffer because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
/// Simple queue for threading tasks together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
//
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if !guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
//
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 && !waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn drop_port(&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap != 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else | ;
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else {
match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> uint { self.size }
fn cap(&self) -> uint { self.buf.len() }
}
////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
}
}
| {
Vec::new()
} | conditional_block |
sync.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Synchronous channels/ports
///
/// This channel implementation differs significantly from the asynchronous
/// implementations found next to it (oneshot/stream/share). This is an
/// implementation of a synchronous, bounded buffer channel.
///
/// Each channel is created with some amount of backing buffer, and sends will
/// *block* until buffer space becomes available. A buffer size of 0 is valid,
/// which means that every successful send is paired with a successful recv.
///
/// This flavor of channels defines a new `send_opt` method for channels which
/// is the method by which a message is sent but the task does not panic if it
/// cannot be delivered.
///
/// Another major difference is that send() will *always* return back the data
/// if it couldn't be sent. This is because it is deterministically known when
/// the data is received and when it is not received.
///
/// Implementation-wise, it can all be summed up with "use a mutex plus some
/// logic". The mutex used here is an OS native mutex, meaning that no user code
/// is run inside of the mutex (to prevent context switching). This
/// implementation shares almost all code for the buffered and unbuffered cases
/// of a synchronous channel. There are a few branches for the unbuffered case,
/// but they're mostly just relevant to blocking senders.
use core::prelude::*;
pub use self::Failure::*;
use self::Blocker::*;
use vec::Vec;
use core::mem;
use core::ptr;
use sync::atomic::{Ordering, AtomicUsize};
use sync::mpsc::blocking::{self, WaitToken, SignalToken};
use sync::mpsc::select::StartResult::{self, Installed, Abort};
use sync::{Mutex, MutexGuard};
pub struct Packet<T> {
/// Only field outside of the mutex. Just done for kicks, but mainly because
/// the other shared channel already had the code implemented
channels: AtomicUsize,
lock: Mutex<State<T>>,
}
unsafe impl<T:Send> Send for Packet<T> { }
unsafe impl<T:Send> Sync for Packet<T> { }
struct State<T> {
disconnected: bool, // Is the channel disconnected yet?
queue: Queue, // queue of senders waiting to send data
blocker: Blocker, // currently blocked task on this channel
buf: Buffer<T>, // storage for buffered messages
cap: uint, // capacity of this channel
/// A curious flag used to indicate whether a sender failed or succeeded in
/// blocking. This is used to transmit information back to the task that it
/// must dequeue its message from the buffer because it was not received.
/// This is only relevant in the 0-buffer case. This obviously cannot be
/// safely constructed, but it's guaranteed to always have a valid pointer
/// value.
canceled: Option<&'static mut bool>,
}
unsafe impl<T: Send> Send for State<T> {}
/// Possible flavors of threads who can be blocked on this channel.
enum Blocker {
BlockedSender(SignalToken),
BlockedReceiver(SignalToken),
NoneBlocked
}
/// Simple queue for threading tasks together. Nodes are stack-allocated, so
/// this structure is not safe at all
struct Queue {
head: *mut Node,
tail: *mut Node,
}
struct Node {
token: Option<SignalToken>,
next: *mut Node,
}
unsafe impl Send for Node {}
/// A simple ring-buffer
struct Buffer<T> {
buf: Vec<Option<T>>,
start: uint,
size: uint,
}
#[derive(Show)]
pub enum Failure {
Empty,
Disconnected,
}
/// Atomically blocks the current thread, placing it into `slot`, unlocking `lock`
/// in the meantime. This re-locks the mutex upon returning.
fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>,
mut guard: MutexGuard<'b, State<T>>,
f: fn(SignalToken) -> Blocker)
-> MutexGuard<'a, State<T>>
{
let (wait_token, signal_token) = blocking::tokens();
match mem::replace(&mut guard.blocker, f(signal_token)) {
NoneBlocked => {}
_ => unreachable!(),
}
drop(guard); // unlock
wait_token.wait(); // block
lock.lock().unwrap() // relock
}
/// Wakes up a thread, dropping the lock at the correct time
fn wakeup<T>(token: SignalToken, guard: MutexGuard<State<T>>) {
// We need to be careful to wake up the waiting task *outside* of the mutex
// in case it incurs a context switch.
drop(guard);
token.signal();
}
impl<T: Send> Packet<T> {
pub fn new(cap: uint) -> Packet<T> {
Packet {
channels: AtomicUsize::new(1),
lock: Mutex::new(State {
disconnected: false,
blocker: NoneBlocked,
cap: cap,
canceled: None,
queue: Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
},
buf: Buffer {
buf: range(0, cap + if cap == 0 {1} else {0}).map(|_| None).collect(),
start: 0,
size: 0,
},
}),
}
}
// wait until a send slot is available, returning locked access to
// the channel state.
fn acquire_send_slot(&self) -> MutexGuard<State<T>> {
let mut node = Node { token: None, next: ptr::null_mut() };
loop {
let mut guard = self.lock.lock().unwrap();
// are we ready to go?
if guard.disconnected || guard.buf.size() < guard.buf.cap() {
return guard;
}
// no room; actually block
let wait_token = guard.queue.enqueue(&mut node);
drop(guard);
wait_token.wait();
}
}
pub fn send(&self, t: T) -> Result<(), T> {
let mut guard = self.acquire_send_slot();
if guard.disconnected { return Err(t) }
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
// if our capacity is 0, then we need to wait for a receiver to be
// available to take our data. After waiting, we check again to make
// sure the port didn't go away in the meantime. If it did, we need
// to hand back our data.
NoneBlocked if guard.cap == 0 => {
let mut canceled = false;
assert!(guard.canceled.is_none());
guard.canceled = Some(unsafe { mem::transmute(&mut canceled) });
let mut guard = wait(&self.lock, guard, BlockedSender);
if canceled {Err(guard.buf.dequeue())} else {Ok(())}
}
// success, we buffered some data
NoneBlocked => Ok(()),
// success, someone's about to receive our buffered data.
BlockedReceiver(token) => { wakeup(token, guard); Ok(()) }
BlockedSender(..) => panic!("lolwut"),
}
}
pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected {
Err(super::TrySendError::Disconnected(t))
} else if guard.buf.size() == guard.buf.cap() {
Err(super::TrySendError::Full(t))
} else if guard.cap == 0 {
// With capacity 0, even though we have buffer space we can't
// transfer the data unless there's a receiver waiting.
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => Err(super::TrySendError::Full(t)),
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => {
guard.buf.enqueue(t);
wakeup(token, guard);
Ok(())
}
}
} else {
// If the buffer has some space and the capacity isn't 0, then we
// just enqueue the data for later retrieval, ensuring to wake up
// any blocked receiver if there is one.
assert!(guard.buf.size() < guard.buf.cap());
guard.buf.enqueue(t);
match mem::replace(&mut guard.blocker, NoneBlocked) {
BlockedReceiver(token) => wakeup(token, guard),
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
}
Ok(())
}
}
// Receives a message from this channel
//
// When reading this, remember that there can only ever be one receiver at
// time.
pub fn recv(&self) -> Result<T, ()> {
let mut guard = self.lock.lock().unwrap();
// Wait for the buffer to have something in it. No need for a while loop
// because we're the only receiver.
let mut waited = false;
if !guard.disconnected && guard.buf.size() == 0 {
guard = wait(&self.lock, guard, BlockedReceiver);
waited = true;
}
if guard.disconnected && guard.buf.size() == 0 { return Err(()) }
// Pick up the data, wake up our neighbors, and carry on
assert!(guard.buf.size() > 0);
let ret = guard.buf.dequeue();
self.wakeup_senders(waited, guard);
return Ok(ret);
}
pub fn try_recv(&self) -> Result<T, Failure> {
let mut guard = self.lock.lock().unwrap();
// Easy cases first
if guard.disconnected { return Err(Disconnected) }
if guard.buf.size() == 0 { return Err(Empty) }
// Be sure to wake up neighbors
let ret = Ok(guard.buf.dequeue());
self.wakeup_senders(false, guard);
return ret;
}
// Wake up pending senders after some data has been received
//
// * `waited` - flag if the receiver blocked to receive some data, or if it
// just picked up some data on the way out
// * `guard` - the lock guard that is held over this channel's lock
fn wakeup_senders(&self, waited: bool, mut guard: MutexGuard<State<T>>) {
let pending_sender1: Option<SignalToken> = guard.queue.dequeue();
// If this is a no-buffer channel (cap == 0), then if we didn't wait we
// need to ACK the sender. If we waited, then the sender waking us up
// was already the ACK.
let pending_sender2 = if guard.cap == 0 && !waited {
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedReceiver(..) => unreachable!(),
BlockedSender(token) => {
guard.canceled.take();
Some(token)
}
}
} else {
None
};
mem::drop(guard);
// only outside of the lock do we wake up the pending tasks
pending_sender1.map(|t| t.signal());
pending_sender2.map(|t| t.signal());
}
// Prepares this shared packet for a channel clone, essentially just bumping
// a refcount.
pub fn clone_chan(&self) {
self.channels.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_chan(&self) {
// Only flag the channel as disconnected if we're the last channel
match self.channels.fetch_sub(1, Ordering::SeqCst) {
1 => {}
_ => return
}
// Not much to do other than wake up a receiver if one's there
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(token) => wakeup(token, guard),
}
}
pub fn | (&self) {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected { return }
guard.disconnected = true;
// If the capacity is 0, then the sender may want its data back after
// we're disconnected. Otherwise it's now our responsibility to destroy
// the buffered data. As with many other portions of this code, this
// needs to be careful to destroy the data *outside* of the lock to
// prevent deadlock.
let _data = if guard.cap != 0 {
mem::replace(&mut guard.buf.buf, Vec::new())
} else {
Vec::new()
};
let mut queue = mem::replace(&mut guard.queue, Queue {
head: ptr::null_mut(),
tail: ptr::null_mut(),
});
let waiter = match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => None,
BlockedSender(token) => {
*guard.canceled.take().unwrap() = true;
Some(token)
}
BlockedReceiver(..) => unreachable!(),
};
mem::drop(guard);
loop {
match queue.dequeue() {
Some(token) => { token.signal(); }
None => break,
}
}
waiter.map(|t| t.signal());
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&self) -> bool {
let guard = self.lock.lock().unwrap();
guard.disconnected || guard.buf.size() > 0
}
// Attempts to start selection on this port. This can either succeed or fail
// because there is data waiting.
pub fn start_selection(&self, token: SignalToken) -> StartResult {
let mut guard = self.lock.lock().unwrap();
if guard.disconnected || guard.buf.size() > 0 {
Abort
} else {
match mem::replace(&mut guard.blocker, BlockedReceiver(token)) {
NoneBlocked => {}
BlockedSender(..) => unreachable!(),
BlockedReceiver(..) => unreachable!(),
}
Installed
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&self) -> bool {
let mut guard = self.lock.lock().unwrap();
match mem::replace(&mut guard.blocker, NoneBlocked) {
NoneBlocked => true,
BlockedSender(token) => {
guard.blocker = BlockedSender(token);
true
}
BlockedReceiver(token) => { drop(token); false }
}
}
}
#[unsafe_destructor]
impl<T: Send> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.channels.load(Ordering::SeqCst), 0);
let mut guard = self.lock.lock().unwrap();
assert!(guard.queue.dequeue().is_none());
assert!(guard.canceled.is_none());
}
}
////////////////////////////////////////////////////////////////////////////////
// Buffer, a simple ring buffer backed by Vec<T>
////////////////////////////////////////////////////////////////////////////////
impl<T> Buffer<T> {
fn enqueue(&mut self, t: T) {
let pos = (self.start + self.size) % self.buf.len();
self.size += 1;
let prev = mem::replace(&mut self.buf[pos], Some(t));
assert!(prev.is_none());
}
fn dequeue(&mut self) -> T {
let start = self.start;
self.size -= 1;
self.start = (self.start + 1) % self.buf.len();
let result = &mut self.buf[start];
result.take().unwrap()
}
fn size(&self) -> uint { self.size }
fn cap(&self) -> uint { self.buf.len() }
}
////////////////////////////////////////////////////////////////////////////////
// Queue, a simple queue to enqueue tasks with (stack-allocated nodes)
////////////////////////////////////////////////////////////////////////////////
impl Queue {
fn enqueue(&mut self, node: &mut Node) -> WaitToken {
let (wait_token, signal_token) = blocking::tokens();
node.token = Some(signal_token);
node.next = ptr::null_mut();
if self.tail.is_null() {
self.head = node as *mut Node;
self.tail = node as *mut Node;
} else {
unsafe {
(*self.tail).next = node as *mut Node;
self.tail = node as *mut Node;
}
}
wait_token
}
fn dequeue(&mut self) -> Option<SignalToken> {
if self.head.is_null() {
return None
}
let node = self.head;
self.head = unsafe { (*node).next };
if self.head.is_null() {
self.tail = ptr::null_mut();
}
unsafe {
(*node).next = ptr::null_mut();
Some((*node).token.take().unwrap())
}
}
}
| drop_port | identifier_name |
angular.js | /*! Raven.js 3.23.1 (84edddc) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2018 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g=(g.Raven||(g.Raven = {}));g=(g.Plugins||(g.Plugins = {}));g.Angular = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Angular.js plugin
*
* Provides an $exceptionHandler for Angular.js
*/
var wrappedCallback = _dereq_(2).wrappedCallback;
// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js
var angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/;
var moduleName = 'ngRaven';
function angularPlugin(Raven, angular) {
angular = angular || window.angular;
if (!angular) return;
function RavenProvider() {
this.$get = [
'$window',
function($window) {
return Raven;
}
];
}
function ExceptionHandlerProvider($provide) {
$provide.decorator('$exceptionHandler', ['Raven', '$delegate', exceptionHandler]);
}
function exceptionHandler(R, $delegate) {
return function(ex, cause) {
R.captureException(ex, {
extra: {cause: cause}
});
$delegate(ex, cause);
};
}
angular
.module(moduleName, [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
var exception = data.exception;
if (exception) {
exception = exception.values[0];
var matches = angularPattern.exec(exception.value);
if (matches) {
// This type now becomes something like: $rootScope:inprog
exception.type = matches[1];
exception.value = matches[2];
data.message = exception.type + ': ' + exception.value;
// auto set a new tag specifically for the angular error url
data.extra.angularDocs = matches[3].substr(0, 250);
}
}
return data;
};
angularPlugin.moduleName = moduleName;
module.exports = angularPlugin;
},{"2":2}],2:[function(_dereq_,module,exports){
(function (global){
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function isObject(what) {
return typeof what === 'object' && what !== null;
}
// Yanked from https://git.io/vS8DV re-used under CC0
// with some tiny modifications
function isError(value) {
switch ({}.toString.call(value)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return value instanceof Error;
}
}
function isErrorEvent(value) {
return supportsErrorEvent() && {}.toString.call(value) === '[object ErrorEvent]';
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isPlainObject(what) {
return Object.prototype.toString.call(what) === '[object Object]';
}
function isString(what) {
return Object.prototype.toString.call(what) === '[object String]';
}
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function isEmptyObject(what) {
if (!isPlainObject(what)) return false;
for (var _ in what) {
if (what.hasOwnProperty(_)) {
return false;
}
}
return true;
}
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsFetch() {
if (!('fetch' in _window)) return false;
try {
new Headers(); // eslint-disable-line no-new
new Request(''); // eslint-disable-line no-new
new Response(); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
function supportsReferrerPolicy() {
if (!supportsFetch()) return false;
try {
// eslint-disable-next-line no-new
new Request('pickleRick', {
referrerPolicy: 'origin'
});
return true;
} catch (e) {
return false;
}
}
function supportsPromiseRejectionEvent() {
return typeof PromiseRejectionEvent === 'function';
}
function wrappedCallback(callback) {
function dataCallback(data, original) {
var normalizedData = callback(data) || data;
if (original) {
return original(normalizedData) || normalizedData;
}
return normalizedData;
}
return dataCallback;
}
function each(obj, callback) {
var i, j;
if (isUndefined(obj.length)) {
for (i in obj) {
if (hasKey(obj, i)) {
callback.call(null, i, obj[i]);
}
}
} else {
j = obj.length;
if (j) {
for (i = 0; i < j; i++) {
callback.call(null, i, obj[i]);
}
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this function in order to check if the object is frozen.
* So it's ok that objectFrozen returns false if Object.isFrozen is not
* supported because it's not relevant for other "platforms". See related issue:
* https://github.com/getsentry/react-native-sentry/issues/57
*/
function objectFrozen(obj) {
if (!Object.isFrozen) {
return false;
}
return Object.isFrozen(obj);
}
function truncate(str, max) {
return !max || str.length <= max ? str : str.substr(0, max) + '\u2026';
}
/**
* hasKey, a better form of hasOwnProperty
* Example: hasKey(MainHostObject, property) === true/false
*
* @param {Object} host object to check property
* @param {string} key to check
*/
function hasKey(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function joinRegExp(patterns) {
// Combine an array of regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'));
} else if (pattern && pattern.source) {
// If it's a regexp already, we want to extract the source
sources.push(pattern.source);
}
// Intentionally skip other cases
}
return new RegExp(sources.join('|'), 'i');
}
function urlencode(o) {
var pairs = [];
each(o, function(key, value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
// borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
// intentionally using regex and not <a/> href parsing trick because React Native and other
// environments where DOM might not be available
function parseUrl(url) {
if (typeof url !== 'string') return {};
var match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
// coerce to undefined values to empty string so we don't get 'undefined'
var query = match[6] || '';
var fragment = match[8] || '';
return {
protocol: match[2],
host: match[4],
path: match[5],
relative: match[5] + query + fragment // everything minus origin
};
}
function uuid4() {
var crypto = _window.crypto || _window.msCrypto;
if (!isUndefined(crypto) && crypto.getRandomValues) {
// Use window.crypto API if available
// eslint-disable-next-line no-undef
var arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
arr[4] = (arr[4] & 0x3fff) | 0x8000;
var pad = function(num) {
var v = num.toString(16);
while (v.length < 4) {
v = '0' + v;
}
return v;
};
return (
pad(arr[0]) +
pad(arr[1]) +
pad(arr[2]) +
pad(arr[3]) +
pad(arr[4]) +
pad(arr[5]) +
pad(arr[6]) +
pad(arr[7])
);
} else {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
}
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @param elem
* @returns {string}
*/
function htmlTreeAsString(elem) {
/* eslint no-extra-parens:0*/
var MAX_TRAVERSE_HEIGHT = 5,
MAX_OUTPUT_LEN = 80,
out = [],
height = 0,
len = 0,
separator = ' > ',
sepLength = separator.length,
nextStr;
while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = htmlElementAsString(elem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (
nextStr === 'html' ||
(height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)
) {
break;
}
out.push(nextStr);
len += nextStr.length;
elem = elem.parentNode;
}
return out.reverse().join(separator);
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @param HTMLElement
* @returns {string}
*/
function htmlElementAsString(elem) {
var out = [],
className,
classes,
key,
attr,
i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push('#' + elem.id);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push('.' + classes[i]);
}
}
var attrWhitelist = ['type', 'name', 'title', 'alt'];
for (i = 0; i < attrWhitelist.length; i++) {
key = attrWhitelist[i];
attr = elem.getAttribute(key);
if (attr) {
out.push('[' + key + '="' + attr + '"]');
}
}
return out.join('');
}
/**
* Returns true if either a OR b is truthy, but not both
*/
function isOnlyOneTruthy(a, b) {
return !!(!!a ^ !!b);
}
/**
* Returns true if both parameters are undefined
*/
function isBothUndefined(a, b) {
return isUndefined(a) && isUndefined(b);
}
/**
* Returns true if the two input exception interfaces have the same content
*/
function isSameException(ex1, ex2) {
if (isOnlyOneTruthy(ex1, ex2)) return false;
ex1 = ex1.values[0];
ex2 = ex2.values[0];
if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false;
// in case both stacktraces are undefined, we can't decide so default to false
if (isBothUndefined(ex1.stacktrace, ex2.stacktrace)) return false;
return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
}
/**
* Returns true if the two input stack trace interfaces have the same content
*/
function isSameStacktrace(stack1, stack2) {
if (isOnlyOneTruthy(stack1, stack2)) return false;
var frames1 = stack1.frames;
var frames2 = stack2.frames;
// Exit early if frame count differs
if (frames1.length !== frames2.length) return false;
// Iterate through every frame; bail out if anything differs
var a, b;
for (var i = 0; i < frames1.length; i++) {
a = frames1[i];
b = frames2[i];
if (
a.filename !== b.filename ||
a.lineno !== b.lineno ||
a.colno !== b.colno ||
a['function'] !== b['function']
)
return false;
}
return true;
}
/**
* Polyfill a method
* @param obj object e.g. `document`
* @param name method name present on object e.g. `addEventListener`
* @param replacement replacement function
* @param track {optional} record instrumentation to an array
*/
function fill(obj, name, replacement, track) {
var orig = obj[name];
obj[name] = replacement(orig);
obj[name].__raven__ = true;
obj[name].__orig__ = orig;
if (track) {
track.push([obj, name, orig]);
}
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns {string}
*/
function safeJoin(input, delimiter) {
if (!isArray(input)) return '';
var output = [];
for (var i = 0; i < input.length; i++) {
try {
output.push(String(input[i]));
} catch (e) {
output.push('[value cannot be serialized]');
}
}
return output.join(delimiter);
}
module.exports = {
isObject: isObject,
isError: isError,
isErrorEvent: isErrorEvent,
isUndefined: isUndefined,
isFunction: isFunction,
isPlainObject: isPlainObject,
isString: isString,
isArray: isArray,
isEmptyObject: isEmptyObject,
supportsErrorEvent: supportsErrorEvent,
supportsFetch: supportsFetch,
supportsReferrerPolicy: supportsReferrerPolicy,
supportsPromiseRejectionEvent: supportsPromiseRejectionEvent,
wrappedCallback: wrappedCallback, | objectMerge: objectMerge,
truncate: truncate,
objectFrozen: objectFrozen,
hasKey: hasKey,
joinRegExp: joinRegExp,
urlencode: urlencode,
uuid4: uuid4,
htmlTreeAsString: htmlTreeAsString,
htmlElementAsString: htmlElementAsString,
isSameException: isSameException,
isSameStacktrace: isSameStacktrace,
parseUrl: parseUrl,
fill: fill,
safeJoin: safeJoin
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
}); | each: each, | random_line_split |
angular.js | /*! Raven.js 3.23.1 (84edddc) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2018 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g=(g.Raven||(g.Raven = {}));g=(g.Plugins||(g.Plugins = {}));g.Angular = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Angular.js plugin
*
* Provides an $exceptionHandler for Angular.js
*/
var wrappedCallback = _dereq_(2).wrappedCallback;
// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js
var angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/;
var moduleName = 'ngRaven';
function angularPlugin(Raven, angular) {
angular = angular || window.angular;
if (!angular) return;
function RavenProvider() {
this.$get = [
'$window',
function($window) {
return Raven;
}
];
}
function ExceptionHandlerProvider($provide) {
$provide.decorator('$exceptionHandler', ['Raven', '$delegate', exceptionHandler]);
}
function exceptionHandler(R, $delegate) {
return function(ex, cause) {
R.captureException(ex, {
extra: {cause: cause}
});
$delegate(ex, cause);
};
}
angular
.module(moduleName, [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
var exception = data.exception;
if (exception) {
exception = exception.values[0];
var matches = angularPattern.exec(exception.value);
if (matches) {
// This type now becomes something like: $rootScope:inprog
exception.type = matches[1];
exception.value = matches[2];
data.message = exception.type + ': ' + exception.value;
// auto set a new tag specifically for the angular error url
data.extra.angularDocs = matches[3].substr(0, 250);
}
}
return data;
};
angularPlugin.moduleName = moduleName;
module.exports = angularPlugin;
},{"2":2}],2:[function(_dereq_,module,exports){
(function (global){
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function isObject(what) {
return typeof what === 'object' && what !== null;
}
// Yanked from https://git.io/vS8DV re-used under CC0
// with some tiny modifications
function isError(value) {
switch ({}.toString.call(value)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return value instanceof Error;
}
}
function isErrorEvent(value) {
return supportsErrorEvent() && {}.toString.call(value) === '[object ErrorEvent]';
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isPlainObject(what) {
return Object.prototype.toString.call(what) === '[object Object]';
}
function isString(what) {
return Object.prototype.toString.call(what) === '[object String]';
}
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function isEmptyObject(what) {
if (!isPlainObject(what)) return false;
for (var _ in what) {
if (what.hasOwnProperty(_)) {
return false;
}
}
return true;
}
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsFetch() {
if (!('fetch' in _window)) return false;
try {
new Headers(); // eslint-disable-line no-new
new Request(''); // eslint-disable-line no-new
new Response(); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
function supportsReferrerPolicy() {
if (!supportsFetch()) return false;
try {
// eslint-disable-next-line no-new
new Request('pickleRick', {
referrerPolicy: 'origin'
});
return true;
} catch (e) {
return false;
}
}
function supportsPromiseRejectionEvent() {
return typeof PromiseRejectionEvent === 'function';
}
function wrappedCallback(callback) {
function dataCallback(data, original) {
var normalizedData = callback(data) || data;
if (original) {
return original(normalizedData) || normalizedData;
}
return normalizedData;
}
return dataCallback;
}
function each(obj, callback) {
var i, j;
if (isUndefined(obj.length)) {
for (i in obj) {
if (hasKey(obj, i)) {
callback.call(null, i, obj[i]);
}
}
} else {
j = obj.length;
if (j) {
for (i = 0; i < j; i++) |
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this function in order to check if the object is frozen.
* So it's ok that objectFrozen returns false if Object.isFrozen is not
* supported because it's not relevant for other "platforms". See related issue:
* https://github.com/getsentry/react-native-sentry/issues/57
*/
function objectFrozen(obj) {
if (!Object.isFrozen) {
return false;
}
return Object.isFrozen(obj);
}
function truncate(str, max) {
return !max || str.length <= max ? str : str.substr(0, max) + '\u2026';
}
/**
* hasKey, a better form of hasOwnProperty
* Example: hasKey(MainHostObject, property) === true/false
*
* @param {Object} host object to check property
* @param {string} key to check
*/
function hasKey(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function joinRegExp(patterns) {
// Combine an array of regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'));
} else if (pattern && pattern.source) {
// If it's a regexp already, we want to extract the source
sources.push(pattern.source);
}
// Intentionally skip other cases
}
return new RegExp(sources.join('|'), 'i');
}
function urlencode(o) {
var pairs = [];
each(o, function(key, value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
// borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
// intentionally using regex and not <a/> href parsing trick because React Native and other
// environments where DOM might not be available
function parseUrl(url) {
if (typeof url !== 'string') return {};
var match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
// coerce to undefined values to empty string so we don't get 'undefined'
var query = match[6] || '';
var fragment = match[8] || '';
return {
protocol: match[2],
host: match[4],
path: match[5],
relative: match[5] + query + fragment // everything minus origin
};
}
function uuid4() {
var crypto = _window.crypto || _window.msCrypto;
if (!isUndefined(crypto) && crypto.getRandomValues) {
// Use window.crypto API if available
// eslint-disable-next-line no-undef
var arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
arr[4] = (arr[4] & 0x3fff) | 0x8000;
var pad = function(num) {
var v = num.toString(16);
while (v.length < 4) {
v = '0' + v;
}
return v;
};
return (
pad(arr[0]) +
pad(arr[1]) +
pad(arr[2]) +
pad(arr[3]) +
pad(arr[4]) +
pad(arr[5]) +
pad(arr[6]) +
pad(arr[7])
);
} else {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
}
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @param elem
* @returns {string}
*/
function htmlTreeAsString(elem) {
/* eslint no-extra-parens:0*/
var MAX_TRAVERSE_HEIGHT = 5,
MAX_OUTPUT_LEN = 80,
out = [],
height = 0,
len = 0,
separator = ' > ',
sepLength = separator.length,
nextStr;
while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = htmlElementAsString(elem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (
nextStr === 'html' ||
(height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)
) {
break;
}
out.push(nextStr);
len += nextStr.length;
elem = elem.parentNode;
}
return out.reverse().join(separator);
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @param HTMLElement
* @returns {string}
*/
function htmlElementAsString(elem) {
var out = [],
className,
classes,
key,
attr,
i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push('#' + elem.id);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push('.' + classes[i]);
}
}
var attrWhitelist = ['type', 'name', 'title', 'alt'];
for (i = 0; i < attrWhitelist.length; i++) {
key = attrWhitelist[i];
attr = elem.getAttribute(key);
if (attr) {
out.push('[' + key + '="' + attr + '"]');
}
}
return out.join('');
}
/**
* Returns true if either a OR b is truthy, but not both
*/
function isOnlyOneTruthy(a, b) {
return !!(!!a ^ !!b);
}
/**
* Returns true if both parameters are undefined
*/
function isBothUndefined(a, b) {
return isUndefined(a) && isUndefined(b);
}
/**
* Returns true if the two input exception interfaces have the same content
*/
function isSameException(ex1, ex2) {
if (isOnlyOneTruthy(ex1, ex2)) return false;
ex1 = ex1.values[0];
ex2 = ex2.values[0];
if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false;
// in case both stacktraces are undefined, we can't decide so default to false
if (isBothUndefined(ex1.stacktrace, ex2.stacktrace)) return false;
return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
}
/**
* Returns true if the two input stack trace interfaces have the same content
*/
function isSameStacktrace(stack1, stack2) {
if (isOnlyOneTruthy(stack1, stack2)) return false;
var frames1 = stack1.frames;
var frames2 = stack2.frames;
// Exit early if frame count differs
if (frames1.length !== frames2.length) return false;
// Iterate through every frame; bail out if anything differs
var a, b;
for (var i = 0; i < frames1.length; i++) {
a = frames1[i];
b = frames2[i];
if (
a.filename !== b.filename ||
a.lineno !== b.lineno ||
a.colno !== b.colno ||
a['function'] !== b['function']
)
return false;
}
return true;
}
/**
* Polyfill a method
* @param obj object e.g. `document`
* @param name method name present on object e.g. `addEventListener`
* @param replacement replacement function
* @param track {optional} record instrumentation to an array
*/
function fill(obj, name, replacement, track) {
var orig = obj[name];
obj[name] = replacement(orig);
obj[name].__raven__ = true;
obj[name].__orig__ = orig;
if (track) {
track.push([obj, name, orig]);
}
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns {string}
*/
function safeJoin(input, delimiter) {
if (!isArray(input)) return '';
var output = [];
for (var i = 0; i < input.length; i++) {
try {
output.push(String(input[i]));
} catch (e) {
output.push('[value cannot be serialized]');
}
}
return output.join(delimiter);
}
module.exports = {
isObject: isObject,
isError: isError,
isErrorEvent: isErrorEvent,
isUndefined: isUndefined,
isFunction: isFunction,
isPlainObject: isPlainObject,
isString: isString,
isArray: isArray,
isEmptyObject: isEmptyObject,
supportsErrorEvent: supportsErrorEvent,
supportsFetch: supportsFetch,
supportsReferrerPolicy: supportsReferrerPolicy,
supportsPromiseRejectionEvent: supportsPromiseRejectionEvent,
wrappedCallback: wrappedCallback,
each: each,
objectMerge: objectMerge,
truncate: truncate,
objectFrozen: objectFrozen,
hasKey: hasKey,
joinRegExp: joinRegExp,
urlencode: urlencode,
uuid4: uuid4,
htmlTreeAsString: htmlTreeAsString,
htmlElementAsString: htmlElementAsString,
isSameException: isSameException,
isSameStacktrace: isSameStacktrace,
parseUrl: parseUrl,
fill: fill,
safeJoin: safeJoin
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
}); | {
callback.call(null, i, obj[i]);
} | conditional_block |
angular.js | /*! Raven.js 3.23.1 (84edddc) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2018 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g=(g.Raven||(g.Raven = {}));g=(g.Plugins||(g.Plugins = {}));g.Angular = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Angular.js plugin
*
* Provides an $exceptionHandler for Angular.js
*/
var wrappedCallback = _dereq_(2).wrappedCallback;
// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js
var angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/;
var moduleName = 'ngRaven';
function angularPlugin(Raven, angular) {
angular = angular || window.angular;
if (!angular) return;
function RavenProvider() {
this.$get = [
'$window',
function($window) {
return Raven;
}
];
}
function ExceptionHandlerProvider($provide) {
$provide.decorator('$exceptionHandler', ['Raven', '$delegate', exceptionHandler]);
}
function exceptionHandler(R, $delegate) {
return function(ex, cause) {
R.captureException(ex, {
extra: {cause: cause}
});
$delegate(ex, cause);
};
}
angular
.module(moduleName, [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
var exception = data.exception;
if (exception) {
exception = exception.values[0];
var matches = angularPattern.exec(exception.value);
if (matches) {
// This type now becomes something like: $rootScope:inprog
exception.type = matches[1];
exception.value = matches[2];
data.message = exception.type + ': ' + exception.value;
// auto set a new tag specifically for the angular error url
data.extra.angularDocs = matches[3].substr(0, 250);
}
}
return data;
};
angularPlugin.moduleName = moduleName;
module.exports = angularPlugin;
},{"2":2}],2:[function(_dereq_,module,exports){
(function (global){
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function isObject(what) {
return typeof what === 'object' && what !== null;
}
// Yanked from https://git.io/vS8DV re-used under CC0
// with some tiny modifications
function isError(value) {
switch ({}.toString.call(value)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return value instanceof Error;
}
}
function isErrorEvent(value) {
return supportsErrorEvent() && {}.toString.call(value) === '[object ErrorEvent]';
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isPlainObject(what) {
return Object.prototype.toString.call(what) === '[object Object]';
}
function isString(what) {
return Object.prototype.toString.call(what) === '[object String]';
}
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function isEmptyObject(what) |
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsFetch() {
if (!('fetch' in _window)) return false;
try {
new Headers(); // eslint-disable-line no-new
new Request(''); // eslint-disable-line no-new
new Response(); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
function supportsReferrerPolicy() {
if (!supportsFetch()) return false;
try {
// eslint-disable-next-line no-new
new Request('pickleRick', {
referrerPolicy: 'origin'
});
return true;
} catch (e) {
return false;
}
}
function supportsPromiseRejectionEvent() {
return typeof PromiseRejectionEvent === 'function';
}
function wrappedCallback(callback) {
function dataCallback(data, original) {
var normalizedData = callback(data) || data;
if (original) {
return original(normalizedData) || normalizedData;
}
return normalizedData;
}
return dataCallback;
}
function each(obj, callback) {
var i, j;
if (isUndefined(obj.length)) {
for (i in obj) {
if (hasKey(obj, i)) {
callback.call(null, i, obj[i]);
}
}
} else {
j = obj.length;
if (j) {
for (i = 0; i < j; i++) {
callback.call(null, i, obj[i]);
}
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this function in order to check if the object is frozen.
* So it's ok that objectFrozen returns false if Object.isFrozen is not
* supported because it's not relevant for other "platforms". See related issue:
* https://github.com/getsentry/react-native-sentry/issues/57
*/
function objectFrozen(obj) {
if (!Object.isFrozen) {
return false;
}
return Object.isFrozen(obj);
}
function truncate(str, max) {
return !max || str.length <= max ? str : str.substr(0, max) + '\u2026';
}
/**
* hasKey, a better form of hasOwnProperty
* Example: hasKey(MainHostObject, property) === true/false
*
* @param {Object} host object to check property
* @param {string} key to check
*/
function hasKey(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function joinRegExp(patterns) {
// Combine an array of regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'));
} else if (pattern && pattern.source) {
// If it's a regexp already, we want to extract the source
sources.push(pattern.source);
}
// Intentionally skip other cases
}
return new RegExp(sources.join('|'), 'i');
}
function urlencode(o) {
var pairs = [];
each(o, function(key, value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
// borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
// intentionally using regex and not <a/> href parsing trick because React Native and other
// environments where DOM might not be available
function parseUrl(url) {
if (typeof url !== 'string') return {};
var match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
// coerce to undefined values to empty string so we don't get 'undefined'
var query = match[6] || '';
var fragment = match[8] || '';
return {
protocol: match[2],
host: match[4],
path: match[5],
relative: match[5] + query + fragment // everything minus origin
};
}
function uuid4() {
var crypto = _window.crypto || _window.msCrypto;
if (!isUndefined(crypto) && crypto.getRandomValues) {
// Use window.crypto API if available
// eslint-disable-next-line no-undef
var arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
arr[4] = (arr[4] & 0x3fff) | 0x8000;
var pad = function(num) {
var v = num.toString(16);
while (v.length < 4) {
v = '0' + v;
}
return v;
};
return (
pad(arr[0]) +
pad(arr[1]) +
pad(arr[2]) +
pad(arr[3]) +
pad(arr[4]) +
pad(arr[5]) +
pad(arr[6]) +
pad(arr[7])
);
} else {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
}
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @param elem
* @returns {string}
*/
function htmlTreeAsString(elem) {
/* eslint no-extra-parens:0*/
var MAX_TRAVERSE_HEIGHT = 5,
MAX_OUTPUT_LEN = 80,
out = [],
height = 0,
len = 0,
separator = ' > ',
sepLength = separator.length,
nextStr;
while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = htmlElementAsString(elem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (
nextStr === 'html' ||
(height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)
) {
break;
}
out.push(nextStr);
len += nextStr.length;
elem = elem.parentNode;
}
return out.reverse().join(separator);
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @param HTMLElement
* @returns {string}
*/
function htmlElementAsString(elem) {
var out = [],
className,
classes,
key,
attr,
i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push('#' + elem.id);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push('.' + classes[i]);
}
}
var attrWhitelist = ['type', 'name', 'title', 'alt'];
for (i = 0; i < attrWhitelist.length; i++) {
key = attrWhitelist[i];
attr = elem.getAttribute(key);
if (attr) {
out.push('[' + key + '="' + attr + '"]');
}
}
return out.join('');
}
/**
* Returns true if either a OR b is truthy, but not both
*/
function isOnlyOneTruthy(a, b) {
return !!(!!a ^ !!b);
}
/**
* Returns true if both parameters are undefined
*/
function isBothUndefined(a, b) {
return isUndefined(a) && isUndefined(b);
}
/**
* Returns true if the two input exception interfaces have the same content
*/
function isSameException(ex1, ex2) {
if (isOnlyOneTruthy(ex1, ex2)) return false;
ex1 = ex1.values[0];
ex2 = ex2.values[0];
if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false;
// in case both stacktraces are undefined, we can't decide so default to false
if (isBothUndefined(ex1.stacktrace, ex2.stacktrace)) return false;
return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
}
/**
* Returns true if the two input stack trace interfaces have the same content
*/
function isSameStacktrace(stack1, stack2) {
if (isOnlyOneTruthy(stack1, stack2)) return false;
var frames1 = stack1.frames;
var frames2 = stack2.frames;
// Exit early if frame count differs
if (frames1.length !== frames2.length) return false;
// Iterate through every frame; bail out if anything differs
var a, b;
for (var i = 0; i < frames1.length; i++) {
a = frames1[i];
b = frames2[i];
if (
a.filename !== b.filename ||
a.lineno !== b.lineno ||
a.colno !== b.colno ||
a['function'] !== b['function']
)
return false;
}
return true;
}
/**
* Polyfill a method
* @param obj object e.g. `document`
* @param name method name present on object e.g. `addEventListener`
* @param replacement replacement function
* @param track {optional} record instrumentation to an array
*/
function fill(obj, name, replacement, track) {
var orig = obj[name];
obj[name] = replacement(orig);
obj[name].__raven__ = true;
obj[name].__orig__ = orig;
if (track) {
track.push([obj, name, orig]);
}
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns {string}
*/
function safeJoin(input, delimiter) {
if (!isArray(input)) return '';
var output = [];
for (var i = 0; i < input.length; i++) {
try {
output.push(String(input[i]));
} catch (e) {
output.push('[value cannot be serialized]');
}
}
return output.join(delimiter);
}
module.exports = {
isObject: isObject,
isError: isError,
isErrorEvent: isErrorEvent,
isUndefined: isUndefined,
isFunction: isFunction,
isPlainObject: isPlainObject,
isString: isString,
isArray: isArray,
isEmptyObject: isEmptyObject,
supportsErrorEvent: supportsErrorEvent,
supportsFetch: supportsFetch,
supportsReferrerPolicy: supportsReferrerPolicy,
supportsPromiseRejectionEvent: supportsPromiseRejectionEvent,
wrappedCallback: wrappedCallback,
each: each,
objectMerge: objectMerge,
truncate: truncate,
objectFrozen: objectFrozen,
hasKey: hasKey,
joinRegExp: joinRegExp,
urlencode: urlencode,
uuid4: uuid4,
htmlTreeAsString: htmlTreeAsString,
htmlElementAsString: htmlElementAsString,
isSameException: isSameException,
isSameStacktrace: isSameStacktrace,
parseUrl: parseUrl,
fill: fill,
safeJoin: safeJoin
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
}); | {
if (!isPlainObject(what)) return false;
for (var _ in what) {
if (what.hasOwnProperty(_)) {
return false;
}
}
return true;
} | identifier_body |
angular.js | /*! Raven.js 3.23.1 (84edddc) | github.com/getsentry/raven-js */
/*
* Includes TraceKit
* https://github.com/getsentry/TraceKit
*
* Copyright 2018 Matt Robenolt and other contributors
* Released under the BSD license
* https://github.com/getsentry/raven-js/blob/master/LICENSE
*
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g=(g.Raven||(g.Raven = {}));g=(g.Plugins||(g.Plugins = {}));g.Angular = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* Angular.js plugin
*
* Provides an $exceptionHandler for Angular.js
*/
var wrappedCallback = _dereq_(2).wrappedCallback;
// See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js
var angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/;
var moduleName = 'ngRaven';
function angularPlugin(Raven, angular) {
angular = angular || window.angular;
if (!angular) return;
function RavenProvider() {
this.$get = [
'$window',
function($window) {
return Raven;
}
];
}
function ExceptionHandlerProvider($provide) {
$provide.decorator('$exceptionHandler', ['Raven', '$delegate', exceptionHandler]);
}
function exceptionHandler(R, $delegate) {
return function(ex, cause) {
R.captureException(ex, {
extra: {cause: cause}
});
$delegate(ex, cause);
};
}
angular
.module(moduleName, [])
.provider('Raven', RavenProvider)
.config(['$provide', ExceptionHandlerProvider]);
Raven.setDataCallback(
wrappedCallback(function(data) {
return angularPlugin._normalizeData(data);
})
);
}
angularPlugin._normalizeData = function(data) {
// We only care about mutating an exception
var exception = data.exception;
if (exception) {
exception = exception.values[0];
var matches = angularPattern.exec(exception.value);
if (matches) {
// This type now becomes something like: $rootScope:inprog
exception.type = matches[1];
exception.value = matches[2];
data.message = exception.type + ': ' + exception.value;
// auto set a new tag specifically for the angular error url
data.extra.angularDocs = matches[3].substr(0, 250);
}
}
return data;
};
angularPlugin.moduleName = moduleName;
module.exports = angularPlugin;
},{"2":2}],2:[function(_dereq_,module,exports){
(function (global){
var _window =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function isObject(what) {
return typeof what === 'object' && what !== null;
}
// Yanked from https://git.io/vS8DV re-used under CC0
// with some tiny modifications
function isError(value) {
switch ({}.toString.call(value)) {
case '[object Error]':
return true;
case '[object Exception]':
return true;
case '[object DOMException]':
return true;
default:
return value instanceof Error;
}
}
function | (value) {
return supportsErrorEvent() && {}.toString.call(value) === '[object ErrorEvent]';
}
function isUndefined(what) {
return what === void 0;
}
function isFunction(what) {
return typeof what === 'function';
}
function isPlainObject(what) {
return Object.prototype.toString.call(what) === '[object Object]';
}
function isString(what) {
return Object.prototype.toString.call(what) === '[object String]';
}
function isArray(what) {
return Object.prototype.toString.call(what) === '[object Array]';
}
function isEmptyObject(what) {
if (!isPlainObject(what)) return false;
for (var _ in what) {
if (what.hasOwnProperty(_)) {
return false;
}
}
return true;
}
function supportsErrorEvent() {
try {
new ErrorEvent(''); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
function supportsFetch() {
if (!('fetch' in _window)) return false;
try {
new Headers(); // eslint-disable-line no-new
new Request(''); // eslint-disable-line no-new
new Response(); // eslint-disable-line no-new
return true;
} catch (e) {
return false;
}
}
// Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
// https://caniuse.com/#feat=referrer-policy
// It doesn't. And it throw exception instead of ignoring this parameter...
// REF: https://github.com/getsentry/raven-js/issues/1233
function supportsReferrerPolicy() {
if (!supportsFetch()) return false;
try {
// eslint-disable-next-line no-new
new Request('pickleRick', {
referrerPolicy: 'origin'
});
return true;
} catch (e) {
return false;
}
}
function supportsPromiseRejectionEvent() {
return typeof PromiseRejectionEvent === 'function';
}
function wrappedCallback(callback) {
function dataCallback(data, original) {
var normalizedData = callback(data) || data;
if (original) {
return original(normalizedData) || normalizedData;
}
return normalizedData;
}
return dataCallback;
}
function each(obj, callback) {
var i, j;
if (isUndefined(obj.length)) {
for (i in obj) {
if (hasKey(obj, i)) {
callback.call(null, i, obj[i]);
}
}
} else {
j = obj.length;
if (j) {
for (i = 0; i < j; i++) {
callback.call(null, i, obj[i]);
}
}
}
}
function objectMerge(obj1, obj2) {
if (!obj2) {
return obj1;
}
each(obj2, function(key, value) {
obj1[key] = value;
});
return obj1;
}
/**
* This function is only used for react-native.
* react-native freezes object that have already been sent over the
* js bridge. We need this function in order to check if the object is frozen.
* So it's ok that objectFrozen returns false if Object.isFrozen is not
* supported because it's not relevant for other "platforms". See related issue:
* https://github.com/getsentry/react-native-sentry/issues/57
*/
function objectFrozen(obj) {
if (!Object.isFrozen) {
return false;
}
return Object.isFrozen(obj);
}
function truncate(str, max) {
return !max || str.length <= max ? str : str.substr(0, max) + '\u2026';
}
/**
* hasKey, a better form of hasOwnProperty
* Example: hasKey(MainHostObject, property) === true/false
*
* @param {Object} host object to check property
* @param {string} key to check
*/
function hasKey(object, key) {
return Object.prototype.hasOwnProperty.call(object, key);
}
function joinRegExp(patterns) {
// Combine an array of regular expressions and strings into one large regexp
// Be mad.
var sources = [],
i = 0,
len = patterns.length,
pattern;
for (; i < len; i++) {
pattern = patterns[i];
if (isString(pattern)) {
// If it's a string, we need to escape it
// Taken from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
sources.push(pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'));
} else if (pattern && pattern.source) {
// If it's a regexp already, we want to extract the source
sources.push(pattern.source);
}
// Intentionally skip other cases
}
return new RegExp(sources.join('|'), 'i');
}
function urlencode(o) {
var pairs = [];
each(o, function(key, value) {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return pairs.join('&');
}
// borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
// intentionally using regex and not <a/> href parsing trick because React Native and other
// environments where DOM might not be available
function parseUrl(url) {
if (typeof url !== 'string') return {};
var match = url.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
// coerce to undefined values to empty string so we don't get 'undefined'
var query = match[6] || '';
var fragment = match[8] || '';
return {
protocol: match[2],
host: match[4],
path: match[5],
relative: match[5] + query + fragment // everything minus origin
};
}
function uuid4() {
var crypto = _window.crypto || _window.msCrypto;
if (!isUndefined(crypto) && crypto.getRandomValues) {
// Use window.crypto API if available
// eslint-disable-next-line no-undef
var arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
arr[4] = (arr[4] & 0x3fff) | 0x8000;
var pad = function(num) {
var v = num.toString(16);
while (v.length < 4) {
v = '0' + v;
}
return v;
};
return (
pad(arr[0]) +
pad(arr[1]) +
pad(arr[2]) +
pad(arr[3]) +
pad(arr[4]) +
pad(arr[5]) +
pad(arr[6]) +
pad(arr[7])
);
} else {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
}
/**
* Given a child DOM element, returns a query-selector statement describing that
* and its ancestors
* e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
* @param elem
* @returns {string}
*/
function htmlTreeAsString(elem) {
/* eslint no-extra-parens:0*/
var MAX_TRAVERSE_HEIGHT = 5,
MAX_OUTPUT_LEN = 80,
out = [],
height = 0,
len = 0,
separator = ' > ',
sepLength = separator.length,
nextStr;
while (elem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = htmlElementAsString(elem);
// bail out if
// - nextStr is the 'html' element
// - the length of the string that would be created exceeds MAX_OUTPUT_LEN
// (ignore this limit if we are on the first iteration)
if (
nextStr === 'html' ||
(height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)
) {
break;
}
out.push(nextStr);
len += nextStr.length;
elem = elem.parentNode;
}
return out.reverse().join(separator);
}
/**
* Returns a simple, query-selector representation of a DOM element
* e.g. [HTMLElement] => input#foo.btn[name=baz]
* @param HTMLElement
* @returns {string}
*/
function htmlElementAsString(elem) {
var out = [],
className,
classes,
key,
attr,
i;
if (!elem || !elem.tagName) {
return '';
}
out.push(elem.tagName.toLowerCase());
if (elem.id) {
out.push('#' + elem.id);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push('.' + classes[i]);
}
}
var attrWhitelist = ['type', 'name', 'title', 'alt'];
for (i = 0; i < attrWhitelist.length; i++) {
key = attrWhitelist[i];
attr = elem.getAttribute(key);
if (attr) {
out.push('[' + key + '="' + attr + '"]');
}
}
return out.join('');
}
/**
* Returns true if either a OR b is truthy, but not both
*/
function isOnlyOneTruthy(a, b) {
return !!(!!a ^ !!b);
}
/**
* Returns true if both parameters are undefined
*/
function isBothUndefined(a, b) {
return isUndefined(a) && isUndefined(b);
}
/**
* Returns true if the two input exception interfaces have the same content
*/
function isSameException(ex1, ex2) {
if (isOnlyOneTruthy(ex1, ex2)) return false;
ex1 = ex1.values[0];
ex2 = ex2.values[0];
if (ex1.type !== ex2.type || ex1.value !== ex2.value) return false;
// in case both stacktraces are undefined, we can't decide so default to false
if (isBothUndefined(ex1.stacktrace, ex2.stacktrace)) return false;
return isSameStacktrace(ex1.stacktrace, ex2.stacktrace);
}
/**
* Returns true if the two input stack trace interfaces have the same content
*/
function isSameStacktrace(stack1, stack2) {
if (isOnlyOneTruthy(stack1, stack2)) return false;
var frames1 = stack1.frames;
var frames2 = stack2.frames;
// Exit early if frame count differs
if (frames1.length !== frames2.length) return false;
// Iterate through every frame; bail out if anything differs
var a, b;
for (var i = 0; i < frames1.length; i++) {
a = frames1[i];
b = frames2[i];
if (
a.filename !== b.filename ||
a.lineno !== b.lineno ||
a.colno !== b.colno ||
a['function'] !== b['function']
)
return false;
}
return true;
}
/**
* Polyfill a method
* @param obj object e.g. `document`
* @param name method name present on object e.g. `addEventListener`
* @param replacement replacement function
* @param track {optional} record instrumentation to an array
*/
function fill(obj, name, replacement, track) {
var orig = obj[name];
obj[name] = replacement(orig);
obj[name].__raven__ = true;
obj[name].__orig__ = orig;
if (track) {
track.push([obj, name, orig]);
}
}
/**
* Join values in array
* @param input array of values to be joined together
* @param delimiter string to be placed in-between values
* @returns {string}
*/
function safeJoin(input, delimiter) {
if (!isArray(input)) return '';
var output = [];
for (var i = 0; i < input.length; i++) {
try {
output.push(String(input[i]));
} catch (e) {
output.push('[value cannot be serialized]');
}
}
return output.join(delimiter);
}
module.exports = {
isObject: isObject,
isError: isError,
isErrorEvent: isErrorEvent,
isUndefined: isUndefined,
isFunction: isFunction,
isPlainObject: isPlainObject,
isString: isString,
isArray: isArray,
isEmptyObject: isEmptyObject,
supportsErrorEvent: supportsErrorEvent,
supportsFetch: supportsFetch,
supportsReferrerPolicy: supportsReferrerPolicy,
supportsPromiseRejectionEvent: supportsPromiseRejectionEvent,
wrappedCallback: wrappedCallback,
each: each,
objectMerge: objectMerge,
truncate: truncate,
objectFrozen: objectFrozen,
hasKey: hasKey,
joinRegExp: joinRegExp,
urlencode: urlencode,
uuid4: uuid4,
htmlTreeAsString: htmlTreeAsString,
htmlElementAsString: htmlElementAsString,
isSameException: isSameException,
isSameStacktrace: isSameStacktrace,
parseUrl: parseUrl,
fill: fill,
safeJoin: safeJoin
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
}); | isErrorEvent | identifier_name |
pydevd_utils.py | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):
# patch provided by: Scott Schlesier - when script is run, it does not
# use globals from pydevd:
# This will prevent the pydevd script from contaminating the namespace for the script to be debugged
# pretend pydevd is not the main module, and
# convince the file to be debugged that it was loaded as main
sys.modules[module_name] = sys.modules['__main__']
sys.modules[module_name].__name__ = module_name
from imp import new_module
m = new_module('__main__')
sys.modules['__main__'] = m
if hasattr(sys.modules[module_name], '__loader__'):
setattr(m, '__loader__', getattr(sys.modules[module_name], '__loader__'))
m.__file__ = file
return m
def to_number(x):
if is_string(x):
try:
n = float(x)
return n
except ValueError:
pass
l = x.find('(')
if l != -1:
y = x[0:l-1]
#print y
try:
n = float(y)
return n
except ValueError:
pass
return None
def compare_object_attrs(x, y):
try:
if x == y:
return 0
x_num = to_number(x)
y_num = to_number(y)
if x_num is not None and y_num is not None:
if x_num - y_num<0:
return -1
else:
return 1
if '__len__' == x:
return -1
if '__len__' == y:
return 1
return x.__cmp__(y)
except:
if IS_PY3K:
return (to_string(x) > to_string(y)) - (to_string(x) < to_string(y))
else:
return cmp(to_string(x), to_string(y))
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K |
else:
def is_string(x):
return isinstance(x, basestring)
def to_string(x):
if is_string(x):
return x
else:
return str(x)
def print_exc():
if traceback:
traceback.print_exc()
if IS_PY3K:
def quote_smart(s, safe='/'):
return quote(s, safe)
else:
def quote_smart(s, safe='/'):
if isinstance(s, unicode):
s = s.encode('utf-8')
return quote(s, safe)
def get_clsname_for_code(code, frame):
clsname = None
if len(code.co_varnames) > 0:
# We are checking the first argument of the function
# (`self` or `cls` for methods).
first_arg_name = code.co_varnames[0]
if first_arg_name in frame.f_locals:
first_arg_obj = frame.f_locals[first_arg_name]
if inspect.isclass(first_arg_obj): # class method
first_arg_class = first_arg_obj
else: # instance method
first_arg_class = first_arg_obj.__class__
func_name = code.co_name
if hasattr(first_arg_class, func_name):
method = getattr(first_arg_class, func_name)
func_code = None
if hasattr(method, 'func_code'): # Python2
func_code = method.func_code
elif hasattr(method, '__code__'): # Python3
func_code = method.__code__
if func_code and func_code == code:
clsname = first_arg_class.__name__
return clsname
def _get_project_roots(project_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not project_roots_cache:
roots = os.getenv('IDE_PROJECT_ROOTS', '').split(os.pathsep)
pydev_log.debug("IDE_PROJECT_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
project_roots_cache.append(new_roots)
return project_roots_cache[-1] # returns the project roots with case normalized
def _get_library_roots(library_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not library_roots_cache:
roots = os.getenv('LIBRARY_ROOTS', '').split(os.pathsep)
pydev_log.debug("LIBRARY_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
library_roots_cache.append(new_roots)
return library_roots_cache[-1] # returns the project roots with case normalized
def not_in_project_roots(filename, filename_to_not_in_scope_cache={}):
# Note: the filename_to_not_in_scope_cache is the same instance among the many calls to the method
try:
return filename_to_not_in_scope_cache[filename]
except:
project_roots = _get_project_roots()
original_filename = filename
if not os.path.isabs(filename) and not filename.startswith('<'):
filename = os.path.abspath(filename)
filename = os.path.normcase(filename)
for root in project_roots:
if filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = False
break
else: # for else (only called if the break wasn't reached).
filename_to_not_in_scope_cache[original_filename] = True
if not filename_to_not_in_scope_cache[original_filename]:
# additional check if interpreter is situated in a project directory
library_roots = _get_library_roots()
for root in library_roots:
if root != '' and filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = True
# at this point it must be loaded.
return filename_to_not_in_scope_cache[original_filename]
def is_filter_enabled():
return os.getenv('PYDEVD_FILTERS') is not None
def is_filter_libraries():
is_filter = os.getenv('PYDEVD_FILTER_LIBRARIES') is not None
pydev_log.debug("PYDEVD_FILTER_LIBRARIES %s\n" % is_filter)
return is_filter
def _get_stepping_filters(filters_cache=[]):
if not filters_cache:
filters = os.getenv('PYDEVD_FILTERS', '').split(';')
pydev_log.debug("PYDEVD_FILTERS %s\n" % filters)
new_filters = []
for new_filter in filters:
new_filters.append(new_filter)
filters_cache.append(new_filters)
return filters_cache[-1]
def is_ignored_by_filter(filename, filename_to_ignored_by_filters_cache={}):
try:
return filename_to_ignored_by_filters_cache[filename]
except:
import fnmatch
for stepping_filter in _get_stepping_filters():
if fnmatch.fnmatch(filename, stepping_filter):
pydev_log.debug("File %s ignored by filter %s" % (filename, stepping_filter))
filename_to_ignored_by_filters_cache[filename] = True
break
else:
filename_to_ignored_by_filters_cache[filename] = False
return filename_to_ignored_by_filters_cache[filename] |
if IS_PY3K:
def is_string(x):
return isinstance(x, str) | random_line_split |
pydevd_utils.py | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):
# patch provided by: Scott Schlesier - when script is run, it does not
# use globals from pydevd:
# This will prevent the pydevd script from contaminating the namespace for the script to be debugged
# pretend pydevd is not the main module, and
# convince the file to be debugged that it was loaded as main
sys.modules[module_name] = sys.modules['__main__']
sys.modules[module_name].__name__ = module_name
from imp import new_module
m = new_module('__main__')
sys.modules['__main__'] = m
if hasattr(sys.modules[module_name], '__loader__'):
setattr(m, '__loader__', getattr(sys.modules[module_name], '__loader__'))
m.__file__ = file
return m
def to_number(x):
if is_string(x):
try:
n = float(x)
return n
except ValueError:
pass
l = x.find('(')
if l != -1:
y = x[0:l-1]
#print y
try:
n = float(y)
return n
except ValueError:
pass
return None
def compare_object_attrs(x, y):
try:
if x == y:
return 0
x_num = to_number(x)
y_num = to_number(y)
if x_num is not None and y_num is not None:
if x_num - y_num<0:
return -1
else:
return 1
if '__len__' == x:
return -1
if '__len__' == y:
return 1
return x.__cmp__(y)
except:
if IS_PY3K:
return (to_string(x) > to_string(y)) - (to_string(x) < to_string(y))
else:
return cmp(to_string(x), to_string(y))
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
if IS_PY3K:
def is_string(x):
return isinstance(x, str)
else:
def is_string(x):
return isinstance(x, basestring)
def to_string(x):
if is_string(x):
return x
else:
return str(x)
def print_exc():
if traceback:
traceback.print_exc()
if IS_PY3K:
def quote_smart(s, safe='/'):
return quote(s, safe)
else:
def | (s, safe='/'):
if isinstance(s, unicode):
s = s.encode('utf-8')
return quote(s, safe)
def get_clsname_for_code(code, frame):
clsname = None
if len(code.co_varnames) > 0:
# We are checking the first argument of the function
# (`self` or `cls` for methods).
first_arg_name = code.co_varnames[0]
if first_arg_name in frame.f_locals:
first_arg_obj = frame.f_locals[first_arg_name]
if inspect.isclass(first_arg_obj): # class method
first_arg_class = first_arg_obj
else: # instance method
first_arg_class = first_arg_obj.__class__
func_name = code.co_name
if hasattr(first_arg_class, func_name):
method = getattr(first_arg_class, func_name)
func_code = None
if hasattr(method, 'func_code'): # Python2
func_code = method.func_code
elif hasattr(method, '__code__'): # Python3
func_code = method.__code__
if func_code and func_code == code:
clsname = first_arg_class.__name__
return clsname
def _get_project_roots(project_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not project_roots_cache:
roots = os.getenv('IDE_PROJECT_ROOTS', '').split(os.pathsep)
pydev_log.debug("IDE_PROJECT_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
project_roots_cache.append(new_roots)
return project_roots_cache[-1] # returns the project roots with case normalized
def _get_library_roots(library_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not library_roots_cache:
roots = os.getenv('LIBRARY_ROOTS', '').split(os.pathsep)
pydev_log.debug("LIBRARY_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
library_roots_cache.append(new_roots)
return library_roots_cache[-1] # returns the project roots with case normalized
def not_in_project_roots(filename, filename_to_not_in_scope_cache={}):
# Note: the filename_to_not_in_scope_cache is the same instance among the many calls to the method
try:
return filename_to_not_in_scope_cache[filename]
except:
project_roots = _get_project_roots()
original_filename = filename
if not os.path.isabs(filename) and not filename.startswith('<'):
filename = os.path.abspath(filename)
filename = os.path.normcase(filename)
for root in project_roots:
if filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = False
break
else: # for else (only called if the break wasn't reached).
filename_to_not_in_scope_cache[original_filename] = True
if not filename_to_not_in_scope_cache[original_filename]:
# additional check if interpreter is situated in a project directory
library_roots = _get_library_roots()
for root in library_roots:
if root != '' and filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = True
# at this point it must be loaded.
return filename_to_not_in_scope_cache[original_filename]
def is_filter_enabled():
return os.getenv('PYDEVD_FILTERS') is not None
def is_filter_libraries():
is_filter = os.getenv('PYDEVD_FILTER_LIBRARIES') is not None
pydev_log.debug("PYDEVD_FILTER_LIBRARIES %s\n" % is_filter)
return is_filter
def _get_stepping_filters(filters_cache=[]):
if not filters_cache:
filters = os.getenv('PYDEVD_FILTERS', '').split(';')
pydev_log.debug("PYDEVD_FILTERS %s\n" % filters)
new_filters = []
for new_filter in filters:
new_filters.append(new_filter)
filters_cache.append(new_filters)
return filters_cache[-1]
def is_ignored_by_filter(filename, filename_to_ignored_by_filters_cache={}):
try:
return filename_to_ignored_by_filters_cache[filename]
except:
import fnmatch
for stepping_filter in _get_stepping_filters():
if fnmatch.fnmatch(filename, stepping_filter):
pydev_log.debug("File %s ignored by filter %s" % (filename, stepping_filter))
filename_to_ignored_by_filters_cache[filename] = True
break
else:
filename_to_ignored_by_filters_cache[filename] = False
return filename_to_ignored_by_filters_cache[filename]
| quote_smart | identifier_name |
pydevd_utils.py | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):
# patch provided by: Scott Schlesier - when script is run, it does not
# use globals from pydevd:
# This will prevent the pydevd script from contaminating the namespace for the script to be debugged
# pretend pydevd is not the main module, and
# convince the file to be debugged that it was loaded as main
sys.modules[module_name] = sys.modules['__main__']
sys.modules[module_name].__name__ = module_name
from imp import new_module
m = new_module('__main__')
sys.modules['__main__'] = m
if hasattr(sys.modules[module_name], '__loader__'):
setattr(m, '__loader__', getattr(sys.modules[module_name], '__loader__'))
m.__file__ = file
return m
def to_number(x):
if is_string(x):
try:
n = float(x)
return n
except ValueError:
pass
l = x.find('(')
if l != -1:
y = x[0:l-1]
#print y
try:
n = float(y)
return n
except ValueError:
pass
return None
def compare_object_attrs(x, y):
try:
if x == y:
return 0
x_num = to_number(x)
y_num = to_number(y)
if x_num is not None and y_num is not None:
if x_num - y_num<0:
return -1
else:
return 1
if '__len__' == x:
return -1
if '__len__' == y:
return 1
return x.__cmp__(y)
except:
if IS_PY3K:
return (to_string(x) > to_string(y)) - (to_string(x) < to_string(y))
else:
return cmp(to_string(x), to_string(y))
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
if IS_PY3K:
def is_string(x):
return isinstance(x, str)
else:
def is_string(x):
return isinstance(x, basestring)
def to_string(x):
if is_string(x):
return x
else:
return str(x)
def print_exc():
if traceback:
traceback.print_exc()
if IS_PY3K:
def quote_smart(s, safe='/'):
return quote(s, safe)
else:
def quote_smart(s, safe='/'):
if isinstance(s, unicode):
s = s.encode('utf-8')
return quote(s, safe)
def get_clsname_for_code(code, frame):
clsname = None
if len(code.co_varnames) > 0:
# We are checking the first argument of the function
# (`self` or `cls` for methods).
first_arg_name = code.co_varnames[0]
if first_arg_name in frame.f_locals:
first_arg_obj = frame.f_locals[first_arg_name]
if inspect.isclass(first_arg_obj): # class method
first_arg_class = first_arg_obj
else: # instance method
first_arg_class = first_arg_obj.__class__
func_name = code.co_name
if hasattr(first_arg_class, func_name):
method = getattr(first_arg_class, func_name)
func_code = None
if hasattr(method, 'func_code'): # Python2
func_code = method.func_code
elif hasattr(method, '__code__'): # Python3
func_code = method.__code__
if func_code and func_code == code:
clsname = first_arg_class.__name__
return clsname
def _get_project_roots(project_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not project_roots_cache:
roots = os.getenv('IDE_PROJECT_ROOTS', '').split(os.pathsep)
pydev_log.debug("IDE_PROJECT_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
project_roots_cache.append(new_roots)
return project_roots_cache[-1] # returns the project roots with case normalized
def _get_library_roots(library_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not library_roots_cache:
roots = os.getenv('LIBRARY_ROOTS', '').split(os.pathsep)
pydev_log.debug("LIBRARY_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
library_roots_cache.append(new_roots)
return library_roots_cache[-1] # returns the project roots with case normalized
def not_in_project_roots(filename, filename_to_not_in_scope_cache={}):
# Note: the filename_to_not_in_scope_cache is the same instance among the many calls to the method
try:
return filename_to_not_in_scope_cache[filename]
except:
project_roots = _get_project_roots()
original_filename = filename
if not os.path.isabs(filename) and not filename.startswith('<'):
filename = os.path.abspath(filename)
filename = os.path.normcase(filename)
for root in project_roots:
if filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = False
break
else: # for else (only called if the break wasn't reached).
filename_to_not_in_scope_cache[original_filename] = True
if not filename_to_not_in_scope_cache[original_filename]:
# additional check if interpreter is situated in a project directory
library_roots = _get_library_roots()
for root in library_roots:
if root != '' and filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = True
# at this point it must be loaded.
return filename_to_not_in_scope_cache[original_filename]
def is_filter_enabled():
return os.getenv('PYDEVD_FILTERS') is not None
def is_filter_libraries():
is_filter = os.getenv('PYDEVD_FILTER_LIBRARIES') is not None
pydev_log.debug("PYDEVD_FILTER_LIBRARIES %s\n" % is_filter)
return is_filter
def _get_stepping_filters(filters_cache=[]):
if not filters_cache:
filters = os.getenv('PYDEVD_FILTERS', '').split(';')
pydev_log.debug("PYDEVD_FILTERS %s\n" % filters)
new_filters = []
for new_filter in filters:
|
filters_cache.append(new_filters)
return filters_cache[-1]
def is_ignored_by_filter(filename, filename_to_ignored_by_filters_cache={}):
try:
return filename_to_ignored_by_filters_cache[filename]
except:
import fnmatch
for stepping_filter in _get_stepping_filters():
if fnmatch.fnmatch(filename, stepping_filter):
pydev_log.debug("File %s ignored by filter %s" % (filename, stepping_filter))
filename_to_ignored_by_filters_cache[filename] = True
break
else:
filename_to_ignored_by_filters_cache[filename] = False
return filename_to_ignored_by_filters_cache[filename]
| new_filters.append(new_filter) | conditional_block |
pydevd_utils.py | from __future__ import nested_scopes
import traceback
import os
try:
from urllib import quote
except:
from urllib.parse import quote # @UnresolvedImport
import inspect
from _pydevd_bundle.pydevd_constants import IS_PY3K
import sys
from _pydev_bundle import pydev_log
def save_main_module(file, module_name):
# patch provided by: Scott Schlesier - when script is run, it does not
# use globals from pydevd:
# This will prevent the pydevd script from contaminating the namespace for the script to be debugged
# pretend pydevd is not the main module, and
# convince the file to be debugged that it was loaded as main
sys.modules[module_name] = sys.modules['__main__']
sys.modules[module_name].__name__ = module_name
from imp import new_module
m = new_module('__main__')
sys.modules['__main__'] = m
if hasattr(sys.modules[module_name], '__loader__'):
setattr(m, '__loader__', getattr(sys.modules[module_name], '__loader__'))
m.__file__ = file
return m
def to_number(x):
if is_string(x):
try:
n = float(x)
return n
except ValueError:
pass
l = x.find('(')
if l != -1:
y = x[0:l-1]
#print y
try:
n = float(y)
return n
except ValueError:
pass
return None
def compare_object_attrs(x, y):
try:
if x == y:
return 0
x_num = to_number(x)
y_num = to_number(y)
if x_num is not None and y_num is not None:
if x_num - y_num<0:
return -1
else:
return 1
if '__len__' == x:
return -1
if '__len__' == y:
return 1
return x.__cmp__(y)
except:
if IS_PY3K:
return (to_string(x) > to_string(y)) - (to_string(x) < to_string(y))
else:
return cmp(to_string(x), to_string(y))
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
if IS_PY3K:
def is_string(x):
return isinstance(x, str)
else:
def is_string(x):
return isinstance(x, basestring)
def to_string(x):
if is_string(x):
return x
else:
return str(x)
def print_exc():
if traceback:
traceback.print_exc()
if IS_PY3K:
def quote_smart(s, safe='/'):
return quote(s, safe)
else:
def quote_smart(s, safe='/'):
if isinstance(s, unicode):
s = s.encode('utf-8')
return quote(s, safe)
def get_clsname_for_code(code, frame):
clsname = None
if len(code.co_varnames) > 0:
# We are checking the first argument of the function
# (`self` or `cls` for methods).
first_arg_name = code.co_varnames[0]
if first_arg_name in frame.f_locals:
first_arg_obj = frame.f_locals[first_arg_name]
if inspect.isclass(first_arg_obj): # class method
first_arg_class = first_arg_obj
else: # instance method
first_arg_class = first_arg_obj.__class__
func_name = code.co_name
if hasattr(first_arg_class, func_name):
method = getattr(first_arg_class, func_name)
func_code = None
if hasattr(method, 'func_code'): # Python2
func_code = method.func_code
elif hasattr(method, '__code__'): # Python3
func_code = method.__code__
if func_code and func_code == code:
clsname = first_arg_class.__name__
return clsname
def _get_project_roots(project_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not project_roots_cache:
roots = os.getenv('IDE_PROJECT_ROOTS', '').split(os.pathsep)
pydev_log.debug("IDE_PROJECT_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
project_roots_cache.append(new_roots)
return project_roots_cache[-1] # returns the project roots with case normalized
def _get_library_roots(library_roots_cache=[]):
# Note: the project_roots_cache is the same instance among the many calls to the method
if not library_roots_cache:
roots = os.getenv('LIBRARY_ROOTS', '').split(os.pathsep)
pydev_log.debug("LIBRARY_ROOTS %s\n" % roots)
new_roots = []
for root in roots:
new_roots.append(os.path.normcase(root))
library_roots_cache.append(new_roots)
return library_roots_cache[-1] # returns the project roots with case normalized
def not_in_project_roots(filename, filename_to_not_in_scope_cache={}):
# Note: the filename_to_not_in_scope_cache is the same instance among the many calls to the method
|
def is_filter_enabled():
return os.getenv('PYDEVD_FILTERS') is not None
def is_filter_libraries():
is_filter = os.getenv('PYDEVD_FILTER_LIBRARIES') is not None
pydev_log.debug("PYDEVD_FILTER_LIBRARIES %s\n" % is_filter)
return is_filter
def _get_stepping_filters(filters_cache=[]):
if not filters_cache:
filters = os.getenv('PYDEVD_FILTERS', '').split(';')
pydev_log.debug("PYDEVD_FILTERS %s\n" % filters)
new_filters = []
for new_filter in filters:
new_filters.append(new_filter)
filters_cache.append(new_filters)
return filters_cache[-1]
def is_ignored_by_filter(filename, filename_to_ignored_by_filters_cache={}):
try:
return filename_to_ignored_by_filters_cache[filename]
except:
import fnmatch
for stepping_filter in _get_stepping_filters():
if fnmatch.fnmatch(filename, stepping_filter):
pydev_log.debug("File %s ignored by filter %s" % (filename, stepping_filter))
filename_to_ignored_by_filters_cache[filename] = True
break
else:
filename_to_ignored_by_filters_cache[filename] = False
return filename_to_ignored_by_filters_cache[filename]
| try:
return filename_to_not_in_scope_cache[filename]
except:
project_roots = _get_project_roots()
original_filename = filename
if not os.path.isabs(filename) and not filename.startswith('<'):
filename = os.path.abspath(filename)
filename = os.path.normcase(filename)
for root in project_roots:
if filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = False
break
else: # for else (only called if the break wasn't reached).
filename_to_not_in_scope_cache[original_filename] = True
if not filename_to_not_in_scope_cache[original_filename]:
# additional check if interpreter is situated in a project directory
library_roots = _get_library_roots()
for root in library_roots:
if root != '' and filename.startswith(root):
filename_to_not_in_scope_cache[original_filename] = True
# at this point it must be loaded.
return filename_to_not_in_scope_cache[original_filename] | identifier_body |
SiteConfig.ts | export class SiteConfig {
constructor() {
$("#smtpAuthType").on("change", this.rebuildVisibility.bind(this));
$("#emailTransport").on("change", this.rebuildVisibility.bind(this)).trigger("change");
}
private | () {
let transport = $("[name=\"mailService[transport]\"]").val(),
auth = $("[name=\"mailService[smtpAuthType]\"]").val();
$('.emailOption').hide();
if (transport == 'sendmail') {
// Nothing to do
} else if (transport == 'mandrill') {
$('.emailOption.mandrillApiKey').show();
} else if (transport == 'mailgun') {
$('.emailOption.mailgunApiKey').show();
$('.emailOption.mailgunDomain').show();
} else if (transport == 'mailjet') {
$('.emailOption.mailjetApiKey').show();
$('.emailOption.mailjetApiSecret').show();
} else if (transport == 'smtp') {
$('.emailOption.smtpHost').show();
$('.emailOption.smtpPort').show();
$('.emailOption.smtpTls').show();
$('.emailOption.smtpAuthType').show();
if (auth != 'none') {
$('.emailOption.smtpUsername').show();
$('.emailOption.smtpPassword').show();
}
}
}
}
| rebuildVisibility | identifier_name |
SiteConfig.ts | export class SiteConfig {
constructor() {
$("#smtpAuthType").on("change", this.rebuildVisibility.bind(this));
$("#emailTransport").on("change", this.rebuildVisibility.bind(this)).trigger("change");
}
private rebuildVisibility() {
let transport = $("[name=\"mailService[transport]\"]").val(),
auth = $("[name=\"mailService[smtpAuthType]\"]").val();
$('.emailOption').hide();
if (transport == 'sendmail') {
// Nothing to do
} else if (transport == 'mandrill') {
$('.emailOption.mandrillApiKey').show();
} else if (transport == 'mailgun') {
$('.emailOption.mailgunApiKey').show();
$('.emailOption.mailgunDomain').show();
} else if (transport == 'mailjet') {
$('.emailOption.mailjetApiKey').show();
$('.emailOption.mailjetApiSecret').show();
} else if (transport == 'smtp') {
$('.emailOption.smtpHost').show();
$('.emailOption.smtpPort').show(); | }
}
}
} | $('.emailOption.smtpTls').show();
$('.emailOption.smtpAuthType').show();
if (auth != 'none') {
$('.emailOption.smtpUsername').show();
$('.emailOption.smtpPassword').show(); | random_line_split |
SiteConfig.ts | export class SiteConfig {
constructor() |
private rebuildVisibility() {
let transport = $("[name=\"mailService[transport]\"]").val(),
auth = $("[name=\"mailService[smtpAuthType]\"]").val();
$('.emailOption').hide();
if (transport == 'sendmail') {
// Nothing to do
} else if (transport == 'mandrill') {
$('.emailOption.mandrillApiKey').show();
} else if (transport == 'mailgun') {
$('.emailOption.mailgunApiKey').show();
$('.emailOption.mailgunDomain').show();
} else if (transport == 'mailjet') {
$('.emailOption.mailjetApiKey').show();
$('.emailOption.mailjetApiSecret').show();
} else if (transport == 'smtp') {
$('.emailOption.smtpHost').show();
$('.emailOption.smtpPort').show();
$('.emailOption.smtpTls').show();
$('.emailOption.smtpAuthType').show();
if (auth != 'none') {
$('.emailOption.smtpUsername').show();
$('.emailOption.smtpPassword').show();
}
}
}
}
| {
$("#smtpAuthType").on("change", this.rebuildVisibility.bind(this));
$("#emailTransport").on("change", this.rebuildVisibility.bind(this)).trigger("change");
} | identifier_body |
sentex_ML_demo7.py | '''
working exercise from sentex tutorials. with mods for clarification + api doc references.
How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9
https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
linear regression model y=mx+b
m = mean(x).mean(y) - mean (x.y)
------------------------------
(mean(x)^2 - mean(x^2)
b = mean(y) - m . mean(x)
'''
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
xs = [1,2,3,4,5,6]
ys = [5,4,6,5,6,7]
#plt.scatter(xs, ys)
#plt.show()
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def best_fit_slope_and_intercept(xs, ys):
m = (mean(xs) * mean(ys) - mean(xs*ys)) / ( mean(xs)*mean(xs) - mean(xs*xs) )
b = mean(ys) - m * mean(xs)
return m, b
m,b = best_fit_slope_and_intercept(xs, ys)
#regression_line = xs*m+b
regression_line = [m*x+b for x in xs]
print ( "m={}".format(m), ", b={}".format(b) )
predict_x = 8
predict_y = (m*predict_x) + b
plt.scatter(xs, ys)
plt.scatter(predict_x, predict_y, color = 'g', marker='s', s=50)
#plt.plot(xs, xs*m+b)
plt.plot(xs, regression_line)
plt.xlabel('xs') | plt.show()
'''
http://matplotlib.org/examples/style_sheets/plot_fivethirtyeight.html
''' | plt.ylabel('ys')
plt.title("plot mx+b using linear regression fit") | random_line_split |
sentex_ML_demo7.py | '''
working exercise from sentex tutorials. with mods for clarification + api doc references.
How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9
https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
linear regression model y=mx+b
m = mean(x).mean(y) - mean (x.y)
------------------------------
(mean(x)^2 - mean(x^2)
b = mean(y) - m . mean(x)
'''
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
xs = [1,2,3,4,5,6]
ys = [5,4,6,5,6,7]
#plt.scatter(xs, ys)
#plt.show()
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def | (xs, ys):
m = (mean(xs) * mean(ys) - mean(xs*ys)) / ( mean(xs)*mean(xs) - mean(xs*xs) )
b = mean(ys) - m * mean(xs)
return m, b
m,b = best_fit_slope_and_intercept(xs, ys)
#regression_line = xs*m+b
regression_line = [m*x+b for x in xs]
print ( "m={}".format(m), ", b={}".format(b) )
predict_x = 8
predict_y = (m*predict_x) + b
plt.scatter(xs, ys)
plt.scatter(predict_x, predict_y, color = 'g', marker='s', s=50)
#plt.plot(xs, xs*m+b)
plt.plot(xs, regression_line)
plt.xlabel('xs')
plt.ylabel('ys')
plt.title("plot mx+b using linear regression fit")
plt.show()
'''
http://matplotlib.org/examples/style_sheets/plot_fivethirtyeight.html
''' | best_fit_slope_and_intercept | identifier_name |
sentex_ML_demo7.py | '''
working exercise from sentex tutorials. with mods for clarification + api doc references.
How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9
https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
linear regression model y=mx+b
m = mean(x).mean(y) - mean (x.y)
------------------------------
(mean(x)^2 - mean(x^2)
b = mean(y) - m . mean(x)
'''
from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
xs = [1,2,3,4,5,6]
ys = [5,4,6,5,6,7]
#plt.scatter(xs, ys)
#plt.show()
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def best_fit_slope_and_intercept(xs, ys):
|
m,b = best_fit_slope_and_intercept(xs, ys)
#regression_line = xs*m+b
regression_line = [m*x+b for x in xs]
print ( "m={}".format(m), ", b={}".format(b) )
predict_x = 8
predict_y = (m*predict_x) + b
plt.scatter(xs, ys)
plt.scatter(predict_x, predict_y, color = 'g', marker='s', s=50)
#plt.plot(xs, xs*m+b)
plt.plot(xs, regression_line)
plt.xlabel('xs')
plt.ylabel('ys')
plt.title("plot mx+b using linear regression fit")
plt.show()
'''
http://matplotlib.org/examples/style_sheets/plot_fivethirtyeight.html
''' | m = (mean(xs) * mean(ys) - mean(xs*ys)) / ( mean(xs)*mean(xs) - mean(xs*xs) )
b = mean(ys) - m * mean(xs)
return m, b | identifier_body |
places.service.ts | /**
*
*/
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { CoordinateModel } from "../models/coordinate.model";
import { PlaceCondensedModel } from "../models/place-condensed.model";
import { ConfigService } from "./config.service";
@Injectable()
export class PlacesService {
constructor(private _http: Http,
private _config: ConfigService) { }
getFlickr(query: string){
let url = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=cb3856e77ccf23b9db42c77ad5c70d96&tags=${query}&per_page=1&format=json&nojsoncallback=1`;
return this._http
.get(url)
.map(res => res.json())
.map((val) => {
if (val.stat === 'ok') {
return val.photos.photo.map((photo: any) => {
let source = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}_b.jpg`;
return {
url: source,
title: photo.title
}
})
}
else |
});
}
list(query: string, coordinate: CoordinateModel) {
const path = this._config.apiUrl + '/places?query={query}&coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{query}', query);
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
getDetails(id: string, coordinate: CoordinateModel){
const path = this._config.apiUrl + '/places/{id}?coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{id}', id);
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
addToFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http
.post(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
deletefromFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http
.delete(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
listTheFavorites(){
const path = this._config.apiUrl + '/places?query=sport&favorites=true';
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
} | {
return [];
} | conditional_block |
places.service.ts | /**
*
*/
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { CoordinateModel } from "../models/coordinate.model";
import { PlaceCondensedModel } from "../models/place-condensed.model";
import { ConfigService } from "./config.service";
@Injectable()
export class PlacesService {
constructor(private _http: Http,
private _config: ConfigService) { }
getFlickr(query: string){
let url = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=cb3856e77ccf23b9db42c77ad5c70d96&tags=${query}&per_page=1&format=json&nojsoncallback=1`;
return this._http
.get(url)
.map(res => res.json())
.map((val) => {
if (val.stat === 'ok') {
return val.photos.photo.map((photo: any) => {
let source = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}_b.jpg`;
return {
url: source,
title: photo.title
}
})
}
else {
return [];
}
});
}
list(query: string, coordinate: CoordinateModel) {
const path = this._config.apiUrl + '/places?query={query}&coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{query}', query);
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
getDetails(id: string, coordinate: CoordinateModel){
const path = this._config.apiUrl + '/places/{id}?coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{id}', id);
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
addToFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http
.post(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
deletefromFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http | }
listTheFavorites(){
const path = this._config.apiUrl + '/places?query=sport&favorites=true';
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
} | .delete(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
}); | random_line_split |
places.service.ts | /**
*
*/
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { CoordinateModel } from "../models/coordinate.model";
import { PlaceCondensedModel } from "../models/place-condensed.model";
import { ConfigService } from "./config.service";
@Injectable()
export class PlacesService {
constructor(private _http: Http,
private _config: ConfigService) { }
getFlickr(query: string){
let url = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=cb3856e77ccf23b9db42c77ad5c70d96&tags=${query}&per_page=1&format=json&nojsoncallback=1`;
return this._http
.get(url)
.map(res => res.json())
.map((val) => {
if (val.stat === 'ok') {
return val.photos.photo.map((photo: any) => {
let source = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}_b.jpg`;
return {
url: source,
title: photo.title
}
})
}
else {
return [];
}
});
}
list(query: string, coordinate: CoordinateModel) {
const path = this._config.apiUrl + '/places?query={query}&coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{query}', query);
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
getDetails(id: string, coordinate: CoordinateModel) |
addToFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http
.post(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
deletefromFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http
.delete(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
listTheFavorites(){
const path = this._config.apiUrl + '/places?query=sport&favorites=true';
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
} | {
const path = this._config.apiUrl + '/places/{id}?coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{id}', id);
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
} | identifier_body |
places.service.ts | /**
*
*/
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { CoordinateModel } from "../models/coordinate.model";
import { PlaceCondensedModel } from "../models/place-condensed.model";
import { ConfigService } from "./config.service";
@Injectable()
export class PlacesService {
constructor(private _http: Http,
private _config: ConfigService) { }
| (query: string){
let url = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=cb3856e77ccf23b9db42c77ad5c70d96&tags=${query}&per_page=1&format=json&nojsoncallback=1`;
return this._http
.get(url)
.map(res => res.json())
.map((val) => {
if (val.stat === 'ok') {
return val.photos.photo.map((photo: any) => {
let source = `https://farm${photo.farm}.staticflickr.com/${photo.server}/${photo.id}_${photo.secret}_b.jpg`;
return {
url: source,
title: photo.title
}
})
}
else {
return [];
}
});
}
list(query: string, coordinate: CoordinateModel) {
const path = this._config.apiUrl + '/places?query={query}&coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{query}', query);
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
getDetails(id: string, coordinate: CoordinateModel){
const path = this._config.apiUrl + '/places/{id}?coordinate={latitude},{longitude}'
.replace('{latitude}', coordinate.lat)
.replace('{longitude}', coordinate.lng)
.replace('{id}', id);
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
addToFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http
.post(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
deletefromFavorite(id: string){
const path = this._config.apiUrl + '/places/{id}/favorite'
.replace('{id}', id);
return this._http
.delete(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
listTheFavorites(){
const path = this._config.apiUrl + '/places?query=sport&favorites=true';
return this._http
.get(path, { headers: this._config.apiHeaders.Default })
.map((res: Response) => {
return res.json();
});
}
} | getFlickr | identifier_name |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
const YEAR: f64 = 365.24;
const N_BODIES: uint = 5;
static BODIES: [Planet;N_BODIES] = [
// Sun
Planet {
x: 0.0, y: 0.0, z: 0.0,
vx: 0.0, vy: 0.0, vz: 0.0,
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * YEAR,
vy: 7.69901118419740425e-03 * YEAR,
vz: -6.90460016972063023e-05 * YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * YEAR,
vy: 4.99852801234917238e-03 * YEAR,
vz: 2.30417297573763929e-05 * YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * YEAR,
vy: 2.37847173959480950e-03 * YEAR,
vz: -2.96589568540237556e-05 * YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune
Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR,
vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let d2 = dx * dx + dy * dy + dz * dz;
let mag = dt / (d2 * d2.sqrt());
let massj_mag = bj.mass * mag;
bi.vx -= dx * massj_mag;
bi.vy -= dy * massj_mag;
bi.vz -= dz * massj_mag;
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &[Planet;N_BODIES]) -> f64 {
let mut e = 0.0;
let mut bodies = bodies.iter();
loop {
let bi = match bodies.next() {
Some(bi) => bi,
None => break
};
e += (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass / 2.0;
for bj in bodies.clone() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
e -= bi.mass * bj.mass / dist;
}
}
e
}
fn offset_momentum(bodies: &mut [Planet;N_BODIES]) {
let mut px = 0.0;
let mut py = 0.0;
let mut pz = 0.0;
for bi in bodies.iter() {
px += bi.vx * bi.mass;
py += bi.vy * bi.mass;
pz += bi.vz * bi.mass;
}
let sun = &mut bodies[0];
sun.vx = - px / SOLAR_MASS;
sun.vy = - py / SOLAR_MASS;
sun.vz = - pz / SOLAR_MASS;
}
fn main() {
let n = if std::os::getenv("RUST_BENCH").is_some() {
5000000
} else {
std::os::args().as_slice().get(1)
.and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println!("{:.9}", energy(&bodies));
advance(&mut bodies, 0.01, n);
println!("{:.9}", energy(&bodies));
}
/// Pop a mutable reference off the head of a slice, mutating the slice to no
/// longer contain the mutable reference. This is a safe operation because the
/// two mutable borrows are entirely disjoint.
fn | <'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 { return None }
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
}
| shift_mut_ref | identifier_name |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
const YEAR: f64 = 365.24;
const N_BODIES: uint = 5;
static BODIES: [Planet;N_BODIES] = [
// Sun
Planet {
x: 0.0, y: 0.0, z: 0.0,
vx: 0.0, vy: 0.0, vz: 0.0,
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * YEAR,
vy: 7.69901118419740425e-03 * YEAR,
vz: -6.90460016972063023e-05 * YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * YEAR,
vy: 4.99852801234917238e-03 * YEAR,
vz: 2.30417297573763929e-05 * YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * YEAR,
vy: 2.37847173959480950e-03 * YEAR,
vz: -2.96589568540237556e-05 * YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune
Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR,
vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) |
fn energy(bodies: &[Planet;N_BODIES]) -> f64 {
let mut e = 0.0;
let mut bodies = bodies.iter();
loop {
let bi = match bodies.next() {
Some(bi) => bi,
None => break
};
e += (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass / 2.0;
for bj in bodies.clone() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
e -= bi.mass * bj.mass / dist;
}
}
e
}
fn offset_momentum(bodies: &mut [Planet;N_BODIES]) {
let mut px = 0.0;
let mut py = 0.0;
let mut pz = 0.0;
for bi in bodies.iter() {
px += bi.vx * bi.mass;
py += bi.vy * bi.mass;
pz += bi.vz * bi.mass;
}
let sun = &mut bodies[0];
sun.vx = - px / SOLAR_MASS;
sun.vy = - py / SOLAR_MASS;
sun.vz = - pz / SOLAR_MASS;
}
fn main() {
let n = if std::os::getenv("RUST_BENCH").is_some() {
5000000
} else {
std::os::args().as_slice().get(1)
.and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println!("{:.9}", energy(&bodies));
advance(&mut bodies, 0.01, n);
println!("{:.9}", energy(&bodies));
}
/// Pop a mutable reference off the head of a slice, mutating the slice to no
/// longer contain the mutable reference. This is a safe operation because the
/// two mutable borrows are entirely disjoint.
fn shift_mut_ref<'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 { return None }
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
}
| {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let d2 = dx * dx + dy * dy + dz * dz;
let mag = dt / (d2 * d2.sqrt());
let massj_mag = bj.mass * mag;
bi.vx -= dx * massj_mag;
bi.vy -= dy * massj_mag;
bi.vz -= dz * massj_mag;
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
} | identifier_body |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
const YEAR: f64 = 365.24;
const N_BODIES: uint = 5;
static BODIES: [Planet;N_BODIES] = [
// Sun
Planet {
x: 0.0, y: 0.0, z: 0.0,
vx: 0.0, vy: 0.0, vz: 0.0,
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * YEAR,
vy: 7.69901118419740425e-03 * YEAR,
vz: -6.90460016972063023e-05 * YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * YEAR,
vy: 4.99852801234917238e-03 * YEAR,
vz: 2.30417297573763929e-05 * YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * YEAR,
vy: 2.37847173959480950e-03 * YEAR,
vz: -2.96589568540237556e-05 * YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune | vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let d2 = dx * dx + dy * dy + dz * dz;
let mag = dt / (d2 * d2.sqrt());
let massj_mag = bj.mass * mag;
bi.vx -= dx * massj_mag;
bi.vy -= dy * massj_mag;
bi.vz -= dz * massj_mag;
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &[Planet;N_BODIES]) -> f64 {
let mut e = 0.0;
let mut bodies = bodies.iter();
loop {
let bi = match bodies.next() {
Some(bi) => bi,
None => break
};
e += (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass / 2.0;
for bj in bodies.clone() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
e -= bi.mass * bj.mass / dist;
}
}
e
}
fn offset_momentum(bodies: &mut [Planet;N_BODIES]) {
let mut px = 0.0;
let mut py = 0.0;
let mut pz = 0.0;
for bi in bodies.iter() {
px += bi.vx * bi.mass;
py += bi.vy * bi.mass;
pz += bi.vz * bi.mass;
}
let sun = &mut bodies[0];
sun.vx = - px / SOLAR_MASS;
sun.vy = - py / SOLAR_MASS;
sun.vz = - pz / SOLAR_MASS;
}
fn main() {
let n = if std::os::getenv("RUST_BENCH").is_some() {
5000000
} else {
std::os::args().as_slice().get(1)
.and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println!("{:.9}", energy(&bodies));
advance(&mut bodies, 0.01, n);
println!("{:.9}", energy(&bodies));
}
/// Pop a mutable reference off the head of a slice, mutating the slice to no
/// longer contain the mutable reference. This is a safe operation because the
/// two mutable borrows are entirely disjoint.
fn shift_mut_ref<'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 { return None }
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
} | Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR, | random_line_split |
shootout-nbody.rs | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2011-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
use std::num::Float;
const PI: f64 = 3.141592653589793;
const SOLAR_MASS: f64 = 4.0 * PI * PI;
const YEAR: f64 = 365.24;
const N_BODIES: uint = 5;
static BODIES: [Planet;N_BODIES] = [
// Sun
Planet {
x: 0.0, y: 0.0, z: 0.0,
vx: 0.0, vy: 0.0, vz: 0.0,
mass: SOLAR_MASS,
},
// Jupiter
Planet {
x: 4.84143144246472090e+00,
y: -1.16032004402742839e+00,
z: -1.03622044471123109e-01,
vx: 1.66007664274403694e-03 * YEAR,
vy: 7.69901118419740425e-03 * YEAR,
vz: -6.90460016972063023e-05 * YEAR,
mass: 9.54791938424326609e-04 * SOLAR_MASS,
},
// Saturn
Planet {
x: 8.34336671824457987e+00,
y: 4.12479856412430479e+00,
z: -4.03523417114321381e-01,
vx: -2.76742510726862411e-03 * YEAR,
vy: 4.99852801234917238e-03 * YEAR,
vz: 2.30417297573763929e-05 * YEAR,
mass: 2.85885980666130812e-04 * SOLAR_MASS,
},
// Uranus
Planet {
x: 1.28943695621391310e+01,
y: -1.51111514016986312e+01,
z: -2.23307578892655734e-01,
vx: 2.96460137564761618e-03 * YEAR,
vy: 2.37847173959480950e-03 * YEAR,
vz: -2.96589568540237556e-05 * YEAR,
mass: 4.36624404335156298e-05 * SOLAR_MASS,
},
// Neptune
Planet {
x: 1.53796971148509165e+01,
y: -2.59193146099879641e+01,
z: 1.79258772950371181e-01,
vx: 2.68067772490389322e-03 * YEAR,
vy: 1.62824170038242295e-03 * YEAR,
vz: -9.51592254519715870e-05 * YEAR,
mass: 5.15138902046611451e-05 * SOLAR_MASS,
},
];
struct Planet {
x: f64, y: f64, z: f64,
vx: f64, vy: f64, vz: f64,
mass: f64,
}
impl Copy for Planet {}
fn advance(bodies: &mut [Planet;N_BODIES], dt: f64, steps: int) {
for _ in range(0, steps) {
let mut b_slice = bodies.as_mut_slice();
loop {
let bi = match shift_mut_ref(&mut b_slice) {
Some(bi) => bi,
None => break
};
for bj in b_slice.iter_mut() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let d2 = dx * dx + dy * dy + dz * dz;
let mag = dt / (d2 * d2.sqrt());
let massj_mag = bj.mass * mag;
bi.vx -= dx * massj_mag;
bi.vy -= dy * massj_mag;
bi.vz -= dz * massj_mag;
let massi_mag = bi.mass * mag;
bj.vx += dx * massi_mag;
bj.vy += dy * massi_mag;
bj.vz += dz * massi_mag;
}
bi.x += dt * bi.vx;
bi.y += dt * bi.vy;
bi.z += dt * bi.vz;
}
}
}
fn energy(bodies: &[Planet;N_BODIES]) -> f64 {
let mut e = 0.0;
let mut bodies = bodies.iter();
loop {
let bi = match bodies.next() {
Some(bi) => bi,
None => break
};
e += (bi.vx * bi.vx + bi.vy * bi.vy + bi.vz * bi.vz) * bi.mass / 2.0;
for bj in bodies.clone() {
let dx = bi.x - bj.x;
let dy = bi.y - bj.y;
let dz = bi.z - bj.z;
let dist = (dx * dx + dy * dy + dz * dz).sqrt();
e -= bi.mass * bj.mass / dist;
}
}
e
}
fn offset_momentum(bodies: &mut [Planet;N_BODIES]) {
let mut px = 0.0;
let mut py = 0.0;
let mut pz = 0.0;
for bi in bodies.iter() {
px += bi.vx * bi.mass;
py += bi.vy * bi.mass;
pz += bi.vz * bi.mass;
}
let sun = &mut bodies[0];
sun.vx = - px / SOLAR_MASS;
sun.vy = - py / SOLAR_MASS;
sun.vz = - pz / SOLAR_MASS;
}
fn main() {
let n = if std::os::getenv("RUST_BENCH").is_some() {
5000000
} else {
std::os::args().as_slice().get(1)
.and_then(|arg| arg.parse())
.unwrap_or(1000)
};
let mut bodies = BODIES;
offset_momentum(&mut bodies);
println!("{:.9}", energy(&bodies));
advance(&mut bodies, 0.01, n);
println!("{:.9}", energy(&bodies));
}
/// Pop a mutable reference off the head of a slice, mutating the slice to no
/// longer contain the mutable reference. This is a safe operation because the
/// two mutable borrows are entirely disjoint.
fn shift_mut_ref<'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> {
use std::mem;
use std::raw::Repr;
if r.len() == 0 |
unsafe {
let mut raw = r.repr();
let ret = raw.data as *mut T;
raw.data = raw.data.offset(1);
raw.len -= 1;
*r = mem::transmute(raw);
Some(unsafe { &mut *ret })
}
}
| { return None } | conditional_block |
custom_exceptions.py | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
def | (self):
return self.message
def get_status_code(self):
return self.status_code
errors = {
510: 'Error fetching available data providers.',
511: 'Data provider is not currently supported.',
512: 'Source type is not currently supported.',
513: 'Error while parsing the payload of the request.',
# geoserver
520: "There is already a store named",
521: "No coverage store named",
522: "Layer file doesn't exists",
523: "Error creating workspace",
# Data processing
550: "Error processing data",
} | get_message | identifier_name |
custom_exceptions.py | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
def get_message(self):
return self.message
def get_status_code(self):
return self.status_code
errors = {
510: 'Error fetching available data providers.',
511: 'Data provider is not currently supported.',
512: 'Source type is not currently supported.',
513: 'Error while parsing the payload of the request.',
# geoserver
520: "There is already a store named",
521: "No coverage store named",
522: "Layer file doesn't exists",
523: "Error creating workspace",
| # Data processing
550: "Error processing data",
} | random_line_split | |
custom_exceptions.py | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
|
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
def get_message(self):
return self.message
def get_status_code(self):
return self.status_code
errors = {
510: 'Error fetching available data providers.',
511: 'Data provider is not currently supported.',
512: 'Source type is not currently supported.',
513: 'Error while parsing the payload of the request.',
# geoserver
520: "There is already a store named",
521: "No coverage store named",
522: "Layer file doesn't exists",
523: "Error creating workspace",
# Data processing
550: "Error processing data",
} | self.status_code = status_code | conditional_block |
custom_exceptions.py | class PGeoException(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self, message)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
def get_message(self):
|
def get_status_code(self):
return self.status_code
errors = {
510: 'Error fetching available data providers.',
511: 'Data provider is not currently supported.',
512: 'Source type is not currently supported.',
513: 'Error while parsing the payload of the request.',
# geoserver
520: "There is already a store named",
521: "No coverage store named",
522: "Layer file doesn't exists",
523: "Error creating workspace",
# Data processing
550: "Error processing data",
} | return self.message | identifier_body |
main.py | from flask import Blueprint, request, current_app as app
from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed
import json
import datetime
import twitter
blueprint = Blueprint("main", __name__)
class MainView(TemplateView):
template_name = "main/index.html"
title = "Post Tweets Anonymously"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
context = super(MainView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if ratelimit.reached(app.config["POST_TWEET_HOURLY_LIMIT"], 60*60):
context["error"] = "You have reached the rate limit must wait before posting more tweets."
return context
tweet = request.form.get("tweet", None)
allowed, err = is_tweet_allowed(tweet)
if not allowed:
context["error"] = err
return context
auth = random_twitter_auth()
if auth is None:
context["error"] = "Could not obtain a Twitter authorization. Please try again later."
return context
api = twitter.Api(consumer_key=app.config["TWITTER_OAUTH_KEY"],
consumer_secret=app.config["TWITTER_OAUTH_SECRET"],
access_token_key=auth.oauth_token,
access_token_secret=auth.oauth_token_secret)
image = request.files["image"] if "image" in request.files else None | except twitter.TwitterError as e:
context["error"] = e.message[0]["message"]
return context
return context
class OptOutHandleView(TemplateView):
template_name = "main/opt-out.html"
title = "Opt-out"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
context = super(OptOutHandleView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if not app.config["INDEX_POSTING_ENABLED"]:
context["error"] = "Posting Tweets from the site index is currently disabled."
return context
if ratelimit.reached(app.config["OPT_OUT_HOURLY_LIMIT"], 60*60):
context["error"] = "You have opted out too many handles and need to wait to submit more."
return context
handle = request.form.get("handle").lower()
if handle[:1] == "@":
handle = handle[1:]
if len(handle) > 15:
context["error"] = "The handle you specified is too long."
elif Blacklisted.query.filter_by(handle=handle).first():
context["error"] = "The handle you specified is already blacklisted."
else:
context["message"] = "The handle you specified is now opted-out."
db.session.add(Blacklisted(handle))
db.session.commit()
return context
blueprint.add_url_rule("/", view_func=MainView.as_view("main"))
blueprint.add_url_rule("/opt-out", view_func=OptOutHandleView.as_view("opt-out")) | if image is not None:
image.mode = "rb"
try:
status = api.PostUpdate(tweet, image)
context["tweet"] = "https://twitter.com/{}/status/{}".format(status.user.name, status.id) | random_line_split |
main.py | from flask import Blueprint, request, current_app as app
from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed
import json
import datetime
import twitter
blueprint = Blueprint("main", __name__)
class MainView(TemplateView):
template_name = "main/index.html"
title = "Post Tweets Anonymously"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
context = super(MainView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if ratelimit.reached(app.config["POST_TWEET_HOURLY_LIMIT"], 60*60):
context["error"] = "You have reached the rate limit must wait before posting more tweets."
return context
tweet = request.form.get("tweet", None)
allowed, err = is_tweet_allowed(tweet)
if not allowed:
context["error"] = err
return context
auth = random_twitter_auth()
if auth is None:
context["error"] = "Could not obtain a Twitter authorization. Please try again later."
return context
api = twitter.Api(consumer_key=app.config["TWITTER_OAUTH_KEY"],
consumer_secret=app.config["TWITTER_OAUTH_SECRET"],
access_token_key=auth.oauth_token,
access_token_secret=auth.oauth_token_secret)
image = request.files["image"] if "image" in request.files else None
if image is not None:
|
try:
status = api.PostUpdate(tweet, image)
context["tweet"] = "https://twitter.com/{}/status/{}".format(status.user.name, status.id)
except twitter.TwitterError as e:
context["error"] = e.message[0]["message"]
return context
return context
class OptOutHandleView(TemplateView):
template_name = "main/opt-out.html"
title = "Opt-out"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
context = super(OptOutHandleView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if not app.config["INDEX_POSTING_ENABLED"]:
context["error"] = "Posting Tweets from the site index is currently disabled."
return context
if ratelimit.reached(app.config["OPT_OUT_HOURLY_LIMIT"], 60*60):
context["error"] = "You have opted out too many handles and need to wait to submit more."
return context
handle = request.form.get("handle").lower()
if handle[:1] == "@":
handle = handle[1:]
if len(handle) > 15:
context["error"] = "The handle you specified is too long."
elif Blacklisted.query.filter_by(handle=handle).first():
context["error"] = "The handle you specified is already blacklisted."
else:
context["message"] = "The handle you specified is now opted-out."
db.session.add(Blacklisted(handle))
db.session.commit()
return context
blueprint.add_url_rule("/", view_func=MainView.as_view("main"))
blueprint.add_url_rule("/opt-out", view_func=OptOutHandleView.as_view("opt-out"))
| image.mode = "rb" | conditional_block |
main.py | from flask import Blueprint, request, current_app as app
from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed
import json
import datetime
import twitter
blueprint = Blueprint("main", __name__)
class MainView(TemplateView):
template_name = "main/index.html"
title = "Post Tweets Anonymously"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
context = super(MainView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if ratelimit.reached(app.config["POST_TWEET_HOURLY_LIMIT"], 60*60):
context["error"] = "You have reached the rate limit must wait before posting more tweets."
return context
tweet = request.form.get("tweet", None)
allowed, err = is_tweet_allowed(tweet)
if not allowed:
context["error"] = err
return context
auth = random_twitter_auth()
if auth is None:
context["error"] = "Could not obtain a Twitter authorization. Please try again later."
return context
api = twitter.Api(consumer_key=app.config["TWITTER_OAUTH_KEY"],
consumer_secret=app.config["TWITTER_OAUTH_SECRET"],
access_token_key=auth.oauth_token,
access_token_secret=auth.oauth_token_secret)
image = request.files["image"] if "image" in request.files else None
if image is not None:
image.mode = "rb"
try:
status = api.PostUpdate(tweet, image)
context["tweet"] = "https://twitter.com/{}/status/{}".format(status.user.name, status.id)
except twitter.TwitterError as e:
context["error"] = e.message[0]["message"]
return context
return context
class OptOutHandleView(TemplateView):
template_name = "main/opt-out.html"
title = "Opt-out"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
|
blueprint.add_url_rule("/", view_func=MainView.as_view("main"))
blueprint.add_url_rule("/opt-out", view_func=OptOutHandleView.as_view("opt-out"))
| context = super(OptOutHandleView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if not app.config["INDEX_POSTING_ENABLED"]:
context["error"] = "Posting Tweets from the site index is currently disabled."
return context
if ratelimit.reached(app.config["OPT_OUT_HOURLY_LIMIT"], 60*60):
context["error"] = "You have opted out too many handles and need to wait to submit more."
return context
handle = request.form.get("handle").lower()
if handle[:1] == "@":
handle = handle[1:]
if len(handle) > 15:
context["error"] = "The handle you specified is too long."
elif Blacklisted.query.filter_by(handle=handle).first():
context["error"] = "The handle you specified is already blacklisted."
else:
context["message"] = "The handle you specified is now opted-out."
db.session.add(Blacklisted(handle))
db.session.commit()
return context | identifier_body |
main.py | from flask import Blueprint, request, current_app as app
from twoxy.blueprints.base import TemplateView
from twoxy.database.models import Blacklisted
from twoxy.database import db_ctx as db
from twoxy.util import ratelimit, random_twitter_auth, is_tweet_allowed
import json
import datetime
import twitter
blueprint = Blueprint("main", __name__)
class MainView(TemplateView):
template_name = "main/index.html"
title = "Post Tweets Anonymously"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
context = super(MainView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if ratelimit.reached(app.config["POST_TWEET_HOURLY_LIMIT"], 60*60):
context["error"] = "You have reached the rate limit must wait before posting more tweets."
return context
tweet = request.form.get("tweet", None)
allowed, err = is_tweet_allowed(tweet)
if not allowed:
context["error"] = err
return context
auth = random_twitter_auth()
if auth is None:
context["error"] = "Could not obtain a Twitter authorization. Please try again later."
return context
api = twitter.Api(consumer_key=app.config["TWITTER_OAUTH_KEY"],
consumer_secret=app.config["TWITTER_OAUTH_SECRET"],
access_token_key=auth.oauth_token,
access_token_secret=auth.oauth_token_secret)
image = request.files["image"] if "image" in request.files else None
if image is not None:
image.mode = "rb"
try:
status = api.PostUpdate(tweet, image)
context["tweet"] = "https://twitter.com/{}/status/{}".format(status.user.name, status.id)
except twitter.TwitterError as e:
context["error"] = e.message[0]["message"]
return context
return context
class | (TemplateView):
template_name = "main/opt-out.html"
title = "Opt-out"
methods = ["GET", "POST"]
def get_context_data(self, *args, **kwargs):
context = super(OptOutHandleView, self).get_context_data(*args, **kwargs)
if request.method == "POST":
if not app.config["INDEX_POSTING_ENABLED"]:
context["error"] = "Posting Tweets from the site index is currently disabled."
return context
if ratelimit.reached(app.config["OPT_OUT_HOURLY_LIMIT"], 60*60):
context["error"] = "You have opted out too many handles and need to wait to submit more."
return context
handle = request.form.get("handle").lower()
if handle[:1] == "@":
handle = handle[1:]
if len(handle) > 15:
context["error"] = "The handle you specified is too long."
elif Blacklisted.query.filter_by(handle=handle).first():
context["error"] = "The handle you specified is already blacklisted."
else:
context["message"] = "The handle you specified is now opted-out."
db.session.add(Blacklisted(handle))
db.session.commit()
return context
blueprint.add_url_rule("/", view_func=MainView.as_view("main"))
blueprint.add_url_rule("/opt-out", view_func=OptOutHandleView.as_view("opt-out"))
| OptOutHandleView | identifier_name |
index.d.ts | // Type definitions for nouislider v9.0.0
// Project: https://github.com/leongersen/noUiSlider
// Definitions by: Patrick Davies <https://github.com/bleuarg>, Guust Nieuwenhuis <https://github.com/lagaffe>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="wnumb"/>
export = noUiSlider;
export as namespace noUiSlider;
declare namespace noUiSlider { | /**
* To create a slider, call noUiSlider.create() with an element and your options.
*/
function create(target: HTMLElement, options: Options): void;
interface Options {
/**
* The start option sets the number of handles and their start positions, relative to range.
*/
start: number | number[] | number[][];
/**
* All values on the slider are part of a range. The range has a minimum and maximum value.
* The minimum value cannot be equal to the maximum value.
*/
range: { [key: string]: number | number[] };
/**
* The connect setting can be used to control the (green) bar between the handles, or the edges of the slider.
* Pass an array with a boolean for every connecting element, including the edges of the slider.
* The length of this array must match the handle count + 1.
* Setting true sets the bars between the handles, but not between the handles and the sliders edges.
*/
connect?: boolean | boolean[];
/**
* When using two handles, the minimum distance between the handles can be set using the margin option.
* The margin value is relative to the value set in 'range'.
* This option is only available on standard linear sliders.
*/
margin?: number;
/**
* The limit option is the opposite of the margin option,
* limiting the maximum distance between two handles.
* As with the margin option, the limit option can only be used on linear sliders.
*/
limit?: number;
/**
* Padding limits how close to the slider edges handles can be.
*/
padding?: number;
/**
* By default, the slider slides fluently.
* In order to make the handles jump between intervals, you can use this option.
* The step option is relative to the values provided to range.
*/
step?: number;
/**
* The orientation setting can be used to set the slider to "vertical" or "horizontal".
* Set dimensions! Vertical sliders don't assume a default height, so you'll need to set one.
* You can use any unit you want, including % or px.
*/
orientation?: 'vertical' | 'horizontal';
/**
* By default the sliders are top-to-bottom and left-to-right,
* but you can change this using the direction option,
* which decides where the upper side of the slider is.
*/
direction?: 'ltr' | 'rtl';
/**
* noUiSlider can provide a basic tooltip without using its events system.
* Set the tooltips option to true to enable.
* This option can also accept formatting options to format the tooltips content.
* In that case, pass an array with a formatter for each handle, true to use the default or false to display no tooltip.
*/
tooltips?: boolean | Object | ((...args: any[]) => any);
/**
* Set the animate option to false to prevent the slider from animating to a new value with when calling .val().
*/
animate?: boolean;
/**
* The animationDuration option can be used to set the animation speed assumed by the slider library.
* In addition to this, you must manually set the CSS (-webkit-)transition property for the .noUi-state-tap .noUi-origin selector.
*/
animationDuration?: number;
/**
* When a non-linear slider has been configured, the snap option can be set to true to force the slider to jump
* between the specified values.
*/
snap?: boolean;
/**
* All values on the slider are part of a range. The range has a minimum and maximum value.
*/
behaviour?: string;
/**
* To format the slider output, noUiSlider offers a format option.
* Simply specify to and from functions to encode and decode the values.
* See manual formatting to the right for usage information.
* By default, noUiSlider will format output with 2 decimals.
*/
format?: Object | ((...args: any[]) => any);
/**
* Allows you to generate points along the slider.
*/
pips?: PipsOptions;
}
interface PipsOptions {
/**
* The 'range' mode uses the slider range to determine where the pips should be. A pip is generated for every percentage specified.
*
* The 'steps', like 'range', uses the slider range. In steps mode, a pip is generated for every step.
* The 'filter' option can be used to filter the generated pips from the 'steps' options'
* The filter function must return 0 (no value), 1 (large value) or 2 (small value).
*
* In 'positions' mode, pips are generated at percentage-based positions on the slider.
* Optionally, the stepped option can be set to true to match the pips to the slider steps.
*
* The 'count' mode can be used to generate a fixed number of pips. As with positions mode, the stepped option can be used.
*
* The 'values' mode is similar to positions, but it accepts values instead of percentages. The stepped option can be used for this mode.
*
*/
mode: 'range' | 'steps' | 'positions' | 'count' | 'values';
/**
* Range Mode: percentage for range mode
* Step Mode: step number for steps
* Positions Mode: percentage-based positions on the slider
* Count Mode: positions between pips
*/
density?: number;
/**
* Step Mode: The filter option can be used to filter the generated pips.
* The filter function must return 0 (no value), 1 (large value) or 2 (small value).
*/
filter?: (...args: any[]) => PipFilterResult;
/**
* format for step mode
* see noUiSlider format
*/
format?: Object | ((...args: any[]) => any);
/**
*
* values for positions and values mode
* number pips for count mode
*/
values?: number | number[];
/**
* stepped option for positions, values and count mode
*/
stepped?: boolean;
}
const enum PipFilterResult {
NoValue,
LargeValue,
SmallValue,
}
interface Callback {
/**
* Array for both one-handle and two-handle sliders. It contains the current slider values,
* with formatting applied.
*/
(values: any[], handle: number, unencodedValues: number[]): void;
}
interface noUiSlider {
/**
* Bind event to the slider.
*/
on(eventName: string, callback: Callback): void;
/**
* Unbind event to the slider.
*/
off(eventName: string): void;
/**
* Destroy's the slider.
*/
destroy(): void;
/**
* To get the current slider value. For one-handle sliders, calling .get() will return the value.
* For two-handle sliders, an array[value, value] will be returned.
*/
get(): string | string[];
/**
* noUiSlider will keep your values within the slider range, which saves you a bunch of validation.
* If you have configured the slider to use one handle, you can change the current value by passing
* a number to the .set() method. If you have two handles, pass an array. One-handled sliders
* will also accept arrays. Within an array, you can set one position to null
* if you want to leave a handle unchanged.
*/
set(value: number | (number | null)[]): void;
/**
* To return to the initial slider values, you can use the .reset() method. This will only reset the slider values.
*/
reset(): void;
/**
* Exposes the options used to create the noUiSlider instance
*/
options: Options;
/**
* method that can change the 'margin', 'limit', 'step', 'range', 'animate' and 'snap' options.
* All other options require changes to the slider's HTML or event bindings.
*/
updateOptions(newOptions: Options, fireSetEvent?: boolean): void;
}
interface Instance extends HTMLElement {
noUiSlider: noUiSlider;
}
} | random_line_split | |
clangextractor.py | #-*- coding: utf-8 -*-
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def | (self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
protos = dict()
for dirpath, dirnames, filenames in os.walk(self.srcdir):
for fname in filenames:
fpath = dirpath + "/" + fname
fext = fname.split(".")[-1]
if fext == "c" or fext == "h":
index = Index.create()
tu = index.parse(fpath)
self.__clang_find_protos(tu.cursor, protos)
return protos
def __clang_find_protos(self, node, protos):
if (node.type.kind == TypeKind.FUNCTIONPROTO): # or node.type.kind == TypeKind.FUNCTIONNOPROTO):
if node.spelling not in protos.keys():
protos[node.spelling] = list()
if len(protos[node.spelling]) == 0:
if (node.result_type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *")
else:
protos[node.spelling].append(node.result_type.get_canonical().spelling)
for c in node.get_arguments():
if (c.type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *")
else:
protos[node.spelling].append(c.type.get_canonical().spelling)
if node.type.is_function_variadic():
protos[node.spelling].append("...")
for c in node.get_children():
self.__clang_find_protos(c, protos)
| __init__ | identifier_name |
clangextractor.py | #-*- coding: utf-8 -*-
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def __init__(self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
protos = dict()
for dirpath, dirnames, filenames in os.walk(self.srcdir):
for fname in filenames:
fpath = dirpath + "/" + fname
fext = fname.split(".")[-1]
if fext == "c" or fext == "h":
index = Index.create()
tu = index.parse(fpath)
self.__clang_find_protos(tu.cursor, protos)
return protos
def __clang_find_protos(self, node, protos):
if (node.type.kind == TypeKind.FUNCTIONPROTO): # or node.type.kind == TypeKind.FUNCTIONNOPROTO):
if node.spelling not in protos.keys():
protos[node.spelling] = list()
if len(protos[node.spelling]) == 0:
if (node.result_type.spelling == "Lisp_Object"):
|
else:
protos[node.spelling].append(node.result_type.get_canonical().spelling)
for c in node.get_arguments():
if (c.type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *")
else:
protos[node.spelling].append(c.type.get_canonical().spelling)
if node.type.is_function_variadic():
protos[node.spelling].append("...")
for c in node.get_children():
self.__clang_find_protos(c, protos)
| protos[node.spelling].append("void *") | conditional_block |
clangextractor.py | #-*- coding: utf-8 -*-
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def __init__(self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
protos = dict()
for dirpath, dirnames, filenames in os.walk(self.srcdir):
for fname in filenames:
fpath = dirpath + "/" + fname
fext = fname.split(".")[-1]
if fext == "c" or fext == "h":
index = Index.create()
tu = index.parse(fpath)
self.__clang_find_protos(tu.cursor, protos)
return protos
def __clang_find_protos(self, node, protos):
if (node.type.kind == TypeKind.FUNCTIONPROTO): # or node.type.kind == TypeKind.FUNCTIONNOPROTO):
if node.spelling not in protos.keys():
protos[node.spelling] = list()
if len(protos[node.spelling]) == 0:
if (node.result_type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *")
else:
protos[node.spelling].append(node.result_type.get_canonical().spelling)
for c in node.get_arguments():
if (c.type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *")
else:
protos[node.spelling].append(c.type.get_canonical().spelling)
if node.type.is_function_variadic():
protos[node.spelling].append("...")
for c in node.get_children(): | self.__clang_find_protos(c, protos) | random_line_split | |
clangextractor.py | #-*- coding: utf-8 -*-
import os
from clang.cindex import Config, Index, TypeKind
class ClangExtractor(object):
def __init__(self, libclang_path, srcdir):
if Config.library_file != libclang_path:
Config.set_library_file(libclang_path)
self.srcdir = srcdir
def extract(self):
protos = dict()
for dirpath, dirnames, filenames in os.walk(self.srcdir):
for fname in filenames:
fpath = dirpath + "/" + fname
fext = fname.split(".")[-1]
if fext == "c" or fext == "h":
index = Index.create()
tu = index.parse(fpath)
self.__clang_find_protos(tu.cursor, protos)
return protos
def __clang_find_protos(self, node, protos):
| if (node.type.kind == TypeKind.FUNCTIONPROTO): # or node.type.kind == TypeKind.FUNCTIONNOPROTO):
if node.spelling not in protos.keys():
protos[node.spelling] = list()
if len(protos[node.spelling]) == 0:
if (node.result_type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *")
else:
protos[node.spelling].append(node.result_type.get_canonical().spelling)
for c in node.get_arguments():
if (c.type.spelling == "Lisp_Object"):
protos[node.spelling].append("void *")
else:
protos[node.spelling].append(c.type.get_canonical().spelling)
if node.type.is_function_variadic():
protos[node.spelling].append("...")
for c in node.get_children():
self.__clang_find_protos(c, protos) | identifier_body | |
test_ddg_api_instant_answers.py | """Our instant answers come from a variety of sources, including
Wikipedia, Wikia, CrunchBase, GitHub, WikiHow, The Free Dictionary – over 100 in total.
Our long-term goal is for all of our instant answers to be available through this open API.
Many of these instant answers are open source via our DuckDuckHack platform.
Using that platform, you can add your own APIs and data sources as well.
More at https://api.duckduckgo.com/api
"""
import pytest
@pytest.allure.feature("API - instant answers")
@pytest.mark.parametrize(
"expected_ans_type, query, expected_value",
(
("currency_in", "currency in US", "United States Dollar (USD)"),
("currency_in", "currency in Russia", "Russian Ruble (RUB)"),
("currency_in", "currency in Sweden", "Swedish Krona (SEK)"),
("timezone_converter", "10:00 MSK to CET", "8:00 CET"),
("timezone_converter", "20:00 MSK to UTC", "17:00 UTC"),
("zodiac", "zodiac 21st June", "Gemini"),
("zodiac", "zodiac 1st July", "Cancer"),
("zodiac", "zodiac 29st August", "Virgo")
)
)
def te | dg, url_params, logger, expected_ans_type, query, expected_value):
with pytest.allure.step("send request: {!r}".format(query)):
url_params.update(q=query)
r = ddg.get(params=url_params)
r.raise_for_status()
with pytest.allure.step("'AnswerType' in the response is {!r}".format(expected_ans_type)):
data = r.json()
ans_type = data['AnswerType']
logger.debug("Expected AnswerType: {!r}".format(expected_ans_type))
logger.debug("Actual AnswerType: {!r}".format(ans_type))
assert ans_type == expected_ans_type
with pytest.allure.step("'Answer' in the response is {!r}".format(expected_value)):
answer = data['Answer']
logger.debug("Raw answer: {!r}".format(data['Answer']))
logger.debug("Processed answer: {!r}".format(answer))
assert answer == expected_value
| st_instant_answer(d | identifier_name |
test_ddg_api_instant_answers.py | """Our instant answers come from a variety of sources, including
Wikipedia, Wikia, CrunchBase, GitHub, WikiHow, The Free Dictionary – over 100 in total.
Our long-term goal is for all of our instant answers to be available through this open API.
Many of these instant answers are open source via our DuckDuckHack platform.
Using that platform, you can add your own APIs and data sources as well.
More at https://api.duckduckgo.com/api
"""
import pytest
@pytest.allure.feature("API - instant answers")
@pytest.mark.parametrize(
"expected_ans_type, query, expected_value",
(
("currency_in", "currency in US", "United States Dollar (USD)"),
("currency_in", "currency in Russia", "Russian Ruble (RUB)"),
("currency_in", "currency in Sweden", "Swedish Krona (SEK)"),
("timezone_converter", "10:00 MSK to CET", "8:00 CET"),
("timezone_converter", "20:00 MSK to UTC", "17:00 UTC"),
("zodiac", "zodiac 21st June", "Gemini"),
("zodiac", "zodiac 1st July", "Cancer"),
("zodiac", "zodiac 29st August", "Virgo")
)
)
def test_instant_answer(ddg, url_params, logger, expected_ans_type, query, expected_value):
with pytest.allure.step("send request: {!r}".format(query)):
url_params.update(q=query)
r = ddg.get(params=url_params)
r.raise_for_status()
with pytest.allure.step("'AnswerType' in the response is {!r}".format(expected_ans_type)):
data = r.json()
ans_type = data['AnswerType']
logger.debug("Expected AnswerType: {!r}".format(expected_ans_type))
logger.debug("Actual AnswerType: {!r}".format(ans_type))
assert ans_type == expected_ans_type | logger.debug("Raw answer: {!r}".format(data['Answer']))
logger.debug("Processed answer: {!r}".format(answer))
assert answer == expected_value |
with pytest.allure.step("'Answer' in the response is {!r}".format(expected_value)):
answer = data['Answer'] | random_line_split |
test_ddg_api_instant_answers.py | """Our instant answers come from a variety of sources, including
Wikipedia, Wikia, CrunchBase, GitHub, WikiHow, The Free Dictionary – over 100 in total.
Our long-term goal is for all of our instant answers to be available through this open API.
Many of these instant answers are open source via our DuckDuckHack platform.
Using that platform, you can add your own APIs and data sources as well.
More at https://api.duckduckgo.com/api
"""
import pytest
@pytest.allure.feature("API - instant answers")
@pytest.mark.parametrize(
"expected_ans_type, query, expected_value",
(
("currency_in", "currency in US", "United States Dollar (USD)"),
("currency_in", "currency in Russia", "Russian Ruble (RUB)"),
("currency_in", "currency in Sweden", "Swedish Krona (SEK)"),
("timezone_converter", "10:00 MSK to CET", "8:00 CET"),
("timezone_converter", "20:00 MSK to UTC", "17:00 UTC"),
("zodiac", "zodiac 21st June", "Gemini"),
("zodiac", "zodiac 1st July", "Cancer"),
("zodiac", "zodiac 29st August", "Virgo")
)
)
def test_instant_answer(ddg, url_params, logger, expected_ans_type, query, expected_value):
wi | th pytest.allure.step("send request: {!r}".format(query)):
url_params.update(q=query)
r = ddg.get(params=url_params)
r.raise_for_status()
with pytest.allure.step("'AnswerType' in the response is {!r}".format(expected_ans_type)):
data = r.json()
ans_type = data['AnswerType']
logger.debug("Expected AnswerType: {!r}".format(expected_ans_type))
logger.debug("Actual AnswerType: {!r}".format(ans_type))
assert ans_type == expected_ans_type
with pytest.allure.step("'Answer' in the response is {!r}".format(expected_value)):
answer = data['Answer']
logger.debug("Raw answer: {!r}".format(data['Answer']))
logger.debug("Processed answer: {!r}".format(answer))
assert answer == expected_value
| identifier_body | |
ServiceAccountsPage.ts | import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { ServiceAccount } from '../../client';
import { MessageService } from '../../core/services/MessageService';
import { YamcsService } from '../../core/services/YamcsService';
@Component({
templateUrl: './ServiceAccountsPage.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ServiceAccountsPage implements AfterViewInit {
filterControl = new FormControl();
@ViewChild(MatSort, { static: true })
sort: MatSort;
displayedColumns = [
'name',
'actions',
];
dataSource = new MatTableDataSource<ServiceAccount>();
| (
private yamcs: YamcsService,
title: Title,
private route: ActivatedRoute,
private router: Router,
private messageService: MessageService,
) {
title.setTitle('Service accounts');
this.dataSource.filterPredicate = (serviceAccount, filter) => {
return serviceAccount.name.toLowerCase().indexOf(filter) >= 0;
};
}
ngAfterViewInit() {
const queryParams = this.route.snapshot.queryParamMap;
if (queryParams.has('filter')) {
this.filterControl.setValue(queryParams.get('filter'));
this.dataSource.filter = queryParams.get('filter')!.toLowerCase();
}
this.filterControl.valueChanges.subscribe(() => {
this.updateURL();
const value = this.filterControl.value || '';
this.dataSource.filter = value.toLowerCase();
});
this.refresh();
this.dataSource.sort = this.sort;
}
private refresh() {
this.yamcs.yamcsClient.getServiceAccounts().then(page => {
this.dataSource.data = page.serviceAccounts || [];
});
}
private updateURL() {
const filterValue = this.filterControl.value;
this.router.navigate([], {
replaceUrl: true,
relativeTo: this.route,
queryParams: {
filter: filterValue || null,
},
queryParamsHandling: 'merge',
});
}
deleteServiceAccount(name: string) {
if (confirm(`Are you sure you want to delete service account ${name}`)) {
this.yamcs.yamcsClient.deleteServiceAccount(name)
.then(() => this.refresh())
.catch(err => this.messageService.showError(err));
}
}
}
| constructor | identifier_name |
ServiceAccountsPage.ts | import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { ServiceAccount } from '../../client';
import { MessageService } from '../../core/services/MessageService';
import { YamcsService } from '../../core/services/YamcsService';
@Component({
templateUrl: './ServiceAccountsPage.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ServiceAccountsPage implements AfterViewInit {
filterControl = new FormControl();
@ViewChild(MatSort, { static: true })
sort: MatSort;
displayedColumns = [
'name',
'actions',
];
dataSource = new MatTableDataSource<ServiceAccount>();
constructor(
private yamcs: YamcsService,
title: Title,
private route: ActivatedRoute,
private router: Router,
private messageService: MessageService,
) {
title.setTitle('Service accounts');
this.dataSource.filterPredicate = (serviceAccount, filter) => {
return serviceAccount.name.toLowerCase().indexOf(filter) >= 0;
};
}
ngAfterViewInit() {
const queryParams = this.route.snapshot.queryParamMap;
if (queryParams.has('filter')) {
this.filterControl.setValue(queryParams.get('filter'));
this.dataSource.filter = queryParams.get('filter')!.toLowerCase();
}
this.filterControl.valueChanges.subscribe(() => {
this.updateURL();
const value = this.filterControl.value || '';
this.dataSource.filter = value.toLowerCase();
});
this.refresh();
this.dataSource.sort = this.sort;
}
private refresh() {
this.yamcs.yamcsClient.getServiceAccounts().then(page => {
this.dataSource.data = page.serviceAccounts || [];
});
}
private updateURL() {
const filterValue = this.filterControl.value;
this.router.navigate([], {
replaceUrl: true,
relativeTo: this.route,
queryParams: {
filter: filterValue || null,
},
queryParamsHandling: 'merge',
});
}
deleteServiceAccount(name: string) {
if (confirm(`Are you sure you want to delete service account ${name}`)) |
}
}
| {
this.yamcs.yamcsClient.deleteServiceAccount(name)
.then(() => this.refresh())
.catch(err => this.messageService.showError(err));
} | conditional_block |
ServiceAccountsPage.ts | import { AfterViewInit, ChangeDetectionStrategy, Component, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { ServiceAccount } from '../../client';
import { MessageService } from '../../core/services/MessageService';
import { YamcsService } from '../../core/services/YamcsService';
@Component({
templateUrl: './ServiceAccountsPage.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ServiceAccountsPage implements AfterViewInit {
filterControl = new FormControl();
@ViewChild(MatSort, { static: true })
sort: MatSort;
displayedColumns = [
'name',
'actions',
]; | private route: ActivatedRoute,
private router: Router,
private messageService: MessageService,
) {
title.setTitle('Service accounts');
this.dataSource.filterPredicate = (serviceAccount, filter) => {
return serviceAccount.name.toLowerCase().indexOf(filter) >= 0;
};
}
ngAfterViewInit() {
const queryParams = this.route.snapshot.queryParamMap;
if (queryParams.has('filter')) {
this.filterControl.setValue(queryParams.get('filter'));
this.dataSource.filter = queryParams.get('filter')!.toLowerCase();
}
this.filterControl.valueChanges.subscribe(() => {
this.updateURL();
const value = this.filterControl.value || '';
this.dataSource.filter = value.toLowerCase();
});
this.refresh();
this.dataSource.sort = this.sort;
}
private refresh() {
this.yamcs.yamcsClient.getServiceAccounts().then(page => {
this.dataSource.data = page.serviceAccounts || [];
});
}
private updateURL() {
const filterValue = this.filterControl.value;
this.router.navigate([], {
replaceUrl: true,
relativeTo: this.route,
queryParams: {
filter: filterValue || null,
},
queryParamsHandling: 'merge',
});
}
deleteServiceAccount(name: string) {
if (confirm(`Are you sure you want to delete service account ${name}`)) {
this.yamcs.yamcsClient.deleteServiceAccount(name)
.then(() => this.refresh())
.catch(err => this.messageService.showError(err));
}
}
} | dataSource = new MatTableDataSource<ServiceAccount>();
constructor(
private yamcs: YamcsService,
title: Title, | random_line_split |
DataDescription.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {Typography, Popover, Input, Select, Checkbox} from 'antd';
import {DataInspectorSetValue} from './DataInspectorNode';
import {PureComponent} from 'react';
import styled from '@emotion/styled';
import {SketchPicker, CompactPicker} from 'react-color';
import React, {KeyboardEvent} from 'react';
import {HighlightContext} from '../Highlight';
import {parseColor} from '../../utils/parseColor';
import {TimelineDataDescription} from './TimelineDataDescription';
import {theme} from '../theme';
import {EditOutlined} from '@ant-design/icons';
import type {CheckboxChangeEvent} from 'antd/lib/checkbox';
const {Link} = Typography;
// Based on FIG UI Core, TODO: does that still makes sense?
export const presetColors = Object.values({
blue: '#4267b2', // Blue - Active-state nav glyphs, nav bars, links, buttons
green: '#42b72a', // Green - Confirmation, success, commerce and status
red: '#FC3A4B', // Red - Badges, error states
blueGray: '#5f6673', // Blue Grey
slate: '#b9cad2', // Slate
aluminum: '#a3cedf', // Aluminum
seaFoam: '#54c7ec', // Sea Foam
teal: '#6bcebb', // Teal
lime: '#a3ce71', // Lime
lemon: '#fcd872', // Lemon
orange: '#f7923b', // Orange
tomato: '#fb724b', // Tomato - Tometo? Tomato.
cherry: '#f35369', // Cherry
pink: '#ec7ebd', // Pink
grape: '#8c72cb', // Grape
});
export const NullValue = styled.span({
color: theme.semanticColors.nullValue,
});
NullValue.displayName = 'DataDescription:NullValue';
const UndefinedValue = styled.span({
color: theme.semanticColors.nullValue,
});
UndefinedValue.displayName = 'DataDescription:UndefinedValue';
export const StringValue = styled.span({
color: theme.semanticColors.stringValue,
wordWrap: 'break-word',
});
StringValue.displayName = 'DataDescription:StringValue';
const ColorValue = styled.span({
color: theme.semanticColors.colorValue,
});
ColorValue.displayName = 'DataDescription:ColorValue';
const SymbolValue = styled.span({
color: theme.semanticColors.stringValue,
});
SymbolValue.displayName = 'DataDescription:SymbolValue';
export const NumberValue = styled.span({
color: theme.semanticColors.numberValue,
});
NumberValue.displayName = 'DataDescription:NumberValue';
export const BooleanValue = styled.span({
color: theme.semanticColors.booleanValue,
});
BooleanValue.displayName = 'DataDescription:BooleanValue';
const ColorBox = styled.span<{color: string}>((props) => ({
backgroundColor: props.color,
boxShadow: `inset 0 0 1px ${theme.black}`,
display: 'inline-block',
height: 12,
marginRight: 4,
verticalAlign: 'middle',
width: 12,
borderRadius: 4,
}));
ColorBox.displayName = 'DataDescription:ColorBox';
const FunctionKeyword = styled.span({
color: theme.semanticColors.nullValue,
fontStyle: 'italic',
});
FunctionKeyword.displayName = 'DataDescription:FunctionKeyword';
const FunctionName = styled.span({
fontStyle: 'italic',
});
FunctionName.displayName = 'DataDescription:FunctionName';
const ColorPickerDescription = styled.div({
display: 'inline',
position: 'relative',
});
ColorPickerDescription.displayName = 'DataDescription:ColorPickerDescription';
const EmptyObjectValue = styled.span({
fontStyle: 'italic',
});
EmptyObjectValue.displayName = 'DataDescription:EmptyObjectValue';
export type DataDescriptionType =
| 'number'
| 'string'
| 'boolean'
| 'undefined'
| 'null'
| 'object'
| 'array'
| 'date'
| 'symbol'
| 'function'
| 'bigint'
| 'text' // deprecated, please use string
| 'enum' // unformatted string
| 'color'
| 'picker' // multiple choise item like an, eehhh, enum
| 'timeline'
| 'color_lite'; // color with limited palette, specific for fblite;
type DataDescriptionProps = {
path?: Array<string>;
type: DataDescriptionType;
value: any;
extra?: any;
setValue: DataInspectorSetValue | null | undefined;
};
type DescriptionCommitOptions = {
value: any;
keep: boolean;
clear: boolean;
set: boolean;
};
class NumberTextEditor extends PureComponent<{
commit: (opts: DescriptionCommitOptions) => void;
type: DataDescriptionType;
value: any;
origValue: any;
}> {
onNumberTextInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val =
this.props.type === 'number'
? parseFloat(e.target.value)
: e.target.value;
this.props.commit({
clear: false,
keep: true,
value: val,
set: false,
});
};
onNumberTextInputKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter') {
const val =
this.props.type === 'number'
? parseFloat(this.props.value)
: this.props.value;
this.props.commit({clear: true, keep: true, value: val, set: true});
} else if (e.key === 'Escape') {
this.props.commit({
clear: true,
keep: false,
value: this.props.origValue,
set: false,
});
}
};
onNumberTextRef = (ref: HTMLElement | undefined | null) => {
if (ref) {
ref.focus();
}
};
onNumberTextBlur = () => {
this.props.commit({
clear: true,
keep: true,
value: this.props.value,
set: true,
});
};
render() |
}
type DataDescriptionState = {
editing: boolean;
origValue: any;
value: any;
};
export class DataDescription extends PureComponent<
DataDescriptionProps,
DataDescriptionState
> {
constructor(props: DataDescriptionProps, context: Object) {
super(props, context);
this.state = {
editing: false,
origValue: '',
value: '',
};
}
commit = (opts: DescriptionCommitOptions) => {
const {path, setValue} = this.props;
if (opts.keep && setValue && path) {
const val = opts.value;
this.setState({value: val});
if (opts.set) {
setValue(path, val);
}
}
if (opts.clear) {
this.setState({
editing: false,
origValue: '',
value: '',
});
}
};
_renderEditing() {
const {type, extra} = this.props;
const {origValue, value} = this.state;
if (
type === 'string' ||
type === 'text' ||
type === 'number' ||
type === 'enum'
) {
return (
<NumberTextEditor
type={type}
value={value}
origValue={origValue}
commit={this.commit}
/>
);
}
if (type === 'color') {
return <ColorEditor value={value} commit={this.commit} />;
}
if (type === 'color_lite') {
return (
<ColorEditor
value={value}
colorSet={extra.colorSet}
commit={this.commit}
/>
);
}
return null;
}
_hasEditUI() {
const {type} = this.props;
return (
type === 'string' ||
type === 'text' ||
type === 'number' ||
type === 'enum' ||
type === 'color' ||
type === 'color_lite'
);
}
onEditStart = () => {
this.setState({
editing: this._hasEditUI(),
origValue: this.props.value,
value: this.props.value,
});
};
render(): any {
if (this.state.editing) {
return this._renderEditing();
} else {
return (
<DataDescriptionPreview
type={this.props.type}
value={this.props.value}
extra={this.props.extra}
editable={!!this.props.setValue}
commit={this.commit}
onEdit={this.onEditStart}
/>
);
}
}
}
class ColorEditor extends PureComponent<{
value: any;
colorSet?: Array<string | number>;
commit: (opts: DescriptionCommitOptions) => void;
}> {
onBlur = (newVisibility: boolean) => {
if (!newVisibility) {
this.props.commit({
clear: true,
keep: false,
value: this.props.value,
set: true,
});
}
};
onChange = ({
hex,
rgb: {a, b, g, r},
}: {
hex: string;
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
let val;
if (typeof prev === 'string') {
if (a === 1) {
// hex is fine and has an implicit 100% alpha
val = hex;
} else {
// turn into a css rgba value
val = `rgba(${r}, ${g}, ${b}, ${a})`;
}
} else if (typeof prev === 'number') {
// compute RRGGBBAA value
val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
const prevClear = ((prev >> 24) & 0xff) === 0;
const onlyAlphaChanged = (prev & 0x00ffffff) === (val & 0x00ffffff);
if (!onlyAlphaChanged && prevClear) {
val = 0xff000000 | (val & 0x00ffffff);
}
} else {
return;
}
this.props.commit({clear: false, keep: true, value: val, set: true});
};
onChangeLite = ({
rgb: {a, b, g, r},
}: {
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
if (typeof prev !== 'number') {
return;
}
// compute RRGGBBAA value
let val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
this.props.commit({clear: false, keep: true, value: val, set: true});
};
render() {
const colorInfo = parseColor(this.props.value);
if (!colorInfo) {
return null;
}
return (
<Popover
trigger={'click'}
onVisibleChange={this.onBlur}
content={() =>
this.props.colorSet ? (
<CompactPicker
color={colorInfo}
colors={this.props.colorSet
.filter((x) => x != 0)
.map(parseColor)
.map((rgba) => {
if (!rgba) {
return '';
}
return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
})}
onChange={(color: {
hex: string;
hsl: {
a?: number;
h: number;
l: number;
s: number;
};
rgb: {a?: number; b: number; g: number; r: number};
}) => {
this.onChangeLite({rgb: {...color.rgb, a: color.rgb.a || 0}});
}}
/>
) : (
<SketchPicker
color={colorInfo}
presetColors={presetColors}
onChange={(color: {
hex: string;
hsl: {
a?: number;
h: number;
l: number;
s: number;
};
rgb: {a?: number; b: number; g: number; r: number};
}) => {
this.onChange({
hex: color.hex,
rgb: {...color.rgb, a: color.rgb.a || 1},
});
}}
/>
)
}>
<ColorPickerDescription>
<DataDescriptionPreview
type="color"
value={this.props.value}
extra={this.props.colorSet}
editable={false}
commit={this.props.commit}
/>
</ColorPickerDescription>
</Popover>
);
}
}
class DataDescriptionPreview extends PureComponent<{
type: DataDescriptionType;
value: any;
extra?: any;
editable: boolean;
commit: (opts: DescriptionCommitOptions) => void;
onEdit?: () => void;
}> {
onClick = () => {
const {onEdit} = this.props;
if (this.props.editable && onEdit) {
onEdit();
}
};
render() {
const {type, value} = this.props;
const description = (
<DataDescriptionContainer
type={type}
value={value}
editable={this.props.editable}
commit={this.props.commit}
/>
);
// booleans are always editable so don't require the onEditStart handler
if (type === 'boolean') {
return description;
}
return (
<span onClick={this.onClick} role="button" tabIndex={-1}>
{description}
</span>
);
}
}
type Picker = {
values: Set<string>;
selected: string;
};
class DataDescriptionContainer extends PureComponent<{
type: DataDescriptionType;
value: any;
editable: boolean;
commit: (opts: DescriptionCommitOptions) => void;
}> {
static contextType = HighlightContext; // Replace with useHighlighter
context!: React.ContextType<typeof HighlightContext>;
onChangeCheckbox = (e: CheckboxChangeEvent) => {
this.props.commit({
clear: true,
keep: true,
value: e.target.checked,
set: true,
});
};
render(): any {
const {type, editable, value: val} = this.props;
const highlighter = this.context;
switch (type) {
case 'timeline': {
return (
<>
<TimelineDataDescription
canSetCurrent={editable}
timeline={JSON.parse(val)}
onClick={(id) => {
this.props.commit({
value: id,
keep: true,
clear: false,
set: true,
});
}}
/>
</>
);
}
case 'number':
return <NumberValue>{+val}</NumberValue>;
case 'color': {
const colorInfo = parseColor(val);
if (typeof val === 'number' && val === 0) {
return <UndefinedValue>(not set)</UndefinedValue>;
} else if (colorInfo) {
const {a, b, g, r} = colorInfo;
return (
<>
<ColorBox
key="color-box"
color={`rgba(${r}, ${g}, ${b}, ${a})`}
/>
<ColorValue key="value">
rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)})
</ColorValue>
</>
);
} else {
return <span>Malformed color</span>;
}
}
case 'color_lite': {
const colorInfo = parseColor(val);
if (typeof val === 'number' && val === 0) {
return <UndefinedValue>(not set)</UndefinedValue>;
} else if (colorInfo) {
const {a, b, g, r} = colorInfo;
return (
<>
<ColorBox
key="color-box"
color={`rgba(${r}, ${g}, ${b}, ${a})`}
/>
<ColorValue key="value">
rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)})
</ColorValue>
</>
);
} else {
return <span>Malformed color</span>;
}
}
case 'picker': {
const picker: Picker = JSON.parse(val);
return (
<Select
disabled={!this.props.editable}
options={Array.from(picker.values).map((value) => ({
value,
label: value,
}))}
value={picker.selected}
onChange={(value: string) =>
this.props.commit({
value,
keep: true,
clear: false,
set: true,
})
}
size="small"
style={{fontSize: 11}}
dropdownMatchSelectWidth={false}
/>
);
}
case 'text':
case 'string':
const isUrl = val.startsWith('http://') || val.startsWith('https://');
if (isUrl) {
return (
<>
<Link href={val}>{highlighter.render(val)}</Link>
{editable && (
<EditOutlined
style={{
color: theme.disabledColor,
cursor: 'pointer',
marginLeft: 8,
}}
/>
)}
</>
);
} else {
return (
<StringValue>{highlighter.render(`"${val || ''}"`)}</StringValue>
);
}
case 'enum':
return <StringValue>{highlighter.render(val)}</StringValue>;
case 'boolean':
return editable ? (
<Checkbox
checked={!!val}
disabled={!editable}
onChange={this.onChangeCheckbox}
/>
) : (
<BooleanValue>{'' + val}</BooleanValue>
);
case 'undefined':
return <UndefinedValue>undefined</UndefinedValue>;
case 'date':
if (Object.prototype.toString.call(val) === '[object Date]') {
return <span>{val.toString()}</span>;
} else {
return <span>{val}</span>;
}
case 'null':
return <NullValue>null</NullValue>;
// no description necessary as we'll typically wrap it in [] or {} which
// already denotes the type
case 'array':
return val.length <= 0 ? <EmptyObjectValue>[]</EmptyObjectValue> : null;
case 'object':
return Object.keys(val ?? {}).length <= 0 ? (
<EmptyObjectValue>{'{}'}</EmptyObjectValue>
) : null;
case 'function':
return (
<span>
<FunctionKeyword>function</FunctionKeyword>
<FunctionName> {val.name}()</FunctionName>
</span>
);
case 'symbol':
return <SymbolValue>Symbol()</SymbolValue>;
default:
return <span>Unknown type "{type}"</span>;
}
}
}
| {
const extraProps: any = {};
if (this.props.type === 'number') {
// render as a HTML number input
extraProps.type = 'number';
// step="any" allows any sort of float to be input, otherwise we're limited
// to decimal
extraProps.step = 'any';
}
return (
<Input
key="input"
{...extraProps}
size="small"
onChange={this.onNumberTextInputChange}
onKeyDown={this.onNumberTextInputKeyDown}
ref={this.onNumberTextRef}
onBlur={this.onNumberTextBlur}
value={this.props.value}
style={{fontSize: 11}}
/>
);
} | identifier_body |
DataDescription.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {Typography, Popover, Input, Select, Checkbox} from 'antd';
import {DataInspectorSetValue} from './DataInspectorNode';
import {PureComponent} from 'react';
import styled from '@emotion/styled';
import {SketchPicker, CompactPicker} from 'react-color';
import React, {KeyboardEvent} from 'react';
import {HighlightContext} from '../Highlight';
import {parseColor} from '../../utils/parseColor';
import {TimelineDataDescription} from './TimelineDataDescription';
import {theme} from '../theme';
import {EditOutlined} from '@ant-design/icons';
import type {CheckboxChangeEvent} from 'antd/lib/checkbox';
const {Link} = Typography;
// Based on FIG UI Core, TODO: does that still makes sense?
export const presetColors = Object.values({
blue: '#4267b2', // Blue - Active-state nav glyphs, nav bars, links, buttons
green: '#42b72a', // Green - Confirmation, success, commerce and status
red: '#FC3A4B', // Red - Badges, error states
blueGray: '#5f6673', // Blue Grey
slate: '#b9cad2', // Slate
aluminum: '#a3cedf', // Aluminum
seaFoam: '#54c7ec', // Sea Foam
teal: '#6bcebb', // Teal
lime: '#a3ce71', // Lime
lemon: '#fcd872', // Lemon
orange: '#f7923b', // Orange
tomato: '#fb724b', // Tomato - Tometo? Tomato.
cherry: '#f35369', // Cherry
pink: '#ec7ebd', // Pink
grape: '#8c72cb', // Grape
});
export const NullValue = styled.span({
color: theme.semanticColors.nullValue,
});
NullValue.displayName = 'DataDescription:NullValue';
const UndefinedValue = styled.span({
color: theme.semanticColors.nullValue,
});
UndefinedValue.displayName = 'DataDescription:UndefinedValue';
export const StringValue = styled.span({
color: theme.semanticColors.stringValue,
wordWrap: 'break-word',
});
StringValue.displayName = 'DataDescription:StringValue';
const ColorValue = styled.span({
color: theme.semanticColors.colorValue,
});
ColorValue.displayName = 'DataDescription:ColorValue';
const SymbolValue = styled.span({
color: theme.semanticColors.stringValue,
});
SymbolValue.displayName = 'DataDescription:SymbolValue';
export const NumberValue = styled.span({
color: theme.semanticColors.numberValue,
});
NumberValue.displayName = 'DataDescription:NumberValue';
export const BooleanValue = styled.span({
color: theme.semanticColors.booleanValue,
});
BooleanValue.displayName = 'DataDescription:BooleanValue';
const ColorBox = styled.span<{color: string}>((props) => ({
backgroundColor: props.color,
boxShadow: `inset 0 0 1px ${theme.black}`,
display: 'inline-block',
height: 12,
marginRight: 4,
verticalAlign: 'middle',
width: 12,
borderRadius: 4,
}));
ColorBox.displayName = 'DataDescription:ColorBox';
const FunctionKeyword = styled.span({
color: theme.semanticColors.nullValue,
fontStyle: 'italic',
});
FunctionKeyword.displayName = 'DataDescription:FunctionKeyword';
const FunctionName = styled.span({
fontStyle: 'italic',
});
FunctionName.displayName = 'DataDescription:FunctionName';
const ColorPickerDescription = styled.div({
display: 'inline',
position: 'relative',
});
ColorPickerDescription.displayName = 'DataDescription:ColorPickerDescription';
const EmptyObjectValue = styled.span({
fontStyle: 'italic',
});
EmptyObjectValue.displayName = 'DataDescription:EmptyObjectValue';
export type DataDescriptionType =
| 'number'
| 'string'
| 'boolean'
| 'undefined'
| 'null'
| 'object'
| 'array'
| 'date'
| 'symbol'
| 'function'
| 'bigint'
| 'text' // deprecated, please use string
| 'enum' // unformatted string
| 'color'
| 'picker' // multiple choise item like an, eehhh, enum
| 'timeline'
| 'color_lite'; // color with limited palette, specific for fblite;
type DataDescriptionProps = {
path?: Array<string>;
type: DataDescriptionType;
value: any;
extra?: any;
setValue: DataInspectorSetValue | null | undefined;
};
type DescriptionCommitOptions = {
value: any;
keep: boolean;
clear: boolean;
set: boolean;
};
class NumberTextEditor extends PureComponent<{
commit: (opts: DescriptionCommitOptions) => void;
type: DataDescriptionType;
value: any;
origValue: any;
}> {
onNumberTextInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val =
this.props.type === 'number'
? parseFloat(e.target.value)
: e.target.value;
this.props.commit({
clear: false,
keep: true,
value: val,
set: false,
});
};
onNumberTextInputKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter') {
const val =
this.props.type === 'number'
? parseFloat(this.props.value)
: this.props.value;
this.props.commit({clear: true, keep: true, value: val, set: true});
} else if (e.key === 'Escape') {
this.props.commit({
clear: true,
keep: false,
value: this.props.origValue,
set: false,
});
}
};
onNumberTextRef = (ref: HTMLElement | undefined | null) => {
if (ref) {
ref.focus();
}
};
onNumberTextBlur = () => {
this.props.commit({
clear: true,
keep: true,
value: this.props.value,
set: true,
});
};
render() {
const extraProps: any = {};
if (this.props.type === 'number') {
// render as a HTML number input
extraProps.type = 'number';
// step="any" allows any sort of float to be input, otherwise we're limited
// to decimal
extraProps.step = 'any';
}
return (
<Input
key="input"
{...extraProps}
size="small"
onChange={this.onNumberTextInputChange}
onKeyDown={this.onNumberTextInputKeyDown}
ref={this.onNumberTextRef}
onBlur={this.onNumberTextBlur}
value={this.props.value}
style={{fontSize: 11}}
/>
);
}
}
type DataDescriptionState = {
editing: boolean;
origValue: any;
value: any;
};
| export class DataDescription extends PureComponent<
DataDescriptionProps,
DataDescriptionState
> {
constructor(props: DataDescriptionProps, context: Object) {
super(props, context);
this.state = {
editing: false,
origValue: '',
value: '',
};
}
commit = (opts: DescriptionCommitOptions) => {
const {path, setValue} = this.props;
if (opts.keep && setValue && path) {
const val = opts.value;
this.setState({value: val});
if (opts.set) {
setValue(path, val);
}
}
if (opts.clear) {
this.setState({
editing: false,
origValue: '',
value: '',
});
}
};
_renderEditing() {
const {type, extra} = this.props;
const {origValue, value} = this.state;
if (
type === 'string' ||
type === 'text' ||
type === 'number' ||
type === 'enum'
) {
return (
<NumberTextEditor
type={type}
value={value}
origValue={origValue}
commit={this.commit}
/>
);
}
if (type === 'color') {
return <ColorEditor value={value} commit={this.commit} />;
}
if (type === 'color_lite') {
return (
<ColorEditor
value={value}
colorSet={extra.colorSet}
commit={this.commit}
/>
);
}
return null;
}
_hasEditUI() {
const {type} = this.props;
return (
type === 'string' ||
type === 'text' ||
type === 'number' ||
type === 'enum' ||
type === 'color' ||
type === 'color_lite'
);
}
onEditStart = () => {
this.setState({
editing: this._hasEditUI(),
origValue: this.props.value,
value: this.props.value,
});
};
render(): any {
if (this.state.editing) {
return this._renderEditing();
} else {
return (
<DataDescriptionPreview
type={this.props.type}
value={this.props.value}
extra={this.props.extra}
editable={!!this.props.setValue}
commit={this.commit}
onEdit={this.onEditStart}
/>
);
}
}
}
class ColorEditor extends PureComponent<{
value: any;
colorSet?: Array<string | number>;
commit: (opts: DescriptionCommitOptions) => void;
}> {
onBlur = (newVisibility: boolean) => {
if (!newVisibility) {
this.props.commit({
clear: true,
keep: false,
value: this.props.value,
set: true,
});
}
};
onChange = ({
hex,
rgb: {a, b, g, r},
}: {
hex: string;
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
let val;
if (typeof prev === 'string') {
if (a === 1) {
// hex is fine and has an implicit 100% alpha
val = hex;
} else {
// turn into a css rgba value
val = `rgba(${r}, ${g}, ${b}, ${a})`;
}
} else if (typeof prev === 'number') {
// compute RRGGBBAA value
val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
const prevClear = ((prev >> 24) & 0xff) === 0;
const onlyAlphaChanged = (prev & 0x00ffffff) === (val & 0x00ffffff);
if (!onlyAlphaChanged && prevClear) {
val = 0xff000000 | (val & 0x00ffffff);
}
} else {
return;
}
this.props.commit({clear: false, keep: true, value: val, set: true});
};
onChangeLite = ({
rgb: {a, b, g, r},
}: {
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
if (typeof prev !== 'number') {
return;
}
// compute RRGGBBAA value
let val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
this.props.commit({clear: false, keep: true, value: val, set: true});
};
render() {
const colorInfo = parseColor(this.props.value);
if (!colorInfo) {
return null;
}
return (
<Popover
trigger={'click'}
onVisibleChange={this.onBlur}
content={() =>
this.props.colorSet ? (
<CompactPicker
color={colorInfo}
colors={this.props.colorSet
.filter((x) => x != 0)
.map(parseColor)
.map((rgba) => {
if (!rgba) {
return '';
}
return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
})}
onChange={(color: {
hex: string;
hsl: {
a?: number;
h: number;
l: number;
s: number;
};
rgb: {a?: number; b: number; g: number; r: number};
}) => {
this.onChangeLite({rgb: {...color.rgb, a: color.rgb.a || 0}});
}}
/>
) : (
<SketchPicker
color={colorInfo}
presetColors={presetColors}
onChange={(color: {
hex: string;
hsl: {
a?: number;
h: number;
l: number;
s: number;
};
rgb: {a?: number; b: number; g: number; r: number};
}) => {
this.onChange({
hex: color.hex,
rgb: {...color.rgb, a: color.rgb.a || 1},
});
}}
/>
)
}>
<ColorPickerDescription>
<DataDescriptionPreview
type="color"
value={this.props.value}
extra={this.props.colorSet}
editable={false}
commit={this.props.commit}
/>
</ColorPickerDescription>
</Popover>
);
}
}
class DataDescriptionPreview extends PureComponent<{
type: DataDescriptionType;
value: any;
extra?: any;
editable: boolean;
commit: (opts: DescriptionCommitOptions) => void;
onEdit?: () => void;
}> {
onClick = () => {
const {onEdit} = this.props;
if (this.props.editable && onEdit) {
onEdit();
}
};
render() {
const {type, value} = this.props;
const description = (
<DataDescriptionContainer
type={type}
value={value}
editable={this.props.editable}
commit={this.props.commit}
/>
);
// booleans are always editable so don't require the onEditStart handler
if (type === 'boolean') {
return description;
}
return (
<span onClick={this.onClick} role="button" tabIndex={-1}>
{description}
</span>
);
}
}
type Picker = {
values: Set<string>;
selected: string;
};
class DataDescriptionContainer extends PureComponent<{
type: DataDescriptionType;
value: any;
editable: boolean;
commit: (opts: DescriptionCommitOptions) => void;
}> {
static contextType = HighlightContext; // Replace with useHighlighter
context!: React.ContextType<typeof HighlightContext>;
onChangeCheckbox = (e: CheckboxChangeEvent) => {
this.props.commit({
clear: true,
keep: true,
value: e.target.checked,
set: true,
});
};
render(): any {
const {type, editable, value: val} = this.props;
const highlighter = this.context;
switch (type) {
case 'timeline': {
return (
<>
<TimelineDataDescription
canSetCurrent={editable}
timeline={JSON.parse(val)}
onClick={(id) => {
this.props.commit({
value: id,
keep: true,
clear: false,
set: true,
});
}}
/>
</>
);
}
case 'number':
return <NumberValue>{+val}</NumberValue>;
case 'color': {
const colorInfo = parseColor(val);
if (typeof val === 'number' && val === 0) {
return <UndefinedValue>(not set)</UndefinedValue>;
} else if (colorInfo) {
const {a, b, g, r} = colorInfo;
return (
<>
<ColorBox
key="color-box"
color={`rgba(${r}, ${g}, ${b}, ${a})`}
/>
<ColorValue key="value">
rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)})
</ColorValue>
</>
);
} else {
return <span>Malformed color</span>;
}
}
case 'color_lite': {
const colorInfo = parseColor(val);
if (typeof val === 'number' && val === 0) {
return <UndefinedValue>(not set)</UndefinedValue>;
} else if (colorInfo) {
const {a, b, g, r} = colorInfo;
return (
<>
<ColorBox
key="color-box"
color={`rgba(${r}, ${g}, ${b}, ${a})`}
/>
<ColorValue key="value">
rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)})
</ColorValue>
</>
);
} else {
return <span>Malformed color</span>;
}
}
case 'picker': {
const picker: Picker = JSON.parse(val);
return (
<Select
disabled={!this.props.editable}
options={Array.from(picker.values).map((value) => ({
value,
label: value,
}))}
value={picker.selected}
onChange={(value: string) =>
this.props.commit({
value,
keep: true,
clear: false,
set: true,
})
}
size="small"
style={{fontSize: 11}}
dropdownMatchSelectWidth={false}
/>
);
}
case 'text':
case 'string':
const isUrl = val.startsWith('http://') || val.startsWith('https://');
if (isUrl) {
return (
<>
<Link href={val}>{highlighter.render(val)}</Link>
{editable && (
<EditOutlined
style={{
color: theme.disabledColor,
cursor: 'pointer',
marginLeft: 8,
}}
/>
)}
</>
);
} else {
return (
<StringValue>{highlighter.render(`"${val || ''}"`)}</StringValue>
);
}
case 'enum':
return <StringValue>{highlighter.render(val)}</StringValue>;
case 'boolean':
return editable ? (
<Checkbox
checked={!!val}
disabled={!editable}
onChange={this.onChangeCheckbox}
/>
) : (
<BooleanValue>{'' + val}</BooleanValue>
);
case 'undefined':
return <UndefinedValue>undefined</UndefinedValue>;
case 'date':
if (Object.prototype.toString.call(val) === '[object Date]') {
return <span>{val.toString()}</span>;
} else {
return <span>{val}</span>;
}
case 'null':
return <NullValue>null</NullValue>;
// no description necessary as we'll typically wrap it in [] or {} which
// already denotes the type
case 'array':
return val.length <= 0 ? <EmptyObjectValue>[]</EmptyObjectValue> : null;
case 'object':
return Object.keys(val ?? {}).length <= 0 ? (
<EmptyObjectValue>{'{}'}</EmptyObjectValue>
) : null;
case 'function':
return (
<span>
<FunctionKeyword>function</FunctionKeyword>
<FunctionName> {val.name}()</FunctionName>
</span>
);
case 'symbol':
return <SymbolValue>Symbol()</SymbolValue>;
default:
return <span>Unknown type "{type}"</span>;
}
}
} | random_line_split | |
DataDescription.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {Typography, Popover, Input, Select, Checkbox} from 'antd';
import {DataInspectorSetValue} from './DataInspectorNode';
import {PureComponent} from 'react';
import styled from '@emotion/styled';
import {SketchPicker, CompactPicker} from 'react-color';
import React, {KeyboardEvent} from 'react';
import {HighlightContext} from '../Highlight';
import {parseColor} from '../../utils/parseColor';
import {TimelineDataDescription} from './TimelineDataDescription';
import {theme} from '../theme';
import {EditOutlined} from '@ant-design/icons';
import type {CheckboxChangeEvent} from 'antd/lib/checkbox';
const {Link} = Typography;
// Based on FIG UI Core, TODO: does that still makes sense?
export const presetColors = Object.values({
blue: '#4267b2', // Blue - Active-state nav glyphs, nav bars, links, buttons
green: '#42b72a', // Green - Confirmation, success, commerce and status
red: '#FC3A4B', // Red - Badges, error states
blueGray: '#5f6673', // Blue Grey
slate: '#b9cad2', // Slate
aluminum: '#a3cedf', // Aluminum
seaFoam: '#54c7ec', // Sea Foam
teal: '#6bcebb', // Teal
lime: '#a3ce71', // Lime
lemon: '#fcd872', // Lemon
orange: '#f7923b', // Orange
tomato: '#fb724b', // Tomato - Tometo? Tomato.
cherry: '#f35369', // Cherry
pink: '#ec7ebd', // Pink
grape: '#8c72cb', // Grape
});
export const NullValue = styled.span({
color: theme.semanticColors.nullValue,
});
NullValue.displayName = 'DataDescription:NullValue';
const UndefinedValue = styled.span({
color: theme.semanticColors.nullValue,
});
UndefinedValue.displayName = 'DataDescription:UndefinedValue';
export const StringValue = styled.span({
color: theme.semanticColors.stringValue,
wordWrap: 'break-word',
});
StringValue.displayName = 'DataDescription:StringValue';
const ColorValue = styled.span({
color: theme.semanticColors.colorValue,
});
ColorValue.displayName = 'DataDescription:ColorValue';
const SymbolValue = styled.span({
color: theme.semanticColors.stringValue,
});
SymbolValue.displayName = 'DataDescription:SymbolValue';
export const NumberValue = styled.span({
color: theme.semanticColors.numberValue,
});
NumberValue.displayName = 'DataDescription:NumberValue';
export const BooleanValue = styled.span({
color: theme.semanticColors.booleanValue,
});
BooleanValue.displayName = 'DataDescription:BooleanValue';
const ColorBox = styled.span<{color: string}>((props) => ({
backgroundColor: props.color,
boxShadow: `inset 0 0 1px ${theme.black}`,
display: 'inline-block',
height: 12,
marginRight: 4,
verticalAlign: 'middle',
width: 12,
borderRadius: 4,
}));
ColorBox.displayName = 'DataDescription:ColorBox';
const FunctionKeyword = styled.span({
color: theme.semanticColors.nullValue,
fontStyle: 'italic',
});
FunctionKeyword.displayName = 'DataDescription:FunctionKeyword';
const FunctionName = styled.span({
fontStyle: 'italic',
});
FunctionName.displayName = 'DataDescription:FunctionName';
const ColorPickerDescription = styled.div({
display: 'inline',
position: 'relative',
});
ColorPickerDescription.displayName = 'DataDescription:ColorPickerDescription';
const EmptyObjectValue = styled.span({
fontStyle: 'italic',
});
EmptyObjectValue.displayName = 'DataDescription:EmptyObjectValue';
export type DataDescriptionType =
| 'number'
| 'string'
| 'boolean'
| 'undefined'
| 'null'
| 'object'
| 'array'
| 'date'
| 'symbol'
| 'function'
| 'bigint'
| 'text' // deprecated, please use string
| 'enum' // unformatted string
| 'color'
| 'picker' // multiple choise item like an, eehhh, enum
| 'timeline'
| 'color_lite'; // color with limited palette, specific for fblite;
type DataDescriptionProps = {
path?: Array<string>;
type: DataDescriptionType;
value: any;
extra?: any;
setValue: DataInspectorSetValue | null | undefined;
};
type DescriptionCommitOptions = {
value: any;
keep: boolean;
clear: boolean;
set: boolean;
};
class NumberTextEditor extends PureComponent<{
commit: (opts: DescriptionCommitOptions) => void;
type: DataDescriptionType;
value: any;
origValue: any;
}> {
onNumberTextInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val =
this.props.type === 'number'
? parseFloat(e.target.value)
: e.target.value;
this.props.commit({
clear: false,
keep: true,
value: val,
set: false,
});
};
onNumberTextInputKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter') {
const val =
this.props.type === 'number'
? parseFloat(this.props.value)
: this.props.value;
this.props.commit({clear: true, keep: true, value: val, set: true});
} else if (e.key === 'Escape') {
this.props.commit({
clear: true,
keep: false,
value: this.props.origValue,
set: false,
});
}
};
onNumberTextRef = (ref: HTMLElement | undefined | null) => {
if (ref) {
ref.focus();
}
};
onNumberTextBlur = () => {
this.props.commit({
clear: true,
keep: true,
value: this.props.value,
set: true,
});
};
render() {
const extraProps: any = {};
if (this.props.type === 'number') {
// render as a HTML number input
extraProps.type = 'number';
// step="any" allows any sort of float to be input, otherwise we're limited
// to decimal
extraProps.step = 'any';
}
return (
<Input
key="input"
{...extraProps}
size="small"
onChange={this.onNumberTextInputChange}
onKeyDown={this.onNumberTextInputKeyDown}
ref={this.onNumberTextRef}
onBlur={this.onNumberTextBlur}
value={this.props.value}
style={{fontSize: 11}}
/>
);
}
}
type DataDescriptionState = {
editing: boolean;
origValue: any;
value: any;
};
export class DataDescription extends PureComponent<
DataDescriptionProps,
DataDescriptionState
> {
constructor(props: DataDescriptionProps, context: Object) {
super(props, context);
this.state = {
editing: false,
origValue: '',
value: '',
};
}
commit = (opts: DescriptionCommitOptions) => {
const {path, setValue} = this.props;
if (opts.keep && setValue && path) {
const val = opts.value;
this.setState({value: val});
if (opts.set) {
setValue(path, val);
}
}
if (opts.clear) {
this.setState({
editing: false,
origValue: '',
value: '',
});
}
};
_renderEditing() {
const {type, extra} = this.props;
const {origValue, value} = this.state;
if (
type === 'string' ||
type === 'text' ||
type === 'number' ||
type === 'enum'
) {
return (
<NumberTextEditor
type={type}
value={value}
origValue={origValue}
commit={this.commit}
/>
);
}
if (type === 'color') {
return <ColorEditor value={value} commit={this.commit} />;
}
if (type === 'color_lite') {
return (
<ColorEditor
value={value}
colorSet={extra.colorSet}
commit={this.commit}
/>
);
}
return null;
}
_hasEditUI() {
const {type} = this.props;
return (
type === 'string' ||
type === 'text' ||
type === 'number' ||
type === 'enum' ||
type === 'color' ||
type === 'color_lite'
);
}
onEditStart = () => {
this.setState({
editing: this._hasEditUI(),
origValue: this.props.value,
value: this.props.value,
});
};
render(): any {
if (this.state.editing) {
return this._renderEditing();
} else {
return (
<DataDescriptionPreview
type={this.props.type}
value={this.props.value}
extra={this.props.extra}
editable={!!this.props.setValue}
commit={this.commit}
onEdit={this.onEditStart}
/>
);
}
}
}
class ColorEditor extends PureComponent<{
value: any;
colorSet?: Array<string | number>;
commit: (opts: DescriptionCommitOptions) => void;
}> {
onBlur = (newVisibility: boolean) => {
if (!newVisibility) {
this.props.commit({
clear: true,
keep: false,
value: this.props.value,
set: true,
});
}
};
onChange = ({
hex,
rgb: {a, b, g, r},
}: {
hex: string;
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
let val;
if (typeof prev === 'string') {
if (a === 1) {
// hex is fine and has an implicit 100% alpha
val = hex;
} else {
// turn into a css rgba value
val = `rgba(${r}, ${g}, ${b}, ${a})`;
}
} else if (typeof prev === 'number') {
// compute RRGGBBAA value
val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
const prevClear = ((prev >> 24) & 0xff) === 0;
const onlyAlphaChanged = (prev & 0x00ffffff) === (val & 0x00ffffff);
if (!onlyAlphaChanged && prevClear) {
val = 0xff000000 | (val & 0x00ffffff);
}
} else {
return;
}
this.props.commit({clear: false, keep: true, value: val, set: true});
};
onChangeLite = ({
rgb: {a, b, g, r},
}: {
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
if (typeof prev !== 'number') {
return;
}
// compute RRGGBBAA value
let val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
this.props.commit({clear: false, keep: true, value: val, set: true});
};
render() {
const colorInfo = parseColor(this.props.value);
if (!colorInfo) {
return null;
}
return (
<Popover
trigger={'click'}
onVisibleChange={this.onBlur}
content={() =>
this.props.colorSet ? (
<CompactPicker
color={colorInfo}
colors={this.props.colorSet
.filter((x) => x != 0)
.map(parseColor)
.map((rgba) => {
if (!rgba) {
return '';
}
return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
})}
onChange={(color: {
hex: string;
hsl: {
a?: number;
h: number;
l: number;
s: number;
};
rgb: {a?: number; b: number; g: number; r: number};
}) => {
this.onChangeLite({rgb: {...color.rgb, a: color.rgb.a || 0}});
}}
/>
) : (
<SketchPicker
color={colorInfo}
presetColors={presetColors}
onChange={(color: {
hex: string;
hsl: {
a?: number;
h: number;
l: number;
s: number;
};
rgb: {a?: number; b: number; g: number; r: number};
}) => {
this.onChange({
hex: color.hex,
rgb: {...color.rgb, a: color.rgb.a || 1},
});
}}
/>
)
}>
<ColorPickerDescription>
<DataDescriptionPreview
type="color"
value={this.props.value}
extra={this.props.colorSet}
editable={false}
commit={this.props.commit}
/>
</ColorPickerDescription>
</Popover>
);
}
}
class DataDescriptionPreview extends PureComponent<{
type: DataDescriptionType;
value: any;
extra?: any;
editable: boolean;
commit: (opts: DescriptionCommitOptions) => void;
onEdit?: () => void;
}> {
onClick = () => {
const {onEdit} = this.props;
if (this.props.editable && onEdit) {
onEdit();
}
};
| () {
const {type, value} = this.props;
const description = (
<DataDescriptionContainer
type={type}
value={value}
editable={this.props.editable}
commit={this.props.commit}
/>
);
// booleans are always editable so don't require the onEditStart handler
if (type === 'boolean') {
return description;
}
return (
<span onClick={this.onClick} role="button" tabIndex={-1}>
{description}
</span>
);
}
}
type Picker = {
values: Set<string>;
selected: string;
};
class DataDescriptionContainer extends PureComponent<{
type: DataDescriptionType;
value: any;
editable: boolean;
commit: (opts: DescriptionCommitOptions) => void;
}> {
static contextType = HighlightContext; // Replace with useHighlighter
context!: React.ContextType<typeof HighlightContext>;
onChangeCheckbox = (e: CheckboxChangeEvent) => {
this.props.commit({
clear: true,
keep: true,
value: e.target.checked,
set: true,
});
};
render(): any {
const {type, editable, value: val} = this.props;
const highlighter = this.context;
switch (type) {
case 'timeline': {
return (
<>
<TimelineDataDescription
canSetCurrent={editable}
timeline={JSON.parse(val)}
onClick={(id) => {
this.props.commit({
value: id,
keep: true,
clear: false,
set: true,
});
}}
/>
</>
);
}
case 'number':
return <NumberValue>{+val}</NumberValue>;
case 'color': {
const colorInfo = parseColor(val);
if (typeof val === 'number' && val === 0) {
return <UndefinedValue>(not set)</UndefinedValue>;
} else if (colorInfo) {
const {a, b, g, r} = colorInfo;
return (
<>
<ColorBox
key="color-box"
color={`rgba(${r}, ${g}, ${b}, ${a})`}
/>
<ColorValue key="value">
rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)})
</ColorValue>
</>
);
} else {
return <span>Malformed color</span>;
}
}
case 'color_lite': {
const colorInfo = parseColor(val);
if (typeof val === 'number' && val === 0) {
return <UndefinedValue>(not set)</UndefinedValue>;
} else if (colorInfo) {
const {a, b, g, r} = colorInfo;
return (
<>
<ColorBox
key="color-box"
color={`rgba(${r}, ${g}, ${b}, ${a})`}
/>
<ColorValue key="value">
rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)})
</ColorValue>
</>
);
} else {
return <span>Malformed color</span>;
}
}
case 'picker': {
const picker: Picker = JSON.parse(val);
return (
<Select
disabled={!this.props.editable}
options={Array.from(picker.values).map((value) => ({
value,
label: value,
}))}
value={picker.selected}
onChange={(value: string) =>
this.props.commit({
value,
keep: true,
clear: false,
set: true,
})
}
size="small"
style={{fontSize: 11}}
dropdownMatchSelectWidth={false}
/>
);
}
case 'text':
case 'string':
const isUrl = val.startsWith('http://') || val.startsWith('https://');
if (isUrl) {
return (
<>
<Link href={val}>{highlighter.render(val)}</Link>
{editable && (
<EditOutlined
style={{
color: theme.disabledColor,
cursor: 'pointer',
marginLeft: 8,
}}
/>
)}
</>
);
} else {
return (
<StringValue>{highlighter.render(`"${val || ''}"`)}</StringValue>
);
}
case 'enum':
return <StringValue>{highlighter.render(val)}</StringValue>;
case 'boolean':
return editable ? (
<Checkbox
checked={!!val}
disabled={!editable}
onChange={this.onChangeCheckbox}
/>
) : (
<BooleanValue>{'' + val}</BooleanValue>
);
case 'undefined':
return <UndefinedValue>undefined</UndefinedValue>;
case 'date':
if (Object.prototype.toString.call(val) === '[object Date]') {
return <span>{val.toString()}</span>;
} else {
return <span>{val}</span>;
}
case 'null':
return <NullValue>null</NullValue>;
// no description necessary as we'll typically wrap it in [] or {} which
// already denotes the type
case 'array':
return val.length <= 0 ? <EmptyObjectValue>[]</EmptyObjectValue> : null;
case 'object':
return Object.keys(val ?? {}).length <= 0 ? (
<EmptyObjectValue>{'{}'}</EmptyObjectValue>
) : null;
case 'function':
return (
<span>
<FunctionKeyword>function</FunctionKeyword>
<FunctionName> {val.name}()</FunctionName>
</span>
);
case 'symbol':
return <SymbolValue>Symbol()</SymbolValue>;
default:
return <span>Unknown type "{type}"</span>;
}
}
}
| render | identifier_name |
DataDescription.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {Typography, Popover, Input, Select, Checkbox} from 'antd';
import {DataInspectorSetValue} from './DataInspectorNode';
import {PureComponent} from 'react';
import styled from '@emotion/styled';
import {SketchPicker, CompactPicker} from 'react-color';
import React, {KeyboardEvent} from 'react';
import {HighlightContext} from '../Highlight';
import {parseColor} from '../../utils/parseColor';
import {TimelineDataDescription} from './TimelineDataDescription';
import {theme} from '../theme';
import {EditOutlined} from '@ant-design/icons';
import type {CheckboxChangeEvent} from 'antd/lib/checkbox';
const {Link} = Typography;
// Based on FIG UI Core, TODO: does that still makes sense?
export const presetColors = Object.values({
blue: '#4267b2', // Blue - Active-state nav glyphs, nav bars, links, buttons
green: '#42b72a', // Green - Confirmation, success, commerce and status
red: '#FC3A4B', // Red - Badges, error states
blueGray: '#5f6673', // Blue Grey
slate: '#b9cad2', // Slate
aluminum: '#a3cedf', // Aluminum
seaFoam: '#54c7ec', // Sea Foam
teal: '#6bcebb', // Teal
lime: '#a3ce71', // Lime
lemon: '#fcd872', // Lemon
orange: '#f7923b', // Orange
tomato: '#fb724b', // Tomato - Tometo? Tomato.
cherry: '#f35369', // Cherry
pink: '#ec7ebd', // Pink
grape: '#8c72cb', // Grape
});
export const NullValue = styled.span({
color: theme.semanticColors.nullValue,
});
NullValue.displayName = 'DataDescription:NullValue';
const UndefinedValue = styled.span({
color: theme.semanticColors.nullValue,
});
UndefinedValue.displayName = 'DataDescription:UndefinedValue';
export const StringValue = styled.span({
color: theme.semanticColors.stringValue,
wordWrap: 'break-word',
});
StringValue.displayName = 'DataDescription:StringValue';
const ColorValue = styled.span({
color: theme.semanticColors.colorValue,
});
ColorValue.displayName = 'DataDescription:ColorValue';
const SymbolValue = styled.span({
color: theme.semanticColors.stringValue,
});
SymbolValue.displayName = 'DataDescription:SymbolValue';
export const NumberValue = styled.span({
color: theme.semanticColors.numberValue,
});
NumberValue.displayName = 'DataDescription:NumberValue';
export const BooleanValue = styled.span({
color: theme.semanticColors.booleanValue,
});
BooleanValue.displayName = 'DataDescription:BooleanValue';
const ColorBox = styled.span<{color: string}>((props) => ({
backgroundColor: props.color,
boxShadow: `inset 0 0 1px ${theme.black}`,
display: 'inline-block',
height: 12,
marginRight: 4,
verticalAlign: 'middle',
width: 12,
borderRadius: 4,
}));
ColorBox.displayName = 'DataDescription:ColorBox';
const FunctionKeyword = styled.span({
color: theme.semanticColors.nullValue,
fontStyle: 'italic',
});
FunctionKeyword.displayName = 'DataDescription:FunctionKeyword';
const FunctionName = styled.span({
fontStyle: 'italic',
});
FunctionName.displayName = 'DataDescription:FunctionName';
const ColorPickerDescription = styled.div({
display: 'inline',
position: 'relative',
});
ColorPickerDescription.displayName = 'DataDescription:ColorPickerDescription';
const EmptyObjectValue = styled.span({
fontStyle: 'italic',
});
EmptyObjectValue.displayName = 'DataDescription:EmptyObjectValue';
export type DataDescriptionType =
| 'number'
| 'string'
| 'boolean'
| 'undefined'
| 'null'
| 'object'
| 'array'
| 'date'
| 'symbol'
| 'function'
| 'bigint'
| 'text' // deprecated, please use string
| 'enum' // unformatted string
| 'color'
| 'picker' // multiple choise item like an, eehhh, enum
| 'timeline'
| 'color_lite'; // color with limited palette, specific for fblite;
type DataDescriptionProps = {
path?: Array<string>;
type: DataDescriptionType;
value: any;
extra?: any;
setValue: DataInspectorSetValue | null | undefined;
};
type DescriptionCommitOptions = {
value: any;
keep: boolean;
clear: boolean;
set: boolean;
};
class NumberTextEditor extends PureComponent<{
commit: (opts: DescriptionCommitOptions) => void;
type: DataDescriptionType;
value: any;
origValue: any;
}> {
onNumberTextInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val =
this.props.type === 'number'
? parseFloat(e.target.value)
: e.target.value;
this.props.commit({
clear: false,
keep: true,
value: val,
set: false,
});
};
onNumberTextInputKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Enter') {
const val =
this.props.type === 'number'
? parseFloat(this.props.value)
: this.props.value;
this.props.commit({clear: true, keep: true, value: val, set: true});
} else if (e.key === 'Escape') {
this.props.commit({
clear: true,
keep: false,
value: this.props.origValue,
set: false,
});
}
};
onNumberTextRef = (ref: HTMLElement | undefined | null) => {
if (ref) {
ref.focus();
}
};
onNumberTextBlur = () => {
this.props.commit({
clear: true,
keep: true,
value: this.props.value,
set: true,
});
};
render() {
const extraProps: any = {};
if (this.props.type === 'number') {
// render as a HTML number input
extraProps.type = 'number';
// step="any" allows any sort of float to be input, otherwise we're limited
// to decimal
extraProps.step = 'any';
}
return (
<Input
key="input"
{...extraProps}
size="small"
onChange={this.onNumberTextInputChange}
onKeyDown={this.onNumberTextInputKeyDown}
ref={this.onNumberTextRef}
onBlur={this.onNumberTextBlur}
value={this.props.value}
style={{fontSize: 11}}
/>
);
}
}
type DataDescriptionState = {
editing: boolean;
origValue: any;
value: any;
};
export class DataDescription extends PureComponent<
DataDescriptionProps,
DataDescriptionState
> {
constructor(props: DataDescriptionProps, context: Object) {
super(props, context);
this.state = {
editing: false,
origValue: '',
value: '',
};
}
commit = (opts: DescriptionCommitOptions) => {
const {path, setValue} = this.props;
if (opts.keep && setValue && path) {
const val = opts.value;
this.setState({value: val});
if (opts.set) {
setValue(path, val);
}
}
if (opts.clear) {
this.setState({
editing: false,
origValue: '',
value: '',
});
}
};
_renderEditing() {
const {type, extra} = this.props;
const {origValue, value} = this.state;
if (
type === 'string' ||
type === 'text' ||
type === 'number' ||
type === 'enum'
) {
return (
<NumberTextEditor
type={type}
value={value}
origValue={origValue}
commit={this.commit}
/>
);
}
if (type === 'color') {
return <ColorEditor value={value} commit={this.commit} />;
}
if (type === 'color_lite') {
return (
<ColorEditor
value={value}
colorSet={extra.colorSet}
commit={this.commit}
/>
);
}
return null;
}
_hasEditUI() {
const {type} = this.props;
return (
type === 'string' ||
type === 'text' ||
type === 'number' ||
type === 'enum' ||
type === 'color' ||
type === 'color_lite'
);
}
onEditStart = () => {
this.setState({
editing: this._hasEditUI(),
origValue: this.props.value,
value: this.props.value,
});
};
render(): any {
if (this.state.editing) {
return this._renderEditing();
} else {
return (
<DataDescriptionPreview
type={this.props.type}
value={this.props.value}
extra={this.props.extra}
editable={!!this.props.setValue}
commit={this.commit}
onEdit={this.onEditStart}
/>
);
}
}
}
class ColorEditor extends PureComponent<{
value: any;
colorSet?: Array<string | number>;
commit: (opts: DescriptionCommitOptions) => void;
}> {
onBlur = (newVisibility: boolean) => {
if (!newVisibility) {
this.props.commit({
clear: true,
keep: false,
value: this.props.value,
set: true,
});
}
};
onChange = ({
hex,
rgb: {a, b, g, r},
}: {
hex: string;
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
let val;
if (typeof prev === 'string') {
if (a === 1) {
// hex is fine and has an implicit 100% alpha
val = hex;
} else {
// turn into a css rgba value
val = `rgba(${r}, ${g}, ${b}, ${a})`;
}
} else if (typeof prev === 'number') | else {
return;
}
this.props.commit({clear: false, keep: true, value: val, set: true});
};
onChangeLite = ({
rgb: {a, b, g, r},
}: {
rgb: {a: number; b: number; g: number; r: number};
}) => {
const prev = this.props.value;
if (typeof prev !== 'number') {
return;
}
// compute RRGGBBAA value
let val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
this.props.commit({clear: false, keep: true, value: val, set: true});
};
render() {
const colorInfo = parseColor(this.props.value);
if (!colorInfo) {
return null;
}
return (
<Popover
trigger={'click'}
onVisibleChange={this.onBlur}
content={() =>
this.props.colorSet ? (
<CompactPicker
color={colorInfo}
colors={this.props.colorSet
.filter((x) => x != 0)
.map(parseColor)
.map((rgba) => {
if (!rgba) {
return '';
}
return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
})}
onChange={(color: {
hex: string;
hsl: {
a?: number;
h: number;
l: number;
s: number;
};
rgb: {a?: number; b: number; g: number; r: number};
}) => {
this.onChangeLite({rgb: {...color.rgb, a: color.rgb.a || 0}});
}}
/>
) : (
<SketchPicker
color={colorInfo}
presetColors={presetColors}
onChange={(color: {
hex: string;
hsl: {
a?: number;
h: number;
l: number;
s: number;
};
rgb: {a?: number; b: number; g: number; r: number};
}) => {
this.onChange({
hex: color.hex,
rgb: {...color.rgb, a: color.rgb.a || 1},
});
}}
/>
)
}>
<ColorPickerDescription>
<DataDescriptionPreview
type="color"
value={this.props.value}
extra={this.props.colorSet}
editable={false}
commit={this.props.commit}
/>
</ColorPickerDescription>
</Popover>
);
}
}
class DataDescriptionPreview extends PureComponent<{
type: DataDescriptionType;
value: any;
extra?: any;
editable: boolean;
commit: (opts: DescriptionCommitOptions) => void;
onEdit?: () => void;
}> {
onClick = () => {
const {onEdit} = this.props;
if (this.props.editable && onEdit) {
onEdit();
}
};
render() {
const {type, value} = this.props;
const description = (
<DataDescriptionContainer
type={type}
value={value}
editable={this.props.editable}
commit={this.props.commit}
/>
);
// booleans are always editable so don't require the onEditStart handler
if (type === 'boolean') {
return description;
}
return (
<span onClick={this.onClick} role="button" tabIndex={-1}>
{description}
</span>
);
}
}
type Picker = {
values: Set<string>;
selected: string;
};
class DataDescriptionContainer extends PureComponent<{
type: DataDescriptionType;
value: any;
editable: boolean;
commit: (opts: DescriptionCommitOptions) => void;
}> {
static contextType = HighlightContext; // Replace with useHighlighter
context!: React.ContextType<typeof HighlightContext>;
onChangeCheckbox = (e: CheckboxChangeEvent) => {
this.props.commit({
clear: true,
keep: true,
value: e.target.checked,
set: true,
});
};
render(): any {
const {type, editable, value: val} = this.props;
const highlighter = this.context;
switch (type) {
case 'timeline': {
return (
<>
<TimelineDataDescription
canSetCurrent={editable}
timeline={JSON.parse(val)}
onClick={(id) => {
this.props.commit({
value: id,
keep: true,
clear: false,
set: true,
});
}}
/>
</>
);
}
case 'number':
return <NumberValue>{+val}</NumberValue>;
case 'color': {
const colorInfo = parseColor(val);
if (typeof val === 'number' && val === 0) {
return <UndefinedValue>(not set)</UndefinedValue>;
} else if (colorInfo) {
const {a, b, g, r} = colorInfo;
return (
<>
<ColorBox
key="color-box"
color={`rgba(${r}, ${g}, ${b}, ${a})`}
/>
<ColorValue key="value">
rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)})
</ColorValue>
</>
);
} else {
return <span>Malformed color</span>;
}
}
case 'color_lite': {
const colorInfo = parseColor(val);
if (typeof val === 'number' && val === 0) {
return <UndefinedValue>(not set)</UndefinedValue>;
} else if (colorInfo) {
const {a, b, g, r} = colorInfo;
return (
<>
<ColorBox
key="color-box"
color={`rgba(${r}, ${g}, ${b}, ${a})`}
/>
<ColorValue key="value">
rgba({r}, {g}, {b}, {a === 1 ? '1' : a.toFixed(2)})
</ColorValue>
</>
);
} else {
return <span>Malformed color</span>;
}
}
case 'picker': {
const picker: Picker = JSON.parse(val);
return (
<Select
disabled={!this.props.editable}
options={Array.from(picker.values).map((value) => ({
value,
label: value,
}))}
value={picker.selected}
onChange={(value: string) =>
this.props.commit({
value,
keep: true,
clear: false,
set: true,
})
}
size="small"
style={{fontSize: 11}}
dropdownMatchSelectWidth={false}
/>
);
}
case 'text':
case 'string':
const isUrl = val.startsWith('http://') || val.startsWith('https://');
if (isUrl) {
return (
<>
<Link href={val}>{highlighter.render(val)}</Link>
{editable && (
<EditOutlined
style={{
color: theme.disabledColor,
cursor: 'pointer',
marginLeft: 8,
}}
/>
)}
</>
);
} else {
return (
<StringValue>{highlighter.render(`"${val || ''}"`)}</StringValue>
);
}
case 'enum':
return <StringValue>{highlighter.render(val)}</StringValue>;
case 'boolean':
return editable ? (
<Checkbox
checked={!!val}
disabled={!editable}
onChange={this.onChangeCheckbox}
/>
) : (
<BooleanValue>{'' + val}</BooleanValue>
);
case 'undefined':
return <UndefinedValue>undefined</UndefinedValue>;
case 'date':
if (Object.prototype.toString.call(val) === '[object Date]') {
return <span>{val.toString()}</span>;
} else {
return <span>{val}</span>;
}
case 'null':
return <NullValue>null</NullValue>;
// no description necessary as we'll typically wrap it in [] or {} which
// already denotes the type
case 'array':
return val.length <= 0 ? <EmptyObjectValue>[]</EmptyObjectValue> : null;
case 'object':
return Object.keys(val ?? {}).length <= 0 ? (
<EmptyObjectValue>{'{}'}</EmptyObjectValue>
) : null;
case 'function':
return (
<span>
<FunctionKeyword>function</FunctionKeyword>
<FunctionName> {val.name}()</FunctionName>
</span>
);
case 'symbol':
return <SymbolValue>Symbol()</SymbolValue>;
default:
return <span>Unknown type "{type}"</span>;
}
}
}
| {
// compute RRGGBBAA value
val = (Math.round(a * 255) & 0xff) << 24;
val |= (r & 0xff) << 16;
val |= (g & 0xff) << 8;
val |= b & 0xff;
const prevClear = ((prev >> 24) & 0xff) === 0;
const onlyAlphaChanged = (prev & 0x00ffffff) === (val & 0x00ffffff);
if (!onlyAlphaChanged && prevClear) {
val = 0xff000000 | (val & 0x00ffffff);
}
} | conditional_block |
Navigation.ts | /**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
/// <reference path="../../index.d.ts" />
/// <reference path="./report/index.ts" />
/// <reference path="./users/index.ts" />
namespace reportanalysis {
export namespace ui {
/**
* 视图导航
*/
export class Navigation extends ibas.ViewNavigation {
/**
* 创建实例
* @param id 应用id
*/
protected newView(id: string): ibas.IView {
le | t view: ibas.IView = null;
switch (id) {
case app.ReportViewerApp.APPLICATION_ID:
view = new m.ReportViewerView();
break;
case app.UserReportPageApp.APPLICATION_ID:
view = new m.UserReportPageView();
break;
case app.BOReportService.APPLICATION_ID:
view = new m.BOReportServiceView();
break;
default:
break;
}
return view;
}
}
}
} | identifier_body | |
Navigation.ts | /**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
/// <reference path="../../index.d.ts" />
/// <reference path="./report/index.ts" />
/// <reference path="./users/index.ts" />
namespace reportanalysis {
export namespace ui {
/**
* 视图导航
*/
export class Navigation extends ibas.ViewNavigation {
/**
* 创建实例
* @param id 应用id
*/
protected newView(id: string): | View {
let view: ibas.IView = null;
switch (id) {
case app.ReportViewerApp.APPLICATION_ID:
view = new m.ReportViewerView();
break;
case app.UserReportPageApp.APPLICATION_ID:
view = new m.UserReportPageView();
break;
case app.BOReportService.APPLICATION_ID:
view = new m.BOReportServiceView();
break;
default:
break;
}
return view;
}
}
}
} | ibas.I | identifier_name |
Navigation.ts | /**
* @license
* Copyright Color-Coding Studio. All Rights Reserved.
*
* Use of this source code is governed by an Apache License, Version 2.0
* that can be found in the LICENSE file at http://www.apache.org/licenses/LICENSE-2.0
*/
/// <reference path="../../index.d.ts" />
/// <reference path="./report/index.ts" />
/// <reference path="./users/index.ts" />
namespace reportanalysis {
export namespace ui {
/**
* 视图导航
*/
export class Navigation extends ibas.ViewNavigation {
/**
* 创建实例
* @param id 应用id
*/
protected newView(id: string): ibas.IView {
let view: ibas.IView = null;
switch (id) {
case app.ReportViewerApp.APPLICATION_ID:
view = new m.ReportViewerView();
break;
case app.UserReportPageApp.APPLICATION_ID:
view = new m.UserReportPageView();
break;
case app.BOReportService.APPLICATION_ID:
view = new m.BOReportServiceView(); | }
}
}
} | break;
default:
break;
}
return view; | random_line_split |
api_handlers.py | # -*- coding: utf-8 -*-
import json
import os
from tornado import web
from notebook.base.handlers import APIHandler
from .handlers import notebook_dir
def _trim_notebook_dir(dir):
if not dir.startswith("/"):
return os.path.join(
"<notebook_dir>", os.path.relpath(dir, notebook_dir)
)
return dir
class TbRootHandler(APIHandler):
@web.authenticated
def get(self):
terms = [
{
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
"reload_time": entry.thread.reload_time,
} for entry in
self.settings["tensorboard_manager"].values()
]
self.finish(json.dumps(terms))
@web.authenticated
def post(self):
data = self.get_json_body()
reload_interval = data.get("reload_interval", None)
entry = (
self.settings["tensorboard_manager"]
.new_instance(data["logdir"], reload_interval=reload_interval)
)
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time}))
class TbInstanceHandler(APIHandler):
SUPPORTED_METHODS = ('GET', 'DELETE')
@web.authenticated
def get(self, name):
manager = self.settings["tensorboard_manager"]
if name in manager:
|
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name)
@web.authenticated
def delete(self, name):
manager = self.settings["tensorboard_manager"]
if name in manager:
manager.terminate(name, force=True)
self.set_status(204)
self.finish()
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name)
| entry = manager[name]
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time})) | conditional_block |
api_handlers.py | # -*- coding: utf-8 -*-
import json
import os
from tornado import web
from notebook.base.handlers import APIHandler
from .handlers import notebook_dir
def _trim_notebook_dir(dir):
if not dir.startswith("/"):
return os.path.join(
"<notebook_dir>", os.path.relpath(dir, notebook_dir)
)
return dir
class TbRootHandler(APIHandler):
@web.authenticated
def get(self):
terms = [
{
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
"reload_time": entry.thread.reload_time,
} for entry in
self.settings["tensorboard_manager"].values()
]
self.finish(json.dumps(terms))
@web.authenticated
def post(self):
data = self.get_json_body()
reload_interval = data.get("reload_interval", None)
entry = (
self.settings["tensorboard_manager"]
.new_instance(data["logdir"], reload_interval=reload_interval)
)
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time}))
class TbInstanceHandler(APIHandler):
SUPPORTED_METHODS = ('GET', 'DELETE')
@web.authenticated
def get(self, name):
manager = self.settings["tensorboard_manager"]
if name in manager:
entry = manager[name]
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time}))
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name)
@web.authenticated
def delete(self, name):
| manager = self.settings["tensorboard_manager"]
if name in manager:
manager.terminate(name, force=True)
self.set_status(204)
self.finish()
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name) | identifier_body | |
api_handlers.py | # -*- coding: utf-8 -*-
import json
import os
from tornado import web
from notebook.base.handlers import APIHandler
from .handlers import notebook_dir
def _trim_notebook_dir(dir):
if not dir.startswith("/"):
return os.path.join(
"<notebook_dir>", os.path.relpath(dir, notebook_dir)
)
return dir
class TbRootHandler(APIHandler):
@web.authenticated
def get(self):
terms = [
{
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
"reload_time": entry.thread.reload_time,
} for entry in
self.settings["tensorboard_manager"].values()
]
self.finish(json.dumps(terms))
@web.authenticated
def post(self):
data = self.get_json_body()
reload_interval = data.get("reload_interval", None)
entry = (
self.settings["tensorboard_manager"]
.new_instance(data["logdir"], reload_interval=reload_interval)
)
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time}))
class TbInstanceHandler(APIHandler):
SUPPORTED_METHODS = ('GET', 'DELETE')
| manager = self.settings["tensorboard_manager"]
if name in manager:
entry = manager[name]
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time}))
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name)
@web.authenticated
def delete(self, name):
manager = self.settings["tensorboard_manager"]
if name in manager:
manager.terminate(name, force=True)
self.set_status(204)
self.finish()
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name) | @web.authenticated
def get(self, name):
| random_line_split |
api_handlers.py | # -*- coding: utf-8 -*-
import json
import os
from tornado import web
from notebook.base.handlers import APIHandler
from .handlers import notebook_dir
def _trim_notebook_dir(dir):
if not dir.startswith("/"):
return os.path.join(
"<notebook_dir>", os.path.relpath(dir, notebook_dir)
)
return dir
class TbRootHandler(APIHandler):
@web.authenticated
def get(self):
terms = [
{
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
"reload_time": entry.thread.reload_time,
} for entry in
self.settings["tensorboard_manager"].values()
]
self.finish(json.dumps(terms))
@web.authenticated
def post(self):
data = self.get_json_body()
reload_interval = data.get("reload_interval", None)
entry = (
self.settings["tensorboard_manager"]
.new_instance(data["logdir"], reload_interval=reload_interval)
)
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time}))
class TbInstanceHandler(APIHandler):
SUPPORTED_METHODS = ('GET', 'DELETE')
@web.authenticated
def | (self, name):
manager = self.settings["tensorboard_manager"]
if name in manager:
entry = manager[name]
self.finish(json.dumps({
'name': entry.name,
'logdir': _trim_notebook_dir(entry.logdir),
'reload_time': entry.thread.reload_time}))
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name)
@web.authenticated
def delete(self, name):
manager = self.settings["tensorboard_manager"]
if name in manager:
manager.terminate(name, force=True)
self.set_status(204)
self.finish()
else:
raise web.HTTPError(
404, "TensorBoard instance not found: %r" % name)
| get | identifier_name |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn new(ip: String, date: String, req: String, code: i32, size: i32, referer: String, agent: String) -> Weblog {
Weblog { ip: ip, date: date, req: req, code: code, size: size, referer: referer, agent: agent }
}
}
impl Eq for Weblog {}
impl PartialEq for Weblog {
fn eq(&self, other: &Self) -> bool {
self.ip == other.ip && self.date == other.date
}
}
impl fmt::Display for Weblog {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
| {
write!(f, "({}, {}, {}, {}, {}, {}, {})",
self.ip, self.date, self.req, self.code,
self.size, self.referer, self.agent)
} | identifier_body |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn | (ip: String, date: String, req: String, code: i32, size: i32, referer: String, agent: String) -> Weblog {
Weblog { ip: ip, date: date, req: req, code: code, size: size, referer: referer, agent: agent }
}
}
impl Eq for Weblog {}
impl PartialEq for Weblog {
fn eq(&self, other: &Self) -> bool {
self.ip == other.ip && self.date == other.date
}
}
impl fmt::Display for Weblog {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {}, {}, {}, {}, {}, {})",
self.ip, self.date, self.req, self.code,
self.size, self.referer, self.agent)
}
}
| new | identifier_name |
weblog.rs | use std::fmt;
// Define a weblog struct
#[derive(Debug)]
pub struct Weblog {
pub ip: String,
pub date: String,
pub req: String,
pub code: i32,
pub size: i32,
pub referer: String,
pub agent: String,
}
impl Weblog {
pub fn new(ip: String, date: String, req: String, code: i32, size: i32, referer: String, agent: String) -> Weblog {
Weblog { ip: ip, date: date, req: req, code: code, size: size, referer: referer, agent: agent }
}
}
impl Eq for Weblog {}
impl PartialEq for Weblog { | }
impl fmt::Display for Weblog {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {}, {}, {}, {}, {}, {})",
self.ip, self.date, self.req, self.code,
self.size, self.referer, self.agent)
}
} | fn eq(&self, other: &Self) -> bool {
self.ip == other.ip && self.date == other.date
} | random_line_split |
mir-typeck-normalize-fn-sig.rs | // Copyright 2016 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)]
// This code was creating an ICE in the MIR type checker. The reason
// is that we are reifying a reference to a function (`foo::<'x>`),
// which involves extracting its signature, but we were not
// normalizing the signature afterwards. As a result, we sometimes got
// errors around the `<u32 as Foo<'x>>::Value`, which can be
// normalized to `f64`.
#![allow(dead_code)]
trait Foo<'x> {
type Value;
}
impl<'x> Foo<'x> for u32 {
type Value = f64;
}
struct | <'x> {
foo: for<'y> fn(x: &'x u32, y: &'y u32) -> <u32 as Foo<'x>>::Value,
}
fn foo<'y, 'x: 'x>(x: &'x u32, y: &'y u32) -> <u32 as Foo<'x>>::Value {
*x as f64
}
fn main() {
Providers { foo };
}
| Providers | identifier_name |
mir-typeck-normalize-fn-sig.rs | // Copyright 2016 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)]
// This code was creating an ICE in the MIR type checker. The reason
// is that we are reifying a reference to a function (`foo::<'x>`),
// which involves extracting its signature, but we were not
// normalizing the signature afterwards. As a result, we sometimes got
// errors around the `<u32 as Foo<'x>>::Value`, which can be
// normalized to `f64`.
#![allow(dead_code)]
trait Foo<'x> {
type Value;
}
impl<'x> Foo<'x> for u32 {
type Value = f64;
}
struct Providers<'x> {
foo: for<'y> fn(x: &'x u32, y: &'y u32) -> <u32 as Foo<'x>>::Value,
}
fn foo<'y, 'x: 'x>(x: &'x u32, y: &'y u32) -> <u32 as Foo<'x>>::Value {
*x as f64
}
fn main() | {
Providers { foo };
} | identifier_body | |
mir-typeck-normalize-fn-sig.rs | // Copyright 2016 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_variables)]
// This code was creating an ICE in the MIR type checker. The reason
// is that we are reifying a reference to a function (`foo::<'x>`), | // normalizing the signature afterwards. As a result, we sometimes got
// errors around the `<u32 as Foo<'x>>::Value`, which can be
// normalized to `f64`.
#![allow(dead_code)]
trait Foo<'x> {
type Value;
}
impl<'x> Foo<'x> for u32 {
type Value = f64;
}
struct Providers<'x> {
foo: for<'y> fn(x: &'x u32, y: &'y u32) -> <u32 as Foo<'x>>::Value,
}
fn foo<'y, 'x: 'x>(x: &'x u32, y: &'y u32) -> <u32 as Foo<'x>>::Value {
*x as f64
}
fn main() {
Providers { foo };
} | // which involves extracting its signature, but we were not | random_line_split |
_webcore.ts | // TypeScript declarations for the Dicoogle webcore
import {SearchPatientResult} from 'dicoogle-client';
export type WebPluginType = string;
export type WebcoreEvent = 'load' | 'result' | string;
export interface WebPlugin {
name: string,
slotId: WebPluginType,
caption?: string,
} | [key: string]: any,
}
export interface Webcore {
issueQuery(query, options: IssueQueryOptions, callback: (error: any, result: any) => void);
issueQuery(query, callback: (error: any, result: any) => void);
addEventListener(eventName: WebcoreEvent, fn: (...args: any[]) => void);
addResultListener(fn: (result: any, requestTime: number, options: any) => void);
addPluginLoadListener(fn: (plugin: WebPlugin) => void);
emit(eventName: WebcoreEvent, ...args: any[]);
emitSlotSignal(slotDOM: HTMLElement, eventName: WebcoreEvent, data: any);
}
export interface PluginData {
query?: string;
queryProvider?: string[];
results?: SearchPatientResult[];
[att: string]: any;
}
export interface SlotHTMLElement extends HTMLElement {
slotId: string;
pluginName: string;
data?: PluginData;
} |
export interface IssueQueryOptions {
override?: string, | random_line_split |
image_reader.py | from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="",
pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
rescale_h: bool = False,
keep_aspect_ratio: bool = False,
mode: str = 'RGB') -> Callable:
"""Get a reader of images loading them from a list of pahts.
Args:
prefix: Prefix of the paths that are listed in a image files.
pad_w: Width to which the images will be padded/cropped/resized.
pad_h: Height to with the images will be padded/corpped/resized.
rescale_w: If true, image is rescaled to have given width. It is
cropped/padded otherwise.
rescale_h: If true, image is rescaled to have given height. It is
cropped/padded otherwise.
keep_aspect_ratio: Flag whether the aspect ration should be kept during
rescaling. Can only be used if both width and height are rescaled.
mode: Scipy image loading mode, see scipy documentation for more
details.
Returns:
The reader function that takes a list of image paths (relative to
provided prefix) and returns a list of images as numpy arrays of shape
pad_h x pad_w x number of channels.
"""
if not rescale_w and not rescale_h and keep_aspect_ratio:
raise ValueError(
"It does not make sense to keep the aspect ratio while not "
"rescaling the image.")
if rescale_w != rescale_h and not keep_aspect_ratio:
raise ValueError(
"While rescaling only one side, aspect ratio must be kept, "
"was set to false.")
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
|
return load
def imagenet_reader(prefix: str,
target_width: int = 227,
target_height: int = 227) -> Callable:
"""Load and prepare image the same way as Caffe scripts."""
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
"Image file '{}' no. {} does not exist."
.format(path, i + 1))
image = Image.open(path).convert('RGB')
width, height = image.size
if width == height:
_rescale_or_crop(image, target_width, target_height,
True, True, False)
elif height < width:
_rescale_or_crop(
image,
int(width * float(target_height) / height),
target_height, True, True, False)
else:
_rescale_or_crop(
image, target_width,
int(height * float(target_width) / width),
True, True, False)
cropped_image = _crop(image, target_width, target_height)
res = _pad(np.array(cropped_image),
target_width, target_height, 3)
assert res.shape == (target_width, target_height, 3)
yield res
return load
def _rescale_or_crop(image: Image.Image, pad_w: int, pad_h: int,
rescale_w: bool, rescale_h: bool,
keep_aspect_ratio: bool) -> Image.Image:
"""Rescale and/or crop the image based on the rescale configuration."""
orig_w, orig_h = image.size
if orig_w == pad_w and orig_h == pad_h:
return image
if rescale_w and rescale_h and not keep_aspect_ratio:
image.thumbnail((pad_w, pad_h))
elif rescale_w and rescale_h and keep_aspect_ratio:
ratio = min(pad_h / orig_h, pad_w / orig_h)
image.thumbnail((int(orig_w * ratio), int(orig_h * ratio)))
elif rescale_w and not rescale_h:
orig_w, orig_h = image.size
if orig_w != pad_w:
ratio = pad_w / orig_w
image.thumbnail((pad_w, int(orig_h * ratio)))
elif rescale_h and not rescale_w:
orig_w, orig_h = image.size
if orig_h != pad_h:
ratio = pad_h / orig_h
image.thumbnail((int(orig_w * ratio), pad_h))
return _crop(image, pad_w, pad_h)
def _crop(image: Image.Image, pad_w: int, pad_h: int) -> Image.Image:
orig_w, orig_h = image.size
w_shift = max(orig_w - pad_w, 0) // 2
h_shift = max(orig_h - pad_h, 0) // 2
even_w = max(orig_w - pad_w, 0) % 2
even_h = max(orig_h - pad_h, 0) % 2
return image.crop(
(w_shift, h_shift, orig_w - w_shift - even_w,
orig_h - h_shift - even_h))
def _pad(image: np.ndarray, pad_w: int, pad_h: int,
channels: int) -> np.ndarray:
img_h, img_w = image.shape[:2]
image_padded = np.zeros((pad_h, pad_w, channels))
image_padded[:img_h, :img_w, :] = image
return image_padded
| with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
("Image file '{}' no."
"{} does not exist.").format(path, i + 1))
try:
image = Image.open(path).convert(mode)
except IOError:
image = Image.new(mode, (pad_w, pad_h))
image = _rescale_or_crop(image, pad_w, pad_h,
rescale_w, rescale_h,
keep_aspect_ratio)
image_np = np.array(image)
if len(image_np.shape) == 2:
channels = 1
image_np = np.expand_dims(image_np, 2)
elif len(image_np.shape) == 3:
channels = image_np.shape[2]
else:
raise ValueError(
("Image should have either 2 (black and white) "
"or three dimensions (color channels), has {} "
"dimension.").format(len(image_np.shape)))
yield _pad(image_np, pad_w, pad_h, channels) | conditional_block |
image_reader.py | from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="",
pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
rescale_h: bool = False,
keep_aspect_ratio: bool = False,
mode: str = 'RGB') -> Callable:
"""Get a reader of images loading them from a list of pahts.
Args:
prefix: Prefix of the paths that are listed in a image files.
pad_w: Width to which the images will be padded/cropped/resized.
pad_h: Height to with the images will be padded/corpped/resized.
rescale_w: If true, image is rescaled to have given width. It is
cropped/padded otherwise.
rescale_h: If true, image is rescaled to have given height. It is
cropped/padded otherwise.
keep_aspect_ratio: Flag whether the aspect ration should be kept during
rescaling. Can only be used if both width and height are rescaled.
mode: Scipy image loading mode, see scipy documentation for more
details.
Returns:
The reader function that takes a list of image paths (relative to
provided prefix) and returns a list of images as numpy arrays of shape
pad_h x pad_w x number of channels.
"""
if not rescale_w and not rescale_h and keep_aspect_ratio:
raise ValueError(
"It does not make sense to keep the aspect ratio while not "
"rescaling the image.")
if rescale_w != rescale_h and not keep_aspect_ratio:
raise ValueError(
"While rescaling only one side, aspect ratio must be kept, "
"was set to false.")
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
("Image file '{}' no."
"{} does not exist.").format(path, i + 1))
try:
image = Image.open(path).convert(mode)
except IOError:
image = Image.new(mode, (pad_w, pad_h))
image = _rescale_or_crop(image, pad_w, pad_h,
rescale_w, rescale_h,
keep_aspect_ratio)
image_np = np.array(image)
if len(image_np.shape) == 2:
channels = 1
image_np = np.expand_dims(image_np, 2)
elif len(image_np.shape) == 3:
channels = image_np.shape[2]
else:
raise ValueError(
("Image should have either 2 (black and white) "
"or three dimensions (color channels), has {} "
"dimension.").format(len(image_np.shape)))
yield _pad(image_np, pad_w, pad_h, channels)
return load
| target_height: int = 227) -> Callable:
"""Load and prepare image the same way as Caffe scripts."""
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
"Image file '{}' no. {} does not exist."
.format(path, i + 1))
image = Image.open(path).convert('RGB')
width, height = image.size
if width == height:
_rescale_or_crop(image, target_width, target_height,
True, True, False)
elif height < width:
_rescale_or_crop(
image,
int(width * float(target_height) / height),
target_height, True, True, False)
else:
_rescale_or_crop(
image, target_width,
int(height * float(target_width) / width),
True, True, False)
cropped_image = _crop(image, target_width, target_height)
res = _pad(np.array(cropped_image),
target_width, target_height, 3)
assert res.shape == (target_width, target_height, 3)
yield res
return load
def _rescale_or_crop(image: Image.Image, pad_w: int, pad_h: int,
rescale_w: bool, rescale_h: bool,
keep_aspect_ratio: bool) -> Image.Image:
"""Rescale and/or crop the image based on the rescale configuration."""
orig_w, orig_h = image.size
if orig_w == pad_w and orig_h == pad_h:
return image
if rescale_w and rescale_h and not keep_aspect_ratio:
image.thumbnail((pad_w, pad_h))
elif rescale_w and rescale_h and keep_aspect_ratio:
ratio = min(pad_h / orig_h, pad_w / orig_h)
image.thumbnail((int(orig_w * ratio), int(orig_h * ratio)))
elif rescale_w and not rescale_h:
orig_w, orig_h = image.size
if orig_w != pad_w:
ratio = pad_w / orig_w
image.thumbnail((pad_w, int(orig_h * ratio)))
elif rescale_h and not rescale_w:
orig_w, orig_h = image.size
if orig_h != pad_h:
ratio = pad_h / orig_h
image.thumbnail((int(orig_w * ratio), pad_h))
return _crop(image, pad_w, pad_h)
def _crop(image: Image.Image, pad_w: int, pad_h: int) -> Image.Image:
orig_w, orig_h = image.size
w_shift = max(orig_w - pad_w, 0) // 2
h_shift = max(orig_h - pad_h, 0) // 2
even_w = max(orig_w - pad_w, 0) % 2
even_h = max(orig_h - pad_h, 0) % 2
return image.crop(
(w_shift, h_shift, orig_w - w_shift - even_w,
orig_h - h_shift - even_h))
def _pad(image: np.ndarray, pad_w: int, pad_h: int,
channels: int) -> np.ndarray:
img_h, img_w = image.shape[:2]
image_padded = np.zeros((pad_h, pad_w, channels))
image_padded[:img_h, :img_w, :] = image
return image_padded |
def imagenet_reader(prefix: str,
target_width: int = 227, | random_line_split |
image_reader.py | from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="",
pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
rescale_h: bool = False,
keep_aspect_ratio: bool = False,
mode: str = 'RGB') -> Callable:
"""Get a reader of images loading them from a list of pahts.
Args:
prefix: Prefix of the paths that are listed in a image files.
pad_w: Width to which the images will be padded/cropped/resized.
pad_h: Height to with the images will be padded/corpped/resized.
rescale_w: If true, image is rescaled to have given width. It is
cropped/padded otherwise.
rescale_h: If true, image is rescaled to have given height. It is
cropped/padded otherwise.
keep_aspect_ratio: Flag whether the aspect ration should be kept during
rescaling. Can only be used if both width and height are rescaled.
mode: Scipy image loading mode, see scipy documentation for more
details.
Returns:
The reader function that takes a list of image paths (relative to
provided prefix) and returns a list of images as numpy arrays of shape
pad_h x pad_w x number of channels.
"""
if not rescale_w and not rescale_h and keep_aspect_ratio:
raise ValueError(
"It does not make sense to keep the aspect ratio while not "
"rescaling the image.")
if rescale_w != rescale_h and not keep_aspect_ratio:
raise ValueError(
"While rescaling only one side, aspect ratio must be kept, "
"was set to false.")
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
("Image file '{}' no."
"{} does not exist.").format(path, i + 1))
try:
image = Image.open(path).convert(mode)
except IOError:
image = Image.new(mode, (pad_w, pad_h))
image = _rescale_or_crop(image, pad_w, pad_h,
rescale_w, rescale_h,
keep_aspect_ratio)
image_np = np.array(image)
if len(image_np.shape) == 2:
channels = 1
image_np = np.expand_dims(image_np, 2)
elif len(image_np.shape) == 3:
channels = image_np.shape[2]
else:
raise ValueError(
("Image should have either 2 (black and white) "
"or three dimensions (color channels), has {} "
"dimension.").format(len(image_np.shape)))
yield _pad(image_np, pad_w, pad_h, channels)
return load
def imagenet_reader(prefix: str,
target_width: int = 227,
target_height: int = 227) -> Callable:
"""Load and prepare image the same way as Caffe scripts."""
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
"Image file '{}' no. {} does not exist."
.format(path, i + 1))
image = Image.open(path).convert('RGB')
width, height = image.size
if width == height:
_rescale_or_crop(image, target_width, target_height,
True, True, False)
elif height < width:
_rescale_or_crop(
image,
int(width * float(target_height) / height),
target_height, True, True, False)
else:
_rescale_or_crop(
image, target_width,
int(height * float(target_width) / width),
True, True, False)
cropped_image = _crop(image, target_width, target_height)
res = _pad(np.array(cropped_image),
target_width, target_height, 3)
assert res.shape == (target_width, target_height, 3)
yield res
return load
def _rescale_or_crop(image: Image.Image, pad_w: int, pad_h: int,
rescale_w: bool, rescale_h: bool,
keep_aspect_ratio: bool) -> Image.Image:
"""Rescale and/or crop the image based on the rescale configuration."""
orig_w, orig_h = image.size
if orig_w == pad_w and orig_h == pad_h:
return image
if rescale_w and rescale_h and not keep_aspect_ratio:
image.thumbnail((pad_w, pad_h))
elif rescale_w and rescale_h and keep_aspect_ratio:
ratio = min(pad_h / orig_h, pad_w / orig_h)
image.thumbnail((int(orig_w * ratio), int(orig_h * ratio)))
elif rescale_w and not rescale_h:
orig_w, orig_h = image.size
if orig_w != pad_w:
ratio = pad_w / orig_w
image.thumbnail((pad_w, int(orig_h * ratio)))
elif rescale_h and not rescale_w:
orig_w, orig_h = image.size
if orig_h != pad_h:
ratio = pad_h / orig_h
image.thumbnail((int(orig_w * ratio), pad_h))
return _crop(image, pad_w, pad_h)
def _crop(image: Image.Image, pad_w: int, pad_h: int) -> Image.Image:
orig_w, orig_h = image.size
w_shift = max(orig_w - pad_w, 0) // 2
h_shift = max(orig_h - pad_h, 0) // 2
even_w = max(orig_w - pad_w, 0) % 2
even_h = max(orig_h - pad_h, 0) % 2
return image.crop(
(w_shift, h_shift, orig_w - w_shift - even_w,
orig_h - h_shift - even_h))
def _pad(image: np.ndarray, pad_w: int, pad_h: int,
channels: int) -> np.ndarray:
| img_h, img_w = image.shape[:2]
image_padded = np.zeros((pad_h, pad_w, channels))
image_padded[:img_h, :img_w, :] = image
return image_padded | identifier_body | |
image_reader.py | from typing import Callable, Iterable, List, Optional
import os
import numpy as np
from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
def image_reader(prefix="",
pad_w: Optional[int] = None,
pad_h: Optional[int] = None,
rescale_w: bool = False,
rescale_h: bool = False,
keep_aspect_ratio: bool = False,
mode: str = 'RGB') -> Callable:
"""Get a reader of images loading them from a list of pahts.
Args:
prefix: Prefix of the paths that are listed in a image files.
pad_w: Width to which the images will be padded/cropped/resized.
pad_h: Height to with the images will be padded/corpped/resized.
rescale_w: If true, image is rescaled to have given width. It is
cropped/padded otherwise.
rescale_h: If true, image is rescaled to have given height. It is
cropped/padded otherwise.
keep_aspect_ratio: Flag whether the aspect ration should be kept during
rescaling. Can only be used if both width and height are rescaled.
mode: Scipy image loading mode, see scipy documentation for more
details.
Returns:
The reader function that takes a list of image paths (relative to
provided prefix) and returns a list of images as numpy arrays of shape
pad_h x pad_w x number of channels.
"""
if not rescale_w and not rescale_h and keep_aspect_ratio:
raise ValueError(
"It does not make sense to keep the aspect ratio while not "
"rescaling the image.")
if rescale_w != rescale_h and not keep_aspect_ratio:
raise ValueError(
"While rescaling only one side, aspect ratio must be kept, "
"was set to false.")
def | (list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
("Image file '{}' no."
"{} does not exist.").format(path, i + 1))
try:
image = Image.open(path).convert(mode)
except IOError:
image = Image.new(mode, (pad_w, pad_h))
image = _rescale_or_crop(image, pad_w, pad_h,
rescale_w, rescale_h,
keep_aspect_ratio)
image_np = np.array(image)
if len(image_np.shape) == 2:
channels = 1
image_np = np.expand_dims(image_np, 2)
elif len(image_np.shape) == 3:
channels = image_np.shape[2]
else:
raise ValueError(
("Image should have either 2 (black and white) "
"or three dimensions (color channels), has {} "
"dimension.").format(len(image_np.shape)))
yield _pad(image_np, pad_w, pad_h, channels)
return load
def imagenet_reader(prefix: str,
target_width: int = 227,
target_height: int = 227) -> Callable:
"""Load and prepare image the same way as Caffe scripts."""
def load(list_files: List[str]) -> Iterable[np.ndarray]:
for list_file in list_files:
with open(list_file) as f_list:
for i, image_file in enumerate(f_list):
path = os.path.join(prefix, image_file.rstrip())
if not os.path.exists(path):
raise Exception(
"Image file '{}' no. {} does not exist."
.format(path, i + 1))
image = Image.open(path).convert('RGB')
width, height = image.size
if width == height:
_rescale_or_crop(image, target_width, target_height,
True, True, False)
elif height < width:
_rescale_or_crop(
image,
int(width * float(target_height) / height),
target_height, True, True, False)
else:
_rescale_or_crop(
image, target_width,
int(height * float(target_width) / width),
True, True, False)
cropped_image = _crop(image, target_width, target_height)
res = _pad(np.array(cropped_image),
target_width, target_height, 3)
assert res.shape == (target_width, target_height, 3)
yield res
return load
def _rescale_or_crop(image: Image.Image, pad_w: int, pad_h: int,
rescale_w: bool, rescale_h: bool,
keep_aspect_ratio: bool) -> Image.Image:
"""Rescale and/or crop the image based on the rescale configuration."""
orig_w, orig_h = image.size
if orig_w == pad_w and orig_h == pad_h:
return image
if rescale_w and rescale_h and not keep_aspect_ratio:
image.thumbnail((pad_w, pad_h))
elif rescale_w and rescale_h and keep_aspect_ratio:
ratio = min(pad_h / orig_h, pad_w / orig_h)
image.thumbnail((int(orig_w * ratio), int(orig_h * ratio)))
elif rescale_w and not rescale_h:
orig_w, orig_h = image.size
if orig_w != pad_w:
ratio = pad_w / orig_w
image.thumbnail((pad_w, int(orig_h * ratio)))
elif rescale_h and not rescale_w:
orig_w, orig_h = image.size
if orig_h != pad_h:
ratio = pad_h / orig_h
image.thumbnail((int(orig_w * ratio), pad_h))
return _crop(image, pad_w, pad_h)
def _crop(image: Image.Image, pad_w: int, pad_h: int) -> Image.Image:
orig_w, orig_h = image.size
w_shift = max(orig_w - pad_w, 0) // 2
h_shift = max(orig_h - pad_h, 0) // 2
even_w = max(orig_w - pad_w, 0) % 2
even_h = max(orig_h - pad_h, 0) % 2
return image.crop(
(w_shift, h_shift, orig_w - w_shift - even_w,
orig_h - h_shift - even_h))
def _pad(image: np.ndarray, pad_w: int, pad_h: int,
channels: int) -> np.ndarray:
img_h, img_w = image.shape[:2]
image_padded = np.zeros((pad_h, pad_w, channels))
image_padded[:img_h, :img_w, :] = image
return image_padded
| load | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.7@@
from __future__ import unicode_literals
from datetime import datetime
import logging
from types import NoneType
from google.appengine.ext import ndb, deferred, db
from google.appengine.ext.ndb.query import Cursor
from typing import Optional, List, Union, Tuple
from mcfw.rpc import returns, arguments
from rogerthat.bizz.communities.communities import get_community
from rogerthat.bizz.jobs.matching import rebuild_matches_check_current
from rogerthat.bizz.jobs.notifications import calculate_next_reminder
from rogerthat.bizz.jobs.translations import localize as localize_jobs
from rogerthat.capi.jobs import newJobs
from rogerthat.consts import JOBS_WORKER_QUEUE
from rogerthat.dal.mobile import get_mobile_key_by_account
from rogerthat.dal.profile import get_user_profile
from rogerthat.models import NdbUserProfile
from rogerthat.models.jobs import JobOffer, JobMatchingCriteria, JobMatchingCriteriaNotifications, JobMatch, \
JobMatchStatus, JobNotificationSchedule, JobOfferSourceType
from rogerthat.rpc import users
from rogerthat.rpc.models import RpcCAPICall, RpcException
from rogerthat.rpc.rpc import mapping, logError, CAPI_KEYWORD_ARG_PRIORITY, \
PRIORITY_HIGH
from rogerthat.service.api.messaging import add_chat_members
from rogerthat.to.jobs import GetJobsResponseTO, JobOfferTO, NewJobsResponseTO, \
NewJobsRequestTO, SaveJobsCriteriaResponseTO, GetJobsCriteriaResponseTO, \
JobKeyLabelTO, JobCriteriaLocationTO, JobCriteriaNotificationsTO, JobCriteriaGeoLocationTO, \
SaveJobsCriteriaRequestTO, JobOfferChatActionTO, JobOfferOpenActionTO, GetJobChatInfoResponseTO, JobChatAnonymousTO, \
CreateJobChatResponseTO, CreateJobChatRequestTO, JobsInfoTO, JobOfferProviderTO
from rogerthat.translations import localize
from rogerthat.utils import now, get_epoch_from_datetime
from rogerthat.utils.location import coordinates_to_city
from solutions.common.jobs.models import JobSolicitation
TAG_JOB_CHAT = '__rt__.jobs_chat'
CONTRACT_TYPES = [
'contract_type_001',
'contract_type_002',
'contract_type_003',
'contract_type_004',
'contract_type_005',
'contract_type_006',
'contract_type_007',
]
JOB_DOMAINS = [
'job_domain_001',
'job_domain_002',
'job_domain_003',
'job_domain_004',
'job_domain_005',
'job_domain_006',
'job_domain_007',
'job_domain_008',
'job_domain_009',
'job_domain_010',
'job_domain_011',
'job_domain_012',
'job_domain_013',
'job_domain_014',
'job_domain_015',
'job_domain_016',
'job_domain_017',
'job_domain_018',
'job_domain_019',
'job_domain_020',
'job_domain_021',
'job_domain_022',
'job_domain_023',
'job_domain_024',
]
def get_job_criteria(app_user):
# type: (users.User) -> GetJobsCriteriaResponseTO
user_profile = get_user_profile(app_user)
response = GetJobsCriteriaResponseTO()
response.location = JobCriteriaLocationTO()
response.location.address = None
response.location.geo = None
response.location.distance = 20000 # 20 Km
response.contract_types = []
response.job_domains = []
response.keywords = []
response.notifications = JobCriteriaNotificationsTO()
response.notifications.timezone = None
response.notifications.how_often = JobNotificationSchedule.NEVER
response.notifications.delivery_day = 'monday'
response.notifications.delivery_time = 64800 # 18:00
job_criteria = JobMatchingCriteria.create_key(app_user).get() # type: JobMatchingCriteria
for contract_type in CONTRACT_TYPES:
to = JobKeyLabelTO()
to.key = contract_type
to.label = localize_jobs(user_profile.language, contract_type)
to.enabled = contract_type in job_criteria.contract_types if job_criteria else False
response.contract_types.append(to)
response.contract_types.sort(key=lambda item: item.label)
for domain in JOB_DOMAINS:
to = JobKeyLabelTO()
to.key = domain
to.label = localize_jobs(user_profile.language, domain)
to.enabled = domain in job_criteria.job_domains if job_criteria else False
response.job_domains.append(to)
response.job_domains.sort(key=lambda item: item.label)
if job_criteria:
response.active = job_criteria.active
response.location = JobCriteriaLocationTO()
response.location.address = job_criteria.address
response.location.geo = JobCriteriaGeoLocationTO()
response.location.geo.latitude = job_criteria.geo_location.lat
response.location.geo.longitude = job_criteria.geo_location.lon
response.location.distance = job_criteria.distance
response.keywords = job_criteria.keywords
if job_criteria.notifications:
response.notifications.how_often = job_criteria.notifications.how_often
if job_criteria.notifications.delivery_day:
response.notifications.delivery_day = job_criteria.notifications.delivery_day
if job_criteria.notifications.delivery_time:
response.notifications.delivery_time = job_criteria.notifications.delivery_time
else:
response.active = True # user first usage
return response
@returns(SaveJobsCriteriaResponseTO)
@arguments(app_user=users.User, request=SaveJobsCriteriaRequestTO)
def save_job_criteria(app_user, request):
# type: (users.User, SaveJobsCriteriaRequestTO) -> SaveJobsCriteriaResponseTO
job_criteria_key = JobMatchingCriteria.create_key(app_user)
job_criteria = job_criteria_key.get() # type: JobMatchingCriteria
new_job_profile = not job_criteria
if new_job_profile:
if not request.criteria:
return SaveJobsCriteriaResponseTO(active=False, new_profile=new_job_profile)
job_criteria = JobMatchingCriteria(key=job_criteria_key)
job_criteria.last_load_request = datetime.utcnow()
job_criteria.demo = get_community(get_user_profile(app_user).community_id).demo
original_job_criteria = None
else:
original_job_criteria = job_criteria.to_dict(exclude=['notifications', 'active'])
notifications = None
job_criteria.active = request.active
if request.criteria:
location = request.criteria.location
notifications = request.criteria.notifications
if location.geo:
job_criteria.geo_location = ndb.GeoPt(location.geo.latitude, location.geo.longitude)
if location.address:
job_criteria.address = location.address
else:
job_criteria.address = coordinates_to_city(job_criteria.geo_location.lat,
job_criteria.geo_location.lon)
job_criteria.distance = location.distance
job_criteria.contract_types = sorted(request.criteria.contract_types)
job_criteria.job_domains = sorted(request.criteria.job_domains)
job_criteria.keywords = sorted(request.criteria.keywords)
if not job_criteria.job_domains:
raise RpcException('at_least_one_job_domain_required', app_user)
if not job_criteria.contract_types:
raise RpcException('at_least_one_contract_type_required', app_user)
updated_criteria = job_criteria.to_dict(exclude=['notifications', 'active'])
should_build_matches = original_job_criteria != updated_criteria
should_calculate_reminder = should_build_matches
should_clear_notifications = should_build_matches
og_notifications = job_criteria.notifications and job_criteria.notifications.to_dict()
if not job_criteria.notifications:
job_criteria.notifications = JobMatchingCriteriaNotifications()
job_criteria.notifications.how_often = JobNotificationSchedule.NEVER
if notifications and notifications.timezone:
job_criteria.notifications.timezone = notifications.timezone
if job_criteria.notifications.how_often != notifications.how_often:
delayed_notification_types = (JobNotificationSchedule.AT_MOST_ONCE_A_DAY,
JobNotificationSchedule.AT_MOST_ONCE_A_WEEK)
if job_criteria.notifications.how_often in delayed_notification_types and \
notifications.how_often not in delayed_notification_types:
should_clear_notifications = True
job_criteria.notifications.how_often = notifications.how_often
job_criteria.notifications.delivery_day = notifications.delivery_day
job_criteria.notifications.delivery_time = notifications.delivery_time
if not should_calculate_reminder:
should_calculate_reminder = job_criteria.notifications.to_dict() != og_notifications
job_criteria.put()
if should_build_matches:
deferred.defer(rebuild_matches_check_current, app_user, _queue=JOBS_WORKER_QUEUE)
if should_calculate_reminder:
deferred.defer(calculate_next_reminder, app_user, should_clear_notifications, _queue=JOBS_WORKER_QUEUE)
return SaveJobsCriteriaResponseTO(active=job_criteria.active, new_profile=new_job_profile)
def get_oca_logo_url(language):
if language.startswith('nl'):
return 'https://storage.googleapis.com/oca-files/jobs/OCA-nl.png'
return 'https://storage.googleapis.com/oca-files/jobs/OCA.png'
def get_jobs_for_activity_type(app_user, activity_type, cursor, ids):
# type: (users.User, unicode, Optional[unicode], List[int]) -> GetJobsResponseTO
job_criteria_key = JobMatchingCriteria.create_key(app_user)
user_profile_key = NdbUserProfile.createKey(app_user)
keys = [job_criteria_key, user_profile_key]
job_criteria, user_profile = ndb.get_multi(keys) # type: Optional[JobMatchingCriteria], NdbUserProfile
resp = GetJobsResponseTO()
if not job_criteria or not job_criteria.active:
resp.is_profile_active = False
resp.items = []
resp.cursor = None
resp.has_more = False
else:
if cursor is None and activity_type == JobOfferTO.ACTIVITY_TYPE_NEW:
job_criteria.last_load_request = datetime.utcnow()
job_criteria.put()
resp.items, resp.cursor, resp.has_more = _get_jobs(activity_type, app_user, cursor, user_profile.language, ids)
resp.is_profile_active = True
info = JobsInfoTO()
info.title = localize(user_profile.language, 'app_jobs_title')
info.description = localize(user_profile.language, 'app_jobs_description')
info.providers = [
JobOfferProviderTO(image_url=get_oca_logo_url(user_profile.language)),
JobOfferProviderTO(image_url='https://storage.googleapis.com/oca-files/jobs/VDAB.jpg'),
]
resp.info = info
return resp
def bulk_save_jobs(app_user, job_ids, status):
# type: (users.User, List[int], int) -> List[int]
keys = [JobMatch.create_key(app_user, job_id) for job_id in job_ids]
matches = ndb.get_multi(keys) # type: List[JobMatch]
to_put = []
for match in matches:
if not match:
continue
match.status = status
to_put.append(match)
ndb.put_multi(to_put)
return [match.get_job_id() for match in to_put]
@mapping('com.mobicage.capi.jobs.new_jobs_response_handler')
@returns(NoneType)
@arguments(context=RpcCAPICall, result=NewJobsResponseTO)
def | (context, result):
pass
def _get_jobs(activity_type, app_user, cursor, language, ids):
# type: (str, users.User, Optional[str], str, List[int]) -> Tuple[List[JobOfferTO], Optional[str], bool]
fetch_size = 20
start_cursor = Cursor.from_websafe_string(cursor) if cursor else None
if activity_type == JobOfferTO.ACTIVITY_TYPE_NEW:
qry = JobMatch.list_new_by_app_user(app_user)
elif activity_type == JobOfferTO.ACTIVITY_TYPE_HISTORY:
qry = JobMatch.list_by_app_user_and_status(app_user, JobMatchStatus.DELETED)
elif activity_type == JobOfferTO.ACTIVITY_TYPE_STARRED:
qry = JobMatch.list_by_app_user_and_status(app_user, JobMatchStatus.STARRED)
else:
raise Exception('Unknown activity type %s' % activity_type)
job_matches_keys, new_cursor, has_more = qry.fetch_page(
fetch_size, start_cursor=start_cursor, keys_only=True) # type: List[ndb.Key], Cursor, bool
match_keys = [JobMatch.create_key(app_user, job_id) for job_id in ids if job_id] + \
[key for key in job_matches_keys if key.id() not in ids]
offer_keys = [JobOffer.create_key(match_key.id()) for match_key in match_keys]
models = ndb.get_multi(match_keys + offer_keys) # type: List[Union[JobMatch, JobOffer]]
job_matches = models[0: len(models) / 2]
job_offers = models[len(models) / 2:]
items = []
to_put = []
for match, job_offer in zip(job_matches, job_offers): # type: JobMatch, JobOffer
if not match:
# this should only happen when the job was requested using the 'ids' property
# like when the jobs activity is opened via a button on a news item
if job_offer.id not in ids:
logging.warning('Expected JobMatch to exist, creating it anyway...')
logging.debug('Creating manual JobMatch entry for job %d', job_offer.id)
match = JobMatch.manually_create(app_user, job_offer.id)
to_put.append(match)
timestamp = get_epoch_from_datetime(match.update_date)
items.append(JobOfferTO.from_job_offer(job_offer, timestamp, language,
get_job_offer_actions(job_offer, match, language)))
ndb.put_multi(to_put)
return items, new_cursor.to_websafe_string().decode('utf-8') if new_cursor else None, has_more
def get_job_offer_actions(job_offer, match, language):
# type: (JobOffer, JobMatch, str) -> List[Union[JobOfferChatActionTO, JobOfferOpenActionTO]]
actions = []
if job_offer.source.type == JobOfferSourceType.OCA:
action = JobOfferChatActionTO()
action.label = localize(language, 'open_chat')
action.chat_key = match.chat_key # possibly None
action.icon = 'fa-comment'
actions.append(action)
return actions
def send_new_jobs_for_activity_types(app_user, activity_types):
user_profile = get_user_profile(app_user)
if not user_profile.get_mobiles():
return
request = NewJobsRequestTO()
request.creation_time = now()
request.activity_types = activity_types
mobiles = db.get([get_mobile_key_by_account(mobile_detail.account) for mobile_detail in user_profile.get_mobiles().values()])
for mobile in mobiles:
ios_push_id = None
if mobile.is_ios:
ios_push_id = mobile.iOSPushId
kwargs = {}
if ios_push_id:
kwargs[CAPI_KEYWORD_ARG_PRIORITY] = PRIORITY_HIGH
newJobs(new_jobs_response_handler, logError, app_user, request=request, MOBILE_ACCOUNT=mobile, **kwargs)
def get_job_chat_info(app_user, job_id):
# type: (users.User, int) -> GetJobChatInfoResponseTO
keys = [JobOffer.create_key(job_id), JobMatch.create_key(app_user, job_id)]
job_offer, job_match = ndb.get_multi(keys) # type: JobOffer, JobMatch
job_sln_id = long(job_offer.source.id)
solicitation = JobSolicitation.list_by_job_and_user(users.User(job_offer.service_email),
job_sln_id,
app_user.email()).get() # type: Optional[JobSolicitation]
lang = get_user_profile(app_user).language
response = GetJobChatInfoResponseTO()
response.anonymous = JobChatAnonymousTO()
response.job_id = job_id
response.anonymous.enabled = True
response.anonymous.default_value = False
response.default_text = ''
response.info_text = localize(lang, 'job_info_text')
if solicitation:
# User has already applied before, but deleted the chat.
# Add him back to the chat and return the original chat key.
job_match.chat_key = solicitation.chat_key
response.chat_key = solicitation.chat_key
with users.set_user(users.User(job_offer.service_email)):
add_chat_members(solicitation.chat_key, [app_user.email()])
job_match.put()
return response
def create_job_chat(app_user, request):
# type: (users.User, CreateJobChatRequestTO) -> CreateJobChatResponseTO
keys = [JobMatch.create_key(app_user, request.job_id),
JobOffer.create_key(request.job_id)]
job_match, job_offer = ndb.get_multi(keys) # type: JobMatch, JobOffer
if not job_match.chat_key:
# If you ever want to create a separate service for jobs, you'll have to create a service api callback for this
from solutions.common.jobs.solicitations import create_job_solicitation
message_key = create_job_solicitation(app_user, job_offer, request)
job_match.chat_key = message_key
job_match.put()
response = CreateJobChatResponseTO()
response.message_key = job_match.chat_key
return response
| new_jobs_response_handler | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.7@@
from __future__ import unicode_literals
from datetime import datetime
import logging
from types import NoneType
from google.appengine.ext import ndb, deferred, db
from google.appengine.ext.ndb.query import Cursor
from typing import Optional, List, Union, Tuple
from mcfw.rpc import returns, arguments
from rogerthat.bizz.communities.communities import get_community
from rogerthat.bizz.jobs.matching import rebuild_matches_check_current
from rogerthat.bizz.jobs.notifications import calculate_next_reminder
from rogerthat.bizz.jobs.translations import localize as localize_jobs
from rogerthat.capi.jobs import newJobs
from rogerthat.consts import JOBS_WORKER_QUEUE
from rogerthat.dal.mobile import get_mobile_key_by_account
from rogerthat.dal.profile import get_user_profile
from rogerthat.models import NdbUserProfile
from rogerthat.models.jobs import JobOffer, JobMatchingCriteria, JobMatchingCriteriaNotifications, JobMatch, \
JobMatchStatus, JobNotificationSchedule, JobOfferSourceType
from rogerthat.rpc import users
from rogerthat.rpc.models import RpcCAPICall, RpcException
from rogerthat.rpc.rpc import mapping, logError, CAPI_KEYWORD_ARG_PRIORITY, \
PRIORITY_HIGH
from rogerthat.service.api.messaging import add_chat_members
from rogerthat.to.jobs import GetJobsResponseTO, JobOfferTO, NewJobsResponseTO, \
NewJobsRequestTO, SaveJobsCriteriaResponseTO, GetJobsCriteriaResponseTO, \
JobKeyLabelTO, JobCriteriaLocationTO, JobCriteriaNotificationsTO, JobCriteriaGeoLocationTO, \
SaveJobsCriteriaRequestTO, JobOfferChatActionTO, JobOfferOpenActionTO, GetJobChatInfoResponseTO, JobChatAnonymousTO, \
CreateJobChatResponseTO, CreateJobChatRequestTO, JobsInfoTO, JobOfferProviderTO
from rogerthat.translations import localize
from rogerthat.utils import now, get_epoch_from_datetime
from rogerthat.utils.location import coordinates_to_city
from solutions.common.jobs.models import JobSolicitation
TAG_JOB_CHAT = '__rt__.jobs_chat'
CONTRACT_TYPES = [
'contract_type_001',
'contract_type_002',
'contract_type_003',
'contract_type_004',
'contract_type_005',
'contract_type_006',
'contract_type_007',
]
JOB_DOMAINS = [
'job_domain_001',
'job_domain_002',
'job_domain_003',
'job_domain_004',
'job_domain_005',
'job_domain_006',
'job_domain_007',
'job_domain_008',
'job_domain_009',
'job_domain_010',
'job_domain_011',
'job_domain_012',
'job_domain_013',
'job_domain_014',
'job_domain_015',
'job_domain_016',
'job_domain_017',
'job_domain_018',
'job_domain_019',
'job_domain_020',
'job_domain_021',
'job_domain_022',
'job_domain_023',
'job_domain_024',
]
def get_job_criteria(app_user):
# type: (users.User) -> GetJobsCriteriaResponseTO
user_profile = get_user_profile(app_user)
response = GetJobsCriteriaResponseTO()
response.location = JobCriteriaLocationTO()
response.location.address = None
response.location.geo = None
response.location.distance = 20000 # 20 Km
response.contract_types = []
response.job_domains = []
response.keywords = []
response.notifications = JobCriteriaNotificationsTO()
response.notifications.timezone = None
response.notifications.how_often = JobNotificationSchedule.NEVER
response.notifications.delivery_day = 'monday'
response.notifications.delivery_time = 64800 # 18:00
job_criteria = JobMatchingCriteria.create_key(app_user).get() # type: JobMatchingCriteria
for contract_type in CONTRACT_TYPES:
to = JobKeyLabelTO()
to.key = contract_type
to.label = localize_jobs(user_profile.language, contract_type)
to.enabled = contract_type in job_criteria.contract_types if job_criteria else False
response.contract_types.append(to)
response.contract_types.sort(key=lambda item: item.label)
for domain in JOB_DOMAINS: | response.job_domains.sort(key=lambda item: item.label)
if job_criteria:
response.active = job_criteria.active
response.location = JobCriteriaLocationTO()
response.location.address = job_criteria.address
response.location.geo = JobCriteriaGeoLocationTO()
response.location.geo.latitude = job_criteria.geo_location.lat
response.location.geo.longitude = job_criteria.geo_location.lon
response.location.distance = job_criteria.distance
response.keywords = job_criteria.keywords
if job_criteria.notifications:
response.notifications.how_often = job_criteria.notifications.how_often
if job_criteria.notifications.delivery_day:
response.notifications.delivery_day = job_criteria.notifications.delivery_day
if job_criteria.notifications.delivery_time:
response.notifications.delivery_time = job_criteria.notifications.delivery_time
else:
response.active = True # user first usage
return response
@returns(SaveJobsCriteriaResponseTO)
@arguments(app_user=users.User, request=SaveJobsCriteriaRequestTO)
def save_job_criteria(app_user, request):
# type: (users.User, SaveJobsCriteriaRequestTO) -> SaveJobsCriteriaResponseTO
job_criteria_key = JobMatchingCriteria.create_key(app_user)
job_criteria = job_criteria_key.get() # type: JobMatchingCriteria
new_job_profile = not job_criteria
if new_job_profile:
if not request.criteria:
return SaveJobsCriteriaResponseTO(active=False, new_profile=new_job_profile)
job_criteria = JobMatchingCriteria(key=job_criteria_key)
job_criteria.last_load_request = datetime.utcnow()
job_criteria.demo = get_community(get_user_profile(app_user).community_id).demo
original_job_criteria = None
else:
original_job_criteria = job_criteria.to_dict(exclude=['notifications', 'active'])
notifications = None
job_criteria.active = request.active
if request.criteria:
location = request.criteria.location
notifications = request.criteria.notifications
if location.geo:
job_criteria.geo_location = ndb.GeoPt(location.geo.latitude, location.geo.longitude)
if location.address:
job_criteria.address = location.address
else:
job_criteria.address = coordinates_to_city(job_criteria.geo_location.lat,
job_criteria.geo_location.lon)
job_criteria.distance = location.distance
job_criteria.contract_types = sorted(request.criteria.contract_types)
job_criteria.job_domains = sorted(request.criteria.job_domains)
job_criteria.keywords = sorted(request.criteria.keywords)
if not job_criteria.job_domains:
raise RpcException('at_least_one_job_domain_required', app_user)
if not job_criteria.contract_types:
raise RpcException('at_least_one_contract_type_required', app_user)
updated_criteria = job_criteria.to_dict(exclude=['notifications', 'active'])
should_build_matches = original_job_criteria != updated_criteria
should_calculate_reminder = should_build_matches
should_clear_notifications = should_build_matches
og_notifications = job_criteria.notifications and job_criteria.notifications.to_dict()
if not job_criteria.notifications:
job_criteria.notifications = JobMatchingCriteriaNotifications()
job_criteria.notifications.how_often = JobNotificationSchedule.NEVER
if notifications and notifications.timezone:
job_criteria.notifications.timezone = notifications.timezone
if job_criteria.notifications.how_often != notifications.how_often:
delayed_notification_types = (JobNotificationSchedule.AT_MOST_ONCE_A_DAY,
JobNotificationSchedule.AT_MOST_ONCE_A_WEEK)
if job_criteria.notifications.how_often in delayed_notification_types and \
notifications.how_often not in delayed_notification_types:
should_clear_notifications = True
job_criteria.notifications.how_often = notifications.how_often
job_criteria.notifications.delivery_day = notifications.delivery_day
job_criteria.notifications.delivery_time = notifications.delivery_time
if not should_calculate_reminder:
should_calculate_reminder = job_criteria.notifications.to_dict() != og_notifications
job_criteria.put()
if should_build_matches:
deferred.defer(rebuild_matches_check_current, app_user, _queue=JOBS_WORKER_QUEUE)
if should_calculate_reminder:
deferred.defer(calculate_next_reminder, app_user, should_clear_notifications, _queue=JOBS_WORKER_QUEUE)
return SaveJobsCriteriaResponseTO(active=job_criteria.active, new_profile=new_job_profile)
def get_oca_logo_url(language):
if language.startswith('nl'):
return 'https://storage.googleapis.com/oca-files/jobs/OCA-nl.png'
return 'https://storage.googleapis.com/oca-files/jobs/OCA.png'
def get_jobs_for_activity_type(app_user, activity_type, cursor, ids):
# type: (users.User, unicode, Optional[unicode], List[int]) -> GetJobsResponseTO
job_criteria_key = JobMatchingCriteria.create_key(app_user)
user_profile_key = NdbUserProfile.createKey(app_user)
keys = [job_criteria_key, user_profile_key]
job_criteria, user_profile = ndb.get_multi(keys) # type: Optional[JobMatchingCriteria], NdbUserProfile
resp = GetJobsResponseTO()
if not job_criteria or not job_criteria.active:
resp.is_profile_active = False
resp.items = []
resp.cursor = None
resp.has_more = False
else:
if cursor is None and activity_type == JobOfferTO.ACTIVITY_TYPE_NEW:
job_criteria.last_load_request = datetime.utcnow()
job_criteria.put()
resp.items, resp.cursor, resp.has_more = _get_jobs(activity_type, app_user, cursor, user_profile.language, ids)
resp.is_profile_active = True
info = JobsInfoTO()
info.title = localize(user_profile.language, 'app_jobs_title')
info.description = localize(user_profile.language, 'app_jobs_description')
info.providers = [
JobOfferProviderTO(image_url=get_oca_logo_url(user_profile.language)),
JobOfferProviderTO(image_url='https://storage.googleapis.com/oca-files/jobs/VDAB.jpg'),
]
resp.info = info
return resp
def bulk_save_jobs(app_user, job_ids, status):
# type: (users.User, List[int], int) -> List[int]
keys = [JobMatch.create_key(app_user, job_id) for job_id in job_ids]
matches = ndb.get_multi(keys) # type: List[JobMatch]
to_put = []
for match in matches:
if not match:
continue
match.status = status
to_put.append(match)
ndb.put_multi(to_put)
return [match.get_job_id() for match in to_put]
@mapping('com.mobicage.capi.jobs.new_jobs_response_handler')
@returns(NoneType)
@arguments(context=RpcCAPICall, result=NewJobsResponseTO)
def new_jobs_response_handler(context, result):
pass
def _get_jobs(activity_type, app_user, cursor, language, ids):
# type: (str, users.User, Optional[str], str, List[int]) -> Tuple[List[JobOfferTO], Optional[str], bool]
fetch_size = 20
start_cursor = Cursor.from_websafe_string(cursor) if cursor else None
if activity_type == JobOfferTO.ACTIVITY_TYPE_NEW:
qry = JobMatch.list_new_by_app_user(app_user)
elif activity_type == JobOfferTO.ACTIVITY_TYPE_HISTORY:
qry = JobMatch.list_by_app_user_and_status(app_user, JobMatchStatus.DELETED)
elif activity_type == JobOfferTO.ACTIVITY_TYPE_STARRED:
qry = JobMatch.list_by_app_user_and_status(app_user, JobMatchStatus.STARRED)
else:
raise Exception('Unknown activity type %s' % activity_type)
job_matches_keys, new_cursor, has_more = qry.fetch_page(
fetch_size, start_cursor=start_cursor, keys_only=True) # type: List[ndb.Key], Cursor, bool
match_keys = [JobMatch.create_key(app_user, job_id) for job_id in ids if job_id] + \
[key for key in job_matches_keys if key.id() not in ids]
offer_keys = [JobOffer.create_key(match_key.id()) for match_key in match_keys]
models = ndb.get_multi(match_keys + offer_keys) # type: List[Union[JobMatch, JobOffer]]
job_matches = models[0: len(models) / 2]
job_offers = models[len(models) / 2:]
items = []
to_put = []
for match, job_offer in zip(job_matches, job_offers): # type: JobMatch, JobOffer
if not match:
# this should only happen when the job was requested using the 'ids' property
# like when the jobs activity is opened via a button on a news item
if job_offer.id not in ids:
logging.warning('Expected JobMatch to exist, creating it anyway...')
logging.debug('Creating manual JobMatch entry for job %d', job_offer.id)
match = JobMatch.manually_create(app_user, job_offer.id)
to_put.append(match)
timestamp = get_epoch_from_datetime(match.update_date)
items.append(JobOfferTO.from_job_offer(job_offer, timestamp, language,
get_job_offer_actions(job_offer, match, language)))
ndb.put_multi(to_put)
return items, new_cursor.to_websafe_string().decode('utf-8') if new_cursor else None, has_more
def get_job_offer_actions(job_offer, match, language):
# type: (JobOffer, JobMatch, str) -> List[Union[JobOfferChatActionTO, JobOfferOpenActionTO]]
actions = []
if job_offer.source.type == JobOfferSourceType.OCA:
action = JobOfferChatActionTO()
action.label = localize(language, 'open_chat')
action.chat_key = match.chat_key # possibly None
action.icon = 'fa-comment'
actions.append(action)
return actions
def send_new_jobs_for_activity_types(app_user, activity_types):
user_profile = get_user_profile(app_user)
if not user_profile.get_mobiles():
return
request = NewJobsRequestTO()
request.creation_time = now()
request.activity_types = activity_types
mobiles = db.get([get_mobile_key_by_account(mobile_detail.account) for mobile_detail in user_profile.get_mobiles().values()])
for mobile in mobiles:
ios_push_id = None
if mobile.is_ios:
ios_push_id = mobile.iOSPushId
kwargs = {}
if ios_push_id:
kwargs[CAPI_KEYWORD_ARG_PRIORITY] = PRIORITY_HIGH
newJobs(new_jobs_response_handler, logError, app_user, request=request, MOBILE_ACCOUNT=mobile, **kwargs)
def get_job_chat_info(app_user, job_id):
# type: (users.User, int) -> GetJobChatInfoResponseTO
keys = [JobOffer.create_key(job_id), JobMatch.create_key(app_user, job_id)]
job_offer, job_match = ndb.get_multi(keys) # type: JobOffer, JobMatch
job_sln_id = long(job_offer.source.id)
solicitation = JobSolicitation.list_by_job_and_user(users.User(job_offer.service_email),
job_sln_id,
app_user.email()).get() # type: Optional[JobSolicitation]
lang = get_user_profile(app_user).language
response = GetJobChatInfoResponseTO()
response.anonymous = JobChatAnonymousTO()
response.job_id = job_id
response.anonymous.enabled = True
response.anonymous.default_value = False
response.default_text = ''
response.info_text = localize(lang, 'job_info_text')
if solicitation:
# User has already applied before, but deleted the chat.
# Add him back to the chat and return the original chat key.
job_match.chat_key = solicitation.chat_key
response.chat_key = solicitation.chat_key
with users.set_user(users.User(job_offer.service_email)):
add_chat_members(solicitation.chat_key, [app_user.email()])
job_match.put()
return response
def create_job_chat(app_user, request):
# type: (users.User, CreateJobChatRequestTO) -> CreateJobChatResponseTO
keys = [JobMatch.create_key(app_user, request.job_id),
JobOffer.create_key(request.job_id)]
job_match, job_offer = ndb.get_multi(keys) # type: JobMatch, JobOffer
if not job_match.chat_key:
# If you ever want to create a separate service for jobs, you'll have to create a service api callback for this
from solutions.common.jobs.solicitations import create_job_solicitation
message_key = create_job_solicitation(app_user, job_offer, request)
job_match.chat_key = message_key
job_match.put()
response = CreateJobChatResponseTO()
response.message_key = job_match.chat_key
return response | to = JobKeyLabelTO()
to.key = domain
to.label = localize_jobs(user_profile.language, domain)
to.enabled = domain in job_criteria.job_domains if job_criteria else False
response.job_domains.append(to) | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.7@@
from __future__ import unicode_literals
from datetime import datetime
import logging
from types import NoneType
from google.appengine.ext import ndb, deferred, db
from google.appengine.ext.ndb.query import Cursor
from typing import Optional, List, Union, Tuple
from mcfw.rpc import returns, arguments
from rogerthat.bizz.communities.communities import get_community
from rogerthat.bizz.jobs.matching import rebuild_matches_check_current
from rogerthat.bizz.jobs.notifications import calculate_next_reminder
from rogerthat.bizz.jobs.translations import localize as localize_jobs
from rogerthat.capi.jobs import newJobs
from rogerthat.consts import JOBS_WORKER_QUEUE
from rogerthat.dal.mobile import get_mobile_key_by_account
from rogerthat.dal.profile import get_user_profile
from rogerthat.models import NdbUserProfile
from rogerthat.models.jobs import JobOffer, JobMatchingCriteria, JobMatchingCriteriaNotifications, JobMatch, \
JobMatchStatus, JobNotificationSchedule, JobOfferSourceType
from rogerthat.rpc import users
from rogerthat.rpc.models import RpcCAPICall, RpcException
from rogerthat.rpc.rpc import mapping, logError, CAPI_KEYWORD_ARG_PRIORITY, \
PRIORITY_HIGH
from rogerthat.service.api.messaging import add_chat_members
from rogerthat.to.jobs import GetJobsResponseTO, JobOfferTO, NewJobsResponseTO, \
NewJobsRequestTO, SaveJobsCriteriaResponseTO, GetJobsCriteriaResponseTO, \
JobKeyLabelTO, JobCriteriaLocationTO, JobCriteriaNotificationsTO, JobCriteriaGeoLocationTO, \
SaveJobsCriteriaRequestTO, JobOfferChatActionTO, JobOfferOpenActionTO, GetJobChatInfoResponseTO, JobChatAnonymousTO, \
CreateJobChatResponseTO, CreateJobChatRequestTO, JobsInfoTO, JobOfferProviderTO
from rogerthat.translations import localize
from rogerthat.utils import now, get_epoch_from_datetime
from rogerthat.utils.location import coordinates_to_city
from solutions.common.jobs.models import JobSolicitation
TAG_JOB_CHAT = '__rt__.jobs_chat'
CONTRACT_TYPES = [
'contract_type_001',
'contract_type_002',
'contract_type_003',
'contract_type_004',
'contract_type_005',
'contract_type_006',
'contract_type_007',
]
JOB_DOMAINS = [
'job_domain_001',
'job_domain_002',
'job_domain_003',
'job_domain_004',
'job_domain_005',
'job_domain_006',
'job_domain_007',
'job_domain_008',
'job_domain_009',
'job_domain_010',
'job_domain_011',
'job_domain_012',
'job_domain_013',
'job_domain_014',
'job_domain_015',
'job_domain_016',
'job_domain_017',
'job_domain_018',
'job_domain_019',
'job_domain_020',
'job_domain_021',
'job_domain_022',
'job_domain_023',
'job_domain_024',
]
def get_job_criteria(app_user):
# type: (users.User) -> GetJobsCriteriaResponseTO
user_profile = get_user_profile(app_user)
response = GetJobsCriteriaResponseTO()
response.location = JobCriteriaLocationTO()
response.location.address = None
response.location.geo = None
response.location.distance = 20000 # 20 Km
response.contract_types = []
response.job_domains = []
response.keywords = []
response.notifications = JobCriteriaNotificationsTO()
response.notifications.timezone = None
response.notifications.how_often = JobNotificationSchedule.NEVER
response.notifications.delivery_day = 'monday'
response.notifications.delivery_time = 64800 # 18:00
job_criteria = JobMatchingCriteria.create_key(app_user).get() # type: JobMatchingCriteria
for contract_type in CONTRACT_TYPES:
|
response.contract_types.sort(key=lambda item: item.label)
for domain in JOB_DOMAINS:
to = JobKeyLabelTO()
to.key = domain
to.label = localize_jobs(user_profile.language, domain)
to.enabled = domain in job_criteria.job_domains if job_criteria else False
response.job_domains.append(to)
response.job_domains.sort(key=lambda item: item.label)
if job_criteria:
response.active = job_criteria.active
response.location = JobCriteriaLocationTO()
response.location.address = job_criteria.address
response.location.geo = JobCriteriaGeoLocationTO()
response.location.geo.latitude = job_criteria.geo_location.lat
response.location.geo.longitude = job_criteria.geo_location.lon
response.location.distance = job_criteria.distance
response.keywords = job_criteria.keywords
if job_criteria.notifications:
response.notifications.how_often = job_criteria.notifications.how_often
if job_criteria.notifications.delivery_day:
response.notifications.delivery_day = job_criteria.notifications.delivery_day
if job_criteria.notifications.delivery_time:
response.notifications.delivery_time = job_criteria.notifications.delivery_time
else:
response.active = True # user first usage
return response
@returns(SaveJobsCriteriaResponseTO)
@arguments(app_user=users.User, request=SaveJobsCriteriaRequestTO)
def save_job_criteria(app_user, request):
# type: (users.User, SaveJobsCriteriaRequestTO) -> SaveJobsCriteriaResponseTO
job_criteria_key = JobMatchingCriteria.create_key(app_user)
job_criteria = job_criteria_key.get() # type: JobMatchingCriteria
new_job_profile = not job_criteria
if new_job_profile:
if not request.criteria:
return SaveJobsCriteriaResponseTO(active=False, new_profile=new_job_profile)
job_criteria = JobMatchingCriteria(key=job_criteria_key)
job_criteria.last_load_request = datetime.utcnow()
job_criteria.demo = get_community(get_user_profile(app_user).community_id).demo
original_job_criteria = None
else:
original_job_criteria = job_criteria.to_dict(exclude=['notifications', 'active'])
notifications = None
job_criteria.active = request.active
if request.criteria:
location = request.criteria.location
notifications = request.criteria.notifications
if location.geo:
job_criteria.geo_location = ndb.GeoPt(location.geo.latitude, location.geo.longitude)
if location.address:
job_criteria.address = location.address
else:
job_criteria.address = coordinates_to_city(job_criteria.geo_location.lat,
job_criteria.geo_location.lon)
job_criteria.distance = location.distance
job_criteria.contract_types = sorted(request.criteria.contract_types)
job_criteria.job_domains = sorted(request.criteria.job_domains)
job_criteria.keywords = sorted(request.criteria.keywords)
if not job_criteria.job_domains:
raise RpcException('at_least_one_job_domain_required', app_user)
if not job_criteria.contract_types:
raise RpcException('at_least_one_contract_type_required', app_user)
updated_criteria = job_criteria.to_dict(exclude=['notifications', 'active'])
should_build_matches = original_job_criteria != updated_criteria
should_calculate_reminder = should_build_matches
should_clear_notifications = should_build_matches
og_notifications = job_criteria.notifications and job_criteria.notifications.to_dict()
if not job_criteria.notifications:
job_criteria.notifications = JobMatchingCriteriaNotifications()
job_criteria.notifications.how_often = JobNotificationSchedule.NEVER
if notifications and notifications.timezone:
job_criteria.notifications.timezone = notifications.timezone
if job_criteria.notifications.how_often != notifications.how_often:
delayed_notification_types = (JobNotificationSchedule.AT_MOST_ONCE_A_DAY,
JobNotificationSchedule.AT_MOST_ONCE_A_WEEK)
if job_criteria.notifications.how_often in delayed_notification_types and \
notifications.how_often not in delayed_notification_types:
should_clear_notifications = True
job_criteria.notifications.how_often = notifications.how_often
job_criteria.notifications.delivery_day = notifications.delivery_day
job_criteria.notifications.delivery_time = notifications.delivery_time
if not should_calculate_reminder:
should_calculate_reminder = job_criteria.notifications.to_dict() != og_notifications
job_criteria.put()
if should_build_matches:
deferred.defer(rebuild_matches_check_current, app_user, _queue=JOBS_WORKER_QUEUE)
if should_calculate_reminder:
deferred.defer(calculate_next_reminder, app_user, should_clear_notifications, _queue=JOBS_WORKER_QUEUE)
return SaveJobsCriteriaResponseTO(active=job_criteria.active, new_profile=new_job_profile)
def get_oca_logo_url(language):
if language.startswith('nl'):
return 'https://storage.googleapis.com/oca-files/jobs/OCA-nl.png'
return 'https://storage.googleapis.com/oca-files/jobs/OCA.png'
def get_jobs_for_activity_type(app_user, activity_type, cursor, ids):
# type: (users.User, unicode, Optional[unicode], List[int]) -> GetJobsResponseTO
job_criteria_key = JobMatchingCriteria.create_key(app_user)
user_profile_key = NdbUserProfile.createKey(app_user)
keys = [job_criteria_key, user_profile_key]
job_criteria, user_profile = ndb.get_multi(keys) # type: Optional[JobMatchingCriteria], NdbUserProfile
resp = GetJobsResponseTO()
if not job_criteria or not job_criteria.active:
resp.is_profile_active = False
resp.items = []
resp.cursor = None
resp.has_more = False
else:
if cursor is None and activity_type == JobOfferTO.ACTIVITY_TYPE_NEW:
job_criteria.last_load_request = datetime.utcnow()
job_criteria.put()
resp.items, resp.cursor, resp.has_more = _get_jobs(activity_type, app_user, cursor, user_profile.language, ids)
resp.is_profile_active = True
info = JobsInfoTO()
info.title = localize(user_profile.language, 'app_jobs_title')
info.description = localize(user_profile.language, 'app_jobs_description')
info.providers = [
JobOfferProviderTO(image_url=get_oca_logo_url(user_profile.language)),
JobOfferProviderTO(image_url='https://storage.googleapis.com/oca-files/jobs/VDAB.jpg'),
]
resp.info = info
return resp
def bulk_save_jobs(app_user, job_ids, status):
# type: (users.User, List[int], int) -> List[int]
keys = [JobMatch.create_key(app_user, job_id) for job_id in job_ids]
matches = ndb.get_multi(keys) # type: List[JobMatch]
to_put = []
for match in matches:
if not match:
continue
match.status = status
to_put.append(match)
ndb.put_multi(to_put)
return [match.get_job_id() for match in to_put]
@mapping('com.mobicage.capi.jobs.new_jobs_response_handler')
@returns(NoneType)
@arguments(context=RpcCAPICall, result=NewJobsResponseTO)
def new_jobs_response_handler(context, result):
pass
def _get_jobs(activity_type, app_user, cursor, language, ids):
# type: (str, users.User, Optional[str], str, List[int]) -> Tuple[List[JobOfferTO], Optional[str], bool]
fetch_size = 20
start_cursor = Cursor.from_websafe_string(cursor) if cursor else None
if activity_type == JobOfferTO.ACTIVITY_TYPE_NEW:
qry = JobMatch.list_new_by_app_user(app_user)
elif activity_type == JobOfferTO.ACTIVITY_TYPE_HISTORY:
qry = JobMatch.list_by_app_user_and_status(app_user, JobMatchStatus.DELETED)
elif activity_type == JobOfferTO.ACTIVITY_TYPE_STARRED:
qry = JobMatch.list_by_app_user_and_status(app_user, JobMatchStatus.STARRED)
else:
raise Exception('Unknown activity type %s' % activity_type)
job_matches_keys, new_cursor, has_more = qry.fetch_page(
fetch_size, start_cursor=start_cursor, keys_only=True) # type: List[ndb.Key], Cursor, bool
match_keys = [JobMatch.create_key(app_user, job_id) for job_id in ids if job_id] + \
[key for key in job_matches_keys if key.id() not in ids]
offer_keys = [JobOffer.create_key(match_key.id()) for match_key in match_keys]
models = ndb.get_multi(match_keys + offer_keys) # type: List[Union[JobMatch, JobOffer]]
job_matches = models[0: len(models) / 2]
job_offers = models[len(models) / 2:]
items = []
to_put = []
for match, job_offer in zip(job_matches, job_offers): # type: JobMatch, JobOffer
if not match:
# this should only happen when the job was requested using the 'ids' property
# like when the jobs activity is opened via a button on a news item
if job_offer.id not in ids:
logging.warning('Expected JobMatch to exist, creating it anyway...')
logging.debug('Creating manual JobMatch entry for job %d', job_offer.id)
match = JobMatch.manually_create(app_user, job_offer.id)
to_put.append(match)
timestamp = get_epoch_from_datetime(match.update_date)
items.append(JobOfferTO.from_job_offer(job_offer, timestamp, language,
get_job_offer_actions(job_offer, match, language)))
ndb.put_multi(to_put)
return items, new_cursor.to_websafe_string().decode('utf-8') if new_cursor else None, has_more
def get_job_offer_actions(job_offer, match, language):
# type: (JobOffer, JobMatch, str) -> List[Union[JobOfferChatActionTO, JobOfferOpenActionTO]]
actions = []
if job_offer.source.type == JobOfferSourceType.OCA:
action = JobOfferChatActionTO()
action.label = localize(language, 'open_chat')
action.chat_key = match.chat_key # possibly None
action.icon = 'fa-comment'
actions.append(action)
return actions
def send_new_jobs_for_activity_types(app_user, activity_types):
user_profile = get_user_profile(app_user)
if not user_profile.get_mobiles():
return
request = NewJobsRequestTO()
request.creation_time = now()
request.activity_types = activity_types
mobiles = db.get([get_mobile_key_by_account(mobile_detail.account) for mobile_detail in user_profile.get_mobiles().values()])
for mobile in mobiles:
ios_push_id = None
if mobile.is_ios:
ios_push_id = mobile.iOSPushId
kwargs = {}
if ios_push_id:
kwargs[CAPI_KEYWORD_ARG_PRIORITY] = PRIORITY_HIGH
newJobs(new_jobs_response_handler, logError, app_user, request=request, MOBILE_ACCOUNT=mobile, **kwargs)
def get_job_chat_info(app_user, job_id):
# type: (users.User, int) -> GetJobChatInfoResponseTO
keys = [JobOffer.create_key(job_id), JobMatch.create_key(app_user, job_id)]
job_offer, job_match = ndb.get_multi(keys) # type: JobOffer, JobMatch
job_sln_id = long(job_offer.source.id)
solicitation = JobSolicitation.list_by_job_and_user(users.User(job_offer.service_email),
job_sln_id,
app_user.email()).get() # type: Optional[JobSolicitation]
lang = get_user_profile(app_user).language
response = GetJobChatInfoResponseTO()
response.anonymous = JobChatAnonymousTO()
response.job_id = job_id
response.anonymous.enabled = True
response.anonymous.default_value = False
response.default_text = ''
response.info_text = localize(lang, 'job_info_text')
if solicitation:
# User has already applied before, but deleted the chat.
# Add him back to the chat and return the original chat key.
job_match.chat_key = solicitation.chat_key
response.chat_key = solicitation.chat_key
with users.set_user(users.User(job_offer.service_email)):
add_chat_members(solicitation.chat_key, [app_user.email()])
job_match.put()
return response
def create_job_chat(app_user, request):
# type: (users.User, CreateJobChatRequestTO) -> CreateJobChatResponseTO
keys = [JobMatch.create_key(app_user, request.job_id),
JobOffer.create_key(request.job_id)]
job_match, job_offer = ndb.get_multi(keys) # type: JobMatch, JobOffer
if not job_match.chat_key:
# If you ever want to create a separate service for jobs, you'll have to create a service api callback for this
from solutions.common.jobs.solicitations import create_job_solicitation
message_key = create_job_solicitation(app_user, job_offer, request)
job_match.chat_key = message_key
job_match.put()
response = CreateJobChatResponseTO()
response.message_key = job_match.chat_key
return response
| to = JobKeyLabelTO()
to.key = contract_type
to.label = localize_jobs(user_profile.language, contract_type)
to.enabled = contract_type in job_criteria.contract_types if job_criteria else False
response.contract_types.append(to) | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.7@@
from __future__ import unicode_literals
from datetime import datetime
import logging
from types import NoneType
from google.appengine.ext import ndb, deferred, db
from google.appengine.ext.ndb.query import Cursor
from typing import Optional, List, Union, Tuple
from mcfw.rpc import returns, arguments
from rogerthat.bizz.communities.communities import get_community
from rogerthat.bizz.jobs.matching import rebuild_matches_check_current
from rogerthat.bizz.jobs.notifications import calculate_next_reminder
from rogerthat.bizz.jobs.translations import localize as localize_jobs
from rogerthat.capi.jobs import newJobs
from rogerthat.consts import JOBS_WORKER_QUEUE
from rogerthat.dal.mobile import get_mobile_key_by_account
from rogerthat.dal.profile import get_user_profile
from rogerthat.models import NdbUserProfile
from rogerthat.models.jobs import JobOffer, JobMatchingCriteria, JobMatchingCriteriaNotifications, JobMatch, \
JobMatchStatus, JobNotificationSchedule, JobOfferSourceType
from rogerthat.rpc import users
from rogerthat.rpc.models import RpcCAPICall, RpcException
from rogerthat.rpc.rpc import mapping, logError, CAPI_KEYWORD_ARG_PRIORITY, \
PRIORITY_HIGH
from rogerthat.service.api.messaging import add_chat_members
from rogerthat.to.jobs import GetJobsResponseTO, JobOfferTO, NewJobsResponseTO, \
NewJobsRequestTO, SaveJobsCriteriaResponseTO, GetJobsCriteriaResponseTO, \
JobKeyLabelTO, JobCriteriaLocationTO, JobCriteriaNotificationsTO, JobCriteriaGeoLocationTO, \
SaveJobsCriteriaRequestTO, JobOfferChatActionTO, JobOfferOpenActionTO, GetJobChatInfoResponseTO, JobChatAnonymousTO, \
CreateJobChatResponseTO, CreateJobChatRequestTO, JobsInfoTO, JobOfferProviderTO
from rogerthat.translations import localize
from rogerthat.utils import now, get_epoch_from_datetime
from rogerthat.utils.location import coordinates_to_city
from solutions.common.jobs.models import JobSolicitation
TAG_JOB_CHAT = '__rt__.jobs_chat'
CONTRACT_TYPES = [
'contract_type_001',
'contract_type_002',
'contract_type_003',
'contract_type_004',
'contract_type_005',
'contract_type_006',
'contract_type_007',
]
JOB_DOMAINS = [
'job_domain_001',
'job_domain_002',
'job_domain_003',
'job_domain_004',
'job_domain_005',
'job_domain_006',
'job_domain_007',
'job_domain_008',
'job_domain_009',
'job_domain_010',
'job_domain_011',
'job_domain_012',
'job_domain_013',
'job_domain_014',
'job_domain_015',
'job_domain_016',
'job_domain_017',
'job_domain_018',
'job_domain_019',
'job_domain_020',
'job_domain_021',
'job_domain_022',
'job_domain_023',
'job_domain_024',
]
def get_job_criteria(app_user):
# type: (users.User) -> GetJobsCriteriaResponseTO
user_profile = get_user_profile(app_user)
response = GetJobsCriteriaResponseTO()
response.location = JobCriteriaLocationTO()
response.location.address = None
response.location.geo = None
response.location.distance = 20000 # 20 Km
response.contract_types = []
response.job_domains = []
response.keywords = []
response.notifications = JobCriteriaNotificationsTO()
response.notifications.timezone = None
response.notifications.how_often = JobNotificationSchedule.NEVER
response.notifications.delivery_day = 'monday'
response.notifications.delivery_time = 64800 # 18:00
job_criteria = JobMatchingCriteria.create_key(app_user).get() # type: JobMatchingCriteria
for contract_type in CONTRACT_TYPES:
to = JobKeyLabelTO()
to.key = contract_type
to.label = localize_jobs(user_profile.language, contract_type)
to.enabled = contract_type in job_criteria.contract_types if job_criteria else False
response.contract_types.append(to)
response.contract_types.sort(key=lambda item: item.label)
for domain in JOB_DOMAINS:
to = JobKeyLabelTO()
to.key = domain
to.label = localize_jobs(user_profile.language, domain)
to.enabled = domain in job_criteria.job_domains if job_criteria else False
response.job_domains.append(to)
response.job_domains.sort(key=lambda item: item.label)
if job_criteria:
response.active = job_criteria.active
response.location = JobCriteriaLocationTO()
response.location.address = job_criteria.address
response.location.geo = JobCriteriaGeoLocationTO()
response.location.geo.latitude = job_criteria.geo_location.lat
response.location.geo.longitude = job_criteria.geo_location.lon
response.location.distance = job_criteria.distance
response.keywords = job_criteria.keywords
if job_criteria.notifications:
response.notifications.how_often = job_criteria.notifications.how_often
if job_criteria.notifications.delivery_day:
response.notifications.delivery_day = job_criteria.notifications.delivery_day
if job_criteria.notifications.delivery_time:
response.notifications.delivery_time = job_criteria.notifications.delivery_time
else:
response.active = True # user first usage
return response
@returns(SaveJobsCriteriaResponseTO)
@arguments(app_user=users.User, request=SaveJobsCriteriaRequestTO)
def save_job_criteria(app_user, request):
# type: (users.User, SaveJobsCriteriaRequestTO) -> SaveJobsCriteriaResponseTO
job_criteria_key = JobMatchingCriteria.create_key(app_user)
job_criteria = job_criteria_key.get() # type: JobMatchingCriteria
new_job_profile = not job_criteria
if new_job_profile:
if not request.criteria:
return SaveJobsCriteriaResponseTO(active=False, new_profile=new_job_profile)
job_criteria = JobMatchingCriteria(key=job_criteria_key)
job_criteria.last_load_request = datetime.utcnow()
job_criteria.demo = get_community(get_user_profile(app_user).community_id).demo
original_job_criteria = None
else:
original_job_criteria = job_criteria.to_dict(exclude=['notifications', 'active'])
notifications = None
job_criteria.active = request.active
if request.criteria:
location = request.criteria.location
notifications = request.criteria.notifications
if location.geo:
job_criteria.geo_location = ndb.GeoPt(location.geo.latitude, location.geo.longitude)
if location.address:
job_criteria.address = location.address
else:
job_criteria.address = coordinates_to_city(job_criteria.geo_location.lat,
job_criteria.geo_location.lon)
job_criteria.distance = location.distance
job_criteria.contract_types = sorted(request.criteria.contract_types)
job_criteria.job_domains = sorted(request.criteria.job_domains)
job_criteria.keywords = sorted(request.criteria.keywords)
if not job_criteria.job_domains:
raise RpcException('at_least_one_job_domain_required', app_user)
if not job_criteria.contract_types:
raise RpcException('at_least_one_contract_type_required', app_user)
updated_criteria = job_criteria.to_dict(exclude=['notifications', 'active'])
should_build_matches = original_job_criteria != updated_criteria
should_calculate_reminder = should_build_matches
should_clear_notifications = should_build_matches
og_notifications = job_criteria.notifications and job_criteria.notifications.to_dict()
if not job_criteria.notifications:
job_criteria.notifications = JobMatchingCriteriaNotifications()
job_criteria.notifications.how_often = JobNotificationSchedule.NEVER
if notifications and notifications.timezone:
job_criteria.notifications.timezone = notifications.timezone
if job_criteria.notifications.how_often != notifications.how_often:
delayed_notification_types = (JobNotificationSchedule.AT_MOST_ONCE_A_DAY,
JobNotificationSchedule.AT_MOST_ONCE_A_WEEK)
if job_criteria.notifications.how_often in delayed_notification_types and \
notifications.how_often not in delayed_notification_types:
should_clear_notifications = True
job_criteria.notifications.how_often = notifications.how_often
job_criteria.notifications.delivery_day = notifications.delivery_day
job_criteria.notifications.delivery_time = notifications.delivery_time
if not should_calculate_reminder:
should_calculate_reminder = job_criteria.notifications.to_dict() != og_notifications
job_criteria.put()
if should_build_matches:
deferred.defer(rebuild_matches_check_current, app_user, _queue=JOBS_WORKER_QUEUE)
if should_calculate_reminder:
deferred.defer(calculate_next_reminder, app_user, should_clear_notifications, _queue=JOBS_WORKER_QUEUE)
return SaveJobsCriteriaResponseTO(active=job_criteria.active, new_profile=new_job_profile)
def get_oca_logo_url(language):
if language.startswith('nl'):
return 'https://storage.googleapis.com/oca-files/jobs/OCA-nl.png'
return 'https://storage.googleapis.com/oca-files/jobs/OCA.png'
def get_jobs_for_activity_type(app_user, activity_type, cursor, ids):
# type: (users.User, unicode, Optional[unicode], List[int]) -> GetJobsResponseTO
job_criteria_key = JobMatchingCriteria.create_key(app_user)
user_profile_key = NdbUserProfile.createKey(app_user)
keys = [job_criteria_key, user_profile_key]
job_criteria, user_profile = ndb.get_multi(keys) # type: Optional[JobMatchingCriteria], NdbUserProfile
resp = GetJobsResponseTO()
if not job_criteria or not job_criteria.active:
resp.is_profile_active = False
resp.items = []
resp.cursor = None
resp.has_more = False
else:
if cursor is None and activity_type == JobOfferTO.ACTIVITY_TYPE_NEW:
job_criteria.last_load_request = datetime.utcnow()
job_criteria.put()
resp.items, resp.cursor, resp.has_more = _get_jobs(activity_type, app_user, cursor, user_profile.language, ids)
resp.is_profile_active = True
info = JobsInfoTO()
info.title = localize(user_profile.language, 'app_jobs_title')
info.description = localize(user_profile.language, 'app_jobs_description')
info.providers = [
JobOfferProviderTO(image_url=get_oca_logo_url(user_profile.language)),
JobOfferProviderTO(image_url='https://storage.googleapis.com/oca-files/jobs/VDAB.jpg'),
]
resp.info = info
return resp
def bulk_save_jobs(app_user, job_ids, status):
# type: (users.User, List[int], int) -> List[int]
keys = [JobMatch.create_key(app_user, job_id) for job_id in job_ids]
matches = ndb.get_multi(keys) # type: List[JobMatch]
to_put = []
for match in matches:
if not match:
continue
match.status = status
to_put.append(match)
ndb.put_multi(to_put)
return [match.get_job_id() for match in to_put]
@mapping('com.mobicage.capi.jobs.new_jobs_response_handler')
@returns(NoneType)
@arguments(context=RpcCAPICall, result=NewJobsResponseTO)
def new_jobs_response_handler(context, result):
|
def _get_jobs(activity_type, app_user, cursor, language, ids):
# type: (str, users.User, Optional[str], str, List[int]) -> Tuple[List[JobOfferTO], Optional[str], bool]
fetch_size = 20
start_cursor = Cursor.from_websafe_string(cursor) if cursor else None
if activity_type == JobOfferTO.ACTIVITY_TYPE_NEW:
qry = JobMatch.list_new_by_app_user(app_user)
elif activity_type == JobOfferTO.ACTIVITY_TYPE_HISTORY:
qry = JobMatch.list_by_app_user_and_status(app_user, JobMatchStatus.DELETED)
elif activity_type == JobOfferTO.ACTIVITY_TYPE_STARRED:
qry = JobMatch.list_by_app_user_and_status(app_user, JobMatchStatus.STARRED)
else:
raise Exception('Unknown activity type %s' % activity_type)
job_matches_keys, new_cursor, has_more = qry.fetch_page(
fetch_size, start_cursor=start_cursor, keys_only=True) # type: List[ndb.Key], Cursor, bool
match_keys = [JobMatch.create_key(app_user, job_id) for job_id in ids if job_id] + \
[key for key in job_matches_keys if key.id() not in ids]
offer_keys = [JobOffer.create_key(match_key.id()) for match_key in match_keys]
models = ndb.get_multi(match_keys + offer_keys) # type: List[Union[JobMatch, JobOffer]]
job_matches = models[0: len(models) / 2]
job_offers = models[len(models) / 2:]
items = []
to_put = []
for match, job_offer in zip(job_matches, job_offers): # type: JobMatch, JobOffer
if not match:
# this should only happen when the job was requested using the 'ids' property
# like when the jobs activity is opened via a button on a news item
if job_offer.id not in ids:
logging.warning('Expected JobMatch to exist, creating it anyway...')
logging.debug('Creating manual JobMatch entry for job %d', job_offer.id)
match = JobMatch.manually_create(app_user, job_offer.id)
to_put.append(match)
timestamp = get_epoch_from_datetime(match.update_date)
items.append(JobOfferTO.from_job_offer(job_offer, timestamp, language,
get_job_offer_actions(job_offer, match, language)))
ndb.put_multi(to_put)
return items, new_cursor.to_websafe_string().decode('utf-8') if new_cursor else None, has_more
def get_job_offer_actions(job_offer, match, language):
# type: (JobOffer, JobMatch, str) -> List[Union[JobOfferChatActionTO, JobOfferOpenActionTO]]
actions = []
if job_offer.source.type == JobOfferSourceType.OCA:
action = JobOfferChatActionTO()
action.label = localize(language, 'open_chat')
action.chat_key = match.chat_key # possibly None
action.icon = 'fa-comment'
actions.append(action)
return actions
def send_new_jobs_for_activity_types(app_user, activity_types):
user_profile = get_user_profile(app_user)
if not user_profile.get_mobiles():
return
request = NewJobsRequestTO()
request.creation_time = now()
request.activity_types = activity_types
mobiles = db.get([get_mobile_key_by_account(mobile_detail.account) for mobile_detail in user_profile.get_mobiles().values()])
for mobile in mobiles:
ios_push_id = None
if mobile.is_ios:
ios_push_id = mobile.iOSPushId
kwargs = {}
if ios_push_id:
kwargs[CAPI_KEYWORD_ARG_PRIORITY] = PRIORITY_HIGH
newJobs(new_jobs_response_handler, logError, app_user, request=request, MOBILE_ACCOUNT=mobile, **kwargs)
def get_job_chat_info(app_user, job_id):
# type: (users.User, int) -> GetJobChatInfoResponseTO
keys = [JobOffer.create_key(job_id), JobMatch.create_key(app_user, job_id)]
job_offer, job_match = ndb.get_multi(keys) # type: JobOffer, JobMatch
job_sln_id = long(job_offer.source.id)
solicitation = JobSolicitation.list_by_job_and_user(users.User(job_offer.service_email),
job_sln_id,
app_user.email()).get() # type: Optional[JobSolicitation]
lang = get_user_profile(app_user).language
response = GetJobChatInfoResponseTO()
response.anonymous = JobChatAnonymousTO()
response.job_id = job_id
response.anonymous.enabled = True
response.anonymous.default_value = False
response.default_text = ''
response.info_text = localize(lang, 'job_info_text')
if solicitation:
# User has already applied before, but deleted the chat.
# Add him back to the chat and return the original chat key.
job_match.chat_key = solicitation.chat_key
response.chat_key = solicitation.chat_key
with users.set_user(users.User(job_offer.service_email)):
add_chat_members(solicitation.chat_key, [app_user.email()])
job_match.put()
return response
def create_job_chat(app_user, request):
# type: (users.User, CreateJobChatRequestTO) -> CreateJobChatResponseTO
keys = [JobMatch.create_key(app_user, request.job_id),
JobOffer.create_key(request.job_id)]
job_match, job_offer = ndb.get_multi(keys) # type: JobMatch, JobOffer
if not job_match.chat_key:
# If you ever want to create a separate service for jobs, you'll have to create a service api callback for this
from solutions.common.jobs.solicitations import create_job_solicitation
message_key = create_job_solicitation(app_user, job_offer, request)
job_match.chat_key = message_key
job_match.put()
response = CreateJobChatResponseTO()
response.message_key = job_match.chat_key
return response
| pass | identifier_body |
forms.py | import os
from django import forms
from django.core.validators import RegexValidator
from django.conf import settings
from .models import Site, Process, Database, DatabaseHost, Domain, SiteHost
from .helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_php_fpm, update_supervisor, clean_site_type
from .database_helpers import create_postgres_database, create_mysql_database
from ..users.models import User, Group
class SiteForm(forms.ModelForm):
name_validator = RegexValidator(r"^[0-9a-zA-Z_\-]*$", "Only alphanumeric characters, underscores, and dashes are allowed.")
domain_validator = RegexValidator(r"^[0-9a-zA-Z_\- .]*$", "Only alphanumeric characters, underscores, dashes, and spaces are allowed.")
name = forms.CharField(max_length=32,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Can only contain alphanumeric characters, underscores, and dashes. Maximum length of 32 characters.",
validators=[name_validator])
description = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}), required=False)
category = forms.ChoiceField(choices=(("static", "Static"), ("php", "PHP"), ("dynamic", "Dynamic"), ("vm", "Virtual Machine")),
help_text="If you want to run a custom server, like Node.js or Django, you will need to set this to Dynamic.",
widget=forms.Select(attrs={"class": "form-control"}))
purpose = forms.ChoiceField(choices=(("user", "User"), ("project", "Project"), ("activity", "Activity"), ("other", "Other")),
widget=forms.Select(attrs={"class": "form-control"}))
users = forms.ModelMultipleChoiceField(required=False, queryset=User.objects.filter(service=False))
custom_nginx = forms.BooleanField(required=False,
label="Custom Nginx Configuration",
widget=forms.CheckboxInput(attrs={"class": "custom-control-input"}))
domain = forms.CharField(max_length=255,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Can only contain alphanumeric characters, underscores, and dashes. Separate multiple domains with spaces.",
validators=[domain_validator])
def __init__(self, *args, **kwargs):
if kwargs.get("instance"):
initial = kwargs.setdefault('initial', {})
initial["users"] = [u.pk for u in kwargs['instance'].group.users.filter(service=False)]
if kwargs.get("user"):
self._user = kwargs["user"]
del kwargs["user"]
forms.ModelForm.__init__(self, *args, **kwargs)
instance = getattr(self, "instance", None)
if instance and instance.pk:
self.fields["name"].disabled = True
self.fields["domain"].initial = " ".join([x.domain for x in instance.domain_set.all()])
if hasattr(self, "_user") and not self._user.is_staff:
for field in self.fields:
self.fields[field].disabled = True
self.fields["description"].disabled = False
self.fields["category"].disabled = False
self.fields["domain"].disabled = False
self.fields["users"].disabled = False
self._old_path = instance.path
if instance.purpose == "legacy" or (hasattr(self, "_user") and self._user.is_superuser):
purpose_choices = self.fields["purpose"].choices
purpose_choices.append(("legacy", "Legacy"))
self.fields["purpose"].choices = purpose_choices
else:
if hasattr(self, "_user") and not self._user.is_superuser:
self.fields["purpose"].initial = "project"
self.fields["purpose"].disabled = True
self.fields["users"].initial = (self._user.id,)
self.fields["custom_nginx"].disabled = True
self._old_path = None
def clean_domain(self):
data = [x.strip() for x in self.cleaned_data["domain"].strip().split(" ")]
data = [x for x in data if x]
default_domain = "{}.sites.tjhsst.edu".format(self.cleaned_data["name"])
if not data:
raise forms.ValidationError("You must enter at least one domain!")
for domain in data:
if domain.endswith("tjhsst.edu"):
if not domain == default_domain:
if not self._user.is_superuser:
raise forms.ValidationError("Only administrators can set up *.tjhsst.edu domains.")
elif domain.endswith(settings.PROJECT_DOMAIN):
if not domain[:-len(settings.PROJECT_DOMAIN)].rstrip(".") == self.cleaned_data["name"]:
if not self._user.is_superuser:
raise forms.ValidationError("Your subdomain for {} must match your site name!".format(settings.PROJECT_DOMAIN))
else:
if Domain.objects.filter(domain=domain).exclude(site__name=self.cleaned_data["name"]).exists():
raise forms.ValidationError("The domain {} is already taken by another site! If you believe this is an error, please send an email to {}.".format(domain, settings.EMAIL_CONTACT))
return data
def clean(self):
cleaned_data = super(SiteForm, self).clean()
default_domain = "{}.sites.tjhsst.edu".format(cleaned_data["name"])
if "domain" in cleaned_data:
if cleaned_data["purpose"] in ["user", "activity", "legacy"]:
if default_domain not in cleaned_data["domain"]:
raise forms.ValidationError("Sites of type '{}' must keep the default '{}' domain!".format(cleaned_data["purpose"], default_domain))
if cleaned_data["name"] in ["user", "activities", "legacy", "projects"]:
raise forms.ValidationError("Invalid site name")
return cleaned_data
def save(self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.host = SiteHost.objects.first()
old_save_m2m = self.save_m2m
def save_m2m():
old_save_m2m()
instance.group.users.clear()
instance.group.users.add(instance.user)
for user in self.cleaned_data['users']:
instance.group.users.add(user)
self.save_m2m = save_m2m
if commit:
try:
instance.user
instance.group
except (User.DoesNotExist, Group.DoesNotExist):
create_site_users(instance)
if self._old_path and not instance.path == self._old_path:
os.rename(self._old_path, instance.path)
if instance.category == "dynamic" and hasattr(instance, "process"):
proc = instance.process
proc.path = proc.path.replace(self._old_path, instance.path)
proc.save()
update_supervisor()
make_site_dirs(instance)
flush_permissions()
clean_site_type(instance)
instance.save()
self.save_m2m()
domains = self.cleaned_data["domain"]
instance.domain_set.exclude(domain__in=domains).delete()
for domain in domains:
if not instance.domain_set.filter(domain=domain).exists():
Domain.objects.create(site=instance, domain=domain)
create_config_files(instance)
return instance
class Meta:
model = Site
fields = ["name", "domain", "description", "category", "purpose", "users", "custom_nginx"]
class ProcessForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(ProcessForm, self).__init__(*args, **kwargs)
if not user.is_superuser:
self.fields['site'].queryset = Site.objects.filter(group__users__id=user.id).filter(category="dynamic")
path_validator = RegexValidator(r"^{}/.*$".format(settings.WEB_ROOT), "Please enter a valid path starting with {}.".format(settings.WEB_ROOT))
site = forms.ModelChoiceField(queryset=Site.objects.filter(category="dynamic"), disabled=True)
path = forms.CharField(max_length=255,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Enter a valid path starting with {}.".format(settings.WEB_ROOT),
validators=[path_validator])
def clean_path(self):
value = os.path.abspath(self.cleaned_data["path"].strip())
if self.instance.pk:
root_path = self.instance.site.path
else:
root_path = Site.objects.get(id=self.initial["site"]).path
if not os.path.isfile(value):
raise forms.ValidationError("The script you are trying to reference does not exist!")
if not value.startswith(root_path):
raise forms.ValidationError("The script you are trying to reference must be in the {} folder!".format(root_path))
return value
class Meta:
model = Process
fields = ["site", "path"]
class DatabaseForm(forms.ModelForm):
| site = forms.ModelChoiceField(queryset=Site.objects.all(), disabled=True)
host = forms.ModelChoiceField(queryset=DatabaseHost.objects.all(), widget=forms.RadioSelect(), empty_label=None)
def __init__(self, user, *args, **kwargs):
super(DatabaseForm, self).__init__(*args, **kwargs)
self.initial["category"] = "postgresql"
if not user.is_superuser:
self.fields['site'].queryset = Site.objects.exclude(category="static").filter(group__users__id=user.id)
def save(self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.password = User.objects.make_random_password(length=24)
if commit:
flag = False
if instance.category == "postgresql":
flag = create_postgres_database(instance)
elif instance.category == "mysql":
flag = create_mysql_database(instance)
if flag:
instance.save()
else:
return None
create_config_files(instance.site)
if instance.site.category == "php":
reload_php_fpm()
elif instance.site.category == "dynamic":
update_supervisor()
return instance
class Meta:
model = Database
fields = ["site", "host"] | identifier_body | |
forms.py | import os
from django import forms
from django.core.validators import RegexValidator
from django.conf import settings
from .models import Site, Process, Database, DatabaseHost, Domain, SiteHost
from .helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_php_fpm, update_supervisor, clean_site_type
from .database_helpers import create_postgres_database, create_mysql_database
from ..users.models import User, Group
class SiteForm(forms.ModelForm):
name_validator = RegexValidator(r"^[0-9a-zA-Z_\-]*$", "Only alphanumeric characters, underscores, and dashes are allowed.")
domain_validator = RegexValidator(r"^[0-9a-zA-Z_\- .]*$", "Only alphanumeric characters, underscores, dashes, and spaces are allowed.")
name = forms.CharField(max_length=32,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Can only contain alphanumeric characters, underscores, and dashes. Maximum length of 32 characters.",
validators=[name_validator])
description = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}), required=False)
category = forms.ChoiceField(choices=(("static", "Static"), ("php", "PHP"), ("dynamic", "Dynamic"), ("vm", "Virtual Machine")),
help_text="If you want to run a custom server, like Node.js or Django, you will need to set this to Dynamic.",
widget=forms.Select(attrs={"class": "form-control"}))
purpose = forms.ChoiceField(choices=(("user", "User"), ("project", "Project"), ("activity", "Activity"), ("other", "Other")),
widget=forms.Select(attrs={"class": "form-control"}))
users = forms.ModelMultipleChoiceField(required=False, queryset=User.objects.filter(service=False))
custom_nginx = forms.BooleanField(required=False,
label="Custom Nginx Configuration",
widget=forms.CheckboxInput(attrs={"class": "custom-control-input"}))
domain = forms.CharField(max_length=255,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Can only contain alphanumeric characters, underscores, and dashes. Separate multiple domains with spaces.",
validators=[domain_validator])
def __init__(self, *args, **kwargs):
if kwargs.get("instance"):
initial = kwargs.setdefault('initial', {})
initial["users"] = [u.pk for u in kwargs['instance'].group.users.filter(service=False)]
if kwargs.get("user"):
self._user = kwargs["user"]
del kwargs["user"]
forms.ModelForm.__init__(self, *args, **kwargs)
instance = getattr(self, "instance", None)
if instance and instance.pk:
self.fields["name"].disabled = True
self.fields["domain"].initial = " ".join([x.domain for x in instance.domain_set.all()])
if hasattr(self, "_user") and not self._user.is_staff:
for field in self.fields:
self.fields[field].disabled = True
self.fields["description"].disabled = False
self.fields["category"].disabled = False
self.fields["domain"].disabled = False
self.fields["users"].disabled = False
self._old_path = instance.path
if instance.purpose == "legacy" or (hasattr(self, "_user") and self._user.is_superuser):
purpose_choices = self.fields["purpose"].choices
purpose_choices.append(("legacy", "Legacy"))
self.fields["purpose"].choices = purpose_choices
else:
if hasattr(self, "_user") and not self._user.is_superuser:
self.fields["purpose"].initial = "project"
self.fields["purpose"].disabled = True
self.fields["users"].initial = (self._user.id,)
self.fields["custom_nginx"].disabled = True
self._old_path = None
def clean_domain(self):
data = [x.strip() for x in self.cleaned_data["domain"].strip().split(" ")]
data = [x for x in data if x]
default_domain = "{}.sites.tjhsst.edu".format(self.cleaned_data["name"])
if not data:
raise forms.ValidationError("You must enter at least one domain!")
for domain in data:
if domain.endswith("tjhsst.edu"):
if not domain == default_domain:
if not self._user.is_superuser:
raise forms.ValidationError("Only administrators can set up *.tjhsst.edu domains.")
elif domain.endswith(settings.PROJECT_DOMAIN):
if not domain[:-len(settings.PROJECT_DOMAIN)].rstrip(".") == self.cleaned_data["name"]:
if not self._user.is_superuser:
raise forms.ValidationError("Your subdomain for {} must match your site name!".format(settings.PROJECT_DOMAIN))
else:
if Domain.objects.filter(domain=domain).exclude(site__name=self.cleaned_data["name"]).exists():
raise forms.ValidationError("The domain {} is already taken by another site! If you believe this is an error, please send an email to {}.".format(domain, settings.EMAIL_CONTACT))
return data
def clean(self):
cleaned_data = super(SiteForm, self).clean()
default_domain = "{}.sites.tjhsst.edu".format(cleaned_data["name"])
if "domain" in cleaned_data:
if cleaned_data["purpose"] in ["user", "activity", "legacy"]:
if default_domain not in cleaned_data["domain"]:
raise forms.ValidationError("Sites of type '{}' must keep the default '{}' domain!".format(cleaned_data["purpose"], default_domain))
if cleaned_data["name"] in ["user", "activities", "legacy", "projects"]:
raise forms.ValidationError("Invalid site name")
return cleaned_data
def | (self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.host = SiteHost.objects.first()
old_save_m2m = self.save_m2m
def save_m2m():
old_save_m2m()
instance.group.users.clear()
instance.group.users.add(instance.user)
for user in self.cleaned_data['users']:
instance.group.users.add(user)
self.save_m2m = save_m2m
if commit:
try:
instance.user
instance.group
except (User.DoesNotExist, Group.DoesNotExist):
create_site_users(instance)
if self._old_path and not instance.path == self._old_path:
os.rename(self._old_path, instance.path)
if instance.category == "dynamic" and hasattr(instance, "process"):
proc = instance.process
proc.path = proc.path.replace(self._old_path, instance.path)
proc.save()
update_supervisor()
make_site_dirs(instance)
flush_permissions()
clean_site_type(instance)
instance.save()
self.save_m2m()
domains = self.cleaned_data["domain"]
instance.domain_set.exclude(domain__in=domains).delete()
for domain in domains:
if not instance.domain_set.filter(domain=domain).exists():
Domain.objects.create(site=instance, domain=domain)
create_config_files(instance)
return instance
class Meta:
model = Site
fields = ["name", "domain", "description", "category", "purpose", "users", "custom_nginx"]
class ProcessForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(ProcessForm, self).__init__(*args, **kwargs)
if not user.is_superuser:
self.fields['site'].queryset = Site.objects.filter(group__users__id=user.id).filter(category="dynamic")
path_validator = RegexValidator(r"^{}/.*$".format(settings.WEB_ROOT), "Please enter a valid path starting with {}.".format(settings.WEB_ROOT))
site = forms.ModelChoiceField(queryset=Site.objects.filter(category="dynamic"), disabled=True)
path = forms.CharField(max_length=255,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Enter a valid path starting with {}.".format(settings.WEB_ROOT),
validators=[path_validator])
def clean_path(self):
value = os.path.abspath(self.cleaned_data["path"].strip())
if self.instance.pk:
root_path = self.instance.site.path
else:
root_path = Site.objects.get(id=self.initial["site"]).path
if not os.path.isfile(value):
raise forms.ValidationError("The script you are trying to reference does not exist!")
if not value.startswith(root_path):
raise forms.ValidationError("The script you are trying to reference must be in the {} folder!".format(root_path))
return value
class Meta:
model = Process
fields = ["site", "path"]
class DatabaseForm(forms.ModelForm):
site = forms.ModelChoiceField(queryset=Site.objects.all(), disabled=True)
host = forms.ModelChoiceField(queryset=DatabaseHost.objects.all(), widget=forms.RadioSelect(), empty_label=None)
def __init__(self, user, *args, **kwargs):
super(DatabaseForm, self).__init__(*args, **kwargs)
self.initial["category"] = "postgresql"
if not user.is_superuser:
self.fields['site'].queryset = Site.objects.exclude(category="static").filter(group__users__id=user.id)
def save(self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.password = User.objects.make_random_password(length=24)
if commit:
flag = False
if instance.category == "postgresql":
flag = create_postgres_database(instance)
elif instance.category == "mysql":
flag = create_mysql_database(instance)
if flag:
instance.save()
else:
return None
create_config_files(instance.site)
if instance.site.category == "php":
reload_php_fpm()
elif instance.site.category == "dynamic":
update_supervisor()
return instance
class Meta:
model = Database
fields = ["site", "host"]
| save | identifier_name |
forms.py | import os
from django import forms
from django.core.validators import RegexValidator
from django.conf import settings
from .models import Site, Process, Database, DatabaseHost, Domain, SiteHost
from .helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_php_fpm, update_supervisor, clean_site_type
from .database_helpers import create_postgres_database, create_mysql_database
from ..users.models import User, Group
class SiteForm(forms.ModelForm):
name_validator = RegexValidator(r"^[0-9a-zA-Z_\-]*$", "Only alphanumeric characters, underscores, and dashes are allowed.")
domain_validator = RegexValidator(r"^[0-9a-zA-Z_\- .]*$", "Only alphanumeric characters, underscores, dashes, and spaces are allowed.")
name = forms.CharField(max_length=32,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Can only contain alphanumeric characters, underscores, and dashes. Maximum length of 32 characters.",
validators=[name_validator])
description = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}), required=False)
category = forms.ChoiceField(choices=(("static", "Static"), ("php", "PHP"), ("dynamic", "Dynamic"), ("vm", "Virtual Machine")),
help_text="If you want to run a custom server, like Node.js or Django, you will need to set this to Dynamic.",
widget=forms.Select(attrs={"class": "form-control"}))
purpose = forms.ChoiceField(choices=(("user", "User"), ("project", "Project"), ("activity", "Activity"), ("other", "Other")),
widget=forms.Select(attrs={"class": "form-control"}))
users = forms.ModelMultipleChoiceField(required=False, queryset=User.objects.filter(service=False))
custom_nginx = forms.BooleanField(required=False,
label="Custom Nginx Configuration",
widget=forms.CheckboxInput(attrs={"class": "custom-control-input"}))
domain = forms.CharField(max_length=255,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Can only contain alphanumeric characters, underscores, and dashes. Separate multiple domains with spaces.",
validators=[domain_validator])
def __init__(self, *args, **kwargs):
if kwargs.get("instance"):
initial = kwargs.setdefault('initial', {})
initial["users"] = [u.pk for u in kwargs['instance'].group.users.filter(service=False)]
if kwargs.get("user"):
self._user = kwargs["user"]
del kwargs["user"]
forms.ModelForm.__init__(self, *args, **kwargs)
instance = getattr(self, "instance", None)
if instance and instance.pk:
self.fields["name"].disabled = True
self.fields["domain"].initial = " ".join([x.domain for x in instance.domain_set.all()])
if hasattr(self, "_user") and not self._user.is_staff:
for field in self.fields:
self.fields[field].disabled = True
self.fields["description"].disabled = False
self.fields["category"].disabled = False
self.fields["domain"].disabled = False
self.fields["users"].disabled = False
self._old_path = instance.path
if instance.purpose == "legacy" or (hasattr(self, "_user") and self._user.is_superuser):
purpose_choices = self.fields["purpose"].choices
purpose_choices.append(("legacy", "Legacy"))
self.fields["purpose"].choices = purpose_choices
else:
if hasattr(self, "_user") and not self._user.is_superuser:
self.fields["purpose"].initial = "project"
self.fields["purpose"].disabled = True
self.fields["users"].initial = (self._user.id,)
self.fields["custom_nginx"].disabled = True
self._old_path = None
def clean_domain(self):
data = [x.strip() for x in self.cleaned_data["domain"].strip().split(" ")]
data = [x for x in data if x]
default_domain = "{}.sites.tjhsst.edu".format(self.cleaned_data["name"])
if not data:
raise forms.ValidationError("You must enter at least one domain!")
for domain in data:
if domain.endswith("tjhsst.edu"):
if not domain == default_domain:
if not self._user.is_superuser:
|
elif domain.endswith(settings.PROJECT_DOMAIN):
if not domain[:-len(settings.PROJECT_DOMAIN)].rstrip(".") == self.cleaned_data["name"]:
if not self._user.is_superuser:
raise forms.ValidationError("Your subdomain for {} must match your site name!".format(settings.PROJECT_DOMAIN))
else:
if Domain.objects.filter(domain=domain).exclude(site__name=self.cleaned_data["name"]).exists():
raise forms.ValidationError("The domain {} is already taken by another site! If you believe this is an error, please send an email to {}.".format(domain, settings.EMAIL_CONTACT))
return data
def clean(self):
cleaned_data = super(SiteForm, self).clean()
default_domain = "{}.sites.tjhsst.edu".format(cleaned_data["name"])
if "domain" in cleaned_data:
if cleaned_data["purpose"] in ["user", "activity", "legacy"]:
if default_domain not in cleaned_data["domain"]:
raise forms.ValidationError("Sites of type '{}' must keep the default '{}' domain!".format(cleaned_data["purpose"], default_domain))
if cleaned_data["name"] in ["user", "activities", "legacy", "projects"]:
raise forms.ValidationError("Invalid site name")
return cleaned_data
def save(self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.host = SiteHost.objects.first()
old_save_m2m = self.save_m2m
def save_m2m():
old_save_m2m()
instance.group.users.clear()
instance.group.users.add(instance.user)
for user in self.cleaned_data['users']:
instance.group.users.add(user)
self.save_m2m = save_m2m
if commit:
try:
instance.user
instance.group
except (User.DoesNotExist, Group.DoesNotExist):
create_site_users(instance)
if self._old_path and not instance.path == self._old_path:
os.rename(self._old_path, instance.path)
if instance.category == "dynamic" and hasattr(instance, "process"):
proc = instance.process
proc.path = proc.path.replace(self._old_path, instance.path)
proc.save()
update_supervisor()
make_site_dirs(instance)
flush_permissions()
clean_site_type(instance)
instance.save()
self.save_m2m()
domains = self.cleaned_data["domain"]
instance.domain_set.exclude(domain__in=domains).delete()
for domain in domains:
if not instance.domain_set.filter(domain=domain).exists():
Domain.objects.create(site=instance, domain=domain)
create_config_files(instance)
return instance
class Meta:
model = Site
fields = ["name", "domain", "description", "category", "purpose", "users", "custom_nginx"]
class ProcessForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(ProcessForm, self).__init__(*args, **kwargs)
if not user.is_superuser:
self.fields['site'].queryset = Site.objects.filter(group__users__id=user.id).filter(category="dynamic")
path_validator = RegexValidator(r"^{}/.*$".format(settings.WEB_ROOT), "Please enter a valid path starting with {}.".format(settings.WEB_ROOT))
site = forms.ModelChoiceField(queryset=Site.objects.filter(category="dynamic"), disabled=True)
path = forms.CharField(max_length=255,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Enter a valid path starting with {}.".format(settings.WEB_ROOT),
validators=[path_validator])
def clean_path(self):
value = os.path.abspath(self.cleaned_data["path"].strip())
if self.instance.pk:
root_path = self.instance.site.path
else:
root_path = Site.objects.get(id=self.initial["site"]).path
if not os.path.isfile(value):
raise forms.ValidationError("The script you are trying to reference does not exist!")
if not value.startswith(root_path):
raise forms.ValidationError("The script you are trying to reference must be in the {} folder!".format(root_path))
return value
class Meta:
model = Process
fields = ["site", "path"]
class DatabaseForm(forms.ModelForm):
site = forms.ModelChoiceField(queryset=Site.objects.all(), disabled=True)
host = forms.ModelChoiceField(queryset=DatabaseHost.objects.all(), widget=forms.RadioSelect(), empty_label=None)
def __init__(self, user, *args, **kwargs):
super(DatabaseForm, self).__init__(*args, **kwargs)
self.initial["category"] = "postgresql"
if not user.is_superuser:
self.fields['site'].queryset = Site.objects.exclude(category="static").filter(group__users__id=user.id)
def save(self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.password = User.objects.make_random_password(length=24)
if commit:
flag = False
if instance.category == "postgresql":
flag = create_postgres_database(instance)
elif instance.category == "mysql":
flag = create_mysql_database(instance)
if flag:
instance.save()
else:
return None
create_config_files(instance.site)
if instance.site.category == "php":
reload_php_fpm()
elif instance.site.category == "dynamic":
update_supervisor()
return instance
class Meta:
model = Database
fields = ["site", "host"]
| raise forms.ValidationError("Only administrators can set up *.tjhsst.edu domains.") | conditional_block |
forms.py | import os
from django import forms
from django.core.validators import RegexValidator
from django.conf import settings
from .models import Site, Process, Database, DatabaseHost, Domain, SiteHost
from .helpers import create_site_users, make_site_dirs, create_config_files, flush_permissions, reload_php_fpm, update_supervisor, clean_site_type
from .database_helpers import create_postgres_database, create_mysql_database
from ..users.models import User, Group
class SiteForm(forms.ModelForm):
name_validator = RegexValidator(r"^[0-9a-zA-Z_\-]*$", "Only alphanumeric characters, underscores, and dashes are allowed.")
domain_validator = RegexValidator(r"^[0-9a-zA-Z_\- .]*$", "Only alphanumeric characters, underscores, dashes, and spaces are allowed.")
name = forms.CharField(max_length=32,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Can only contain alphanumeric characters, underscores, and dashes. Maximum length of 32 characters.",
validators=[name_validator])
description = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}), required=False)
category = forms.ChoiceField(choices=(("static", "Static"), ("php", "PHP"), ("dynamic", "Dynamic"), ("vm", "Virtual Machine")),
help_text="If you want to run a custom server, like Node.js or Django, you will need to set this to Dynamic.",
widget=forms.Select(attrs={"class": "form-control"}))
purpose = forms.ChoiceField(choices=(("user", "User"), ("project", "Project"), ("activity", "Activity"), ("other", "Other")),
widget=forms.Select(attrs={"class": "form-control"}))
users = forms.ModelMultipleChoiceField(required=False, queryset=User.objects.filter(service=False))
custom_nginx = forms.BooleanField(required=False,
label="Custom Nginx Configuration",
widget=forms.CheckboxInput(attrs={"class": "custom-control-input"}))
domain = forms.CharField(max_length=255,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Can only contain alphanumeric characters, underscores, and dashes. Separate multiple domains with spaces.",
validators=[domain_validator])
def __init__(self, *args, **kwargs):
if kwargs.get("instance"):
initial = kwargs.setdefault('initial', {})
initial["users"] = [u.pk for u in kwargs['instance'].group.users.filter(service=False)]
if kwargs.get("user"):
self._user = kwargs["user"]
del kwargs["user"]
forms.ModelForm.__init__(self, *args, **kwargs)
instance = getattr(self, "instance", None)
if instance and instance.pk:
self.fields["name"].disabled = True
self.fields["domain"].initial = " ".join([x.domain for x in instance.domain_set.all()])
if hasattr(self, "_user") and not self._user.is_staff:
for field in self.fields:
self.fields[field].disabled = True
self.fields["description"].disabled = False
self.fields["category"].disabled = False
self.fields["domain"].disabled = False
self.fields["users"].disabled = False
self._old_path = instance.path
if instance.purpose == "legacy" or (hasattr(self, "_user") and self._user.is_superuser):
purpose_choices = self.fields["purpose"].choices
purpose_choices.append(("legacy", "Legacy"))
self.fields["purpose"].choices = purpose_choices
else:
if hasattr(self, "_user") and not self._user.is_superuser:
self.fields["purpose"].initial = "project"
self.fields["purpose"].disabled = True
self.fields["users"].initial = (self._user.id,)
self.fields["custom_nginx"].disabled = True
self._old_path = None
def clean_domain(self):
data = [x.strip() for x in self.cleaned_data["domain"].strip().split(" ")]
data = [x for x in data if x]
default_domain = "{}.sites.tjhsst.edu".format(self.cleaned_data["name"])
if not data:
raise forms.ValidationError("You must enter at least one domain!")
for domain in data:
if domain.endswith("tjhsst.edu"):
if not domain == default_domain:
if not self._user.is_superuser:
raise forms.ValidationError("Only administrators can set up *.tjhsst.edu domains.")
elif domain.endswith(settings.PROJECT_DOMAIN):
if not domain[:-len(settings.PROJECT_DOMAIN)].rstrip(".") == self.cleaned_data["name"]:
if not self._user.is_superuser:
raise forms.ValidationError("Your subdomain for {} must match your site name!".format(settings.PROJECT_DOMAIN))
else:
if Domain.objects.filter(domain=domain).exclude(site__name=self.cleaned_data["name"]).exists():
raise forms.ValidationError("The domain {} is already taken by another site! If you believe this is an error, please send an email to {}.".format(domain, settings.EMAIL_CONTACT))
return data
def clean(self):
cleaned_data = super(SiteForm, self).clean()
default_domain = "{}.sites.tjhsst.edu".format(cleaned_data["name"])
if "domain" in cleaned_data:
if cleaned_data["purpose"] in ["user", "activity", "legacy"]:
if default_domain not in cleaned_data["domain"]:
raise forms.ValidationError("Sites of type '{}' must keep the default '{}' domain!".format(cleaned_data["purpose"], default_domain))
if cleaned_data["name"] in ["user", "activities", "legacy", "projects"]:
raise forms.ValidationError("Invalid site name")
return cleaned_data
def save(self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.host = SiteHost.objects.first()
old_save_m2m = self.save_m2m
def save_m2m():
old_save_m2m()
instance.group.users.clear()
instance.group.users.add(instance.user)
for user in self.cleaned_data['users']:
instance.group.users.add(user)
self.save_m2m = save_m2m
if commit:
try:
instance.user
instance.group
except (User.DoesNotExist, Group.DoesNotExist):
create_site_users(instance)
if self._old_path and not instance.path == self._old_path:
os.rename(self._old_path, instance.path)
if instance.category == "dynamic" and hasattr(instance, "process"):
proc = instance.process
proc.path = proc.path.replace(self._old_path, instance.path)
proc.save()
update_supervisor()
make_site_dirs(instance)
flush_permissions()
clean_site_type(instance)
instance.save()
self.save_m2m()
domains = self.cleaned_data["domain"]
instance.domain_set.exclude(domain__in=domains).delete()
for domain in domains:
if not instance.domain_set.filter(domain=domain).exists():
Domain.objects.create(site=instance, domain=domain)
|
class Meta:
model = Site
fields = ["name", "domain", "description", "category", "purpose", "users", "custom_nginx"]
class ProcessForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(ProcessForm, self).__init__(*args, **kwargs)
if not user.is_superuser:
self.fields['site'].queryset = Site.objects.filter(group__users__id=user.id).filter(category="dynamic")
path_validator = RegexValidator(r"^{}/.*$".format(settings.WEB_ROOT), "Please enter a valid path starting with {}.".format(settings.WEB_ROOT))
site = forms.ModelChoiceField(queryset=Site.objects.filter(category="dynamic"), disabled=True)
path = forms.CharField(max_length=255,
widget=forms.TextInput(attrs={"class": "form-control"}),
help_text="Enter a valid path starting with {}.".format(settings.WEB_ROOT),
validators=[path_validator])
def clean_path(self):
value = os.path.abspath(self.cleaned_data["path"].strip())
if self.instance.pk:
root_path = self.instance.site.path
else:
root_path = Site.objects.get(id=self.initial["site"]).path
if not os.path.isfile(value):
raise forms.ValidationError("The script you are trying to reference does not exist!")
if not value.startswith(root_path):
raise forms.ValidationError("The script you are trying to reference must be in the {} folder!".format(root_path))
return value
class Meta:
model = Process
fields = ["site", "path"]
class DatabaseForm(forms.ModelForm):
site = forms.ModelChoiceField(queryset=Site.objects.all(), disabled=True)
host = forms.ModelChoiceField(queryset=DatabaseHost.objects.all(), widget=forms.RadioSelect(), empty_label=None)
def __init__(self, user, *args, **kwargs):
super(DatabaseForm, self).__init__(*args, **kwargs)
self.initial["category"] = "postgresql"
if not user.is_superuser:
self.fields['site'].queryset = Site.objects.exclude(category="static").filter(group__users__id=user.id)
def save(self, commit=True):
instance = forms.ModelForm.save(self, commit=False)
instance.password = User.objects.make_random_password(length=24)
if commit:
flag = False
if instance.category == "postgresql":
flag = create_postgres_database(instance)
elif instance.category == "mysql":
flag = create_mysql_database(instance)
if flag:
instance.save()
else:
return None
create_config_files(instance.site)
if instance.site.category == "php":
reload_php_fpm()
elif instance.site.category == "dynamic":
update_supervisor()
return instance
class Meta:
model = Database
fields = ["site", "host"] | create_config_files(instance)
return instance | random_line_split |
SearchContainer.js | import React, { Component } from 'react';
import InfoSection from '../components/InfoSection';
import InfoSectionToggle from '../components/InfoSectionToggle';
class SearchContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
error: '',
showContent: true,
content: `The field below accepts search criteria for those on Odecee bench. Try searching by technologies like: 'node', or 'javascript' and you will see a list of candidates with those skill sets.`
};
}
onPressError() {
this.setState({
error: ''
});
}
onPressInfo() {
this.setState({
showContent: !this.state.showContent
});
}
renderError() {
if(this.state.error) |
}
renderInfoSection() {
return (
<InfoSection
revealContent={this.state.showContent}
content={this.state.content}
title={'Add Skill'}
/>
);
}
render() {
return (
<div>
{this.renderInfoSection()}
<section>
<InfoSectionToggle onPressInfo={this.onPressInfo.bind(this)} />
<ul className="input-list style-4 clearfix">
{this.renderError()}
<li>
<label className="search" htmlFor="search">Search: </label>
<input
type="text"
style={{width: '100%'}}
placeholder="Search"
ref="email"
id="search"
/>
</li>
</ul>
</section>
</div>
)
}
}
export default SearchContainer;
| {
return (
<li>
<div className="error">
<span className="message">{this.state.error}</span>
<span className="error-icon" onClick={this.onPressError.bind(this)}>
<i className="fa fa-times-circle"></i>
</span>
</div>
</li>
)
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.