file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
virtual_interface.py | # Copyright (C) 2014, Red Hat, 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.
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
# TODO(berrange): Remove NovaObjectDictCompat
class VirtualInterface(base.NovaPersistentObject, base.NovaObject,
base.NovaObjectDictCompat):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.IntegerField(),
'address': fields.StringField(nullable=True),
'network_id': fields.IntegerField(),
'instance_uuid': fields.UUIDField(),
'uuid': fields.UUIDField(),
}
@staticmethod
def _from_db_object(context, vif, db_vif):
for field in vif.fields:
vif[field] = db_vif[field]
vif._context = context
vif.obj_reset_changes()
return vif
@base.remotable_classmethod
def get_by_id(cls, context, vif_id):
db_vif = db.virtual_interface_get(context, vif_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_uuid(cls, context, vif_uuid):
db_vif = db.virtual_interface_get_by_uuid(context, vif_uuid)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_address(cls, context, address):
db_vif = db.virtual_interface_get_by_address(context, address)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_instance_and_network(cls, context, instance_uuid, network_id):
db_vif = db.virtual_interface_get_by_instance_and_network(context,
instance_uuid, network_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable
def create(self):
if self.obj_attr_is_set('id'):
raise exception.ObjectActionError(action='create',
reason='already created')
updates = self.obj_get_changes()
db_vif = db.virtual_interface_create(self._context, updates)
self._from_db_object(self._context, self, db_vif)
@base.remotable_classmethod
def delete_by_instance_uuid(cls, context, instance_uuid):
db.virtual_interface_delete_by_instance(context, instance_uuid)
class VirtualInterfaceList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'objects': fields.ListOfObjectsField('VirtualInterface'),
}
child_versions = {
'1.0': '1.0',
}
@base.remotable_classmethod
def get_all(cls, context):
db_vifs = db.virtual_interface_get_all(context)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
@base.remotable_classmethod
def | (cls, context, instance_uuid, use_slave=False):
db_vifs = db.virtual_interface_get_by_instance(context, instance_uuid,
use_slave=use_slave)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
| get_by_instance_uuid | identifier_name |
virtual_interface.py | # Copyright (C) 2014, Red Hat, 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.
from nova import db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields
# TODO(berrange): Remove NovaObjectDictCompat
class VirtualInterface(base.NovaPersistentObject, base.NovaObject,
base.NovaObjectDictCompat):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.IntegerField(),
'address': fields.StringField(nullable=True),
'network_id': fields.IntegerField(),
'instance_uuid': fields.UUIDField(),
'uuid': fields.UUIDField(),
}
@staticmethod
def _from_db_object(context, vif, db_vif):
for field in vif.fields:
vif[field] = db_vif[field]
vif._context = context
vif.obj_reset_changes()
return vif
@base.remotable_classmethod
def get_by_id(cls, context, vif_id):
db_vif = db.virtual_interface_get(context, vif_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_uuid(cls, context, vif_uuid):
db_vif = db.virtual_interface_get_by_uuid(context, vif_uuid)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable_classmethod
def get_by_address(cls, context, address):
db_vif = db.virtual_interface_get_by_address(context, address)
if db_vif:
|
@base.remotable_classmethod
def get_by_instance_and_network(cls, context, instance_uuid, network_id):
db_vif = db.virtual_interface_get_by_instance_and_network(context,
instance_uuid, network_id)
if db_vif:
return cls._from_db_object(context, cls(), db_vif)
@base.remotable
def create(self):
if self.obj_attr_is_set('id'):
raise exception.ObjectActionError(action='create',
reason='already created')
updates = self.obj_get_changes()
db_vif = db.virtual_interface_create(self._context, updates)
self._from_db_object(self._context, self, db_vif)
@base.remotable_classmethod
def delete_by_instance_uuid(cls, context, instance_uuid):
db.virtual_interface_delete_by_instance(context, instance_uuid)
class VirtualInterfaceList(base.ObjectListBase, base.NovaObject):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'objects': fields.ListOfObjectsField('VirtualInterface'),
}
child_versions = {
'1.0': '1.0',
}
@base.remotable_classmethod
def get_all(cls, context):
db_vifs = db.virtual_interface_get_all(context)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
@base.remotable_classmethod
def get_by_instance_uuid(cls, context, instance_uuid, use_slave=False):
db_vifs = db.virtual_interface_get_by_instance(context, instance_uuid,
use_slave=use_slave)
return base.obj_make_list(context, cls(context),
objects.VirtualInterface, db_vifs)
| return cls._from_db_object(context, cls(), db_vif) | conditional_block |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn new() -> Mem |
/// Return the value of cell at the current pointer.
#[inline]
pub fn get(&self) -> u8 {
self.cells[self.ptr]
}
/// Set the value at the current pointer.
#[inline]
pub fn set(&mut self, value: u8) {
self.cells[self.ptr] = value;
}
/// Adds `value` to the current cell.
#[inline]
pub fn add(&mut self, value: u8) {
self.cells[self.ptr] += value;
}
/// Subtracts `value` from the current cell.
#[inline]
pub fn subtract(&mut self, value: u8) {
self.cells[self.ptr] -= value;
}
/// Shifts the current pointer to the left or right by a number of steps.
#[inline]
pub fn shift(&mut self, dir: Dir, steps: usize) {
match dir {
Left => self.ptr -= steps,
Right => self.ptr += steps,
}
}
// optimizations
/// Clears the current cell.
#[inline]
pub fn clear(&mut self) {
self.cells[self.ptr] = 0;
}
/// Scans left or right for a zero cell. This fuction will panic! if there
/// is no zero cell before it scans past the beginning of the address space.
#[inline]
pub fn scan(&mut self, dir: Dir) {
while self.cells[self.ptr] != 0 {
self.shift(dir, 1);
}
}
/// Copys the value of the current cell into the cell left or right a
/// number of steps.
#[inline]
pub fn copy(&mut self, dir: Dir, steps: usize) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
self.cells[index] += self.cells[self.ptr];
}
/// Multiplys the value of the current cell by a factor and inserts the
/// product into the cell left or right a number of steps.
pub fn multiply(&mut self, dir: Dir, steps: usize, factor: i8) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
// safely cast factor to u8
let u8_factor = SignedInt::abs(factor) as u8;
// when factor is 1 it acts like a copy
if factor == 1 {
self.cells[index] += self.cells[self.ptr];
}
// when factor is -1 it acts like the inverse of copy
else if factor == -1 {
self.cells[index] -= self.cells[self.ptr];
}
// when factor is >= 2 it adds the product of the current cell and the
// absolute value of factor to the cell at index
else if factor >= 2 {
self.cells[index] += self.cells[self.ptr] * u8_factor;
}
// when factor is <= -2 it subtracts the product of the current cell and the
// absolute value of factor to the cell at index
else if factor <= -2 {
self.cells[index] -= self.cells[self.ptr] * u8_factor;
}
// when factor is 0 it is ignored, as it would do nothing
else {}
}
}
| {
Mem {
cells: box [0u8; MEM_SIZE],
ptr: 0
}
} | identifier_body |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn new() -> Mem {
Mem {
cells: box [0u8; MEM_SIZE],
ptr: 0
}
}
/// Return the value of cell at the current pointer.
#[inline]
pub fn get(&self) -> u8 {
self.cells[self.ptr]
}
/// Set the value at the current pointer.
#[inline]
pub fn set(&mut self, value: u8) {
self.cells[self.ptr] = value;
}
/// Adds `value` to the current cell.
#[inline]
pub fn add(&mut self, value: u8) {
self.cells[self.ptr] += value;
}
/// Subtracts `value` from the current cell.
#[inline]
pub fn subtract(&mut self, value: u8) {
self.cells[self.ptr] -= value;
}
/// Shifts the current pointer to the left or right by a number of steps.
#[inline]
pub fn shift(&mut self, dir: Dir, steps: usize) {
match dir {
Left => self.ptr -= steps,
Right => self.ptr += steps,
}
}
// optimizations
/// Clears the current cell.
#[inline]
pub fn clear(&mut self) {
self.cells[self.ptr] = 0;
}
/// Scans left or right for a zero cell. This fuction will panic! if there
/// is no zero cell before it scans past the beginning of the address space.
#[inline]
pub fn scan(&mut self, dir: Dir) {
while self.cells[self.ptr] != 0 {
self.shift(dir, 1);
}
}
/// Copys the value of the current cell into the cell left or right a
/// number of steps.
#[inline] | };
self.cells[index] += self.cells[self.ptr];
}
/// Multiplys the value of the current cell by a factor and inserts the
/// product into the cell left or right a number of steps.
pub fn multiply(&mut self, dir: Dir, steps: usize, factor: i8) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
// safely cast factor to u8
let u8_factor = SignedInt::abs(factor) as u8;
// when factor is 1 it acts like a copy
if factor == 1 {
self.cells[index] += self.cells[self.ptr];
}
// when factor is -1 it acts like the inverse of copy
else if factor == -1 {
self.cells[index] -= self.cells[self.ptr];
}
// when factor is >= 2 it adds the product of the current cell and the
// absolute value of factor to the cell at index
else if factor >= 2 {
self.cells[index] += self.cells[self.ptr] * u8_factor;
}
// when factor is <= -2 it subtracts the product of the current cell and the
// absolute value of factor to the cell at index
else if factor <= -2 {
self.cells[index] -= self.cells[self.ptr] * u8_factor;
}
// when factor is 0 it is ignored, as it would do nothing
else {}
}
} | pub fn copy(&mut self, dir: Dir, steps: usize) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps, | random_line_split |
mem.rs | use std::num::SignedInt;
use syntax::{Dir, Left, Right};
// size of allocated memory in bytes
const MEM_SIZE: usize = 65_536; // 64kB!
pub struct Mem {
cells: Box<[u8]>, // address space
ptr: usize // pointer in address space
}
impl Mem {
/// Create a new `Mem` stuct.
#[inline]
pub fn new() -> Mem {
Mem {
cells: box [0u8; MEM_SIZE],
ptr: 0
}
}
/// Return the value of cell at the current pointer.
#[inline]
pub fn get(&self) -> u8 {
self.cells[self.ptr]
}
/// Set the value at the current pointer.
#[inline]
pub fn set(&mut self, value: u8) {
self.cells[self.ptr] = value;
}
/// Adds `value` to the current cell.
#[inline]
pub fn add(&mut self, value: u8) {
self.cells[self.ptr] += value;
}
/// Subtracts `value` from the current cell.
#[inline]
pub fn subtract(&mut self, value: u8) {
self.cells[self.ptr] -= value;
}
/// Shifts the current pointer to the left or right by a number of steps.
#[inline]
pub fn shift(&mut self, dir: Dir, steps: usize) {
match dir {
Left => self.ptr -= steps,
Right => self.ptr += steps,
}
}
// optimizations
/// Clears the current cell.
#[inline]
pub fn clear(&mut self) {
self.cells[self.ptr] = 0;
}
/// Scans left or right for a zero cell. This fuction will panic! if there
/// is no zero cell before it scans past the beginning of the address space.
#[inline]
pub fn | (&mut self, dir: Dir) {
while self.cells[self.ptr] != 0 {
self.shift(dir, 1);
}
}
/// Copys the value of the current cell into the cell left or right a
/// number of steps.
#[inline]
pub fn copy(&mut self, dir: Dir, steps: usize) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
self.cells[index] += self.cells[self.ptr];
}
/// Multiplys the value of the current cell by a factor and inserts the
/// product into the cell left or right a number of steps.
pub fn multiply(&mut self, dir: Dir, steps: usize, factor: i8) {
let index = match dir {
Left => self.ptr - steps,
Right => self.ptr + steps,
};
// safely cast factor to u8
let u8_factor = SignedInt::abs(factor) as u8;
// when factor is 1 it acts like a copy
if factor == 1 {
self.cells[index] += self.cells[self.ptr];
}
// when factor is -1 it acts like the inverse of copy
else if factor == -1 {
self.cells[index] -= self.cells[self.ptr];
}
// when factor is >= 2 it adds the product of the current cell and the
// absolute value of factor to the cell at index
else if factor >= 2 {
self.cells[index] += self.cells[self.ptr] * u8_factor;
}
// when factor is <= -2 it subtracts the product of the current cell and the
// absolute value of factor to the cell at index
else if factor <= -2 {
self.cells[index] -= self.cells[self.ptr] * u8_factor;
}
// when factor is 0 it is ignored, as it would do nothing
else {}
}
}
| scan | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class | (AutotoolsPackage):
"""The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbucket.org/saws/saws/wiki/Home"
version('develop', git='https://bitbucket.org/saws/saws.git', tag='master')
version('0.1.0', git='https://bitbucket.org/saws/saws.git', tag='v0.1.0')
| Saws | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Saws(AutotoolsPackage):
| """The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbucket.org/saws/saws/wiki/Home"
version('develop', git='https://bitbucket.org/saws/saws.git', tag='master')
version('0.1.0', git='https://bitbucket.org/saws/saws.git', tag='v0.1.0') | identifier_body | |
package.py | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
# |
class Saws(AutotoolsPackage):
"""The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (and even modify) the state of the
simulation with any browser from anywhere."""
homepage = "https://bitbucket.org/saws/saws/wiki/Home"
version('develop', git='https://bitbucket.org/saws/saws.git', tag='master')
version('0.1.0', git='https://bitbucket.org/saws/saws.git', tag='v0.1.0') | # You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import * | random_line_split |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status: {
danger: string;
};
}
// allow configuration using `createMuiTheme`
interface ThemeOptions {
status?: {
danger?: string;
};
}
}
const CustomCheckbox = styled(Checkbox)(({ theme }) => ({
color: theme.status.danger,
'&.Mui-checked': {
color: theme.status.danger,
},
}));
const theme = createMuiTheme({
status: {
danger: orange[500],
}, | <ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
} | });
export default function CustomStyles() {
return ( | random_line_split |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status: {
danger: string;
};
}
// allow configuration using `createMuiTheme`
interface ThemeOptions {
status?: {
danger?: string;
};
}
}
const CustomCheckbox = styled(Checkbox)(({ theme }) => ({
color: theme.status.danger,
'&.Mui-checked': {
color: theme.status.danger,
},
}));
const theme = createMuiTheme({
status: {
danger: orange[500],
},
});
export default function | () {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
}
| CustomStyles | identifier_name |
CustomStyles.tsx | import * as React from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import {
createMuiTheme,
ThemeProvider,
experimentalStyled as styled,
} from '@material-ui/core/styles';
import { orange } from '@material-ui/core/colors';
declare module '@material-ui/core/styles' {
interface Theme {
status: {
danger: string;
};
}
// allow configuration using `createMuiTheme`
interface ThemeOptions {
status?: {
danger?: string;
};
}
}
const CustomCheckbox = styled(Checkbox)(({ theme }) => ({
color: theme.status.danger,
'&.Mui-checked': {
color: theme.status.danger,
},
}));
const theme = createMuiTheme({
status: {
danger: orange[500],
},
});
export default function CustomStyles() | {
return (
<ThemeProvider theme={theme}>
<CustomCheckbox defaultChecked />
</ThemeProvider>
);
} | identifier_body | |
indexedlogauxstore.rs | Entry {
fn from(v: FileAuxData) -> Self {
Entry {
total_size: v.total_size,
content_id: v.content_id,
content_sha1: v.sha1,
content_sha256: v.sha256,
}
}
}
impl Entry {
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn content_id(&self) -> ContentId {
self.content_id
}
pub fn content_sha1(&self) -> Sha1 {
self.content_sha1
}
pub fn content_sha256(&self) -> Sha256 {
self.content_sha256
}
/// Serialize the Entry to Bytes.
///
/// The serialization format is as follows:
/// - HgId <20 bytes>
/// - Version <1 byte> (for compatibility)
/// - content_id <32 bytes>
/// - content sha1 <20 bytes>
/// - content sha256 <32 bytes>
/// - total_size <u64 VLQ, 1-9 bytes>
fn serialize(&self, hgid: HgId) -> Result<Bytes> {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
Ok(buf.into())
}
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
}
let mut content_id = [0u8; 32];
cur.read_exact(&mut content_id)?;
let mut content_sha1 = [0u8; 20];
cur.read_exact(&mut content_sha1)?;
let mut content_sha256 = [0u8; 32];
cur.read_exact(&mut content_sha256)?;
let total_size: u64 = cur.read_vlq()?;
Ok((
hgid,
Entry {
content_id: content_id.into(),
content_sha1: content_sha1.into(),
content_sha256: content_sha256.into(),
total_size,
},
))
}
}
pub struct AuxStore(RwLock<Store>);
impl AuxStore {
pub fn new(path: impl AsRef<Path>, config: &ConfigSet, store_type: StoreType) -> Result<Self> {
// TODO(meyer): Eliminate "local" AuxStore - always treat it as shared / cache?
let open_options = AuxStore::open_options(config)?;
let log = match store_type {
StoreType::Local => open_options.local(&path),
StoreType::Shared => open_options.shared(&path),
}?;
Ok(AuxStore(RwLock::new(log)))
}
fn open_options(config: &ConfigSet) -> Result<StoreOpenOptions> {
// TODO(meyer): Decide exactly how we want to configure this store. This is all copied from indexedlogdatastore
// Default configuration: 4 x 2.5GB.
let mut open_options = StoreOpenOptions::new()
.max_log_count(4)
.max_bytes_per_log(2500 * 1000 * 1000)
.auto_sync_threshold(10 * 1024 * 1024)
.create(true)
.index("node", |_| {
vec![IndexOutput::Reference(0..HgId::len() as u64)]
});
if let Some(max_log_count) = config.get_opt::<u8>("indexedlog", "data.max-log-count")? {
open_options = open_options.max_log_count(max_log_count);
}
if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("indexedlog", "data.max-bytes-per-log")?
{
open_options = open_options.max_bytes_per_log(max_bytes_per_log.value());
} else if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("remotefilelog", "cachelimit")?
|
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes = log.slice_to_bytes(slice);
drop(log);
Entry::deserialize(bytes).map(|(_hgid, entry)| Some(entry))
}
pub fn put(&self, hgid: HgId, entry: &Entry) -> Result<()> {
let serialized = entry.serialize(hgid)?;
self.0.write().append(&serialized)
}
pub fn flush(&self) -> Result<()> {
self.0.write().flush()
}
#[cfg(test)]
pub(crate) fn hgids(&self) -> Result<Vec<HgId>> {
let log = self.0.read();
log.iter()
.map(|slice| {
let bytes = log.slice_to_bytes(slice?);
Entry::deserialize(bytes).map(|(hgid, _entry)| hgid)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use std::str::FromStr;
use std::sync::Arc;
use tempfile::TempDir;
use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mut x: [u8; Sha1::len()] = Default::default();
x[0] = fst;
Sha1::from(x)
}
#[test]
fn test_empty() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let found = store.get(k.hgid)?;
assert_eq!(Some(entry), found);
Ok(())
}
#[test]
fn test_lookup_failure() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let k2 = key("b", "2");
let found = store.get(k2.hgid)?;
assert_eq!(None, found);
Ok(())
}
#[test]
fn test_corrupted() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "2");
let mut entry = Entry::default();
entry.total_size = 2;
entry.content_sha1 = single_byte_sha1(2);
store.put(k.hgid, &entry)?;
store.flush()?;
drop(store);
// Corrupt the log by removing the "log" file.
let mut rotate_log_path = tempdir.path().to_path_buf();
rotate_log_path.push("0");
rotate_log_path.push("log");
remove_file(rotate_log_path)?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "3");
let mut entry = Entry::default();
entry.total_size = 3;
entry.content_sha1 = single_byte_sha1(3);
store.put(k.hgid, &entry)?;
store.flush()?;
// There should be only one key in the store.
assert_eq!(store.hgids().into_iter().count(), | {
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
} | conditional_block |
indexedlogauxstore.rs | Entry {
fn from(v: FileAuxData) -> Self {
Entry {
total_size: v.total_size,
content_id: v.content_id,
content_sha1: v.sha1,
content_sha256: v.sha256,
}
}
}
impl Entry {
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn content_id(&self) -> ContentId {
self.content_id
}
pub fn content_sha1(&self) -> Sha1 {
self.content_sha1
}
pub fn content_sha256(&self) -> Sha256 {
self.content_sha256
}
/// Serialize the Entry to Bytes.
///
/// The serialization format is as follows:
/// - HgId <20 bytes>
/// - Version <1 byte> (for compatibility)
/// - content_id <32 bytes>
/// - content sha1 <20 bytes>
/// - content sha256 <32 bytes>
/// - total_size <u64 VLQ, 1-9 bytes>
fn serialize(&self, hgid: HgId) -> Result<Bytes> {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
Ok(buf.into())
}
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
}
let mut content_id = [0u8; 32];
cur.read_exact(&mut content_id)?;
let mut content_sha1 = [0u8; 20];
cur.read_exact(&mut content_sha1)?;
let mut content_sha256 = [0u8; 32];
cur.read_exact(&mut content_sha256)?;
let total_size: u64 = cur.read_vlq()?;
Ok((
hgid,
Entry {
content_id: content_id.into(),
content_sha1: content_sha1.into(),
content_sha256: content_sha256.into(),
total_size,
},
))
}
}
pub struct AuxStore(RwLock<Store>);
impl AuxStore {
pub fn new(path: impl AsRef<Path>, config: &ConfigSet, store_type: StoreType) -> Result<Self> {
// TODO(meyer): Eliminate "local" AuxStore - always treat it as shared / cache?
let open_options = AuxStore::open_options(config)?;
let log = match store_type {
StoreType::Local => open_options.local(&path),
StoreType::Shared => open_options.shared(&path),
}?;
Ok(AuxStore(RwLock::new(log)))
}
fn open_options(config: &ConfigSet) -> Result<StoreOpenOptions> {
// TODO(meyer): Decide exactly how we want to configure this store. This is all copied from indexedlogdatastore
// Default configuration: 4 x 2.5GB.
let mut open_options = StoreOpenOptions::new()
.max_log_count(4)
.max_bytes_per_log(2500 * 1000 * 1000)
.auto_sync_threshold(10 * 1024 * 1024)
.create(true)
.index("node", |_| {
vec![IndexOutput::Reference(0..HgId::len() as u64)]
});
if let Some(max_log_count) = config.get_opt::<u8>("indexedlog", "data.max-log-count")? {
open_options = open_options.max_log_count(max_log_count);
}
if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("indexedlog", "data.max-bytes-per-log")?
{
open_options = open_options.max_bytes_per_log(max_bytes_per_log.value());
} else if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("remotefilelog", "cachelimit")?
{
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
}
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes = log.slice_to_bytes(slice);
drop(log);
Entry::deserialize(bytes).map(|(_hgid, entry)| Some(entry))
}
pub fn put(&self, hgid: HgId, entry: &Entry) -> Result<()> {
let serialized = entry.serialize(hgid)?;
self.0.write().append(&serialized)
}
pub fn flush(&self) -> Result<()> {
self.0.write().flush()
}
#[cfg(test)]
pub(crate) fn hgids(&self) -> Result<Vec<HgId>> {
let log = self.0.read();
log.iter()
.map(|slice| {
let bytes = log.slice_to_bytes(slice?);
Entry::deserialize(bytes).map(|(hgid, _entry)| hgid)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use std::str::FromStr;
use std::sync::Arc;
use tempfile::TempDir;
use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mut x: [u8; Sha1::len()] = Default::default();
x[0] = fst;
Sha1::from(x)
}
#[test]
fn | () -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let found = store.get(k.hgid)?;
assert_eq!(Some(entry), found);
Ok(())
}
#[test]
fn test_lookup_failure() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let k2 = key("b", "2");
let found = store.get(k2.hgid)?;
assert_eq!(None, found);
Ok(())
}
#[test]
fn test_corrupted() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "2");
let mut entry = Entry::default();
entry.total_size = 2;
entry.content_sha1 = single_byte_sha1(2);
store.put(k.hgid, &entry)?;
store.flush()?;
drop(store);
// Corrupt the log by removing the "log" file.
let mut rotate_log_path = tempdir.path().to_path_buf();
rotate_log_path.push("0");
rotate_log_path.push("log");
remove_file(rotate_log_path)?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "3");
let mut entry = Entry::default();
entry.total_size = 3;
entry.content_sha1 = single_byte_sha1(3);
store.put(k.hgid, &entry)?;
store.flush()?;
// There should be only one key in the store.
assert_eq!(store.hgids().into_iter().count(), | test_empty | identifier_name |
indexedlogauxstore.rs | Entry {
fn from(v: FileAuxData) -> Self {
Entry {
total_size: v.total_size,
content_id: v.content_id,
content_sha1: v.sha1,
content_sha256: v.sha256,
}
}
}
impl Entry {
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn content_id(&self) -> ContentId {
self.content_id
}
pub fn content_sha1(&self) -> Sha1 {
self.content_sha1
}
pub fn content_sha256(&self) -> Sha256 {
self.content_sha256
}
/// Serialize the Entry to Bytes.
///
/// The serialization format is as follows:
/// - HgId <20 bytes>
/// - Version <1 byte> (for compatibility)
/// - content_id <32 bytes>
/// - content sha1 <20 bytes>
/// - content sha256 <32 bytes>
/// - total_size <u64 VLQ, 1-9 bytes>
fn serialize(&self, hgid: HgId) -> Result<Bytes> |
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
}
let mut content_id = [0u8; 32];
cur.read_exact(&mut content_id)?;
let mut content_sha1 = [0u8; 20];
cur.read_exact(&mut content_sha1)?;
let mut content_sha256 = [0u8; 32];
cur.read_exact(&mut content_sha256)?;
let total_size: u64 = cur.read_vlq()?;
Ok((
hgid,
Entry {
content_id: content_id.into(),
content_sha1: content_sha1.into(),
content_sha256: content_sha256.into(),
total_size,
},
))
}
}
pub struct AuxStore(RwLock<Store>);
impl AuxStore {
pub fn new(path: impl AsRef<Path>, config: &ConfigSet, store_type: StoreType) -> Result<Self> {
// TODO(meyer): Eliminate "local" AuxStore - always treat it as shared / cache?
let open_options = AuxStore::open_options(config)?;
let log = match store_type {
StoreType::Local => open_options.local(&path),
StoreType::Shared => open_options.shared(&path),
}?;
Ok(AuxStore(RwLock::new(log)))
}
fn open_options(config: &ConfigSet) -> Result<StoreOpenOptions> {
// TODO(meyer): Decide exactly how we want to configure this store. This is all copied from indexedlogdatastore
// Default configuration: 4 x 2.5GB.
let mut open_options = StoreOpenOptions::new()
.max_log_count(4)
.max_bytes_per_log(2500 * 1000 * 1000)
.auto_sync_threshold(10 * 1024 * 1024)
.create(true)
.index("node", |_| {
vec![IndexOutput::Reference(0..HgId::len() as u64)]
});
if let Some(max_log_count) = config.get_opt::<u8>("indexedlog", "data.max-log-count")? {
open_options = open_options.max_log_count(max_log_count);
}
if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("indexedlog", "data.max-bytes-per-log")?
{
open_options = open_options.max_bytes_per_log(max_bytes_per_log.value());
} else if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("remotefilelog", "cachelimit")?
{
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
}
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes = log.slice_to_bytes(slice);
drop(log);
Entry::deserialize(bytes).map(|(_hgid, entry)| Some(entry))
}
pub fn put(&self, hgid: HgId, entry: &Entry) -> Result<()> {
let serialized = entry.serialize(hgid)?;
self.0.write().append(&serialized)
}
pub fn flush(&self) -> Result<()> {
self.0.write().flush()
}
#[cfg(test)]
pub(crate) fn hgids(&self) -> Result<Vec<HgId>> {
let log = self.0.read();
log.iter()
.map(|slice| {
let bytes = log.slice_to_bytes(slice?);
Entry::deserialize(bytes).map(|(hgid, _entry)| hgid)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use std::str::FromStr;
use std::sync::Arc;
use tempfile::TempDir;
use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mut x: [u8; Sha1::len()] = Default::default();
x[0] = fst;
Sha1::from(x)
}
#[test]
fn test_empty() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let found = store.get(k.hgid)?;
assert_eq!(Some(entry), found);
Ok(())
}
#[test]
fn test_lookup_failure() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let k2 = key("b", "2");
let found = store.get(k2.hgid)?;
assert_eq!(None, found);
Ok(())
}
#[test]
fn test_corrupted() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "2");
let mut entry = Entry::default();
entry.total_size = 2;
entry.content_sha1 = single_byte_sha1(2);
store.put(k.hgid, &entry)?;
store.flush()?;
drop(store);
// Corrupt the log by removing the "log" file.
let mut rotate_log_path = tempdir.path().to_path_buf();
rotate_log_path.push("0");
rotate_log_path.push("log");
remove_file(rotate_log_path)?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "3");
let mut entry = Entry::default();
entry.total_size = 3;
entry.content_sha1 = single_byte_sha1(3);
store.put(k.hgid, &entry)?;
store.flush()?;
// There should be only one key in the store.
assert_eq!(store.hgids().into_iter().count(), | {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
Ok(buf.into())
} | identifier_body |
indexedlogauxstore.rs | Entry {
fn from(v: FileAuxData) -> Self {
Entry {
total_size: v.total_size,
content_id: v.content_id,
content_sha1: v.sha1,
content_sha256: v.sha256,
}
}
}
impl Entry {
pub fn total_size(&self) -> u64 {
self.total_size
}
pub fn content_id(&self) -> ContentId {
self.content_id
}
pub fn content_sha1(&self) -> Sha1 {
self.content_sha1
}
pub fn content_sha256(&self) -> Sha256 {
self.content_sha256
}
/// Serialize the Entry to Bytes.
///
/// The serialization format is as follows:
/// - HgId <20 bytes>
/// - Version <1 byte> (for compatibility)
/// - content_id <32 bytes>
/// - content sha1 <20 bytes>
/// - content sha256 <32 bytes>
/// - total_size <u64 VLQ, 1-9 bytes>
fn serialize(&self, hgid: HgId) -> Result<Bytes> {
let mut buf = Vec::new();
buf.write_all(hgid.as_ref())?;
buf.write_u8(0)?; // write version
buf.write_all(self.content_id.as_ref())?;
buf.write_all(self.content_sha1.as_ref())?;
buf.write_all(self.content_sha256.as_ref())?;
buf.write_vlq(self.total_size)?;
Ok(buf.into())
}
fn deserialize(bytes: Bytes) -> Result<(HgId, Self)> {
let data: &[u8] = bytes.as_ref();
let mut cur = Cursor::new(data);
let hgid = cur.read_hgid()?;
let version = cur.read_u8()?;
if version != 0 {
bail!("unsupported auxstore entry version {}", version);
}
let mut content_id = [0u8; 32];
cur.read_exact(&mut content_id)?;
let mut content_sha1 = [0u8; 20];
cur.read_exact(&mut content_sha1)?;
let mut content_sha256 = [0u8; 32];
cur.read_exact(&mut content_sha256)?;
let total_size: u64 = cur.read_vlq()?;
Ok((
hgid,
Entry {
content_id: content_id.into(),
content_sha1: content_sha1.into(),
content_sha256: content_sha256.into(),
total_size,
},
))
}
}
pub struct AuxStore(RwLock<Store>);
impl AuxStore {
pub fn new(path: impl AsRef<Path>, config: &ConfigSet, store_type: StoreType) -> Result<Self> {
// TODO(meyer): Eliminate "local" AuxStore - always treat it as shared / cache?
let open_options = AuxStore::open_options(config)?;
let log = match store_type {
StoreType::Local => open_options.local(&path),
StoreType::Shared => open_options.shared(&path),
}?;
Ok(AuxStore(RwLock::new(log)))
}
fn open_options(config: &ConfigSet) -> Result<StoreOpenOptions> {
// TODO(meyer): Decide exactly how we want to configure this store. This is all copied from indexedlogdatastore
// Default configuration: 4 x 2.5GB.
let mut open_options = StoreOpenOptions::new()
.max_log_count(4)
.max_bytes_per_log(2500 * 1000 * 1000)
.auto_sync_threshold(10 * 1024 * 1024)
.create(true)
.index("node", |_| {
vec![IndexOutput::Reference(0..HgId::len() as u64)]
});
if let Some(max_log_count) = config.get_opt::<u8>("indexedlog", "data.max-log-count")? {
open_options = open_options.max_log_count(max_log_count);
}
if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("indexedlog", "data.max-bytes-per-log")?
{
open_options = open_options.max_bytes_per_log(max_bytes_per_log.value());
} else if let Some(max_bytes_per_log) =
config.get_opt::<ByteCount>("remotefilelog", "cachelimit")?
{
let log_count: u64 = open_options.max_log_count.unwrap_or(1).max(1).into();
open_options =
open_options.max_bytes_per_log((max_bytes_per_log.value() / log_count).max(1));
}
Ok(open_options)
}
pub fn get(&self, hgid: HgId) -> Result<Option<Entry>> {
let log = self.0.read();
let mut entries = log.lookup(0, &hgid)?;
let slice = match entries.next() {
None => return Ok(None),
Some(slice) => slice?,
};
let bytes = log.slice_to_bytes(slice);
drop(log);
Entry::deserialize(bytes).map(|(_hgid, entry)| Some(entry))
}
pub fn put(&self, hgid: HgId, entry: &Entry) -> Result<()> {
let serialized = entry.serialize(hgid)?;
self.0.write().append(&serialized)
}
pub fn flush(&self) -> Result<()> {
self.0.write().flush()
}
#[cfg(test)]
pub(crate) fn hgids(&self) -> Result<Vec<HgId>> {
let log = self.0.read();
log.iter()
.map(|slice| {
let bytes = log.slice_to_bytes(slice?);
Entry::deserialize(bytes).map(|(hgid, _entry)| hgid)
})
.collect()
}
}
#[cfg(test)]
mod tests {
use std::fs::remove_file;
use std::str::FromStr;
use std::sync::Arc;
use tempfile::TempDir; | use types::testutil::*;
use super::*;
use crate::scmstore::FileAttributes;
use crate::scmstore::FileStore;
use crate::testutil::*;
use crate::ExtStoredPolicy;
use crate::HgIdMutableDeltaStore;
use crate::IndexedLogHgIdDataStore;
fn single_byte_sha1(fst: u8) -> Sha1 {
let mut x: [u8; Sha1::len()] = Default::default();
x[0] = fst;
Sha1::from(x)
}
#[test]
fn test_empty() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
store.flush()?;
Ok(())
}
#[test]
fn test_add_get() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let found = store.get(k.hgid)?;
assert_eq!(Some(entry), found);
Ok(())
}
#[test]
fn test_lookup_failure() -> Result<()> {
let tempdir = TempDir::new().unwrap();
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let mut entry = Entry::default();
entry.total_size = 1;
entry.content_sha1 = single_byte_sha1(1);
let k = key("a", "1");
store.put(k.hgid, &entry)?;
store.flush()?;
let k2 = key("b", "2");
let found = store.get(k2.hgid)?;
assert_eq!(None, found);
Ok(())
}
#[test]
fn test_corrupted() -> Result<()> {
let tempdir = TempDir::new()?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "2");
let mut entry = Entry::default();
entry.total_size = 2;
entry.content_sha1 = single_byte_sha1(2);
store.put(k.hgid, &entry)?;
store.flush()?;
drop(store);
// Corrupt the log by removing the "log" file.
let mut rotate_log_path = tempdir.path().to_path_buf();
rotate_log_path.push("0");
rotate_log_path.push("log");
remove_file(rotate_log_path)?;
let store = AuxStore::new(&tempdir, &ConfigSet::new(), StoreType::Shared)?;
let k = key("a", "3");
let mut entry = Entry::default();
entry.total_size = 3;
entry.content_sha1 = single_byte_sha1(3);
store.put(k.hgid, &entry)?;
store.flush()?;
// There should be only one key in the store.
assert_eq!(store.hgids().into_iter().count(), 1 | random_line_split | |
index.tsx | /// <reference path="../node_modules/protobufjs/stub-node.d.ts" />
/**
* UI/NEXT TODO LIST
*
* ! = Potentially difficult to implement
*
* - All Pages / Shared Components
* - "Last Updated"
* - Dropdowns
* - Fix 1px offset bug
* - Tables
* - CSS Match to design
* - Management of column widths
* - Cluster Page
* - Alert notifications
* - Mismatched/Out-of-date Version
* - Help us
* - Right-side Summary Section
* - Link to Nodes page
* - Events?
* - Graphs
* - Tooltip when hover over title
* - Code block syntax highlighting
* - Choose keywords correctly
* - Fix bug on direct page load
* - Databases Page
* - Last Updated Column
* - Retrieve/Filter events
* - Single database page
* - Table component row limit
* - Route to single database
* - Schema Change
* - Retrieve information from backend
* - Display in table list column
* - Display alert on table details page
* - Table details page
* - Schema Change notification
* - Fill out summary stats
* - Back Button
* - Column widths for grants table
* - Nodes page
* - Table Style
* - Add Summary Section
* - Remove Link from Navigation Bar
* - Helpus Page
* - New Navigation Bar Icon
* - Header links
* - New form field Appearance
*
* NICE TO HAVE:
* - Create a "NodeStatusProvider" similar to "MetricsDataProvider", allowing
* different components to access nodes data.
*
* - Commonize code between different graph types (LineGraph and
* StackedAreaGraph). This can likely be done by converting them into stateless
* functions, that return an underlying "Common" graph component. The props of
* the Common graph component would include the part of `initGraph` and
* `drawGraph` that are different for these two chart types.
*
*/
import "nvd3/build/nv.d3.min.css";
import "react-select/dist/react-select.css";
import "../styl/app.styl";
import "./js/sim/style.css";
import * as protobuf from "protobufjs/minimal";
import Long from "long";
protobuf.util.Long = Long as any;
protobuf.configure();
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Router, Route, IndexRoute, IndexRedirect } from "react-router";
import {
tableNameAttr, databaseNameAttr, nodeIDAttr, dashboardNameAttr,
} from "./util/constants";
import { store, history } from "./redux/state";
import Layout from "./containers/layout";
import { DatabaseTablesList, DatabaseGrantsList } from "./containers/databases/databases";
import TableDetails from "./containers/databases/tableDetails";
import Nodes from "./containers/nodes";
import NodesOverview from "./containers/nodesOverview";
import NodeOverview from "./containers/nodeOverview";
import NodeGraphs from "./containers/nodeGraphs";
import NodeLogs from "./containers/nodeLogs";
import { EventPage } from "./containers/events";
import Raft from "./containers/raft";
import RaftRanges from "./containers/raftRanges";
import ClusterViz from "./containers/clusterViz";
import { alertDataSync } from "./redux/alerts";
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={Layout}>
<IndexRedirect to="cluster" />
<Route path="cluster" component={ Nodes }>
<IndexRedirect to="all/overview" />
<Route path={`all/:${dashboardNameAttr}`} component={NodeGraphs} />
<Route path={ `node/:${nodeIDAttr}/:${dashboardNameAttr}` } component={NodeGraphs} />
</Route>
<Route path="cluster">
<Route path="nodes">
<IndexRoute component={NodesOverview} />
<Route path={`:${nodeIDAttr}`}>
<IndexRoute component={NodeOverview} />
<Route path="logs" component={ NodeLogs } />
</Route>
</Route>
<Route path="events" component={ EventPage } />
</Route>
<Route path="databases">
<IndexRedirect to="tables" /> | <Route path="raft" component={ Raft }>
<IndexRedirect to="ranges" />
<Route path="ranges" component={ RaftRanges } />
</Route>
<Route path="clusterviz" component={ ClusterViz } />
</Route>
</Router>
</Provider>,
document.getElementById("react-layout"),
);
store.subscribe(alertDataSync(store)); | <Route path="tables" component={ DatabaseTablesList } />
<Route path="grants" component={ DatabaseGrantsList } />
<Route path={ `database/:${databaseNameAttr}/table/:${tableNameAttr}` } component={ TableDetails } />
</Route> | random_line_split |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law 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 subprocess
import jsonschema
import mock
from rally import consts
from rally.plugins.common.hook import sys_call
from rally.task import hook
from tests.unit import fakes
from tests.unit import test
class SysCallHookTestCase(test.TestCase):
def test_validate(self):
|
def test_validate_error(self):
conf = {
"name": "sys_call",
"description": "list folder",
"args": {
"cmd": 50,
},
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
self.assertRaises(
jsonschema.ValidationError, hook.Hook.validate, conf)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 0
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.SUCCESS,
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run_error(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 1
popen_instance.stdout.read.return_value = b"No such file or directory"
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.FAILED,
"error": [
"n/a",
"Subprocess returned 1",
"No such file or directory",
]
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
| hook.Hook.validate(
{
"name": "sys_call",
"description": "list folder",
"args": "ls",
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
) | identifier_body |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law 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 subprocess
import jsonschema
import mock
from rally import consts
from rally.plugins.common.hook import sys_call
from rally.task import hook
from tests.unit import fakes
from tests.unit import test
class | (test.TestCase):
def test_validate(self):
hook.Hook.validate(
{
"name": "sys_call",
"description": "list folder",
"args": "ls",
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
)
def test_validate_error(self):
conf = {
"name": "sys_call",
"description": "list folder",
"args": {
"cmd": 50,
},
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
self.assertRaises(
jsonschema.ValidationError, hook.Hook.validate, conf)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 0
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.SUCCESS,
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run_error(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 1
popen_instance.stdout.read.return_value = b"No such file or directory"
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.FAILED,
"error": [
"n/a",
"Subprocess returned 1",
"No such file or directory",
]
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
| SysCallHookTestCase | identifier_name |
test_sys_call.py | # Copyright 2016: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law 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 subprocess
import jsonschema
import mock
from rally import consts
from rally.plugins.common.hook import sys_call
from rally.task import hook
from tests.unit import fakes
from tests.unit import test
class SysCallHookTestCase(test.TestCase):
def test_validate(self):
hook.Hook.validate(
{
"name": "sys_call",
"description": "list folder",
"args": "ls",
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
)
def test_validate_error(self):
conf = {
"name": "sys_call", | "cmd": 50,
},
"trigger": {
"name": "event",
"args": {
"unit": "iteration",
"at": [10]
}
}
}
self.assertRaises(
jsonschema.ValidationError, hook.Hook.validate, conf)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 0
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.SUCCESS,
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
@mock.patch("rally.common.utils.Timer", side_effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run_error(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 1
popen_instance.stdout.read.return_value = b"No such file or directory"
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
{"iteration": 1}, "dummy_action")
sys_call_hook.run_sync()
sys_call_hook.validate_result_schema()
self.assertEqual(
{
"hook": "sys_call",
"description": "dummy_action",
"triggered_by": {"iteration": 1},
"started_at": fakes.FakeTimer().timestamp(),
"finished_at": fakes.FakeTimer().finish_timestamp(),
"status": consts.HookStatus.FAILED,
"error": [
"n/a",
"Subprocess returned 1",
"No such file or directory",
]
}, sys_call_hook.result())
mock_popen.assert_called_once_with(
["/bin/bash", "-c", "ls"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) | "description": "list folder",
"args": { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_syntax)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![plugin(plugins)]
#![deny(unsafe_code)]
#![plugin(serde_macros)]
extern crate app_units;
extern crate azure;
extern crate canvas;
extern crate canvas_traits;
extern crate clipboard;
#[cfg(target_os = "macos")]
extern crate core_graphics;
#[cfg(target_os = "macos")]
extern crate core_text;
extern crate devtools_traits;
extern crate euclid;
#[cfg(not(target_os = "windows"))]
extern crate gaol;
extern crate gfx;
extern crate gfx_traits;
extern crate gleam;
extern crate image;
extern crate ipc_channel;
extern crate layers;
extern crate layout_traits;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate script_traits;
extern crate serde;
extern crate style_traits;
extern crate time;
extern crate url;
#[macro_use]
extern crate util;
extern crate webrender;
extern crate webrender_traits;
pub use compositor_thread::{CompositorEventListener, CompositorProxy, CompositorThread};
pub use constellation::Constellation;
use euclid::size::{Size2D};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcSender};
use msg::constellation_msg::{FrameId, Key, KeyState, KeyModifiers, LoadData};
use msg::constellation_msg::{NavigationDirection, PipelineId, SubpageId};
use msg::constellation_msg::{WebDriverCommandMsg, WindowSizeData};
use std::collections::HashMap;
use url::Url;
mod compositor;
mod compositor_layer;
pub mod compositor_thread;
pub mod constellation;
mod delayed_composition;
pub mod pipeline;
#[cfg(not(target_os = "windows"))]
pub mod sandboxing;
mod surface_map;
mod timer_scheduler;
mod touch;
pub mod windowing;
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum | {
Script,
Layout,
}
/// Messages from the compositor to the constellation.
#[derive(Deserialize, Serialize)]
pub enum CompositorMsg {
Exit,
FrameSize(PipelineId, Size2D<f32>),
/// Request that the constellation send the FrameId corresponding to the document
/// with the provided pipeline id
GetFrame(PipelineId, IpcSender<Option<FrameId>>),
/// Request that the constellation send the current pipeline id for the provided frame
/// id, or for the root frame if this is None, over a provided channel
GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>),
/// Requests that the constellation inform the compositor of the title of the pipeline
/// immediately.
GetPipelineTitle(PipelineId),
InitLoadUrl(Url),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
KeyEvent(Key, KeyState, KeyModifiers),
LoadUrl(PipelineId, LoadData),
Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection),
ResizedWindow(WindowSizeData),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
}
| AnimationTickType | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_syntax)]
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(mpsc_select)]
#![feature(plugin)]
#![plugin(plugins)]
#![deny(unsafe_code)]
#![plugin(serde_macros)]
extern crate app_units;
extern crate azure;
extern crate canvas;
extern crate canvas_traits;
extern crate clipboard;
#[cfg(target_os = "macos")]
extern crate core_graphics;
#[cfg(target_os = "macos")]
extern crate core_text;
extern crate devtools_traits;
extern crate euclid;
#[cfg(not(target_os = "windows"))]
extern crate gaol;
extern crate gfx;
extern crate gfx_traits;
extern crate gleam;
extern crate image; | extern crate layout_traits;
#[macro_use]
extern crate log;
extern crate msg;
extern crate net_traits;
extern crate num;
extern crate offscreen_gl_context;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate script_traits;
extern crate serde;
extern crate style_traits;
extern crate time;
extern crate url;
#[macro_use]
extern crate util;
extern crate webrender;
extern crate webrender_traits;
pub use compositor_thread::{CompositorEventListener, CompositorProxy, CompositorThread};
pub use constellation::Constellation;
use euclid::size::{Size2D};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcSender};
use msg::constellation_msg::{FrameId, Key, KeyState, KeyModifiers, LoadData};
use msg::constellation_msg::{NavigationDirection, PipelineId, SubpageId};
use msg::constellation_msg::{WebDriverCommandMsg, WindowSizeData};
use std::collections::HashMap;
use url::Url;
mod compositor;
mod compositor_layer;
pub mod compositor_thread;
pub mod constellation;
mod delayed_composition;
pub mod pipeline;
#[cfg(not(target_os = "windows"))]
pub mod sandboxing;
mod surface_map;
mod timer_scheduler;
mod touch;
pub mod windowing;
/// Specifies whether the script or layout thread needs to be ticked for animation.
#[derive(Deserialize, Serialize)]
pub enum AnimationTickType {
Script,
Layout,
}
/// Messages from the compositor to the constellation.
#[derive(Deserialize, Serialize)]
pub enum CompositorMsg {
Exit,
FrameSize(PipelineId, Size2D<f32>),
/// Request that the constellation send the FrameId corresponding to the document
/// with the provided pipeline id
GetFrame(PipelineId, IpcSender<Option<FrameId>>),
/// Request that the constellation send the current pipeline id for the provided frame
/// id, or for the root frame if this is None, over a provided channel
GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>),
/// Requests that the constellation inform the compositor of the title of the pipeline
/// immediately.
GetPipelineTitle(PipelineId),
InitLoadUrl(Url),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
KeyEvent(Key, KeyState, KeyModifiers),
LoadUrl(PipelineId, LoadData),
Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection),
ResizedWindow(WindowSizeData),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId, AnimationTickType),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
} | extern crate ipc_channel;
extern crate layers; | random_line_split |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveActionService',
'otusjs.player.core.phase.PostSaveActionService'
];
function Service(ActionPipeService, PreSaveActionService, ExecutionSaveActionService, PostSaveActionService) |
})();
| {
var self = this;
/* Public methods */
self.PreSaveActionService = PreSaveActionService;
self.ExecutionSaveActionService = ExecutionSaveActionService;
self.PostSaveActionService = PostSaveActionService;
self.execute = execute;
function execute() {
var phaseData = PreSaveActionService.execute(ActionPipeService.flowData);
phaseData = ExecutionSaveActionService.execute(phaseData);
phaseData = PostSaveActionService.execute(phaseData);
}
} | identifier_body |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveActionService',
'otusjs.player.core.phase.PostSaveActionService' |
/* Public methods */
self.PreSaveActionService = PreSaveActionService;
self.ExecutionSaveActionService = ExecutionSaveActionService;
self.PostSaveActionService = PostSaveActionService;
self.execute = execute;
function execute() {
var phaseData = PreSaveActionService.execute(ActionPipeService.flowData);
phaseData = ExecutionSaveActionService.execute(phaseData);
phaseData = PostSaveActionService.execute(phaseData);
}
}
})(); | ];
function Service(ActionPipeService, PreSaveActionService, ExecutionSaveActionService, PostSaveActionService) {
var self = this; | random_line_split |
save-action-service.js | (function() {
'use strict';
angular
.module('otusjs.player.core.phase')
.service('otusjs.player.core.phase.SaveActionService', Service);
Service.$inject = [
'otusjs.player.core.phase.ActionPipeService',
'otusjs.player.core.phase.PreSaveActionService',
'otusjs.player.core.phase.ExecutionSaveActionService',
'otusjs.player.core.phase.PostSaveActionService'
];
function Service(ActionPipeService, PreSaveActionService, ExecutionSaveActionService, PostSaveActionService) {
var self = this;
/* Public methods */
self.PreSaveActionService = PreSaveActionService;
self.ExecutionSaveActionService = ExecutionSaveActionService;
self.PostSaveActionService = PostSaveActionService;
self.execute = execute;
function | () {
var phaseData = PreSaveActionService.execute(ActionPipeService.flowData);
phaseData = ExecutionSaveActionService.execute(phaseData);
phaseData = PostSaveActionService.execute(phaseData);
}
}
})();
| execute | identifier_name |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix...
let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
}
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
}
}
if !in_pp {
preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
}
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn | (program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
}
| display_usage | identifier_name |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) | let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
}
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
}
}
if !in_pp {
preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
}
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn display_usage(program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
}
| {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix... | identifier_body |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix...
let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
}
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
} | preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
}
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn display_usage(program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
} | }
if !in_pp { | random_line_split |
main.rs | /*
Full Monkey.
Generic preprocessor tool.
Copyright 2016 Sam Saint-Pettersen.
Released under the MIT/X11 License.
*/
extern crate clioptions;
extern crate regex;
use clioptions::CliOptions;
use regex::Regex;
use std::io::{BufRead, BufReader, Write};
use std::fs::File;
use std::process::exit;
fn preprocess(input: &str, output: &str, conditions: &str, verbose: bool) {
let mut loc: Vec<String> = Vec::new();
let mut preprocessed: Vec<String> = Vec::new();
let mut cond = String::new();
let mut set_conds: Vec<String> = Vec::new();
let mut prefixed: Vec<String> = Vec::new();
let mut prefixes: Vec<String> = Vec::new();
let mut in_pp = false;
let conditions = conditions.split(",");
for sc in conditions {
set_conds.push(sc.to_string());
}
let f = File::open(input).unwrap();
let file = BufReader::new(&f);
for l in file.lines() {
let l = l.unwrap();
// Process prefix...
let mut p = Regex::new("#prefix (.*) with (.*)").unwrap();
if p.is_match(&l) {
for cap in p.captures_iter(&l) {
prefixed.push(cap.at(1).unwrap().to_string());
prefixes.push(cap.at(2).unwrap().to_string());
}
continue;
}
// Process conditional (if/else/elseif)...
p = Regex::new("#[else]*[if]* (.*)").unwrap();
if p.is_match(&l) |
// Process end block...
p = Regex::new("#[fi|endif]").unwrap();
if p.is_match(&l) {
in_pp = false;
continue;
}
// Push relevant LoC to vector...
for sc in set_conds.clone() {
if in_pp && cond == sc {
preprocessed.push(l.to_string());
}
}
if !in_pp {
preprocessed.push(l.to_string());
continue;
}
}
// Do any alterations:
for line in preprocessed {
let mut fl = line;
for (i, p) in prefixed.iter().enumerate() {
let r = Regex::new(®ex::quote(&p)).unwrap();
let repl = format!("{}{}", &prefixes[i], &p);
fl = r.replace_all(&fl, &repl[..]);
}
loc.push(fl);
}
loc.push(String::new());
if verbose {
println!("Preprocessing {} --> {}", input, output);
}
let mut w = File::create(output).unwrap();
let _ = w.write_all(loc.join("\n").as_bytes());
}
fn display_version() {
println!("Full Monkey v. 0.1");
println!(r" __");
println!(r"w c(..)o (");
println!(r" \__(-) __)");
println!(r" /\ (");
println!(r" /(_)___)");
println!(r" w /|");
println!(r" | \");
println!(r" m m");
println!("\nMonkey appears courtesy of ejm97:");
println!("http://www.ascii-art.de/ascii/mno/monkey.txt");
exit(0);
}
fn display_error(program: &str, error: &str) {
println!("Error: {}.", error);
display_usage(&program, -1);
}
fn display_usage(program: &str, exit_code: i32) {
println!("\nFull Monkey.");
println!("Generic preprocessor tool.");
println!("\nCopyright 2016 Sam Saint-Pettersen.");
println!("Released under the MIT/X11 License.");
println!("\n{} -f|--file <input> [-c|--condition <condition(s)>] -o|--out <output>", program);
println!("[-l|--verbose][-h|--help | -v|--version]");
println!("\n-f|--file: File to run preprocessing on.");
println!("-c|--conditon: Comma delimited list of conditon(s) to apply.");
println!("-o|--out: File to output preprocessed LoC to.");
println!("-l|--verbose: Display message to console on process.");
println!("-h|--help: Display this help information and exit.");
println!("-v|--version: Display program version and exit.");
exit(exit_code);
}
fn main() {
let cli = CliOptions::new("fm");
let program = cli.get_program();
let mut input = String::new();
let mut output = String::new();
let mut conditions = String::new();
let mut verbose = false;
if cli.get_num() > 1 {
for (i, a) in cli.get_args().iter().enumerate() {
match a.trim() {
"-h" | "--help" => display_usage(&program, 0),
"-v" | "--version" => display_version(),
"-f" | "--file" => input = cli.next_argument(i),
"-c" | "--condition" => conditions = cli.next_argument(i),
"-o" | "--out" => output = cli.next_argument(i),
"-l" | "--verbose" => verbose = true,
_ => continue,
}
}
if input.is_empty() {
display_error(&program, "No input specified");
}
if output.is_empty() {
display_error(&program, "No output specified");
}
preprocess(&input, &output, &conditions, verbose);
}
else {
display_error(&program, "No options specified");
}
}
| {
for cap in p.captures_iter(&l) {
cond = cap.at(1).unwrap().to_string();
in_pp = true;
}
continue;
} | conditional_block |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, ServerName};
ruma_api! {
metadata: {
description: "Get mapped room ID and resident homeservers for a given room alias.",
name: "get_room_information",
method: GET,
stable_path: "/_matrix/federation/v1/query/directory",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// Room alias to query.
#[ruma_api(query)]
pub room_alias: &'a RoomAliasId,
}
response: {
/// Room ID mapped to queried alias.
pub room_id: Box<RoomId>,
/// An array of server names that are likely to hold the given room.
pub servers: Vec<Box<ServerName>>,
}
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given room alias ID.
pub fn new(room_alias: &'a RoomAliasId) -> Self {
Self { room_alias }
}
}
impl Response {
/// Creates a new `Response` with the given room IDs and servers.
pub fn new(room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self |
}
}
| {
Self { room_id, servers }
} | identifier_body |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, ServerName};
ruma_api! {
metadata: {
description: "Get mapped room ID and resident homeservers for a given room alias.",
name: "get_room_information",
method: GET,
stable_path: "/_matrix/federation/v1/query/directory",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// Room alias to query.
#[ruma_api(query)]
pub room_alias: &'a RoomAliasId,
}
response: {
/// Room ID mapped to queried alias.
pub room_id: Box<RoomId>,
/// An array of server names that are likely to hold the given room.
pub servers: Vec<Box<ServerName>>,
}
}
impl<'a> Request<'a> {
/// Creates a new `Request` with the given room alias ID.
pub fn new(room_alias: &'a RoomAliasId) -> Self {
Self { room_alias }
}
}
impl Response {
/// Creates a new `Response` with the given room IDs and servers.
pub fn | (room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self {
Self { room_id, servers }
}
}
}
| new | identifier_name |
get_room_information.rs | //! `GET /_matrix/federation/*/query/directory`
//!
//! Endpoint to query room information with a room alias.
pub mod v1 {
//! `/v1/` ([spec])
//!
//! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1querydirectory
use ruma_common::{api::ruma_api, RoomAliasId, RoomId, ServerName};
ruma_api! {
metadata: {
description: "Get mapped room ID and resident homeservers for a given room alias.",
name: "get_room_information",
method: GET,
stable_path: "/_matrix/federation/v1/query/directory",
rate_limited: false,
authentication: ServerSignatures,
added: 1.0,
}
request: {
/// Room alias to query.
#[ruma_api(query)]
pub room_alias: &'a RoomAliasId,
}
response: {
/// Room ID mapped to queried alias.
pub room_id: Box<RoomId>,
/// An array of server names that are likely to hold the given room. | impl<'a> Request<'a> {
/// Creates a new `Request` with the given room alias ID.
pub fn new(room_alias: &'a RoomAliasId) -> Self {
Self { room_alias }
}
}
impl Response {
/// Creates a new `Response` with the given room IDs and servers.
pub fn new(room_id: Box<RoomId>, servers: Vec<Box<ServerName>>) -> Self {
Self { room_id, servers }
}
}
} | pub servers: Vec<Box<ServerName>>,
}
}
| random_line_split |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from the current buffer.
r = 8-self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v<<bits) | ((self.buff>>(r-bits)) & ((1<<bits)-1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v<<r) | (self.buff & ((1<<r)-1))
bits -= r
x = self.fp.read(1)
if not x: raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = ''
if code == 256:
self.table = [ chr(c) for c in xrange(256) ] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = ''
self.nbits = 9
elif code == 257:
pass
elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def | (self):
while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __name__ == '__main__': sys.exit(main(sys.argv))
| run | identifier_name |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from the current buffer.
r = 8-self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v<<bits) | ((self.buff>>(r-bits)) & ((1<<bits)-1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v<<r) | (self.buff & ((1<<r)-1))
bits -= r
x = self.fp.read(1)
if not x: raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = ''
if code == 256:
self.table = [ chr(c) for c in xrange(256) ] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = ''
self.nbits = 9
elif code == 257:
pass
elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def run(self):
|
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __name__ == '__main__': sys.exit(main(sys.argv))
| while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return | identifier_body |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from the current buffer.
r = 8-self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v<<bits) | ((self.buff>>(r-bits)) & ((1<<bits)-1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v<<r) | (self.buff & ((1<<r)-1))
bits -= r
x = self.fp.read(1)
if not x: raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = ''
if code == 256:
self.table = [ chr(c) for c in xrange(256) ] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = ''
self.nbits = 9
elif code == 257:
pass | elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def run(self):
while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:]))
return
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __name__ == '__main__': sys.exit(main(sys.argv)) | random_line_split | |
lzw.py | #!/usr/bin/env python
import sys
stderr = sys.stderr
## LZWDecoder
##
class LZWDecoder(object):
debug = 0
def __init__(self, fp):
self.fp = fp
self.buff = 0
self.bpos = 8
self.nbits = 9
self.table = None
self.prevbuf = None
return
def readbits(self, bits):
v = 0
while 1:
# the number of remaining bits we can get from the current buffer.
r = 8-self.bpos
if bits <= r:
# |-----8-bits-----|
# |-bpos-|-bits-| |
# | |----r----|
v = (v<<bits) | ((self.buff>>(r-bits)) & ((1<<bits)-1))
self.bpos += bits
break
else:
# |-----8-bits-----|
# |-bpos-|---bits----...
# | |----r----|
v = (v<<r) | (self.buff & ((1<<r)-1))
bits -= r
x = self.fp.read(1)
if not x: raise EOFError
self.buff = ord(x)
self.bpos = 0
return v
def feed(self, code):
x = ''
if code == 256:
self.table = [ chr(c) for c in xrange(256) ] # 0-255
self.table.append(None) # 256
self.table.append(None) # 257
self.prevbuf = ''
self.nbits = 9
elif code == 257:
pass
elif not self.prevbuf:
x = self.prevbuf = self.table[code]
else:
if code < len(self.table):
x = self.table[code]
self.table.append(self.prevbuf+x[0])
else:
self.table.append(self.prevbuf+self.prevbuf[0])
x = self.table[code]
l = len(self.table)
if l == 511:
self.nbits = 10
elif l == 1023:
self.nbits = 11
elif l == 2047:
self.nbits = 12
self.prevbuf = x
return x
def run(self):
while 1:
try:
code = self.readbits(self.nbits)
except EOFError:
break
x = self.feed(code)
yield x
if self.debug:
|
return
def main(argv):
import StringIO
input = '\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01'
fp = StringIO.StringIO(input)
expected = '\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
LZWDecoder.debug = 1
output = ''.join(LZWDecoder(fp).run())
print (input, expected, output)
print output == expected
return 0
if __name__ == '__main__': sys.exit(main(sys.argv))
| print >>stderr, ('nbits=%d, code=%d, output=%r, table=%r' %
(self.nbits, code, x, self.table[258:])) | conditional_block |
code_from_book.py | return '\n'.join(result)
with open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base64
base64.b64encode('encodings are fun...')
# 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4='
base64.b64decode(_)
# 'encodings are fun...'
string = "hello\x00"
binary_string = ' '.join('{:08b}'.format(ord(char)) for char in string)
" ".join(binary_string[i:i+6] for i in range(0, len(binary_string), 6))
# '011010 000110 010101 101100 011011 000110 111100 000000'
bin_string = '011010 000110 010101 101100 011011 000110 111100 000000'
[int(b, 2) for b in bin_string.split()]
# [26, 6, 21, 44, 27, 6, 60, 0]
u'โ \u2020'.encode('utf8')
# '\xe2\x97\x91 \xe2\x80\xa0'
'\xe2\x97\x91 \xe2\x80\xa0'.decode('utf8')
# u'\u25d1 \u2020'
unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8')
# u'\u25d1 \u2020'
utf8_string = 'ร
รชรญรฒรผ'
utf8_string
# '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc'
unicode_string = utf8_string.decode('utf8')
unicode_string
# u'\xc5\xea\xed\xf2\xfc'
unicode_string.encode('mac roman')
# '\x81\x90\x92\x98\x9f'
'ร
รชรญรฒรผ'.decode('utf8').encode('ascii')
# Traceback (most recent call last):
# ย File "<stdin>", line 1, in <module>
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """ๆฝๆฅชๆ
ขๆซๆค โณๆกดโฅๆ
งๆฒๆฌโคๆด็ธ็ ๆ
จโด็ฉ็ ๆจ็ ็ฅๆฑตโดๆฏ็ ็กฅโดๆขๆนฉโงๆคๆฝฃๆคโค็ตๆนฉโงๆนก็ ๆฅฎ็ฎๆนฅๆคโคๆกฃ
็กๆกๆดโฒๆนฅๆฝฃๆฅคๆฎๆฅทๆกดๆ ๆตฏๆฑฐ็ฅๆฑฅโนๆนตๆฒๆ
ฌๆดโคๆนฏ็ฅๆฏๆดโฎ็ฆๆตฏๆ ๆ ๆฉๆฆๆฒ็ฎ็ ๆฅฒๆฅดๆฎ็ ็นๆดโนญโงโ ๆ
ๆซโฎ
็ฆๆตฏๆ โนฎๆฅทๆฅซๆฐๆฅคโนก็ฏโฅง"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"รขโฌลMojibakeรขโฌล can be fixed.")
# u'"Mojibake" can be fixed.'
bin(0b1010 & 0b1111110111)
# '0b10'
bin(0b1010 | 0b0110)
# '0b1110'
bin(0b10111 | 0b01000)
# '0b11111'
bin(0b100 ^ 0b110)
# '0b10'
bin(-0b1010 >> 0b10)
# '-0b11'
x = 0b1111
y = 0b1010
bin(int("{:b}{:b}".format(x, y), 2))
# '0b11111010'
bin(x << 4 | y)
# '0b11111010'
####################################################################
# 4. Cryptography
####################################################################
import random
import string
ย
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
ย
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
ย
# Generate a random 40-bit number
r.getrandbits(40)
# 595477188771L
# Choose a random item from a string or list
chars = string.printable
r.choice(chars)
# 'e'
ย # Randomize the order of a sequence
seq = ['a', 'b', 'c', 'd', 'e']
r.shuffle(seq)
print seq
# ['c','d', 'a', 'e', 'b']
"ALLIGATOR".encode('rot13')
# 'NYYVTNGBE'
"NYYVTNGBE".encode('rot13')
# 'ALLIGATOR'
plaintext = "A secret-ish message!"
"".join(chr((ord(c) + 20) % 256) for c in plaintext)
# 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
"".join(chr((ord(c) - 20) % 256) for c in ciphertext)
# 'A secret-ish message!'
plaintext = 0b110100001101001
one_time_pad = 0b110000011100001
bin(plaintext ^ one_time_pad)
# '0b100010001000'
decrypted = 0b100010001000 ^ one_time_pad
format(decrypted, 'x').decode('hex')
# 'hi'
import os
import binascii
# ASCII-encoded plaintext
plaintext = "this is a secret message"
plaintext_bits = int(binascii.hexlify(plaintext), 16)
print "plaintext (ascii):", plaintext
print "plaintext (hex):", plaintext_bits
# Generate the one-time pad
onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16)
print "one-time pad: (hex):", onetime_pad
# Encrypt plaintext using XOR operation with one-time pad
ciphertext_bits = plaintext_bits ^ onetime_pad
print "encrypted text (hex):", ciphertext_bits
# Decrypt using XOR operation with one-time pad
decrypted_text = ciphertext_bits ^ onetime_pad
decrypted_text = binascii.unhexlify(hex(decrypted_text)[2:-1])
print "decrypted text (ascii):", decrypted_text
import random
import binascii
p1 = "this is the part where you run away"
p2 = "from bad cryptography practices."
# pad plaintexts with spaces to ensure equal length
p1 = p1.ljust(len(p2))
p2 = p2.ljust(len(p1))
p1 = int(binascii.hexlify(p1), 16)
p2 = int(binascii.hexlify(p2), 16)
# get random one-time pad
otp = random.SystemRandom().getrandbits(p1.bit_length())
# encrypt
c1 = p1 ^ otp
c2 = p2 ^ otp # otp reuse...not good!
print "c1 | = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X}ย ย {:{}}ย ย {}".format(i, hexa, length * (digits + 1), text))
| conditional_block | |
code_from_book.py | th open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base64
base64.b64encode('encodings are fun...')
# 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4='
base64.b64decode(_)
# 'encodings are fun...'
string = "hello\x00"
binary_string = ' '.join('{:08b}'.format(ord(char)) for char in string)
" ".join(binary_string[i:i+6] for i in range(0, len(binary_string), 6))
# '011010 000110 010101 101100 011011 000110 111100 000000'
bin_string = '011010 000110 010101 101100 011011 000110 111100 000000'
[int(b, 2) for b in bin_string.split()]
# [26, 6, 21, 44, 27, 6, 60, 0]
u'โ \u2020'.encode('utf8')
# '\xe2\x97\x91 \xe2\x80\xa0'
'\xe2\x97\x91 \xe2\x80\xa0'.decode('utf8')
# u'\u25d1 \u2020'
unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8')
# u'\u25d1 \u2020'
utf8_string = 'ร
รชรญรฒรผ'
utf8_string
# '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc'
unicode_string = utf8_string.decode('utf8')
unicode_string
# u'\xc5\xea\xed\xf2\xfc'
unicode_string.encode('mac roman')
# '\x81\x90\x92\x98\x9f'
'ร
รชรญรฒรผ'.decode('utf8').encode('ascii')
# Traceback (most recent call last):
# ย File "<stdin>", line 1, in <module>
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """ๆฝๆฅชๆ
ขๆซๆค โณๆกดโฅๆ
งๆฒๆฌโคๆด็ธ็ ๆ
จโด็ฉ็ ๆจ็ ็ฅๆฑตโดๆฏ็ ็กฅโดๆขๆนฉโงๆคๆฝฃๆคโค็ตๆนฉโงๆนก็ ๆฅฎ็ฎๆนฅๆคโคๆกฃ
็กๆกๆดโฒๆนฅๆฝฃๆฅคๆฎๆฅทๆกดๆ ๆตฏๆฑฐ็ฅๆฑฅโนๆนตๆฒๆ
ฌๆดโคๆนฏ็ฅๆฏๆดโฎ็ฆๆตฏๆ ๆ ๆฉๆฆๆฒ็ฎ็ ๆฅฒๆฅดๆฎ็ ็นๆดโนญโงโ ๆ
ๆซโฎ
็ฆๆตฏๆ โนฎๆฅทๆฅซๆฐๆฅคโนก็ฏโฅง"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"รขโฌลMojibakeรขโฌล can be fixed.")
# u'"Mojibake" can be fixed.'
bin(0b1010 & 0b1111110111)
# '0b10'
bin(0b1010 | 0b0110)
# '0b1110'
bin(0b10111 | 0b01000)
# '0b11111'
bin(0b100 ^ 0b110)
# '0b10'
bin(-0b1010 >> 0b10)
# '-0b11'
x = 0b1111
y = 0b1010
bin(int("{:b}{:b}".format(x, y), 2))
# '0b11111010'
bin(x << 4 | y)
# '0b11111010'
####################################################################
# 4. Cryptography
####################################################################
import random
import string
ย
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
ย
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
ย
# Generate a random 40-bit number
r.getrandbits(40)
# 595477188771L
# Choose a random item from a string or list
chars = string.printable
r.choice(chars)
# 'e'
ย # Randomize the order of a sequence
seq = ['a', 'b', 'c', 'd', 'e']
r.shuffle(seq)
print seq
# ['c','d', 'a', 'e', 'b']
"ALLIGATOR".encode('rot13')
# 'NYYVTNGBE'
"NYYVTNGBE".encode('rot13')
# 'ALLIGATOR'
plaintext = "A secret-ish message!"
"".join(chr((ord(c) + 20) % 256) for c in plaintext)
# 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
"".join(chr((ord(c) - 20) % 256) for c in ciphertext)
# 'A secret-ish message!'
plaintext = 0b110100001101001
one_time_pad = 0b110000011100001
bin(plaintext ^ one_time_pad)
# '0b100010001000'
decrypted = 0b100010001000 ^ one_time_pad
format(decrypted, 'x').decode('hex')
# 'hi'
import os
import binascii
# ASCII-encoded plaintext
plaintext = "this is a secret message"
plaintext_bits = int(binascii.hexlify(plaintext), 16)
print "plaintext (ascii):", plaintext
print "plaintext (hex):", plaintext_bits
# Generate the one-time pad
onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16)
print "one-time pad: (hex):", onetime_pad
# Encrypt plaintext using XOR operation with one-time pad
ciphertext_bits = plaintext_bits ^ onetime_pad
print "encrypted text (hex):", ciphertext_bits
# Decrypt using XOR operation with one-time pad
decrypted_text = ciphertext_bits ^ onetime_pad
decrypted_text = binascii.unhexlify(hex(decrypted_text)[2:-1])
print "decrypted text (ascii):", decrypted_text
import random
import binascii
p1 = "this is the part where you run away"
p2 = "from bad cryptography practices."
# pad plaintexts with spaces to ensure equal length
p1 = p1.ljust(len(p2))
p2 = p2.ljust(len(p1))
p1 = int(binascii.hexlify(p1), 16)
p2 = int(binascii.hexlify(p2), 16)
# get random one-time pad
otp = random.SystemRandom().getrandbits | sult = []
digits = 4 if isinstance(string, unicode) else 2
for i in xrange(0, len(string), length):
s = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X}ย ย {:{}}ย ย {}".format(i, hexa, length * (digits + 1), text))
return '\n'.join(result)
wi | identifier_body | |
code_from_book.py | 1 \xe2\x80\xa0'.decode('utf8')
# u'\u25d1 \u2020'
unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8')
# u'\u25d1 \u2020'
utf8_string = 'ร
รชรญรฒรผ'
utf8_string
# '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc'
unicode_string = utf8_string.decode('utf8')
unicode_string
# u'\xc5\xea\xed\xf2\xfc'
unicode_string.encode('mac roman')
# '\x81\x90\x92\x98\x9f'
'ร
รชรญรฒรผ'.decode('utf8').encode('ascii')
# Traceback (most recent call last):
# ย File "<stdin>", line 1, in <module>
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """ๆฝๆฅชๆ
ขๆซๆค โณๆกดโฅๆ
งๆฒๆฌโคๆด็ธ็ ๆ
จโด็ฉ็ ๆจ็ ็ฅๆฑตโดๆฏ็ ็กฅโดๆขๆนฉโงๆคๆฝฃๆคโค็ตๆนฉโงๆนก็ ๆฅฎ็ฎๆนฅๆคโคๆกฃ
็กๆกๆดโฒๆนฅๆฝฃๆฅคๆฎๆฅทๆกดๆ ๆตฏๆฑฐ็ฅๆฑฅโนๆนตๆฒๆ
ฌๆดโคๆนฏ็ฅๆฏๆดโฎ็ฆๆตฏๆ ๆ ๆฉๆฆๆฒ็ฎ็ ๆฅฒๆฅดๆฎ็ ็นๆดโนญโงโ ๆ
ๆซโฎ
็ฆๆตฏๆ โนฎๆฅทๆฅซๆฐๆฅคโนก็ฏโฅง"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"รขโฌลMojibakeรขโฌล can be fixed.")
# u'"Mojibake" can be fixed.'
bin(0b1010 & 0b1111110111)
# '0b10'
bin(0b1010 | 0b0110)
# '0b1110'
bin(0b10111 | 0b01000)
# '0b11111'
bin(0b100 ^ 0b110)
# '0b10'
bin(-0b1010 >> 0b10)
# '-0b11'
x = 0b1111
y = 0b1010
bin(int("{:b}{:b}".format(x, y), 2))
# '0b11111010'
bin(x << 4 | y)
# '0b11111010'
####################################################################
# 4. Cryptography
####################################################################
import random
import string
ย
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
ย
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
ย
# Generate a random 40-bit number
r.getrandbits(40)
# 595477188771L
# Choose a random item from a string or list
chars = string.printable
r.choice(chars)
# 'e'
ย # Randomize the order of a sequence
seq = ['a', 'b', 'c', 'd', 'e']
r.shuffle(seq)
print seq
# ['c','d', 'a', 'e', 'b']
"ALLIGATOR".encode('rot13')
# 'NYYVTNGBE'
"NYYVTNGBE".encode('rot13')
# 'ALLIGATOR'
plaintext = "A secret-ish message!"
"".join(chr((ord(c) + 20) % 256) for c in plaintext)
# 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
"".join(chr((ord(c) - 20) % 256) for c in ciphertext)
# 'A secret-ish message!'
plaintext = 0b110100001101001
one_time_pad = 0b110000011100001
bin(plaintext ^ one_time_pad)
# '0b100010001000'
decrypted = 0b100010001000 ^ one_time_pad
format(decrypted, 'x').decode('hex')
# 'hi'
import os
import binascii
# ASCII-encoded plaintext
plaintext = "this is a secret message"
plaintext_bits = int(binascii.hexlify(plaintext), 16)
print "plaintext (ascii):", plaintext
print "plaintext (hex):", plaintext_bits
# Generate the one-time pad
onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16)
print "one-time pad: (hex):", onetime_pad
# Encrypt plaintext using XOR operation with one-time pad
ciphertext_bits = plaintext_bits ^ onetime_pad
print "encrypted text (hex):", ciphertext_bits
# Decrypt using XOR operation with one-time pad
decrypted_text = ciphertext_bits ^ onetime_pad
decrypted_text = binascii.unhexlify(hex(decrypted_text)[2:-1])
print "decrypted text (ascii):", decrypted_text
import random
import binascii
p1 = "this is the part where you run away"
p2 = "from bad cryptography practices."
# pad plaintexts with spaces to ensure equal length
p1 = p1.ljust(len(p2))
p2 = p2.ljust(len(p1))
p1 = int(binascii.hexlify(p1), 16)
p2 = int(binascii.hexlify(p2), 16)
# get random one-time pad
otp = random.SystemRandom().getrandbits(p1.bit_length())
# encrypt
c1 = p1 ^ otp
c2 = p2 ^ otp # otp reuse...not good!
print "c1 ^ c2 == p1 ^ p2 ?", c1 ^ c2 == p1 ^ p2
print "c1 ^ c2 =", hex(c1 ^ c2)
# the crib
crib = " the "
crib = int(binascii.hexlify(crib), 16)
xored = c1 ^ c2
print "crib =", hex(crib)
cbl = crib.bit_length()
xbl = xored.bit_length()
print
mask = (2**(cbl + 1) - 1)
fill = len(str(xbl / 8))
# crib dragging
for s in range(0, xbl - cbl + 8, 8):
xor = (xored ^ (crib << s)) & (mask << s)
out = binascii.unhexlify(hex(xor)[2:-1])
print "{:>{}} {}".format(s/8, fill, out)
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
ciphertext = f.encrypt("this is my plaintext")
decrypted = f.decrypt(ciphertext)
print decrypted
# this is my plaintext
import os
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
pt = "my plaintext"
backend = default_backend()
key = os.urandom(32)
iv = os.urandom(16)
| pt = padder.update(pt) + padder.finalize()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(pt) + encryptor.finalize()
decryptor = cipher.decryptor()
out = decryptor.update(ct) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
out = unpadder.update(out) + unpadder.finalize()
print out
import hashlib
hashlib.md5("hash me please").hexdigest()
# '760d92b6a6f974ae11904cd0a6fc2e90'
hashlib.sha1("hash me please").hexdigest()
# '1a58c9b3d138a45519518ee42e634600d1b52153'
import os | padder = padding.PKCS7(128).padder() | random_line_split |
code_from_book.py | tring):
return " ".join(format(ord(char), '08b') for char in string)
string = "my ascii string"
"".join(hex(ord(char))[2:] for char in string)
# '6d7920617363696920737472696e67'
hex_string = "6d7920617363696920737472696e67"
hex_string.decode("hex")
# 'my ascii string'
"".join(chr(int(hex_string[i:i+2], 16)) for i in range(0, len(hex_string), 2))
# 'my ascii string'
# adapted from https://code.activestate.com/recipes/142812-hex-dumper/
def hexdump(string, length=8):
result = []
digits = 4 if isinstance(string, unicode) else 2
for i in xrange(0, len(string), length):
s = string[i:i + length]
hexa = "".join("{:0{}X}".format(ord(x), digits) for x in s)
text = "".join(x if 0x20 <= ord(x) < 0x7F else '.' for x in s)
result.append("{:04X}ย ย {:{}}ย ย {}".format(i, hexa, length * (digits + 1), text))
return '\n'.join(result)
with open("/path/to/my_file.ext", "r") as f:
print hexdump(f.read())
import struct
num = 0x103e4
struct.pack("I", 0x103e4)
# '\xe4\x03\x01\x00'
string = '\xe4\x03\x01\x00'
struct.unpack("i", string)
# (66532,)
bytes = '\x01\xc2'
struct.pack("<h", struct.unpack(">h", bytes)[0])
# '\xc2\x01'
import base64
base64.b64encode('encodings are fun...')
# 'ZW5jb2RpbmdzIGFyZSBmdW4uLi4='
base64.b64decode(_)
# 'encodings are fun...'
string = "hello\x00"
binary_string = ' '.join('{:08b}'.format(ord(char)) for char in string)
" ".join(binary_string[i:i+6] for i in range(0, len(binary_string), 6))
# '011010 000110 010101 101100 011011 000110 111100 000000'
bin_string = '011010 000110 010101 101100 011011 000110 111100 000000'
[int(b, 2) for b in bin_string.split()]
# [26, 6, 21, 44, 27, 6, 60, 0]
u'โ \u2020'.encode('utf8')
# '\xe2\x97\x91 \xe2\x80\xa0'
'\xe2\x97\x91 \xe2\x80\xa0'.decode('utf8')
# u'\u25d1 \u2020'
unicode('\xe2\x97\x91 \xe2\x80\xa0', encoding='utf8')
# u'\u25d1 \u2020'
utf8_string = 'ร
รชรญรฒรผ'
utf8_string
# '\xc3\x85\xc3\xaa\xc3\xad\xc3\xb2\xc3\xbc'
unicode_string = utf8_string.decode('utf8')
unicode_string
# u'\xc5\xea\xed\xf2\xfc'
unicode_string.encode('mac roman')
# '\x81\x90\x92\x98\x9f'
'ร
รชรญรฒรผ'.decode('utf8').encode('ascii')
# Traceback (most recent call last):
# ย File "<stdin>", line 1, in <module>
# UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
file = """ๆฝๆฅชๆ
ขๆซๆค โณๆกดโฅๆ
งๆฒๆฌโคๆด็ธ็ ๆ
จโด็ฉ็ ๆจ็ ็ฅๆฑตโดๆฏ็ ็กฅโดๆขๆนฉโงๆคๆฝฃๆคโค็ตๆนฉโงๆนก็ ๆฅฎ็ฎๆนฅๆคโคๆกฃ
็กๆกๆดโฒๆนฅๆฝฃๆฅคๆฎๆฅทๆกดๆ ๆตฏๆฑฐ็ฅๆฑฅโนๆนตๆฒๆ
ฌๆดโคๆนฏ็ฅๆฏๆดโฎ็ฆๆตฏๆ ๆ ๆฉๆฆๆฒ็ฎ็ ๆฅฒๆฅดๆฎ็ ็นๆดโนญโงโ ๆ
ๆซโฎ
็ฆๆตฏๆ โนฎๆฅทๆฅซๆฐๆฅคโนก็ฏโฅง"""
print file.decode('utf8').encode('utf16')
# ??Mojibake is the garbled text that is the result of text being decoded using an
# unintended character encoding with completely unrelated ones, often from a
# different writing system.' (Taken from en.wikipedia.org)
import ftfy
ftfy.fix_text(u"รขโฌลMojibakeรขโฌล can be fixed.")
# u'"Mojibake" can be fixed.'
bin(0b1010 & 0b1111110111)
# '0b10'
bin(0b1010 | 0b0110)
# '0b1110'
bin(0b10111 | 0b01000)
# '0b11111'
bin(0b100 ^ 0b110)
# '0b10'
bin(-0b1010 >> 0b10)
# '-0b11'
x = 0b1111
y = 0b1010
bin(int("{:b}{:b}".format(x, y), 2))
# '0b11111010'
bin(x << 4 | y)
# '0b11111010'
####################################################################
# 4. Cryptography
####################################################################
import random
import string
ย
r = random.SystemRandom()
# Get a random integer between 0 and 20
r.randint(0, 20)
# 5
ย
# Get a random number between 0 and 1
r.random()
# 0.8282475835972263
ย
# Generate a random 40-bit number
r.getrandbits(40)
# 595477188771L
# Choose a random item from a string or list
chars = string.printable
r.choice(chars)
# 'e'
ย # Randomize the order of a sequence
seq = ['a', 'b', 'c', 'd', 'e']
r.shuffle(seq)
print seq
# ['c','d', 'a', 'e', 'b']
"ALLIGATOR".encode('rot13')
# 'NYYVTNGBE'
"NYYVTNGBE".encode('rot13')
# 'ALLIGATOR'
plaintext = "A secret-ish message!"
"".join(chr((ord(c) + 20) % 256) for c in plaintext)
# 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
ciphertext = 'U4\x87yw\x86y\x88A}\x87|4\x81y\x87\x87u{y5'
"".join(chr((ord(c) - 20) % 256) for c in ciphertext)
# 'A secret-ish message!'
plaintext = 0b110100001101001
one_time_pad = 0b110000011100001
bin(plaintext ^ one_time_pad)
# '0b100010001000'
decrypted = 0b100010001000 ^ one_time_pad
format(decrypted, 'x').decode('hex')
# 'hi'
import os
import binascii
# ASCII-encoded plaintext
plaintext = "this is a secret message"
plaintext_bits = int(binascii.hexlify(plaintext), 16)
print "plaintext (ascii):", plaintext
print "plaintext (hex):", plaintext_bits
# Generate the one-time pad
onetime_pad = int(binascii.hexlify(os.urandom(len(plaintext))), 16)
print "one-time pad: (hex):", onetime_pad
# Encrypt | _ascii_bytes(s | identifier_name | |
device_id.rs | #[cfg(feature = "rand")]
use super::generate_localpart;
/// A Matrix key ID.
///
/// Device identifiers in Matrix are completely opaque character sequences. This type is provided
/// simply for its semantic value.
///
/// # Example
///
/// ```
/// use ruma_common::{device_id, DeviceId};
///
/// let random_id = DeviceId::new();
/// assert_eq!(random_id.as_str().len(), 8);
///
/// let static_id = device_id!("01234567");
/// assert_eq!(static_id.as_str(), "01234567");
///
/// let ref_id: &DeviceId = "abcdefghi".into();
/// assert_eq!(ref_id.as_str(), "abcdefghi");
///
/// let owned_id: Box<DeviceId> = "ijklmnop".into();
/// assert_eq!(owned_id.as_str(), "ijklmnop");
/// ```
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DeviceId(str);
| opaque_identifier!(DeviceId);
impl DeviceId {
/// Generates a random `DeviceId`, suitable for assignment to a new device.
#[cfg(feature = "rand")]
pub fn new() -> Box<Self> {
Self::from_owned(generate_localpart(8))
}
}
#[cfg(all(test, feature = "rand"))]
mod tests {
use super::DeviceId;
#[test]
fn generate_device_id() {
assert_eq!(DeviceId::new().as_str().len(), 8);
}
#[test]
fn create_device_id_from_str() {
let ref_id: &DeviceId = "abcdefgh".into();
assert_eq!(ref_id.as_str(), "abcdefgh");
}
#[test]
fn create_boxed_device_id_from_str() {
let box_id: Box<DeviceId> = "12345678".into();
assert_eq!(box_id.as_str(), "12345678");
}
#[test]
fn create_device_id_from_box() {
let box_str: Box<str> = "ijklmnop".into();
let device_id: Box<DeviceId> = DeviceId::from_owned(box_str);
assert_eq!(device_id.as_str(), "ijklmnop");
}
} | random_line_split | |
device_id.rs | #[cfg(feature = "rand")]
use super::generate_localpart;
/// A Matrix key ID.
///
/// Device identifiers in Matrix are completely opaque character sequences. This type is provided
/// simply for its semantic value.
///
/// # Example
///
/// ```
/// use ruma_common::{device_id, DeviceId};
///
/// let random_id = DeviceId::new();
/// assert_eq!(random_id.as_str().len(), 8);
///
/// let static_id = device_id!("01234567");
/// assert_eq!(static_id.as_str(), "01234567");
///
/// let ref_id: &DeviceId = "abcdefghi".into();
/// assert_eq!(ref_id.as_str(), "abcdefghi");
///
/// let owned_id: Box<DeviceId> = "ijklmnop".into();
/// assert_eq!(owned_id.as_str(), "ijklmnop");
/// ```
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DeviceId(str);
opaque_identifier!(DeviceId);
impl DeviceId {
/// Generates a random `DeviceId`, suitable for assignment to a new device.
#[cfg(feature = "rand")]
pub fn | () -> Box<Self> {
Self::from_owned(generate_localpart(8))
}
}
#[cfg(all(test, feature = "rand"))]
mod tests {
use super::DeviceId;
#[test]
fn generate_device_id() {
assert_eq!(DeviceId::new().as_str().len(), 8);
}
#[test]
fn create_device_id_from_str() {
let ref_id: &DeviceId = "abcdefgh".into();
assert_eq!(ref_id.as_str(), "abcdefgh");
}
#[test]
fn create_boxed_device_id_from_str() {
let box_id: Box<DeviceId> = "12345678".into();
assert_eq!(box_id.as_str(), "12345678");
}
#[test]
fn create_device_id_from_box() {
let box_str: Box<str> = "ijklmnop".into();
let device_id: Box<DeviceId> = DeviceId::from_owned(box_str);
assert_eq!(device_id.as_str(), "ijklmnop");
}
}
| new | identifier_name |
globals.ts | import * as path from 'path';
export const UPDATE_INTERVALL = 2 * 60 * 60 * 1000;
export const GITHUB_RELEASES_URL = "https://api.github.com/repos/kumpelblase2/proxtop/releases";
export const UPDATER_FEED_URL = "https://proxtop.eternalwings.de/update/";
export const APP_NAME = "proxtop";
export const PROXER_BASE_URL = "https://proxer.me";
export const PROXER_API_BASE_URL = "https://proxer.me/api/v1";
export const INDEX_LOCATION = __dirname + "/index.html";
export const LOGO_RELATIVE_PATH = "static/assets/proxtop_logo_256.png";
export const LOGO_LOCATION = path.join(__dirname, "../", LOGO_RELATIVE_PATH);
let appDir: string;
try {
appDir = path.join(require("electron").app.getPath("appData"), APP_NAME);
} catch (e) {
appDir = path.join(__dirname, '..', '..', APP_NAME);
}
export const APP_DIR = appDir;
export const PROXER_PATHS = {
ROOT: '/',
LOGIN: '/component/user/?task=user.login',
API_LOGIN: '/login?format=json&action=login',
WATCHLIST: '/ucp?s=reminder',
OWN_PROFILE: '/user',
NEWS: '/news',
NEWS_API: '/notifications?format=json&s=news&p=1',
CONVERSATIONS_API: '/messages/?format=json&json=conferences',
CONVERSATION_PAGE: '/messages/?id=',
CONVERSATION_FAVORITES: '/messages/favourite',
CONVERSATION_MARK_FAVORITE: '/messages/?format=json&json=favour&id=',
CONVERSATION_UNMARK_FAVORITE: '/messages/?format=json&json=unfavour&id=',
CONVERSATION_MARK_BLOCKED: '/messages/?format=json&json=block&id=',
CONVERSATION_UNMARK_BLOCKED: '/messages/?format=json&json=unblock&id=',
CONVERSATION_REPORT: '/messages/?s=report&format=raw&id=',
CONVERSATION_NEW_CONFERENCE: "/messages/?format=json&json=newConference",
CONVERSATION_NEW: "/messages/?format=json&json=new",
MESSAGE_API: '/messages/?format=json&json=messages&id=',
MESSAGE_NEW_API: '/messages/?format=json&json=newmessages&id=',
MESSAGE_WRITE_API: '/messages/?format=json&json=answer&id=',
MESSAGE_NOTIFICATIONS: '/messages?format=raw&s=notification',
WATCH_ANIME: '/watch/%d/%d/%s',
VIEW_MANGA: '/chapter/%d/%d/%s',
LOGOUT: '/component/users/?task=user.logout',
DELETE_WATCHLIST: '/ucp?format=json&type=deleteReminder&id='
};
export const API_PATHS = {
USER: {
LOGIN: "/user/login",
LOGOUT: "/user/logout",
PROFILE: "/user/userinfo"
},
WATCHLIST: {
GET: "/ucp/reminder",
REMOVE: "/ucp/deletereminder",
SET: "/ucp/setreminder",
SET_EPISODE: "/ucp/setcommentstate"
},
ANIME: {
UPDATE_STATUS: "/info/setuserinfo"
},
QUERY: {
USERS: "/user/list",
SEARCH: "/list/entrysearch",
},
MESSAGES: {
CONSTANTS: "/messenger/constants",
CONFERENCES: "/messenger/conferences",
CONFERENCE_INFO: "/messenger/conferenceinfo",
MESSAGES: "/messenger/messages",
WRITE_MESSAGE: "/messenger/setmessage",
NEW_CONVERSATION: "/messenger/newconference",
NEW_CONFERENCE: "/messenger/newconferencegroup",
REPORT: "/messenger/report",
MARK_READ: "/messenger/setread",
MARK_UNREAD: "/messenger/setunread",
BLOCK: "/messenger/setblock",
UNBLOCK: "/messenger/setunblock",
FAVORITE: "/messenger/setfavour",
UNFAVORITE: "/messenger/setunfavour"
},
NOTIFICATIONS: {
NEWS: "/notifications/news",
AMOUNT: "/notifications/count",
CLEAR: "/notifications/delete"
},
UCP: {
ANIME_MANGA_LIST: "/ucp/list",
SET_COMMENT_STATE: "/ucp/setcommentstate" | }
};
export const Errors = {
CONNECTION: {
NO_NETWORK: 'ERROR.CONNECTION_NO_NETWORK',
UNABLE_TO_RESOLVE: 'ERROR.CONNECTION_NO_RESOLVE',
TIMEOUT: 'ERROR.CONNECTION_TIMEOUT',
NOT_FOUND: 'ERROR.CONNECTION_NOT_FOUND',
NO_CACHE: 'ERROR.CONNECTION_NO_CACHE_AVAILABLE',
NETWORK_RECONNECT: 'ERROR.CONNECTION_RECONNECT'
},
PROXER: {
OFFLINE: 'ERROR.PROXER_OFFLINE',
INVALID_CREDENTIALS: 'ERROR.PROXER_INVALID_CREDENTIALS',
NO_DETAILS_PROVIDED: 'ERROR.PROXER_NO_DETAILS',
MYSQL_DOWN: 'ERROR.PROXER_MYSQL_ERROR',
CLOUDFLARE: 'ERROR.PROXER_CLOUDFLARE_PROTECTION',
API_LIMIT_REACHED: 'ERROR.PROXER_API_LIMIT'
},
STREAMS: {
CANNOT_PARSE: 'ERROR.STREAM_NO_PARSER'
},
OTHER: {
UNKNOWN: 'ERROR.UNKNOWN_ERROR',
CACHE_CLEAR: 'ERROR.CACHE_CLEAR'
},
SEVERITY: {
SEVERE: 'ERROR_SEVERITY.severe',
WARNING: 'ERROR_SEVERITY.warn',
INFO: 'ERROR_SEVERITY.info'
}
}; | random_line_split | |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 faultes
for(var i=1;i<6;i++)
{
list.push( new Fault(i,4,101,"ื ืืกืื",false,new Date(2018,2,14),new Date(2018,2,14),"ืจืื","ืืืืงื"));
}
for(var i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"ืืืฆืขืืช",true,new Date(2018,2,20),new Date(2018,2,20),"ืื ื","ืืืืงื"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
private _system:string,
private _state:boolean, //ืื ืืชืงืื ืืฉืืืชื ืื ืืืจืืื ืืฉืจืืืืช TRUE=ืืฉืืืช FALSE=ืฉืจืืืืช
private _startTime:Date,
private _endTime:Date,
private _contact:string,
private _remarks:string){}
get id(){return this._id;}
get base(){return this._base;}
get site(){return this._site;}
get system(){return this._system;}
get state(){return this._state;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
| this._remarks;}
}
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get sites(){return this._sites;}
}
| get remarks(){return | identifier_body |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 faultes
for(var i=1;i<6;i++)
{
list.push( new Fault(i,4,101,"ื ืืกืื",false,new Date(2018,2,14),new Date(2018,2,14),"ืจืื","ืืืืงื"));
}
for(var i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"ืืืฆืขืืช",true,new Date(2018,2,20),new Date(2018,2,20),"ืื ื","ืืืืงื"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
private _system:string,
private _state:boolean, //ืื ืืชืงืื ืืฉืืืชื ืื ืืืจืืื ืืฉืจืืืืช TRUE=ืืฉืืืช FALSE=ืฉืจืืืืช
private _startTime:Date,
private _endTime:Date,
private _contact:string,
private _remarks:string){}
get id(){return this._id;}
get base(){return this._base;}
get site(){return this._site;}
get system(){return this._system;}
get state(){return this._state;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
get remarks(){return this._remarks;}
}
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get | tes(){return this._sites;}
}
| si | identifier_name |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 faultes
for(var i=1;i<6;i++)
{
list.push( new Fault(i,4,101,"ื ืืกืื",false,new Date(2018,2,14),new Date(2018,2,14),"ืจืื","ืืืืงื"));
}
for(var i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"ืืืฆืขืืช",true,new Date(2018,2,20),new Date(2018,2,20),"ืื ื","ืืืืงื"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
private _system:string,
private _state:boolean, //ืื ืืชืงืื ืืฉืืืชื ืื ืืืจืืื ืืฉืจืืืืช TRUE=ืืฉืืืช FALSE=ืฉืจืืืืช
private _startTime:Date,
private _endTime:Date,
private _contact:string,
private _remarks:string){}
get id(){return this._id;}
get base(){return this._base;}
get site(){return this._site;}
get system(){return this._system;}
get state(){return this._state;} |
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get sites(){return this._sites;}
} | get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
get remarks(){return this._remarks;}
} | random_line_split |
fault.service.ts | import { TimeAndDateService,Date } from './../time_and_date/time-and-date.service';
import { Injectable } from '@angular/core';
@Injectable()
export class FaultService { //this service used to get, update and delete faults
constructor() { }
getFaults(){
let list:Fault[]=[]; //for testing generate static 10 faultes
for(var i=1;i<6;i++)
| i=6;i<11;i++)
{
list.push( new Fault(i,6,69,"ืืืฆืขืืช",true,new Date(2018,2,20),new Date(2018,2,20),"ืื ื","ืืืืงื"));
}
return list;
}
}
export class Fault{
//this class describe how fault neet to seems
constructor(
private _id:number,
private _base:number,
private _site:number,
private _system:string,
private _state:boolean, //ืื ืืชืงืื ืืฉืืืชื ืื ืืืจืืื ืืฉืจืืืืช TRUE=ืืฉืืืช FALSE=ืฉืจืืืืช
private _startTime:Date,
private _endTime:Date,
private _contact:string,
private _remarks:string){}
get id(){return this._id;}
get base(){return this._base;}
get site(){return this._site;}
get system(){return this._system;}
get state(){return this._state;}
get startTime(){return this._startTime;}
get endTime(){return this._endTime;}
get contact(){return this._contact;}
get remarks(){return this._remarks;}
}
class Base { //class for base include the number of the base and its name and sites. for example base 6 Hatzerim
constructor(
private _id: number,
private _name: string,
private _sites: string[]) { }
get id(){return this._id;}
get name(){return this._name;}
get sites(){return this._sites;}
}
| {
list.push( new Fault(i,4,101,"ื ืืกืื",false,new Date(2018,2,14),new Date(2018,2,14),"ืจืื","ืืืืงื"));
}
for(var | conditional_block |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub toggle_mouse: Gesture,
pub toggle_help: Gesture,
}
impl Default for Bindings {
fn default() -> Self {
Bindings {
quit: Gesture::AnyOf(vec![
Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape),
]),
next_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::N),
]),
previous_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::P),
]),
toggle_mouse: Gesture::KeyTrigger(Scancode::Grave),
toggle_help: Gesture::KeyTrigger(Scancode::H),
}
}
}
#[derive(DependenciesFrom)]
pub struct Dependencies<'context> {
bindings: &'context Bindings,
window: &'context Window,
input: &'context mut Input,
text: &'context mut TextRenderer,
control_flow: &'context mut ControlFlow,
wad: &'context mut WadSystem,
}
pub struct Hud {
mouse_grabbed: bool,
current_help: HelpState,
prompt_text: TextId,
help_text: TextId,
}
impl<'context> InfallibleSystem<'context> for Hud {
type Dependencies = Dependencies<'context>;
fn debug_name() -> &'static str {
"hud"
}
fn create(deps: Dependencies) -> Self {
deps.input.set_mouse_enabled(true);
deps.input.set_cursor_grabbed(true);
let prompt_text = deps
.text
.insert(deps.window, PROMPT_TEXT, Pnt2f::origin(), HELP_PADDING);
let help_text = deps
.text
.insert(deps.window, HELP_TEXT, Pnt2f::origin(), HELP_PADDING);
deps.text[help_text].set_visible(false);
Hud {
prompt_text,
help_text,
mouse_grabbed: true,
current_help: HelpState::Prompt,
}
}
fn update(&mut self, deps: Dependencies) {
let Dependencies {
input,
text,
control_flow,
bindings,
..
} = deps;
if input.poll_gesture(&bindings.quit) {
control_flow.quit_requested = true
}
if input.poll_gesture(&bindings.toggle_mouse) {
self.mouse_grabbed = !self.mouse_grabbed;
input.set_mouse_enabled(self.mouse_grabbed);
input.set_cursor_grabbed(self.mouse_grabbed);
}
if input.poll_gesture(&bindings.toggle_help) {
self.current_help = match self.current_help {
HelpState::Prompt => {
text[self.prompt_text].set_visible(false);
text[self.help_text].set_visible(true);
HelpState::Shown
}
HelpState::Shown => {
text[self.help_text].set_visible(false);
HelpState::Hidden
}
HelpState::Hidden => {
text[self.help_text].set_visible(true);
HelpState::Shown
}
};
}
if input.poll_gesture(&bindings.next_level) {
let index = deps.wad.level_index();
deps.wad.change_level(index + 1);
} else if input.poll_gesture(&bindings.previous_level) {
let index = deps.wad.level_index();
if index > 0 |
}
}
fn teardown(&mut self, deps: Dependencies) {
deps.text.remove(self.help_text);
deps.text.remove(self.prompt_text);
}
}
enum HelpState {
Prompt,
Shown,
Hidden,
}
const HELP_PADDING: u32 = 6;
const PROMPT_TEXT: &str = "WASD and mouse, 'E' to push/use, LB to shoot or 'h' for help.";
const HELP_TEXT: &str = r"Use WASD to move and the mouse or arrow keys to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
E - push/interact/use
Left Click - shoot (only effect is to trigger gun-activated things)
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
Ctrl-N - to change to next level (though using the exit will also do this!)
Ctrl-P - to change to previous level
h - toggle this help message";
| {
deps.wad.change_level(index - 1);
} | conditional_block |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub toggle_mouse: Gesture,
pub toggle_help: Gesture,
}
impl Default for Bindings {
fn default() -> Self {
Bindings {
quit: Gesture::AnyOf(vec![
Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape),
]),
next_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::N),
]),
previous_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::P),
]),
toggle_mouse: Gesture::KeyTrigger(Scancode::Grave),
toggle_help: Gesture::KeyTrigger(Scancode::H),
}
}
}
#[derive(DependenciesFrom)]
pub struct Dependencies<'context> {
bindings: &'context Bindings,
window: &'context Window,
input: &'context mut Input,
text: &'context mut TextRenderer,
control_flow: &'context mut ControlFlow,
wad: &'context mut WadSystem,
}
pub struct Hud {
mouse_grabbed: bool,
current_help: HelpState,
prompt_text: TextId,
help_text: TextId,
}
impl<'context> InfallibleSystem<'context> for Hud {
type Dependencies = Dependencies<'context>;
fn debug_name() -> &'static str {
"hud"
}
fn create(deps: Dependencies) -> Self {
deps.input.set_mouse_enabled(true);
deps.input.set_cursor_grabbed(true);
let prompt_text = deps
.text
.insert(deps.window, PROMPT_TEXT, Pnt2f::origin(), HELP_PADDING);
let help_text = deps
.text
.insert(deps.window, HELP_TEXT, Pnt2f::origin(), HELP_PADDING);
deps.text[help_text].set_visible(false);
Hud {
prompt_text,
help_text,
mouse_grabbed: true,
current_help: HelpState::Prompt,
}
}
fn update(&mut self, deps: Dependencies) {
let Dependencies {
input,
text,
control_flow,
bindings,
..
} = deps;
if input.poll_gesture(&bindings.quit) {
control_flow.quit_requested = true
}
if input.poll_gesture(&bindings.toggle_mouse) {
self.mouse_grabbed = !self.mouse_grabbed;
input.set_mouse_enabled(self.mouse_grabbed);
input.set_cursor_grabbed(self.mouse_grabbed);
}
if input.poll_gesture(&bindings.toggle_help) {
self.current_help = match self.current_help {
HelpState::Prompt => {
text[self.prompt_text].set_visible(false);
text[self.help_text].set_visible(true);
HelpState::Shown
}
HelpState::Shown => {
text[self.help_text].set_visible(false);
HelpState::Hidden
}
HelpState::Hidden => {
text[self.help_text].set_visible(true);
HelpState::Shown
}
};
}
if input.poll_gesture(&bindings.next_level) {
let index = deps.wad.level_index();
deps.wad.change_level(index + 1);
} else if input.poll_gesture(&bindings.previous_level) {
let index = deps.wad.level_index();
if index > 0 {
deps.wad.change_level(index - 1);
}
}
}
fn | (&mut self, deps: Dependencies) {
deps.text.remove(self.help_text);
deps.text.remove(self.prompt_text);
}
}
enum HelpState {
Prompt,
Shown,
Hidden,
}
const HELP_PADDING: u32 = 6;
const PROMPT_TEXT: &str = "WASD and mouse, 'E' to push/use, LB to shoot or 'h' for help.";
const HELP_TEXT: &str = r"Use WASD to move and the mouse or arrow keys to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
E - push/interact/use
Left Click - shoot (only effect is to trigger gun-activated things)
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
Ctrl-N - to change to next level (though using the exit will also do this!)
Ctrl-P - to change to previous level
h - toggle this help message";
| teardown | identifier_name |
hud.rs | use super::wad_system::WadSystem;
use engine::{
ControlFlow, DependenciesFrom, Gesture, InfallibleSystem, Input, Scancode, TextId,
TextRenderer, Window,
};
use math::prelude::*;
use math::Pnt2f;
pub struct Bindings {
pub quit: Gesture,
pub next_level: Gesture,
pub previous_level: Gesture,
pub toggle_mouse: Gesture,
pub toggle_help: Gesture,
}
impl Default for Bindings {
fn default() -> Self {
Bindings {
quit: Gesture::AnyOf(vec![
Gesture::QuitTrigger,
Gesture::KeyTrigger(Scancode::Escape),
]),
next_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::N),
]),
previous_level: Gesture::AllOf(vec![
Gesture::KeyHold(Scancode::LControl),
Gesture::KeyTrigger(Scancode::P),
]),
toggle_mouse: Gesture::KeyTrigger(Scancode::Grave),
toggle_help: Gesture::KeyTrigger(Scancode::H),
}
}
}
#[derive(DependenciesFrom)]
pub struct Dependencies<'context> {
bindings: &'context Bindings,
window: &'context Window,
input: &'context mut Input,
text: &'context mut TextRenderer,
control_flow: &'context mut ControlFlow,
wad: &'context mut WadSystem,
}
pub struct Hud {
mouse_grabbed: bool,
current_help: HelpState,
prompt_text: TextId,
help_text: TextId,
}
impl<'context> InfallibleSystem<'context> for Hud {
type Dependencies = Dependencies<'context>;
fn debug_name() -> &'static str {
"hud"
}
fn create(deps: Dependencies) -> Self {
deps.input.set_mouse_enabled(true);
deps.input.set_cursor_grabbed(true);
let prompt_text = deps
.text
.insert(deps.window, PROMPT_TEXT, Pnt2f::origin(), HELP_PADDING);
let help_text = deps
.text
.insert(deps.window, HELP_TEXT, Pnt2f::origin(), HELP_PADDING);
deps.text[help_text].set_visible(false);
Hud {
prompt_text,
help_text,
mouse_grabbed: true,
current_help: HelpState::Prompt,
}
}
fn update(&mut self, deps: Dependencies) {
let Dependencies {
input,
text,
control_flow,
bindings,
..
} = deps;
if input.poll_gesture(&bindings.quit) {
control_flow.quit_requested = true
}
if input.poll_gesture(&bindings.toggle_mouse) {
self.mouse_grabbed = !self.mouse_grabbed;
input.set_mouse_enabled(self.mouse_grabbed);
input.set_cursor_grabbed(self.mouse_grabbed);
}
if input.poll_gesture(&bindings.toggle_help) {
self.current_help = match self.current_help {
HelpState::Prompt => { | text[self.prompt_text].set_visible(false);
text[self.help_text].set_visible(true);
HelpState::Shown
}
HelpState::Shown => {
text[self.help_text].set_visible(false);
HelpState::Hidden
}
HelpState::Hidden => {
text[self.help_text].set_visible(true);
HelpState::Shown
}
};
}
if input.poll_gesture(&bindings.next_level) {
let index = deps.wad.level_index();
deps.wad.change_level(index + 1);
} else if input.poll_gesture(&bindings.previous_level) {
let index = deps.wad.level_index();
if index > 0 {
deps.wad.change_level(index - 1);
}
}
}
fn teardown(&mut self, deps: Dependencies) {
deps.text.remove(self.help_text);
deps.text.remove(self.prompt_text);
}
}
enum HelpState {
Prompt,
Shown,
Hidden,
}
const HELP_PADDING: u32 = 6;
const PROMPT_TEXT: &str = "WASD and mouse, 'E' to push/use, LB to shoot or 'h' for help.";
const HELP_TEXT: &str = r"Use WASD to move and the mouse or arrow keys to aim.
Other keys:
ESC - to quit
SPACEBAR - jump
E - push/interact/use
Left Click - shoot (only effect is to trigger gun-activated things)
` - to toggle mouse grab (backtick)
f - to toggle fly mode
c - to toggle clipping (wall collisions)
Ctrl-N - to change to next level (though using the exit will also do this!)
Ctrl-P - to change to previous level
h - toggle this help message"; | random_line_split | |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse}; | #[tokio::test]
async fn test_post_text_resposnse_serialization() {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
"slotToElicit": "PickUpCity",
"slots": {
"CarType": null,
"PickUpCity": "Boston"
}
}"#;
let mock_request = MockRequestDispatcher::with_status(200).with_body(mock_resp_body);
let lex_client =
LexRuntimeClient::new_with(mock_request, MockCredentialsProvider, Region::UsEast1);
let post_text_req = PostTextRequest {
input_text: "Book a car".to_owned(),
user_id: "rs".to_owned(),
..Default::default()
};
let mut slots = HashMap::new();
slots.insert("CarType".to_owned(), None);
slots.insert("PickUpCity".to_owned(), Some("Boston".to_owned()));
let expected = PostTextResponse {
active_contexts: None,
alternative_intents: None,
bot_version: None,
dialog_state: Some("ElicitSlot".to_owned()),
intent_name: Some("BookCar".to_owned()),
message: Some("In what city do you need to rent a car?".to_owned()),
message_format: Some("PlainText".to_owned()),
nlu_intent_confidence: None,
slot_to_elicit: Some("PickUpCity".to_owned()),
slots: Some(slots),
response_card: None,
session_attributes: Some(HashMap::new()),
sentiment_response: None,
session_id: None,
};
let result: PostTextResponse = lex_client.post_text(post_text_req).await.unwrap();
assert_eq!(result, expected);
} | use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
| random_line_split |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse};
use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
#[tokio::test]
async fn | () {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
"slotToElicit": "PickUpCity",
"slots": {
"CarType": null,
"PickUpCity": "Boston"
}
}"#;
let mock_request = MockRequestDispatcher::with_status(200).with_body(mock_resp_body);
let lex_client =
LexRuntimeClient::new_with(mock_request, MockCredentialsProvider, Region::UsEast1);
let post_text_req = PostTextRequest {
input_text: "Book a car".to_owned(),
user_id: "rs".to_owned(),
..Default::default()
};
let mut slots = HashMap::new();
slots.insert("CarType".to_owned(), None);
slots.insert("PickUpCity".to_owned(), Some("Boston".to_owned()));
let expected = PostTextResponse {
active_contexts: None,
alternative_intents: None,
bot_version: None,
dialog_state: Some("ElicitSlot".to_owned()),
intent_name: Some("BookCar".to_owned()),
message: Some("In what city do you need to rent a car?".to_owned()),
message_format: Some("PlainText".to_owned()),
nlu_intent_confidence: None,
slot_to_elicit: Some("PickUpCity".to_owned()),
slots: Some(slots),
response_card: None,
session_attributes: Some(HashMap::new()),
sentiment_response: None,
session_id: None,
};
let result: PostTextResponse = lex_client.post_text(post_text_req).await.unwrap();
assert_eq!(result, expected);
}
| test_post_text_resposnse_serialization | identifier_name |
custom_tests.rs | extern crate rusoto_mock;
use crate::generated::{LexRuntime, LexRuntimeClient, PostTextRequest, PostTextResponse};
use rusoto_core::Region;
use std::collections::HashMap;
use self::rusoto_mock::*;
#[tokio::test]
async fn test_post_text_resposnse_serialization() | input_text: "Book a car".to_owned(),
user_id: "rs".to_owned(),
..Default::default()
};
let mut slots = HashMap::new();
slots.insert("CarType".to_owned(), None);
slots.insert("PickUpCity".to_owned(), Some("Boston".to_owned()));
let expected = PostTextResponse {
active_contexts: None,
alternative_intents: None,
bot_version: None,
dialog_state: Some("ElicitSlot".to_owned()),
intent_name: Some("BookCar".to_owned()),
message: Some("In what city do you need to rent a car?".to_owned()),
message_format: Some("PlainText".to_owned()),
nlu_intent_confidence: None,
slot_to_elicit: Some("PickUpCity".to_owned()),
slots: Some(slots),
response_card: None,
session_attributes: Some(HashMap::new()),
sentiment_response: None,
session_id: None,
};
let result: PostTextResponse = lex_client.post_text(post_text_req).await.unwrap();
assert_eq!(result, expected);
}
| {
let mock_resp_body = r#"{
"dialogState": "ElicitSlot",
"intentName": "BookCar",
"message": "In what city do you need to rent a car?",
"messageFormat": "PlainText",
"responseCard": null,
"sessionAttributes": {},
"slotToElicit": "PickUpCity",
"slots": {
"CarType": null,
"PickUpCity": "Boston"
}
}"#;
let mock_request = MockRequestDispatcher::with_status(200).with_body(mock_resp_body);
let lex_client =
LexRuntimeClient::new_with(mock_request, MockCredentialsProvider, Region::UsEast1);
let post_text_req = PostTextRequest { | identifier_body |
removeformatting.js | .
// Expand the selection to include any outermost tags that weren't included
// in the selection, but have the same visible selection. Stop expanding
// if we reach the top level field.
var expandedRange = goog.editor.range.expand(range,
this.getFieldObject().getElement());
var startInTable = this.getTableAncestor_(expandedRange.getStartNode());
var endInTable = this.getTableAncestor_(expandedRange.getEndNode());
if (startInTable || endInTable) {
if (startInTable == endInTable) {
// We are fully contained in the same table, there is no extra
// remove formatting that we can do, just return and run browser
// formatting only.
return;
}
// Adjust the range to not contain any partially selected tables, since
// we don't want to run our custom remove formatting on them.
var savedCaretRange = this.adjustRangeForTables_(range,
startInTable, endInTable);
// Hack alert!!
// If start is not in a table, then the saved caret will get sent out
// for uber remove formatting, and it will get blown away. This is
// fine, except that we need to be able to re-create a range from the
// savedCaretRange later on. So, we just remove it from the dom, and
// put it back later so we can create a range later (not exactly in the
// same spot, but don't worry we don't actually try to use it later)
// and then it will be removed when we dispose the range.
if (!startInTable) {
this.putCaretInCave_(savedCaretRange, true);
}
if (!endInTable) {
this.putCaretInCave_(savedCaretRange, false);
}
// Re-fetch the range, and re-expand it, since we just modified it.
range = this.getFieldObject().getRange();
expandedRange = goog.editor.range.expand(range,
this.getFieldObject().getElement());
}
expandedRange.select();
range = expandedRange;
}
// Convert the selected text to the format-less version, paste back into
// the selection.
var text = this.getHtmlText_(range);
this.pasteHtml_(convertFunc(text));
if (goog.userAgent.GECKO && savedCaretRange) {
// If we moved the selection, move it back so the user can't tell we did
// anything crazy and so the browser removeFormat that we call next
// will operate on the entire originally selected range.
range = this.getFieldObject().getRange();
this.restoreCaretsFromCave_();
var realSavedCaretRange = savedCaretRange.toAbstractRange();
var startRange = startInTable ? realSavedCaretRange : range;
var endRange = endInTable ? realSavedCaretRange : range;
var restoredRange =
goog.editor.plugins.RemoveFormatting.createRangeDelimitedByRanges_(
startRange, endRange);
restoredRange.select();
savedCaretRange.dispose();
}
};
/**
* Does a best-effort attempt at clobbering all formatting that the
* browser's execCommand couldn't clobber without being totally inefficient.
* Attempts to convert visual line breaks to BRs. Leaves anchors that contain an
* href and images.
* Adapted from Gmail's MessageUtil's htmlToPlainText. http://go/messageutil.js
* @param {string} html The original html of the message.
* @return {string} The unformatted html, which is just text, br's, anchors and
* images.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.removeFormattingWorker_ =
function(html) {
var el = goog.dom.createElement('div');
el.innerHTML = html;
// Put everything into a string buffer to avoid lots of expensive string
// concatenation along the way.
var sb = [];
var stack = [el.childNodes, 0];
// Keep separate stacks for places where we need to keep track of
// how deeply embedded we are. These are analogous to the general stack.
var preTagStack = [];
var preTagLevel = 0; // Length of the prestack.
var tableStack = [];
var tableLevel = 0;
// sp = stack pointer, pointing to the stack array.
// decrement by 2 since the stack alternates node lists and
// processed node counts
for (var sp = 0; sp >= 0; sp -= 2) {
// Check if we should pop the table level.
var changedLevel = false;
while (tableLevel > 0 && sp <= tableStack[tableLevel - 1]) {
tableLevel--;
changedLevel = true;
}
if (changedLevel) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
// Check if we should pop the <pre>/<xmp> level.
changedLevel = false;
while (preTagLevel > 0 && sp <= preTagStack[preTagLevel - 1]) {
preTagLevel--;
changedLevel = true;
}
if (changedLevel) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
// The list of of nodes to process at the current stack level.
var nodeList = stack[sp];
// The number of nodes processed so far, stored in the stack immediately
// following the node list for that stack level.
var numNodesProcessed = stack[sp + 1];
while (numNodesProcessed < nodeList.length) {
var node = nodeList[numNodesProcessed++];
var nodeName = node.nodeName;
var formatted = this.getValueForNode(node);
if (goog.isDefAndNotNull(formatted)) {
sb.push(formatted);
continue;
}
// TODO(user): Handle case 'EMBED' and case 'OBJECT'.
switch (nodeName) {
case '#text':
// Note that IE does not preserve whitespace in the dom
// values, even in a pre tag, so this is useless for IE.
var nodeValue = preTagLevel > 0 ?
node.nodeValue :
goog.string.stripNewlines(node.nodeValue);
nodeValue = goog.string.htmlEscape(nodeValue);
sb.push(nodeValue);
continue;
case goog.dom.TagName.P:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
break; // break (not continue) so that child nodes are processed.
case goog.dom.TagName.BR:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
continue;
case goog.dom.TagName.TABLE:
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
tableStack[tableLevel++] = sp;
break;
case goog.dom.TagName.PRE:
case 'XMP':
// This doesn't fully handle xmp, since
// it doesn't actually ignore tags within the xmp tag.
preTagStack[preTagLevel++] = sp;
break;
case goog.dom.TagName.STYLE:
case goog.dom.TagName.SCRIPT:
case goog.dom.TagName.SELECT:
continue;
case goog.dom.TagName.A:
if (node.href && node.href != '') {
sb.push("<a href='");
sb.push(node.href);
sb.push("'>");
sb.push(this.removeFormattingWorker_(node.innerHTML));
sb.push('</a>');
continue; // Children taken care of.
} else {
break; // Take care of the children.
}
case goog.dom.TagName.IMG:
sb.push("<img src='");
sb.push(node.src);
sb.push("'");
// border=0 is a common way to not show a blue border around an image
// that is wrapped by a link. If we remove that, the blue border will
// show up, which to the user looks like adding format, not removing.
if (node.border == '0') {
sb.push(" border='0'");
}
sb.push('>');
continue;
case goog.dom.TagName.TD:
// Don't add a space for the first TD, we only want spaces to
// separate td's.
if (node.previousSibling) {
sb.push(' ');
}
break;
case goog.dom.TagName.TR:
// Don't add a newline for the first TR.
if (node.previousSibling) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
break;
case goog.dom.TagName.DIV:
var parent = node.parentNode;
if (parent.firstChild == node &&
goog.editor.plugins.RemoveFormatting.BLOCK_RE_.test(
parent.tagName)) {
// If a DIV is the first child of another element that itself is a
// block element, the DIV does not add a new line.
break;
}
// Otherwise, the DIV does add a new line. Fall through.
default:
if (goog.editor.plugins.RemoveFormatting.BLOCK_RE_.test(nodeName)) {
goog.editor.plugins.RemoveFormatting.appendNewline_(sb);
}
}
// Recurse down the node.
var children = node.childNodes;
if (children.length > 0) | {
// Push the current state on the stack.
stack[sp++] = nodeList;
stack[sp++] = numNodesProcessed;
// Iterate through the children nodes.
nodeList = children;
numNodesProcessed = 0;
} | conditional_block | |
removeformatting.js | .
goog.dom.insertSiblingAfter(dummySpan, parent);
goog.dom.removeNode(parent);
}
goog.editor.node.replaceInnerHtml(parent,
parent.innerHTML.replace(new RegExp(dummySpanText, 'i'), html));
}
}
var startSpan = dh.getElement(startSpanId);
var endSpan = dh.getElement(endSpanId);
goog.dom.Range.createFromNodes(startSpan, 0, endSpan,
endSpan.childNodes.length).select();
goog.dom.removeNode(startSpan);
goog.dom.removeNode(endSpan);
};
/**
* Gets the html inside the selection to send off for further processing.
*
* TODO(user): Make this general so that it can be moved into
* goog.editor.range. The main reason it can't be moved is becuase we need to
* get the range before we do the execCommand and continue to operate on that
* same range (reasons are documented above).
*
* @param {goog.dom.AbstractRange} range The selection.
* @return {string} The html string to format.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.getHtmlText_ = function(range) {
var div = this.getFieldDomHelper().createDom('div');
var textRange = range.getBrowserRangeObject();
if (goog.editor.BrowserFeature.HAS_W3C_RANGES) {
// Get the text to convert.
div.appendChild(textRange.cloneContents());
} else if (goog.editor.BrowserFeature.HAS_IE_RANGES) {
// Trim the whitespace on the ends of the range, so that it the container
// will be the container of only the text content that we are changing.
// This gets around issues in IE where the spaces are included in the
// selection, but ignored sometimes by execCommand, and left orphaned.
var rngText = range.getText();
// BRs get reported as \r\n, but only count as one character for moves.
// Adjust the string so our move counter is correct.
rngText = rngText.replace(/\r\n/g, '\r');
var rngTextLength = rngText.length;
var left = rngTextLength - goog.string.trimLeft(rngText).length;
var right = rngTextLength - goog.string.trimRight(rngText).length;
textRange.moveStart('character', left);
textRange.moveEnd('character', -right);
var htmlText = textRange.htmlText;
// Check if in pretag and fix up formatting so that new lines are preserved.
if (textRange.queryCommandValue('formatBlock') == 'Formatted') {
htmlText = goog.string.newLineToBr(textRange.htmlText);
}
div.innerHTML = htmlText;
}
// Get the innerHTML of the node instead of just returning the text above
// so that its properly html escaped.
return div.innerHTML;
};
/**
* Move the range so that it doesn't include any partially selected tables.
* @param {goog.dom.AbstractRange} range The range to adjust.
* @param {Node} startInTable Table node that the range starts in.
* @param {Node} endInTable Table node that the range ends in.
* @return {!goog.dom.SavedCaretRange} Range to use to restore the
* selection after we run our custom remove formatting.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.adjustRangeForTables_ =
function(range, startInTable, endInTable) {
// Create placeholders for the current selection so we can restore it
// later.
var savedCaretRange = goog.editor.range.saveUsingNormalizedCarets(range);
var startNode = range.getStartNode();
var startOffset = range.getStartOffset();
var endNode = range.getEndNode();
var endOffset = range.getEndOffset();
var dh = this.getFieldDomHelper();
// Move start after the table.
if (startInTable) {
var textNode = dh.createTextNode('');
goog.dom.insertSiblingAfter(textNode, startInTable);
startNode = textNode;
startOffset = 0;
}
// Move end before the table.
if (endInTable) {
var textNode = dh.createTextNode('');
goog.dom.insertSiblingBefore(textNode, endInTable);
endNode = textNode;
endOffset = 0;
}
goog.dom.Range.createFromNodes(startNode, startOffset,
endNode, endOffset).select();
return savedCaretRange;
};
/**
* Remove a caret from the dom and hide it in a safe place, so it can
* be restored later via restoreCaretsFromCave.
* @param {goog.dom.SavedCaretRange} caretRange The caret range to
* get the carets from.
* @param {boolean} isStart Whether this is the start or end caret.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.putCaretInCave_ = function(
caretRange, isStart) {
var cavedCaret = goog.dom.removeNode(caretRange.getCaret(isStart));
if (isStart) {
this.startCaretInCave_ = cavedCaret;
} else {
this.endCaretInCave_ = cavedCaret;
}
};
/**
* Restore carets that were hidden away by adding them back into the dom.
* Note: this does not restore to the original dom location, as that
* will likely have been modified with remove formatting. The only
* guarentees here are that start will still be before end, and that
* they will be in the editable region. This should only be used when
* you don't actually intend to USE the caret again.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.restoreCaretsFromCave_ =
function() {
// To keep start before end, we put the end caret at the bottom of the field
// and the start caret at the start of the field.
var field = this.getFieldObject().getElement();
if (this.startCaretInCave_) {
field.insertBefore(this.startCaretInCave_, field.firstChild);
this.startCaretInCave_ = null;
}
if (this.endCaretInCave_) {
field.appendChild(this.endCaretInCave_);
this.endCaretInCave_ = null;
}
};
/**
* Gets the html inside the current selection, passes it through the given
* conversion function, and puts it back into the selection.
*
* @param {function(string): string} convertFunc A conversion function that
* transforms an html string to new html string.
* @private
*/
goog.editor.plugins.RemoveFormatting.prototype.convertSelectedHtmlText_ =
function(convertFunc) {
var range = this.getFieldObject().getRange();
// For multiple ranges, it is really hard to do our custom remove formatting
// without invalidating other ranges. So instead of always losing the
// content, this solution at least lets the browser do its own remove
// formatting which works correctly most of the time.
if (range.getTextRangeCount() > 1) {
return;
}
if (goog.userAgent.GECKO) {
// Determine if we need to handle tables, since they are special cases.
// If the selection is entirely within a table, there is no extra
// formatting removal we can do. If a table is fully selected, we will
// just blow it away. If a table is only partially selected, we can
// perform custom remove formatting only on the non table parts, since we
// we can't just remove the parts and paste back into it (eg. we can't
// inject html where a TR used to be).
// If the selection contains the table and more, this is automatically
// handled, but if just the table is selected, it can be tricky to figure
// this case out, because of the numerous ways selections can be formed -
// ex. if a table has a single tr with a single td with a single text node
// in it, and the selection is (textNode: 0), (textNode: nextNode.length)
// then the entire table is selected, even though the start and end aren't
// the table itself. We are truly inside a table if the expanded endpoints
// are still inside the table.
// Expand the selection to include any outermost tags that weren't included
// in the selection, but have the same visible selection. Stop expanding
// if we reach the top level field.
var expandedRange = goog.editor.range.expand(range,
this.getFieldObject().getElement());
var startInTable = this.getTableAncestor_(expandedRange.getStartNode());
var endInTable = this.getTableAncestor_(expandedRange.getEndNode());
if (startInTable || endInTable) {
if (startInTable == endInTable) {
// We are fully contained in the same table, there is no extra
// remove formatting that we can do, just return and run browser
// formatting only.
return;
}
// Adjust the range to not contain any partially selected tables, since
// we don't want to run our custom remove formatting on them.
var savedCaretRange = this.adjustRangeForTables_(range,
startInTable, endInTable);
// Hack alert!!
// If start is not in a table, then the saved caret will get sent out | // for uber remove formatting, and it will get blown away. This is
// fine, except that we need to be able to re-create a range from the | random_line_split | |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(73)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 192, 73], OperandSize::Dword)
}
fn roundsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectDisplaced(EAX, 455015242, Some(OperandSize::Qword), None)), operand3: Some(Literal8(66)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 176, 74, 251, 30, 27, 66], OperandSize::Dword)
}
fn roundsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(21)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 249, 21], OperandSize::Qword)
} |
fn roundsd_4() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 1515642711, Some(OperandSize::Qword), None)), operand3: Some(Literal8(102)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 180, 202, 87, 223, 86, 90, 102], OperandSize::Qword)
} | random_line_split | |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(73)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 192, 73], OperandSize::Dword)
}
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectDisplaced(EAX, 455015242, Some(OperandSize::Qword), None)), operand3: Some(Literal8(66)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 176, 74, 251, 30, 27, 66], OperandSize::Dword)
}
fn roundsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(21)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 249, 21], OperandSize::Qword)
}
fn roundsd_4() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 1515642711, Some(OperandSize::Qword), None)), operand3: Some(Literal8(102)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 180, 202, 87, 223, 86, 90, 102], OperandSize::Qword)
}
| roundsd_2 | identifier_name |
roundsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn roundsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(73)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 192, 73], OperandSize::Dword)
}
fn roundsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectDisplaced(EAX, 455015242, Some(OperandSize::Qword), None)), operand3: Some(Literal8(66)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 176, 74, 251, 30, 27, 66], OperandSize::Dword)
}
fn roundsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM1)), operand3: Some(Literal8(21)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 249, 21], OperandSize::Qword)
}
fn roundsd_4() | {
run_test(&Instruction { mnemonic: Mnemonic::ROUNDSD, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexedDisplaced(RDX, RCX, Eight, 1515642711, Some(OperandSize::Qword), None)), operand3: Some(Literal8(102)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 11, 180, 202, 87, 223, 86, 90, 102], OperandSize::Qword)
} | identifier_body | |
process.rs | use std::io::process::{Command,ProcessOutput};
fn main() | let s = String::from_utf8_lossy(err.as_slice());
print!("rustc failed and stderr was:\n{}", s);
}
},
}
}
| {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
// The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
Err(why) => panic!("couldn't spawn rustc: {}", why.desc),
// Destructure `ProcessOutput`
Ok(ProcessOutput { error: err, output: out, status: exit }) => {
// Check if the process succeeded, i.e. the exit code was 0
if exit.success() {
// `out` has type `Vec<u8>`, convert it to a UTF-8 `$str`
let s = String::from_utf8_lossy(out.as_slice());
print!("rustc succeeded and stdout was:\n{}", s);
} else {
// `err` also has type `Vec<u8>` | identifier_body |
process.rs | use std::io::process::{Command,ProcessOutput};
fn main() {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
| Ok(ProcessOutput { error: err, output: out, status: exit }) => {
// Check if the process succeeded, i.e. the exit code was 0
if exit.success() {
// `out` has type `Vec<u8>`, convert it to a UTF-8 `$str`
let s = String::from_utf8_lossy(out.as_slice());
print!("rustc succeeded and stdout was:\n{}", s);
} else {
// `err` also has type `Vec<u8>`
let s = String::from_utf8_lossy(err.as_slice());
print!("rustc failed and stderr was:\n{}", s);
}
},
}
} | // The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
Err(why) => panic!("couldn't spawn rustc: {}", why.desc),
// Destructure `ProcessOutput` | random_line_split |
process.rs | use std::io::process::{Command,ProcessOutput};
fn | () {
// Initial command `rustc`
let mut cmd = Command::new("rustc");
// append the "--version" flag to the command
cmd.arg("--version");
// The `output` method will spawn `rustc --version`, wait until the process
// finishes and return the output of the process
match cmd.output() {
Err(why) => panic!("couldn't spawn rustc: {}", why.desc),
// Destructure `ProcessOutput`
Ok(ProcessOutput { error: err, output: out, status: exit }) => {
// Check if the process succeeded, i.e. the exit code was 0
if exit.success() {
// `out` has type `Vec<u8>`, convert it to a UTF-8 `$str`
let s = String::from_utf8_lossy(out.as_slice());
print!("rustc succeeded and stdout was:\n{}", s);
} else {
// `err` also has type `Vec<u8>`
let s = String::from_utf8_lossy(err.as_slice());
print!("rustc failed and stderr was:\n{}", s);
}
},
}
}
| main | identifier_name |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1)
def | ():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
assert Join(1, 2) == 2
assert Join(2, 2) == 2
assert Join(Join(2, 3), 4) == Join(2, 3, 4)
assert Join() == 1
assert Join(4) == 4
assert Join(1, 4, 2, 3, 1, 3, 2) == Join(2, 3, 4)
def test_lattice_shortcircuit():
pytest.raises(SympifyError, lambda: Join(object))
assert Join(0, object) == 0
def test_lattice_print():
assert str(Join(5, 4, 3, 2)) == 'Join(2, 3, 4, 5)'
def test_lattice_make_args():
assert Join.make_args(0) == {0}
assert Join.make_args(1) == {1}
assert Join.make_args(Join(2, 3, 4)) == {Integer(2), Integer(3), Integer(4)}
| test_flatten | identifier_name |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1) |
def test_flatten():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
assert Join(1, 2) == 2
assert Join(2, 2) == 2
assert Join(Join(2, 3), 4) == Join(2, 3, 4)
assert Join() == 1
assert Join(4) == 4
assert Join(1, 4, 2, 3, 1, 3, 2) == Join(2, 3, 4)
def test_lattice_shortcircuit():
pytest.raises(SympifyError, lambda: Join(object))
assert Join(0, object) == 0
def test_lattice_print():
assert str(Join(5, 4, 3, 2)) == 'Join(2, 3, 4, 5)'
def test_lattice_make_args():
assert Join.make_args(0) == {0}
assert Join.make_args(1) == {1}
assert Join.make_args(Join(2, 3, 4)) == {Integer(2), Integer(3), Integer(4)} | random_line_split | |
test_operations.py | import pytest
from diofant import Integer, SympifyError
from diofant.core.operations import AssocOp, LatticeOp
__all__ = ()
class MyMul(AssocOp):
identity = Integer(1)
def test_flatten():
assert MyMul(2, MyMul(4, 3)) == MyMul(2, 4, 3)
class Join(LatticeOp):
"""Simplest possible Lattice class."""
zero = Integer(0)
identity = Integer(1)
def test_lattice_simple():
|
def test_lattice_shortcircuit():
pytest.raises(SympifyError, lambda: Join(object))
assert Join(0, object) == 0
def test_lattice_print():
assert str(Join(5, 4, 3, 2)) == 'Join(2, 3, 4, 5)'
def test_lattice_make_args():
assert Join.make_args(0) == {0}
assert Join.make_args(1) == {1}
assert Join.make_args(Join(2, 3, 4)) == {Integer(2), Integer(3), Integer(4)}
| assert Join(Join(2, 3), 4) == Join(2, Join(3, 4))
assert Join(2, 3) == Join(3, 2)
assert Join(0, 2) == 0
assert Join(1, 2) == 2
assert Join(2, 2) == 2
assert Join(Join(2, 3), 4) == Join(2, 3, 4)
assert Join() == 1
assert Join(4) == 4
assert Join(1, 4, 2, 3, 1, 3, 2) == Join(2, 3, 4) | identifier_body |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from .Registration import Registration
from lib.CommaSeparatedStringsField import CommaSeparatedStringsField
class Event(models.Model):
name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline_at = models.DateTimeField()
start_at = models.DateTimeField()
end_at = models.DateTimeField()
note_field = models.CharField(max_length=100, default='', blank=True)
note_field_options = CommaSeparatedStringsField(max_length=255, default='', blank=True)
note_field_required = models.BooleanField()
note_field_public = models.BooleanField()
location = models.CharField(max_length=25)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0)
calendar_url = models.CharField(max_length=255, blank=True)
committee = models.ForeignKey(Committee, on_delete=models.PROTECT)
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Registration)
places = models.PositiveIntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)])
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event-detail', args=[self.pk])
def | (self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is_full(self):
"""
Return true if there are no free places left.
"""
return self.get_free_places() is not None and self.get_free_places() <= 0
def get_free_places(self):
"""
Return the number of free places left.
"""
if self.places is None:
# If the event doesn't have a places limit, the value of this function is not defined
return None
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations
"""
return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return list of tuples from list of options
"""
return [('', self.note_field + ':')] + [(x, x) for x in self.note_field_options]
def clean(self):
if self.start_at > self.end_at:
raise ValidationError(_("Begindatum is later dan de einddatum!"))
if self.start_at < timezone.now():
raise ValidationError({'start_at': _("Startdatum is in het verleden!")})
if self.end_at < timezone.now():
raise ValidationError({'end_at': _("Einddatum is in het verleden!")})
if self.note_field_options and len(self.note_field_options) < 2:
raise ValidationError({'note_field_options': _("Geef minstens twee opties op.")})
class Meta:
ordering = ['created_at']
| is_published | identifier_name |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from .Registration import Registration
from lib.CommaSeparatedStringsField import CommaSeparatedStringsField
class Event(models.Model):
| def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event-detail', args=[self.pk])
def is_published(self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is_full(self):
"""
Return true if there are no free places left.
"""
return self.get_free_places() is not None and self.get_free_places() <= 0
def get_free_places(self):
"""
Return the number of free places left.
"""
if self.places is None:
# If the event doesn't have a places limit, the value of this function is not defined
return None
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations
"""
return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return list of tuples from list of options
"""
return [('', self.note_field + ':')] + [(x, x) for x in self.note_field_options]
def clean(self):
if self.start_at > self.end_at:
raise ValidationError(_("Begindatum is later dan de einddatum!"))
if self.start_at < timezone.now():
raise ValidationError({'start_at': _("Startdatum is in het verleden!")})
if self.end_at < timezone.now():
raise ValidationError({'end_at': _("Einddatum is in het verleden!")})
if self.note_field_options and len(self.note_field_options) < 2:
raise ValidationError({'note_field_options': _("Geef minstens twee opties op.")})
class Meta:
ordering = ['created_at']
| name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline_at = models.DateTimeField()
start_at = models.DateTimeField()
end_at = models.DateTimeField()
note_field = models.CharField(max_length=100, default='', blank=True)
note_field_options = CommaSeparatedStringsField(max_length=255, default='', blank=True)
note_field_required = models.BooleanField()
note_field_public = models.BooleanField()
location = models.CharField(max_length=25)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0)
calendar_url = models.CharField(max_length=255, blank=True)
committee = models.ForeignKey(Committee, on_delete=models.PROTECT)
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Registration)
places = models.PositiveIntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)])
| identifier_body |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from .Registration import Registration
from lib.CommaSeparatedStringsField import CommaSeparatedStringsField
class Event(models.Model):
name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline_at = models.DateTimeField()
start_at = models.DateTimeField()
end_at = models.DateTimeField()
note_field = models.CharField(max_length=100, default='', blank=True)
note_field_options = CommaSeparatedStringsField(max_length=255, default='', blank=True)
note_field_required = models.BooleanField()
note_field_public = models.BooleanField()
location = models.CharField(max_length=25)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0)
calendar_url = models.CharField(max_length=255, blank=True)
committee = models.ForeignKey(Committee, on_delete=models.PROTECT)
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Registration)
places = models.PositiveIntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)])
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event-detail', args=[self.pk])
def is_published(self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is_full(self):
"""
Return true if there are no free places left.
"""
return self.get_free_places() is not None and self.get_free_places() <= 0
def get_free_places(self):
"""
Return the number of free places left.
"""
if self.places is None:
# If the event doesn't have a places limit, the value of this function is not defined
|
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations
"""
return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return list of tuples from list of options
"""
return [('', self.note_field + ':')] + [(x, x) for x in self.note_field_options]
def clean(self):
if self.start_at > self.end_at:
raise ValidationError(_("Begindatum is later dan de einddatum!"))
if self.start_at < timezone.now():
raise ValidationError({'start_at': _("Startdatum is in het verleden!")})
if self.end_at < timezone.now():
raise ValidationError({'end_at': _("Einddatum is in het verleden!")})
if self.note_field_options and len(self.note_field_options) < 2:
raise ValidationError({'note_field_options': _("Geef minstens twee opties op.")})
class Meta:
ordering = ['created_at']
| return None | conditional_block |
Event.py | from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from .Registration import Registration
from lib.CommaSeparatedStringsField import CommaSeparatedStringsField
class Event(models.Model):
name = models.CharField(max_length=25)
description = models.TextField(max_length=255)
long_description = models.TextField(blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
published_at = models.DateTimeField(default=timezone.now, blank=True)
deadline_at = models.DateTimeField()
start_at = models.DateTimeField()
end_at = models.DateTimeField()
note_field = models.CharField(max_length=100, default='', blank=True)
note_field_options = CommaSeparatedStringsField(max_length=255, default='', blank=True)
note_field_required = models.BooleanField()
note_field_public = models.BooleanField()
location = models.CharField(max_length=25)
price = models.DecimalField(max_digits=5, decimal_places=2, default=0)
calendar_url = models.CharField(max_length=255, blank=True)
committee = models.ForeignKey(Committee, on_delete=models.PROTECT)
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through=Registration)
places = models.PositiveIntegerField(default=None, null=True, blank=True, validators=[MinValueValidator(1)])
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('event-detail', args=[self.pk])
def is_published(self):
"""
Return true if the event is published (past published date and not past end date)
"""
return self.published_at < timezone.now() < self.end_at
def is_expired(self):
"""
Return true if deadline is expired.
"""
return self.deadline_at is not None and self.deadline_at < timezone.now()
def is_full(self):
"""
Return true if there are no free places left.
"""
return self.get_free_places() is not None and self.get_free_places() <= 0
def get_free_places(self):
"""
Return the number of free places left.
"""
if self.places is None:
# If the event doesn't have a places limit, the value of this function is not defined
return None
else:
return self.places - Registration.objects.filter(event=self, withdrawn_at__isnull=True).count()
def get_active_registrations_count(self):
"""
Return the number of non-withdrawn registrations | return self.registration_set.filter(withdrawn_at__isnull=True).count()
def is_almost_expired(self):
"""
Return true if the deadline is closer than a day.
"""
return self.deadline_at - timezone.now() < timezone.timedelta(days=1) and not self.is_expired()
def get_note_field_options(self):
"""
Return list of tuples from list of options
"""
return [('', self.note_field + ':')] + [(x, x) for x in self.note_field_options]
def clean(self):
if self.start_at > self.end_at:
raise ValidationError(_("Begindatum is later dan de einddatum!"))
if self.start_at < timezone.now():
raise ValidationError({'start_at': _("Startdatum is in het verleden!")})
if self.end_at < timezone.now():
raise ValidationError({'end_at': _("Einddatum is in het verleden!")})
if self.note_field_options and len(self.note_field_options) < 2:
raise ValidationError({'note_field_options': _("Geef minstens twee opties op.")})
class Meta:
ordering = ['created_at'] | """ | random_line_split |
lexer.py | 2028<PS>\\\u2029<CR><LF>\\\r\n'",
["STRING '<LF>\\\n<CR>\\\r<LS>\\\u2028<PS>\\\u2029<CR><LF>\\\r\n'"])
), (
# okay this is getting ridiculous how bad ECMA is.
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
),
]
# various string related syntax errors
es5_error_cases_str = [
(
'unterminated_string_eof',
"var foo = 'test",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_separator_in_string',
"vaf foo = 'test\u2028foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_feed_in_string',
"var foo = 'test\u2029foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_crnl_in_string',
"var foo = 'test\r\nfoo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_cr_in_string',
"var foo = 'test\\\n\rfoo'",
# FIXME Note that the \\ is double escaped
'Unterminated string literal "\'test\\\\" at 1:11',
), (
'invalid_hex_sequence',
"var foo = 'fail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 1:16",
), (
'invalid_unicode_sequence',
"var foo = 'fail\\u12'",
"Invalid unicode escape sequence `\\u12` at 1:16",
), (
'invalid_hex_sequence_multiline',
"var foo = 'foobar\\\r\nfail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 2:5",
), (
'invalid_unicode_sequence_multiline',
"var foo = 'foobar\\\nfail\\u12'",
"Invalid unicode escape sequence `\\u12` at 2:5",
), (
'long_invalid_string_truncated',
"var foo = '1234567890abcdetruncated",
'Unterminated string literal "\'1234567890abcde..." at 1:11',
)
]
es5_comment_cases = [
(
'line_comment_whole',
('//comment\na = 5;\n',
['LINE_COMMENT //comment', 'ID a', 'EQ =', 'NUMBER 5', 'SEMI ;']),
), (
'line_comment_trail',
('a//comment', ['ID a', 'LINE_COMMENT //comment']),
), (
'block_comment_single',
('/***/b/=3//line',
['BLOCK_COMMENT /***/', 'ID b', 'DIVEQUAL /=',
'NUMBER 3', 'LINE_COMMENT //line']),
), (
'block_comment_multiline',
('/*\n * Copyright LGPL 2011 \n*/\na = 1;',
['BLOCK_COMMENT /*\n * Copyright LGPL 2011 \n*/',
'ID a', 'EQ =', 'NUMBER 1', 'SEMI ;']),
), (
# this will replace the standard test cases
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'BLOCK_COMMENT /** **/', 'DIV /', 'ID hi',
'DIV /', 'ID s'])
)
]
# replace the section_7_comments test case
es5_all_cases = es5_cases[:-1] + es5_comment_cases
# double quote version
es5_error_cases_str_dq = [
(n, arg.translate(swapquotes), msg.translate(swapquotes))
for n, arg, msg in es5_error_cases_str
]
# single quote version
es5_error_cases_str_sq = [
(n, arg, msg.translate({96: 39}))
for n, arg, msg in es5_error_cases_str
]
es5_pos_cases = [
(
'single_line',
"""
var foo = bar; // line 1
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13'
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
])
), (
'multi_line',
"""
var foo = bar; // line 1
var bar = baz; // line 4
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13',
'var 4:28', 'bar 4:32', '= 4:36', 'baz 4:38', '; 4:41',
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
'var 4:1', 'bar 4:5', '= 4:9', 'baz 4:11', '; 4:14',
])
), (
'inline_comment',
"""
// this is a comment // line 1
var foo = bar; // line 2
// another one // line 4
var bar = baz; // line 5
""", ([
'var 2:32', 'foo 2:36', '= 2:40', 'bar 2:42', '; 2:45',
'var 5:85', 'bar 5:89', '= 5:93', 'baz 5:95', '; 5:98',
], [
'var 2:1', 'foo 2:5', '= 2:9', 'bar 2:11', '; 2:14',
'var 5:1', 'bar 5:5', '= 5:9', 'baz 5:11', '; 5:14',
])
), (
'block_comment',
"""
/*
This is a block comment
*/
var foo = bar; // line 4
/* block single line */ // line 6
var bar = baz; // line 7
/* oops */bar(); // line 9
foo();
""", ([
'var 4:30', 'foo 4:34', '= 4:38', 'bar 4:40', '; 4:43',
'var 7:91', 'bar 7:95', '= 7:99', 'baz 7:101', '; 7:104',
'bar 9:128', '( 9:131', ') 9:132', '; 9:133',
'foo 11:149', '( 11:152', ') 11:153', '; 11:154',
], [
'var 4:1', 'foo 4:5', '= 4:9', 'bar 4:11', '; 4:14',
'var 7:1', 'bar 7:5', '= 7:9', 'baz 7:11', '; 7:14',
'bar 9:11', '( 9:14', ') 9:15', '; 9:16',
'foo 11:3', '( 11:6', ') 11:7', '; 11:8',
])
), (
'syntax_error_heading_comma',
"""
var a;
, b;
""", ([
'var 1:0', 'a 1:4', '; 1:5',
', 2:7', 'b 2:9', '; 2:10'
], [
'var 1:1', 'a 1:5', '; 1:6',
', 2:1', 'b 2:3', '; 2:4'
])
)
]
def run_lexer(value, lexer_cls):
lexer = lexer_cls()
lexer.input(value)
return ['%s %s' % (token.type, token.value) for token in lexer]
def run_lexer_pos(value, | lexer_cls):
| identifier_name | |
lexer.py | a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'DIV /', 'ID hi', 'DIV /', 'ID s'])
),
]
# various string related syntax errors
es5_error_cases_str = [
(
'unterminated_string_eof',
"var foo = 'test",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_separator_in_string',
"vaf foo = 'test\u2028foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_line_feed_in_string',
"var foo = 'test\u2029foo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_crnl_in_string',
"var foo = 'test\r\nfoo'",
'Unterminated string literal "\'test" at 1:11',
), (
'naked_cr_in_string',
"var foo = 'test\\\n\rfoo'",
# FIXME Note that the \\ is double escaped
'Unterminated string literal "\'test\\\\" at 1:11',
), (
'invalid_hex_sequence',
"var foo = 'fail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 1:16",
), (
'invalid_unicode_sequence',
"var foo = 'fail\\u12'",
"Invalid unicode escape sequence `\\u12` at 1:16",
), (
'invalid_hex_sequence_multiline',
"var foo = 'foobar\\\r\nfail\\x1'",
# backticks are converted to single quotes
"Invalid hexadecimal escape sequence `\\x1` at 2:5",
), (
'invalid_unicode_sequence_multiline',
"var foo = 'foobar\\\nfail\\u12'",
"Invalid unicode escape sequence `\\u12` at 2:5",
), (
'long_invalid_string_truncated',
"var foo = '1234567890abcdetruncated",
'Unterminated string literal "\'1234567890abcde..." at 1:11',
)
]
es5_comment_cases = [
(
'line_comment_whole',
('//comment\na = 5;\n',
['LINE_COMMENT //comment', 'ID a', 'EQ =', 'NUMBER 5', 'SEMI ;']),
), (
'line_comment_trail',
('a//comment', ['ID a', 'LINE_COMMENT //comment']),
), (
'block_comment_single',
('/***/b/=3//line',
['BLOCK_COMMENT /***/', 'ID b', 'DIVEQUAL /=',
'NUMBER 3', 'LINE_COMMENT //line']),
), (
'block_comment_multiline',
('/*\n * Copyright LGPL 2011 \n*/\na = 1;',
['BLOCK_COMMENT /*\n * Copyright LGPL 2011 \n*/',
'ID a', 'EQ =', 'NUMBER 1', 'SEMI ;']),
), (
# this will replace the standard test cases
'section_7_comments',
("a = b\n/** **/\n\n/hi/s",
['ID a', 'EQ =', 'ID b', 'BLOCK_COMMENT /** **/', 'DIV /', 'ID hi',
'DIV /', 'ID s'])
)
]
# replace the section_7_comments test case
es5_all_cases = es5_cases[:-1] + es5_comment_cases
# double quote version
es5_error_cases_str_dq = [
(n, arg.translate(swapquotes), msg.translate(swapquotes))
for n, arg, msg in es5_error_cases_str
]
# single quote version
es5_error_cases_str_sq = [
(n, arg, msg.translate({96: 39}))
for n, arg, msg in es5_error_cases_str
]
es5_pos_cases = [
(
'single_line',
"""
var foo = bar; // line 1
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13'
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
])
), (
'multi_line',
"""
var foo = bar; // line 1
var bar = baz; // line 4
""", ([
'var 1:0', 'foo 1:4', '= 1:8', 'bar 1:10', '; 1:13',
'var 4:28', 'bar 4:32', '= 4:36', 'baz 4:38', '; 4:41',
], [
'var 1:1', 'foo 1:5', '= 1:9', 'bar 1:11', '; 1:14',
'var 4:1', 'bar 4:5', '= 4:9', 'baz 4:11', '; 4:14',
])
), (
'inline_comment',
"""
// this is a comment // line 1
var foo = bar; // line 2
// another one // line 4
var bar = baz; // line 5
""", ([
'var 2:32', 'foo 2:36', '= 2:40', 'bar 2:42', '; 2:45',
'var 5:85', 'bar 5:89', '= 5:93', 'baz 5:95', '; 5:98',
], [
'var 2:1', 'foo 2:5', '= 2:9', 'bar 2:11', '; 2:14',
'var 5:1', 'bar 5:5', '= 5:9', 'baz 5:11', '; 5:14',
])
), (
'block_comment',
"""
/*
This is a block comment
*/
var foo = bar; // line 4
/* block single line */ // line 6
var bar = baz; // line 7
/* oops */bar(); // line 9
foo();
""", ([
'var 4:30', 'foo 4:34', '= 4:38', 'bar 4:40', '; 4:43',
'var 7:91', 'bar 7:95', '= 7:99', 'baz 7:101', '; 7:104',
'bar 9:128', '( 9:131', ') 9:132', '; 9:133',
'foo 11:149', '( 11:152', ') 11:153', '; 11:154',
], [
'var 4:1', 'foo 4:5', '= 4:9', 'bar 4:11', '; 4:14',
'var 7:1', 'bar 7:5', '= 7:9', 'baz 7:11', '; 7:14',
'bar 9:11', '( 9:14', ') 9:15', '; 9:16',
'foo 11:3', '( 11:6', ') 11:7', '; 11:8',
])
), (
'syntax_error_heading_comma',
"""
var a;
, b;
""", ([
'var 1:0', 'a 1:4', '; 1:5',
', 2:7', 'b 2:9', '; 2:10'
], [
'var 1:1', 'a 1:5', '; 1:6',
', 2:1', 'b 2:3', '; 2:4'
])
)
]
def run_lexer(value, lexer_cls):
lexer = lexer_cls()
lexer.input(value)
return ['%s %s' % (token.type, token.value) for token in lexer]
def run_lexer_pos(value, lexer_cls):
lexer = lexer_cls()
| lexer.input(textwrap.dedent(value).strip())
tokens = list(lexer)
return ([
'%s %d:%d' % (token.value, token.lineno, token.lexpos)
for token in tokens
], [
'%s %d:%d' % (token.value, token.lineno, token.colno)
for token in tokens
])
| identifier_body | |
lexer.py | (r'a=/a*/,1', ['ID a', 'EQ =', 'REGEX /a*/', 'COMMA ,', 'NUMBER 1']),
), (
'regex_2',
(r'a=/a*[^/]+/,1',
['ID a', 'EQ =', 'REGEX /a*[^/]+/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_3',
(r'a=/a*\[^/,1',
['ID a', 'EQ =', r'REGEX /a*\[^/', 'COMMA ,', 'NUMBER 1']
),
), (
'regex_4',
(r'a=/\//,1', ['ID a', 'EQ =', r'REGEX /\//', 'COMMA ,', 'NUMBER 1']),
), (
# not a regex, just a division
# https://github.com/rspivak/slimit/issues/6
'slimit_issue_6_not_regex_but_division',
(r'x = this / y;',
['ID x', 'EQ =', 'THIS this', r'DIV /', r'ID y', r'SEMI ;']),
), (
'regex_mozilla_example_1',
# next two are from
# http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions
('for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) '
'{xyz(x++);}',
["FOR for", "LPAREN (", "VAR var", "ID x", "EQ =", "ID a", "IN in",
"ID foo", "AND &&", 'STRING "</x>"', "OR ||", "ID mot", "CONDOP ?",
"ID z", "COLON :", "REGEX /x:3;x<5;y</g", "DIV /", "ID i",
"RPAREN )", "LBRACE {", "ID xyz", "LPAREN (", "ID x", "PLUSPLUS ++",
"RPAREN )", "SEMI ;", "RBRACE }"]
),
), (
'regex_mozilla_example_2',
('for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) '
'{xyz(x++);}',
["FOR for", "LPAREN (", "VAR var", "ID x", "EQ =", "ID a", "IN in",
"ID foo", "AND &&", 'STRING "</x>"', "OR ||", "ID mot", "CONDOP ?",
"ID z", "DIV /", "ID x", "COLON :", "NUMBER 3", "SEMI ;", "ID x",
"LT <", "NUMBER 5", "SEMI ;", "ID y", "LT <", "REGEX /g/i",
"RPAREN )", "LBRACE {", "ID xyz", "LPAREN (", "ID x", "PLUSPLUS ++",
"RPAREN )", "SEMI ;", "RBRACE }"]
),
), (
'regex_illegal_1',
# Various "illegal" regexes that are valid according to the std.
(r"""/????/, /++++/, /[----]/ """,
['REGEX /????/', 'COMMA ,',
'REGEX /++++/', 'COMMA ,', 'REGEX /[----]/']
),
), (
'regex_stress_test_1',
# Stress cases from
# http://stackoverflow.com/questions/5533925/
# what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409
(r"""/\[/""", [r"""REGEX /\[/"""]),
), (
'regex_stress_test_2',
(r"""/[i]/""", [r"""REGEX /[i]/"""]),
), (
'regex_stress_test_3',
(r"""/[\]]/""", [r"""REGEX /[\]]/"""]),
), (
'regex_stress_test_4',
(r"""/a[\]]/""", [r"""REGEX /a[\]]/"""]),
), (
'regex_stress_test_5',
(r"""/a[\]]b/""", [r"""REGEX /a[\]]b/"""]),
), (
'regex_stress_test_6',
(r"""/[\]/]/gi""", [r"""REGEX /[\]/]/gi"""]),
), (
'regex_stress_test_7',
(r"""/\[[^\]]+\]/gi""", [r"""REGEX /\[[^\]]+\]/gi"""]),
), (
'regex_stress_test_8',
(r"""
rexl.re = {
NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
QUOTED_LITERAL: /^'(?:[^']|'')*'/,
NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/,
SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/
};
""", [
"ID rexl", "PERIOD .", "ID re", "EQ =", "LBRACE {",
"ID NAME", "COLON :",
r"""REGEX /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/""", "COMMA ,",
"ID UNQUOTED_LITERAL", "COLON :",
r"""REGEX /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""",
"COMMA ,", "ID QUOTED_LITERAL", "COLON :",
r"""REGEX /^'(?:[^']|'')*'/""", "COMMA ,", "ID NUMERIC_LITERAL",
"COLON :",
r"""REGEX /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "COMMA ,",
"ID SYMBOL", "COLON :",
r"""REGEX /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""",
"RBRACE }", "SEMI ;"]),
), (
'regex_stress_test_9',
(r"""
rexl.re = {
NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/,
UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/,
QUOTED_LITERAL: /^'(?:[^']|'')*'/,
NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/,
SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/
};
str = '"';
""", [
"ID rexl", "PERIOD .", "ID re", "EQ =", "LBRACE {",
"ID NAME", "COLON :", r"""REGEX /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/""",
"COMMA ,", "ID UNQUOTED_LITERAL", "COLON :",
r"""REGEX /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""",
"COMMA ,", "ID QUOTED_LITERAL", "COLON :",
r"""REGEX /^'(?:[^']|'')*'/""", "COMMA ,",
"ID NUMERIC_LITERAL", "COLON :",
r"""REGEX /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "COMMA ,",
"ID SYMBOL", "COLON :",
r"""REGEX /^(?:==|=|<>|<=|<|>=|>|!~~|!~ | random_line_split | ||
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): string {
while (term.match(regex)) |
return term;
}
export class searchResult {
match: number;
antiMatch: number;
item: any;
}
export class SearchQuery {
matchTerms: string[] = [];
antiMatchTerms: string[] = [];
}
class search {
public searchQuery = ko.observable("").extend({persist: 'searchQuery'});
public titleOnly = ko.observable(false);
public results: KnockoutComputed<any[]>;
searchData: KnockoutObservableArray<any>;
public searchQueryObj: KnockoutComputed<SearchQuery>;
constructor(element: HTMLElement, params: searchParams) {
this.searchData = params.array;
this.setupSearchQuery();
this.setupResults();
}
setupSearchQuery() {
this.searchQueryObj = ko.computed(() => {
var searchQuery = this.searchQuery().toLowerCase();
//Need to get this so we auto-update
var titleOnly = this.titleOnly();
var verbatim = new RegExp("['\"][^'\"]+['\"]");
var terms: string[] = [];
searchQuery = extract(searchQuery, verbatim, terms);
terms = _.map(terms, term => term.substr(1, term.length - 2));
terms = terms.concat(searchQuery.split(new RegExp("\\s+")));
terms = _.filter(terms, term => term.length > 0);
var matchTerms = _.filter(terms, term => term.indexOf("-") !== 0);
var antiMatchTerms = _.filter(terms, term => term.indexOf("-") === 0);
antiMatchTerms = _.map(antiMatchTerms, term => term.substr(1));
var searchObj = new SearchQuery();
searchObj.matchTerms = matchTerms;
searchObj.antiMatchTerms = antiMatchTerms;
return searchObj;
});
}
setupResults() {
this.results = ko.computed(() => {
var searchObj = this.searchQueryObj();
var matchTerms = searchObj.matchTerms;
var antiMatchTerms = searchObj.antiMatchTerms;
var matches: searchResult[] = [];
//With a lookup table this could become much much faster...
_.forEach(this.searchData(), item => {
var itemToSearch = item;
if(this.titleOnly()) {
itemToSearch = item.jobTitle;
}
var match = 0;
var antiMatch = 0;
var rawText = JSON.stringify(itemToSearch).toLowerCase();
_.forEach(matchTerms, term => {
if (rawText.indexOf(term) >= 0) {
match++;
}
});
_.forEach(antiMatchTerms, term => {
if (rawText.indexOf(term) >= 0) {
antiMatch++;
}
});
if (match > 0) {
matches.push({ match: match, antiMatch: antiMatch, item: item });
}
});
matches.sort((a, b) => {
return (b.match - b.antiMatch) - (a.match - a.antiMatch);
});
return matches;
});
}
getResults(maxCount: number): KnockoutComputed<any[]> {
return ko.computed(() => {
var results = this.results();
var count = Math.min(results.length, maxCount);
var culledResults = [];
for (var ix = 0; ix < count; ix++) {
culledResults.push(results[ix]);
}
return culledResults;
});
}
}
koControl(search); | {
results.push(term.match(regex)[0]);
term = term.replace(regex, "");
} | conditional_block |
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): string {
while (term.match(regex)) {
results.push(term.match(regex)[0]);
term = term.replace(regex, "");
}
return term;
}
export class searchResult {
match: number;
antiMatch: number;
item: any;
}
export class SearchQuery {
matchTerms: string[] = [];
antiMatchTerms: string[] = [];
}
class | {
public searchQuery = ko.observable("").extend({persist: 'searchQuery'});
public titleOnly = ko.observable(false);
public results: KnockoutComputed<any[]>;
searchData: KnockoutObservableArray<any>;
public searchQueryObj: KnockoutComputed<SearchQuery>;
constructor(element: HTMLElement, params: searchParams) {
this.searchData = params.array;
this.setupSearchQuery();
this.setupResults();
}
setupSearchQuery() {
this.searchQueryObj = ko.computed(() => {
var searchQuery = this.searchQuery().toLowerCase();
//Need to get this so we auto-update
var titleOnly = this.titleOnly();
var verbatim = new RegExp("['\"][^'\"]+['\"]");
var terms: string[] = [];
searchQuery = extract(searchQuery, verbatim, terms);
terms = _.map(terms, term => term.substr(1, term.length - 2));
terms = terms.concat(searchQuery.split(new RegExp("\\s+")));
terms = _.filter(terms, term => term.length > 0);
var matchTerms = _.filter(terms, term => term.indexOf("-") !== 0);
var antiMatchTerms = _.filter(terms, term => term.indexOf("-") === 0);
antiMatchTerms = _.map(antiMatchTerms, term => term.substr(1));
var searchObj = new SearchQuery();
searchObj.matchTerms = matchTerms;
searchObj.antiMatchTerms = antiMatchTerms;
return searchObj;
});
}
setupResults() {
this.results = ko.computed(() => {
var searchObj = this.searchQueryObj();
var matchTerms = searchObj.matchTerms;
var antiMatchTerms = searchObj.antiMatchTerms;
var matches: searchResult[] = [];
//With a lookup table this could become much much faster...
_.forEach(this.searchData(), item => {
var itemToSearch = item;
if(this.titleOnly()) {
itemToSearch = item.jobTitle;
}
var match = 0;
var antiMatch = 0;
var rawText = JSON.stringify(itemToSearch).toLowerCase();
_.forEach(matchTerms, term => {
if (rawText.indexOf(term) >= 0) {
match++;
}
});
_.forEach(antiMatchTerms, term => {
if (rawText.indexOf(term) >= 0) {
antiMatch++;
}
});
if (match > 0) {
matches.push({ match: match, antiMatch: antiMatch, item: item });
}
});
matches.sort((a, b) => {
return (b.match - b.antiMatch) - (a.match - a.antiMatch);
});
return matches;
});
}
getResults(maxCount: number): KnockoutComputed<any[]> {
return ko.computed(() => {
var results = this.results();
var count = Math.min(results.length, maxCount);
var culledResults = [];
for (var ix = 0; ix < count; ix++) {
culledResults.push(results[ix]);
}
return culledResults;
});
}
}
koControl(search); | search | identifier_name |
search.ts | /// <amd-dependency path="koExtends/persist">
import $ = require("jquery");
import ko = require("knockout");
import _ = require("underscore");
import koControl = require("./koControl");
class searchParams {
array: KnockoutObservableArray<any>;
}
function extract(term: string, regex: RegExp, results: string[]): string {
while (term.match(regex)) {
results.push(term.match(regex)[0]);
term = term.replace(regex, "");
}
return term;
}
export class searchResult {
match: number;
antiMatch: number;
item: any;
}
export class SearchQuery {
matchTerms: string[] = [];
antiMatchTerms: string[] = [];
}
class search {
public searchQuery = ko.observable("").extend({persist: 'searchQuery'});
public titleOnly = ko.observable(false);
| public searchQueryObj: KnockoutComputed<SearchQuery>;
constructor(element: HTMLElement, params: searchParams) {
this.searchData = params.array;
this.setupSearchQuery();
this.setupResults();
}
setupSearchQuery() {
this.searchQueryObj = ko.computed(() => {
var searchQuery = this.searchQuery().toLowerCase();
//Need to get this so we auto-update
var titleOnly = this.titleOnly();
var verbatim = new RegExp("['\"][^'\"]+['\"]");
var terms: string[] = [];
searchQuery = extract(searchQuery, verbatim, terms);
terms = _.map(terms, term => term.substr(1, term.length - 2));
terms = terms.concat(searchQuery.split(new RegExp("\\s+")));
terms = _.filter(terms, term => term.length > 0);
var matchTerms = _.filter(terms, term => term.indexOf("-") !== 0);
var antiMatchTerms = _.filter(terms, term => term.indexOf("-") === 0);
antiMatchTerms = _.map(antiMatchTerms, term => term.substr(1));
var searchObj = new SearchQuery();
searchObj.matchTerms = matchTerms;
searchObj.antiMatchTerms = antiMatchTerms;
return searchObj;
});
}
setupResults() {
this.results = ko.computed(() => {
var searchObj = this.searchQueryObj();
var matchTerms = searchObj.matchTerms;
var antiMatchTerms = searchObj.antiMatchTerms;
var matches: searchResult[] = [];
//With a lookup table this could become much much faster...
_.forEach(this.searchData(), item => {
var itemToSearch = item;
if(this.titleOnly()) {
itemToSearch = item.jobTitle;
}
var match = 0;
var antiMatch = 0;
var rawText = JSON.stringify(itemToSearch).toLowerCase();
_.forEach(matchTerms, term => {
if (rawText.indexOf(term) >= 0) {
match++;
}
});
_.forEach(antiMatchTerms, term => {
if (rawText.indexOf(term) >= 0) {
antiMatch++;
}
});
if (match > 0) {
matches.push({ match: match, antiMatch: antiMatch, item: item });
}
});
matches.sort((a, b) => {
return (b.match - b.antiMatch) - (a.match - a.antiMatch);
});
return matches;
});
}
getResults(maxCount: number): KnockoutComputed<any[]> {
return ko.computed(() => {
var results = this.results();
var count = Math.min(results.length, maxCount);
var culledResults = [];
for (var ix = 0; ix < count; ix++) {
culledResults.push(results[ix]);
}
return culledResults;
});
}
}
koControl(search); | public results: KnockoutComputed<any[]>;
searchData: KnockoutObservableArray<any>;
| random_line_split |
static.module.js | const ng = require('angular');
ng.module('porybox.static', ['ngRoute']).config(['$routeProvider', $routeProvider => {
[
'about',
'donate',
'extracting-pokemon-files',
'faq',
'how-to-pk6-1-bvs',
'how-to-pk6-2-homebrew',
'how-to-pk6-3-4-save-files',
'how-to-pk6-6-decrypted-powersaves',
'how-to-pk7-1-bvs',
'how-to-pk7-2-homebrew',
'how-to-pk7-3-digital-save-files',
'how-to-pk7-4-tea', | 'privacy-policy',
'tos'
].forEach(pageName => {
$routeProvider.when(`/${pageName}`, {templateUrl: `/static/${pageName}.html`});
});
$routeProvider.when('/extracting-pk6-files', {redirectTo: '/extracting-pokemon-files'});
}]); | 'markdown', | random_line_split |
events.d.ts | import { State, Ctx, PlayerID, Game } from '../../types';
export interface EventsAPI {
endGame?(...args: any[]): void;
endPhase?(...args: any[]): void;
endStage?(...args: any[]): void;
endTurn?(...args: any[]): void;
pass?(...args: any[]): void;
setActivePlayers?(...args: any[]): void;
setPhase?(...args: any[]): void;
setStage?(...args: any[]): void;
}
| update(state: State): State;
};
}
/**
* Events
*/
export declare class Events {
flow: Game['flow'];
playerID: PlayerID | undefined;
dispatch: Array<{
key: string;
args: any[];
phase: string;
turn: number;
}>;
constructor(flow: Game['flow'], playerID?: PlayerID);
/**
* Attaches the Events API to ctx.
* @param {object} ctx - The ctx object to attach to.
*/
api(ctx: Ctx): EventsAPI & PrivateEventsAPI;
isUsed(): boolean;
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state: State): State<any, Ctx>;
} | export interface PrivateEventsAPI {
_obj: {
isUsed(): boolean;
| random_line_split |
events.d.ts | import { State, Ctx, PlayerID, Game } from '../../types';
export interface EventsAPI {
endGame?(...args: any[]): void;
endPhase?(...args: any[]): void;
endStage?(...args: any[]): void;
endTurn?(...args: any[]): void;
pass?(...args: any[]): void;
setActivePlayers?(...args: any[]): void;
setPhase?(...args: any[]): void;
setStage?(...args: any[]): void;
}
export interface PrivateEventsAPI {
_obj: {
isUsed(): boolean;
update(state: State): State;
};
}
/**
* Events
*/
export declare class | {
flow: Game['flow'];
playerID: PlayerID | undefined;
dispatch: Array<{
key: string;
args: any[];
phase: string;
turn: number;
}>;
constructor(flow: Game['flow'], playerID?: PlayerID);
/**
* Attaches the Events API to ctx.
* @param {object} ctx - The ctx object to attach to.
*/
api(ctx: Ctx): EventsAPI & PrivateEventsAPI;
isUsed(): boolean;
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state: State): State<any, Ctx>;
}
| Events | identifier_name |
test_cli_config.py | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
| runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log_collection else '--no-enable-log-collection'
cell_tracking_arg = '--enable-cell-tracking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_options') as persist_configuration_options:
result = runner.invoke(cli, [
'config',
'--api-token=some_test_token',
log_collection_arg,
cell_tracking_arg,
])
persist_configuration_options.assert_called_once_with({
'api_token': 'some_test_token',
'code_tracking_enabled': opt_into_cell_tracking,
'log_collection_enabled': opt_into_log_collection,
})
assert result.exit_code == 0
assert result.output == '' | identifier_body | |
test_cli_config.py | import click
import mock
import pytest
from click.testing import CliRunner
from sigopt.cli import cli
class | (object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log_collection else '--no-enable-log-collection'
cell_tracking_arg = '--enable-cell-tracking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_options') as persist_configuration_options:
result = runner.invoke(cli, [
'config',
'--api-token=some_test_token',
log_collection_arg,
cell_tracking_arg,
])
persist_configuration_options.assert_called_once_with({
'api_token': 'some_test_token',
'code_tracking_enabled': opt_into_cell_tracking,
'log_collection_enabled': opt_into_log_collection,
})
assert result.exit_code == 0
assert result.output == ''
| TestRunCli | identifier_name |
test_cli_config.py |
from sigopt.cli import cli
class TestRunCli(object):
@pytest.mark.parametrize('opt_into_log_collection', [False, True])
@pytest.mark.parametrize('opt_into_cell_tracking', [False, True])
def test_config_command(self, opt_into_log_collection, opt_into_cell_tracking):
runner = CliRunner()
log_collection_arg = '--enable-log-collection' if opt_into_log_collection else '--no-enable-log-collection'
cell_tracking_arg = '--enable-cell-tracking' if opt_into_cell_tracking else '--no-enable-cell-tracking'
with mock.patch('sigopt.cli.commands.config._config.persist_configuration_options') as persist_configuration_options:
result = runner.invoke(cli, [
'config',
'--api-token=some_test_token',
log_collection_arg,
cell_tracking_arg,
])
persist_configuration_options.assert_called_once_with({
'api_token': 'some_test_token',
'code_tracking_enabled': opt_into_cell_tracking,
'log_collection_enabled': opt_into_log_collection,
})
assert result.exit_code == 0
assert result.output == '' | import click
import mock
import pytest
from click.testing import CliRunner | random_line_split | |
gcs.rs | ::Result<url::Url> {
self.bucket.url("gcs").map_err(|s| {
io::Error::new(
io::ErrorKind::Other,
format!("error creating bucket url: {}", s),
)
})
}
}
// GCS compatible storage
#[derive(Clone)]
pub struct GCSStorage {
config: Config,
svc_access: Option<Arc<ServiceAccountAccess>>,
client: Client<HttpsConnector<HttpConnector>, Body>,
}
trait ResultExt {
type Ok;
// Maps the error of this result as an `std::io::Error` with `Other` error
// kind.
fn or_io_error<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
// Maps the error of this result as an `std::io::Error` with `InvalidInput`
// error kind.
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
}
impl<T, E: Display> ResultExt for Result<T, E> {
type Ok = T;
fn or_io_error<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}: {}", msg, e)))
}
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: {}", msg, e)))
}
}
enum RequestError {
Hyper(hyper::Error, String),
OAuth(tame_oauth::Error, String),
Gcs(tame_gcs::Error),
InvalidEndpoint(http::uri::InvalidUri),
}
impl From<http::uri::InvalidUri> for RequestError {
fn from(err: http::uri::InvalidUri) -> Self {
Self::InvalidEndpoint(err)
}
}
fn status_code_error(code: StatusCode, msg: String) -> RequestError {
RequestError::OAuth(tame_oauth::Error::HttpStatus(code), msg)
}
impl From<RequestError> for io::Error {
fn from(err: RequestError) -> Self {
match err {
RequestError::Hyper(e, msg) => {
Self::new(io::ErrorKind::InvalidInput, format!("HTTP {}: {}", msg, e))
}
RequestError::OAuth(tame_oauth::Error::Io(e), _) => e,
RequestError::OAuth(tame_oauth::Error::HttpStatus(sc), msg) => {
let fmt = format!("GCS OAuth: {}: {}", msg, sc);
match sc.as_u16() {
401 | 403 => Self::new(io::ErrorKind::PermissionDenied, fmt),
404 => Self::new(io::ErrorKind::NotFound, fmt),
_ if sc.is_server_error() => Self::new(io::ErrorKind::Interrupted, fmt),
_ => Self::new(io::ErrorKind::InvalidInput, fmt),
}
}
RequestError::OAuth(tame_oauth::Error::AuthError(e), msg) => Self::new(
io::ErrorKind::PermissionDenied,
format!("authorization failed: {}: {}", msg, e),
),
RequestError::OAuth(e, msg) => Self::new(
io::ErrorKind::InvalidInput,
format!("oauth failed: {}: {}", msg, e),
),
RequestError::Gcs(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS request: {}", e),
),
RequestError::InvalidEndpoint(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS endpoint URI: {}", e),
),
}
}
}
impl RetryError for RequestError {
fn is_retryable(&self) -> bool {
match self {
// FIXME: Inspect the error source?
Self::Hyper(e, _) => {
e.is_closed()
|| e.is_connect()
|| e.is_incomplete_message()
|| e.is_body_write_aborted()
}
// See https://cloud.google.com/storage/docs/exponential-backoff.
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::TOO_MANY_REQUESTS), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::REQUEST_TIMEOUT), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(status), _) => status.is_server_error(),
// Consider everything else not retryable.
_ => false,
}
}
}
impl GCSStorage {
pub fn from_input(input: InputConfig) -> io::Result<Self> {
Self::new(Config::from_input(input)?)
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Self> {
Self::new(Config::from_cloud_dynamic(cloud_dynamic)?)
}
/// Create a new GCS storage for the given config.
pub fn new(config: Config) -> io::Result<GCSStorage> {
let svc_access = if let Some(si) = &config.svc_info {
Some(
ServiceAccountAccess::new(si.clone())
.or_invalid_input("invalid credentials_blob")?,
)
} else {
None
};
let client = Client::builder().build(HttpsConnector::new());
Ok(GCSStorage {
config,
svc_access: svc_access.map(Arc::new),
client,
})
}
fn maybe_prefix_key(&self, key: &str) -> String {
if let Some(prefix) = &self.config.bucket.prefix {
return format!("{}/{}", prefix, key);
}
key.to_owned()
}
async fn set_auth(
&self,
req: &mut Request<Body>,
scope: tame_gcs::Scopes,
svc_access: Arc<ServiceAccountAccess>,
) -> Result<(), RequestError> {
let token_or_request = svc_access
.get_token(&[scope])
.map_err(|e| RequestError::OAuth(e, "get_token".to_string()))?;
let token = match token_or_request {
TokenOrRequest::Token(token) => token,
TokenOrRequest::Request {
request,
scope_hash,
..
} => {
let res = self
.client
.request(request.map(From::from))
.await
.map_err(|e| RequestError::Hyper(e, "set auth request".to_owned()))?;
if !res.status().is_success() |
let (parts, body) = res.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(|e| RequestError::Hyper(e, "set auth body".to_owned()))?;
svc_access
.parse_token_response(scope_hash, Response::from_parts(parts, body))
.map_err(|e| RequestError::OAuth(e, "set auth parse token".to_string()))?
}
};
req.headers_mut().insert(
http::header::AUTHORIZATION,
token
.try_into()
.map_err(|e| RequestError::OAuth(e, "set auth add auth header".to_string()))?,
);
Ok(())
}
async fn make_request(
&self,
mut req: Request<Body>,
scope: tame_gcs::Scopes,
) -> Result<Response<Body>, RequestError> {
// replace the hard-coded GCS endpoint by the custom one.
if let Some(endpoint) = &self.config.bucket.endpoint {
let uri = req.uri().to_string();
let new_url_opt = change_host(endpoint, &uri);
if let Some(new_url) = new_url_opt {
*req.uri_mut() = new_url.parse()?;
}
}
if let Some(svc_access) = &self.svc_access {
self.set_auth(&mut req, scope, svc_access.clone()).await?;
}
let uri = req.uri().to_string();
let res = self
.client
.request(req)
.await
.map_err(|e| RequestError::Hyper(e, uri.clone()))?;
if !res.status().is_success() {
return Err(status_code_error(res.status(), uri));
}
Ok(res)
}
fn error_to_async_read<E>(kind: io::ErrorKind, e: E) -> Box<dyn AsyncRead + Unpin>
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Box::new(error_stream(io::Error::new(kind, e)).into_async_read())
}
}
fn change_host(host: &StringNonEmpty, url: &str) -> Option<String> {
let new_host = (|| {
for hardcoded in HARDCODED_ENDPOINTS_SUFFIX {
if let Some(res) = host.strip_suffix(hardcoded) {
return StringNonEmpty::opt(res.to_owned()).unwrap();
}
}
host.to_owned()
})();
if let Some(res) = url.strip_prefix(GOOGLE_APIS) {
return Some([new_host.trim_end_matches('/'), res].concat());
}
None
}
// Convert manually since they don't implement FromStr.
fn parse_storage_class(sc: &str) -> Result<Option<StorageClass>, &str> {
Ok(Some(match sc {
"" => return Ok(None),
" | {
return Err(status_code_error(
res.status(),
"set auth request".to_string(),
));
} | conditional_block |
gcs.rs | , uri.clone()))?;
if !res.status().is_success() {
return Err(status_code_error(res.status(), uri));
}
Ok(res)
}
fn error_to_async_read<E>(kind: io::ErrorKind, e: E) -> Box<dyn AsyncRead + Unpin>
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Box::new(error_stream(io::Error::new(kind, e)).into_async_read())
}
}
fn change_host(host: &StringNonEmpty, url: &str) -> Option<String> {
let new_host = (|| {
for hardcoded in HARDCODED_ENDPOINTS_SUFFIX {
if let Some(res) = host.strip_suffix(hardcoded) {
return StringNonEmpty::opt(res.to_owned()).unwrap();
}
}
host.to_owned()
})();
if let Some(res) = url.strip_prefix(GOOGLE_APIS) {
return Some([new_host.trim_end_matches('/'), res].concat());
}
None
}
// Convert manually since they don't implement FromStr.
fn parse_storage_class(sc: &str) -> Result<Option<StorageClass>, &str> {
Ok(Some(match sc {
"" => return Ok(None),
"STANDARD" => StorageClass::Standard,
"NEARLINE" => StorageClass::Nearline,
"COLDLINE" => StorageClass::Coldline,
"DURABLE_REDUCED_AVAILABILITY" => StorageClass::DurableReducedAvailability,
"REGIONAL" => StorageClass::Regional,
"MULTI_REGIONAL" => StorageClass::MultiRegional,
_ => return Err(sc),
}))
}
fn parse_predefined_acl(acl: &str) -> Result<Option<PredefinedAcl>, &str> {
Ok(Some(match acl {
"" => return Ok(None),
"authenticatedRead" => PredefinedAcl::AuthenticatedRead,
"bucketOwnerFullControl" => PredefinedAcl::BucketOwnerFullControl,
"bucketOwnerRead" => PredefinedAcl::BucketOwnerRead,
"private" => PredefinedAcl::Private,
"projectPrivate" => PredefinedAcl::ProjectPrivate,
"publicRead" => PredefinedAcl::PublicRead,
_ => return Err(acl),
}))
}
const STORAGE_NAME: &str = "gcs";
impl BlobStorage for GCSStorage {
fn config(&self) -> Box<dyn BlobConfig> {
Box::new(self.config.clone()) as Box<dyn BlobConfig>
}
fn put(
&self,
name: &str,
mut reader: Box<dyn AsyncRead + Send + Unpin>,
content_length: u64,
) -> io::Result<()> {
if content_length == 0 {
// It is probably better to just write the empty file
// However, currently going forward results in a body write aborted error
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"no content to write",
));
}
use std::convert::TryFrom;
let key = self.maybe_prefix_key(name);
debug!("save file to GCS storage"; "key" => %key);
let bucket = BucketName::try_from(self.config.bucket.bucket.to_string())
.or_invalid_input(format_args!("invalid bucket {}", self.config.bucket.bucket))?;
let metadata = Metadata {
name: Some(key),
storage_class: self.config.storage_class,
..Default::default()
};
block_on_external_io(async move {
// FIXME: Switch to upload() API so we don't need to read the entire data into memory
// in order to retry.
let mut data = Vec::with_capacity(content_length as usize);
reader.read_to_end(&mut data).await?;
retry(|| async {
let data = Cursor::new(data.clone());
let req = Object::insert_multipart(
&bucket,
data,
content_length,
&metadata,
Some(InsertObjectOptional {
predefined_acl: self.config.predefined_acl,
..Default::default()
}),
)
.map_err(RequestError::Gcs)?
.map(|reader| Body::wrap_stream(AsyncReadAsSyncStreamOfBytes::new(reader)));
self.make_request(req, tame_gcs::Scopes::ReadWrite).await
})
.await?;
Ok::<_, io::Error>(())
})?;
Ok(())
}
fn get(&self, name: &str) -> Box<dyn AsyncRead + Unpin + '_> {
let bucket = self.config.bucket.bucket.to_string();
let name = self.maybe_prefix_key(name);
debug!("read file from GCS storage"; "key" => %name);
let oid = match ObjectId::new(bucket, name) {
Ok(oid) => oid,
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::InvalidInput, e),
};
let request = match Object::download(&oid, None /*optional*/) {
Ok(request) => request.map(|_: io::Empty| Body::empty()),
Err(e) => return GCSStorage::error_to_async_read(io::ErrorKind::Other, e),
};
Box::new(
self.make_request(request, tame_gcs::Scopes::ReadOnly)
.and_then(|response| async {
if response.status().is_success() {
Ok(response.into_body().map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("download from GCS error: {}", e),
)
}))
} else {
Err(status_code_error(
response.status(),
"bucket read".to_string(),
))
}
})
.err_into::<io::Error>()
.try_flatten_stream()
.boxed() // this `.boxed()` pin the stream.
.into_async_read(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use matches::assert_matches;
const HARDCODED_ENDPOINTS: &[&str] = &[
"https://www.googleapis.com/upload/storage/v1",
"https://www.googleapis.com/storage/v1",
];
#[test]
fn test_change_host() {
let host = StringNonEmpty::static_str("http://localhost:4443");
assert_eq!(
&change_host(&host, &format!("{}/storage/v1/foo", GOOGLE_APIS)).unwrap(),
"http://localhost:4443/storage/v1/foo"
);
let h1 = url::Url::parse(HARDCODED_ENDPOINTS[0]).unwrap();
let h2 = url::Url::parse(HARDCODED_ENDPOINTS[1]).unwrap();
let endpoint = StringNonEmpty::static_str("http://example.com");
assert_eq!(
&change_host(&endpoint, h1.as_str()).unwrap(),
"http://example.com/upload/storage/v1"
);
assert_eq!(
&change_host(&endpoint, h2.as_str()).unwrap(),
"http://example.com/storage/v1"
);
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
assert_matches!(&change_host(&endpoint, "foo"), None);
// if we get the endpoint with suffix "/storage/v1/"
let endpoint = StringNonEmpty::static_str("http://example.com/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
let endpoint = StringNonEmpty::static_str("http://example.com/upload/storage/v1/");
assert_eq!(
&change_host(&endpoint, &format!("{}/foo", h2)).unwrap(),
"http://example.com/storage/v1/foo"
);
}
#[test]
fn test_parse_storage_class() {
assert_matches!(
parse_storage_class("STANDARD"),
Ok(Some(StorageClass::Standard))
);
assert_matches!(parse_storage_class(""), Ok(None));
assert_matches!(
parse_storage_class("NOT_A_STORAGE_CLASS"),
Err("NOT_A_STORAGE_CLASS")
);
}
#[test]
fn test_parse_acl() {
// can't use assert_matches!(), PredefinedAcl doesn't even implement Debug.
assert!(matches!(
parse_predefined_acl("private"),
Ok(Some(PredefinedAcl::Private))
));
assert!(matches!(parse_predefined_acl(""), Ok(None)));
assert!(matches!(parse_predefined_acl("notAnACL"), Err("notAnACL")));
}
#[test]
fn test_url_of_backend() {
let bucket_name = StringNonEmpty::static_str("bucket");
let mut bucket = BucketConf::default(bucket_name);
bucket.prefix = Some(StringNonEmpty::static_str("/backup 02/prefix/"));
let gcs = Config::default(bucket.clone());
// only 'bucket' and 'prefix' should be visible in url_of_backend()
assert_eq!(
gcs.url().unwrap().to_string(),
"gcs://bucket/backup%2002/prefix/"
);
bucket.endpoint = Some(StringNonEmpty::static_str("http://endpoint.com"));
assert_eq!(
&Config::default(bucket).url().unwrap().to_string(),
"http://endpoint.com/bucket/backup%2002/prefix/"
);
}
#[test]
fn | test_config_round_trip | identifier_name | |
gcs.rs |
fn deserialize_service_account_info(
cred: StringNonEmpty,
) -> std::result::Result<ServiceAccountInfo, RequestError> {
ServiceAccountInfo::deserialize(cred.to_string())
.map_err(|e| RequestError::OAuth(e, "deserialize ServiceAccountInfo".to_string()))
}
impl BlobConfig for Config {
fn name(&self) -> &'static str {
STORAGE_NAME
}
fn url(&self) -> io::Result<url::Url> {
self.bucket.url("gcs").map_err(|s| {
io::Error::new(
io::ErrorKind::Other,
format!("error creating bucket url: {}", s),
)
})
}
}
// GCS compatible storage
#[derive(Clone)]
pub struct GCSStorage {
config: Config,
svc_access: Option<Arc<ServiceAccountAccess>>,
client: Client<HttpsConnector<HttpConnector>, Body>,
}
trait ResultExt {
type Ok;
// Maps the error of this result as an `std::io::Error` with `Other` error
// kind.
fn or_io_error<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
// Maps the error of this result as an `std::io::Error` with `InvalidInput`
// error kind.
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
}
impl<T, E: Display> ResultExt for Result<T, E> {
type Ok = T;
fn or_io_error<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}: {}", msg, e)))
}
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: {}", msg, e)))
}
}
enum RequestError {
Hyper(hyper::Error, String),
OAuth(tame_oauth::Error, String),
Gcs(tame_gcs::Error),
InvalidEndpoint(http::uri::InvalidUri),
}
impl From<http::uri::InvalidUri> for RequestError {
fn from(err: http::uri::InvalidUri) -> Self {
Self::InvalidEndpoint(err)
}
}
fn status_code_error(code: StatusCode, msg: String) -> RequestError {
RequestError::OAuth(tame_oauth::Error::HttpStatus(code), msg)
}
impl From<RequestError> for io::Error {
fn from(err: RequestError) -> Self {
match err {
RequestError::Hyper(e, msg) => {
Self::new(io::ErrorKind::InvalidInput, format!("HTTP {}: {}", msg, e))
}
RequestError::OAuth(tame_oauth::Error::Io(e), _) => e,
RequestError::OAuth(tame_oauth::Error::HttpStatus(sc), msg) => {
let fmt = format!("GCS OAuth: {}: {}", msg, sc);
match sc.as_u16() {
401 | 403 => Self::new(io::ErrorKind::PermissionDenied, fmt),
404 => Self::new(io::ErrorKind::NotFound, fmt),
_ if sc.is_server_error() => Self::new(io::ErrorKind::Interrupted, fmt),
_ => Self::new(io::ErrorKind::InvalidInput, fmt),
}
}
RequestError::OAuth(tame_oauth::Error::AuthError(e), msg) => Self::new(
io::ErrorKind::PermissionDenied,
format!("authorization failed: {}: {}", msg, e),
),
RequestError::OAuth(e, msg) => Self::new(
io::ErrorKind::InvalidInput,
format!("oauth failed: {}: {}", msg, e),
),
RequestError::Gcs(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS request: {}", e),
),
RequestError::InvalidEndpoint(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS endpoint URI: {}", e),
),
}
}
}
impl RetryError for RequestError {
fn is_retryable(&self) -> bool {
match self {
// FIXME: Inspect the error source?
Self::Hyper(e, _) => {
e.is_closed()
|| e.is_connect()
|| e.is_incomplete_message()
|| e.is_body_write_aborted()
}
// See https://cloud.google.com/storage/docs/exponential-backoff.
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::TOO_MANY_REQUESTS), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::REQUEST_TIMEOUT), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(status), _) => status.is_server_error(),
// Consider everything else not retryable.
_ => false,
}
}
}
impl GCSStorage {
pub fn from_input(input: InputConfig) -> io::Result<Self> {
Self::new(Config::from_input(input)?)
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Self> {
Self::new(Config::from_cloud_dynamic(cloud_dynamic)?)
}
/// Create a new GCS storage for the given config.
pub fn new(config: Config) -> io::Result<GCSStorage> {
let svc_access = if let Some(si) = &config.svc_info {
Some(
ServiceAccountAccess::new(si.clone())
.or_invalid_input("invalid credentials_blob")?,
)
} else {
None
};
let client = Client::builder().build(HttpsConnector::new());
Ok(GCSStorage {
config,
svc_access: svc_access.map(Arc::new),
client,
})
}
fn maybe_prefix_key(&self, key: &str) -> String {
if let Some(prefix) = &self.config.bucket.prefix {
return format!("{}/{}", prefix, key);
}
key.to_owned()
}
async fn set_auth(
&self,
req: &mut Request<Body>,
scope: tame_gcs::Scopes,
svc_access: Arc<ServiceAccountAccess>,
) -> Result<(), RequestError> {
let token_or_request = svc_access
.get_token(&[scope])
.map_err(|e| RequestError::OAuth(e, "get_token".to_string()))?;
let token = match token_or_request {
TokenOrRequest::Token(token) => token,
TokenOrRequest::Request {
request,
scope_hash,
..
} => {
let res = self
.client
.request(request.map(From::from))
.await
.map_err(|e| RequestError::Hyper(e, "set auth request".to_owned()))?;
if !res.status().is_success() {
return Err(status_code_error(
res.status(),
"set auth request".to_string(),
));
}
let (parts, body) = res.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(|e| RequestError::Hyper(e, "set auth body".to_owned()))?;
svc_access
.parse_token_response(scope_hash, Response::from_parts(parts, body))
.map_err(|e| RequestError::OAuth(e, "set auth parse token".to_string()))?
}
};
req.headers_mut().insert(
http::header::AUTHORIZATION,
token
.try_into()
.map_err(|e| RequestError::OAuth(e, "set auth add auth header".to_string()))?,
);
Ok(())
}
async fn make_request(
&self,
mut req: Request<Body>,
scope: tame_gcs::Scopes,
) -> Result<Response<Body>, RequestError> {
// replace the hard-coded GCS endpoint by the custom one.
if let Some(endpoint) = &self.config.bucket.endpoint {
let uri = req.uri().to_string();
let new_url_opt = change_host(endpoint, &uri);
if let Some(new_url) = new_url_opt {
*req.uri_mut() = new_url.parse()?;
}
}
if let Some(svc_access) = &self.svc_access {
self.set_auth(&mut req, scope, svc_access.clone()).await?;
}
let uri = req.uri().to_string();
let res = self
.client
.request(req)
.await
.map_err(|e| RequestError::Hyper(e, uri.clone()))?;
if !res.status().is_success() {
return Err(status_code_error(res.status(), uri));
}
Ok(res)
}
fn error_to_async_read<E>(kind: io::ErrorKind, e: E) -> Box<dyn AsyncRead + Unpin>
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Box::new(error_stream(io::Error::new(kind, e)).into_async_read())
}
}
fn change_host(host: &StringNonEmpty, url: &str) -> Option<String> {
let new_host = (|| {
for hardcoded in HARDCODED_ENDPOINTS_SUFFIX {
if let Some(res) = host.strip_suffix(hardcoded) {
return StringNonEmpty::opt | storage_class,
})
}
} | random_line_split | |
gcs.rs | ::Result<url::Url> {
self.bucket.url("gcs").map_err(|s| {
io::Error::new(
io::ErrorKind::Other,
format!("error creating bucket url: {}", s),
)
})
}
}
// GCS compatible storage
#[derive(Clone)]
pub struct GCSStorage {
config: Config,
svc_access: Option<Arc<ServiceAccountAccess>>,
client: Client<HttpsConnector<HttpConnector>, Body>,
}
trait ResultExt {
type Ok;
// Maps the error of this result as an `std::io::Error` with `Other` error
// kind.
fn or_io_error<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
// Maps the error of this result as an `std::io::Error` with `InvalidInput`
// error kind.
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<Self::Ok>;
}
impl<T, E: Display> ResultExt for Result<T, E> {
type Ok = T;
fn or_io_error<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("{}: {}", msg, e)))
}
fn or_invalid_input<D: Display>(self, msg: D) -> io::Result<T> {
self.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: {}", msg, e)))
}
}
enum RequestError {
Hyper(hyper::Error, String),
OAuth(tame_oauth::Error, String),
Gcs(tame_gcs::Error),
InvalidEndpoint(http::uri::InvalidUri),
}
impl From<http::uri::InvalidUri> for RequestError {
fn from(err: http::uri::InvalidUri) -> Self {
Self::InvalidEndpoint(err)
}
}
fn status_code_error(code: StatusCode, msg: String) -> RequestError {
RequestError::OAuth(tame_oauth::Error::HttpStatus(code), msg)
}
impl From<RequestError> for io::Error {
fn from(err: RequestError) -> Self {
match err {
RequestError::Hyper(e, msg) => {
Self::new(io::ErrorKind::InvalidInput, format!("HTTP {}: {}", msg, e))
}
RequestError::OAuth(tame_oauth::Error::Io(e), _) => e,
RequestError::OAuth(tame_oauth::Error::HttpStatus(sc), msg) => {
let fmt = format!("GCS OAuth: {}: {}", msg, sc);
match sc.as_u16() {
401 | 403 => Self::new(io::ErrorKind::PermissionDenied, fmt),
404 => Self::new(io::ErrorKind::NotFound, fmt),
_ if sc.is_server_error() => Self::new(io::ErrorKind::Interrupted, fmt),
_ => Self::new(io::ErrorKind::InvalidInput, fmt),
}
}
RequestError::OAuth(tame_oauth::Error::AuthError(e), msg) => Self::new(
io::ErrorKind::PermissionDenied,
format!("authorization failed: {}: {}", msg, e),
),
RequestError::OAuth(e, msg) => Self::new(
io::ErrorKind::InvalidInput,
format!("oauth failed: {}: {}", msg, e),
),
RequestError::Gcs(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS request: {}", e),
),
RequestError::InvalidEndpoint(e) => Self::new(
io::ErrorKind::InvalidInput,
format!("invalid GCS endpoint URI: {}", e),
),
}
}
}
impl RetryError for RequestError {
fn is_retryable(&self) -> bool {
match self {
// FIXME: Inspect the error source?
Self::Hyper(e, _) => {
e.is_closed()
|| e.is_connect()
|| e.is_incomplete_message()
|| e.is_body_write_aborted()
}
// See https://cloud.google.com/storage/docs/exponential-backoff.
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::TOO_MANY_REQUESTS), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(StatusCode::REQUEST_TIMEOUT), _) => true,
Self::OAuth(tame_oauth::Error::HttpStatus(status), _) => status.is_server_error(),
// Consider everything else not retryable.
_ => false,
}
}
}
impl GCSStorage {
pub fn from_input(input: InputConfig) -> io::Result<Self> {
Self::new(Config::from_input(input)?)
}
pub fn from_cloud_dynamic(cloud_dynamic: &CloudDynamic) -> io::Result<Self> {
Self::new(Config::from_cloud_dynamic(cloud_dynamic)?)
}
/// Create a new GCS storage for the given config.
pub fn new(config: Config) -> io::Result<GCSStorage> {
let svc_access = if let Some(si) = &config.svc_info {
Some(
ServiceAccountAccess::new(si.clone())
.or_invalid_input("invalid credentials_blob")?,
)
} else {
None
};
let client = Client::builder().build(HttpsConnector::new());
Ok(GCSStorage {
config,
svc_access: svc_access.map(Arc::new),
client,
})
}
fn maybe_prefix_key(&self, key: &str) -> String {
if let Some(prefix) = &self.config.bucket.prefix {
return format!("{}/{}", prefix, key);
}
key.to_owned()
}
async fn set_auth(
&self,
req: &mut Request<Body>,
scope: tame_gcs::Scopes,
svc_access: Arc<ServiceAccountAccess>,
) -> Result<(), RequestError> | ));
}
let (parts, body) = res.into_parts();
let body = hyper::body::to_bytes(body)
.await
.map_err(|e| RequestError::Hyper(e, "set auth body".to_owned()))?;
svc_access
.parse_token_response(scope_hash, Response::from_parts(parts, body))
.map_err(|e| RequestError::OAuth(e, "set auth parse token".to_string()))?
}
};
req.headers_mut().insert(
http::header::AUTHORIZATION,
token
.try_into()
.map_err(|e| RequestError::OAuth(e, "set auth add auth header".to_string()))?,
);
Ok(())
}
async fn make_request(
&self,
mut req: Request<Body>,
scope: tame_gcs::Scopes,
) -> Result<Response<Body>, RequestError> {
// replace the hard-coded GCS endpoint by the custom one.
if let Some(endpoint) = &self.config.bucket.endpoint {
let uri = req.uri().to_string();
let new_url_opt = change_host(endpoint, &uri);
if let Some(new_url) = new_url_opt {
*req.uri_mut() = new_url.parse()?;
}
}
if let Some(svc_access) = &self.svc_access {
self.set_auth(&mut req, scope, svc_access.clone()).await?;
}
let uri = req.uri().to_string();
let res = self
.client
.request(req)
.await
.map_err(|e| RequestError::Hyper(e, uri.clone()))?;
if !res.status().is_success() {
return Err(status_code_error(res.status(), uri));
}
Ok(res)
}
fn error_to_async_read<E>(kind: io::ErrorKind, e: E) -> Box<dyn AsyncRead + Unpin>
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Box::new(error_stream(io::Error::new(kind, e)).into_async_read())
}
}
fn change_host(host: &StringNonEmpty, url: &str) -> Option<String> {
let new_host = (|| {
for hardcoded in HARDCODED_ENDPOINTS_SUFFIX {
if let Some(res) = host.strip_suffix(hardcoded) {
return StringNonEmpty::opt(res.to_owned()).unwrap();
}
}
host.to_owned()
})();
if let Some(res) = url.strip_prefix(GOOGLE_APIS) {
return Some([new_host.trim_end_matches('/'), res].concat());
}
None
}
// Convert manually since they don't implement FromStr.
fn parse_storage_class(sc: &str) -> Result<Option<StorageClass>, &str> {
Ok(Some(match sc {
"" => return Ok(None),
"ST | {
let token_or_request = svc_access
.get_token(&[scope])
.map_err(|e| RequestError::OAuth(e, "get_token".to_string()))?;
let token = match token_or_request {
TokenOrRequest::Token(token) => token,
TokenOrRequest::Request {
request,
scope_hash,
..
} => {
let res = self
.client
.request(request.map(From::from))
.await
.map_err(|e| RequestError::Hyper(e, "set auth request".to_owned()))?;
if !res.status().is_success() {
return Err(status_code_error(
res.status(),
"set auth request".to_string(), | identifier_body |
setup.py | from distutils.core import setup
import sys
import py2exe
try:
scriptName = sys.argv[3]
except IndexError:
print "Usage: python setup.py py2exe -i nombreApp"
| setup(
name=scriptName,
version="2.0",
description="Aplicacion Python creada con py2exe",
author="Pueyo Luciano",
author_email="PueyoLuciano.getMail()",
url="http://cafeidotica.blogspot.com.ar/",
license="Mozilla Public License 2.0",
scripts=[scriptName + ".py"],
console=[{"script":scriptName + ".py", "icon_resources": [(1, "pyc.ico")]}],
options={"py2exe": {"bundle_files": 1}},
zipfile=None,
# windows=[{"script":scriptName + ".py" , "icon_resources": [(1, "pyc.ico")] }] <<-- si configuras el windows, corre el .exe como un proceso.
) | sys.exit(2)
# Para crear el exe hay que ir al cmd y correr python setup.py py2exe
| random_line_split |
interaction-helper.ts |
import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character';
import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static tryToOpenDoor(player: Character, door, { gameState }): boolean {
door.properties = door.properties || {};
const { requireLockpick, skillRequired, requireHeld, requireEventToOpen, lockedIfAlive } = door.properties;
if(requireEventToOpen) return false;
if(!door.isOpen
&& (requireLockpick || requireHeld || lockedIfAlive)) {
let shouldOpen = false;
if(player.rightHand && player.rightHand.itemClass === 'Key') {
if(player.rightHand.isBroken()) |
if(requireHeld && player.hasHeldItem(requireHeld)) {
shouldOpen = true;
player.rightHand.condition -= 1000;
} else {
player.sendClientMessage('The key snapped off in the lock!');
player.rightHand.condition = 0;
return;
}
}
/** PERK:CLASS:THIEF:Thieves can pick locks. */
if(requireLockpick
&& skillRequired
&& player.baseClass === 'Thief'
&& player.hasHeldItem('Lockpick', 'right')) {
const playerSkill = player.calcSkillLevel(SkillClassNames.Thievery) + player.getTraitLevel('LockpickSpecialty');
if(playerSkill < skillRequired) {
player.sendClientMessage('You are not skilled enough to pick this lock.');
return false;
}
player.gainSkill(SkillClassNames.Thievery, skillRequired);
player.sendClientMessage('You successfully picked the lock!');
player.setRightHand(null);
shouldOpen = true;
}
if(lockedIfAlive) {
const isNPCAlive = find(values(player.$$room.state.mapNPCs), { npcId: lockedIfAlive });
if(!isNPCAlive || (isNPCAlive && isNPCAlive.isDead())) {
shouldOpen = true;
} else {
player.sendClientMessage('The door is sealed shut by a magical force.');
return false;
}
}
if(!shouldOpen) {
player.sendClientMessage('The door is locked.');
return false;
}
}
if(door.isOpen) {
const allInDoor = player.$$room.state.getAllInRangeRaw({ x: door.x / 64, y: (door.y / 64) - 1 }, 0);
if(allInDoor.length > 0) {
player.sendClientMessage('Something is blocking the door.');
return false;
}
}
player.sendClientMessage({ message: door.isOpen ? 'You close the door.' : 'You open the door.', sfx: door.isOpen ? 'env-door-close' : 'env-door-open' });
gameState.toggleDoor(door);
return true;
}
}
| {
player.sendClientMessage('That key is not currently usable!');
return;
} | conditional_block |
interaction-helper.ts |
import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character';
import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static | (player: Character, door, { gameState }): boolean {
door.properties = door.properties || {};
const { requireLockpick, skillRequired, requireHeld, requireEventToOpen, lockedIfAlive } = door.properties;
if(requireEventToOpen) return false;
if(!door.isOpen
&& (requireLockpick || requireHeld || lockedIfAlive)) {
let shouldOpen = false;
if(player.rightHand && player.rightHand.itemClass === 'Key') {
if(player.rightHand.isBroken()) {
player.sendClientMessage('That key is not currently usable!');
return;
}
if(requireHeld && player.hasHeldItem(requireHeld)) {
shouldOpen = true;
player.rightHand.condition -= 1000;
} else {
player.sendClientMessage('The key snapped off in the lock!');
player.rightHand.condition = 0;
return;
}
}
/** PERK:CLASS:THIEF:Thieves can pick locks. */
if(requireLockpick
&& skillRequired
&& player.baseClass === 'Thief'
&& player.hasHeldItem('Lockpick', 'right')) {
const playerSkill = player.calcSkillLevel(SkillClassNames.Thievery) + player.getTraitLevel('LockpickSpecialty');
if(playerSkill < skillRequired) {
player.sendClientMessage('You are not skilled enough to pick this lock.');
return false;
}
player.gainSkill(SkillClassNames.Thievery, skillRequired);
player.sendClientMessage('You successfully picked the lock!');
player.setRightHand(null);
shouldOpen = true;
}
if(lockedIfAlive) {
const isNPCAlive = find(values(player.$$room.state.mapNPCs), { npcId: lockedIfAlive });
if(!isNPCAlive || (isNPCAlive && isNPCAlive.isDead())) {
shouldOpen = true;
} else {
player.sendClientMessage('The door is sealed shut by a magical force.');
return false;
}
}
if(!shouldOpen) {
player.sendClientMessage('The door is locked.');
return false;
}
}
if(door.isOpen) {
const allInDoor = player.$$room.state.getAllInRangeRaw({ x: door.x / 64, y: (door.y / 64) - 1 }, 0);
if(allInDoor.length > 0) {
player.sendClientMessage('Something is blocking the door.');
return false;
}
}
player.sendClientMessage({ message: door.isOpen ? 'You close the door.' : 'You open the door.', sfx: door.isOpen ? 'env-door-close' : 'env-door-open' });
gameState.toggleDoor(door);
return true;
}
}
| tryToOpenDoor | identifier_name |
interaction-helper.ts | import { SkillClassNames } from '../../../shared/interfaces/character';
export class InteractionHelper {
static tryToOpenDoor(player: Character, door, { gameState }): boolean {
door.properties = door.properties || {};
const { requireLockpick, skillRequired, requireHeld, requireEventToOpen, lockedIfAlive } = door.properties;
if(requireEventToOpen) return false;
if(!door.isOpen
&& (requireLockpick || requireHeld || lockedIfAlive)) {
let shouldOpen = false;
if(player.rightHand && player.rightHand.itemClass === 'Key') {
if(player.rightHand.isBroken()) {
player.sendClientMessage('That key is not currently usable!');
return;
}
if(requireHeld && player.hasHeldItem(requireHeld)) {
shouldOpen = true;
player.rightHand.condition -= 1000;
} else {
player.sendClientMessage('The key snapped off in the lock!');
player.rightHand.condition = 0;
return;
}
}
/** PERK:CLASS:THIEF:Thieves can pick locks. */
if(requireLockpick
&& skillRequired
&& player.baseClass === 'Thief'
&& player.hasHeldItem('Lockpick', 'right')) {
const playerSkill = player.calcSkillLevel(SkillClassNames.Thievery) + player.getTraitLevel('LockpickSpecialty');
if(playerSkill < skillRequired) {
player.sendClientMessage('You are not skilled enough to pick this lock.');
return false;
}
player.gainSkill(SkillClassNames.Thievery, skillRequired);
player.sendClientMessage('You successfully picked the lock!');
player.setRightHand(null);
shouldOpen = true;
}
if(lockedIfAlive) {
const isNPCAlive = find(values(player.$$room.state.mapNPCs), { npcId: lockedIfAlive });
if(!isNPCAlive || (isNPCAlive && isNPCAlive.isDead())) {
shouldOpen = true;
} else {
player.sendClientMessage('The door is sealed shut by a magical force.');
return false;
}
}
if(!shouldOpen) {
player.sendClientMessage('The door is locked.');
return false;
}
}
if(door.isOpen) {
const allInDoor = player.$$room.state.getAllInRangeRaw({ x: door.x / 64, y: (door.y / 64) - 1 }, 0);
if(allInDoor.length > 0) {
player.sendClientMessage('Something is blocking the door.');
return false;
}
}
player.sendClientMessage({ message: door.isOpen ? 'You close the door.' : 'You open the door.', sfx: door.isOpen ? 'env-door-close' : 'env-door-open' });
gameState.toggleDoor(door);
return true;
}
} | import { find, values } from 'lodash';
import { Character } from '../../../shared/models/character'; | random_line_split | |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } from '../../../src/config/error-handling';
import gql from 'graphql-tag';
import { makeExecutableSchema } from '@graphql-tools/schema';
const errorClient: GraphQLClient = {
| (query, vars, context, introspection): Promise<ExecutionResult> {
throw new Error(introspection ? 'Throwing introspection' : 'Throwing query');
}
};
const normalSchema = makeExecutableSchema({
// ZInner should be alphabeticaly after Query so that joining occurs before linking (to test another error case)
typeDefs: gql`type ZInner { field: String } type Query { inner: ZInner, inners: [ZInner] }`,
resolvers: {
Query: {
inner() {
return { field: 'hello' };
},
inners() {
return [ { field: 'hello' }, { field: 'world' } ];
}
}
}
});
export async function getConfig(): Promise<WeavingConfig> {
return {
endpoints: [
{
client: errorClient,
identifier: 'namespaceless-erroneous'
},
{
namespace: 'erroneous',
client: errorClient
},
{
namespace: 'erroneousPrefixed',
typePrefix: 'Erroneous',
client: errorClient
},
{
namespace: 'working',
typePrefix: 'Working',
schema: defaultTestSchema
},
{
namespace: 'linkConfigError',
typePrefix: 'LinkConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: false
}
}
}
},
{
namespace: 'joinConfigError',
typePrefix: 'joinConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: true,
keyField: 'key'
}
},
'Query.inners': {
join: {
linkField: 'field'
}
}
}
},
],
errorHandling: WeavingErrorHandlingMode.CONTINUE_AND_REPORT_IN_SCHEMA
};
}
| execute | identifier_name |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } from '../../../src/config/error-handling';
import gql from 'graphql-tag';
import { makeExecutableSchema } from '@graphql-tools/schema';
const errorClient: GraphQLClient = {
execute(query, vars, context, introspection): Promise<ExecutionResult> {
throw new Error(introspection ? 'Throwing introspection' : 'Throwing query');
}
};
const normalSchema = makeExecutableSchema({
// ZInner should be alphabeticaly after Query so that joining occurs before linking (to test another error case)
typeDefs: gql`type ZInner { field: String } type Query { inner: ZInner, inners: [ZInner] }`,
resolvers: {
Query: {
inner() {
return { field: 'hello' };
},
inners() {
return [ { field: 'hello' }, { field: 'world' } ];
}
}
}
});
export async function getConfig(): Promise<WeavingConfig> {
return {
endpoints: [
{
client: errorClient,
identifier: 'namespaceless-erroneous'
},
{
namespace: 'erroneous',
client: errorClient
},
{
namespace: 'erroneousPrefixed',
typePrefix: 'Erroneous',
client: errorClient
},
{
namespace: 'working',
typePrefix: 'Working',
schema: defaultTestSchema | fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: false
}
}
}
},
{
namespace: 'joinConfigError',
typePrefix: 'joinConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: true,
keyField: 'key'
}
},
'Query.inners': {
join: {
linkField: 'field'
}
}
}
},
],
errorHandling: WeavingErrorHandlingMode.CONTINUE_AND_REPORT_IN_SCHEMA
};
} | },
{
namespace: 'linkConfigError',
typePrefix: 'LinkConfigError',
schema: normalSchema, | random_line_split |
endpoint-schema-errors-continue.config.ts | import { WeavingConfig } from '../../../src/config/weaving-config';
import { GraphQLClient } from '../../../src/graphql-client/graphql-client';
import { ExecutionResult } from 'graphql';
import { defaultTestSchema } from '../../helpers/grapqhl-http-test/graphql-http-test-schema';
import { WeavingErrorHandlingMode } from '../../../src/config/error-handling';
import gql from 'graphql-tag';
import { makeExecutableSchema } from '@graphql-tools/schema';
const errorClient: GraphQLClient = {
execute(query, vars, context, introspection): Promise<ExecutionResult> {
throw new Error(introspection ? 'Throwing introspection' : 'Throwing query');
}
};
const normalSchema = makeExecutableSchema({
// ZInner should be alphabeticaly after Query so that joining occurs before linking (to test another error case)
typeDefs: gql`type ZInner { field: String } type Query { inner: ZInner, inners: [ZInner] }`,
resolvers: {
Query: {
inner() {
return { field: 'hello' };
},
inners() {
return [ { field: 'hello' }, { field: 'world' } ];
}
}
}
});
export async function getConfig(): Promise<WeavingConfig> | },
{
namespace: 'linkConfigError',
typePrefix: 'LinkConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: false
}
}
}
},
{
namespace: 'joinConfigError',
typePrefix: 'joinConfigError',
schema: normalSchema,
fieldMetadata: {
'ZInner.field': {
link: {
field: 'nonexisting',
argument: 'id',
batchMode: true,
keyField: 'key'
}
},
'Query.inners': {
join: {
linkField: 'field'
}
}
}
},
],
errorHandling: WeavingErrorHandlingMode.CONTINUE_AND_REPORT_IN_SCHEMA
};
}
| {
return {
endpoints: [
{
client: errorClient,
identifier: 'namespaceless-erroneous'
},
{
namespace: 'erroneous',
client: errorClient
},
{
namespace: 'erroneousPrefixed',
typePrefix: 'Erroneous',
client: errorClient
},
{
namespace: 'working',
typePrefix: 'Working',
schema: defaultTestSchema | identifier_body |
lib.rs | grammar you would have
//! written with other parser approaches.
//!
//! This gives us a few advantages:
//!
//! - The parsers are small and easy to write
//! - The parsers components are easy to reuse (if they're general enough, please add them to nom!)
//! - The parsers components are easy to test separately (unit tests and property-based tests)
//! - The parser combination code looks close to the grammar you would have written
//! - You can build partial parsers, specific to the data you need at the moment, and ignore the rest
//!
//! Here is an example of one such parser, to recognize text between parentheses:
//!
//! ```rust
//! use nom::{
//! IResult,
//! sequence::delimited,
//! // see the "streaming/complete" paragraph lower for an explanation of these submodules
//! character::complete::char,
//! bytes::complete::is_not
//! };
//!
//! fn parens(input: &str) -> IResult<&str, &str> {
//! delimited(char('('), is_not(")"), char(')'))(input)
//! }
//! ```
//!
//! It defines a function named `parens` which will recognize a sequence of the
//! character `(`, the longest byte array not containing `)`, then the character
//! `)`, and will return the byte array in the middle.
//!
//! Here is another parser, written without using nom's combinators this time:
//!
//! ```rust
//! use nom::{IResult, Err, Needed};
//!
//! # fn main() {
//! fn take4(i: &[u8]) -> IResult<&[u8], &[u8]>{
//! if i.len() < 4 {
//! Err(Err::Incomplete(Needed::new(4)))
//! } else {
//! Ok((&i[4..], &i[0..4]))
//! }
//! }
//! # }
//! ```
//!
//! This function takes a byte array as input, and tries to consume 4 bytes.
//! Writing all the parsers manually, like this, is dangerous, despite Rust's
//! safety features. There are still a lot of mistakes one can make. That's why
//! nom provides a list of functions to help in developing parsers.
//!
//! With functions, you would write it like this:
//!
//! ```rust
//! use nom::{IResult, bytes::streaming::take};
//! fn take4(input: &str) -> IResult<&str, &str> {
//! take(4u8)(input)
//! }
//! ```
//!
//! A parser in nom is a function which, for an input type `I`, an output type `O`
//! and an optional error type `E`, will have the following signature:
//!
//! ```rust,compile_fail
//! fn parser(input: I) -> IResult<I, O, E>;
//! ```
//!
//! Or like this, if you don't want to specify a custom error type (it will be `(I, ErrorKind)` by default):
//!
//! ```rust,compile_fail
//! fn parser(input: I) -> IResult<I, O>;
//! ```
//!
//! `IResult` is an alias for the `Result` type:
//!
//! ```rust
//! use nom::{Needed, error::Error};
//!
//! type IResult<I, O, E = Error<I>> = Result<(I, O), Err<E>>;
//!
//! enum Err<E> {
//! Incomplete(Needed),
//! Error(E),
//! Failure(E),
//! }
//! ```
//!
//! It can have the following values:
//!
//! - A correct result `Ok((I,O))` with the first element being the remaining of the input (not parsed yet), and the second the output value;
//! - An error `Err(Err::Error(c))` with `c` an error that can be built from the input position and a parser specific error
//! - An error `Err(Err::Incomplete(Needed))` indicating that more input is necessary. `Needed` can indicate how much data is needed
//! - An error `Err(Err::Failure(c))`. It works like the `Error` case, except it indicates an unrecoverable error: We cannot backtrack and test another parser
//!
//! Please refer to the ["choose a combinator" guide](https://github.com/Geal/nom/blob/master/doc/choosing_a_combinator.md) for an exhaustive list of parsers.
//! See also the rest of the documentation [here](https://github.com/Geal/nom/blob/master/doc).
//!
//! ## Making new parsers with function combinators
//!
//! nom is based on functions that generate parsers, with a signature like
//! this: `(arguments) -> impl Fn(Input) -> IResult<Input, Output, Error>`.
//! The arguments of a combinator can be direct values (like `take` which uses
//! a number of bytes or character as argument) or even other parsers (like
//! `delimited` which takes as argument 3 parsers, and returns the result of
//! the second one if all are successful).
//!
//! Here are some examples:
//!
//! ```rust
//! use nom::IResult;
//! use nom::bytes::complete::{tag, take};
//! fn abcd_parser(i: &str) -> IResult<&str, &str> {
//! tag("abcd")(i) // will consume bytes if the input begins with "abcd"
//! }
//!
//! fn take_10(i: &[u8]) -> IResult<&[u8], &[u8]> {
//! take(10u8)(i) // will consume and return 10 bytes of input
//! }
//! ```
//!
//! ## Combining parsers
//!
//! There are higher level patterns, like the **`alt`** combinator, which
//! provides a choice between multiple parsers. If one branch fails, it tries
//! the next, and returns the result of the first parser that succeeds:
//!
//! ```rust
//! use nom::IResult;
//! use nom::branch::alt;
//! use nom::bytes::complete::tag;
//!
//! let mut alt_tags = alt((tag("abcd"), tag("efgh")));
//!
//! assert_eq!(alt_tags(&b"abcdxxx"[..]), Ok((&b"xxx"[..], &b"abcd"[..])));
//! assert_eq!(alt_tags(&b"efghxxx"[..]), Ok((&b"xxx"[..], &b"efgh"[..])));
//! assert_eq!(alt_tags(&b"ijklxxx"[..]), Err(nom::Err::Error((&b"ijklxxx"[..], nom::error::ErrorKind::Tag))));
//! ```
//!
//! The **`opt`** combinator makes a parser optional. If the child parser returns
//! an error, **`opt`** will still succeed and return None:
//!
//! ```rust
//! use nom::{IResult, combinator::opt, bytes::complete::tag};
//! fn abcd_opt(i: &[u8]) -> IResult<&[u8], Option<&[u8]>> {
//! opt(tag("abcd"))(i)
//! }
//!
//! assert_eq!(abcd_opt(&b"abcdxxx"[..]), Ok((&b"xxx"[..], Some(&b"abcd"[..]))));
//! assert_eq!(abcd_opt(&b"efghxxx"[..]), Ok((&b"efghxxx"[..], None)));
//! ```
//!
//! **`many0`** applies a parser 0 or more times, and returns a vector of the aggregated results:
//!
//! ```rust
//! # #[cfg(feature = "alloc")]
//! # fn main() {
//! use nom::{IResult, multi::many0, bytes::complete::tag};
//! use std::str;
//!
//! fn multi(i: &str) -> IResult<&str, Vec<&str>> {
//! many0(tag("abcd"))(i)
//! }
//!
//! let a = "abcdef";
//! let b = "abcdabcdef";
//! let c = "azerty";
//! assert_eq!(multi(a), Ok(("ef", vec!["abcd"])));
//! assert_eq!(multi(b), Ok(("ef", vec!["abcd", "abcd"])));
//! assert_eq!(multi(c), Ok(("azerty", Vec::new())));
//! # }
//! # #[cfg(not(feature = "alloc"))]
//! # fn main() {}
//! ```
//!
//! Here are some basic combinators available:
//!
//! - **`opt`**: Will make the parser optional (if it returns the `O` type, the new parser returns `Option<O>`) | //! There are more complex (and more useful) parsers like `tuple!`, which is
//! used to apply a series of parsers then assemble their results.
//!
//! Example with `tuple`:
//!
//! ```rust
//! # fn main() {
//! use nom::{error::ErrorKind, Needed,
//! number::streaming::be_u16,
//! bytes::streaming::{tag, take},
//! sequence::tuple};
//!
//! let mut tpl = tuple((be_u16, take(3u8), tag("fg")));
//!
//! assert_eq!(
//! tpl(&b"abcdefgh"[..]),
//! Ok((
//! &b"h"[..],
//! (0x6162u16, &b"cde"[..], &b"fg"[..])
//! ))
//! );
//! assert_eq!(tpl(&b"abcde"[..]), Err(nom::Err::Incomplete(N | //! - **`many0`**: Will apply the parser 0 or more times (if it returns the `O` type, the new parser returns `Vec<O>`)
//! - **`many1`**: Will apply the parser 1 or more times
//! | random_line_split |
generate.ts | import selectorsLibrary from '../selectorsLibrary';
import cssVariablesLibrary from '../cssVariablesLibrary';
import keyframesLibrary from '../keyframesLibrary';
interface Stat {
appearanceCount: number;
}
export interface UsageCount {
[s: string]: number;
}
export interface Statistic {
unused: string[];
usageCount: UsageCount;
}
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const generate = () => {
const classSelector = selectorsLibrary.getClassSelector();
const idSelector = selectorsLibrary.getIdSelector();
const cssVariables = Object.entries(cssVariablesLibrary.meta);
const keyframes = Object.entries(keyframesLibrary.meta);
const getUnused = (obj: [string, Stat][]): string[] => (
obj.filter((entry) => entry[1].appearanceCount === 0)
.map(([name]) => name)
);
const unusedCssVariables = getUnused(cssVariables);
const unusedKeyframes = getUnused(keyframes);
const unusedClasses = getUnused(Object.entries(classSelector.meta));
const unusedIds = getUnused(Object.entries(idSelector.meta));
const classUsageCount: UsageCount = {};
const idUsageCount: UsageCount = {};
const cssVariablesUsageCount: UsageCount = {};
const keyframesUsageCount: UsageCount = {};
Object.keys(classSelector.values).forEach((v) => {
classUsageCount[v] = classSelector.meta[v].appearanceCount;
});
Object.keys(idSelector.values).forEach((v) => {
idUsageCount[v] = idSelector.meta[v].appearanceCount;
});
cssVariables.forEach(([name, meta]) => {
cssVariablesUsageCount[name] = meta.appearanceCount;
});
keyframes.forEach(([name, meta]) => {
keyframesUsageCount[name] = meta.appearanceCount;
});
return {
ids: {
unused: unusedIds,
usageCount: idUsageCount,
},
classes: {
unused: unusedClasses,
usageCount: classUsageCount,
},
cssVariables: {
unused: unusedCssVariables,
usageCount: cssVariablesUsageCount,
},
keyframes: {
unused: unusedKeyframes,
usageCount: keyframesUsageCount,
},
};
}; |
export default generate; | random_line_split | |
mod.rs | (the first line starting with `#`) is also considered as a comment.
Comment,
/// A punctuation.
Punct(Punct),
/// A keyword.
Keyword(Keyword),
/// A number.
Num(f64),
/// A name (either an identifier or a quoted name in the meta block).
Name(Name),
/// A string (either `"string"` or `[[string]]`).
Str(Str),
/// The end of file.
///
/// A valid stream of tokens is expected to have only one EOF token at the end.
EOF,
}
impl Localize for Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
match (&locale[..], self) {
("ko", &Tok::Error) => write!(f, "์๋ชป๋ ๋ฌธ์"),
(_, &Tok::Error) => write!(f, "an invalid character"),
("ko", &Tok::Comment) => write!(f, "์ฃผ์"),
(_, &Tok::Comment) => write!(f, "a comment"),
(_, &Tok::Punct(p)) => write!(f, "{}", Localized::new(&p, locale)),
(_, &Tok::Keyword(w)) => write!(f, "{}", Localized::new(&w, locale)),
("ko", &Tok::Num(_)) => write!(f, "์ซ์"),
(_, &Tok::Num(_)) => write!(f, "a number"),
("ko", &Tok::Name(_)) => write!(f, "์ด๋ฆ"),
(_, &Tok::Name(_)) => write!(f, "a name"),
("ko", &Tok::Str(_)) => write!(f, "๋ฌธ์์ด ๋ฆฌํฐ๋ด"),
(_, &Tok::Str(_)) => write!(f, "a string literal"),
("ko", &Tok::EOF) => write!(f, "ํ์ผ์ ๋"),
(_, &Tok::EOF) => write!(f, "the end of file"),
}
}
}
impl<'a> Localize for &'a Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
(**self).fmt_localized(f, locale)
}
}
macro_rules! define_puncts {
($ty:ident |$locale:ident|: $($i:ident $t:expr, #[$m:meta])*) => (
/// A punctuation.
///
/// This includes Kailua-specific punctuations,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* }
impl Localize for $ty {
fn fmt_localized(&self, f: &mut fmt::Formatter, $locale: Locale) -> fmt::Result {
let text = match *self { $($ty::$i => $t,)* };
fmt::Display::fmt(text, f)
}
}
);
}
define_puncts! { Punct |locale|:
Plus "`+`", /// `+`.
Dash "`-`", /// `-`.
Star "`*`", /// `*`.
Slash "`/`", /// `/`.
Percent "`%`", /// `%`.
Caret "`^`", /// `^`.
Hash "`#`", /// `#`.
EqEq "`==`", /// `==`.
TildeEq "`~=`", /// `~=`.
LtEq "`<=`", /// `<=`.
GtEq "`>=`", /// `>=`.
Lt "`<`", /// `<`.
Gt "`>`", /// `>`.
Eq "`=`", /// `=`.
Amp "`&`", /// `&`. [5.3+]
Tilde "`~`", /// `~`. [5.3+]
Pipe "`|`", /// `|`. [5.3+ or M]
LtLt "`<<`", /// `<<`. [5.3+]
GtGt "`>>`", /// `>>`. [5.3+]
SlashSlash "`//`", /// `//`. [5.3+]
LParen "`(`", /// `(`.
RParen "`)`", /// `)`.
LBrace "`{`", /// `{`.
RBrace "`}`", /// `}`.
LBracket "`[`", /// `[`.
RBracket "`]`", /// `]`.
Semicolon "`;`", /// `;`.
Colon "`:`", /// `:`.
ColonColon "`::`", /// `::`. [5.2+]
Comma "`,`", /// `,`.
Dot "`.`", /// `.`.
DotDot "`..`", /// `..`.
DotDotDot "`...`", /// `...`.
// Kailua extensions | DashDashColon "`--:`", /// `--:`. [M]
DashDashGt "`-->`", /// `-->`. [M]
Ques "`?`", /// `?`. [M]
Bang "`!`", /// `!`. [M]
Newline match &locale[..] { "ko" => "๊ฐํ๋ฌธ์", _ => "a newline" },
/// A newline. Only generated at the end of the meta block.
}
macro_rules! define_keywords {
($ty:ident: everywhere { $($i:ident $t:expr, #[$m:meta])* }
meta_only { $($mi:ident $mt:expr, #[$mm:meta])* }) => (
/// A keyword.
///
/// This includes Kailua-specific keywords,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* $(#[$mm] $mi,)* }
impl $ty {
pub fn from(s: &[u8], in_meta: bool) -> Option<Keyword> {
match (in_meta, s) {
$((_, $t) => Some(Keyword::$i),)*
$((true, $mt) => Some(Keyword::$mi),)*
(_, _) => None,
}
}
pub fn name(&self) -> &'static [u8] {
match *self { $($ty::$i => $t,)* $($ty::$mi => $mt,)* }
}
}
);
}
define_keywords! { Keyword:
everywhere {
And b"and", /// `and`.
Break b"break", /// `break`.
Do b"do", /// `do`.
Else b"else", /// `else`.
Elseif b"elseif", /// `elseif`.
End b"end", /// `end`.
False b"false", /// `false`.
For b"for", /// `for`.
Function b"function", /// `function`.
Goto b"goto", /// `goto`. [5.2+; a normal identifier in Lua 5.1]
If b"if", /// `if`.
In b"in", /// `in`.
Local b"local", /// `local`.
Nil b"nil", /// `nil`.
Not b"not", /// `not`.
Or b"or", /// `or`.
Repeat b"repeat", /// `repeat`.
Return b"return", /// `return`.
Then b"then", /// `then`.
True b"true", /// `true`.
Until b"until", /// `until`.
While b"while", /// `while`.
}
meta_only { // Kailua extensions
Assume b"assume", /// `assume`. [M]
Class b"class", /// `class`. [M]
Const b"const", /// `const`. [M]
Global b"global", /// `global`. [M]
Map b"map", /// `map`. [M]
Method b"method", /// `method`. [M]
Module b"module", /// `module`. [M]
Once b"once", /// `once`. [M]
Open b"open", /// `open`. [M]
Static b"static", | DashDashHash "`--#`", /// `--#`. [M]
DashDashV "`--v`", /// `--v`. [M] | random_line_split |
mod.rs | {
/// A token which is distinct from all other tokens.
///
/// The lexer emits this token on an error.
Error,
/// A comment token. The parser should ignore this.
///
/// The shebang line (the first line starting with `#`) is also considered as a comment.
Comment,
/// A punctuation.
Punct(Punct),
/// A keyword.
Keyword(Keyword),
/// A number.
Num(f64),
/// A name (either an identifier or a quoted name in the meta block).
Name(Name),
/// A string (either `"string"` or `[[string]]`).
Str(Str),
/// The end of file.
///
/// A valid stream of tokens is expected to have only one EOF token at the end.
EOF,
}
impl Localize for Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
match (&locale[..], self) {
("ko", &Tok::Error) => write!(f, "์๋ชป๋ ๋ฌธ์"),
(_, &Tok::Error) => write!(f, "an invalid character"),
("ko", &Tok::Comment) => write!(f, "์ฃผ์"),
(_, &Tok::Comment) => write!(f, "a comment"),
(_, &Tok::Punct(p)) => write!(f, "{}", Localized::new(&p, locale)),
(_, &Tok::Keyword(w)) => write!(f, "{}", Localized::new(&w, locale)),
("ko", &Tok::Num(_)) => write!(f, "์ซ์"),
(_, &Tok::Num(_)) => write!(f, "a number"),
("ko", &Tok::Name(_)) => write!(f, "์ด๋ฆ"),
(_, &Tok::Name(_)) => write!(f, "a name"),
("ko", &Tok::Str(_)) => write!(f, "๋ฌธ์์ด ๋ฆฌํฐ๋ด"),
(_, &Tok::Str(_)) => write!(f, "a string literal"),
("ko", &Tok::EOF) => write!(f, "ํ์ผ์ ๋"),
(_, &Tok::EOF) => write!(f, "the end of file"),
}
}
}
impl<'a> Localize for &'a Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
(**self).fmt_localized(f, locale)
}
}
macro_rules! define_puncts {
($ty:ident |$locale:ident|: $($i:ident $t:expr, #[$m:meta])*) => (
/// A punctuation.
///
/// This includes Kailua-specific punctuations,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* }
impl Localize for $ty {
fn fmt_localized(&self, f: &mut fmt::Formatter, $locale: Locale) -> fmt::Result {
let text = match *self { $($ty::$i => $t,)* };
fmt::Display::fmt(text, f)
}
}
);
}
define_puncts! { Punct |locale|:
Plus "`+`", /// `+`.
Dash "`-`", /// `-`.
Star "`*`", /// `*`.
Slash "`/`", /// `/`.
Percent "`%`", /// `%`.
Caret "`^`", /// `^`.
Hash "`#`", /// `#`.
EqEq "`==`", /// `==`.
TildeEq "`~=`", /// `~=`.
LtEq "`<=`", /// `<=`.
GtEq "`>=`", /// `>=`.
Lt "`<`", /// `<`.
Gt "`>`", /// `>`.
Eq "`=`", /// `=`.
Amp "`&`", /// `&`. [5.3+]
Tilde "`~`", /// `~`. [5.3+]
Pipe "`|`", /// `|`. [5.3+ or M]
LtLt "`<<`", /// `<<`. [5.3+]
GtGt "`>>`", /// `>>`. [5.3+]
SlashSlash "`//`", /// `//`. [5.3+]
LParen "`(`", /// `(`.
RParen "`)`", /// `)`.
LBrace "`{`", /// `{`.
RBrace "`}`", /// `}`.
LBracket "`[`", /// `[`.
RBracket "`]`", /// `]`.
Semicolon "`;`", /// `;`.
Colon "`:`", /// `:`.
ColonColon "`::`", /// `::`. [5.2+]
Comma "`,`", /// `,`.
Dot "`.`", /// `.`.
DotDot "`..`", /// `..`.
DotDotDot "`...`", /// `...`.
// Kailua extensions
DashDashHash "`--#`", /// `--#`. [M]
DashDashV "`--v`", /// `--v`. [M]
DashDashColon "`--:`", /// `--:`. [M]
DashDashGt "`-->`", /// `-->`. [M]
Ques "`?`", /// `?`. [M]
Bang "`!`", /// `!`. [M]
Newline match &locale[..] { "ko" => "๊ฐํ๋ฌธ์", _ => "a newline" },
/// A newline. Only generated at the end of the meta block.
}
macro_rules! define_keywords {
($ty:ident: everywhere { $($i:ident $t:expr, #[$m:meta])* }
meta_only { $($mi:ident $mt:expr, #[$mm:meta])* }) => (
/// A keyword.
///
/// This includes Kailua-specific keywords,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* $(#[$mm] $mi,)* }
impl $ty {
pub fn from(s: &[u8], in_meta: bool) -> Option<Keyword> {
match (in_meta, s) {
$((_, $t) => Some(Keyword::$i),)*
$((true, $mt) => Some(Keyword::$mi),)*
(_, _) => None,
}
}
pub fn name(&self) -> &'static [u8] {
match *self { $($ty::$i => $t,)* $($ty::$mi => $mt,)* }
}
}
);
}
define_keywords! { Keyword:
everywhere {
And b"and", /// `and`.
Break b"break", /// `break`.
Do b"do", /// `do`.
Else b"else", /// `else`.
Elseif b"elseif", /// `elseif`.
End b"end", /// `end`.
False b"false", /// `false`.
For b"for", /// `for`.
Function b"function", /// `function`.
Goto b"goto", /// `goto`. [5.2+; a normal identifier in Lua 5.1]
If b"if", /// `if`.
In b"in", /// `in`.
Local b"local", /// `local`.
Nil b"nil", /// `nil`.
Not b"not", /// `not`.
Or b"or", /// `or`.
Repeat b"repeat", /// `repeat`.
Return b"return", /// `return`.
Then b"then", /// `then`.
True b"true", /// `true`.
Until b"until", /// `until`.
While b"while", /// `while`.
}
meta_only { // Kailua extensions
Assume b"assume", /// `assume`. [M]
Class b"class", /// `class`. [M]
Const b"const", /// `const`. [M]
Global b"global", /// `global`. [M]
Map b"map", /// `map`. [M]
Method b"method", /// `method`. [M]
Module | Tok | identifier_name | |
mod.rs | ///
/// A valid stream of tokens is expected to have only one EOF token at the end.
EOF,
}
impl Localize for Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
match (&locale[..], self) {
("ko", &Tok::Error) => write!(f, "์๋ชป๋ ๋ฌธ์"),
(_, &Tok::Error) => write!(f, "an invalid character"),
("ko", &Tok::Comment) => write!(f, "์ฃผ์"),
(_, &Tok::Comment) => write!(f, "a comment"),
(_, &Tok::Punct(p)) => write!(f, "{}", Localized::new(&p, locale)),
(_, &Tok::Keyword(w)) => write!(f, "{}", Localized::new(&w, locale)),
("ko", &Tok::Num(_)) => write!(f, "์ซ์"),
(_, &Tok::Num(_)) => write!(f, "a number"),
("ko", &Tok::Name(_)) => write!(f, "์ด๋ฆ"),
(_, &Tok::Name(_)) => write!(f, "a name"),
("ko", &Tok::Str(_)) => write!(f, "๋ฌธ์์ด ๋ฆฌํฐ๋ด"),
(_, &Tok::Str(_)) => write!(f, "a string literal"),
("ko", &Tok::EOF) => write!(f, "ํ์ผ์ ๋"),
(_, &Tok::EOF) => write!(f, "the end of file"),
}
}
}
impl<'a> Localize for &'a Tok {
fn fmt_localized(&self, f: &mut fmt::Formatter, locale: Locale) -> fmt::Result {
(**self).fmt_localized(f, locale)
}
}
macro_rules! define_puncts {
($ty:ident |$locale:ident|: $($i:ident $t:expr, #[$m:meta])*) => (
/// A punctuation.
///
/// This includes Kailua-specific punctuations,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* }
impl Localize for $ty {
fn fmt_localized(&self, f: &mut fmt::Formatter, $locale: Locale) -> fmt::Result {
let text = match *self { $($ty::$i => $t,)* };
fmt::Display::fmt(text, f)
}
}
);
}
define_puncts! { Punct |locale|:
Plus "`+`", /// `+`.
Dash "`-`", /// `-`.
Star "`*`", /// `*`.
Slash "`/`", /// `/`.
Percent "`%`", /// `%`.
Caret "`^`", /// `^`.
Hash "`#`", /// `#`.
EqEq "`==`", /// `==`.
TildeEq "`~=`", /// `~=`.
LtEq "`<=`", /// `<=`.
GtEq "`>=`", /// `>=`.
Lt "`<`", /// `<`.
Gt "`>`", /// `>`.
Eq "`=`", /// `=`.
Amp "`&`", /// `&`. [5.3+]
Tilde "`~`", /// `~`. [5.3+]
Pipe "`|`", /// `|`. [5.3+ or M]
LtLt "`<<`", /// `<<`. [5.3+]
GtGt "`>>`", /// `>>`. [5.3+]
SlashSlash "`//`", /// `//`. [5.3+]
LParen "`(`", /// `(`.
RParen "`)`", /// `)`.
LBrace "`{`", /// `{`.
RBrace "`}`", /// `}`.
LBracket "`[`", /// `[`.
RBracket "`]`", /// `]`.
Semicolon "`;`", /// `;`.
Colon "`:`", /// `:`.
ColonColon "`::`", /// `::`. [5.2+]
Comma "`,`", /// `,`.
Dot "`.`", /// `.`.
DotDot "`..`", /// `..`.
DotDotDot "`...`", /// `...`.
// Kailua extensions
DashDashHash "`--#`", /// `--#`. [M]
DashDashV "`--v`", /// `--v`. [M]
DashDashColon "`--:`", /// `--:`. [M]
DashDashGt "`-->`", /// `-->`. [M]
Ques "`?`", /// `?`. [M]
Bang "`!`", /// `!`. [M]
Newline match &locale[..] { "ko" => "๊ฐํ๋ฌธ์", _ => "a newline" },
/// A newline. Only generated at the end of the meta block.
}
macro_rules! define_keywords {
($ty:ident: everywhere { $($i:ident $t:expr, #[$m:meta])* }
meta_only { $($mi:ident $mt:expr, #[$mm:meta])* }) => (
/// A keyword.
///
/// This includes Kailua-specific keywords,
/// which are only generated in the meta block (marked as [M] below).
/// Some of them are also only generated after a particular Lua version
/// (marked as [5.x+] below).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum $ty { $(#[$m] $i,)* $(#[$mm] $mi,)* }
impl $ty {
pub fn from(s: &[u8], in_meta: bool) -> Option<Keyword> {
match (in_meta, s) {
$((_, $t) => Some(Keyword::$i),)*
$((true, $mt) => Some(Keyword::$mi),)*
(_, _) => None,
}
}
pub fn name(&self) -> &'static [u8] {
match *self { $($ty::$i => $t,)* $($ty::$mi => $mt,)* }
}
}
);
}
define_keywords! { Keyword:
everywhere {
And b"and", /// `and`.
Break b"break", /// `break`.
Do b"do", /// `do`.
Else b"else", /// `else`.
Elseif b"elseif", /// `elseif`.
End b"end", /// `end`.
False b"false", /// `false`.
For b"for", /// `for`.
Function b"function", /// `function`.
Goto b"goto", /// `goto`. [5.2+; a normal identifier in Lua 5.1]
If b"if", /// `if`.
In b"in", /// `in`.
Local b"local", /// `local`.
Nil b"nil", /// `nil`.
Not b"not", /// `not`.
Or b"or", /// `or`.
Repeat b"repeat", /// `repeat`.
Return b"return", /// `return`.
Then b"then", /// `then`.
True b"true", /// `true`.
Until b"until", /// `until`.
While b"while", /// `while`.
}
meta_only { // Kailua extensions
Assume b"assume", /// `assume`. [M]
Class b"class", /// `class`. [M]
Const b"const", /// `const`. [M]
Global b"global", /// `global`. [M]
Map b"map", /// `map`. [M]
Method b"method", /// `method`. [M]
Module b"module", /// `module`. [M]
Once b"once", /// `once`. [M]
Open b"open", /// `open`. [M]
Static b"static", /// `static`. [M]
Type b"type", /// `type`. [M]
Var b"var", /// `var`. [M]
Vector b"vector", /// `vector`. [M]
}
}
impl From<Keyword> for Str {
fn from(kw: Keyword) -> Str {
kw.name().into()
}
}
impl From<Keyw | ord> for Name {
fn from(kw: | identifier_body | |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options):
if len(args) != 4:
|
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed()
| raise CommandError("must provide all parameters") | conditional_block |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options): |
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed() | if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args | random_line_split |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def | (self, *args, **options):
if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed()
| handle | identifier_name |
import_jenkinsserver.py | from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from jenkins.management.helpers import import_jenkinsserver
# TODO: implement optional field updating...
class Command(BaseCommand):
help = "Import or update a JenkinsServer"
args = "[name] [url] [username] [password]"
option_list = BaseCommand.option_list + (
make_option(
"--update", action="store_true", dest="update",
default=False, help="Update if server already exists."),
)
def handle(self, *args, **options):
| if len(args) != 4:
raise CommandError("must provide all parameters")
name, url, username, password = args
import_jenkinsserver(
name, url, username, password, update=options["update"],
stdout=self.stdout)
transaction.commit_unless_managed() | identifier_body | |
sha1.rs | 325476), wr(0xC3D2E1F0)];
#[cfg(not(test))]
fn main() {
let mut d = Digest::new();
let _ = write!(&mut d, "The quick brown fox jumps over the lazy dog");
let sha1=d.sha1();
for h in &sha1 {
print!("{:x} ", *h);
}
}
// digest represents the partial evaluation of a checksum.
struct Digest {
h: [wr<u32>; 5],
x: [u8; CHUNK],
nx: usize,
len: u64
}
impl Digest {
fn new() -> Digest {
Digest {
h: INIT,
x: [0u8; CHUNK],
nx: 0,
len:0u64
}
}
fn sha1(&mut self) -> [u8; SIZE] {
let mut len = self.len;
// Padding. Add a 1 bit and 0 bits until 56 bytes mod 64.
let mut tmp : [u8; 64] = [0u8; 64];
tmp[0] = 0x80u8;
let m:usize=(len%64u64) as usize;
if m < 56 {
self.write_all(&tmp[0..56-m]).unwrap();
} else {
self.write_all(&tmp[0..64+56-m]).unwrap();
}
// Length in bits (=lengh in bytes*8=shift 3 bits to the right).
len = len << 3;
for i in (0..8) {
tmp[i] = (len >> (56 - 8*i)) as u8;
}
self.write_all(&tmp[0..8]).unwrap();
assert!(self.nx == 0);
let mut digest : [u8; SIZE]=[0u8; SIZE];
for (i, s) in self.h.iter().enumerate() {
digest[i*4] = (*s >> 24).0 as u8;
digest[i*4+1] = (*s >> 16).0 as u8;
digest[i*4+2] = (*s >> 8).0 as u8;
digest[i*4+3] = s.0 as u8;
}
digest
}
fn process_block(&self, data:&[u8]) -> [wr<u32>; 5]{
let k:[u32; 4] = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6];
#[inline]
fn part(a: wr<u32>, b: wr<u32>) -> (wr<u32>, wr<u32>) {
((a<<5 | a>>(32-5)), (b<<30 | b>>(32-30)))
}
let mut w :[u32; 16] = [0u32; 16];
let (mut h0, mut h1, mut h2, mut h3, mut h4) =
(self.h[0], self.h[1], self.h[2], self.h[3], self.h[4]);
let mut p = data;
while p.len() >= CHUNK {
for i in (0..16) {
let j = i * 4;
w[i] = (p[j] as u32)<<24 |
(p[j+1] as u32)<<16 |
(p[j+2] as u32) <<8 |
p[j+3] as u32;
}
let (mut a, mut b, mut c, mut d, mut e) = (h0, h1, h2, h3, h4);
for i in (0..16) {
let f = b & c | (!b) & d;
let (a5, b30) = part(a, b);
let t = a5 + f + e + wr(w[i&0xf]) + wr(k[0]);
b=a; a=t; e=d; d=c; c=b30;
}
for i in (16..20) {
let tmp = w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf];
w[i&0xf] = tmp<<1 | tmp>>(32-1);
let f = b & c | (!b) & d;
let (a5, b30) = part(a, b);
let t = a5 + f + e + wr(w[i&0xf]) + wr(k[0]);
b=a; a=t; e=d; d=c; c=b30;
}
for i in (20..40) {
let tmp = w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf];
w[i&0xf] = tmp<<1 | tmp>>(32-1);
let f = b ^ c ^ d;
let (a5, b30) = part(a, b);
let t = a5 + f + e + wr(w[i&0xf]) + wr(k[1]);
b=a; a=t; e=d; d=c; c=b30;
}
for i in (40..60) {
let tmp = w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf];
w[i&0xf] = tmp<<1 | tmp>>(32-1);
let f = ((b | c) & d) | (b & c);
let (a5, b30) = part(a, b);
let t = a5 + f + e + wr(w[i&0xf]) + wr(k[2]);
b=a; a=t; e=d; d=c; c=b30;
}
for i in (60..80) {
let tmp = w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf];
w[i&0xf] = tmp<<1 | tmp>>(32-1);
let f = b ^ c ^ d;
let (a5, b30) = part(a, b);
let t = a5 + f + e + wr(w[i&0xf]) + wr(k[3]);
b=a; a=t; e=d; d=c; c=b30;
}
h0 = h0 + a;
h1 = h1 + b;
h2 = h2 + c;
h3 = h3 + d;
h4 = h4 + e;
p = &p[CHUNK..];
}
[h0, h1, h2, h3, h4]
}
}
impl Write for Digest {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
try!(self.write_all(buf));
Ok(buf.len())
}
#[inline]
fn write_all(&mut self, buf: &[u8]) -> Result<()> {
let mut buf_m = buf;
self.len += buf_m.len() as u64;
if self.nx > 0 {
let mut n = buf_m.len();
if n > CHUNK - self.nx {
n = CHUNK - self.nx;
}
for i in (0..n) {
self.x[self.nx + i] = *buf_m.get(i).unwrap();
}
self.nx += n;
if self.nx == CHUNK {
let x = &(self.x[..]);
self.h=self.process_block(x);
self.nx = 0;
}
buf_m = &buf_m[n..];
}
if buf_m.len() >= CHUNK {
let n = buf_m.len() &!(CHUNK - 1);
let x = &(self.x[n..]);
self.h=self.process_block(x); | assert!(self.x.len() >= ln);
copy_memory(buf_m, &mut self.x);
self.nx = ln;
}
Ok(())
}
fn flush(&mut self) -> Result<()> { Ok(()) }
}
#[test]
fn known_sha1s() {
let input_output = [
(
"His money is twice tainted: 'taint yours and 'taint mine.",
[0x59u8, 0x7f, 0x6a, 0x54, 0x0, 0x10, 0xf9, 0x4c,
0x15, | buf_m = &buf_m[n..];
}
let ln=buf_m.len();
if ln > 0 { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.