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 |
|---|---|---|---|---|
mainTelemetryService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as Platform from 'vs/base/common/platform';
import * as uuid from 'vs/base/common/uuid';
import {AbstractTelemetryService} from 'vs/platform/telemetry/common/abstractTelemetryService';
import {ITelemetryService, ITelemetryServiceConfig} from 'vs/platform/telemetry/common/telemetry';
import {IdleMonitor, UserStatus} from 'vs/base/browser/idleMonitor';
export class MainTelemetryService extends AbstractTelemetryService implements ITelemetryService {
// how long of inactivity before a user is considered 'inactive' - 2 minutes
public static SOFT_IDLE_TIME = 2 * 60 * 1000;
public static IDLE_START_EVENT_NAME = 'UserIdleStart';
public static IDLE_STOP_EVENT_NAME = 'UserIdleStop';
private hardIdleMonitor: IdleMonitor;
private softIdleMonitor: IdleMonitor;
private eventCount: number;
private userIdHash: string;
private startTime: Date;
private optInFriendly: string[];
constructor(config?: ITelemetryServiceConfig) {
super(config);
this.sessionId = this.config.sessionID || (uuid.generateUuid() + Date.now());
if (this.config.enableHardIdle) {
this.hardIdleMonitor = new IdleMonitor();
}
if (this.config.enableSoftIdle) {
this.softIdleMonitor = new IdleMonitor(MainTelemetryService.SOFT_IDLE_TIME);
this.softIdleMonitor.addOneTimeActiveListener(() => this.onUserActive());
this.softIdleMonitor.addOneTimeIdleListener(() => this.onUserIdle());
}
this.eventCount = 0;
this.startTime = new Date();
//holds a cache of predefined events that can be sent regardress of user optin status
this.optInFriendly = ['optInStatus'];
}
private onUserIdle(): void {
this.publicLog(MainTelemetryService.IDLE_START_EVENT_NAME);
this.softIdleMonitor.addOneTimeIdleListener(() => this.onUserIdle());
}
private onUserActive(): void {
this.publicLog(MainTelemetryService.IDLE_STOP_EVENT_NAME);
this.softIdleMonitor.addOneTimeActiveListener(() => this.onUserActive());
}
public dispose(): void {
if (this.hardIdleMonitor) {
this.hardIdleMonitor.dispose();
}
if (this.softIdleMonitor) {
this.softIdleMonitor.dispose();
}
super.dispose();
}
protected | (eventName: string, data?: any): void {
if (this.hardIdleMonitor && this.hardIdleMonitor.getStatus() === UserStatus.Idle) {
return;
}
// don't send telemetry when channel is not enabled
if (!this.config.enableTelemetry) {
return;
}
// don't send events when the user is optout unless the event is flaged as optin friendly
if(!this.config.userOptIn && this.optInFriendly.indexOf(eventName) === -1) {
return;
}
this.eventCount++;
data = this.addCommonProperties(data);
let allAppenders = this.getAppenders();
for (let i = 0; i < allAppenders.length; i++) {
allAppenders[i].log(eventName, data);
}
}
protected addCommonProperties(data?: any): void {
data = data || {};
let eventDate: Date = new Date();
data['sessionID'] = this.sessionId;
data['timestamp'] = eventDate;
data['version'] = this.config.version;
data['userId'] = this.userIdHash;
data['commitHash'] = this.config.commitHash;
data['common.platform'] = Platform.Platform[Platform.platform];
data['common.timesincesessionstart'] = (eventDate.getTime() - this.startTime.getTime());
data['common.sequence'] = this.eventCount;
data['common.instanceId'] = this.instanceId;
data['common.machineId'] = this.machineId;
return data;
}
}
| handleEvent | identifier_name |
mainTelemetryService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as Platform from 'vs/base/common/platform';
import * as uuid from 'vs/base/common/uuid';
import {AbstractTelemetryService} from 'vs/platform/telemetry/common/abstractTelemetryService';
import {ITelemetryService, ITelemetryServiceConfig} from 'vs/platform/telemetry/common/telemetry';
import {IdleMonitor, UserStatus} from 'vs/base/browser/idleMonitor';
export class MainTelemetryService extends AbstractTelemetryService implements ITelemetryService {
// how long of inactivity before a user is considered 'inactive' - 2 minutes
public static SOFT_IDLE_TIME = 2 * 60 * 1000;
public static IDLE_START_EVENT_NAME = 'UserIdleStart';
public static IDLE_STOP_EVENT_NAME = 'UserIdleStop';
private hardIdleMonitor: IdleMonitor;
private softIdleMonitor: IdleMonitor;
private eventCount: number;
private userIdHash: string;
private startTime: Date;
private optInFriendly: string[];
constructor(config?: ITelemetryServiceConfig) {
super(config);
this.sessionId = this.config.sessionID || (uuid.generateUuid() + Date.now());
if (this.config.enableHardIdle) {
this.hardIdleMonitor = new IdleMonitor();
}
if (this.config.enableSoftIdle) {
this.softIdleMonitor = new IdleMonitor(MainTelemetryService.SOFT_IDLE_TIME);
this.softIdleMonitor.addOneTimeActiveListener(() => this.onUserActive());
this.softIdleMonitor.addOneTimeIdleListener(() => this.onUserIdle());
}
this.eventCount = 0;
this.startTime = new Date();
//holds a cache of predefined events that can be sent regardress of user optin status
this.optInFriendly = ['optInStatus'];
}
private onUserIdle(): void {
this.publicLog(MainTelemetryService.IDLE_START_EVENT_NAME);
this.softIdleMonitor.addOneTimeIdleListener(() => this.onUserIdle());
}
private onUserActive(): void {
this.publicLog(MainTelemetryService.IDLE_STOP_EVENT_NAME);
this.softIdleMonitor.addOneTimeActiveListener(() => this.onUserActive());
}
public dispose(): void {
if (this.hardIdleMonitor) {
this.hardIdleMonitor.dispose();
}
if (this.softIdleMonitor) {
this.softIdleMonitor.dispose();
}
super.dispose();
}
protected handleEvent(eventName: string, data?: any): void |
protected addCommonProperties(data?: any): void {
data = data || {};
let eventDate: Date = new Date();
data['sessionID'] = this.sessionId;
data['timestamp'] = eventDate;
data['version'] = this.config.version;
data['userId'] = this.userIdHash;
data['commitHash'] = this.config.commitHash;
data['common.platform'] = Platform.Platform[Platform.platform];
data['common.timesincesessionstart'] = (eventDate.getTime() - this.startTime.getTime());
data['common.sequence'] = this.eventCount;
data['common.instanceId'] = this.instanceId;
data['common.machineId'] = this.machineId;
return data;
}
}
| {
if (this.hardIdleMonitor && this.hardIdleMonitor.getStatus() === UserStatus.Idle) {
return;
}
// don't send telemetry when channel is not enabled
if (!this.config.enableTelemetry) {
return;
}
// don't send events when the user is optout unless the event is flaged as optin friendly
if(!this.config.userOptIn && this.optInFriendly.indexOf(eventName) === -1) {
return;
}
this.eventCount++;
data = this.addCommonProperties(data);
let allAppenders = this.getAppenders();
for (let i = 0; i < allAppenders.length; i++) {
allAppenders[i].log(eventName, data);
}
} | identifier_body |
mainTelemetryService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as Platform from 'vs/base/common/platform';
import * as uuid from 'vs/base/common/uuid';
import {AbstractTelemetryService} from 'vs/platform/telemetry/common/abstractTelemetryService';
import {ITelemetryService, ITelemetryServiceConfig} from 'vs/platform/telemetry/common/telemetry';
import {IdleMonitor, UserStatus} from 'vs/base/browser/idleMonitor';
export class MainTelemetryService extends AbstractTelemetryService implements ITelemetryService {
// how long of inactivity before a user is considered 'inactive' - 2 minutes
public static SOFT_IDLE_TIME = 2 * 60 * 1000;
public static IDLE_START_EVENT_NAME = 'UserIdleStart';
public static IDLE_STOP_EVENT_NAME = 'UserIdleStop';
private hardIdleMonitor: IdleMonitor;
private softIdleMonitor: IdleMonitor;
private eventCount: number;
private userIdHash: string; |
this.sessionId = this.config.sessionID || (uuid.generateUuid() + Date.now());
if (this.config.enableHardIdle) {
this.hardIdleMonitor = new IdleMonitor();
}
if (this.config.enableSoftIdle) {
this.softIdleMonitor = new IdleMonitor(MainTelemetryService.SOFT_IDLE_TIME);
this.softIdleMonitor.addOneTimeActiveListener(() => this.onUserActive());
this.softIdleMonitor.addOneTimeIdleListener(() => this.onUserIdle());
}
this.eventCount = 0;
this.startTime = new Date();
//holds a cache of predefined events that can be sent regardress of user optin status
this.optInFriendly = ['optInStatus'];
}
private onUserIdle(): void {
this.publicLog(MainTelemetryService.IDLE_START_EVENT_NAME);
this.softIdleMonitor.addOneTimeIdleListener(() => this.onUserIdle());
}
private onUserActive(): void {
this.publicLog(MainTelemetryService.IDLE_STOP_EVENT_NAME);
this.softIdleMonitor.addOneTimeActiveListener(() => this.onUserActive());
}
public dispose(): void {
if (this.hardIdleMonitor) {
this.hardIdleMonitor.dispose();
}
if (this.softIdleMonitor) {
this.softIdleMonitor.dispose();
}
super.dispose();
}
protected handleEvent(eventName: string, data?: any): void {
if (this.hardIdleMonitor && this.hardIdleMonitor.getStatus() === UserStatus.Idle) {
return;
}
// don't send telemetry when channel is not enabled
if (!this.config.enableTelemetry) {
return;
}
// don't send events when the user is optout unless the event is flaged as optin friendly
if(!this.config.userOptIn && this.optInFriendly.indexOf(eventName) === -1) {
return;
}
this.eventCount++;
data = this.addCommonProperties(data);
let allAppenders = this.getAppenders();
for (let i = 0; i < allAppenders.length; i++) {
allAppenders[i].log(eventName, data);
}
}
protected addCommonProperties(data?: any): void {
data = data || {};
let eventDate: Date = new Date();
data['sessionID'] = this.sessionId;
data['timestamp'] = eventDate;
data['version'] = this.config.version;
data['userId'] = this.userIdHash;
data['commitHash'] = this.config.commitHash;
data['common.platform'] = Platform.Platform[Platform.platform];
data['common.timesincesessionstart'] = (eventDate.getTime() - this.startTime.getTime());
data['common.sequence'] = this.eventCount;
data['common.instanceId'] = this.instanceId;
data['common.machineId'] = this.machineId;
return data;
}
} | private startTime: Date;
private optInFriendly: string[];
constructor(config?: ITelemetryServiceConfig) {
super(config); | random_line_split |
mainTelemetryService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import * as Platform from 'vs/base/common/platform';
import * as uuid from 'vs/base/common/uuid';
import {AbstractTelemetryService} from 'vs/platform/telemetry/common/abstractTelemetryService';
import {ITelemetryService, ITelemetryServiceConfig} from 'vs/platform/telemetry/common/telemetry';
import {IdleMonitor, UserStatus} from 'vs/base/browser/idleMonitor';
export class MainTelemetryService extends AbstractTelemetryService implements ITelemetryService {
// how long of inactivity before a user is considered 'inactive' - 2 minutes
public static SOFT_IDLE_TIME = 2 * 60 * 1000;
public static IDLE_START_EVENT_NAME = 'UserIdleStart';
public static IDLE_STOP_EVENT_NAME = 'UserIdleStop';
private hardIdleMonitor: IdleMonitor;
private softIdleMonitor: IdleMonitor;
private eventCount: number;
private userIdHash: string;
private startTime: Date;
private optInFriendly: string[];
constructor(config?: ITelemetryServiceConfig) {
super(config);
this.sessionId = this.config.sessionID || (uuid.generateUuid() + Date.now());
if (this.config.enableHardIdle) {
this.hardIdleMonitor = new IdleMonitor();
}
if (this.config.enableSoftIdle) {
this.softIdleMonitor = new IdleMonitor(MainTelemetryService.SOFT_IDLE_TIME);
this.softIdleMonitor.addOneTimeActiveListener(() => this.onUserActive());
this.softIdleMonitor.addOneTimeIdleListener(() => this.onUserIdle());
}
this.eventCount = 0;
this.startTime = new Date();
//holds a cache of predefined events that can be sent regardress of user optin status
this.optInFriendly = ['optInStatus'];
}
private onUserIdle(): void {
this.publicLog(MainTelemetryService.IDLE_START_EVENT_NAME);
this.softIdleMonitor.addOneTimeIdleListener(() => this.onUserIdle());
}
private onUserActive(): void {
this.publicLog(MainTelemetryService.IDLE_STOP_EVENT_NAME);
this.softIdleMonitor.addOneTimeActiveListener(() => this.onUserActive());
}
public dispose(): void {
if (this.hardIdleMonitor) {
this.hardIdleMonitor.dispose();
}
if (this.softIdleMonitor) {
this.softIdleMonitor.dispose();
}
super.dispose();
}
protected handleEvent(eventName: string, data?: any): void {
if (this.hardIdleMonitor && this.hardIdleMonitor.getStatus() === UserStatus.Idle) |
// don't send telemetry when channel is not enabled
if (!this.config.enableTelemetry) {
return;
}
// don't send events when the user is optout unless the event is flaged as optin friendly
if(!this.config.userOptIn && this.optInFriendly.indexOf(eventName) === -1) {
return;
}
this.eventCount++;
data = this.addCommonProperties(data);
let allAppenders = this.getAppenders();
for (let i = 0; i < allAppenders.length; i++) {
allAppenders[i].log(eventName, data);
}
}
protected addCommonProperties(data?: any): void {
data = data || {};
let eventDate: Date = new Date();
data['sessionID'] = this.sessionId;
data['timestamp'] = eventDate;
data['version'] = this.config.version;
data['userId'] = this.userIdHash;
data['commitHash'] = this.config.commitHash;
data['common.platform'] = Platform.Platform[Platform.platform];
data['common.timesincesessionstart'] = (eventDate.getTime() - this.startTime.getTime());
data['common.sequence'] = this.eventCount;
data['common.instanceId'] = this.instanceId;
data['common.machineId'] = this.machineId;
return data;
}
}
| {
return;
} | conditional_block |
job.rs | use std::collections::HashSet;
use std::net::SocketAddr;
use std::time;
use crate::control::cio;
use crate::torrent::Torrent;
use crate::util::UHashMap;
pub trait Job<T: cio::CIO> {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>);
}
pub struct TrackerUpdate;
impl<T: cio::CIO> Job<T> for TrackerUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
torrent.try_update_tracker();
}
}
}
pub struct UnchokeUpdate;
impl<T: cio::CIO> Job<T> for UnchokeUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
torrent.update_unchoked();
}
}
}
pub struct SessionUpdate;
impl<T: cio::CIO> Job<T> for SessionUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
if torrent.dirty() {
torrent.serialize();
}
}
}
}
pub struct TorrentTxUpdate {
piece_update: time::Instant,
active: UHashMap<bool>,
}
impl TorrentTxUpdate {
pub fn new() -> TorrentTxUpdate {
TorrentTxUpdate {
piece_update: time::Instant::now(),
active: UHashMap::default(),
}
}
}
impl<T: cio::CIO> Job<T> for TorrentTxUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (id, torrent) in torrents.iter_mut() {
let active = torrent.tick();
if active {
torrent.update_rpc_transfer();
torrent.update_rpc_peers();
// TODO: consider making tick triggered by on the fly validation
if self.piece_update.elapsed() > time::Duration::from_secs(30) |
}
if !torrent.complete() {
torrent.rank_peers();
}
if !self.active.contains_key(id) {
self.active.insert(*id, active);
}
let prev = self.active.get_mut(id).unwrap();
if *prev != active {
*prev = active;
torrent.announce_status();
}
}
self.active.retain(|id, _| torrents.contains_key(id));
}
}
pub struct PEXUpdate {
peers: UHashMap<HashSet<SocketAddr>>,
}
impl PEXUpdate {
pub fn new() -> PEXUpdate {
PEXUpdate {
peers: UHashMap::default(),
}
}
}
impl<T: cio::CIO> Job<T> for PEXUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (id, torrent) in torrents.iter_mut().filter(|&(_, ref t)| !t.info().private) {
if !self.peers.contains_key(id) {
self.peers.insert(*id, HashSet::new());
}
let (added, removed) = {
let peers: HashSet<_> = torrent.peers().values().map(|p| p.addr()).collect();
let prev = self.peers.get_mut(id).unwrap();
let mut add: Vec<_> = peers.difference(prev).cloned().collect();
let mut rem: Vec<_> = prev.difference(&peers).cloned().collect();
add.truncate(50);
rem.truncate(50 - add.len());
(add, rem)
};
torrent.update_pex(&added, &removed);
}
self.peers.retain(|id, _| torrents.contains_key(id));
}
}
| {
torrent.rpc_update_pieces();
self.piece_update = time::Instant::now();
} | conditional_block |
job.rs | use std::collections::HashSet;
use std::net::SocketAddr;
use std::time;
use crate::control::cio;
use crate::torrent::Torrent;
use crate::util::UHashMap;
pub trait Job<T: cio::CIO> {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>);
}
pub struct TrackerUpdate;
impl<T: cio::CIO> Job<T> for TrackerUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
torrent.try_update_tracker();
}
}
}
pub struct UnchokeUpdate;
impl<T: cio::CIO> Job<T> for UnchokeUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
torrent.update_unchoked();
}
}
}
pub struct SessionUpdate; |
impl<T: cio::CIO> Job<T> for SessionUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
if torrent.dirty() {
torrent.serialize();
}
}
}
}
pub struct TorrentTxUpdate {
piece_update: time::Instant,
active: UHashMap<bool>,
}
impl TorrentTxUpdate {
pub fn new() -> TorrentTxUpdate {
TorrentTxUpdate {
piece_update: time::Instant::now(),
active: UHashMap::default(),
}
}
}
impl<T: cio::CIO> Job<T> for TorrentTxUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (id, torrent) in torrents.iter_mut() {
let active = torrent.tick();
if active {
torrent.update_rpc_transfer();
torrent.update_rpc_peers();
// TODO: consider making tick triggered by on the fly validation
if self.piece_update.elapsed() > time::Duration::from_secs(30) {
torrent.rpc_update_pieces();
self.piece_update = time::Instant::now();
}
}
if !torrent.complete() {
torrent.rank_peers();
}
if !self.active.contains_key(id) {
self.active.insert(*id, active);
}
let prev = self.active.get_mut(id).unwrap();
if *prev != active {
*prev = active;
torrent.announce_status();
}
}
self.active.retain(|id, _| torrents.contains_key(id));
}
}
pub struct PEXUpdate {
peers: UHashMap<HashSet<SocketAddr>>,
}
impl PEXUpdate {
pub fn new() -> PEXUpdate {
PEXUpdate {
peers: UHashMap::default(),
}
}
}
impl<T: cio::CIO> Job<T> for PEXUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (id, torrent) in torrents.iter_mut().filter(|&(_, ref t)| !t.info().private) {
if !self.peers.contains_key(id) {
self.peers.insert(*id, HashSet::new());
}
let (added, removed) = {
let peers: HashSet<_> = torrent.peers().values().map(|p| p.addr()).collect();
let prev = self.peers.get_mut(id).unwrap();
let mut add: Vec<_> = peers.difference(prev).cloned().collect();
let mut rem: Vec<_> = prev.difference(&peers).cloned().collect();
add.truncate(50);
rem.truncate(50 - add.len());
(add, rem)
};
torrent.update_pex(&added, &removed);
}
self.peers.retain(|id, _| torrents.contains_key(id));
}
} | random_line_split | |
job.rs | use std::collections::HashSet;
use std::net::SocketAddr;
use std::time;
use crate::control::cio;
use crate::torrent::Torrent;
use crate::util::UHashMap;
pub trait Job<T: cio::CIO> {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>);
}
pub struct TrackerUpdate;
impl<T: cio::CIO> Job<T> for TrackerUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
torrent.try_update_tracker();
}
}
}
pub struct UnchokeUpdate;
impl<T: cio::CIO> Job<T> for UnchokeUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
torrent.update_unchoked();
}
}
}
pub struct SessionUpdate;
impl<T: cio::CIO> Job<T> for SessionUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (_, torrent) in torrents.iter_mut() {
if torrent.dirty() {
torrent.serialize();
}
}
}
}
pub struct | {
piece_update: time::Instant,
active: UHashMap<bool>,
}
impl TorrentTxUpdate {
pub fn new() -> TorrentTxUpdate {
TorrentTxUpdate {
piece_update: time::Instant::now(),
active: UHashMap::default(),
}
}
}
impl<T: cio::CIO> Job<T> for TorrentTxUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (id, torrent) in torrents.iter_mut() {
let active = torrent.tick();
if active {
torrent.update_rpc_transfer();
torrent.update_rpc_peers();
// TODO: consider making tick triggered by on the fly validation
if self.piece_update.elapsed() > time::Duration::from_secs(30) {
torrent.rpc_update_pieces();
self.piece_update = time::Instant::now();
}
}
if !torrent.complete() {
torrent.rank_peers();
}
if !self.active.contains_key(id) {
self.active.insert(*id, active);
}
let prev = self.active.get_mut(id).unwrap();
if *prev != active {
*prev = active;
torrent.announce_status();
}
}
self.active.retain(|id, _| torrents.contains_key(id));
}
}
pub struct PEXUpdate {
peers: UHashMap<HashSet<SocketAddr>>,
}
impl PEXUpdate {
pub fn new() -> PEXUpdate {
PEXUpdate {
peers: UHashMap::default(),
}
}
}
impl<T: cio::CIO> Job<T> for PEXUpdate {
fn update(&mut self, torrents: &mut UHashMap<Torrent<T>>) {
for (id, torrent) in torrents.iter_mut().filter(|&(_, ref t)| !t.info().private) {
if !self.peers.contains_key(id) {
self.peers.insert(*id, HashSet::new());
}
let (added, removed) = {
let peers: HashSet<_> = torrent.peers().values().map(|p| p.addr()).collect();
let prev = self.peers.get_mut(id).unwrap();
let mut add: Vec<_> = peers.difference(prev).cloned().collect();
let mut rem: Vec<_> = prev.difference(&peers).cloned().collect();
add.truncate(50);
rem.truncate(50 - add.len());
(add, rem)
};
torrent.update_pex(&added, &removed);
}
self.peers.retain(|id, _| torrents.contains_key(id));
}
}
| TorrentTxUpdate | identifier_name |
2_4_1_a.rs | /*
2.4.6:
a) S -> + S S | - S S | a
$> rustc -o parser 2_4_1_a.rs
$> ./parser
*/
static CODE: &'static str = "-+aa-aa";
pub fn sa(mut head: i32) -> i32 |
fn main() {
let head = sa(0);
if head as usize!= CODE.len() {
panic!("parsed {} chars, but totally {} chars", head, CODE.len());
}
}
| {
match CODE.chars().nth(head as usize){
None => {
panic!("missing required element!");
},
Some('a') => {
head += 1;
},
Some('+') | Some('-') => {
head += 1;
head = sa(head);
head = sa(head);
},
_ => { panic!("undefind element!"); }
}
head
} | identifier_body |
2_4_1_a.rs | /*
2.4.6:
a) S -> + S S | - S S | a
$> rustc -o parser 2_4_1_a.rs
$> ./parser
*/
static CODE: &'static str = "-+aa-aa";
pub fn sa(mut head: i32) -> i32 {
match CODE.chars().nth(head as usize){
None => {
panic!("missing required element!");
},
Some('a') => {
head += 1;
},
Some('+') | Some('-') => {
head += 1;
head = sa(head);
head = sa(head);
},
_ => { panic!("undefind element!"); }
}
head
}
fn main() {
let head = sa(0);
if head as usize!= CODE.len() |
}
| {
panic!("parsed {} chars, but totally {} chars", head, CODE.len());
} | conditional_block |
2_4_1_a.rs | /*
2.4.6:
a) S -> + S S | - S S | a
$> rustc -o parser 2_4_1_a.rs
$> ./parser
*/
static CODE: &'static str = "-+aa-aa";
pub fn sa(mut head: i32) -> i32 {
match CODE.chars().nth(head as usize){
None => {
panic!("missing required element!");
},
Some('a') => {
head += 1;
},
Some('+') | Some('-') => {
head += 1;
head = sa(head);
head = sa(head);
},
_ => { panic!("undefind element!"); }
}
head
}
fn | () {
let head = sa(0);
if head as usize!= CODE.len() {
panic!("parsed {} chars, but totally {} chars", head, CODE.len());
}
}
| main | identifier_name |
2_4_1_a.rs | /*
2.4.6:
a) S -> + S S | - S S | a
$> rustc -o parser 2_4_1_a.rs
$> ./parser
*/
static CODE: &'static str = "-+aa-aa";
pub fn sa(mut head: i32) -> i32 {
match CODE.chars().nth(head as usize){
None => {
panic!("missing required element!");
},
Some('a') => {
head += 1;
},
Some('+') | Some('-') => {
head += 1;
head = sa(head);
head = sa(head); | },
_ => { panic!("undefind element!"); }
}
head
}
fn main() {
let head = sa(0);
if head as usize!= CODE.len() {
panic!("parsed {} chars, but totally {} chars", head, CODE.len());
}
} | random_line_split | |
start.js | 'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`);
console.log();
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) |
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
| {
return console.log(err);
} | conditional_block |
start.js | 'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
| });
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const config = require('../config/webpack.config.dev');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`);
console.log();
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
choosePort(HOST, DEFAULT_PORT)
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const urls = prepareUrls(protocol, HOST, port);
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler(webpack, config, appName, urls, useYarn);
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web sever.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
}); | // Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err; | random_line_split |
team.ts | const team = {
sidemenu: 'Side menu',
sidemenuTooltip: 'The vertical menu bar on the left side of the screen, the top half of which can be customized by team',
subTitle: 'Manage team members & settings',
add: 'Add team',
name: 'Team name',
addMember: 'Add member',
member: 'Team member',
memberRole: 'Member role',
editMember: 'Edit team member',
deleteMember: 'Delete team member',
deleteConfirmBody: 'Are you sure you want to delete this member?',
menuManage:'Menu manage',
addMenuTitle: `Add menu item around {title}`,
updateMenuTitle: `Update menu item {title}`,
uidTooltip: "press key 'f' to open search board and copy it",
addToPosition: 'Add to position',
asBrother: 'As brother',
asChild: 'As child',
iconTooltip: `You can find icons in https://iconscout.com/unicons/explore/line`,
menuName: 'Menu name',
menuSubUrl: 'Menu sub url',
menuUrlTooltip: 'Must be a sub url,for example, you can use /test ,but cannot use /test/ok',
delMenuConfirmTitle: `Delete menu item`,
delMenuConfirmBody: `Are you sure you want to delete this menu item? all of its children will be removed too!`,
setting: 'Team setting',
dashboardPermission: 'Dashboard permission',
transfer: 'Transfer team', | toMember: 'To member',
leave: 'Leave team',
delete: 'Delete team',
isPublicTips: 'Set to public means users not in this team can also use this sidemenu',
menuNotExist: 'Target sidemenu is not exist',
menuNotPublic: 'Target sidement is not public',
mainTeamTips: 'Every user will be in global team,this team cannot be changed',
}
export default team | random_line_split | |
error.rs | use std::{error, fmt, str};
use string::SafeString; | pub struct Error {
desc: SafeString,
}
impl Error {
/// Creates a new Error.
pub fn new(desc: &str) -> Error {
Self {
desc: SafeString::from(desc),
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error: {}", error::Error::description(self))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", error::Error::description(self))
}
}
impl error::Error for Error {
fn description(&self) -> &str {
&self.desc
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error;
#[test]
fn description() {
let msg = "out of bounds";
let err = Error::new(msg);
assert_eq!(error::Error::description(&err), msg);
}
} |
/// An error object.
#[repr(C)]
#[derive(Clone, PartialEq)] | random_line_split |
error.rs | use std::{error, fmt, str};
use string::SafeString;
/// An error object.
#[repr(C)]
#[derive(Clone, PartialEq)]
pub struct Error {
desc: SafeString,
}
impl Error {
/// Creates a new Error.
pub fn new(desc: &str) -> Error {
Self {
desc: SafeString::from(desc),
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error: {}", error::Error::description(self))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", error::Error::description(self))
}
}
impl error::Error for Error {
fn description(&self) -> &str {
&self.desc
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error;
#[test]
fn | () {
let msg = "out of bounds";
let err = Error::new(msg);
assert_eq!(error::Error::description(&err), msg);
}
}
| description | identifier_name |
environment.py | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_dir": 'imgs/original/',
"header_img_url": 'imgs/headers/',
"scaled_img_url": 'imgs/scaled/',
"original_img_url": 'imgs/original/',
"template_dir": join(script_dir,'templates'),
"max_article_img_width": 710,
"max_avatar_width": 710,
"database_file": "database.yml",
"static_dir": join(script_dir,'static'),
"copyright_msg": None,
"extra_links": [],
"import_to_discourse": False,
"strapline": None,
}
config = dict()
def getConfig():
if not config:
raise RuntimeError('config not loaded yet')
return config
def loadConfig(yml_filepath):
config.update(defaults)
with open(yml_filepath) as f:
patch = yaml.load(f.read())
config.update(patch)
# make paths absolute
config['header_img_dir'] = join(config['output_dir'],config['header_img_dir'])
config['scaled_img_dir'] = join(config['output_dir'],config['scaled_img_dir'])
config['original_img_dir'] = join(config['output_dir'],config['original_img_dir'])
config['database_file'] = join(config['output_dir'],config['database_file'])
def makeDirs():
if not config: |
if not isdir(path):
makedirs(path) | raise RuntimeError('config not loaded yet')
for key in ['header_img_dir','scaled_img_dir','original_img_dir']:
path = config[key] | random_line_split |
environment.py | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_dir": 'imgs/original/',
"header_img_url": 'imgs/headers/',
"scaled_img_url": 'imgs/scaled/',
"original_img_url": 'imgs/original/',
"template_dir": join(script_dir,'templates'),
"max_article_img_width": 710,
"max_avatar_width": 710,
"database_file": "database.yml",
"static_dir": join(script_dir,'static'),
"copyright_msg": None,
"extra_links": [],
"import_to_discourse": False,
"strapline": None,
}
config = dict()
def getConfig():
if not config:
raise RuntimeError('config not loaded yet')
return config
def loadConfig(yml_filepath):
config.update(defaults)
with open(yml_filepath) as f:
patch = yaml.load(f.read())
config.update(patch)
# make paths absolute
config['header_img_dir'] = join(config['output_dir'],config['header_img_dir'])
config['scaled_img_dir'] = join(config['output_dir'],config['scaled_img_dir'])
config['original_img_dir'] = join(config['output_dir'],config['original_img_dir'])
config['database_file'] = join(config['output_dir'],config['database_file'])
def makeDirs():
if not config:
raise RuntimeError('config not loaded yet')
for key in ['header_img_dir','scaled_img_dir','original_img_dir']:
| path = config[key]
if not isdir(path):
makedirs(path) | conditional_block | |
environment.py | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_dir": 'imgs/original/',
"header_img_url": 'imgs/headers/',
"scaled_img_url": 'imgs/scaled/',
"original_img_url": 'imgs/original/',
"template_dir": join(script_dir,'templates'),
"max_article_img_width": 710,
"max_avatar_width": 710,
"database_file": "database.yml",
"static_dir": join(script_dir,'static'),
"copyright_msg": None,
"extra_links": [],
"import_to_discourse": False,
"strapline": None,
}
config = dict()
def | ():
if not config:
raise RuntimeError('config not loaded yet')
return config
def loadConfig(yml_filepath):
config.update(defaults)
with open(yml_filepath) as f:
patch = yaml.load(f.read())
config.update(patch)
# make paths absolute
config['header_img_dir'] = join(config['output_dir'],config['header_img_dir'])
config['scaled_img_dir'] = join(config['output_dir'],config['scaled_img_dir'])
config['original_img_dir'] = join(config['output_dir'],config['original_img_dir'])
config['database_file'] = join(config['output_dir'],config['database_file'])
def makeDirs():
if not config:
raise RuntimeError('config not loaded yet')
for key in ['header_img_dir','scaled_img_dir','original_img_dir']:
path = config[key]
if not isdir(path):
makedirs(path)
| getConfig | identifier_name |
environment.py | import yaml
from os import makedirs
from os.path import join,dirname,realpath,isdir
script_dir = dirname(realpath(__file__))
default_yml_filepath = join(script_dir,'defaults.yml')
defaults = {
"output_dir": 'output',
"header_img_dir": 'imgs/headers/',
"scaled_img_dir": 'imgs/scaled/',
"original_img_dir": 'imgs/original/',
"header_img_url": 'imgs/headers/',
"scaled_img_url": 'imgs/scaled/',
"original_img_url": 'imgs/original/',
"template_dir": join(script_dir,'templates'),
"max_article_img_width": 710,
"max_avatar_width": 710,
"database_file": "database.yml",
"static_dir": join(script_dir,'static'),
"copyright_msg": None,
"extra_links": [],
"import_to_discourse": False,
"strapline": None,
}
config = dict()
def getConfig():
|
def loadConfig(yml_filepath):
config.update(defaults)
with open(yml_filepath) as f:
patch = yaml.load(f.read())
config.update(patch)
# make paths absolute
config['header_img_dir'] = join(config['output_dir'],config['header_img_dir'])
config['scaled_img_dir'] = join(config['output_dir'],config['scaled_img_dir'])
config['original_img_dir'] = join(config['output_dir'],config['original_img_dir'])
config['database_file'] = join(config['output_dir'],config['database_file'])
def makeDirs():
if not config:
raise RuntimeError('config not loaded yet')
for key in ['header_img_dir','scaled_img_dir','original_img_dir']:
path = config[key]
if not isdir(path):
makedirs(path)
| if not config:
raise RuntimeError('config not loaded yet')
return config | identifier_body |
binder.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class APIMethod(object):
path = config['path']
payload_type = config.get('payload_type', None)
payload_list = config.get('payload_list', False)
allowed_param = config.get('allowed_param', [])
method = config.get('method', 'GET')
require_auth = config.get('require_auth', False)
search_api = config.get('search_api', False)
use_cache = config.get('use_cache', True)
def __init__(self, api, args, kargs):
# If authentication is required and no credentials
# are provided, throw an error.
if self.require_auth and not api.auth:
raise TweepError('Authentication required!')
self.api = api
self.post_data = kargs.pop('post_data', None)
self.retry_count = kargs.pop('retry_count', api.retry_count)
self.retry_delay = kargs.pop('retry_delay', api.retry_delay)
self.retry_errors = kargs.pop('retry_errors', api.retry_errors)
self.headers = kargs.pop('headers', {})
self.build_parameters(args, kargs)
# Pick correct URL root to use
if self.search_api:
self.api_root = api.search_root
else:
self.api_root = api.api_root
# Perform any path variable substitution
self.build_path()
if api.secure:
self.scheme = 'https://'
else:
self.scheme = 'http://'
if self.search_api:
self.host = api.search_host
else:
self.host = api.host
# Manually set Host header to fix an issue in python 2.5
# or older where Host is set including the 443 port.
# This causes Twitter to issue 301 redirect.
# See Issue https://github.com/tweepy/tweepy/issues/12
self.headers['Host'] = self.host
def build_parameters(self, args, kargs):
self.parameters = {}
for idx, arg in enumerate(args):
if arg is None:
continue
try:
self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg)
except IndexError:
raise TweepError('Too many parameters supplied!')
for k, arg in kargs.items():
if arg is None:
continue
if k in self.parameters:
raise TweepError('Multiple values for parameter %s supplied!' % k)
self.parameters[k] = convert_to_utf8_str(arg)
def build_path(self):
for variable in re_path_template.findall(self.path):
name = variable.strip('{}')
if name == 'user' and 'user' not in self.parameters and self.api.auth:
# No 'user' parameter provided, fetch it from Auth instead.
value = self.api.auth.get_username()
else:
|
self.path = self.path.replace(variable, value)
def execute(self):
# Build the request URL
url = self.api_root + self.path
if len(self.parameters):
url = '%s?%s' % (url, urllib.urlencode(self.parameters))
# Query the cache if one is available
# and this request uses a GET method.
if self.use_cache and self.api.cache and self.method == 'GET':
cache_result = self.api.cache.get(url)
# if cache result found and not expired, return it
if cache_result:
# must restore api reference
if isinstance(cache_result, list):
for result in cache_result:
if isinstance(result, Model):
result._api = self.api
else:
if isinstance(cache_result, Model):
cache_result._api = self.api
return cache_result
# Continue attempting request until successful
# or maximum number of retries is reached.
retries_performed = 0
while retries_performed < self.retry_count + 1:
# Open connection
# FIXME: add timeout
if self.api.secure:
conn = httplib.HTTPSConnection(self.host)
else:
conn = httplib.HTTPConnection(self.host)
# Apply authentication
if self.api.auth:
self.api.auth.apply_auth(
self.scheme + self.host + url,
self.method, self.headers, self.parameters
)
# Execute request
try:
conn.request(self.method, url, headers=self.headers, body=self.post_data)
resp = conn.getresponse()
except Exception, e:
raise TweepError('Failed to send request: %s' % e)
# Exit request loop if non-retry error code
if self.retry_errors:
if resp.status not in self.retry_errors: break
else:
if resp.status == 200: break
# Sleep before retrying request again
time.sleep(self.retry_delay)
retries_performed += 1
# If an error was returned, throw an exception
self.api.last_response = resp
if resp.status != 200:
try:
error_msg = self.api.parser.parse_error(resp.read())
except Exception:
error_msg = "Twitter error response: status code = %s" % resp.status
raise TweepError(error_msg, resp)
# Parse the response payload
result = self.api.parser.parse(self, resp.read())
conn.close()
# Store result into cache if one is available.
if self.use_cache and self.api.cache and self.method == 'GET' and result:
self.api.cache.store(url, result)
return result
def _call(api, *args, **kargs):
method = APIMethod(api, args, kargs)
return method.execute()
# Set pagination mode
if 'cursor' in APIMethod.allowed_param:
_call.pagination_mode = 'cursor'
elif 'page' in APIMethod.allowed_param:
_call.pagination_mode = 'page'
return _call
| try:
value = urllib.quote(self.parameters[name])
except KeyError:
raise TweepError('No parameter value found for path variable: %s' % name)
del self.parameters[name] | conditional_block |
binder.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class APIMethod(object):
path = config['path']
payload_type = config.get('payload_type', None)
payload_list = config.get('payload_list', False)
allowed_param = config.get('allowed_param', [])
method = config.get('method', 'GET')
require_auth = config.get('require_auth', False)
search_api = config.get('search_api', False)
use_cache = config.get('use_cache', True)
def __init__(self, api, args, kargs):
# If authentication is required and no credentials
# are provided, throw an error.
if self.require_auth and not api.auth:
raise TweepError('Authentication required!')
self.api = api
self.post_data = kargs.pop('post_data', None)
self.retry_count = kargs.pop('retry_count', api.retry_count)
self.retry_delay = kargs.pop('retry_delay', api.retry_delay)
self.retry_errors = kargs.pop('retry_errors', api.retry_errors)
self.headers = kargs.pop('headers', {})
self.build_parameters(args, kargs)
# Pick correct URL root to use
if self.search_api:
self.api_root = api.search_root
else:
self.api_root = api.api_root
# Perform any path variable substitution
self.build_path()
if api.secure:
self.scheme = 'https://'
else:
self.scheme = 'http://'
if self.search_api:
self.host = api.search_host
else:
self.host = api.host
# Manually set Host header to fix an issue in python 2.5
# or older where Host is set including the 443 port.
# This causes Twitter to issue 301 redirect.
# See Issue https://github.com/tweepy/tweepy/issues/12
self.headers['Host'] = self.host
def build_parameters(self, args, kargs):
self.parameters = {}
for idx, arg in enumerate(args):
if arg is None:
continue
try:
self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg)
except IndexError:
raise TweepError('Too many parameters supplied!')
for k, arg in kargs.items():
if arg is None:
continue
if k in self.parameters:
raise TweepError('Multiple values for parameter %s supplied!' % k)
self.parameters[k] = convert_to_utf8_str(arg)
def build_path(self):
for variable in re_path_template.findall(self.path):
name = variable.strip('{}')
if name == 'user' and 'user' not in self.parameters and self.api.auth:
# No 'user' parameter provided, fetch it from Auth instead.
value = self.api.auth.get_username()
else:
try:
value = urllib.quote(self.parameters[name])
except KeyError:
raise TweepError('No parameter value found for path variable: %s' % name)
del self.parameters[name]
self.path = self.path.replace(variable, value)
def execute(self):
# Build the request URL
url = self.api_root + self.path
if len(self.parameters):
url = '%s?%s' % (url, urllib.urlencode(self.parameters))
# Query the cache if one is available
# and this request uses a GET method.
if self.use_cache and self.api.cache and self.method == 'GET':
cache_result = self.api.cache.get(url)
# if cache result found and not expired, return it
if cache_result:
# must restore api reference
if isinstance(cache_result, list):
for result in cache_result:
if isinstance(result, Model):
result._api = self.api
else:
if isinstance(cache_result, Model):
cache_result._api = self.api
return cache_result
# Continue attempting request until successful
# or maximum number of retries is reached.
retries_performed = 0
while retries_performed < self.retry_count + 1:
# Open connection
# FIXME: add timeout
if self.api.secure:
conn = httplib.HTTPSConnection(self.host)
else:
conn = httplib.HTTPConnection(self.host)
# Apply authentication
if self.api.auth:
self.api.auth.apply_auth(
self.scheme + self.host + url,
self.method, self.headers, self.parameters
)
# Execute request
try:
conn.request(self.method, url, headers=self.headers, body=self.post_data) | # Exit request loop if non-retry error code
if self.retry_errors:
if resp.status not in self.retry_errors: break
else:
if resp.status == 200: break
# Sleep before retrying request again
time.sleep(self.retry_delay)
retries_performed += 1
# If an error was returned, throw an exception
self.api.last_response = resp
if resp.status != 200:
try:
error_msg = self.api.parser.parse_error(resp.read())
except Exception:
error_msg = "Twitter error response: status code = %s" % resp.status
raise TweepError(error_msg, resp)
# Parse the response payload
result = self.api.parser.parse(self, resp.read())
conn.close()
# Store result into cache if one is available.
if self.use_cache and self.api.cache and self.method == 'GET' and result:
self.api.cache.store(url, result)
return result
def _call(api, *args, **kargs):
method = APIMethod(api, args, kargs)
return method.execute()
# Set pagination mode
if 'cursor' in APIMethod.allowed_param:
_call.pagination_mode = 'cursor'
elif 'page' in APIMethod.allowed_param:
_call.pagination_mode = 'page'
return _call | resp = conn.getresponse()
except Exception, e:
raise TweepError('Failed to send request: %s' % e)
| random_line_split |
binder.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
| class APIMethod(object):
path = config['path']
payload_type = config.get('payload_type', None)
payload_list = config.get('payload_list', False)
allowed_param = config.get('allowed_param', [])
method = config.get('method', 'GET')
require_auth = config.get('require_auth', False)
search_api = config.get('search_api', False)
use_cache = config.get('use_cache', True)
def __init__(self, api, args, kargs):
# If authentication is required and no credentials
# are provided, throw an error.
if self.require_auth and not api.auth:
raise TweepError('Authentication required!')
self.api = api
self.post_data = kargs.pop('post_data', None)
self.retry_count = kargs.pop('retry_count', api.retry_count)
self.retry_delay = kargs.pop('retry_delay', api.retry_delay)
self.retry_errors = kargs.pop('retry_errors', api.retry_errors)
self.headers = kargs.pop('headers', {})
self.build_parameters(args, kargs)
# Pick correct URL root to use
if self.search_api:
self.api_root = api.search_root
else:
self.api_root = api.api_root
# Perform any path variable substitution
self.build_path()
if api.secure:
self.scheme = 'https://'
else:
self.scheme = 'http://'
if self.search_api:
self.host = api.search_host
else:
self.host = api.host
# Manually set Host header to fix an issue in python 2.5
# or older where Host is set including the 443 port.
# This causes Twitter to issue 301 redirect.
# See Issue https://github.com/tweepy/tweepy/issues/12
self.headers['Host'] = self.host
def build_parameters(self, args, kargs):
self.parameters = {}
for idx, arg in enumerate(args):
if arg is None:
continue
try:
self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg)
except IndexError:
raise TweepError('Too many parameters supplied!')
for k, arg in kargs.items():
if arg is None:
continue
if k in self.parameters:
raise TweepError('Multiple values for parameter %s supplied!' % k)
self.parameters[k] = convert_to_utf8_str(arg)
def build_path(self):
for variable in re_path_template.findall(self.path):
name = variable.strip('{}')
if name == 'user' and 'user' not in self.parameters and self.api.auth:
# No 'user' parameter provided, fetch it from Auth instead.
value = self.api.auth.get_username()
else:
try:
value = urllib.quote(self.parameters[name])
except KeyError:
raise TweepError('No parameter value found for path variable: %s' % name)
del self.parameters[name]
self.path = self.path.replace(variable, value)
def execute(self):
# Build the request URL
url = self.api_root + self.path
if len(self.parameters):
url = '%s?%s' % (url, urllib.urlencode(self.parameters))
# Query the cache if one is available
# and this request uses a GET method.
if self.use_cache and self.api.cache and self.method == 'GET':
cache_result = self.api.cache.get(url)
# if cache result found and not expired, return it
if cache_result:
# must restore api reference
if isinstance(cache_result, list):
for result in cache_result:
if isinstance(result, Model):
result._api = self.api
else:
if isinstance(cache_result, Model):
cache_result._api = self.api
return cache_result
# Continue attempting request until successful
# or maximum number of retries is reached.
retries_performed = 0
while retries_performed < self.retry_count + 1:
# Open connection
# FIXME: add timeout
if self.api.secure:
conn = httplib.HTTPSConnection(self.host)
else:
conn = httplib.HTTPConnection(self.host)
# Apply authentication
if self.api.auth:
self.api.auth.apply_auth(
self.scheme + self.host + url,
self.method, self.headers, self.parameters
)
# Execute request
try:
conn.request(self.method, url, headers=self.headers, body=self.post_data)
resp = conn.getresponse()
except Exception, e:
raise TweepError('Failed to send request: %s' % e)
# Exit request loop if non-retry error code
if self.retry_errors:
if resp.status not in self.retry_errors: break
else:
if resp.status == 200: break
# Sleep before retrying request again
time.sleep(self.retry_delay)
retries_performed += 1
# If an error was returned, throw an exception
self.api.last_response = resp
if resp.status != 200:
try:
error_msg = self.api.parser.parse_error(resp.read())
except Exception:
error_msg = "Twitter error response: status code = %s" % resp.status
raise TweepError(error_msg, resp)
# Parse the response payload
result = self.api.parser.parse(self, resp.read())
conn.close()
# Store result into cache if one is available.
if self.use_cache and self.api.cache and self.method == 'GET' and result:
self.api.cache.store(url, result)
return result
def _call(api, *args, **kargs):
method = APIMethod(api, args, kargs)
return method.execute()
# Set pagination mode
if 'cursor' in APIMethod.allowed_param:
_call.pagination_mode = 'cursor'
elif 'page' in APIMethod.allowed_param:
_call.pagination_mode = 'page'
return _call | identifier_body | |
binder.py | # Tweepy
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def | (**config):
class APIMethod(object):
path = config['path']
payload_type = config.get('payload_type', None)
payload_list = config.get('payload_list', False)
allowed_param = config.get('allowed_param', [])
method = config.get('method', 'GET')
require_auth = config.get('require_auth', False)
search_api = config.get('search_api', False)
use_cache = config.get('use_cache', True)
def __init__(self, api, args, kargs):
# If authentication is required and no credentials
# are provided, throw an error.
if self.require_auth and not api.auth:
raise TweepError('Authentication required!')
self.api = api
self.post_data = kargs.pop('post_data', None)
self.retry_count = kargs.pop('retry_count', api.retry_count)
self.retry_delay = kargs.pop('retry_delay', api.retry_delay)
self.retry_errors = kargs.pop('retry_errors', api.retry_errors)
self.headers = kargs.pop('headers', {})
self.build_parameters(args, kargs)
# Pick correct URL root to use
if self.search_api:
self.api_root = api.search_root
else:
self.api_root = api.api_root
# Perform any path variable substitution
self.build_path()
if api.secure:
self.scheme = 'https://'
else:
self.scheme = 'http://'
if self.search_api:
self.host = api.search_host
else:
self.host = api.host
# Manually set Host header to fix an issue in python 2.5
# or older where Host is set including the 443 port.
# This causes Twitter to issue 301 redirect.
# See Issue https://github.com/tweepy/tweepy/issues/12
self.headers['Host'] = self.host
def build_parameters(self, args, kargs):
self.parameters = {}
for idx, arg in enumerate(args):
if arg is None:
continue
try:
self.parameters[self.allowed_param[idx]] = convert_to_utf8_str(arg)
except IndexError:
raise TweepError('Too many parameters supplied!')
for k, arg in kargs.items():
if arg is None:
continue
if k in self.parameters:
raise TweepError('Multiple values for parameter %s supplied!' % k)
self.parameters[k] = convert_to_utf8_str(arg)
def build_path(self):
for variable in re_path_template.findall(self.path):
name = variable.strip('{}')
if name == 'user' and 'user' not in self.parameters and self.api.auth:
# No 'user' parameter provided, fetch it from Auth instead.
value = self.api.auth.get_username()
else:
try:
value = urllib.quote(self.parameters[name])
except KeyError:
raise TweepError('No parameter value found for path variable: %s' % name)
del self.parameters[name]
self.path = self.path.replace(variable, value)
def execute(self):
# Build the request URL
url = self.api_root + self.path
if len(self.parameters):
url = '%s?%s' % (url, urllib.urlencode(self.parameters))
# Query the cache if one is available
# and this request uses a GET method.
if self.use_cache and self.api.cache and self.method == 'GET':
cache_result = self.api.cache.get(url)
# if cache result found and not expired, return it
if cache_result:
# must restore api reference
if isinstance(cache_result, list):
for result in cache_result:
if isinstance(result, Model):
result._api = self.api
else:
if isinstance(cache_result, Model):
cache_result._api = self.api
return cache_result
# Continue attempting request until successful
# or maximum number of retries is reached.
retries_performed = 0
while retries_performed < self.retry_count + 1:
# Open connection
# FIXME: add timeout
if self.api.secure:
conn = httplib.HTTPSConnection(self.host)
else:
conn = httplib.HTTPConnection(self.host)
# Apply authentication
if self.api.auth:
self.api.auth.apply_auth(
self.scheme + self.host + url,
self.method, self.headers, self.parameters
)
# Execute request
try:
conn.request(self.method, url, headers=self.headers, body=self.post_data)
resp = conn.getresponse()
except Exception, e:
raise TweepError('Failed to send request: %s' % e)
# Exit request loop if non-retry error code
if self.retry_errors:
if resp.status not in self.retry_errors: break
else:
if resp.status == 200: break
# Sleep before retrying request again
time.sleep(self.retry_delay)
retries_performed += 1
# If an error was returned, throw an exception
self.api.last_response = resp
if resp.status != 200:
try:
error_msg = self.api.parser.parse_error(resp.read())
except Exception:
error_msg = "Twitter error response: status code = %s" % resp.status
raise TweepError(error_msg, resp)
# Parse the response payload
result = self.api.parser.parse(self, resp.read())
conn.close()
# Store result into cache if one is available.
if self.use_cache and self.api.cache and self.method == 'GET' and result:
self.api.cache.store(url, result)
return result
def _call(api, *args, **kargs):
method = APIMethod(api, args, kargs)
return method.execute()
# Set pagination mode
if 'cursor' in APIMethod.allowed_param:
_call.pagination_mode = 'cursor'
elif 'page' in APIMethod.allowed_param:
_call.pagination_mode = 'page'
return _call
| bind_api | identifier_name |
task.rs | use std::collections::HashMap;
use std::str::FromStr;
use author::Author;
#[derive(Debug)]
pub struct Task {
pub task_type: String,
pub id: u32,
pub title: String,
description: Option<String>,
assignees: Vec<Author>,
properties: HashMap<String, String>,
}
impl Task {
pub fn new(lines: &Vec<&str>) -> Task {
let subject = lines[0][4..].to_string();
let words: Vec<&str> = lines[0][4..].split_whitespace().collect();
let task_type = words[0].to_string();
let id_str = words[1];
let id: u32 = FromStr::from_str(id_str).unwrap();
let title =
if words[2] == "-" | else {
let index = subject.find(id_str).unwrap();
subject[index + id_str.len() + 1..].trim().to_string()
};
Task {
id: id,
title: title,
task_type: task_type,
description: None,
assignees: Vec::new(),
properties: HashMap::new(),
}
}
}
| {
let index = subject.find('-').unwrap();
subject[index + 1..].trim().to_string()
} | conditional_block |
task.rs | use std::collections::HashMap;
use std::str::FromStr;
use author::Author;
#[derive(Debug)]
pub struct Task {
pub task_type: String,
pub id: u32,
pub title: String,
description: Option<String>,
assignees: Vec<Author>,
properties: HashMap<String, String>,
}
impl Task {
pub fn new(lines: &Vec<&str>) -> Task |
}
| {
let subject = lines[0][4..].to_string();
let words: Vec<&str> = lines[0][4..].split_whitespace().collect();
let task_type = words[0].to_string();
let id_str = words[1];
let id: u32 = FromStr::from_str(id_str).unwrap();
let title =
if words[2] == "-" {
let index = subject.find('-').unwrap();
subject[index + 1..].trim().to_string()
} else {
let index = subject.find(id_str).unwrap();
subject[index + id_str.len() + 1..].trim().to_string()
};
Task {
id: id,
title: title,
task_type: task_type,
description: None,
assignees: Vec::new(),
properties: HashMap::new(),
}
} | identifier_body |
task.rs | use std::collections::HashMap;
use std::str::FromStr;
use author::Author;
#[derive(Debug)]
pub struct Task {
pub task_type: String,
pub id: u32,
pub title: String,
description: Option<String>,
assignees: Vec<Author>,
properties: HashMap<String, String>,
}
impl Task {
pub fn | (lines: &Vec<&str>) -> Task {
let subject = lines[0][4..].to_string();
let words: Vec<&str> = lines[0][4..].split_whitespace().collect();
let task_type = words[0].to_string();
let id_str = words[1];
let id: u32 = FromStr::from_str(id_str).unwrap();
let title =
if words[2] == "-" {
let index = subject.find('-').unwrap();
subject[index + 1..].trim().to_string()
} else {
let index = subject.find(id_str).unwrap();
subject[index + id_str.len() + 1..].trim().to_string()
};
Task {
id: id,
title: title,
task_type: task_type,
description: None,
assignees: Vec::new(),
properties: HashMap::new(),
}
}
}
| new | identifier_name |
task.rs | use std::collections::HashMap;
use std::str::FromStr;
use author::Author;
#[derive(Debug)]
pub struct Task {
pub task_type: String,
pub id: u32,
pub title: String,
description: Option<String>,
assignees: Vec<Author>,
properties: HashMap<String, String>,
}
impl Task {
pub fn new(lines: &Vec<&str>) -> Task {
let subject = lines[0][4..].to_string();
let words: Vec<&str> = lines[0][4..].split_whitespace().collect();
let task_type = words[0].to_string();
let id_str = words[1];
let id: u32 = FromStr::from_str(id_str).unwrap();
let title =
if words[2] == "-" {
let index = subject.find('-').unwrap(); |
Task {
id: id,
title: title,
task_type: task_type,
description: None,
assignees: Vec::new(),
properties: HashMap::new(),
}
}
} | subject[index + 1..].trim().to_string()
} else {
let index = subject.find(id_str).unwrap();
subject[index + id_str.len() + 1..].trim().to_string()
}; | random_line_split |
struct-return.rs | // Copyright 2012-2015 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.
//
// ignore-lexer-test FIXME #15883
pub struct Quad { a: u64, b: u64, c: u64, d: u64 }
impl Copy for Quad {}
pub struct Floats { a: f64, b: u8, c: f64 }
impl Copy for Floats {}
mod rustrt {
use super::{Floats, Quad};
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_abi_1(q: Quad) -> Quad;
pub fn rust_dbg_abi_2(f: Floats) -> Floats;
}
}
fn test1() {
unsafe {
let q = Quad { a: 0xaaaa_aaaa_aaaa_aaaa_u64,
b: 0xbbbb_bbbb_bbbb_bbbb_u64,
c: 0xcccc_cccc_cccc_cccc_u64,
d: 0xdddd_dddd_dddd_dddd_u64 };
let qq = rustrt::rust_dbg_abi_1(q);
println!("a: {:x}", qq.a as uint);
println!("b: {:x}", qq.b as uint);
println!("c: {:x}", qq.c as uint);
println!("d: {:x}", qq.d as uint);
assert_eq!(qq.a, q.c + 1u64);
assert_eq!(qq.b, q.d - 1u64);
assert_eq!(qq.c, q.a + 1u64);
assert_eq!(qq.d, q.b - 1u64);
}
}
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
fn | () {
unsafe {
let f = Floats { a: 1.234567890e-15_f64,
b: 0b_1010_1010_u8,
c: 1.0987654321e-15_f64 };
let ff = rustrt::rust_dbg_abi_2(f);
println!("a: {}", ff.a as f64);
println!("b: {}", ff.b as uint);
println!("c: {}", ff.c as f64);
assert_eq!(ff.a, f.c + 1.0f64);
assert_eq!(ff.b, 0xff_u8);
assert_eq!(ff.c, f.a - 1.0f64);
}
}
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
fn test2() {
}
pub fn main() {
test1();
test2();
}
| test2 | identifier_name |
struct-return.rs | // Copyright 2012-2015 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.
//
// ignore-lexer-test FIXME #15883
pub struct Quad { a: u64, b: u64, c: u64, d: u64 }
impl Copy for Quad {}
pub struct Floats { a: f64, b: u8, c: f64 }
impl Copy for Floats {}
mod rustrt {
use super::{Floats, Quad};
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_abi_1(q: Quad) -> Quad;
pub fn rust_dbg_abi_2(f: Floats) -> Floats;
}
}
fn test1() |
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
fn test2() {
unsafe {
let f = Floats { a: 1.234567890e-15_f64,
b: 0b_1010_1010_u8,
c: 1.0987654321e-15_f64 };
let ff = rustrt::rust_dbg_abi_2(f);
println!("a: {}", ff.a as f64);
println!("b: {}", ff.b as uint);
println!("c: {}", ff.c as f64);
assert_eq!(ff.a, f.c + 1.0f64);
assert_eq!(ff.b, 0xff_u8);
assert_eq!(ff.c, f.a - 1.0f64);
}
}
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
fn test2() {
}
pub fn main() {
test1();
test2();
}
| {
unsafe {
let q = Quad { a: 0xaaaa_aaaa_aaaa_aaaa_u64,
b: 0xbbbb_bbbb_bbbb_bbbb_u64,
c: 0xcccc_cccc_cccc_cccc_u64,
d: 0xdddd_dddd_dddd_dddd_u64 };
let qq = rustrt::rust_dbg_abi_1(q);
println!("a: {:x}", qq.a as uint);
println!("b: {:x}", qq.b as uint);
println!("c: {:x}", qq.c as uint);
println!("d: {:x}", qq.d as uint);
assert_eq!(qq.a, q.c + 1u64);
assert_eq!(qq.b, q.d - 1u64);
assert_eq!(qq.c, q.a + 1u64);
assert_eq!(qq.d, q.b - 1u64);
}
} | identifier_body |
struct-return.rs | // Copyright 2012-2015 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.
//
// ignore-lexer-test FIXME #15883
pub struct Quad { a: u64, b: u64, c: u64, d: u64 }
impl Copy for Quad {}
pub struct Floats { a: f64, b: u8, c: f64 }
impl Copy for Floats {}
mod rustrt {
use super::{Floats, Quad};
#[link(name = "rust_test_helpers")]
extern {
pub fn rust_dbg_abi_1(q: Quad) -> Quad;
pub fn rust_dbg_abi_2(f: Floats) -> Floats;
}
}
fn test1() {
unsafe {
let q = Quad { a: 0xaaaa_aaaa_aaaa_aaaa_u64,
b: 0xbbbb_bbbb_bbbb_bbbb_u64,
c: 0xcccc_cccc_cccc_cccc_u64,
d: 0xdddd_dddd_dddd_dddd_u64 };
let qq = rustrt::rust_dbg_abi_1(q);
println!("a: {:x}", qq.a as uint);
println!("b: {:x}", qq.b as uint);
println!("c: {:x}", qq.c as uint);
println!("d: {:x}", qq.d as uint);
assert_eq!(qq.a, q.c + 1u64);
assert_eq!(qq.b, q.d - 1u64);
assert_eq!(qq.c, q.a + 1u64);
assert_eq!(qq.d, q.b - 1u64);
}
}
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
fn test2() {
unsafe {
let f = Floats { a: 1.234567890e-15_f64, | b: 0b_1010_1010_u8,
c: 1.0987654321e-15_f64 };
let ff = rustrt::rust_dbg_abi_2(f);
println!("a: {}", ff.a as f64);
println!("b: {}", ff.b as uint);
println!("c: {}", ff.c as f64);
assert_eq!(ff.a, f.c + 1.0f64);
assert_eq!(ff.b, 0xff_u8);
assert_eq!(ff.c, f.a - 1.0f64);
}
}
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
fn test2() {
}
pub fn main() {
test1();
test2();
} | random_line_split | |
fork.py | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd']) | if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'amd64':
if os in ['linux', 'freebsd']:
return _fork_amd64(parent, child)
bug('OS/arch combination (%s, %s) was not supported for fork' % (os, arch))
def _fork_amd64(parent, child):
code = """
push SYS_fork
pop rax
syscall
test rax, rax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
def _fork_i386(parent, child):
code = """
push SYS_fork
pop eax
int 0x80
test eax, eax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code | def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
| random_line_split |
fork.py | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd'])
def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'amd64':
if os in ['linux', 'freebsd']:
return _fork_amd64(parent, child)
bug('OS/arch combination (%s, %s) was not supported for fork' % (os, arch))
def _fork_amd64(parent, child):
code = """
push SYS_fork
pop rax
syscall
test rax, rax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
def _fork_i386(parent, child):
| code = """
push SYS_fork
pop eax
int 0x80
test eax, eax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code | identifier_body | |
fork.py | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd'])
def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'amd64':
if os in ['linux', 'freebsd']:
return _fork_amd64(parent, child)
bug('OS/arch combination (%s, %s) was not supported for fork' % (os, arch))
def _fork_amd64(parent, child):
code = """
push SYS_fork
pop rax
syscall
test rax, rax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
def | (parent, child):
code = """
push SYS_fork
pop eax
int 0x80
test eax, eax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
| _fork_i386 | identifier_name |
fork.py | from pwn.internal.shellcode_helper import *
@shellcode_reqs(arch=['i386', 'amd64'], os=['linux', 'freebsd'])
def fork(parent, child = None, os = None, arch = None):
"""Fork this shit."""
if arch == 'i386':
if os in ['linux', 'freebsd']:
return _fork_i386(parent, child)
elif arch == 'amd64':
|
bug('OS/arch combination (%s, %s) was not supported for fork' % (os, arch))
def _fork_amd64(parent, child):
code = """
push SYS_fork
pop rax
syscall
test rax, rax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
def _fork_i386(parent, child):
code = """
push SYS_fork
pop eax
int 0x80
test eax, eax
jne %s
""" % parent
if child is not None:
code += 'jmp %s\n' % child
return code
| if os in ['linux', 'freebsd']:
return _fork_amd64(parent, child) | conditional_block |
ray.rs | use std::f32;
use linalg::{Point, Vector};
/// Ray is a standard 3D ray, starting at origin `o` and heading in direction `d`
/// The min and max points along the ray can be specified with `min_t` and `max_t`
/// `depth` is the recursion depth of the ray
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Ray {
/// Origin of the ray
pub o: Point,
/// Direction the ray is heading
pub d: Vector,
/// Point along the ray that the actual ray starts at, `p = o + min_t * d`
pub min_t: f32,
/// Point along the ray at which it stops, will be inf if the ray is infinite
pub max_t: f32,
/// Recursion depth of the ray
pub depth: u32,
}
impl Ray {
/// Create a new ray from `o` heading in `d` with infinite length
pub fn new(o: &Point, d: &Vector) -> Ray {
Ray { o: *o, d: *d, min_t: 0f32, max_t: f32::INFINITY, depth: 0 }
}
/// Create a new segment ray from `o + min_t * d` to `o + max_t * d`
pub fn segment(o: &Point, d: &Vector, min_t: f32, max_t: f32) -> Ray |
/// Create a child ray from the parent starting at `o` and heading in `d`
pub fn child(&self, o: &Point, d: &Vector) -> Ray {
Ray { o: *o, d: *d, min_t: 0f32, max_t: f32::INFINITY, depth: self.depth + 1 }
}
/// Create a child ray segment from `o + min_t * d` to `o + max_t * d`
pub fn child_segment(&self, o: &Point, d: &Vector, min_t: f32, max_t: f32) -> Ray {
Ray { o: *o, d: *d, min_t: min_t, max_t: max_t, depth: self.depth + 1}
}
/// Evaulate the ray equation at some t value and return the point
/// returns result of `self.o + t * self.d`
pub fn at(&self, t: f32) -> Point {
self.o + self.d * t
}
}
| {
Ray { o: *o, d: *d, min_t: min_t, max_t: max_t, depth: 0}
} | identifier_body |
ray.rs | use std::f32;
use linalg::{Point, Vector};
/// Ray is a standard 3D ray, starting at origin `o` and heading in direction `d`
/// The min and max points along the ray can be specified with `min_t` and `max_t`
/// `depth` is the recursion depth of the ray
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct | {
/// Origin of the ray
pub o: Point,
/// Direction the ray is heading
pub d: Vector,
/// Point along the ray that the actual ray starts at, `p = o + min_t * d`
pub min_t: f32,
/// Point along the ray at which it stops, will be inf if the ray is infinite
pub max_t: f32,
/// Recursion depth of the ray
pub depth: u32,
}
impl Ray {
/// Create a new ray from `o` heading in `d` with infinite length
pub fn new(o: &Point, d: &Vector) -> Ray {
Ray { o: *o, d: *d, min_t: 0f32, max_t: f32::INFINITY, depth: 0 }
}
/// Create a new segment ray from `o + min_t * d` to `o + max_t * d`
pub fn segment(o: &Point, d: &Vector, min_t: f32, max_t: f32) -> Ray {
Ray { o: *o, d: *d, min_t: min_t, max_t: max_t, depth: 0}
}
/// Create a child ray from the parent starting at `o` and heading in `d`
pub fn child(&self, o: &Point, d: &Vector) -> Ray {
Ray { o: *o, d: *d, min_t: 0f32, max_t: f32::INFINITY, depth: self.depth + 1 }
}
/// Create a child ray segment from `o + min_t * d` to `o + max_t * d`
pub fn child_segment(&self, o: &Point, d: &Vector, min_t: f32, max_t: f32) -> Ray {
Ray { o: *o, d: *d, min_t: min_t, max_t: max_t, depth: self.depth + 1}
}
/// Evaulate the ray equation at some t value and return the point
/// returns result of `self.o + t * self.d`
pub fn at(&self, t: f32) -> Point {
self.o + self.d * t
}
}
| Ray | identifier_name |
ray.rs | use std::f32;
use linalg::{Point, Vector}; |
/// Ray is a standard 3D ray, starting at origin `o` and heading in direction `d`
/// The min and max points along the ray can be specified with `min_t` and `max_t`
/// `depth` is the recursion depth of the ray
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Ray {
/// Origin of the ray
pub o: Point,
/// Direction the ray is heading
pub d: Vector,
/// Point along the ray that the actual ray starts at, `p = o + min_t * d`
pub min_t: f32,
/// Point along the ray at which it stops, will be inf if the ray is infinite
pub max_t: f32,
/// Recursion depth of the ray
pub depth: u32,
}
impl Ray {
/// Create a new ray from `o` heading in `d` with infinite length
pub fn new(o: &Point, d: &Vector) -> Ray {
Ray { o: *o, d: *d, min_t: 0f32, max_t: f32::INFINITY, depth: 0 }
}
/// Create a new segment ray from `o + min_t * d` to `o + max_t * d`
pub fn segment(o: &Point, d: &Vector, min_t: f32, max_t: f32) -> Ray {
Ray { o: *o, d: *d, min_t: min_t, max_t: max_t, depth: 0}
}
/// Create a child ray from the parent starting at `o` and heading in `d`
pub fn child(&self, o: &Point, d: &Vector) -> Ray {
Ray { o: *o, d: *d, min_t: 0f32, max_t: f32::INFINITY, depth: self.depth + 1 }
}
/// Create a child ray segment from `o + min_t * d` to `o + max_t * d`
pub fn child_segment(&self, o: &Point, d: &Vector, min_t: f32, max_t: f32) -> Ray {
Ray { o: *o, d: *d, min_t: min_t, max_t: max_t, depth: self.depth + 1}
}
/// Evaulate the ray equation at some t value and return the point
/// returns result of `self.o + t * self.d`
pub fn at(&self, t: f32) -> Point {
self.o + self.d * t
}
} | random_line_split | |
lint-shorthand-field.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.
#![allow(bad_style, unused_variables)]
#![deny(non_shorthand_field_patterns)]
struct Foo { | fn main() {
{
let Foo {
x: x, //~ ERROR the `x:` in this pattern is redundant
y: ref y, //~ ERROR the `y:` in this pattern is redundant
} = Foo { x: 0, y: 0 };
let Foo {
x,
ref y,
} = Foo { x: 0, y: 0 };
}
{
const x: isize = 1;
match (Foo { x: 1, y: 1 }) {
Foo { x: x, ..} => {},
_ => {},
}
}
{
struct Bar {
x: x,
}
struct x;
match (Bar { x: x }) {
Bar { x: x } => {},
}
}
{
struct Bar {
x: Foo,
}
enum Foo { x }
match (Bar { x: Foo::x }) {
Bar { x: Foo::x } => {},
}
}
} | x: isize,
y: isize,
}
| random_line_split |
lint-shorthand-field.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.
#![allow(bad_style, unused_variables)]
#![deny(non_shorthand_field_patterns)]
struct Foo {
x: isize,
y: isize,
}
fn main() {
{
let Foo {
x: x, //~ ERROR the `x:` in this pattern is redundant
y: ref y, //~ ERROR the `y:` in this pattern is redundant
} = Foo { x: 0, y: 0 };
let Foo {
x,
ref y,
} = Foo { x: 0, y: 0 };
}
{
const x: isize = 1;
match (Foo { x: 1, y: 1 }) {
Foo { x: x, ..} => {},
_ => {},
}
}
{
struct Bar {
x: x,
}
struct x;
match (Bar { x: x }) {
Bar { x: x } => {},
}
}
{
struct | {
x: Foo,
}
enum Foo { x }
match (Bar { x: Foo::x }) {
Bar { x: Foo::x } => {},
}
}
}
| Bar | identifier_name |
testcaselinkedlistsource0.rs | use List::*;
enum List {
// Cons: Un tuple contenant un élément(i.e. u32) et un pointeur vers le noeud suivant (i.e. Box<List>).
Cons(u32, Box<List>),
// Nil: Un noeud témoignant de la fin de la liste.
Nil,
}
// Il est possible de lier, d'implémenter des méthodes
// pour une énumération.
impl List {
// Créé une liste vide.
fn new() -> List {
// `Nil` est une variante de `List`.
Nil
}
// Consomme, s'approprie la liste et renvoie une copie de cette même liste
// avec un nouvel élément ajouté à la suite.
fn prepend(self, | 32) -> List {
// `Cons` est également une variante de `List`.
Cons(elem, Box::new(self))
}
// Renvoie la longueur de la liste.
fn len(&self) -> u32 {
// `self` doit être analysé car le comportement de cette méthode
// dépend du type de variante auquel appartient `self`.
// `self` est de type `&List` et `*self` est de type `List`, rendant
// possible l'analyse directe de la ressource plutôt que par le biais d'un alias (i.e. une référence).
// Pour faire simple: on déréférence `self` avant de l'analyser.
// Note: Lorsque vous travaillez sur des références, préférez le déréférencement
// avant analyse.
match *self {
// On ne peut pas prendre "l'ownership" de la queue (liste)
// puisque l'on emprunte seulement `self` (nous ne le possédons pas);
// Nous créerons simplement une référence de la queue.
Cons(_, ref tail) => 1 + tail.len(),
// De base, une liste vide possède 0 élément.
Nil => 0
}
}
// Renvoie une représentation de la liste sous une chaîne de caractères
// (wrapper)
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` est équivalente à `println!` mais elle renvoie
// une chaîne de caractères allouée dans le tas (wrapper)
// plutôt que de l'afficher dans la console.
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}
fn main() {
// Créé une liste vide.
let mut list = List::new();
// On ajoute quelques éléments.
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Affiche l'état définitif de la liste.
println!("La linked list possède une longueur de: {}", list.len());
println!("{}", list.stringify());
}
| elem: u | identifier_name |
testcaselinkedlistsource0.rs | use List::*;
enum List {
// Cons: Un tuple contenant un élément(i.e. u32) et un pointeur vers le noeud suivant (i.e. Box<List>).
Cons(u32, Box<List>),
// Nil: Un noeud témoignant de la fin de la liste.
Nil,
}
// Il est possible de lier, d'implémenter des méthodes
// pour une énumération.
impl List {
// Créé une liste vide.
fn new() -> List {
| Consomme, s'approprie la liste et renvoie une copie de cette même liste
// avec un nouvel élément ajouté à la suite.
fn prepend(self, elem: u32) -> List {
// `Cons` est également une variante de `List`.
Cons(elem, Box::new(self))
}
// Renvoie la longueur de la liste.
fn len(&self) -> u32 {
// `self` doit être analysé car le comportement de cette méthode
// dépend du type de variante auquel appartient `self`.
// `self` est de type `&List` et `*self` est de type `List`, rendant
// possible l'analyse directe de la ressource plutôt que par le biais d'un alias (i.e. une référence).
// Pour faire simple: on déréférence `self` avant de l'analyser.
// Note: Lorsque vous travaillez sur des références, préférez le déréférencement
// avant analyse.
match *self {
// On ne peut pas prendre "l'ownership" de la queue (liste)
// puisque l'on emprunte seulement `self` (nous ne le possédons pas);
// Nous créerons simplement une référence de la queue.
Cons(_, ref tail) => 1 + tail.len(),
// De base, une liste vide possède 0 élément.
Nil => 0
}
}
// Renvoie une représentation de la liste sous une chaîne de caractères
// (wrapper)
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` est équivalente à `println!` mais elle renvoie
// une chaîne de caractères allouée dans le tas (wrapper)
// plutôt que de l'afficher dans la console.
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}
fn main() {
// Créé une liste vide.
let mut list = List::new();
// On ajoute quelques éléments.
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Affiche l'état définitif de la liste.
println!("La linked list possède une longueur de: {}", list.len());
println!("{}", list.stringify());
}
| // `Nil` est une variante de `List`.
Nil
}
// | identifier_body |
testcaselinkedlistsource0.rs | use List::*;
enum List {
// Cons: Un tuple contenant un élément(i.e. u32) et un pointeur vers le noeud suivant (i.e. Box<List>).
Cons(u32, Box<List>),
// Nil: Un noeud témoignant de la fin de la liste.
Nil,
}
// Il est possible de lier, d'implémenter des méthodes
// pour une énumération.
impl List {
// Créé une liste vide.
fn new() -> List {
// `Nil` est une variante de `List`.
Nil
}
// Consomme, s'approprie la liste et renvoie une copie de cette même liste
// avec un nouvel élément ajouté à la suite.
fn prepend(self, elem: u32) -> List {
// `Cons` est également une variante de `List`.
Cons(elem, Box::new(self))
}
// Renvoie la longueur de la liste.
fn len(&self) -> u32 {
// `self` doit être analysé car le comportement de cette méthode
// dépend du type de variante auquel appartient `self`.
// `self` est de type `&List` et `*self` est de type `List`, rendant
// possible l'analyse directe de la ressource plutôt que par le biais d'un alias (i.e. une référence).
// Pour faire simple: on déréférence `self` avant de l'analyser.
// Note: Lorsque vous travaillez sur des références, préférez le déréférencement
// avant analyse.
match *self {
// On ne peut pas prendre "l'ownership" de la queue (liste)
// puisque l'on emprunte seulement `self` (nous ne le possédons pas);
// Nous créerons simplement une référence de la queue.
Cons(_, ref tail) => 1 + tail.len(),
// De base, une liste vide possède 0 élément.
Nil => 0
}
}
// Renvoie une représentation de la liste sous une chaîne de caractères | fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` est équivalente à `println!` mais elle renvoie
// une chaîne de caractères allouée dans le tas (wrapper)
// plutôt que de l'afficher dans la console.
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!("Nil")
},
}
}
}
fn main() {
// Créé une liste vide.
let mut list = List::new();
// On ajoute quelques éléments.
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Affiche l'état définitif de la liste.
println!("La linked list possède une longueur de: {}", list.len());
println!("{}", list.stringify());
} | // (wrapper) | random_line_split |
testcaselinkedlistsource0.rs | use List::*;
enum List {
// Cons: Un tuple contenant un élément(i.e. u32) et un pointeur vers le noeud suivant (i.e. Box<List>).
Cons(u32, Box<List>),
// Nil: Un noeud témoignant de la fin de la liste.
Nil,
}
// Il est possible de lier, d'implémenter des méthodes
// pour une énumération.
impl List {
// Créé une liste vide.
fn new() -> List {
// `Nil` est une variante de `List`.
Nil
}
// Consomme, s'approprie la liste et renvoie une copie de cette même liste
// avec un nouvel élément ajouté à la suite.
fn prepend(self, elem: u32) -> List {
// `Cons` est également une variante de `List`.
Cons(elem, Box::new(self))
}
// Renvoie la longueur de la liste.
fn len(&self) -> u32 {
// `self` doit être analysé car le comportement de cette méthode
// dépend du type de variante auquel appartient `self`.
// `self` est de type `&List` et `*self` est de type `List`, rendant
// possible l'analyse directe de la ressource plutôt que par le biais d'un alias (i.e. une référence).
// Pour faire simple: on déréférence `self` avant de l'analyser.
// Note: Lorsque vous travaillez sur des références, préférez le déréférencement
// avant analyse.
match *self {
// On ne peut pas prendre "l'ownership" de la queue (liste)
// puisque l'on emprunte seulement `self` (nous ne le possédons pas);
// Nous créerons simplement une référence de la queue.
Cons(_, ref tail) => 1 + tail.len(),
// De base, une liste vide possède 0 élément.
Nil => 0
}
}
// Renvoie une représentation de la liste sous une chaîne de caractères
// (wrapper)
fn stringify(&self) -> String {
match *self {
Cons(head, ref tail) => {
// `format!` est équival | Nil")
},
}
}
}
fn main() {
// Créé une liste vide.
let mut list = List::new();
// On ajoute quelques éléments.
list = list.prepend(1);
list = list.prepend(2);
list = list.prepend(3);
// Affiche l'état définitif de la liste.
println!("La linked list possède une longueur de: {}", list.len());
println!("{}", list.stringify());
}
| ente à `println!` mais elle renvoie
// une chaîne de caractères allouée dans le tas (wrapper)
// plutôt que de l'afficher dans la console.
format!("{}, {}", head, tail.stringify())
},
Nil => {
format!(" | conditional_block |
flags.ts | // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
///<reference path='typescript.ts' />
module TypeScript {
export function hasFlag(val: number, flag: number) |
export enum ErrorRecoverySet {
None = 0,
Comma = 1, // Comma
SColon = 1 << 1, // SColon
Asg = 1 << 2, // Asg
BinOp = 1 << 3, // Lsh, Rsh, Rs2, Le, Ge, INSTANCEOF, EQ, NE, Eqv, NEqv, LogAnd, LogOr, AsgMul, AsgDiv
// AsgMod, AsgAdd, AsgSub, AsgLsh, AsgRsh, AsgRs2, AsgAnd, AsgXor, AsgOr, QMark, Mult, Div,
// Pct, GT, LT, And, Xor, Or
RBrack = 1 << 4, // RBrack
RCurly = 1 << 5, // RCurly
RParen = 1 << 6, // RParen
Dot = 1 << 7, // Dot
Colon = 1 << 8, // Colon
PrimType = 1 << 9, // number, string, bool
AddOp = 1 << 10, // Add, Sub
LCurly = 1 << 11, // LCurly
PreOp = 1 << 12, // Tilde, Bang, Inc, Dec
RegExp = 1 << 13, // RegExp
LParen = 1 << 14, // LParen
LBrack = 1 << 15, // LBrack
Scope = 1 << 16, // Scope
In = 1 << 17, // IN
SCase = 1 << 18, // CASE, DEFAULT
Else = 1 << 19, // ELSE
Catch = 1 << 20, // CATCH, FINALLY
Var = 1 << 21, //
Stmt = 1 << 22, // BREAK, RETURN, THROW, DEBUGGER, FOR, SWITCH, DO, IF, TRY, WITH
While = 1 << 23, // WHILE
ID = 1 << 24, // ID
Prefix = 1 << 25, // VOID, DELETE, TYPEOF, AWAIT
Literal = 1 << 26, // IntCon, FltCon, StrCon
RLit = 1 << 27, // THIS, TRUE, FALSE, NULL
Func = 1 << 28, // FUNCTION
EOF = 1 << 29, // EOF
TypeScriptS = 1 << 30, // PROPERTY, PRIVATE, STATIC, INTERFACE, CLASS, MODULE, EXPORT, IMPORT
ExprStart = SColon | AddOp | LCurly | PreOp | RegExp | LParen | LBrack | ID | Prefix | RLit | Func | Literal,
StmtStart = ExprStart | SColon | Var | Stmt | While | TypeScriptS,
Postfix = Dot | LParen | LBrack,
}
export enum AllowedElements {
None = 0,
Statements = 1,
FunctionDecls = 1 << 1,
ModuleDecls = 1 << 2,
ClassDecls = 1 << 3,
InterfaceDecls = 1 << 4,
TypedFuncDecls = 1 << 5,
TypedDecls = 1 << 6,
TypedFuncSignatures = 1 << 8,
TypedSignatures = 1 << 9,
AmbientDecls = 1 << 10,
Properties = 1 << 11,
Block = Statements | FunctionDecls | TypedFuncDecls | TypedDecls,
Global = Statements | FunctionDecls | ModuleDecls | ClassDecls | InterfaceDecls | AmbientDecls,
FunctionBody = Statements | FunctionDecls,
ModuleMembers = TypedFuncDecls | FunctionDecls | ModuleDecls | ClassDecls | InterfaceDecls | TypedDecls | Statements | AmbientDecls,
ClassMembers = TypedFuncDecls | FunctionDecls | Statements | TypedDecls | Properties,
InterfaceMembers = TypedFuncSignatures | TypedSignatures,
QuickParse = Global | Properties,
}
export enum Modifiers {
None = 0,
Private = 1,
Public = 1 << 1,
Readonly = 1 << 2,
Ambient = 1 << 3,
Exported = 1 << 4,
Getter = 1 << 5,
Setter = 1 << 6,
Static = 1 << 7,
}
export enum ASTFlags {
None = 0,
ExplicitSemicolon = 1, // statment terminated by an explicit semicolon
AutomaticSemicolon = 1 << 1, // statment terminated by an automatic semicolon
Writeable = 1 << 2, // node is lhs that can be modified
Error = 1 << 3, // node has an error
DotLHSPartial = 1 << 4, // node is the lhs of an incomplete dot expr at cursor
DotLHS = 1 << 5, // node is the lhs of a dot expr
IsStatement = 1 << 6, // node is a statement
StrictMode = 1 << 7, // node is in the strict mode environment
PossibleOptionalParameter = 1 << 8,
ClassBaseConstructorCall = 1 << 9,
OptionalName = 1 << 10,
}
export enum DeclFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
}
export enum ModuleFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
IsEnum = 1 << 8,
ShouldEmitModuleDecl = 1 << 9,
IsWholeFile = 1 << 10,
IsDynamic = 1 << 11,
}
export enum SymbolFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
Property = 1 << 8,
Readonly = 1 << 9,
ModuleMember = 1 << 10,
InterfaceMember = 1 << 11,
ClassMember = 1 << 12,
BuiltIn = 1 << 13,
TypeSetDuringScopeAssignment = 1 << 14,
Constant = 1 << 15,
Optional = 1 << 16,
RecursivelyReferenced = 1 << 17,
Bound = 1 << 18,
}
export enum VarFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
AutoInit = 1 << 8,
Property = 1 << 9,
Readonly = 1 << 10,
Class = 1 << 11,
ClassProperty = 1 << 12,
ClassBodyProperty = 1 << 13,
ClassConstructorProperty = 1 << 14,
ClassSuperMustBeFirstCallInConstructor = 1 << 15,
Constant = 1 << 16,
}
export enum FncFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
Definition = 1 << 8,
Signature = 1 << 9,
Method = 1 << 10,
HasReturnExpression = 1 << 11,
CallMember = 1 << 12,
ConstructMember = 1 << 13,
HasSelfReference = 1 << 14,
IsFatArrowFunction = 1 << 15,
IndexerMember = 1 << 16,
IsFunctionExpression = 1 << 17,
ClassMethod = 1 << 18,
ClassPropertyMethodExported = 1 << 19,
}
export enum SignatureFlags {
None = 0,
IsIndexer = 1,
IsStringIndexer = 1 << 1,
IsNumberIndexer = 1 << 2,
}
export function ToDeclFlags(fncFlags: FncFlags) : DeclFlags;
export function ToDeclFlags(varFlags: VarFlags) : DeclFlags;
export function ToDeclFlags(symFlags: SymbolFlags): DeclFlags;
export function ToDeclFlags(moduleFlags: ModuleFlags): DeclFlags;
export function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags: any) {
return <DeclFlags>fncOrVarOrSymbolOrModuleFlags;
}
export enum TypeFlags {
None = 0,
HasImplementation = 1,
HasSelfReference = 1 << 1,
MergeResult = 1 << 2,
IsEnum = 1 << 3,
BuildingName = 1 << 4,
HasBaseType = 1 << 5,
HasBaseTypeOfObject = 1 << 6,
IsClass = 1 << 7,
}
export enum TypeRelationshipFlags {
SuccessfulComparison = 0,
SourceIsNullTargetIsVoidOrUndefined = 1,
RequiredPropertyIsMissing = 1 << 1,
IncompatibleSignatures = 1 << 2,
SourceSignatureHasTooManyParameters = 3,
IncompatibleReturnTypes = 1 << 4,
IncompatiblePropertyTypes = 1 << 5,
IncompatibleParameterTypes = 1 << 6,
}
export enum CodeGenTarget {
ES3 = 0,
ES5 = 1,
}
export enum ModuleGenTarget {
Synchronous = 0,
Asynchronous = 1,
Local = 1 << 1,
}
// Compiler defaults to generating ES5-compliant code for
// - getters and setters
export var codeGenTarget: CodeGenTarget = CodeGenTarget.ES3;
export var moduleGenTarget: ModuleGenTarget = ModuleGenTarget.Synchronous;
export var optimizeModuleCodeGen = true;
export function flagsToString(e, flags: number): string {
var builder = "";
for (var i = 1; i < (1 << 31) ; i = i << 1) {
if ((flags & i) != 0) {
for (var k in e) {
if (e[k] == i) {
if (builder.length > 0) {
builder += "|";
}
builder += k;
break;
}
}
}
}
return builder;
}
} | {
return (val & flag) != 0;
} | identifier_body |
flags.ts | // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
///<reference path='typescript.ts' />
module TypeScript {
export function hasFlag(val: number, flag: number) {
return (val & flag) != 0;
}
export enum ErrorRecoverySet {
None = 0,
Comma = 1, // Comma
SColon = 1 << 1, // SColon
Asg = 1 << 2, // Asg
BinOp = 1 << 3, // Lsh, Rsh, Rs2, Le, Ge, INSTANCEOF, EQ, NE, Eqv, NEqv, LogAnd, LogOr, AsgMul, AsgDiv
// AsgMod, AsgAdd, AsgSub, AsgLsh, AsgRsh, AsgRs2, AsgAnd, AsgXor, AsgOr, QMark, Mult, Div,
// Pct, GT, LT, And, Xor, Or
RBrack = 1 << 4, // RBrack
RCurly = 1 << 5, // RCurly
RParen = 1 << 6, // RParen
Dot = 1 << 7, // Dot
Colon = 1 << 8, // Colon
PrimType = 1 << 9, // number, string, bool
AddOp = 1 << 10, // Add, Sub
LCurly = 1 << 11, // LCurly
PreOp = 1 << 12, // Tilde, Bang, Inc, Dec
| RegExp = 1 << 13, // RegExp
LParen = 1 << 14, // LParen
LBrack = 1 << 15, // LBrack
Scope = 1 << 16, // Scope
In = 1 << 17, // IN
SCase = 1 << 18, // CASE, DEFAULT
Else = 1 << 19, // ELSE
Catch = 1 << 20, // CATCH, FINALLY
Var = 1 << 21, //
Stmt = 1 << 22, // BREAK, RETURN, THROW, DEBUGGER, FOR, SWITCH, DO, IF, TRY, WITH
While = 1 << 23, // WHILE
ID = 1 << 24, // ID
Prefix = 1 << 25, // VOID, DELETE, TYPEOF, AWAIT
Literal = 1 << 26, // IntCon, FltCon, StrCon
RLit = 1 << 27, // THIS, TRUE, FALSE, NULL
Func = 1 << 28, // FUNCTION
EOF = 1 << 29, // EOF
TypeScriptS = 1 << 30, // PROPERTY, PRIVATE, STATIC, INTERFACE, CLASS, MODULE, EXPORT, IMPORT
ExprStart = SColon | AddOp | LCurly | PreOp | RegExp | LParen | LBrack | ID | Prefix | RLit | Func | Literal,
StmtStart = ExprStart | SColon | Var | Stmt | While | TypeScriptS,
Postfix = Dot | LParen | LBrack,
}
export enum AllowedElements {
None = 0,
Statements = 1,
FunctionDecls = 1 << 1,
ModuleDecls = 1 << 2,
ClassDecls = 1 << 3,
InterfaceDecls = 1 << 4,
TypedFuncDecls = 1 << 5,
TypedDecls = 1 << 6,
TypedFuncSignatures = 1 << 8,
TypedSignatures = 1 << 9,
AmbientDecls = 1 << 10,
Properties = 1 << 11,
Block = Statements | FunctionDecls | TypedFuncDecls | TypedDecls,
Global = Statements | FunctionDecls | ModuleDecls | ClassDecls | InterfaceDecls | AmbientDecls,
FunctionBody = Statements | FunctionDecls,
ModuleMembers = TypedFuncDecls | FunctionDecls | ModuleDecls | ClassDecls | InterfaceDecls | TypedDecls | Statements | AmbientDecls,
ClassMembers = TypedFuncDecls | FunctionDecls | Statements | TypedDecls | Properties,
InterfaceMembers = TypedFuncSignatures | TypedSignatures,
QuickParse = Global | Properties,
}
export enum Modifiers {
None = 0,
Private = 1,
Public = 1 << 1,
Readonly = 1 << 2,
Ambient = 1 << 3,
Exported = 1 << 4,
Getter = 1 << 5,
Setter = 1 << 6,
Static = 1 << 7,
}
export enum ASTFlags {
None = 0,
ExplicitSemicolon = 1, // statment terminated by an explicit semicolon
AutomaticSemicolon = 1 << 1, // statment terminated by an automatic semicolon
Writeable = 1 << 2, // node is lhs that can be modified
Error = 1 << 3, // node has an error
DotLHSPartial = 1 << 4, // node is the lhs of an incomplete dot expr at cursor
DotLHS = 1 << 5, // node is the lhs of a dot expr
IsStatement = 1 << 6, // node is a statement
StrictMode = 1 << 7, // node is in the strict mode environment
PossibleOptionalParameter = 1 << 8,
ClassBaseConstructorCall = 1 << 9,
OptionalName = 1 << 10,
}
export enum DeclFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
}
export enum ModuleFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
IsEnum = 1 << 8,
ShouldEmitModuleDecl = 1 << 9,
IsWholeFile = 1 << 10,
IsDynamic = 1 << 11,
}
export enum SymbolFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
Property = 1 << 8,
Readonly = 1 << 9,
ModuleMember = 1 << 10,
InterfaceMember = 1 << 11,
ClassMember = 1 << 12,
BuiltIn = 1 << 13,
TypeSetDuringScopeAssignment = 1 << 14,
Constant = 1 << 15,
Optional = 1 << 16,
RecursivelyReferenced = 1 << 17,
Bound = 1 << 18,
}
export enum VarFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
AutoInit = 1 << 8,
Property = 1 << 9,
Readonly = 1 << 10,
Class = 1 << 11,
ClassProperty = 1 << 12,
ClassBodyProperty = 1 << 13,
ClassConstructorProperty = 1 << 14,
ClassSuperMustBeFirstCallInConstructor = 1 << 15,
Constant = 1 << 16,
}
export enum FncFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
Definition = 1 << 8,
Signature = 1 << 9,
Method = 1 << 10,
HasReturnExpression = 1 << 11,
CallMember = 1 << 12,
ConstructMember = 1 << 13,
HasSelfReference = 1 << 14,
IsFatArrowFunction = 1 << 15,
IndexerMember = 1 << 16,
IsFunctionExpression = 1 << 17,
ClassMethod = 1 << 18,
ClassPropertyMethodExported = 1 << 19,
}
export enum SignatureFlags {
None = 0,
IsIndexer = 1,
IsStringIndexer = 1 << 1,
IsNumberIndexer = 1 << 2,
}
export function ToDeclFlags(fncFlags: FncFlags) : DeclFlags;
export function ToDeclFlags(varFlags: VarFlags) : DeclFlags;
export function ToDeclFlags(symFlags: SymbolFlags): DeclFlags;
export function ToDeclFlags(moduleFlags: ModuleFlags): DeclFlags;
export function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags: any) {
return <DeclFlags>fncOrVarOrSymbolOrModuleFlags;
}
export enum TypeFlags {
None = 0,
HasImplementation = 1,
HasSelfReference = 1 << 1,
MergeResult = 1 << 2,
IsEnum = 1 << 3,
BuildingName = 1 << 4,
HasBaseType = 1 << 5,
HasBaseTypeOfObject = 1 << 6,
IsClass = 1 << 7,
}
export enum TypeRelationshipFlags {
SuccessfulComparison = 0,
SourceIsNullTargetIsVoidOrUndefined = 1,
RequiredPropertyIsMissing = 1 << 1,
IncompatibleSignatures = 1 << 2,
SourceSignatureHasTooManyParameters = 3,
IncompatibleReturnTypes = 1 << 4,
IncompatiblePropertyTypes = 1 << 5,
IncompatibleParameterTypes = 1 << 6,
}
export enum CodeGenTarget {
ES3 = 0,
ES5 = 1,
}
export enum ModuleGenTarget {
Synchronous = 0,
Asynchronous = 1,
Local = 1 << 1,
}
// Compiler defaults to generating ES5-compliant code for
// - getters and setters
export var codeGenTarget: CodeGenTarget = CodeGenTarget.ES3;
export var moduleGenTarget: ModuleGenTarget = ModuleGenTarget.Synchronous;
export var optimizeModuleCodeGen = true;
export function flagsToString(e, flags: number): string {
var builder = "";
for (var i = 1; i < (1 << 31) ; i = i << 1) {
if ((flags & i) != 0) {
for (var k in e) {
if (e[k] == i) {
if (builder.length > 0) {
builder += "|";
}
builder += k;
break;
}
}
}
}
return builder;
}
} | random_line_split | |
flags.ts | // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
///<reference path='typescript.ts' />
module TypeScript {
export function hasFlag(val: number, flag: number) {
return (val & flag) != 0;
}
export enum ErrorRecoverySet {
None = 0,
Comma = 1, // Comma
SColon = 1 << 1, // SColon
Asg = 1 << 2, // Asg
BinOp = 1 << 3, // Lsh, Rsh, Rs2, Le, Ge, INSTANCEOF, EQ, NE, Eqv, NEqv, LogAnd, LogOr, AsgMul, AsgDiv
// AsgMod, AsgAdd, AsgSub, AsgLsh, AsgRsh, AsgRs2, AsgAnd, AsgXor, AsgOr, QMark, Mult, Div,
// Pct, GT, LT, And, Xor, Or
RBrack = 1 << 4, // RBrack
RCurly = 1 << 5, // RCurly
RParen = 1 << 6, // RParen
Dot = 1 << 7, // Dot
Colon = 1 << 8, // Colon
PrimType = 1 << 9, // number, string, bool
AddOp = 1 << 10, // Add, Sub
LCurly = 1 << 11, // LCurly
PreOp = 1 << 12, // Tilde, Bang, Inc, Dec
RegExp = 1 << 13, // RegExp
LParen = 1 << 14, // LParen
LBrack = 1 << 15, // LBrack
Scope = 1 << 16, // Scope
In = 1 << 17, // IN
SCase = 1 << 18, // CASE, DEFAULT
Else = 1 << 19, // ELSE
Catch = 1 << 20, // CATCH, FINALLY
Var = 1 << 21, //
Stmt = 1 << 22, // BREAK, RETURN, THROW, DEBUGGER, FOR, SWITCH, DO, IF, TRY, WITH
While = 1 << 23, // WHILE
ID = 1 << 24, // ID
Prefix = 1 << 25, // VOID, DELETE, TYPEOF, AWAIT
Literal = 1 << 26, // IntCon, FltCon, StrCon
RLit = 1 << 27, // THIS, TRUE, FALSE, NULL
Func = 1 << 28, // FUNCTION
EOF = 1 << 29, // EOF
TypeScriptS = 1 << 30, // PROPERTY, PRIVATE, STATIC, INTERFACE, CLASS, MODULE, EXPORT, IMPORT
ExprStart = SColon | AddOp | LCurly | PreOp | RegExp | LParen | LBrack | ID | Prefix | RLit | Func | Literal,
StmtStart = ExprStart | SColon | Var | Stmt | While | TypeScriptS,
Postfix = Dot | LParen | LBrack,
}
export enum AllowedElements {
None = 0,
Statements = 1,
FunctionDecls = 1 << 1,
ModuleDecls = 1 << 2,
ClassDecls = 1 << 3,
InterfaceDecls = 1 << 4,
TypedFuncDecls = 1 << 5,
TypedDecls = 1 << 6,
TypedFuncSignatures = 1 << 8,
TypedSignatures = 1 << 9,
AmbientDecls = 1 << 10,
Properties = 1 << 11,
Block = Statements | FunctionDecls | TypedFuncDecls | TypedDecls,
Global = Statements | FunctionDecls | ModuleDecls | ClassDecls | InterfaceDecls | AmbientDecls,
FunctionBody = Statements | FunctionDecls,
ModuleMembers = TypedFuncDecls | FunctionDecls | ModuleDecls | ClassDecls | InterfaceDecls | TypedDecls | Statements | AmbientDecls,
ClassMembers = TypedFuncDecls | FunctionDecls | Statements | TypedDecls | Properties,
InterfaceMembers = TypedFuncSignatures | TypedSignatures,
QuickParse = Global | Properties,
}
export enum Modifiers {
None = 0,
Private = 1,
Public = 1 << 1,
Readonly = 1 << 2,
Ambient = 1 << 3,
Exported = 1 << 4,
Getter = 1 << 5,
Setter = 1 << 6,
Static = 1 << 7,
}
export enum ASTFlags {
None = 0,
ExplicitSemicolon = 1, // statment terminated by an explicit semicolon
AutomaticSemicolon = 1 << 1, // statment terminated by an automatic semicolon
Writeable = 1 << 2, // node is lhs that can be modified
Error = 1 << 3, // node has an error
DotLHSPartial = 1 << 4, // node is the lhs of an incomplete dot expr at cursor
DotLHS = 1 << 5, // node is the lhs of a dot expr
IsStatement = 1 << 6, // node is a statement
StrictMode = 1 << 7, // node is in the strict mode environment
PossibleOptionalParameter = 1 << 8,
ClassBaseConstructorCall = 1 << 9,
OptionalName = 1 << 10,
}
export enum DeclFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
}
export enum ModuleFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
IsEnum = 1 << 8,
ShouldEmitModuleDecl = 1 << 9,
IsWholeFile = 1 << 10,
IsDynamic = 1 << 11,
}
export enum SymbolFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
Property = 1 << 8,
Readonly = 1 << 9,
ModuleMember = 1 << 10,
InterfaceMember = 1 << 11,
ClassMember = 1 << 12,
BuiltIn = 1 << 13,
TypeSetDuringScopeAssignment = 1 << 14,
Constant = 1 << 15,
Optional = 1 << 16,
RecursivelyReferenced = 1 << 17,
Bound = 1 << 18,
}
export enum VarFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
AutoInit = 1 << 8,
Property = 1 << 9,
Readonly = 1 << 10,
Class = 1 << 11,
ClassProperty = 1 << 12,
ClassBodyProperty = 1 << 13,
ClassConstructorProperty = 1 << 14,
ClassSuperMustBeFirstCallInConstructor = 1 << 15,
Constant = 1 << 16,
}
export enum FncFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
Definition = 1 << 8,
Signature = 1 << 9,
Method = 1 << 10,
HasReturnExpression = 1 << 11,
CallMember = 1 << 12,
ConstructMember = 1 << 13,
HasSelfReference = 1 << 14,
IsFatArrowFunction = 1 << 15,
IndexerMember = 1 << 16,
IsFunctionExpression = 1 << 17,
ClassMethod = 1 << 18,
ClassPropertyMethodExported = 1 << 19,
}
export enum SignatureFlags {
None = 0,
IsIndexer = 1,
IsStringIndexer = 1 << 1,
IsNumberIndexer = 1 << 2,
}
export function ToDeclFlags(fncFlags: FncFlags) : DeclFlags;
export function ToDeclFlags(varFlags: VarFlags) : DeclFlags;
export function ToDeclFlags(symFlags: SymbolFlags): DeclFlags;
export function ToDeclFlags(moduleFlags: ModuleFlags): DeclFlags;
export function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags: any) {
return <DeclFlags>fncOrVarOrSymbolOrModuleFlags;
}
export enum TypeFlags {
None = 0,
HasImplementation = 1,
HasSelfReference = 1 << 1,
MergeResult = 1 << 2,
IsEnum = 1 << 3,
BuildingName = 1 << 4,
HasBaseType = 1 << 5,
HasBaseTypeOfObject = 1 << 6,
IsClass = 1 << 7,
}
export enum TypeRelationshipFlags {
SuccessfulComparison = 0,
SourceIsNullTargetIsVoidOrUndefined = 1,
RequiredPropertyIsMissing = 1 << 1,
IncompatibleSignatures = 1 << 2,
SourceSignatureHasTooManyParameters = 3,
IncompatibleReturnTypes = 1 << 4,
IncompatiblePropertyTypes = 1 << 5,
IncompatibleParameterTypes = 1 << 6,
}
export enum CodeGenTarget {
ES3 = 0,
ES5 = 1,
}
export enum ModuleGenTarget {
Synchronous = 0,
Asynchronous = 1,
Local = 1 << 1,
}
// Compiler defaults to generating ES5-compliant code for
// - getters and setters
export var codeGenTarget: CodeGenTarget = CodeGenTarget.ES3;
export var moduleGenTarget: ModuleGenTarget = ModuleGenTarget.Synchronous;
export var optimizeModuleCodeGen = true;
export function flagsToString(e, flags: number): string {
var builder = "";
for (var i = 1; i < (1 << 31) ; i = i << 1) |
return builder;
}
} | {
if ((flags & i) != 0) {
for (var k in e) {
if (e[k] == i) {
if (builder.length > 0) {
builder += "|";
}
builder += k;
break;
}
}
}
} | conditional_block |
flags.ts | // Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.
///<reference path='typescript.ts' />
module TypeScript {
export function hasFlag(val: number, flag: number) {
return (val & flag) != 0;
}
export enum ErrorRecoverySet {
None = 0,
Comma = 1, // Comma
SColon = 1 << 1, // SColon
Asg = 1 << 2, // Asg
BinOp = 1 << 3, // Lsh, Rsh, Rs2, Le, Ge, INSTANCEOF, EQ, NE, Eqv, NEqv, LogAnd, LogOr, AsgMul, AsgDiv
// AsgMod, AsgAdd, AsgSub, AsgLsh, AsgRsh, AsgRs2, AsgAnd, AsgXor, AsgOr, QMark, Mult, Div,
// Pct, GT, LT, And, Xor, Or
RBrack = 1 << 4, // RBrack
RCurly = 1 << 5, // RCurly
RParen = 1 << 6, // RParen
Dot = 1 << 7, // Dot
Colon = 1 << 8, // Colon
PrimType = 1 << 9, // number, string, bool
AddOp = 1 << 10, // Add, Sub
LCurly = 1 << 11, // LCurly
PreOp = 1 << 12, // Tilde, Bang, Inc, Dec
RegExp = 1 << 13, // RegExp
LParen = 1 << 14, // LParen
LBrack = 1 << 15, // LBrack
Scope = 1 << 16, // Scope
In = 1 << 17, // IN
SCase = 1 << 18, // CASE, DEFAULT
Else = 1 << 19, // ELSE
Catch = 1 << 20, // CATCH, FINALLY
Var = 1 << 21, //
Stmt = 1 << 22, // BREAK, RETURN, THROW, DEBUGGER, FOR, SWITCH, DO, IF, TRY, WITH
While = 1 << 23, // WHILE
ID = 1 << 24, // ID
Prefix = 1 << 25, // VOID, DELETE, TYPEOF, AWAIT
Literal = 1 << 26, // IntCon, FltCon, StrCon
RLit = 1 << 27, // THIS, TRUE, FALSE, NULL
Func = 1 << 28, // FUNCTION
EOF = 1 << 29, // EOF
TypeScriptS = 1 << 30, // PROPERTY, PRIVATE, STATIC, INTERFACE, CLASS, MODULE, EXPORT, IMPORT
ExprStart = SColon | AddOp | LCurly | PreOp | RegExp | LParen | LBrack | ID | Prefix | RLit | Func | Literal,
StmtStart = ExprStart | SColon | Var | Stmt | While | TypeScriptS,
Postfix = Dot | LParen | LBrack,
}
export enum AllowedElements {
None = 0,
Statements = 1,
FunctionDecls = 1 << 1,
ModuleDecls = 1 << 2,
ClassDecls = 1 << 3,
InterfaceDecls = 1 << 4,
TypedFuncDecls = 1 << 5,
TypedDecls = 1 << 6,
TypedFuncSignatures = 1 << 8,
TypedSignatures = 1 << 9,
AmbientDecls = 1 << 10,
Properties = 1 << 11,
Block = Statements | FunctionDecls | TypedFuncDecls | TypedDecls,
Global = Statements | FunctionDecls | ModuleDecls | ClassDecls | InterfaceDecls | AmbientDecls,
FunctionBody = Statements | FunctionDecls,
ModuleMembers = TypedFuncDecls | FunctionDecls | ModuleDecls | ClassDecls | InterfaceDecls | TypedDecls | Statements | AmbientDecls,
ClassMembers = TypedFuncDecls | FunctionDecls | Statements | TypedDecls | Properties,
InterfaceMembers = TypedFuncSignatures | TypedSignatures,
QuickParse = Global | Properties,
}
export enum Modifiers {
None = 0,
Private = 1,
Public = 1 << 1,
Readonly = 1 << 2,
Ambient = 1 << 3,
Exported = 1 << 4,
Getter = 1 << 5,
Setter = 1 << 6,
Static = 1 << 7,
}
export enum ASTFlags {
None = 0,
ExplicitSemicolon = 1, // statment terminated by an explicit semicolon
AutomaticSemicolon = 1 << 1, // statment terminated by an automatic semicolon
Writeable = 1 << 2, // node is lhs that can be modified
Error = 1 << 3, // node has an error
DotLHSPartial = 1 << 4, // node is the lhs of an incomplete dot expr at cursor
DotLHS = 1 << 5, // node is the lhs of a dot expr
IsStatement = 1 << 6, // node is a statement
StrictMode = 1 << 7, // node is in the strict mode environment
PossibleOptionalParameter = 1 << 8,
ClassBaseConstructorCall = 1 << 9,
OptionalName = 1 << 10,
}
export enum DeclFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
}
export enum ModuleFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
IsEnum = 1 << 8,
ShouldEmitModuleDecl = 1 << 9,
IsWholeFile = 1 << 10,
IsDynamic = 1 << 11,
}
export enum SymbolFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
Property = 1 << 8,
Readonly = 1 << 9,
ModuleMember = 1 << 10,
InterfaceMember = 1 << 11,
ClassMember = 1 << 12,
BuiltIn = 1 << 13,
TypeSetDuringScopeAssignment = 1 << 14,
Constant = 1 << 15,
Optional = 1 << 16,
RecursivelyReferenced = 1 << 17,
Bound = 1 << 18,
}
export enum VarFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
AutoInit = 1 << 8,
Property = 1 << 9,
Readonly = 1 << 10,
Class = 1 << 11,
ClassProperty = 1 << 12,
ClassBodyProperty = 1 << 13,
ClassConstructorProperty = 1 << 14,
ClassSuperMustBeFirstCallInConstructor = 1 << 15,
Constant = 1 << 16,
}
export enum FncFlags {
None = 0,
Exported = 1,
Private = 1 << 1,
Public = 1 << 2,
Ambient = 1 << 3,
Static = 1 << 4,
LocalStatic = 1 << 5,
GetAccessor = 1 << 6,
SetAccessor = 1 << 7,
Definition = 1 << 8,
Signature = 1 << 9,
Method = 1 << 10,
HasReturnExpression = 1 << 11,
CallMember = 1 << 12,
ConstructMember = 1 << 13,
HasSelfReference = 1 << 14,
IsFatArrowFunction = 1 << 15,
IndexerMember = 1 << 16,
IsFunctionExpression = 1 << 17,
ClassMethod = 1 << 18,
ClassPropertyMethodExported = 1 << 19,
}
export enum SignatureFlags {
None = 0,
IsIndexer = 1,
IsStringIndexer = 1 << 1,
IsNumberIndexer = 1 << 2,
}
export function ToDeclFlags(fncFlags: FncFlags) : DeclFlags;
export function ToDeclFlags(varFlags: VarFlags) : DeclFlags;
export function ToDeclFlags(symFlags: SymbolFlags): DeclFlags;
export function ToDeclFlags(moduleFlags: ModuleFlags): DeclFlags;
export function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags: any) {
return <DeclFlags>fncOrVarOrSymbolOrModuleFlags;
}
export enum TypeFlags {
None = 0,
HasImplementation = 1,
HasSelfReference = 1 << 1,
MergeResult = 1 << 2,
IsEnum = 1 << 3,
BuildingName = 1 << 4,
HasBaseType = 1 << 5,
HasBaseTypeOfObject = 1 << 6,
IsClass = 1 << 7,
}
export enum TypeRelationshipFlags {
SuccessfulComparison = 0,
SourceIsNullTargetIsVoidOrUndefined = 1,
RequiredPropertyIsMissing = 1 << 1,
IncompatibleSignatures = 1 << 2,
SourceSignatureHasTooManyParameters = 3,
IncompatibleReturnTypes = 1 << 4,
IncompatiblePropertyTypes = 1 << 5,
IncompatibleParameterTypes = 1 << 6,
}
export enum CodeGenTarget {
ES3 = 0,
ES5 = 1,
}
export enum ModuleGenTarget {
Synchronous = 0,
Asynchronous = 1,
Local = 1 << 1,
}
// Compiler defaults to generating ES5-compliant code for
// - getters and setters
export var codeGenTarget: CodeGenTarget = CodeGenTarget.ES3;
export var moduleGenTarget: ModuleGenTarget = ModuleGenTarget.Synchronous;
export var optimizeModuleCodeGen = true;
export function | (e, flags: number): string {
var builder = "";
for (var i = 1; i < (1 << 31) ; i = i << 1) {
if ((flags & i) != 0) {
for (var k in e) {
if (e[k] == i) {
if (builder.length > 0) {
builder += "|";
}
builder += k;
break;
}
}
}
}
return builder;
}
} | flagsToString | identifier_name |
get.js | import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) |
export default get;
| {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
} | identifier_body |
get.js | import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function | (object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
export default get;
| get | identifier_name |
get.js | import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
} | export default get; | random_line_split | |
partialpressure.component.ts | import { Component } from '@angular/core';
import { BlendCalculatorService } from '../../services/blendCalculator.service';
import { MeasureMode } from '../../models/calculator/measureMode';
import { Gas } from '../../models/calculator/gas';
import { PartialPressureRequest } from '../../models/calculator/partialPressureRequest';
import { PartialPressureResult } from '../../models/calculator/partialPressureResult';
@Component({
selector: 'partialpressure',
templateUrl: './partialpressure.component.html',
styleUrls: ['./partialpressure.component.css']
})
export class PartialPressureComponent {
private readonly service: BlendCalculatorService;
ppImperialSelected: boolean;
ppMeasurement: string;
depth: number;
result: PartialPressureResult;
gas: Gas;
constructor(calculator: BlendCalculatorService) {
this.service = calculator;
this.gas = new Gas();
}
ngOnInit() {
this.gas.oxygen = 21;
this.gas.nitrogen = 79;
this.gas.helium = 0;
this.depth = 0;
this.ppSystemSelectionChange(true);
}
ppSystemSelectionChange(value: boolean): void {
| ppUpdateGas(gas: Gas): void {
this.gas = gas;
let request = new PartialPressureRequest();
request.depth = this.depth;
request.gas = this.gas;
request.system = this.ppImperialSelected ? MeasureMode.Imperial : MeasureMode.Metric;
this.result = this.service.calculatePartialPressure(request);
}
ppUpdateDepth(): void {
this.ppUpdateGas(this.gas);
}
} | this.ppImperialSelected = value;
this.ppMeasurement = this.ppImperialSelected ? 'feet' : 'meeters';
this.ppUpdateDepth();
}
| identifier_body |
partialpressure.component.ts | import { Component } from '@angular/core';
import { BlendCalculatorService } from '../../services/blendCalculator.service';
import { MeasureMode } from '../../models/calculator/measureMode';
import { Gas } from '../../models/calculator/gas';
import { PartialPressureRequest } from '../../models/calculator/partialPressureRequest';
import { PartialPressureResult } from '../../models/calculator/partialPressureResult';
@Component({
selector: 'partialpressure',
templateUrl: './partialpressure.component.html',
styleUrls: ['./partialpressure.component.css']
})
export class PartialPressureComponent {
private readonly service: BlendCalculatorService;
ppImperialSelected: boolean;
ppMeasurement: string;
depth: number;
result: PartialPressureResult;
gas: Gas;
co | alculator: BlendCalculatorService) {
this.service = calculator;
this.gas = new Gas();
}
ngOnInit() {
this.gas.oxygen = 21;
this.gas.nitrogen = 79;
this.gas.helium = 0;
this.depth = 0;
this.ppSystemSelectionChange(true);
}
ppSystemSelectionChange(value: boolean): void {
this.ppImperialSelected = value;
this.ppMeasurement = this.ppImperialSelected ? 'feet' : 'meeters';
this.ppUpdateDepth();
}
ppUpdateGas(gas: Gas): void {
this.gas = gas;
let request = new PartialPressureRequest();
request.depth = this.depth;
request.gas = this.gas;
request.system = this.ppImperialSelected ? MeasureMode.Imperial : MeasureMode.Metric;
this.result = this.service.calculatePartialPressure(request);
}
ppUpdateDepth(): void {
this.ppUpdateGas(this.gas);
}
} | nstructor(c | identifier_name |
partialpressure.component.ts | import { Component } from '@angular/core';
import { BlendCalculatorService } from '../../services/blendCalculator.service';
import { MeasureMode } from '../../models/calculator/measureMode';
import { Gas } from '../../models/calculator/gas';
import { PartialPressureRequest } from '../../models/calculator/partialPressureRequest';
import { PartialPressureResult } from '../../models/calculator/partialPressureResult';
@Component({
selector: 'partialpressure',
templateUrl: './partialpressure.component.html',
styleUrls: ['./partialpressure.component.css']
})
export class PartialPressureComponent {
private readonly service: BlendCalculatorService;
ppImperialSelected: boolean;
ppMeasurement: string; | gas: Gas;
constructor(calculator: BlendCalculatorService) {
this.service = calculator;
this.gas = new Gas();
}
ngOnInit() {
this.gas.oxygen = 21;
this.gas.nitrogen = 79;
this.gas.helium = 0;
this.depth = 0;
this.ppSystemSelectionChange(true);
}
ppSystemSelectionChange(value: boolean): void {
this.ppImperialSelected = value;
this.ppMeasurement = this.ppImperialSelected ? 'feet' : 'meeters';
this.ppUpdateDepth();
}
ppUpdateGas(gas: Gas): void {
this.gas = gas;
let request = new PartialPressureRequest();
request.depth = this.depth;
request.gas = this.gas;
request.system = this.ppImperialSelected ? MeasureMode.Imperial : MeasureMode.Metric;
this.result = this.service.calculatePartialPressure(request);
}
ppUpdateDepth(): void {
this.ppUpdateGas(this.gas);
}
} | depth: number;
result: PartialPressureResult; | random_line_split |
submaker_updatezip.py | from .submaker import Submaker
from inception.tools.signapk import SignApk
import shutil
import os
from inception.constants import InceptionConstants
class UpdatezipSubmaker(Submaker):
def make(self, updatePkgDir):
| keys_name = self.getValue("keys")
signingKeys = self.getMaker().getConfig().getKeyConfig(keys_name) if keys_name else None
updateBinaryKey, updateBinary = self.getTargetBinary("update-binary")
assert updateBinary, "%s is not set" % updateBinaryKey
if keys_name:
assert signingKeys, "update.keys is '%s' but __config__.host.keys.%s is not set" % (keys_name, keys_name)
signingKeys = signingKeys["private"], signingKeys["public"]
shutil.copy(updateBinary, os.path.join(updatePkgDir, "META-INF/com/google/android/update-binary"))
updateZipPath = updatePkgDir + "/../"
updateZipPath += "update_unsigned" if signingKeys else "update"
shutil.make_archive(updateZipPath, "zip", updatePkgDir)
updateZipPath += ".zip"
if signingKeys:
javaKey, javaPath = self.getHostBinary("java")
signApkKey, signApkPath = self.getHostBinary("signapk")
assert signApkPath, "%s is not set" % signApkKey
assert os.path.exists(signApkPath), "'%s' from %s does not exist" % (signApkPath, signApkKey)
assert os.path.exists(javaPath), "'%s' from %s does not exist" % (javaPath, javaKey)
signApk = SignApk(javaPath, signApkPath)
targetPath = updatePkgDir + "/../" + InceptionConstants.OUT_NAME_UPDATE
signApk.sign(updateZipPath, targetPath, signingKeys[0], signingKeys[1])
updateZipPath = targetPath
return updateZipPath | identifier_body | |
submaker_updatezip.py | from .submaker import Submaker
from inception.tools.signapk import SignApk
import shutil
import os
from inception.constants import InceptionConstants
class UpdatezipSubmaker(Submaker):
def make(self, updatePkgDir):
keys_name = self.getValue("keys")
signingKeys = self.getMaker().getConfig().getKeyConfig(keys_name) if keys_name else None
updateBinaryKey, updateBinary = self.getTargetBinary("update-binary")
assert updateBinary, "%s is not set" % updateBinaryKey
if keys_name:
assert signingKeys, "update.keys is '%s' but __config__.host.keys.%s is not set" % (keys_name, keys_name)
signingKeys = signingKeys["private"], signingKeys["public"]
shutil.copy(updateBinary, os.path.join(updatePkgDir, "META-INF/com/google/android/update-binary"))
updateZipPath = updatePkgDir + "/../"
updateZipPath += "update_unsigned" if signingKeys else "update"
shutil.make_archive(updateZipPath, "zip", updatePkgDir)
updateZipPath += ".zip"
if signingKeys:
|
return updateZipPath
| javaKey, javaPath = self.getHostBinary("java")
signApkKey, signApkPath = self.getHostBinary("signapk")
assert signApkPath, "%s is not set" % signApkKey
assert os.path.exists(signApkPath), "'%s' from %s does not exist" % (signApkPath, signApkKey)
assert os.path.exists(javaPath), "'%s' from %s does not exist" % (javaPath, javaKey)
signApk = SignApk(javaPath, signApkPath)
targetPath = updatePkgDir + "/../" + InceptionConstants.OUT_NAME_UPDATE
signApk.sign(updateZipPath, targetPath, signingKeys[0], signingKeys[1])
updateZipPath = targetPath | conditional_block |
submaker_updatezip.py | from .submaker import Submaker
from inception.tools.signapk import SignApk
import shutil
import os
from inception.constants import InceptionConstants
class UpdatezipSubmaker(Submaker):
def make(self, updatePkgDir):
keys_name = self.getValue("keys")
signingKeys = self.getMaker().getConfig().getKeyConfig(keys_name) if keys_name else None
updateBinaryKey, updateBinary = self.getTargetBinary("update-binary")
assert updateBinary, "%s is not set" % updateBinaryKey
if keys_name:
assert signingKeys, "update.keys is '%s' but __config__.host.keys.%s is not set" % (keys_name, keys_name)
signingKeys = signingKeys["private"], signingKeys["public"]
shutil.copy(updateBinary, os.path.join(updatePkgDir, "META-INF/com/google/android/update-binary"))
updateZipPath = updatePkgDir + "/../"
updateZipPath += "update_unsigned" if signingKeys else "update"
shutil.make_archive(updateZipPath, "zip", updatePkgDir)
updateZipPath += ".zip"
if signingKeys:
javaKey, javaPath = self.getHostBinary("java")
signApkKey, signApkPath = self.getHostBinary("signapk")
assert signApkPath, "%s is not set" % signApkKey
assert os.path.exists(signApkPath), "'%s' from %s does not exist" % (signApkPath, signApkKey)
assert os.path.exists(javaPath), "'%s' from %s does not exist" % (javaPath, javaKey)
signApk = SignApk(javaPath, signApkPath)
targetPath = updatePkgDir + "/../" + InceptionConstants.OUT_NAME_UPDATE
signApk.sign(updateZipPath, targetPath, signingKeys[0], signingKeys[1])
updateZipPath = targetPath | return updateZipPath | random_line_split | |
submaker_updatezip.py | from .submaker import Submaker
from inception.tools.signapk import SignApk
import shutil
import os
from inception.constants import InceptionConstants
class | (Submaker):
def make(self, updatePkgDir):
keys_name = self.getValue("keys")
signingKeys = self.getMaker().getConfig().getKeyConfig(keys_name) if keys_name else None
updateBinaryKey, updateBinary = self.getTargetBinary("update-binary")
assert updateBinary, "%s is not set" % updateBinaryKey
if keys_name:
assert signingKeys, "update.keys is '%s' but __config__.host.keys.%s is not set" % (keys_name, keys_name)
signingKeys = signingKeys["private"], signingKeys["public"]
shutil.copy(updateBinary, os.path.join(updatePkgDir, "META-INF/com/google/android/update-binary"))
updateZipPath = updatePkgDir + "/../"
updateZipPath += "update_unsigned" if signingKeys else "update"
shutil.make_archive(updateZipPath, "zip", updatePkgDir)
updateZipPath += ".zip"
if signingKeys:
javaKey, javaPath = self.getHostBinary("java")
signApkKey, signApkPath = self.getHostBinary("signapk")
assert signApkPath, "%s is not set" % signApkKey
assert os.path.exists(signApkPath), "'%s' from %s does not exist" % (signApkPath, signApkKey)
assert os.path.exists(javaPath), "'%s' from %s does not exist" % (javaPath, javaKey)
signApk = SignApk(javaPath, signApkPath)
targetPath = updatePkgDir + "/../" + InceptionConstants.OUT_NAME_UPDATE
signApk.sign(updateZipPath, targetPath, signingKeys[0], signingKeys[1])
updateZipPath = targetPath
return updateZipPath
| UpdatezipSubmaker | identifier_name |
generate-certs.py | #!/usr/bin/python
# Copyright (c) 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A chain with four possible intermediates with different notBefore and notAfter
dates, for testing path bulding prioritization.
"""
import sys
sys.path += ['../..']
import gencerts
DATE_A = '150101120000Z'
DATE_B = '150102120000Z'
DATE_C = '180101120000Z'
DATE_D = '180102120000Z' |
int_ac = gencerts.create_intermediate_certificate('Intermediate', root)
int_ac.set_validity_range(DATE_A, DATE_C)
int_ad = gencerts.create_intermediate_certificate('Intermediate', root)
int_ad.set_validity_range(DATE_A, DATE_D)
int_ad.set_key(int_ac.get_key())
int_bc = gencerts.create_intermediate_certificate('Intermediate', root)
int_bc.set_validity_range(DATE_B, DATE_C)
int_bc.set_key(int_ac.get_key())
int_bd = gencerts.create_intermediate_certificate('Intermediate', root)
int_bd.set_validity_range(DATE_B, DATE_D)
int_bd.set_key(int_ac.get_key())
target = gencerts.create_end_entity_certificate('Target', int_ac)
target.set_validity_range(DATE_A, DATE_D)
gencerts.write_chain('The root', [root], out_pem='root.pem')
gencerts.write_chain('Intermediate with validity range A..C',
[int_ac], out_pem='int_ac.pem')
gencerts.write_chain('Intermediate with validity range A..D',
[int_ad], out_pem='int_ad.pem')
gencerts.write_chain('Intermediate with validity range B..C',
[int_bc], out_pem='int_bc.pem')
gencerts.write_chain('Intermediate with validity range B..D',
[int_bd], out_pem='int_bd.pem')
gencerts.write_chain('The target', [target], out_pem='target.pem') |
root = gencerts.create_self_signed_root_certificate('Root')
root.set_validity_range(DATE_A, DATE_D) | random_line_split |
blob.test.ts | /**
* Copyright 2017 Google 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.
*/
import { assert } from 'chai';
import * as sinon from 'sinon';
import { FbsBlob } from '../src/implementation/blob';
import * as type from '../src/implementation/type';
import * as testShared from './testshared';
describe('Firebase Storage > Blob', () => {
let stubs = [];
before(() => {
const definedStub = sinon.stub(type, 'isNativeBlobDefined');
definedStub.returns(false);
stubs.push(definedStub);
const blobStub = sinon.stub(window, 'Blob');
blobStub.throws(Error("I don't exist"));
stubs.push(blobStub);
});
after(() => {
stubs.forEach(stub => {
stub.restore();
});
stubs = [];
});
it('Slicing works', () => {
const blob = new FbsBlob(new Uint8Array([1, 2, 3, 4, 5, 6, 7]));
const sliced = blob.slice(1, 5);
testShared.assertUint8ArrayEquals( | it('Blobs are merged with strings correctly', () => {
const blob = new FbsBlob(new Uint8Array([1, 2, 3, 4]));
const merged = FbsBlob.getBlob('what', blob, '\ud83d\ude0a ');
testShared.assertUint8ArrayEquals(
merged.uploadData() as Uint8Array,
new Uint8Array([
0x77,
0x68,
0x61,
0x74,
0x1,
0x2,
0x3,
0x4,
0xf0,
0x9f,
0x98,
0x8a,
0x20
])
);
});
it('Respects windowed views of ArrayBuffers when merging', () => {
const buf = new ArrayBuffer(100);
const arr1 = new Uint8Array(buf, 0, 10);
const arr2 = new Uint8Array(buf, 10, 10);
const blob1 = new FbsBlob(arr1, true);
const blob2 = new FbsBlob(arr2, true);
const concatenated = FbsBlob.getBlob(blob1, blob2);
assert.equal(20, concatenated.size());
});
}); | sliced.uploadData() as Uint8Array,
new Uint8Array([2, 3, 4, 5])
);
}); | random_line_split |
execute_brainfuck.rs | // http://rosettacode.org/wiki/Execute_Brain****
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} [path] (--debug)", args[0]);
return;
}
let src: Vec<char> = {
let mut buf = String::new();
match File::open(&args[1])
{
Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); }
Err(e) => {
println!("Error opening '{}': {}", args[1], e);
return;
}
}
buf.chars().collect()
};
// Launch options
let debug = args.contains(&"--debug".to_owned());
// One pass to find bracket pairs.
let brackets: HashMap<usize, usize> = {
let mut m = HashMap::new();
let mut scope_stack = Vec::new();
for (idx, ch) in src.iter().enumerate() {
match ch {
&'[' => { scope_stack.push(idx); }
&']' => { m.insert(scope_stack.pop().unwrap(), idx); }
_ => { /* ignore */ }
}
}
m
};
let mut pc: usize = 0; // Program counter
let mut mem: [Wrapping<u8>;5000] = [Wrapping(0);5000]; // Program cemory
let mut ptr: usize = 0; // Pointer
let mut stack: Vec<usize> = Vec::new(); // Bracket stack
let stdin_ = stdin();
let mut reader = stdin_.lock().bytes();
while pc < src.len() {
let Wrapping(val) = mem[ptr];
if debug {
println!("(BFDB) PC: {:04} \tPTR: {:04} \t$PTR: {:03} \tSTACK_DEPTH: {} \tSYMBOL: {}",
pc, ptr, val, stack.len(), src[pc]);
}
const ONE: Wrapping<u8> = Wrapping(1);
match src[pc] {
'>' => { ptr += 1; }
'<' => { ptr -= 1; }
'+' => { mem[ptr] = mem[ptr] + ONE; }
'-' => { mem[ptr] = mem[ptr] - ONE; }
'[' => {
if val == 0 {
pc = brackets[&pc];
} else {
stack.push(pc);
}
}
']' => {
let matching_bracket = stack.pop().unwrap();
if val != 0 {
pc = matching_bracket - 1;
}
}
'.' => {
if debug | else {
print!("{}", val as char);
}
}
',' => {
mem[ptr] = Wrapping(reader.next().unwrap().unwrap());
}
_ => { /* ignore */ }
}
pc += 1;
}
}
| {
println!("(BFDB) STDOUT: '{}'", val as char); // Intercept output
} | conditional_block |
execute_brainfuck.rs | // http://rosettacode.org/wiki/Execute_Brain****
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;
fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} [path] (--debug)", args[0]);
return;
}
let src: Vec<char> = {
let mut buf = String::new();
match File::open(&args[1])
{
Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); }
Err(e) => {
println!("Error opening '{}': {}", args[1], e);
return;
}
}
buf.chars().collect()
};
// Launch options
let debug = args.contains(&"--debug".to_owned());
// One pass to find bracket pairs.
let brackets: HashMap<usize, usize> = {
let mut m = HashMap::new();
let mut scope_stack = Vec::new();
for (idx, ch) in src.iter().enumerate() {
match ch {
&'[' => { scope_stack.push(idx); }
&']' => { m.insert(scope_stack.pop().unwrap(), idx); }
_ => { /* ignore */ }
}
}
m
};
let mut pc: usize = 0; // Program counter
let mut mem: [Wrapping<u8>;5000] = [Wrapping(0);5000]; // Program cemory
let mut ptr: usize = 0; // Pointer
let mut stack: Vec<usize> = Vec::new(); // Bracket stack
let stdin_ = stdin();
let mut reader = stdin_.lock().bytes();
while pc < src.len() {
let Wrapping(val) = mem[ptr];
if debug {
println!("(BFDB) PC: {:04} \tPTR: {:04} \t$PTR: {:03} \tSTACK_DEPTH: {} \tSYMBOL: {}",
pc, ptr, val, stack.len(), src[pc]);
}
const ONE: Wrapping<u8> = Wrapping(1);
match src[pc] {
'>' => { ptr += 1; }
'<' => { ptr -= 1; }
'+' => { mem[ptr] = mem[ptr] + ONE; }
'-' => { mem[ptr] = mem[ptr] - ONE; }
'[' => {
if val == 0 {
pc = brackets[&pc];
} else {
stack.push(pc);
}
}
']' => {
let matching_bracket = stack.pop().unwrap();
if val != 0 {
pc = matching_bracket - 1;
}
}
'.' => {
if debug {
println!("(BFDB) STDOUT: '{}'", val as char); // Intercept output | ',' => {
mem[ptr] = Wrapping(reader.next().unwrap().unwrap());
}
_ => { /* ignore */ }
}
pc += 1;
}
} | } else {
print!("{}", val as char);
}
} | random_line_split |
execute_brainfuck.rs | // http://rosettacode.org/wiki/Execute_Brain****
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;
fn | () {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} [path] (--debug)", args[0]);
return;
}
let src: Vec<char> = {
let mut buf = String::new();
match File::open(&args[1])
{
Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); }
Err(e) => {
println!("Error opening '{}': {}", args[1], e);
return;
}
}
buf.chars().collect()
};
// Launch options
let debug = args.contains(&"--debug".to_owned());
// One pass to find bracket pairs.
let brackets: HashMap<usize, usize> = {
let mut m = HashMap::new();
let mut scope_stack = Vec::new();
for (idx, ch) in src.iter().enumerate() {
match ch {
&'[' => { scope_stack.push(idx); }
&']' => { m.insert(scope_stack.pop().unwrap(), idx); }
_ => { /* ignore */ }
}
}
m
};
let mut pc: usize = 0; // Program counter
let mut mem: [Wrapping<u8>;5000] = [Wrapping(0);5000]; // Program cemory
let mut ptr: usize = 0; // Pointer
let mut stack: Vec<usize> = Vec::new(); // Bracket stack
let stdin_ = stdin();
let mut reader = stdin_.lock().bytes();
while pc < src.len() {
let Wrapping(val) = mem[ptr];
if debug {
println!("(BFDB) PC: {:04} \tPTR: {:04} \t$PTR: {:03} \tSTACK_DEPTH: {} \tSYMBOL: {}",
pc, ptr, val, stack.len(), src[pc]);
}
const ONE: Wrapping<u8> = Wrapping(1);
match src[pc] {
'>' => { ptr += 1; }
'<' => { ptr -= 1; }
'+' => { mem[ptr] = mem[ptr] + ONE; }
'-' => { mem[ptr] = mem[ptr] - ONE; }
'[' => {
if val == 0 {
pc = brackets[&pc];
} else {
stack.push(pc);
}
}
']' => {
let matching_bracket = stack.pop().unwrap();
if val != 0 {
pc = matching_bracket - 1;
}
}
'.' => {
if debug {
println!("(BFDB) STDOUT: '{}'", val as char); // Intercept output
} else {
print!("{}", val as char);
}
}
',' => {
mem[ptr] = Wrapping(reader.next().unwrap().unwrap());
}
_ => { /* ignore */ }
}
pc += 1;
}
}
| main | identifier_name |
execute_brainfuck.rs | // http://rosettacode.org/wiki/Execute_Brain****
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::stdin;
use std::num::Wrapping;
fn main() | {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: {} [path] (--debug)", args[0]);
return;
}
let src: Vec<char> = {
let mut buf = String::new();
match File::open(&args[1])
{
Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); }
Err(e) => {
println!("Error opening '{}': {}", args[1], e);
return;
}
}
buf.chars().collect()
};
// Launch options
let debug = args.contains(&"--debug".to_owned());
// One pass to find bracket pairs.
let brackets: HashMap<usize, usize> = {
let mut m = HashMap::new();
let mut scope_stack = Vec::new();
for (idx, ch) in src.iter().enumerate() {
match ch {
&'[' => { scope_stack.push(idx); }
&']' => { m.insert(scope_stack.pop().unwrap(), idx); }
_ => { /* ignore */ }
}
}
m
};
let mut pc: usize = 0; // Program counter
let mut mem: [Wrapping<u8>;5000] = [Wrapping(0);5000]; // Program cemory
let mut ptr: usize = 0; // Pointer
let mut stack: Vec<usize> = Vec::new(); // Bracket stack
let stdin_ = stdin();
let mut reader = stdin_.lock().bytes();
while pc < src.len() {
let Wrapping(val) = mem[ptr];
if debug {
println!("(BFDB) PC: {:04} \tPTR: {:04} \t$PTR: {:03} \tSTACK_DEPTH: {} \tSYMBOL: {}",
pc, ptr, val, stack.len(), src[pc]);
}
const ONE: Wrapping<u8> = Wrapping(1);
match src[pc] {
'>' => { ptr += 1; }
'<' => { ptr -= 1; }
'+' => { mem[ptr] = mem[ptr] + ONE; }
'-' => { mem[ptr] = mem[ptr] - ONE; }
'[' => {
if val == 0 {
pc = brackets[&pc];
} else {
stack.push(pc);
}
}
']' => {
let matching_bracket = stack.pop().unwrap();
if val != 0 {
pc = matching_bracket - 1;
}
}
'.' => {
if debug {
println!("(BFDB) STDOUT: '{}'", val as char); // Intercept output
} else {
print!("{}", val as char);
}
}
',' => {
mem[ptr] = Wrapping(reader.next().unwrap().unwrap());
}
_ => { /* ignore */ }
}
pc += 1;
}
} | identifier_body | |
strict_and_lenient_forms.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::request::{Form, LenientForm};
use rocket::http::RawStr;
#[derive(FromForm)]
struct | <'r> {
field: &'r RawStr,
}
#[post("/strict", data = "<form>")]
fn strict<'r>(form: Form<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
#[post("/lenient", data = "<form>")]
fn lenient<'r>(form: LenientForm<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
mod strict_and_lenient_forms_tests {
use super::*;
use rocket::local::Client;
use rocket::http::{Status, ContentType};
const FIELD_VALUE: &str = "just_some_value";
fn client() -> Client {
Client::new(rocket::ignite().mount("/", routes![strict, lenient])).unwrap()
}
#[test]
fn test_strict_form() {
let client = client();
let mut response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
let response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::UnprocessableEntity);
}
#[test]
fn test_lenient_form() {
let client = client();
let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
}
}
| MyForm | identifier_name |
strict_and_lenient_forms.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::request::{Form, LenientForm};
use rocket::http::RawStr;
#[derive(FromForm)]
struct MyForm<'r> {
field: &'r RawStr,
}
#[post("/strict", data = "<form>")]
fn strict<'r>(form: Form<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
#[post("/lenient", data = "<form>")]
fn lenient<'r>(form: LenientForm<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
mod strict_and_lenient_forms_tests {
use super::*;
use rocket::local::Client;
use rocket::http::{Status, ContentType};
const FIELD_VALUE: &str = "just_some_value";
fn client() -> Client {
Client::new(rocket::ignite().mount("/", routes![strict, lenient])).unwrap()
}
#[test]
fn test_strict_form() {
let client = client();
let mut response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
let response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::UnprocessableEntity);
}
#[test]
fn test_lenient_form() {
let client = client();
let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch();
| let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
}
} | assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
| random_line_split |
strict_and_lenient_forms.rs | #![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
use rocket::request::{Form, LenientForm};
use rocket::http::RawStr;
#[derive(FromForm)]
struct MyForm<'r> {
field: &'r RawStr,
}
#[post("/strict", data = "<form>")]
fn strict<'r>(form: Form<'r, MyForm<'r>>) -> String |
#[post("/lenient", data = "<form>")]
fn lenient<'r>(form: LenientForm<'r, MyForm<'r>>) -> String {
form.get().field.as_str().into()
}
mod strict_and_lenient_forms_tests {
use super::*;
use rocket::local::Client;
use rocket::http::{Status, ContentType};
const FIELD_VALUE: &str = "just_some_value";
fn client() -> Client {
Client::new(rocket::ignite().mount("/", routes![strict, lenient])).unwrap()
}
#[test]
fn test_strict_form() {
let client = client();
let mut response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
let response = client.post("/strict")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::UnprocessableEntity);
}
#[test]
fn test_lenient_form() {
let client = client();
let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
let mut response = client.post("/lenient")
.header(ContentType::Form)
.body(format!("field={}&extra=whoops", FIELD_VALUE))
.dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(response.body_string(), Some(FIELD_VALUE.into()));
}
}
| {
form.get().field.as_str().into()
} | identifier_body |
e12n.ts | import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import Outputs from '../../../../../resources/outputs';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
seenIntermission?: boolean;
bombs?: { north: boolean; east: boolean }[];
stacks?: string[];
tethers?: string[];
}
// EDEN'S PROMISE: ETERNITY
// E12 NORMAL
// TODO: Handle the EarthShaker bait --> beam intercept mechanic during the intermission.
// TODO: Math the spawn position of the Titanic Bomb Boulders to call the safe direction like E4s.
// Each tether ID corresponds to a primal:
// 008E -- Leviathan
// 008F -- Ifrit
// 0090 -- Ramuh
// 0091 -- Garuda
// We can collect + store these for later use on Stock/Release.
const tetherIds = ['008E', '008F', '0090', '0091'];
// Keys here indicate SAFE directions!
const bombOutputStrings = {
'north': {
en: 'Between north bombs',
de: 'Zwichen den Bomben im Norden',
fr: 'Entre les bombes au Nord',
ja: '北の岩へ',
cn: '去北边岩石中间',
ko: '북쪽 폭탄 사이',
},
'south': {
en: 'Between south bombs',
de: 'Zwichen den Bomben im Süden',
fr: 'Entre les bombes au Sud',
ja: '南の岩へ',
cn: '去南边岩石中间',
ko: '남쪽 폭탄 사이',
},
'east': {
en: 'Between east bombs',
de: 'Zwichen den Bomben im Osten',
fr: 'Entre les bombes à l\'Est',
ja: '東の岩へ',
cn: '去东边岩石中间',
ko: '동쪽 폭탄 사이',
},
'west': {
en: 'Between west bombs',
de: 'Zwichen den Bomben im Westen',
fr: 'Entre les bombes à l\'Ouest',
ja: '西の岩へ',
cn: '去西边岩石中间',
ko: '서쪽 폭탄 사이',
},
};
const primalOutputStrings = {
'combined': {
en: '${safespot1} + ${safespot2}',
de: '${safespot1} + ${safespot2}',
fr: '${safespot1} + ${safespot2}',
ja: '${safespot1} + ${safespot2}',
cn: '${safespot1} + ${safespot2}',
ko: '${safespot1} + ${safespot2}',
},
'008E': Outputs.middle,
'008F': Outputs.sides,
'0090': Outputs.out,
'0091': {
en: 'Intercards',
de: 'Interkardinale Himmelsrichtungen',
fr: 'Intercardinal',
ja: '斜め',
cn: '四角',
ko: '대각',
},
'008E008F': {
en: 'Under + Sides',
de: 'Unter Ihm + Seiten',
fr: 'En dessous + Côtés',
ja: '真ん中 + 横へ',
cn: '正中间两侧',
ko: '보스 아래 + 양옆',
},
'008E0090': {
en: 'North/South + Out',
de: 'Norden/Süden + Raus',
fr: 'Nord/Sud + Extérieur',
ja: '北/南 + 外へ',
cn: '南北远离',
ko: '북/남 + 바깥',
},
'008E0091': {
en: 'Under + Intercards',
de: 'Unter Ihm + Interkardinale Himmelsrichtungen',
fr: 'En dessous + Intercardinal',
ja: '真ん中 + 斜め',
cn: '正中间四角',
ko: '보스 아래 + 대각',
},
};
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.EdensPromiseEternity,
timelineFile: 'e12n.txt',
triggers: [
{
id: 'E12N Intermission Completion',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '4B48', source: 'Eden\'s Promise', capture: false }),
netRegexDe: NetRegexes.ability({ id: '4B48', source: 'Edens Verheißung', capture: false }),
netRegexFr: NetRegexes.ability({ id: '4B48', source: 'Promesse D\'Éden', capture: false }),
netRegexJa: NetRegexes.ability({ id: '4B48', source: 'プロミス・オブ・エデン', capture: false }),
netRegexCn: NetRegexes.ability({ id: '4B48', source: '伊甸之约', capture: false }),
netRegexKo: NetRegexes.ability({ id: '4B48', source: '에덴의 약속', capture: false }),
run: (data) => data.seenIntermission = true,
},
{
id: 'E12N Maleficium',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '5872', source: 'Eden\'s Promise', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '5872', source: 'Edens Verheißung', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '5872', source: 'Promesse D\'Éden', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '5872', source: 'プロミス・オブ・エデン', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '5872', source: '伊甸之约', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '5872', source: '에덴의 약속', capture: false }),
response: Responses.aoe(),
},
{
id: 'E12N Formless Judgment',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '5873', source: 'Eden\'s Promise' }),
netRegexDe: NetRegexes.startsUsing({ id: '5873', source: 'Edens Verheißung' }),
netRegexFr: NetRegexes.startsUsing({ id: '5873', source: 'Promesse D\'Éden' }),
netRegexJa: NetRegexes.startsUsing({ id: '5873', source: 'プロミス・オブ・エデン' }),
netRegexCn: NetRegexes.startsUsing({ id: '5873', source: '伊甸之约' }),
netRegexKo: NetRegexes.startsUsing({ id: '5873', source: '에덴의 약속' }),
response: Responses.tankCleave(),
},
{
// Titanic Bombs spawn at two of four points:
// SW X: -11.31371 Y: -63.68629
// NW X: -11.31371 Y: -86.3137
// SE X: 11.31371 Y: -63.68629
// NE X: 11.31371 Y: -86.3137
id: 'E12N Bomb Collect',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ npcNameId: '9816' }),
run: (data, matches) => {
const bomb = {
north: parseFloat(matches.y) + 70 < 0,
east: parseFloat(matches.x) > 0,
};
data.bombs ??= [];
data.bombs.push(bomb);
},
},
{
id: 'E12N Boulders Impact',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '586E', source: 'Titanic Bomb Boulder', capture: false }),
netRegexDe: NetRegexes.ability({ id: '586E', source: 'Mega-Bomber-Brocken', capture: false }),
netRegexFr: NetRegexes.ability({ id: '586E', source: 'Méga Bombo Rocher', capture: false }),
netRegexJa: NetRegexes.ability({ id: '586E', source: 'メガ・ボムボルダー', capture: false }),
netRegexCn: NetRegexes.ability({ id: '586E', source: '巨型爆破岩石', capture: false }),
netRegexKo: NetRegexes.ability({ id: '586E', source: '거대 바위폭탄', capture: false }),
suppressSeconds: 5,
infoText: (data, _matches, output) => {
// Whichever direction has two Titanic Bombs, the safe spot is opposite.
const [firstBomb, secondBomb] = data.bombs ?? [];
if (!firstBomb || !secondBomb)
return;
let safe;
if (firstBomb.north === secondBomb.north)
safe = firstBomb.north ? 'south' : 'north';
else
safe = firstBomb.east ? 'west' : 'east';
return output[safe]!();
},
run: (data) => delete data.bombs,
outputStrings: bombOutputStrings,
},
{
id: 'E12N Boulders Explosion',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '586F', source: 'Titanic Bomb Boulder', capture: false }),
netRegexDe: NetRegexes.ability({ id: '586F', source: 'Mega-Bomber-Brocken', capture: false }),
netRegexFr: NetRegexes.ability({ id: '586F', source: 'Méga Bombo Rocher', capture: false }),
netRegexJa: NetRegexes.ability({ id: '586F', source: 'メガ・ボムボルダー', capture: false }),
netRegexCn: NetRegexes.ability({ id: '586F', source: '巨型爆破岩石', capture: false }),
netRegexKo: NetRegexes.ability({ id: '586F', source: '거대 바위폭탄', capture: false }),
suppressSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Move to last explosions',
de: 'Zur letzten Explosion bewegen',
fr: 'Allez sur la dernière explosion',
ja: '最後に爆発した岩へ',
cn: '去最后爆炸的岩石旁',
ko: '마지막 폭발 위치로',
},
},
},
{
id: 'E12N Rapturous Reach Double',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E' }),
condition: (data) => !data.seenIntermission,
preRun: (data, matches) => { | },
alertText: (data, matches, output) => {
if (data.me === matches.target)
return output.stackOnYou!();
},
infoText: (data, _matches, output) => {
if (!data.stacks || data.stacks.length === 1)
return;
const names = data.stacks.map((x) => data.ShortName(x)).sort();
return output.stacks!({ players: names.join(', ') });
},
outputStrings: {
stacks: {
en: 'Stack (${players})',
de: 'Sammeln (${players})',
fr: 'Package sur (${players})',
ja: '頭割り (${players})',
cn: '分摊 (${players})',
ko: '모이기 (${players})',
},
stackOnYou: Outputs.stackOnYou,
},
},
{
id: 'E12N Rapturous Reach Cleanup',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E', capture: false }),
delaySeconds: 10,
run: (data) => delete data.stacks,
},
{
id: 'E12N Rapturous Reach Single',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E' }),
condition: (data) => data.seenIntermission,
response: Responses.stackMarkerOn(),
},
{
id: 'E12N Diamond Dust Mitigate',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '5864', source: 'Eden\'s Promise', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '5864', source: 'Edens Verheißung', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '5864', source: 'Promesse D\'Éden', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '5864', source: 'プロミス・オブ・エデン', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '5864', source: '伊甸之约', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '5864', source: '에덴의 약속', capture: false }),
response: Responses.aoe(),
},
{
id: 'E12N Diamond Dust Stop',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '5864', source: 'Eden\'s Promise', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '5864', source: 'Edens Verheißung', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '5864', source: 'Promesse D\'Éden', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '5864', source: 'プロミス・オブ・エデン', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '5864', source: '伊甸之约', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '5864', source: '에덴의 약속', capture: false }),
delaySeconds: 1, // Avoiding collision with the spread call
response: Responses.stopMoving('alert'),
},
{
id: 'E12N Frigid Stone',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0060' }),
condition: Conditions.targetIsYou(),
response: Responses.spread(),
},
{
id: 'E12N Tether Collect',
type: 'Tether',
netRegex: NetRegexes.tether({ id: tetherIds }),
run: (data, matches) => {
data.tethers ??= [];
data.tethers.push(matches.id);
},
},
{
id: 'E12N Cast Release',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: ['4E2C', '585B', '5861'], capture: false }),
preRun: (data) => data.tethers = data.tethers?.sort(),
delaySeconds: 0.5, // Tethers should be first in the log, but let's be SURE
alertText: (data, _matches, output) => {
const [firstTether, secondTether] = data.tethers ?? [];
if (!firstTether || !secondTether)
return;
// Leviathan's mechanics aren't easily described in a single word,
// so we special-case them.
const comboStr = firstTether + secondTether;
if (comboStr in primalOutputStrings)
return output[comboStr]!();
return output.combined!({
safespot1: output[firstTether]!(),
safespot2: output[secondTether]!(),
});
},
infoText: (data, _matches, output) => {
const onlyTether = data.tethers?.[0];
if (!onlyTether || data.tethers?.length === 2)
return;
return output[onlyTether]!();
},
outputStrings: primalOutputStrings,
},
{
id: 'E12N Tether Cleanup',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: ['4E2C', '585B', '5861'], capture: false }),
delaySeconds: 5,
run: (data) => delete data.tethers,
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'(?<!Titanic )Bomb Boulder': 'Bomber-Brocken',
'Chiseled Sculpture': 'Abbild eines Mannes',
'Eden\'s Promise': 'Edens Verheißung',
'Titanic Bomb Boulder': 'Mega-Bomber-Brocken',
},
'replaceText': {
'Cast': 'Auswerfen',
'Classical Sculpture': 'Klassische Skulptur',
'Conflag Strike': 'Feuersbrunst',
'Diamond Dust': 'Diamantenstaub',
'Earth Shaker': 'Erdstoß',
'Earthen Fury': 'Gaias Zorn',
'Eternal Oblivion': 'Ewiges Vergessen',
'Explosion': 'Explosion',
'Ferostorm': 'Angststurm',
'Formless Judgment': 'Formloses Urteil',
'Frigid Stone': 'Eisstein',
'Ice Floe': 'Eisfluss',
'Impact': 'Impakt',
'Initialize Recall': 'Rückholung initialisieren',
'Judgment Jolt': 'Blitz des Urteils',
'Junction Shiva': 'Verbindung: Shiva',
'Junction Titan': 'Verbindung: Titan',
'Laser Eye': 'Laserauge',
'Maleficium': 'Maleficium',
'Obliteration': 'Auslöschung',
'Palm Of Temperance': 'Hand der Mäßigung',
'Paradise Lost': 'Verlorenes Paradies',
'Rapturous Reach': 'Stürmischer Griff',
'Release': 'Freilassen',
'Stock': 'Sammeln',
'Temporary Current': 'Unstete Gezeiten',
'Under The Weight': 'Wucht der Erde',
},
},
{
'locale': 'fr',
'replaceSync': {
'(?<!Titanic )Bomb Boulder': 'bombo rocher',
'Chiseled Sculpture': 'création masculine',
'Eden\'s Promise': 'Promesse d\'Éden',
'Titanic Bomb Boulder': 'méga bombo rocher',
},
'replaceText': {
'\\?': ' ?',
'Cast': 'Lancer',
'Classical Sculpture': 'Serviteur colossal',
'Conflag Strike': 'Ekpurosis',
'Diamond Dust': 'Poussière de diamant',
'Earth Shaker': 'Secousse',
'Earthen Fury': 'Fureur tellurique',
'Eternal Oblivion': 'Oubli éternel',
'Explosion': 'Explosion',
'Ferostorm': 'Tempête déchaînée',
'Formless Judgment': 'Onde du châtiment',
'Frigid Stone': 'Rocher de glace',
'Ice Floe': 'Flux glacé',
'Impact': 'Impact',
'Initialize Recall': 'Remembrances',
'Judgment Jolt': 'Front orageux du jugement',
'Junction Shiva': 'Associer : Shiva',
'Junction Titan': 'Associer : Titan',
'Laser Eye': 'Faisceau maser',
'Maleficium': 'Maleficium',
'Obliteration': 'Oblitération',
'Palm Of Temperance': 'Paume de tempérance',
'Paradise Lost': 'Paradis perdu',
'Rapturous Reach': 'Main voluptueuse',
'Release': 'Relâcher',
'Stock': 'Stocker',
'Temporary Current': 'Courant évanescent',
'Under The Weight': 'Pression tellurique',
},
},
{
'locale': 'ja',
'replaceSync': {
'(?<!Titanic )Bomb Boulder': 'ボムボルダー',
'Chiseled Sculpture': '創られた男',
'Eden\'s Promise': 'プロミス・オブ・エデン',
'Titanic Bomb Boulder': 'メガ・ボムボルダー',
},
'replaceText': {
'Cast': 'はなつ',
'Classical Sculpture': '巨兵創出',
'Conflag Strike': 'コンフラグレーションストライク',
'Diamond Dust': 'ダイアモンドダスト',
'Earth Shaker': 'アースシェイカー',
'Earthen Fury': '大地の怒り',
'Eternal Oblivion': '永遠の忘却',
'Explosion': '爆発',
'Ferostorm': 'フィアスストーム',
'Formless Judgment': '天罰の波動',
'Frigid Stone': 'アイスストーン',
'Ice Floe': 'アイスフロー',
'Impact': 'インパクト',
'Initialize Recall': '記憶想起',
'Judgment Jolt': '裁きの界雷',
'Junction Shiva': 'ジャンクション:シヴァ',
'Junction Titan': 'ジャンクション:タイタン',
'Laser Eye': 'メーザーアイ',
'Maleficium': 'マレフィキウム',
'Obliteration': 'オブリタレーション',
'Palm Of Temperance': '拒絶の手',
'Paradise Lost': 'パラダイスロスト',
'Rapturous Reach': '悦楽の手',
'Release': 'リリース',
'Stock': 'ストック',
'Temporary Current': 'テンポラリーカレント',
'Under The Weight': '大地の重圧',
},
},
{
'locale': 'cn',
'replaceSync': {
'(?<!Titanic )Bomb Boulder': '爆破岩石',
'Chiseled Sculpture': '被创造的男性',
'Eden\'s Promise': '伊甸之约',
'Titanic Bomb Boulder': '巨型爆破岩石',
},
'replaceText': {
'Cast': '释放',
'Classical Sculpture': '创造巨兵',
'Conflag Strike': '瞬燃强袭',
'Diamond Dust': '钻石星尘',
'Earth Shaker': '大地摇动',
'Earthen Fury': '大地之怒',
'Eternal Oblivion': '永恒忘却',
'Explosion': '爆炸',
'Ferostorm': '凶猛风暴',
'Formless Judgment': '天罚波动',
'Frigid Stone': '冰石',
'Ice Floe': '浮冰',
'Impact': '冲击',
'Initialize Recall': '回想记忆',
'Judgment Jolt': '制裁之界雷',
'Junction Shiva': '融合:希瓦',
'Junction Titan': '融合:泰坦',
'Laser Eye': '激射眼',
'Maleficium': '邪法',
'Obliteration': '灭迹',
'Palm Of Temperance': '拒绝之手',
'Paradise Lost': '失乐园',
'Rapturous Reach': '愉悦之手',
'Release': '施放',
'Stock': '储存',
'Temporary Current': '临时洋流',
'Under The Weight': '大地的重压',
},
},
{
'locale': 'ko',
'replaceSync': {
'(?<!Titanic )Bomb Boulder': '바위폭탄',
'Chiseled Sculpture': '창조된 남자',
'Eden\'s Promise': '에덴의 약속',
'Titanic Bomb Boulder': '거대 바위폭탄',
},
'replaceText': {
'Cast': '발현',
'Classical Sculpture': '거병 창조',
'Conflag Strike': '대화재',
'Diamond Dust': '다이아몬드 더스트',
'Earth Shaker': '요동치는 대지',
'Earthen Fury': '대지의 분노',
'Eternal Oblivion': '영원한 망각',
'Explosion': '폭산',
'Ferostorm': '사나운 폭풍',
'Formless Judgment': '천벌 파동',
'Frigid Stone': '얼음돌',
'Ice Floe': '유빙',
'Impact': '충격',
'Initialize Recall': '기억 상기',
'Judgment Jolt': '심판의 계뢰',
'Junction Shiva': '접속: 시바',
'Junction Titan': '접속: 타이탄',
'Laser Eye': '광선안',
'Maleficium': '마녀의 사술',
'Obliteration': '말소',
'Palm Of Temperance': '거절의 손',
'Paradise Lost': '실낙원',
'Rapturous Reach': '열락의 손',
'Release': '기억 방출',
'Stock': '기억 보존',
'Temporary Current': '순간 해류',
'Under The Weight': '대지의 중압',
},
},
],
};
export default triggerSet; | data.stacks ??= [];
data.stacks.push(matches.target); | random_line_split |
constants.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
// Toast types
import { ToastType } from './types';
export { ToastType } from './types';
// for backward compatibility | export const DANGER_TOAST = ToastType.DANGER; | export const INFO_TOAST = ToastType.INFO;
export const SUCCES_TOAST = ToastType.SUCCESS;
export const WARNING_TOAST = ToastType.WARNING; | random_line_split |
main.rs | fn main() {
// demonstrate the Option<T> and Some
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("Five: {:?}", five);
println!("Six: {:?}", six);
println!("None: {:?}", none);
// simpler syntax if you want to do something with
// only one value (one pattern match)
let some_value = Some(3);
if let Some(3) = some_value {
println!("Found 3");
}
// same as if let but includes an else
if let Some(2) = some_value | else {
println!("Found something different");
}
}
fn plus_one(x: Option<i32>) -> Option<i32> {
// if no value, return none, otherwise return
// the addition of the value plus one
match x {
None => None,
Some(i) => Some(i + 1),
}
}
| {
println!("Found 2");
} | conditional_block |
main.rs | fn main() {
// demonstrate the Option<T> and Some
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("Five: {:?}", five);
println!("Six: {:?}", six);
println!("None: {:?}", none);
// simpler syntax if you want to do something with
// only one value (one pattern match)
let some_value = Some(3);
if let Some(3) = some_value {
println!("Found 3");
}
// same as if let but includes an else
if let Some(2) = some_value {
println!("Found 2");
} else {
println!("Found something different");
}
}
fn | (x: Option<i32>) -> Option<i32> {
// if no value, return none, otherwise return
// the addition of the value plus one
match x {
None => None,
Some(i) => Some(i + 1),
}
}
| plus_one | identifier_name |
main.rs | fn main() |
fn plus_one(x: Option<i32>) -> Option<i32> {
// if no value, return none, otherwise return
// the addition of the value plus one
match x {
None => None,
Some(i) => Some(i + 1),
}
}
| {
// demonstrate the Option<T> and Some
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("Five: {:?}", five);
println!("Six: {:?}", six);
println!("None: {:?}", none);
// simpler syntax if you want to do something with
// only one value (one pattern match)
let some_value = Some(3);
if let Some(3) = some_value {
println!("Found 3");
}
// same as if let but includes an else
if let Some(2) = some_value {
println!("Found 2");
} else {
println!("Found something different");
}
} | identifier_body |
ApplicationPlatformViewView.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
*/
import * as ibas from "ibas/index";
import * as openui5 from "openui5/index";
import * as bo from "../../../borep/bo/index";
import { IApplicationPlatformViewView } from "../../../bsapp/applicationplatform/index";
/**
* 视图-ApplicationPlatform
*/
export class ApplicationPlatformViewView extends ibas.BOViewView implements IApplicationPlatformViewView {
/** 绘制视图 */
darw(): any {
le | page: sap.m.Page;
private form: sap.ui.layout.form.SimpleForm;
/** 显示数据 */
showApplicationPlatform(data: bo.ApplicationPlatform): void {
this.form.setModel(new sap.ui.model.json.JSONModel(data));
}
}
| t that: this = this;
this.form = new sap.ui.layout.form.SimpleForm("", {
content: [
]
});
this.page = new sap.m.Page("", {
showHeader: false,
subHeader: new sap.m.Bar("", {
contentLeft: [
new sap.m.Button("", {
text: ibas.i18n.prop("shell_data_edit"),
type: sap.m.ButtonType.Transparent,
icon: "sap-icon://edit",
press: function (): void {
that.fireViewEvents(that.editDataEvent);
}
})
],
contentRight: [
new sap.m.Button("", {
type: sap.m.ButtonType.Transparent,
icon: "sap-icon://action",
press: function (event: any): void {
that.fireViewEvents(that.callServicesEvent, {
displayServices(services: ibas.IServiceAgent[]): void {
if (ibas.objects.isNull(services) || services.length === 0) {
return;
}
let popover: sap.m.Popover = new sap.m.Popover("", {
showHeader: false,
placement: sap.m.PlacementType.Bottom,
});
for (let service of services) {
popover.addContent(new sap.m.Button({
text: ibas.i18n.prop(service.name),
type: sap.m.ButtonType.Transparent,
icon: service.icon,
press: function (): void {
service.run();
popover.close();
}
}));
}
(<any>popover).addStyleClass("sapMOTAPopover sapTntToolHeaderPopover");
popover.openBy(event.getSource(), true);
}
});
}
})
]
}),
content: [this.form]
});
this.id = this.page.getId();
return this.page;
}
private | identifier_body |
ApplicationPlatformViewView.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
*/
import * as ibas from "ibas/index";
import * as openui5 from "openui5/index";
import * as bo from "../../../borep/bo/index";
import { IApplicationPlatformViewView } from "../../../bsapp/applicationplatform/index";
/**
* 视图-ApplicationPlatform
*/
export class ApplicationPlatformViewView extends ibas.BOViewView implements IApplicationPlatformViewView {
/** 绘制视图 */
darw(): any {
let that: this = this;
this.form = new sap.ui.layout.form.SimpleForm("", {
content: [
]
});
this.page = new sap.m.Page("", {
showHeader: false,
subHeader: new sap.m.Bar("", {
contentLeft: [
new sap.m.Button("", {
text: ibas.i18n.prop("shell_data_edit"),
type: sap.m.ButtonType.Transparent,
icon: "sap-icon://edit",
press: function (): void {
that.fireViewEvents(that.editDataEvent);
}
})
],
contentRight: [
new sap.m.Button("", {
type: sap.m.ButtonType.Transparent,
icon: "sap-icon://action",
press: function (event: any): void {
that.fireViewEvents(that.callServicesEvent, {
displayServices(services: ibas.IServiceAgent[]): void {
if (ibas.objects.isNull(services) || services.length === 0) {
| let popover: sap.m.Popover = new sap.m.Popover("", {
showHeader: false,
placement: sap.m.PlacementType.Bottom,
});
for (let service of services) {
popover.addContent(new sap.m.Button({
text: ibas.i18n.prop(service.name),
type: sap.m.ButtonType.Transparent,
icon: service.icon,
press: function (): void {
service.run();
popover.close();
}
}));
}
(<any>popover).addStyleClass("sapMOTAPopover sapTntToolHeaderPopover");
popover.openBy(event.getSource(), true);
}
});
}
})
]
}),
content: [this.form]
});
this.id = this.page.getId();
return this.page;
}
private page: sap.m.Page;
private form: sap.ui.layout.form.SimpleForm;
/** 显示数据 */
showApplicationPlatform(data: bo.ApplicationPlatform): void {
this.form.setModel(new sap.ui.model.json.JSONModel(data));
}
}
| return;
}
| conditional_block |
ApplicationPlatformViewView.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
*/
import * as ibas from "ibas/index";
import * as openui5 from "openui5/index";
import * as bo from "../../../borep/bo/index";
import { IApplicationPlatformViewView } from "../../../bsapp/applicationplatform/index";
/**
* 视图-ApplicationPlatform
*/
export class ApplicationPlatformViewView extends ibas.BOViewView implements IApplicationPlatformViewView {
/** 绘制视图 */
darw(): any {
let that: this = this;
this.form = new sap.ui.layout.form.SimpleForm("", {
content: [
]
});
this.page = new sap.m.Page("", {
showHeader: false,
subHeader: new sap.m.Bar("", {
contentLeft: [
new sap.m.Button("", {
text: ibas.i18n.prop("shell_data_edit"),
type: sap.m.ButtonType.Transparent,
icon: "sap-icon://edit",
press: function (): void {
that.fireViewEvents(that.editDataEvent);
}
})
],
contentRight: [
new sap.m.Button("", {
type: sap.m.ButtonType.Transparent,
icon: "sap-icon://action",
press: function (event: any): void {
that.fireViewEvents(that.callServicesEvent, {
displayServices(services: ibas.IServiceAgent[]): void {
if (ibas.objects.isNull(services) || services.length === 0) {
return;
}
let popover: sap.m.Popover = new sap.m.Popover("", {
showHeader: false,
placement: sap.m.PlacementType.Bottom,
});
for (let service of services) {
popover.addContent(new sap.m.Button({
text: ibas.i18n.prop(service.name), | icon: service.icon,
press: function (): void {
service.run();
popover.close();
}
}));
}
(<any>popover).addStyleClass("sapMOTAPopover sapTntToolHeaderPopover");
popover.openBy(event.getSource(), true);
}
});
}
})
]
}),
content: [this.form]
});
this.id = this.page.getId();
return this.page;
}
private page: sap.m.Page;
private form: sap.ui.layout.form.SimpleForm;
/** 显示数据 */
showApplicationPlatform(data: bo.ApplicationPlatform): void {
this.form.setModel(new sap.ui.model.json.JSONModel(data));
}
} | type: sap.m.ButtonType.Transparent, | random_line_split |
ApplicationPlatformViewView.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
*/
import * as ibas from "ibas/index";
import * as openui5 from "openui5/index";
import * as bo from "../../../borep/bo/index";
import { IApplicationPlatformViewView } from "../../../bsapp/applicationplatform/index";
/**
* 视图-ApplicationPlatform
*/
export class ApplicationPlatformViewView extends ibas.BOViewView implements IApplicationPlatformViewView {
/** 绘制视图 */
darw(): any | let that: this = this;
this.form = new sap.ui.layout.form.SimpleForm("", {
content: [
]
});
this.page = new sap.m.Page("", {
showHeader: false,
subHeader: new sap.m.Bar("", {
contentLeft: [
new sap.m.Button("", {
text: ibas.i18n.prop("shell_data_edit"),
type: sap.m.ButtonType.Transparent,
icon: "sap-icon://edit",
press: function (): void {
that.fireViewEvents(that.editDataEvent);
}
})
],
contentRight: [
new sap.m.Button("", {
type: sap.m.ButtonType.Transparent,
icon: "sap-icon://action",
press: function (event: any): void {
that.fireViewEvents(that.callServicesEvent, {
displayServices(services: ibas.IServiceAgent[]): void {
if (ibas.objects.isNull(services) || services.length === 0) {
return;
}
let popover: sap.m.Popover = new sap.m.Popover("", {
showHeader: false,
placement: sap.m.PlacementType.Bottom,
});
for (let service of services) {
popover.addContent(new sap.m.Button({
text: ibas.i18n.prop(service.name),
type: sap.m.ButtonType.Transparent,
icon: service.icon,
press: function (): void {
service.run();
popover.close();
}
}));
}
(<any>popover).addStyleClass("sapMOTAPopover sapTntToolHeaderPopover");
popover.openBy(event.getSource(), true);
}
});
}
})
]
}),
content: [this.form]
});
this.id = this.page.getId();
return this.page;
}
private page: sap.m.Page;
private form: sap.ui.layout.form.SimpleForm;
/** 显示数据 */
showApplicationPlatform(data: bo.ApplicationPlatform): void {
this.form.setModel(new sap.ui.model.json.JSONModel(data));
}
}
| {
| identifier_name |
molpro.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# HORTON is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>
#
# --
'''Molpro 2012 FCIDUMP format.
.. note ::
One- and two-electron integrals are stored in chemists' notation in an
FCIDUMP file while HORTON internally uses Physicist's notation.
'''
__all__ = ['load_fcidump', 'dump_fcidump']
def load_fcidump(filename, lf):
'''Read one- and two-electron integrals from a Molpro 2012 FCIDUMP file.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
generated with older versions are not supported.
**Arguments:**
filename
The filename of the fcidump file.
lf
A LinalgFactory instance.
**Returns**: A dictionary with keys: ``lf``, ``nelec``, ``ms2``,
``one_mo``, ``two_mo``, ``core_energy``
'''
with open(filename) as f:
# check header
line = f.next()
if not line.startswith(' &FCI NORB='):
raise IOError('Error in FCIDUMP file header')
# read info from header
words = line[5:].split(',')
header_info = {}
for word in words:
if word.count('=') == 1:
key, value = word.split('=')
header_info[key.strip()] = value.strip()
nbasis = int(header_info['NORB'])
nelec = int(header_info['NELEC'])
ms2 = int(header_info['MS2'])
if lf.default_nbasis is not None and lf.default_nbasis != nbasis:
raise TypeError('The value of lf.default_nbasis does not match NORB reported in the FCIDUMP file.')
lf.default_nbasis = nbasis
# skip rest of header
for line in f:
words = line.split()
if words[0] == "&END" or words[0] == "/END" or words[0]=="/":
break
# read the integrals
one_mo = lf.create_two_index()
two_mo = lf.create_four_index()
core_energy = 0.0
for line in f:
words = line.split()
if len(words) != 5:
raise IOError('Expecting 5 fields on each data line in FCIDUMP')
if words[3] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
ik = int(words[3])-1
il = int(words[4])-1
# Uncomment the following line if you want to assert that the
# FCIDUMP file does not contain duplicate 4-index entries.
#assert two_mo.get_element(ii,ik,ij,il) == 0.0
two_mo.set_element(ii,ik,ij,il,float(words[0]))
elif words[1] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
one_mo.set_element(ii,ij,float(words[0]))
else:
core_energy = float(words[0])
return {
'lf': lf,
'nelec': nelec,
'ms2': ms2,
'one_mo': one_mo,
'two_mo': two_mo,
'core_energy': core_energy,
}
def dump_fcidump(filename, data):
'''Write one- and two-electron integrals in the Molpro 2012 FCIDUMP format.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
written with this function cannot be used with older versions of Molpro
filename
The filename of the FCIDUMP file. This is usually "FCIDUMP".
data
An IOData instance. Must contain ``one_mo``, ``two_mo``.
May contain ``core_energy``, ``nelec`` and ``ms``
'''
with open(filename, 'w') as f:
one_mo = data.one_mo
two_mo = data.two_mo
nactive = one_mo.nbasis
core_energy = getattr(data, 'core_energy', 0.0)
nelec = getattr(data, 'nelec', 0)
ms2 = getattr(data, 'ms2', 0)
# Write header | # Write integrals and core energy
for i in xrange(nactive):
for j in xrange(i+1):
for k in xrange(nactive):
for l in xrange(k+1):
if (i*(i+1))/2+j >= (k*(k+1))/2+l:
value = two_mo.get_element(i,k,j,l)
if value != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, k+1, l+1)
for i in xrange(nactive):
for j in xrange(i+1):
value = one_mo.get_element(i,j)
if value != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, 0, 0)
if core_energy != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (core_energy, 0, 0, 0, 0) | print >> f, ' &FCI NORB=%i,NELEC=%i,MS2=%i,' % (nactive, nelec, ms2)
print >> f, ' ORBSYM= '+",".join(str(1) for v in xrange(nactive))+","
print >> f, ' ISYM=1'
print >> f, ' &END'
| random_line_split |
molpro.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# HORTON is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>
#
# --
'''Molpro 2012 FCIDUMP format.
.. note ::
One- and two-electron integrals are stored in chemists' notation in an
FCIDUMP file while HORTON internally uses Physicist's notation.
'''
__all__ = ['load_fcidump', 'dump_fcidump']
def load_fcidump(filename, lf):
'''Read one- and two-electron integrals from a Molpro 2012 FCIDUMP file.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
generated with older versions are not supported.
**Arguments:**
filename
The filename of the fcidump file.
lf
A LinalgFactory instance.
**Returns**: A dictionary with keys: ``lf``, ``nelec``, ``ms2``,
``one_mo``, ``two_mo``, ``core_energy``
'''
with open(filename) as f:
# check header
line = f.next()
if not line.startswith(' &FCI NORB='):
raise IOError('Error in FCIDUMP file header')
# read info from header
words = line[5:].split(',')
header_info = {}
for word in words:
if word.count('=') == 1:
key, value = word.split('=')
header_info[key.strip()] = value.strip()
nbasis = int(header_info['NORB'])
nelec = int(header_info['NELEC'])
ms2 = int(header_info['MS2'])
if lf.default_nbasis is not None and lf.default_nbasis != nbasis:
raise TypeError('The value of lf.default_nbasis does not match NORB reported in the FCIDUMP file.')
lf.default_nbasis = nbasis
# skip rest of header
for line in f:
words = line.split()
if words[0] == "&END" or words[0] == "/END" or words[0]=="/":
break
# read the integrals
one_mo = lf.create_two_index()
two_mo = lf.create_four_index()
core_energy = 0.0
for line in f:
words = line.split()
if len(words) != 5:
raise IOError('Expecting 5 fields on each data line in FCIDUMP')
if words[3] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
ik = int(words[3])-1
il = int(words[4])-1
# Uncomment the following line if you want to assert that the
# FCIDUMP file does not contain duplicate 4-index entries.
#assert two_mo.get_element(ii,ik,ij,il) == 0.0
two_mo.set_element(ii,ik,ij,il,float(words[0]))
elif words[1] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
one_mo.set_element(ii,ij,float(words[0]))
else:
core_energy = float(words[0])
return {
'lf': lf,
'nelec': nelec,
'ms2': ms2,
'one_mo': one_mo,
'two_mo': two_mo,
'core_energy': core_energy,
}
def dump_fcidump(filename, data):
| '''Write one- and two-electron integrals in the Molpro 2012 FCIDUMP format.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
written with this function cannot be used with older versions of Molpro
filename
The filename of the FCIDUMP file. This is usually "FCIDUMP".
data
An IOData instance. Must contain ``one_mo``, ``two_mo``.
May contain ``core_energy``, ``nelec`` and ``ms``
'''
with open(filename, 'w') as f:
one_mo = data.one_mo
two_mo = data.two_mo
nactive = one_mo.nbasis
core_energy = getattr(data, 'core_energy', 0.0)
nelec = getattr(data, 'nelec', 0)
ms2 = getattr(data, 'ms2', 0)
# Write header
print >> f, ' &FCI NORB=%i,NELEC=%i,MS2=%i,' % (nactive, nelec, ms2)
print >> f, ' ORBSYM= '+",".join(str(1) for v in xrange(nactive))+","
print >> f, ' ISYM=1'
print >> f, ' &END'
# Write integrals and core energy
for i in xrange(nactive):
for j in xrange(i+1):
for k in xrange(nactive):
for l in xrange(k+1):
if (i*(i+1))/2+j >= (k*(k+1))/2+l:
value = two_mo.get_element(i,k,j,l)
if value != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, k+1, l+1)
for i in xrange(nactive):
for j in xrange(i+1):
value = one_mo.get_element(i,j)
if value != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, 0, 0)
if core_energy != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (core_energy, 0, 0, 0, 0) | identifier_body | |
molpro.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# HORTON is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>
#
# --
'''Molpro 2012 FCIDUMP format.
.. note ::
One- and two-electron integrals are stored in chemists' notation in an
FCIDUMP file while HORTON internally uses Physicist's notation.
'''
__all__ = ['load_fcidump', 'dump_fcidump']
def load_fcidump(filename, lf):
'''Read one- and two-electron integrals from a Molpro 2012 FCIDUMP file.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
generated with older versions are not supported.
**Arguments:**
filename
The filename of the fcidump file.
lf
A LinalgFactory instance.
**Returns**: A dictionary with keys: ``lf``, ``nelec``, ``ms2``,
``one_mo``, ``two_mo``, ``core_energy``
'''
with open(filename) as f:
# check header
line = f.next()
if not line.startswith(' &FCI NORB='):
raise IOError('Error in FCIDUMP file header')
# read info from header
words = line[5:].split(',')
header_info = {}
for word in words:
if word.count('=') == 1:
key, value = word.split('=')
header_info[key.strip()] = value.strip()
nbasis = int(header_info['NORB'])
nelec = int(header_info['NELEC'])
ms2 = int(header_info['MS2'])
if lf.default_nbasis is not None and lf.default_nbasis != nbasis:
raise TypeError('The value of lf.default_nbasis does not match NORB reported in the FCIDUMP file.')
lf.default_nbasis = nbasis
# skip rest of header
for line in f:
words = line.split()
if words[0] == "&END" or words[0] == "/END" or words[0]=="/":
break
# read the integrals
one_mo = lf.create_two_index()
two_mo = lf.create_four_index()
core_energy = 0.0
for line in f:
words = line.split()
if len(words) != 5:
|
if words[3] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
ik = int(words[3])-1
il = int(words[4])-1
# Uncomment the following line if you want to assert that the
# FCIDUMP file does not contain duplicate 4-index entries.
#assert two_mo.get_element(ii,ik,ij,il) == 0.0
two_mo.set_element(ii,ik,ij,il,float(words[0]))
elif words[1] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
one_mo.set_element(ii,ij,float(words[0]))
else:
core_energy = float(words[0])
return {
'lf': lf,
'nelec': nelec,
'ms2': ms2,
'one_mo': one_mo,
'two_mo': two_mo,
'core_energy': core_energy,
}
def dump_fcidump(filename, data):
'''Write one- and two-electron integrals in the Molpro 2012 FCIDUMP format.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
written with this function cannot be used with older versions of Molpro
filename
The filename of the FCIDUMP file. This is usually "FCIDUMP".
data
An IOData instance. Must contain ``one_mo``, ``two_mo``.
May contain ``core_energy``, ``nelec`` and ``ms``
'''
with open(filename, 'w') as f:
one_mo = data.one_mo
two_mo = data.two_mo
nactive = one_mo.nbasis
core_energy = getattr(data, 'core_energy', 0.0)
nelec = getattr(data, 'nelec', 0)
ms2 = getattr(data, 'ms2', 0)
# Write header
print >> f, ' &FCI NORB=%i,NELEC=%i,MS2=%i,' % (nactive, nelec, ms2)
print >> f, ' ORBSYM= '+",".join(str(1) for v in xrange(nactive))+","
print >> f, ' ISYM=1'
print >> f, ' &END'
# Write integrals and core energy
for i in xrange(nactive):
for j in xrange(i+1):
for k in xrange(nactive):
for l in xrange(k+1):
if (i*(i+1))/2+j >= (k*(k+1))/2+l:
value = two_mo.get_element(i,k,j,l)
if value != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, k+1, l+1)
for i in xrange(nactive):
for j in xrange(i+1):
value = one_mo.get_element(i,j)
if value != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, 0, 0)
if core_energy != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (core_energy, 0, 0, 0, 0)
| raise IOError('Expecting 5 fields on each data line in FCIDUMP') | conditional_block |
molpro.py | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2016 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# HORTON is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>
#
# --
'''Molpro 2012 FCIDUMP format.
.. note ::
One- and two-electron integrals are stored in chemists' notation in an
FCIDUMP file while HORTON internally uses Physicist's notation.
'''
__all__ = ['load_fcidump', 'dump_fcidump']
def load_fcidump(filename, lf):
'''Read one- and two-electron integrals from a Molpro 2012 FCIDUMP file.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
generated with older versions are not supported.
**Arguments:**
filename
The filename of the fcidump file.
lf
A LinalgFactory instance.
**Returns**: A dictionary with keys: ``lf``, ``nelec``, ``ms2``,
``one_mo``, ``two_mo``, ``core_energy``
'''
with open(filename) as f:
# check header
line = f.next()
if not line.startswith(' &FCI NORB='):
raise IOError('Error in FCIDUMP file header')
# read info from header
words = line[5:].split(',')
header_info = {}
for word in words:
if word.count('=') == 1:
key, value = word.split('=')
header_info[key.strip()] = value.strip()
nbasis = int(header_info['NORB'])
nelec = int(header_info['NELEC'])
ms2 = int(header_info['MS2'])
if lf.default_nbasis is not None and lf.default_nbasis != nbasis:
raise TypeError('The value of lf.default_nbasis does not match NORB reported in the FCIDUMP file.')
lf.default_nbasis = nbasis
# skip rest of header
for line in f:
words = line.split()
if words[0] == "&END" or words[0] == "/END" or words[0]=="/":
break
# read the integrals
one_mo = lf.create_two_index()
two_mo = lf.create_four_index()
core_energy = 0.0
for line in f:
words = line.split()
if len(words) != 5:
raise IOError('Expecting 5 fields on each data line in FCIDUMP')
if words[3] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
ik = int(words[3])-1
il = int(words[4])-1
# Uncomment the following line if you want to assert that the
# FCIDUMP file does not contain duplicate 4-index entries.
#assert two_mo.get_element(ii,ik,ij,il) == 0.0
two_mo.set_element(ii,ik,ij,il,float(words[0]))
elif words[1] != '0':
ii = int(words[1])-1
ij = int(words[2])-1
one_mo.set_element(ii,ij,float(words[0]))
else:
core_energy = float(words[0])
return {
'lf': lf,
'nelec': nelec,
'ms2': ms2,
'one_mo': one_mo,
'two_mo': two_mo,
'core_energy': core_energy,
}
def | (filename, data):
'''Write one- and two-electron integrals in the Molpro 2012 FCIDUMP format.
Works only for restricted wavefunctions.
Keep in mind that the FCIDUMP format changed in Molpro 2012, so files
written with this function cannot be used with older versions of Molpro
filename
The filename of the FCIDUMP file. This is usually "FCIDUMP".
data
An IOData instance. Must contain ``one_mo``, ``two_mo``.
May contain ``core_energy``, ``nelec`` and ``ms``
'''
with open(filename, 'w') as f:
one_mo = data.one_mo
two_mo = data.two_mo
nactive = one_mo.nbasis
core_energy = getattr(data, 'core_energy', 0.0)
nelec = getattr(data, 'nelec', 0)
ms2 = getattr(data, 'ms2', 0)
# Write header
print >> f, ' &FCI NORB=%i,NELEC=%i,MS2=%i,' % (nactive, nelec, ms2)
print >> f, ' ORBSYM= '+",".join(str(1) for v in xrange(nactive))+","
print >> f, ' ISYM=1'
print >> f, ' &END'
# Write integrals and core energy
for i in xrange(nactive):
for j in xrange(i+1):
for k in xrange(nactive):
for l in xrange(k+1):
if (i*(i+1))/2+j >= (k*(k+1))/2+l:
value = two_mo.get_element(i,k,j,l)
if value != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, k+1, l+1)
for i in xrange(nactive):
for j in xrange(i+1):
value = one_mo.get_element(i,j)
if value != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (value, i+1, j+1, 0, 0)
if core_energy != 0.0:
print >> f, '%23.16e %4i %4i %4i %4i' % (core_energy, 0, 0, 0, 0)
| dump_fcidump | identifier_name |
getAnimatedPngDataIfExists.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const ACTL_CHUNK_BYTES = new TextEncoder().encode('acTL');
const IDAT_CHUNK_BYTES = new TextEncoder().encode('IDAT');
const MAX_BYTES_TO_READ = 1024 * 1024;
type AnimatedPngData = {
numPlays: number;
};
/**
* This is a naïve implementation. It only performs two checks:
*
* 1. Do the bytes start with the [PNG signature][0]?
* 2. If so, does it contain the [`acTL` chunk][1] before the [`IDAT` chunk][2], in the
* first megabyte?
*
* Though we _could_ only check for the presence of the `acTL` chunk anywhere, we make
* sure it's before the `IDAT` chunk and within the first megabyte. This adds a small
* amount of validity checking and helps us avoid problems with large PNGs.
*
* It doesn't make sure the PNG is valid. It doesn't verify [the CRC code][3] of each PNG
* chunk; it doesn't verify any of the chunk's data; it doesn't verify that the chunks are
* in the right order; etc.
*
* [0]: https://www.w3.org/TR/PNG/#5PNG-file-signature
* [1]: https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk
* [2]: https://www.w3.org/TR/PNG/#11IDAT
* [3]: https://www.w3.org/TR/PNG/#5Chunk-layout
*/
export function g |
bytes: Uint8Array
): null | AnimatedPngData {
if (!hasPngSignature(bytes)) {
return null;
}
let numPlays: void | number;
const dataView = new DataView(bytes.buffer);
let i = PNG_SIGNATURE.length;
while (i < bytes.byteLength && i <= MAX_BYTES_TO_READ) {
const chunkTypeBytes = bytes.slice(i + 4, i + 8);
if (areBytesEqual(chunkTypeBytes, ACTL_CHUNK_BYTES)) {
// 4 bytes for the length; 4 bytes for the type; 4 bytes for the number of frames.
numPlays = dataView.getUint32(i + 12);
if (numPlays === 0) {
numPlays = Infinity;
}
return { numPlays };
}
if (areBytesEqual(chunkTypeBytes, IDAT_CHUNK_BYTES)) {
return null;
}
// Jump over the length (4 bytes), the type (4 bytes), the data, and the CRC checksum
// (4 bytes).
i += 12 + dataView.getUint32(i);
}
return null;
}
function hasPngSignature(bytes: Uint8Array): boolean {
return areBytesEqual(bytes.slice(0, 8), PNG_SIGNATURE);
}
function areBytesEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
| etAnimatedPngDataIfExists( | identifier_name |
getAnimatedPngDataIfExists.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const ACTL_CHUNK_BYTES = new TextEncoder().encode('acTL');
const IDAT_CHUNK_BYTES = new TextEncoder().encode('IDAT');
const MAX_BYTES_TO_READ = 1024 * 1024;
type AnimatedPngData = {
numPlays: number;
};
/**
* This is a naïve implementation. It only performs two checks:
*
* 1. Do the bytes start with the [PNG signature][0]?
* 2. If so, does it contain the [`acTL` chunk][1] before the [`IDAT` chunk][2], in the
* first megabyte?
*
* Though we _could_ only check for the presence of the `acTL` chunk anywhere, we make
* sure it's before the `IDAT` chunk and within the first megabyte. This adds a small
* amount of validity checking and helps us avoid problems with large PNGs.
*
* It doesn't make sure the PNG is valid. It doesn't verify [the CRC code][3] of each PNG
* chunk; it doesn't verify any of the chunk's data; it doesn't verify that the chunks are
* in the right order; etc.
*
* [0]: https://www.w3.org/TR/PNG/#5PNG-file-signature
* [1]: https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk
* [2]: https://www.w3.org/TR/PNG/#11IDAT
* [3]: https://www.w3.org/TR/PNG/#5Chunk-layout
*/
export function getAnimatedPngDataIfExists(
bytes: Uint8Array
): null | AnimatedPngData {
if (!hasPngSignature(bytes)) {
return null;
}
let numPlays: void | number;
const dataView = new DataView(bytes.buffer);
let i = PNG_SIGNATURE.length;
while (i < bytes.byteLength && i <= MAX_BYTES_TO_READ) {
const chunkTypeBytes = bytes.slice(i + 4, i + 8);
if (areBytesEqual(chunkTypeBytes, ACTL_CHUNK_BYTES)) {
// 4 bytes for the length; 4 bytes for the type; 4 bytes for the number of frames.
numPlays = dataView.getUint32(i + 12);
if (numPlays === 0) {
numPlays = Infinity;
}
return { numPlays };
}
if (areBytesEqual(chunkTypeBytes, IDAT_CHUNK_BYTES)) {
return null;
}
// Jump over the length (4 bytes), the type (4 bytes), the data, and the CRC checksum
// (4 bytes).
i += 12 + dataView.getUint32(i);
}
return null;
}
function hasPngSignature(bytes: Uint8Array): boolean {
return areBytesEqual(bytes.slice(0, 8), PNG_SIGNATURE);
}
function areBytesEqual(a: Uint8Array, b: Uint8Array): boolean { |
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
| identifier_body | |
getAnimatedPngDataIfExists.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const ACTL_CHUNK_BYTES = new TextEncoder().encode('acTL');
const IDAT_CHUNK_BYTES = new TextEncoder().encode('IDAT');
const MAX_BYTES_TO_READ = 1024 * 1024;
type AnimatedPngData = {
numPlays: number;
};
/**
* This is a naïve implementation. It only performs two checks:
*
* 1. Do the bytes start with the [PNG signature][0]?
* 2. If so, does it contain the [`acTL` chunk][1] before the [`IDAT` chunk][2], in the
* first megabyte?
*
* Though we _could_ only check for the presence of the `acTL` chunk anywhere, we make
* sure it's before the `IDAT` chunk and within the first megabyte. This adds a small
* amount of validity checking and helps us avoid problems with large PNGs.
*
* It doesn't make sure the PNG is valid. It doesn't verify [the CRC code][3] of each PNG
* chunk; it doesn't verify any of the chunk's data; it doesn't verify that the chunks are
* in the right order; etc.
*
* [0]: https://www.w3.org/TR/PNG/#5PNG-file-signature
* [1]: https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk
* [2]: https://www.w3.org/TR/PNG/#11IDAT
* [3]: https://www.w3.org/TR/PNG/#5Chunk-layout
*/
export function getAnimatedPngDataIfExists(
bytes: Uint8Array
): null | AnimatedPngData {
if (!hasPngSignature(bytes)) {
return null;
}
let numPlays: void | number;
const dataView = new DataView(bytes.buffer);
let i = PNG_SIGNATURE.length;
while (i < bytes.byteLength && i <= MAX_BYTES_TO_READ) {
const chunkTypeBytes = bytes.slice(i + 4, i + 8);
if (areBytesEqual(chunkTypeBytes, ACTL_CHUNK_BYTES)) {
// 4 bytes for the length; 4 bytes for the type; 4 bytes for the number of frames.
numPlays = dataView.getUint32(i + 12);
if (numPlays === 0) {
numPlays = Infinity;
}
return { numPlays };
}
if (areBytesEqual(chunkTypeBytes, IDAT_CHUNK_BYTES)) {
return null;
}
// Jump over the length (4 bytes), the type (4 bytes), the data, and the CRC checksum
// (4 bytes).
i += 12 + dataView.getUint32(i);
}
return null; | function hasPngSignature(bytes: Uint8Array): boolean {
return areBytesEqual(bytes.slice(0, 8), PNG_SIGNATURE);
}
function areBytesEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
} | }
| random_line_split |
getAnimatedPngDataIfExists.ts | // Copyright 2020-2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const ACTL_CHUNK_BYTES = new TextEncoder().encode('acTL');
const IDAT_CHUNK_BYTES = new TextEncoder().encode('IDAT');
const MAX_BYTES_TO_READ = 1024 * 1024;
type AnimatedPngData = {
numPlays: number;
};
/**
* This is a naïve implementation. It only performs two checks:
*
* 1. Do the bytes start with the [PNG signature][0]?
* 2. If so, does it contain the [`acTL` chunk][1] before the [`IDAT` chunk][2], in the
* first megabyte?
*
* Though we _could_ only check for the presence of the `acTL` chunk anywhere, we make
* sure it's before the `IDAT` chunk and within the first megabyte. This adds a small
* amount of validity checking and helps us avoid problems with large PNGs.
*
* It doesn't make sure the PNG is valid. It doesn't verify [the CRC code][3] of each PNG
* chunk; it doesn't verify any of the chunk's data; it doesn't verify that the chunks are
* in the right order; etc.
*
* [0]: https://www.w3.org/TR/PNG/#5PNG-file-signature
* [1]: https://wiki.mozilla.org/APNG_Specification#.60acTL.60:_The_Animation_Control_Chunk
* [2]: https://www.w3.org/TR/PNG/#11IDAT
* [3]: https://www.w3.org/TR/PNG/#5Chunk-layout
*/
export function getAnimatedPngDataIfExists(
bytes: Uint8Array
): null | AnimatedPngData {
if (!hasPngSignature(bytes)) {
return null;
}
let numPlays: void | number;
const dataView = new DataView(bytes.buffer);
let i = PNG_SIGNATURE.length;
while (i < bytes.byteLength && i <= MAX_BYTES_TO_READ) {
const chunkTypeBytes = bytes.slice(i + 4, i + 8);
if (areBytesEqual(chunkTypeBytes, ACTL_CHUNK_BYTES)) {
// 4 bytes for the length; 4 bytes for the type; 4 bytes for the number of frames.
numPlays = dataView.getUint32(i + 12);
if (numPlays === 0) {
numPlays = Infinity;
}
return { numPlays };
}
if (areBytesEqual(chunkTypeBytes, IDAT_CHUNK_BYTES)) { |
// Jump over the length (4 bytes), the type (4 bytes), the data, and the CRC checksum
// (4 bytes).
i += 12 + dataView.getUint32(i);
}
return null;
}
function hasPngSignature(bytes: Uint8Array): boolean {
return areBytesEqual(bytes.slice(0, 8), PNG_SIGNATURE);
}
function areBytesEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.byteLength !== b.byteLength) {
return false;
}
for (let i = 0; i < a.byteLength; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
|
return null;
}
| conditional_block |
type_resolver.rs | use std::iter;
use crate::model;
use crate::model::WithLoc;
use crate::protobuf_path::ProtobufPath;
use crate::pure::convert::WithFullName;
use crate::FileDescriptorPair;
use crate::ProtobufAbsPath;
use crate::ProtobufAbsPathRef;
use crate::ProtobufIdent;
use crate::ProtobufIdentRef;
use crate::ProtobufRelPath;
use crate::ProtobufRelPathRef;
#[derive(thiserror::Error, Debug)]
enum TypeResolverError {
#[error("object is not found by path: {0}")]
NotFoundByAbsPath(ProtobufAbsPath),
#[error("object is not found by path `{0}` in scope `{1}`")]
NotFoundByRelPath(ProtobufRelPath, ProtobufAbsPath),
}
pub(crate) enum MessageOrEnum<'a> {
Message(&'a model::Message),
Enum(&'a model::Enumeration),
}
impl MessageOrEnum<'_> {
fn _descriptor_type(&self) -> protobuf::descriptor::field_descriptor_proto::Type {
match *self {
MessageOrEnum::Message(..) => {
protobuf::descriptor::field_descriptor_proto::Type::TYPE_MESSAGE
}
MessageOrEnum::Enum(..) => {
protobuf::descriptor::field_descriptor_proto::Type::TYPE_ENUM
}
}
}
}
#[derive(Clone)]
enum LookupScope<'a> {
File(&'a model::FileDescriptor),
Message(&'a model::Message, ProtobufAbsPath),
}
impl<'a> LookupScope<'a> {
fn current_path(&self) -> ProtobufAbsPath {
match self {
LookupScope::File(f) => f.package.clone(),
LookupScope::Message(_, p) => p.clone(),
}
}
fn | (&self) -> &'a [model::WithLoc<model::Message>] {
match self {
&LookupScope::File(file) => &file.messages,
&LookupScope::Message(messasge, _) => &messasge.messages,
}
}
fn find_message(&self, simple_name: &ProtobufIdentRef) -> Option<&'a model::Message> {
self.messages()
.into_iter()
.find(|m| m.t.name == simple_name.as_str())
.map(|m| &m.t)
}
fn enums(&self) -> &'a [WithLoc<model::Enumeration>] {
match self {
&LookupScope::File(file) => &file.enums,
&LookupScope::Message(messasge, _) => &messasge.enums,
}
}
fn members(&self) -> Vec<(ProtobufIdent, MessageOrEnum<'a>)> {
let mut r = Vec::new();
r.extend(
self.enums()
.into_iter()
.map(|e| (ProtobufIdent::from(&e.name[..]), MessageOrEnum::Enum(e))),
);
r.extend(self.messages().into_iter().map(|m| {
(
ProtobufIdent::from(&m.t.name[..]),
MessageOrEnum::Message(&m.t),
)
}));
r
}
fn find_member(&self, simple_name: &ProtobufIdentRef) -> Option<MessageOrEnum<'a>> {
self.members()
.into_iter()
.filter_map(|(member_name, message_or_enum)| {
if member_name.as_ref() == simple_name {
Some(message_or_enum)
} else {
None
}
})
.next()
}
pub(crate) fn find_message_or_enum(
&self,
path: &ProtobufRelPathRef,
) -> Option<WithFullName<MessageOrEnum<'a>>> {
let current_path = self.current_path();
let (first, rem) = match path.split_first_rem() {
Some(x) => x,
None => return None,
};
if rem.is_empty() {
match self.find_member(first) {
Some(message_or_enum) => {
let mut result_path = current_path.clone();
result_path.push_simple(first);
Some(WithFullName {
full_name: result_path,
t: message_or_enum,
})
}
None => None,
}
} else {
match self.find_message(first) {
Some(message) => {
let mut message_path = current_path.clone();
message_path.push_simple(ProtobufIdentRef::new(&message.name));
let message_scope = LookupScope::Message(message, message_path);
message_scope.find_message_or_enum(rem)
}
None => None,
}
}
}
}
pub(crate) struct TypeResolver<'a> {
pub(crate) current_file: &'a model::FileDescriptor,
pub(crate) deps: &'a [FileDescriptorPair],
}
impl<'a> TypeResolver<'a> {
pub(crate) fn all_files(&self) -> Vec<&'a model::FileDescriptor> {
iter::once(self.current_file)
.chain(self.deps.iter().map(|p| &p.parsed))
.collect()
}
pub(crate) fn find_message_or_enum_by_abs_name(
&self,
absolute_path: &ProtobufAbsPath,
) -> anyhow::Result<WithFullName<MessageOrEnum<'a>>> {
for file in self.all_files() {
if let Some(relative) = absolute_path.remove_prefix(&file.package) {
if let Some(w) = LookupScope::File(file).find_message_or_enum(&relative) {
return Ok(w);
}
}
}
return Err(TypeResolverError::NotFoundByAbsPath(absolute_path.clone()).into());
}
pub(crate) fn resolve_message_or_enum(
&self,
scope: &ProtobufAbsPathRef,
name: &ProtobufPath,
) -> anyhow::Result<WithFullName<MessageOrEnum>> {
match name {
ProtobufPath::Abs(name) => Ok(self.find_message_or_enum_by_abs_name(&name)?),
ProtobufPath::Rel(name) => {
// find message or enum in current package
for p in scope.self_and_parents() {
let mut fq = p.to_owned();
fq.push_relative(&name);
if let Ok(me) = self.find_message_or_enum_by_abs_name(&fq) {
return Ok(me);
}
}
Err(TypeResolverError::NotFoundByRelPath(name.clone(), scope.to_owned()).into())
}
}
}
}
| messages | identifier_name |
type_resolver.rs | use std::iter;
use crate::model;
use crate::model::WithLoc;
use crate::protobuf_path::ProtobufPath;
use crate::pure::convert::WithFullName;
use crate::FileDescriptorPair;
use crate::ProtobufAbsPath;
use crate::ProtobufAbsPathRef;
use crate::ProtobufIdent;
use crate::ProtobufIdentRef;
use crate::ProtobufRelPath;
use crate::ProtobufRelPathRef;
#[derive(thiserror::Error, Debug)]
enum TypeResolverError {
#[error("object is not found by path: {0}")]
NotFoundByAbsPath(ProtobufAbsPath),
#[error("object is not found by path `{0}` in scope `{1}`")]
NotFoundByRelPath(ProtobufRelPath, ProtobufAbsPath),
}
pub(crate) enum MessageOrEnum<'a> {
Message(&'a model::Message),
Enum(&'a model::Enumeration),
}
impl MessageOrEnum<'_> {
fn _descriptor_type(&self) -> protobuf::descriptor::field_descriptor_proto::Type {
match *self {
MessageOrEnum::Message(..) => {
protobuf::descriptor::field_descriptor_proto::Type::TYPE_MESSAGE
}
MessageOrEnum::Enum(..) => {
protobuf::descriptor::field_descriptor_proto::Type::TYPE_ENUM
}
}
}
}
#[derive(Clone)]
enum LookupScope<'a> {
File(&'a model::FileDescriptor),
Message(&'a model::Message, ProtobufAbsPath),
}
impl<'a> LookupScope<'a> {
fn current_path(&self) -> ProtobufAbsPath {
match self {
LookupScope::File(f) => f.package.clone(),
LookupScope::Message(_, p) => p.clone(),
}
}
fn messages(&self) -> &'a [model::WithLoc<model::Message>] {
match self {
&LookupScope::File(file) => &file.messages,
&LookupScope::Message(messasge, _) => &messasge.messages,
}
}
fn find_message(&self, simple_name: &ProtobufIdentRef) -> Option<&'a model::Message> {
self.messages()
.into_iter()
.find(|m| m.t.name == simple_name.as_str())
.map(|m| &m.t)
}
fn enums(&self) -> &'a [WithLoc<model::Enumeration>] {
match self {
&LookupScope::File(file) => &file.enums,
&LookupScope::Message(messasge, _) => &messasge.enums,
}
}
fn members(&self) -> Vec<(ProtobufIdent, MessageOrEnum<'a>)> {
let mut r = Vec::new();
r.extend(
self.enums()
.into_iter()
.map(|e| (ProtobufIdent::from(&e.name[..]), MessageOrEnum::Enum(e))),
);
r.extend(self.messages().into_iter().map(|m| {
(
ProtobufIdent::from(&m.t.name[..]),
MessageOrEnum::Message(&m.t),
)
}));
r
}
fn find_member(&self, simple_name: &ProtobufIdentRef) -> Option<MessageOrEnum<'a>> {
self.members()
.into_iter()
.filter_map(|(member_name, message_or_enum)| {
if member_name.as_ref() == simple_name {
Some(message_or_enum)
} else {
None
}
})
.next()
}
pub(crate) fn find_message_or_enum(
&self,
path: &ProtobufRelPathRef,
) -> Option<WithFullName<MessageOrEnum<'a>>> {
let current_path = self.current_path();
let (first, rem) = match path.split_first_rem() {
Some(x) => x,
None => return None,
};
if rem.is_empty() {
match self.find_member(first) {
Some(message_or_enum) => {
let mut result_path = current_path.clone();
result_path.push_simple(first);
Some(WithFullName {
full_name: result_path,
t: message_or_enum,
})
}
None => None,
}
} else {
match self.find_message(first) {
Some(message) => {
let mut message_path = current_path.clone();
message_path.push_simple(ProtobufIdentRef::new(&message.name));
let message_scope = LookupScope::Message(message, message_path);
message_scope.find_message_or_enum(rem)
}
None => None,
}
}
}
}
pub(crate) struct TypeResolver<'a> {
pub(crate) current_file: &'a model::FileDescriptor,
pub(crate) deps: &'a [FileDescriptorPair],
}
impl<'a> TypeResolver<'a> {
pub(crate) fn all_files(&self) -> Vec<&'a model::FileDescriptor> {
iter::once(self.current_file)
.chain(self.deps.iter().map(|p| &p.parsed))
.collect()
}
pub(crate) fn find_message_or_enum_by_abs_name(
&self,
absolute_path: &ProtobufAbsPath,
) -> anyhow::Result<WithFullName<MessageOrEnum<'a>>> {
for file in self.all_files() {
if let Some(relative) = absolute_path.remove_prefix(&file.package) {
if let Some(w) = LookupScope::File(file).find_message_or_enum(&relative) {
return Ok(w);
}
}
}
return Err(TypeResolverError::NotFoundByAbsPath(absolute_path.clone()).into());
}
pub(crate) fn resolve_message_or_enum(
&self,
scope: &ProtobufAbsPathRef,
name: &ProtobufPath,
) -> anyhow::Result<WithFullName<MessageOrEnum>> |
}
| {
match name {
ProtobufPath::Abs(name) => Ok(self.find_message_or_enum_by_abs_name(&name)?),
ProtobufPath::Rel(name) => {
// find message or enum in current package
for p in scope.self_and_parents() {
let mut fq = p.to_owned();
fq.push_relative(&name);
if let Ok(me) = self.find_message_or_enum_by_abs_name(&fq) {
return Ok(me);
}
}
Err(TypeResolverError::NotFoundByRelPath(name.clone(), scope.to_owned()).into())
}
}
} | identifier_body |
type_resolver.rs | use std::iter;
use crate::model;
use crate::model::WithLoc;
use crate::protobuf_path::ProtobufPath;
use crate::pure::convert::WithFullName;
use crate::FileDescriptorPair;
use crate::ProtobufAbsPath;
use crate::ProtobufAbsPathRef;
use crate::ProtobufIdent;
use crate::ProtobufIdentRef;
use crate::ProtobufRelPath;
use crate::ProtobufRelPathRef;
#[derive(thiserror::Error, Debug)]
enum TypeResolverError {
#[error("object is not found by path: {0}")]
NotFoundByAbsPath(ProtobufAbsPath),
#[error("object is not found by path `{0}` in scope `{1}`")]
NotFoundByRelPath(ProtobufRelPath, ProtobufAbsPath),
}
pub(crate) enum MessageOrEnum<'a> {
Message(&'a model::Message),
Enum(&'a model::Enumeration),
}
impl MessageOrEnum<'_> {
fn _descriptor_type(&self) -> protobuf::descriptor::field_descriptor_proto::Type {
match *self {
MessageOrEnum::Message(..) => {
protobuf::descriptor::field_descriptor_proto::Type::TYPE_MESSAGE
}
MessageOrEnum::Enum(..) => {
protobuf::descriptor::field_descriptor_proto::Type::TYPE_ENUM
}
}
}
}
#[derive(Clone)]
enum LookupScope<'a> {
File(&'a model::FileDescriptor),
Message(&'a model::Message, ProtobufAbsPath),
}
impl<'a> LookupScope<'a> {
fn current_path(&self) -> ProtobufAbsPath {
match self {
LookupScope::File(f) => f.package.clone(),
LookupScope::Message(_, p) => p.clone(),
}
}
fn messages(&self) -> &'a [model::WithLoc<model::Message>] {
match self {
&LookupScope::File(file) => &file.messages,
&LookupScope::Message(messasge, _) => &messasge.messages,
}
}
fn find_message(&self, simple_name: &ProtobufIdentRef) -> Option<&'a model::Message> {
self.messages()
.into_iter()
.find(|m| m.t.name == simple_name.as_str())
.map(|m| &m.t)
}
fn enums(&self) -> &'a [WithLoc<model::Enumeration>] {
match self {
&LookupScope::File(file) => &file.enums,
&LookupScope::Message(messasge, _) => &messasge.enums,
}
}
fn members(&self) -> Vec<(ProtobufIdent, MessageOrEnum<'a>)> {
let mut r = Vec::new();
r.extend(
self.enums()
.into_iter()
.map(|e| (ProtobufIdent::from(&e.name[..]), MessageOrEnum::Enum(e))),
);
r.extend(self.messages().into_iter().map(|m| {
(
ProtobufIdent::from(&m.t.name[..]),
MessageOrEnum::Message(&m.t),
)
}));
r
}
fn find_member(&self, simple_name: &ProtobufIdentRef) -> Option<MessageOrEnum<'a>> {
self.members()
.into_iter()
.filter_map(|(member_name, message_or_enum)| {
if member_name.as_ref() == simple_name {
Some(message_or_enum)
} else {
None
}
})
.next()
}
pub(crate) fn find_message_or_enum(
&self,
path: &ProtobufRelPathRef,
) -> Option<WithFullName<MessageOrEnum<'a>>> {
let current_path = self.current_path();
let (first, rem) = match path.split_first_rem() {
Some(x) => x,
None => return None,
};
if rem.is_empty() {
match self.find_member(first) {
Some(message_or_enum) => {
let mut result_path = current_path.clone();
result_path.push_simple(first);
Some(WithFullName {
full_name: result_path,
t: message_or_enum,
})
}
None => None,
}
} else {
match self.find_message(first) {
Some(message) => {
let mut message_path = current_path.clone();
message_path.push_simple(ProtobufIdentRef::new(&message.name));
let message_scope = LookupScope::Message(message, message_path);
message_scope.find_message_or_enum(rem)
}
None => None,
}
}
}
}
pub(crate) struct TypeResolver<'a> {
pub(crate) current_file: &'a model::FileDescriptor,
pub(crate) deps: &'a [FileDescriptorPair],
}
impl<'a> TypeResolver<'a> {
pub(crate) fn all_files(&self) -> Vec<&'a model::FileDescriptor> {
iter::once(self.current_file)
.chain(self.deps.iter().map(|p| &p.parsed))
.collect()
}
pub(crate) fn find_message_or_enum_by_abs_name(
&self,
absolute_path: &ProtobufAbsPath,
) -> anyhow::Result<WithFullName<MessageOrEnum<'a>>> {
for file in self.all_files() {
if let Some(relative) = absolute_path.remove_prefix(&file.package) {
if let Some(w) = LookupScope::File(file).find_message_or_enum(&relative) {
return Ok(w);
}
}
}
return Err(TypeResolverError::NotFoundByAbsPath(absolute_path.clone()).into());
}
| name: &ProtobufPath,
) -> anyhow::Result<WithFullName<MessageOrEnum>> {
match name {
ProtobufPath::Abs(name) => Ok(self.find_message_or_enum_by_abs_name(&name)?),
ProtobufPath::Rel(name) => {
// find message or enum in current package
for p in scope.self_and_parents() {
let mut fq = p.to_owned();
fq.push_relative(&name);
if let Ok(me) = self.find_message_or_enum_by_abs_name(&fq) {
return Ok(me);
}
}
Err(TypeResolverError::NotFoundByRelPath(name.clone(), scope.to_owned()).into())
}
}
}
} | pub(crate) fn resolve_message_or_enum(
&self,
scope: &ProtobufAbsPathRef, | random_line_split |
channels-widget.tsx | import * as React from 'react'
import * as Kb from '../../common-adapters'
import * as Styles from '../../styles'
import * as Types from '../../constants/types/teams'
import ChannelPopup from '../team/settings-tab/channel-popup'
import useAutocompleter from './use-autocompleter'
import {useAllChannelMetas} from './channel-hooks'
type Props = {
channels: Array<Types.ChannelNameID>
disableGeneral?: boolean
disabledChannels?: Array<Types.ChannelNameID>
onAddChannel: (toAdd: Array<Types.ChannelNameID>) => void
onRemoveChannel: (toRemove: Types.ChannelNameID) => void
teamID: Types.TeamID
}
// always shows #general
const ChannelsWidget = (props: Props) => (
<Kb.Box2 direction="vertical" gap="tiny" style={styles.container} fullWidth={true}>
<ChannelInput
onAdd={props.onAddChannel}
teamID={props.teamID}
selected={props.channels}
disableGeneral={props.disableGeneral}
disabledChannels={props.disabledChannels}
/>
{!!props.channels.length && ( | <ChannelPill
key={channel.channelname}
channelname={channel.channelname}
onRemove={channel.channelname === 'general' ? undefined : () => props.onRemoveChannel(channel)}
/>
))}
</Kb.Box2>
)}
</Kb.Box2>
)
type ChannelInputProps = {
disableGeneral?: boolean
disabledChannels?: Array<Types.ChannelNameID>
onAdd: (toAdd: Array<Types.ChannelNameID>) => void
selected: Array<Types.ChannelNameID>
teamID: Types.TeamID
}
const ChannelInputDesktop = (props: ChannelInputProps) => {
const {disableGeneral, disabledChannels, onAdd, selected, teamID} = props
const [filter, setFilter] = React.useState('')
const {channelMetas} = useAllChannelMetas(teamID)
const channelItems = [...channelMetas.values()]
.filter(
c =>
!selected.find(channel => channel.conversationIDKey === c.conversationIDKey) &&
(!disableGeneral || c.channelname !== 'general') &&
(!disabledChannels || !disabledChannels.some(dc => dc.conversationIDKey === c.conversationIDKey))
)
.map(c => ({
label: `#${c.channelname}`,
value: {channelname: c.channelname, conversationIDKey: c.conversationIDKey},
}))
const onSelect = (value: Unpacked<typeof channelItems>['value']) => {
onAdd([value])
setFilter('')
}
const {popup, popupAnchor, onKeyDown, setShowingPopup} = useAutocompleter(channelItems, onSelect, filter)
return (
<>
<Kb.SearchFilter
// @ts-ignore complaining that popupAnchor is missing properties that SearchFilter has
ref={popupAnchor}
onFocus={() => setShowingPopup(true)}
onBlur={() => setShowingPopup(false)}
placeholderText="Add channels"
icon="iconfont-search"
onChange={setFilter}
size={Styles.isMobile ? 'full-width' : 'small'}
onKeyDown={onKeyDown}
value={filter}
valueControlled={true}
/>
{popup}
</>
)
}
const ChannelInputMobile = (props: ChannelInputProps) => {
const {disableGeneral, disabledChannels, onAdd, selected, teamID} = props
const [showingPopup, setShowingPopup] = React.useState(false)
const onComplete = (channels: Array<Types.ChannelNameID>) => {
setShowingPopup(false)
onAdd(channels)
}
return (
<Kb.ClickableBox onClick={() => setShowingPopup(true)}>
<Kb.Box2
direction="horizontal"
gap="tiny"
alignSelf="stretch"
centerChildren={true}
style={styles.channelDummyInput}
>
<Kb.Icon type="iconfont-search" color={Styles.globalColors.black_50} sizeType="Small" />
<Kb.Text type="BodySemibold" style={styles.channelDummyInputText}>
Add channels
</Kb.Text>
</Kb.Box2>
{showingPopup && (
<ChannelPopup
teamID={teamID}
onCancel={() => setShowingPopup(false)}
onComplete={onComplete}
disabledChannels={[...selected, ...(disabledChannels || [])]}
hideGeneral={disableGeneral}
/>
)}
</Kb.ClickableBox>
)
}
const ChannelInput = Styles.isMobile ? ChannelInputMobile : ChannelInputDesktop
const ChannelPill = ({channelname, onRemove}: {channelname: string; onRemove?: () => void}) => (
<Kb.Box2 direction="horizontal" gap="tiny" alignItems="center" style={styles.pill}>
<Kb.Text type={Styles.isMobile ? 'Body' : 'BodySemibold'}>#{channelname}</Kb.Text>
{onRemove && <Kb.Icon type="iconfont-remove" onClick={onRemove} color={Styles.globalColors.black_20} />}
</Kb.Box2>
)
const styles = Styles.styleSheetCreate(() => ({
channelDummyInput: {
backgroundColor: Styles.globalColors.black_10,
borderRadius: Styles.borderRadius,
paddingBottom: Styles.globalMargins.xtiny,
paddingTop: Styles.globalMargins.xtiny,
},
channelDummyInputText: {color: Styles.globalColors.black_50},
container: {
...Styles.padding(Styles.globalMargins.tiny),
backgroundColor: Styles.globalColors.blueGrey,
borderRadius: Styles.borderRadius,
},
pill: Styles.platformStyles({
common: {
...Styles.padding(Styles.globalMargins.xtiny, Styles.globalMargins.tiny),
backgroundColor: Styles.globalColors.white,
borderRadius: Styles.borderRadius,
marginBottom: Styles.globalMargins.xtiny,
},
isMobile: {
borderColor: Styles.globalColors.black_20,
borderStyle: 'solid',
borderWidth: 1,
},
}),
pillContainer: {
flexWrap: 'wrap',
},
}))
export default ChannelsWidget | <Kb.Box2 direction="horizontal" gap="xtiny" fullWidth={true} style={styles.pillContainer}>
{props.channels.map(channel => ( | random_line_split |
query.component.ts | import { Component, Input, OnDestroy } from '@angular/core';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { APIManagerService } from '../core/api-manager/api-manager.service';
import { QueryDataschemaGeneratorService } from '../core/schemas/query-dataschema-generator.service';
import { QueryUischemaGeneratorService } from '../core/schemas/query-uischema-generator.service.ts';
import { DataGeneratorService } from '../core/schemas/data-generator.service';
import { OperationPerformerService } from '../core/operation-performer/operation-performer.service';
import { AuthService } from "../auth/auth.service";
import { Action } from '../core/model/action';
import { Operation } from '../core/model/operation';
import { JsonFormsAdapter } from '../../../adapters/jsonforms.adapter';
@Component({
selector: 'query-section',
template: require('./query.html'),
styles: [require('../center-content.css')],
providers: [
QueryDataschemaGeneratorService,
QueryUischemaGeneratorService,
DataGeneratorService
],
directives: [JsonFormsAdapter]
})
export class QueryComponent implements OnDestroy {
@Input() devMode: boolean;
activeAction: Action;
activeActionSubscription: Subscription;
activeOperation: Operation;
activeOperationSubscription: Subscription;
dataschema: {};
uischema: {};
data: {};
constructor(private dataschemaGeneratorService: QueryDataschemaGeneratorService,
private uischemaGeneratorService: QueryUischemaGeneratorService,
private dataGeneratorService: DataGeneratorService,
private apiManagerService: APIManagerService,
private operationPerformerService: OperationPerformerService,
private authService: AuthService) {
this. activeActionSubscription = apiManagerService.activeAction.subscribe((activeAction: Action) => this.activeAction = activeAction);
this.activeOperationSubscription = apiManagerService.activeOperation.subscribe((activeOperation: Operation) => {
this.activeOperation = activeOperation;
if (this.activeOperation) {
this.dataschema = this.dataschemaGeneratorService.generateDataschema(this.activeOperation.getParameters());
this.uischema = this.uischemaGeneratorService.generateUischema(this.dataschema);
this.data = this.dataGeneratorService.generateData(this.activeOperation.getParameters(), this.apiManagerService.getInitialData());
}
});
}
getOperationsList() {
return (this.activeAction && this.activeAction.operations) || [this.activeOperation];
}
| (operation: Operation) {
this.apiManagerService.setActiveOperation(operation, {});
}
removeOperation(operation: Operation) {
if (this.activeAction.removeOperation(operation)) {
if (this.activeOperation == operation) {
let newActiveOperation: Operation = null;
if (this.activeAction.operations.length > 0) {
newActiveOperation = this.activeAction.operations[0];
}
this.apiManagerService.setActiveOperation(newActiveOperation, {});
}
}
}
performOperation() {
this.operationPerformerService.performOperation(this.activeOperation, this.data);
}
ngOnDestroy() {
this.activeActionSubscription.unsubscribe();
this.activeOperationSubscription.unsubscribe();
}
}
| selectOperation | identifier_name |
query.component.ts | import { Component, Input, OnDestroy } from '@angular/core';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { APIManagerService } from '../core/api-manager/api-manager.service';
import { QueryDataschemaGeneratorService } from '../core/schemas/query-dataschema-generator.service';
import { QueryUischemaGeneratorService } from '../core/schemas/query-uischema-generator.service.ts';
import { DataGeneratorService } from '../core/schemas/data-generator.service';
import { OperationPerformerService } from '../core/operation-performer/operation-performer.service';
import { AuthService } from "../auth/auth.service";
import { Action } from '../core/model/action';
import { Operation } from '../core/model/operation';
import { JsonFormsAdapter } from '../../../adapters/jsonforms.adapter';
@Component({
selector: 'query-section',
template: require('./query.html'),
styles: [require('../center-content.css')],
providers: [
QueryDataschemaGeneratorService,
QueryUischemaGeneratorService,
DataGeneratorService
],
directives: [JsonFormsAdapter]
})
export class QueryComponent implements OnDestroy {
@Input() devMode: boolean;
activeAction: Action;
activeActionSubscription: Subscription;
activeOperation: Operation;
activeOperationSubscription: Subscription;
dataschema: {};
uischema: {};
data: {};
constructor(private dataschemaGeneratorService: QueryDataschemaGeneratorService,
private uischemaGeneratorService: QueryUischemaGeneratorService,
private dataGeneratorService: DataGeneratorService,
private apiManagerService: APIManagerService,
private operationPerformerService: OperationPerformerService,
private authService: AuthService) {
this. activeActionSubscription = apiManagerService.activeAction.subscribe((activeAction: Action) => this.activeAction = activeAction);
this.activeOperationSubscription = apiManagerService.activeOperation.subscribe((activeOperation: Operation) => {
this.activeOperation = activeOperation;
if (this.activeOperation) {
this.dataschema = this.dataschemaGeneratorService.generateDataschema(this.activeOperation.getParameters());
this.uischema = this.uischemaGeneratorService.generateUischema(this.dataschema);
this.data = this.dataGeneratorService.generateData(this.activeOperation.getParameters(), this.apiManagerService.getInitialData());
}
});
}
getOperationsList() {
return (this.activeAction && this.activeAction.operations) || [this.activeOperation];
}
selectOperation(operation: Operation) {
this.apiManagerService.setActiveOperation(operation, {});
}
removeOperation(operation: Operation) {
if (this.activeAction.removeOperation(operation)) {
if (this.activeOperation == operation) {
let newActiveOperation: Operation = null;
if (this.activeAction.operations.length > 0) |
this.apiManagerService.setActiveOperation(newActiveOperation, {});
}
}
}
performOperation() {
this.operationPerformerService.performOperation(this.activeOperation, this.data);
}
ngOnDestroy() {
this.activeActionSubscription.unsubscribe();
this.activeOperationSubscription.unsubscribe();
}
}
| {
newActiveOperation = this.activeAction.operations[0];
} | conditional_block |
query.component.ts | import { Component, Input, OnDestroy } from '@angular/core';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { APIManagerService } from '../core/api-manager/api-manager.service';
import { QueryDataschemaGeneratorService } from '../core/schemas/query-dataschema-generator.service';
import { QueryUischemaGeneratorService } from '../core/schemas/query-uischema-generator.service.ts';
import { DataGeneratorService } from '../core/schemas/data-generator.service';
import { OperationPerformerService } from '../core/operation-performer/operation-performer.service';
import { AuthService } from "../auth/auth.service";
import { Action } from '../core/model/action';
import { Operation } from '../core/model/operation';
import { JsonFormsAdapter } from '../../../adapters/jsonforms.adapter';
@Component({
selector: 'query-section',
template: require('./query.html'),
styles: [require('../center-content.css')],
providers: [
QueryDataschemaGeneratorService,
QueryUischemaGeneratorService,
DataGeneratorService
],
directives: [JsonFormsAdapter]
})
export class QueryComponent implements OnDestroy {
@Input() devMode: boolean;
activeAction: Action;
activeActionSubscription: Subscription;
activeOperation: Operation;
activeOperationSubscription: Subscription;
dataschema: {};
uischema: {};
data: {};
constructor(private dataschemaGeneratorService: QueryDataschemaGeneratorService,
private uischemaGeneratorService: QueryUischemaGeneratorService,
private dataGeneratorService: DataGeneratorService,
private apiManagerService: APIManagerService,
private operationPerformerService: OperationPerformerService,
private authService: AuthService) {
this. activeActionSubscription = apiManagerService.activeAction.subscribe((activeAction: Action) => this.activeAction = activeAction);
this.activeOperationSubscription = apiManagerService.activeOperation.subscribe((activeOperation: Operation) => {
this.activeOperation = activeOperation;
if (this.activeOperation) {
this.dataschema = this.dataschemaGeneratorService.generateDataschema(this.activeOperation.getParameters());
this.uischema = this.uischemaGeneratorService.generateUischema(this.dataschema);
this.data = this.dataGeneratorService.generateData(this.activeOperation.getParameters(), this.apiManagerService.getInitialData());
}
});
}
getOperationsList() {
return (this.activeAction && this.activeAction.operations) || [this.activeOperation];
}
selectOperation(operation: Operation) {
this.apiManagerService.setActiveOperation(operation, {});
}
removeOperation(operation: Operation) {
if (this.activeAction.removeOperation(operation)) {
if (this.activeOperation == operation) {
let newActiveOperation: Operation = null;
if (this.activeAction.operations.length > 0) {
newActiveOperation = this.activeAction.operations[0];
}
this.apiManagerService.setActiveOperation(newActiveOperation, {});
}
}
}
performOperation() {
this.operationPerformerService.performOperation(this.activeOperation, this.data);
}
| this.activeOperationSubscription.unsubscribe();
}
} | ngOnDestroy() {
this.activeActionSubscription.unsubscribe(); | random_line_split |
query.component.ts | import { Component, Input, OnDestroy } from '@angular/core';
import * as _ from 'lodash';
import { Subscription } from 'rxjs/Subscription';
import { APIManagerService } from '../core/api-manager/api-manager.service';
import { QueryDataschemaGeneratorService } from '../core/schemas/query-dataschema-generator.service';
import { QueryUischemaGeneratorService } from '../core/schemas/query-uischema-generator.service.ts';
import { DataGeneratorService } from '../core/schemas/data-generator.service';
import { OperationPerformerService } from '../core/operation-performer/operation-performer.service';
import { AuthService } from "../auth/auth.service";
import { Action } from '../core/model/action';
import { Operation } from '../core/model/operation';
import { JsonFormsAdapter } from '../../../adapters/jsonforms.adapter';
@Component({
selector: 'query-section',
template: require('./query.html'),
styles: [require('../center-content.css')],
providers: [
QueryDataschemaGeneratorService,
QueryUischemaGeneratorService,
DataGeneratorService
],
directives: [JsonFormsAdapter]
})
export class QueryComponent implements OnDestroy {
@Input() devMode: boolean;
activeAction: Action;
activeActionSubscription: Subscription;
activeOperation: Operation;
activeOperationSubscription: Subscription;
dataschema: {};
uischema: {};
data: {};
constructor(private dataschemaGeneratorService: QueryDataschemaGeneratorService,
private uischemaGeneratorService: QueryUischemaGeneratorService,
private dataGeneratorService: DataGeneratorService,
private apiManagerService: APIManagerService,
private operationPerformerService: OperationPerformerService,
private authService: AuthService) {
this. activeActionSubscription = apiManagerService.activeAction.subscribe((activeAction: Action) => this.activeAction = activeAction);
this.activeOperationSubscription = apiManagerService.activeOperation.subscribe((activeOperation: Operation) => {
this.activeOperation = activeOperation;
if (this.activeOperation) {
this.dataschema = this.dataschemaGeneratorService.generateDataschema(this.activeOperation.getParameters());
this.uischema = this.uischemaGeneratorService.generateUischema(this.dataschema);
this.data = this.dataGeneratorService.generateData(this.activeOperation.getParameters(), this.apiManagerService.getInitialData());
}
});
}
getOperationsList() {
return (this.activeAction && this.activeAction.operations) || [this.activeOperation];
}
selectOperation(operation: Operation) {
this.apiManagerService.setActiveOperation(operation, {});
}
removeOperation(operation: Operation) {
if (this.activeAction.removeOperation(operation)) {
if (this.activeOperation == operation) {
let newActiveOperation: Operation = null;
if (this.activeAction.operations.length > 0) {
newActiveOperation = this.activeAction.operations[0];
}
this.apiManagerService.setActiveOperation(newActiveOperation, {});
}
}
}
performOperation() |
ngOnDestroy() {
this.activeActionSubscription.unsubscribe();
this.activeOperationSubscription.unsubscribe();
}
}
| {
this.operationPerformerService.performOperation(this.activeOperation, this.data);
} | identifier_body |
process.py | #!/usr/bin/env python3
# process.py
# This script consists of all core functions.
# Author: Orhan Odabasi (0rh.odabasi[at]gmail.com)
import locale
import csv
import os
from PIL import Image
import re
from collections import Counter
def scanDir(path):
# scan the path and collect media data for copy process
while os.path.exists(path) and os.path.isdir(path):
photos_dataset, totalsize, folder_count, videos_dataset = listphotos(path)
p_count = len(photos_dataset)
p_size = "{:.2f} MB".format(float(totalsize/1000000))
return p_count, p_size, folder_count, photos_dataset, videos_dataset
def saveReport(photo_datas, video_datas, target_path):
# save summary data to a csv file
report_dest_p = os.path.join(target_path, "photo_list.csv")
report_dest_v = os.path.join(target_path, "video_list.csv")
with open(report_dest_p, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(photo_datas)
f.close()
with open(report_dest_v, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(video_datas)
f.close()
def listphotos(path):
# Listing all files in target directory
photos_dataset = []
videos_dataset = []
for root, dirs, files in os.walk(path):
for name in files:
p_data_list = []
v_data_list = []
# filename name [0]
file_name = name
# file path [1]
file_path = os.path.join(root, file_name)
# file size [2]
file_size = os.path.getsize(file_path)
try:
# date taken [3]
date_taken = Image.open(file_path)._getexif()[36867]
# year/month/day format required
ymd_format = re.match("(\d{4}):(\d{2}):(\d{2})", date_taken)
# year taken [4]
year = ymd_format.group(1)
# month taken [5]
month = ymd_format.group(2)
# day taken [6]
day = ymd_format.group(3)
# date info will be our new folder name
date_info = "{0}-{1}".format(year, month)
except:
date_taken = "NOT_FOUND"
day = "NOT_FOUND"
year = "NOT_FOUND"
month = "NOT_FOUND"
# destination folder name [7]
date_info = "NOT_FOUND"
if name.lower().endswith((".jpeg", ".jpg", ".png", ".dng")): | videos_dataset.append(v_data_list)
# total size of photos archive (only jpeg and png files)
totalsize = 0
for s in photos_dataset:
totalsize += int(s[2])
#total file count
dirs = []
for x in photos_dataset:
dirs.append(x[7])
foldercount = len(Counter(dirs).most_common())
return photos_dataset, totalsize, foldercount, videos_dataset | p_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info])
photos_dataset.append(p_data_list)
elif name.lower().endswith((".mov", ".mkv", ".mp4", ".3gp", ".wmv", ".avi")):
v_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info]) | random_line_split |
process.py | #!/usr/bin/env python3
# process.py
# This script consists of all core functions.
# Author: Orhan Odabasi (0rh.odabasi[at]gmail.com)
import locale
import csv
import os
from PIL import Image
import re
from collections import Counter
def | (path):
# scan the path and collect media data for copy process
while os.path.exists(path) and os.path.isdir(path):
photos_dataset, totalsize, folder_count, videos_dataset = listphotos(path)
p_count = len(photos_dataset)
p_size = "{:.2f} MB".format(float(totalsize/1000000))
return p_count, p_size, folder_count, photos_dataset, videos_dataset
def saveReport(photo_datas, video_datas, target_path):
# save summary data to a csv file
report_dest_p = os.path.join(target_path, "photo_list.csv")
report_dest_v = os.path.join(target_path, "video_list.csv")
with open(report_dest_p, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(photo_datas)
f.close()
with open(report_dest_v, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(video_datas)
f.close()
def listphotos(path):
# Listing all files in target directory
photos_dataset = []
videos_dataset = []
for root, dirs, files in os.walk(path):
for name in files:
p_data_list = []
v_data_list = []
# filename name [0]
file_name = name
# file path [1]
file_path = os.path.join(root, file_name)
# file size [2]
file_size = os.path.getsize(file_path)
try:
# date taken [3]
date_taken = Image.open(file_path)._getexif()[36867]
# year/month/day format required
ymd_format = re.match("(\d{4}):(\d{2}):(\d{2})", date_taken)
# year taken [4]
year = ymd_format.group(1)
# month taken [5]
month = ymd_format.group(2)
# day taken [6]
day = ymd_format.group(3)
# date info will be our new folder name
date_info = "{0}-{1}".format(year, month)
except:
date_taken = "NOT_FOUND"
day = "NOT_FOUND"
year = "NOT_FOUND"
month = "NOT_FOUND"
# destination folder name [7]
date_info = "NOT_FOUND"
if name.lower().endswith((".jpeg", ".jpg", ".png", ".dng")):
p_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info])
photos_dataset.append(p_data_list)
elif name.lower().endswith((".mov", ".mkv", ".mp4", ".3gp", ".wmv", ".avi")):
v_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info])
videos_dataset.append(v_data_list)
# total size of photos archive (only jpeg and png files)
totalsize = 0
for s in photos_dataset:
totalsize += int(s[2])
#total file count
dirs = []
for x in photos_dataset:
dirs.append(x[7])
foldercount = len(Counter(dirs).most_common())
return photos_dataset, totalsize, foldercount, videos_dataset
| scanDir | identifier_name |
process.py | #!/usr/bin/env python3
# process.py
# This script consists of all core functions.
# Author: Orhan Odabasi (0rh.odabasi[at]gmail.com)
import locale
import csv
import os
from PIL import Image
import re
from collections import Counter
def scanDir(path):
# scan the path and collect media data for copy process
while os.path.exists(path) and os.path.isdir(path):
|
def saveReport(photo_datas, video_datas, target_path):
# save summary data to a csv file
report_dest_p = os.path.join(target_path, "photo_list.csv")
report_dest_v = os.path.join(target_path, "video_list.csv")
with open(report_dest_p, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(photo_datas)
f.close()
with open(report_dest_v, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(video_datas)
f.close()
def listphotos(path):
# Listing all files in target directory
photos_dataset = []
videos_dataset = []
for root, dirs, files in os.walk(path):
for name in files:
p_data_list = []
v_data_list = []
# filename name [0]
file_name = name
# file path [1]
file_path = os.path.join(root, file_name)
# file size [2]
file_size = os.path.getsize(file_path)
try:
# date taken [3]
date_taken = Image.open(file_path)._getexif()[36867]
# year/month/day format required
ymd_format = re.match("(\d{4}):(\d{2}):(\d{2})", date_taken)
# year taken [4]
year = ymd_format.group(1)
# month taken [5]
month = ymd_format.group(2)
# day taken [6]
day = ymd_format.group(3)
# date info will be our new folder name
date_info = "{0}-{1}".format(year, month)
except:
date_taken = "NOT_FOUND"
day = "NOT_FOUND"
year = "NOT_FOUND"
month = "NOT_FOUND"
# destination folder name [7]
date_info = "NOT_FOUND"
if name.lower().endswith((".jpeg", ".jpg", ".png", ".dng")):
p_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info])
photos_dataset.append(p_data_list)
elif name.lower().endswith((".mov", ".mkv", ".mp4", ".3gp", ".wmv", ".avi")):
v_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info])
videos_dataset.append(v_data_list)
# total size of photos archive (only jpeg and png files)
totalsize = 0
for s in photos_dataset:
totalsize += int(s[2])
#total file count
dirs = []
for x in photos_dataset:
dirs.append(x[7])
foldercount = len(Counter(dirs).most_common())
return photos_dataset, totalsize, foldercount, videos_dataset
| photos_dataset, totalsize, folder_count, videos_dataset = listphotos(path)
p_count = len(photos_dataset)
p_size = "{:.2f} MB".format(float(totalsize/1000000))
return p_count, p_size, folder_count, photos_dataset, videos_dataset | conditional_block |
process.py | #!/usr/bin/env python3
# process.py
# This script consists of all core functions.
# Author: Orhan Odabasi (0rh.odabasi[at]gmail.com)
import locale
import csv
import os
from PIL import Image
import re
from collections import Counter
def scanDir(path):
# scan the path and collect media data for copy process
while os.path.exists(path) and os.path.isdir(path):
photos_dataset, totalsize, folder_count, videos_dataset = listphotos(path)
p_count = len(photos_dataset)
p_size = "{:.2f} MB".format(float(totalsize/1000000))
return p_count, p_size, folder_count, photos_dataset, videos_dataset
def saveReport(photo_datas, video_datas, target_path):
# save summary data to a csv file
|
def listphotos(path):
# Listing all files in target directory
photos_dataset = []
videos_dataset = []
for root, dirs, files in os.walk(path):
for name in files:
p_data_list = []
v_data_list = []
# filename name [0]
file_name = name
# file path [1]
file_path = os.path.join(root, file_name)
# file size [2]
file_size = os.path.getsize(file_path)
try:
# date taken [3]
date_taken = Image.open(file_path)._getexif()[36867]
# year/month/day format required
ymd_format = re.match("(\d{4}):(\d{2}):(\d{2})", date_taken)
# year taken [4]
year = ymd_format.group(1)
# month taken [5]
month = ymd_format.group(2)
# day taken [6]
day = ymd_format.group(3)
# date info will be our new folder name
date_info = "{0}-{1}".format(year, month)
except:
date_taken = "NOT_FOUND"
day = "NOT_FOUND"
year = "NOT_FOUND"
month = "NOT_FOUND"
# destination folder name [7]
date_info = "NOT_FOUND"
if name.lower().endswith((".jpeg", ".jpg", ".png", ".dng")):
p_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info])
photos_dataset.append(p_data_list)
elif name.lower().endswith((".mov", ".mkv", ".mp4", ".3gp", ".wmv", ".avi")):
v_data_list.extend([file_name, file_path, file_size, date_taken, year, month, day, date_info])
videos_dataset.append(v_data_list)
# total size of photos archive (only jpeg and png files)
totalsize = 0
for s in photos_dataset:
totalsize += int(s[2])
#total file count
dirs = []
for x in photos_dataset:
dirs.append(x[7])
foldercount = len(Counter(dirs).most_common())
return photos_dataset, totalsize, foldercount, videos_dataset
| report_dest_p = os.path.join(target_path, "photo_list.csv")
report_dest_v = os.path.join(target_path, "video_list.csv")
with open(report_dest_p, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(photo_datas)
f.close()
with open(report_dest_v, "w") as f:
w = csv.writer(f, delimiter="\t")
w.writerows(video_datas)
f.close() | identifier_body |
TypeGraphQLModule.ts |
/**
* @ignore
*/
@Module()
export class TypeGraphQLModule {
@Inject()
protected service: TypeGraphQLService;
@Inject()
protected injector: InjectorService;
@Configuration()
protected configuration: Configuration;
get settings(): {[key: string]: TypeGraphQLSettings} | undefined {
return this.configuration.get("graphql") || this.configuration.get("typegraphql");
}
$onRoutesInit(): Promise<any> | void {
const {settings} = this;
if (settings) {
const promises = Object.entries(settings).map(async ([key, options]) => {
return this.service.createServer(key, options);
});
return Promise.all(promises);
}
}
$afterListen(): Promise<any> | void {
const host = this.configuration.getBestHost();
const displayLog = (key: string, path: string) => {
const url = typeof host.port === "number" ? `${host.protocol}://${host.address}:${host.port}` : "";
this.injector.logger.info(`[${key}] GraphQL server is available on ${url}/${path.replace(/^\//, "")}`);
};
const {settings} = this;
if (settings) {
Object.entries(settings).map(async ([key, options]) => {
const {path} = options;
displayLog(key, path);
});
}
}
} | import {Configuration, Inject, InjectorService, Module} from "@tsed/di";
import {TypeGraphQLSettings} from "./interfaces";
import {TypeGraphQLService} from "./services/TypeGraphQLService"; | random_line_split | |
TypeGraphQLModule.ts | import {Configuration, Inject, InjectorService, Module} from "@tsed/di";
import {TypeGraphQLSettings} from "./interfaces";
import {TypeGraphQLService} from "./services/TypeGraphQLService";
/**
* @ignore
*/
@Module()
export class | {
@Inject()
protected service: TypeGraphQLService;
@Inject()
protected injector: InjectorService;
@Configuration()
protected configuration: Configuration;
get settings(): {[key: string]: TypeGraphQLSettings} | undefined {
return this.configuration.get("graphql") || this.configuration.get("typegraphql");
}
$onRoutesInit(): Promise<any> | void {
const {settings} = this;
if (settings) {
const promises = Object.entries(settings).map(async ([key, options]) => {
return this.service.createServer(key, options);
});
return Promise.all(promises);
}
}
$afterListen(): Promise<any> | void {
const host = this.configuration.getBestHost();
const displayLog = (key: string, path: string) => {
const url = typeof host.port === "number" ? `${host.protocol}://${host.address}:${host.port}` : "";
this.injector.logger.info(`[${key}] GraphQL server is available on ${url}/${path.replace(/^\//, "")}`);
};
const {settings} = this;
if (settings) {
Object.entries(settings).map(async ([key, options]) => {
const {path} = options;
displayLog(key, path);
});
}
}
}
| TypeGraphQLModule | identifier_name |
TypeGraphQLModule.ts | import {Configuration, Inject, InjectorService, Module} from "@tsed/di";
import {TypeGraphQLSettings} from "./interfaces";
import {TypeGraphQLService} from "./services/TypeGraphQLService";
/**
* @ignore
*/
@Module()
export class TypeGraphQLModule {
@Inject()
protected service: TypeGraphQLService;
@Inject()
protected injector: InjectorService;
@Configuration()
protected configuration: Configuration;
get settings(): {[key: string]: TypeGraphQLSettings} | undefined {
return this.configuration.get("graphql") || this.configuration.get("typegraphql");
}
$onRoutesInit(): Promise<any> | void {
const {settings} = this;
if (settings) {
const promises = Object.entries(settings).map(async ([key, options]) => {
return this.service.createServer(key, options);
});
return Promise.all(promises);
}
}
$afterListen(): Promise<any> | void {
const host = this.configuration.getBestHost();
const displayLog = (key: string, path: string) => {
const url = typeof host.port === "number" ? `${host.protocol}://${host.address}:${host.port}` : "";
this.injector.logger.info(`[${key}] GraphQL server is available on ${url}/${path.replace(/^\//, "")}`);
};
const {settings} = this;
if (settings) |
}
}
| {
Object.entries(settings).map(async ([key, options]) => {
const {path} = options;
displayLog(key, path);
});
} | conditional_block |
TypeGraphQLModule.ts | import {Configuration, Inject, InjectorService, Module} from "@tsed/di";
import {TypeGraphQLSettings} from "./interfaces";
import {TypeGraphQLService} from "./services/TypeGraphQLService";
/**
* @ignore
*/
@Module()
export class TypeGraphQLModule {
@Inject()
protected service: TypeGraphQLService;
@Inject()
protected injector: InjectorService;
@Configuration()
protected configuration: Configuration;
get settings(): {[key: string]: TypeGraphQLSettings} | undefined {
return this.configuration.get("graphql") || this.configuration.get("typegraphql");
}
$onRoutesInit(): Promise<any> | void |
$afterListen(): Promise<any> | void {
const host = this.configuration.getBestHost();
const displayLog = (key: string, path: string) => {
const url = typeof host.port === "number" ? `${host.protocol}://${host.address}:${host.port}` : "";
this.injector.logger.info(`[${key}] GraphQL server is available on ${url}/${path.replace(/^\//, "")}`);
};
const {settings} = this;
if (settings) {
Object.entries(settings).map(async ([key, options]) => {
const {path} = options;
displayLog(key, path);
});
}
}
}
| {
const {settings} = this;
if (settings) {
const promises = Object.entries(settings).map(async ([key, options]) => {
return this.service.createServer(key, options);
});
return Promise.all(promises);
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.