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 |
---|---|---|---|---|
load.rs | /*! # Reading and loading hyphenation dictionaries
To hyphenate words in a given language, it is first necessary to load
the relevant hyphenation dictionary into memory. This module offers
convenience methods for common retrieval patterns, courtesy of the
[`Load`] trait.
```
use hyphenation::Load;
use hyphenation::{Standard, Language};
```
The primary function of [`Load`] is to deserialize dictionaries from
buffers – usually, file buffers.
```ignore
use std::io;
use std::fs::File;
let path_to_dict = "/path/to/english-dictionary.bincode";
let dict_file = File::open(path_to_dict) ?;
let mut reader = io::BufReader::new(dict_file);
let english_us = Standard::from_reader(Language::EnglishUS, &mut reader) ?;
```
Dictionaries can be loaded from the file system rather more succintly with
the [`from_path`] shorthand:
```ignore
let path_to_dict = "/path/to/english-dictionary.bincode";
let english_us = Standard::from_path(Language::EnglishUS, path_to_dict) ?;
```
Dictionaries bundled with the `hyphenation` library are copied to Cargo's
output directory at build time. To locate them, look for a `dictionaries`
folder under `target`:
```text
$ find target -name "dictionaries"
target/debug/build/hyphenation-33034db3e3b5f3ce/out/dictionaries
```
## Embedding
Optionally, hyphenation dictionaries can be embedded in the compiled
artifact by enabling the `embed_all` feature. Embedded dictionaries can be
accessed directly from memory.
```ignore
use hyphenation::{Standard, Language, Load};
let english_us = Standard::from_embedded(Language::EnglishUS) ?;
```
Note that embedding significantly increases the size of the compiled artifact.
[`Load`]: trait.Load.html
[`from_path`]: trait.Load.html#method.from_path
*/
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))] use resources::ResourceId;
use bincode as bin;
use std::error;
use std::fmt;
use std::io;
use std::fs::File;
use std::path::Path;
use std::result;
use hyphenation_commons::Language;
use hyphenation_commons::dictionary::{Standard, extended::Extended};
/// Convenience methods for the retrieval of hyphenation dictionaries.
pub trait Load : Sized {
/// Read and deserialize the dictionary at the given path, verifying that it
/// belongs to the expected language.
fn from_path<P>(lang : Language, path : P) -> Result<Self>
where P : AsRef<Path> {
| /// Deserialize a dictionary from the provided reader, verifying that it
/// belongs to the expected language.
fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self>
where R : io::Read;
/// Deserialize a dictionary from the provided reader.
fn any_from_reader<R>(reader : &mut R) -> Result<Self>
where R : io::Read;
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
/// Deserialize the embedded dictionary for the given language.
fn from_embedded(lang : Language) -> Result<Self>;
}
macro_rules! impl_load {
($dict:ty, $suffix:expr) => {
impl Load for $dict {
fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self>
where R : io::Read {
let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader) ?;
let (found, expected) = (dict.language(), lang);
if found != expected {
Err(Error::LanguageMismatch { expected, found })
} else { Ok(dict) }
}
fn any_from_reader<R>(reader : &mut R) -> Result<Self>
where R : io::Read {
let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader) ?;
Ok(dict)
}
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
fn from_embedded(lang : Language) -> Result<Self> {
let dict_bytes = retrieve_resource(lang.code(), $suffix) ?;
let dict = bin::deserialize(dict_bytes) ?;
Ok(dict)
}
}
}
}
impl_load! { Standard, "standard" }
impl_load! { Extended, "extended" }
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
fn retrieve_resource<'a>(code : &str, suffix : &str) -> Result<&'a [u8]> {
let name = format!("{}.{}.bincode", code, suffix);
let res : Option<ResourceId> = ResourceId::from_name(&name);
match res {
Some(data) => Ok(data.load()),
None => Err(Error::Resource)
}
}
pub type Result<T> = result::Result<T, Error>;
/// Failure modes of dictionary loading.
#[derive(Debug)]
pub enum Error {
/// The dictionary could not be deserialized.
Deserialization(bin::Error),
/// The dictionary could not be read.
IO(io::Error),
/// The loaded dictionary is for the wrong language.
LanguageMismatch { expected : Language, found : Language },
/// The embedded dictionary could not be retrieved.
Resource
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
Error::Deserialization(ref e) => Some(e),
Error::IO(ref e) => Some(e),
_ => None
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Deserialization(ref e) => e.fmt(f),
Error::IO(ref e) => e.fmt(f),
Error::LanguageMismatch { expected, found } =>
write!(f, "\
Language mismatch: attempted to load a dictionary for `{}`, but found
a dictionary for `{}` instead.", expected, found),
Error::Resource => f.write_str("the embedded dictionary could not be retrieved")
}
}
}
impl From<io::Error> for Error {
fn from(err : io::Error) -> Error { Error::IO(err) }
}
impl From<bin::Error> for Error {
fn from(err : bin::Error) -> Error { Error::Deserialization(err) }
}
| let file = File::open(path) ?;
Self::from_reader(lang, &mut io::BufReader::new(file))
}
| identifier_body |
load.rs | /*! # Reading and loading hyphenation dictionaries
To hyphenate words in a given language, it is first necessary to load
the relevant hyphenation dictionary into memory. This module offers
convenience methods for common retrieval patterns, courtesy of the
[`Load`] trait.
```
use hyphenation::Load;
use hyphenation::{Standard, Language};
```
The primary function of [`Load`] is to deserialize dictionaries from
buffers – usually, file buffers.
```ignore
use std::io;
use std::fs::File;
let path_to_dict = "/path/to/english-dictionary.bincode";
let dict_file = File::open(path_to_dict) ?;
let mut reader = io::BufReader::new(dict_file);
let english_us = Standard::from_reader(Language::EnglishUS, &mut reader) ?;
```
Dictionaries can be loaded from the file system rather more succintly with
the [`from_path`] shorthand:
```ignore
let path_to_dict = "/path/to/english-dictionary.bincode";
let english_us = Standard::from_path(Language::EnglishUS, path_to_dict) ?;
```
Dictionaries bundled with the `hyphenation` library are copied to Cargo's
output directory at build time. To locate them, look for a `dictionaries`
folder under `target`:
```text
$ find target -name "dictionaries"
target/debug/build/hyphenation-33034db3e3b5f3ce/out/dictionaries
```
## Embedding
Optionally, hyphenation dictionaries can be embedded in the compiled
artifact by enabling the `embed_all` feature. Embedded dictionaries can be
accessed directly from memory.
```ignore
use hyphenation::{Standard, Language, Load};
let english_us = Standard::from_embedded(Language::EnglishUS) ?;
```
Note that embedding significantly increases the size of the compiled artifact.
[`Load`]: trait.Load.html
[`from_path`]: trait.Load.html#method.from_path
*/
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))] use resources::ResourceId;
use bincode as bin;
use std::error;
use std::fmt;
use std::io;
use std::fs::File;
use std::path::Path;
use std::result;
use hyphenation_commons::Language;
use hyphenation_commons::dictionary::{Standard, extended::Extended};
/// Convenience methods for the retrieval of hyphenation dictionaries.
pub trait Load : Sized {
/// Read and deserialize the dictionary at the given path, verifying that it
/// belongs to the expected language.
fn from_path<P>(lang : Language, path : P) -> Result<Self>
where P : AsRef<Path> {
let file = File::open(path) ?;
Self::from_reader(lang, &mut io::BufReader::new(file))
}
/// Deserialize a dictionary from the provided reader, verifying that it
/// belongs to the expected language.
fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self>
where R : io::Read;
/// Deserialize a dictionary from the provided reader.
fn any_from_reader<R>(reader : &mut R) -> Result<Self>
where R : io::Read;
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
/// Deserialize the embedded dictionary for the given language.
fn from_embedded(lang : Language) -> Result<Self>;
}
macro_rules! impl_load {
($dict:ty, $suffix:expr) => {
impl Load for $dict {
fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self>
where R : io::Read {
let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader) ?;
let (found, expected) = (dict.language(), lang);
if found != expected {
Err(Error::LanguageMismatch { expected, found })
} else { Ok(dict) }
}
fn any_from_reader<R>(reader : &mut R) -> Result<Self>
where R : io::Read {
let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader) ?;
Ok(dict)
}
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
fn from_embedded(lang : Language) -> Result<Self> {
let dict_bytes = retrieve_resource(lang.code(), $suffix) ?;
let dict = bin::deserialize(dict_bytes) ?;
Ok(dict)
}
}
}
}
impl_load! { Standard, "standard" }
impl_load! { Extended, "extended" }
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
fn re | a>(code : &str, suffix : &str) -> Result<&'a [u8]> {
let name = format!("{}.{}.bincode", code, suffix);
let res : Option<ResourceId> = ResourceId::from_name(&name);
match res {
Some(data) => Ok(data.load()),
None => Err(Error::Resource)
}
}
pub type Result<T> = result::Result<T, Error>;
/// Failure modes of dictionary loading.
#[derive(Debug)]
pub enum Error {
/// The dictionary could not be deserialized.
Deserialization(bin::Error),
/// The dictionary could not be read.
IO(io::Error),
/// The loaded dictionary is for the wrong language.
LanguageMismatch { expected : Language, found : Language },
/// The embedded dictionary could not be retrieved.
Resource
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
Error::Deserialization(ref e) => Some(e),
Error::IO(ref e) => Some(e),
_ => None
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Deserialization(ref e) => e.fmt(f),
Error::IO(ref e) => e.fmt(f),
Error::LanguageMismatch { expected, found } =>
write!(f, "\
Language mismatch: attempted to load a dictionary for `{}`, but found
a dictionary for `{}` instead.", expected, found),
Error::Resource => f.write_str("the embedded dictionary could not be retrieved")
}
}
}
impl From<io::Error> for Error {
fn from(err : io::Error) -> Error { Error::IO(err) }
}
impl From<bin::Error> for Error {
fn from(err : bin::Error) -> Error { Error::Deserialization(err) }
}
| trieve_resource<' | identifier_name |
load.rs | /*! # Reading and loading hyphenation dictionaries
To hyphenate words in a given language, it is first necessary to load
the relevant hyphenation dictionary into memory. This module offers
convenience methods for common retrieval patterns, courtesy of the
[`Load`] trait.
```
use hyphenation::Load;
use hyphenation::{Standard, Language};
```
The primary function of [`Load`] is to deserialize dictionaries from
buffers – usually, file buffers.
```ignore
use std::io;
use std::fs::File;
let path_to_dict = "/path/to/english-dictionary.bincode";
let dict_file = File::open(path_to_dict) ?;
let mut reader = io::BufReader::new(dict_file);
let english_us = Standard::from_reader(Language::EnglishUS, &mut reader) ?;
```
Dictionaries can be loaded from the file system rather more succintly with
the [`from_path`] shorthand:
```ignore
let path_to_dict = "/path/to/english-dictionary.bincode";
let english_us = Standard::from_path(Language::EnglishUS, path_to_dict) ?;
```
Dictionaries bundled with the `hyphenation` library are copied to Cargo's
output directory at build time. To locate them, look for a `dictionaries`
folder under `target`:
```text
$ find target -name "dictionaries"
target/debug/build/hyphenation-33034db3e3b5f3ce/out/dictionaries
```
## Embedding
Optionally, hyphenation dictionaries can be embedded in the compiled
artifact by enabling the `embed_all` feature. Embedded dictionaries can be
accessed directly from memory.
```ignore
use hyphenation::{Standard, Language, Load};
let english_us = Standard::from_embedded(Language::EnglishUS) ?;
```
Note that embedding significantly increases the size of the compiled artifact.
[`Load`]: trait.Load.html
[`from_path`]: trait.Load.html#method.from_path
*/
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))] use resources::ResourceId;
use bincode as bin;
use std::error;
use std::fmt;
use std::io;
use std::fs::File;
use std::path::Path;
use std::result;
use hyphenation_commons::Language;
use hyphenation_commons::dictionary::{Standard, extended::Extended};
/// Convenience methods for the retrieval of hyphenation dictionaries.
pub trait Load : Sized {
/// Read and deserialize the dictionary at the given path, verifying that it
/// belongs to the expected language.
fn from_path<P>(lang : Language, path : P) -> Result<Self>
where P : AsRef<Path> {
let file = File::open(path) ?;
Self::from_reader(lang, &mut io::BufReader::new(file))
}
/// Deserialize a dictionary from the provided reader, verifying that it
/// belongs to the expected language.
fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self>
where R : io::Read;
/// Deserialize a dictionary from the provided reader.
fn any_from_reader<R>(reader : &mut R) -> Result<Self>
where R : io::Read;
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
/// Deserialize the embedded dictionary for the given language.
fn from_embedded(lang : Language) -> Result<Self>;
}
macro_rules! impl_load { | where R : io::Read {
let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader) ?;
let (found, expected) = (dict.language(), lang);
if found != expected {
Err(Error::LanguageMismatch { expected, found })
} else { Ok(dict) }
}
fn any_from_reader<R>(reader : &mut R) -> Result<Self>
where R : io::Read {
let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader) ?;
Ok(dict)
}
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
fn from_embedded(lang : Language) -> Result<Self> {
let dict_bytes = retrieve_resource(lang.code(), $suffix) ?;
let dict = bin::deserialize(dict_bytes) ?;
Ok(dict)
}
}
}
}
impl_load! { Standard, "standard" }
impl_load! { Extended, "extended" }
#[cfg(any(feature = "embed_all", feature = "embed_en-us"))]
fn retrieve_resource<'a>(code : &str, suffix : &str) -> Result<&'a [u8]> {
let name = format!("{}.{}.bincode", code, suffix);
let res : Option<ResourceId> = ResourceId::from_name(&name);
match res {
Some(data) => Ok(data.load()),
None => Err(Error::Resource)
}
}
pub type Result<T> = result::Result<T, Error>;
/// Failure modes of dictionary loading.
#[derive(Debug)]
pub enum Error {
/// The dictionary could not be deserialized.
Deserialization(bin::Error),
/// The dictionary could not be read.
IO(io::Error),
/// The loaded dictionary is for the wrong language.
LanguageMismatch { expected : Language, found : Language },
/// The embedded dictionary could not be retrieved.
Resource
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
Error::Deserialization(ref e) => Some(e),
Error::IO(ref e) => Some(e),
_ => None
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Deserialization(ref e) => e.fmt(f),
Error::IO(ref e) => e.fmt(f),
Error::LanguageMismatch { expected, found } =>
write!(f, "\
Language mismatch: attempted to load a dictionary for `{}`, but found
a dictionary for `{}` instead.", expected, found),
Error::Resource => f.write_str("the embedded dictionary could not be retrieved")
}
}
}
impl From<io::Error> for Error {
fn from(err : io::Error) -> Error { Error::IO(err) }
}
impl From<bin::Error> for Error {
fn from(err : bin::Error) -> Error { Error::Deserialization(err) }
} | ($dict:ty, $suffix:expr) => {
impl Load for $dict {
fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self> | random_line_split |
ranking-export.component.ts | import { Component, OnInit } from "@angular/core";
import { faDownload } from "@fortawesome/free-solid-svg-icons/faDownload";
import { Store } from "@ngrx/store";
import { flatMapping } from "../../../@core/lib/collections";
import { ALL_DISCIPLINES } from "../../../dto/athletics";
import { GenderDto, genderDtoOfValue } from "../../../dto/participation";
import { DisciplineRanking } from "../../../dto/ranking";
import { FEMALE, MALE } from "../../../modules/participant/gender/gender-constants";
import { LABEL_ALL, TreeCheckNodeModel } from "../../../modules/tree/tree-model";
import {
downloadDisciplineRankingAction,
downloadTotalRankingAction,
downloadTriathlonRankingAction,
downloadUbsCupRankingAction,
loadRankingData,
} from "../../../store/ranking/ranking.action";
import {
selectIsDisciplineRankingDownloading,
selectIsParticipationOpen,
selectIsTotalRankingDownloading,
selectIsTriathlonRankingDownloading,
selectIsUbsCupRankingDownloading,
} from "../../../store/ranking/ranking.selector";
const GENDER_TREE_BUILDER = TreeCheckNodeModel.newBuilder()
.setLabel(LABEL_ALL)
.setCollapsedEnabled(false)
.addLeafNode(MALE, GenderDto.MALE)
.addLeafNode(FEMALE, GenderDto.FEMALE); |
@Component({
selector: "app-ranking-export",
templateUrl: "./ranking-export.component.html",
})
export class RankingExportComponent implements OnInit {
readonly faDownload = faDownload;
readonly isParticipationOpen$ = this.store.select(selectIsParticipationOpen);
readonly totalTree = GENDER_TREE_BUILDER.build();
readonly isTotalRankingDownloading = this.store.select(selectIsTotalRankingDownloading);
readonly triathlonTree = GENDER_TREE_BUILDER.build();
readonly isTriathlonRankingDownloading = this.store.select(selectIsTriathlonRankingDownloading);
readonly ubsCupTree = GENDER_TREE_BUILDER.build();
readonly isUbsCupRankingDownloading = this.store.select(selectIsUbsCupRankingDownloading);
readonly disciplinesTree = TreeCheckNodeModel.newBuilder()
.setLabel(LABEL_ALL)
.setCollapsedEnabled(false)
// tslint:disable-next-line:no-magic-numbers
.setSplitting(4)
.addNodes(ALL_DISCIPLINES.map(discipline =>
TreeCheckNodeModel.newBuilder()
.setLabel(discipline)
.setCollapsed(true)
.addLeafNode(MALE, GenderDto.MALE)
.addLeafNode(FEMALE, GenderDto.FEMALE)))
.build();
readonly isDisciplineRankingDownloading = this.store.select(selectIsDisciplineRankingDownloading);
constructor(
private readonly store: Store,
) {
}
ngOnInit(): void {
this.store.dispatch(loadRankingData());
}
downloadTotalRanking(): void {
const genders = createGenderListOfTree(this.totalTree);
this.store.dispatch(downloadTotalRankingAction({genders}));
}
downloadTriathlonRanking(): void {
const genders = createGenderListOfTree(this.triathlonTree);
this.store.dispatch(downloadTriathlonRankingAction({genders}));
}
downloadUbsCupRanking(): void {
const genders = createGenderListOfTree(this.ubsCupTree);
this.store.dispatch(downloadUbsCupRankingAction({genders}));
}
downloadDisciplineRanking(): void {
const disciplines = this.disciplinesTree.checkedNodes
.map(disciplineNode =>
disciplineNode.checkedNodes.map<DisciplineRanking>(genderNode => (
{
discipline: disciplineNode.value,
gender: genderDtoOfValue(genderNode.value),
}
)))
.reduce(flatMapping(), []);
this.store.dispatch(downloadDisciplineRankingAction({disciplines}));
}
}
function createGenderListOfTree(tree: TreeCheckNodeModel): ReadonlyArray<GenderDto> {
return tree.checkedNodes.map(node => genderDtoOfValue(node.value));
} | random_line_split |
|
ranking-export.component.ts | import { Component, OnInit } from "@angular/core";
import { faDownload } from "@fortawesome/free-solid-svg-icons/faDownload";
import { Store } from "@ngrx/store";
import { flatMapping } from "../../../@core/lib/collections";
import { ALL_DISCIPLINES } from "../../../dto/athletics";
import { GenderDto, genderDtoOfValue } from "../../../dto/participation";
import { DisciplineRanking } from "../../../dto/ranking";
import { FEMALE, MALE } from "../../../modules/participant/gender/gender-constants";
import { LABEL_ALL, TreeCheckNodeModel } from "../../../modules/tree/tree-model";
import {
downloadDisciplineRankingAction,
downloadTotalRankingAction,
downloadTriathlonRankingAction,
downloadUbsCupRankingAction,
loadRankingData,
} from "../../../store/ranking/ranking.action";
import {
selectIsDisciplineRankingDownloading,
selectIsParticipationOpen,
selectIsTotalRankingDownloading,
selectIsTriathlonRankingDownloading,
selectIsUbsCupRankingDownloading,
} from "../../../store/ranking/ranking.selector";
const GENDER_TREE_BUILDER = TreeCheckNodeModel.newBuilder()
.setLabel(LABEL_ALL)
.setCollapsedEnabled(false)
.addLeafNode(MALE, GenderDto.MALE)
.addLeafNode(FEMALE, GenderDto.FEMALE);
@Component({
selector: "app-ranking-export",
templateUrl: "./ranking-export.component.html",
})
export class RankingExportComponent implements OnInit {
readonly faDownload = faDownload;
readonly isParticipationOpen$ = this.store.select(selectIsParticipationOpen);
readonly totalTree = GENDER_TREE_BUILDER.build();
readonly isTotalRankingDownloading = this.store.select(selectIsTotalRankingDownloading);
readonly triathlonTree = GENDER_TREE_BUILDER.build();
readonly isTriathlonRankingDownloading = this.store.select(selectIsTriathlonRankingDownloading);
readonly ubsCupTree = GENDER_TREE_BUILDER.build();
readonly isUbsCupRankingDownloading = this.store.select(selectIsUbsCupRankingDownloading);
readonly disciplinesTree = TreeCheckNodeModel.newBuilder()
.setLabel(LABEL_ALL)
.setCollapsedEnabled(false)
// tslint:disable-next-line:no-magic-numbers
.setSplitting(4)
.addNodes(ALL_DISCIPLINES.map(discipline =>
TreeCheckNodeModel.newBuilder()
.setLabel(discipline)
.setCollapsed(true)
.addLeafNode(MALE, GenderDto.MALE)
.addLeafNode(FEMALE, GenderDto.FEMALE)))
.build();
readonly isDisciplineRankingDownloading = this.store.select(selectIsDisciplineRankingDownloading);
constructor(
private readonly store: Store,
) {
}
ngOnInit(): void {
this.store.dispatch(loadRankingData());
}
downloadTotalRanking(): void |
downloadTriathlonRanking(): void {
const genders = createGenderListOfTree(this.triathlonTree);
this.store.dispatch(downloadTriathlonRankingAction({genders}));
}
downloadUbsCupRanking(): void {
const genders = createGenderListOfTree(this.ubsCupTree);
this.store.dispatch(downloadUbsCupRankingAction({genders}));
}
downloadDisciplineRanking(): void {
const disciplines = this.disciplinesTree.checkedNodes
.map(disciplineNode =>
disciplineNode.checkedNodes.map<DisciplineRanking>(genderNode => (
{
discipline: disciplineNode.value,
gender: genderDtoOfValue(genderNode.value),
}
)))
.reduce(flatMapping(), []);
this.store.dispatch(downloadDisciplineRankingAction({disciplines}));
}
}
function createGenderListOfTree(tree: TreeCheckNodeModel): ReadonlyArray<GenderDto> {
return tree.checkedNodes.map(node => genderDtoOfValue(node.value));
}
| {
const genders = createGenderListOfTree(this.totalTree);
this.store.dispatch(downloadTotalRankingAction({genders}));
} | identifier_body |
ranking-export.component.ts | import { Component, OnInit } from "@angular/core";
import { faDownload } from "@fortawesome/free-solid-svg-icons/faDownload";
import { Store } from "@ngrx/store";
import { flatMapping } from "../../../@core/lib/collections";
import { ALL_DISCIPLINES } from "../../../dto/athletics";
import { GenderDto, genderDtoOfValue } from "../../../dto/participation";
import { DisciplineRanking } from "../../../dto/ranking";
import { FEMALE, MALE } from "../../../modules/participant/gender/gender-constants";
import { LABEL_ALL, TreeCheckNodeModel } from "../../../modules/tree/tree-model";
import {
downloadDisciplineRankingAction,
downloadTotalRankingAction,
downloadTriathlonRankingAction,
downloadUbsCupRankingAction,
loadRankingData,
} from "../../../store/ranking/ranking.action";
import {
selectIsDisciplineRankingDownloading,
selectIsParticipationOpen,
selectIsTotalRankingDownloading,
selectIsTriathlonRankingDownloading,
selectIsUbsCupRankingDownloading,
} from "../../../store/ranking/ranking.selector";
const GENDER_TREE_BUILDER = TreeCheckNodeModel.newBuilder()
.setLabel(LABEL_ALL)
.setCollapsedEnabled(false)
.addLeafNode(MALE, GenderDto.MALE)
.addLeafNode(FEMALE, GenderDto.FEMALE);
@Component({
selector: "app-ranking-export",
templateUrl: "./ranking-export.component.html",
})
export class RankingExportComponent implements OnInit {
readonly faDownload = faDownload;
readonly isParticipationOpen$ = this.store.select(selectIsParticipationOpen);
readonly totalTree = GENDER_TREE_BUILDER.build();
readonly isTotalRankingDownloading = this.store.select(selectIsTotalRankingDownloading);
readonly triathlonTree = GENDER_TREE_BUILDER.build();
readonly isTriathlonRankingDownloading = this.store.select(selectIsTriathlonRankingDownloading);
readonly ubsCupTree = GENDER_TREE_BUILDER.build();
readonly isUbsCupRankingDownloading = this.store.select(selectIsUbsCupRankingDownloading);
readonly disciplinesTree = TreeCheckNodeModel.newBuilder()
.setLabel(LABEL_ALL)
.setCollapsedEnabled(false)
// tslint:disable-next-line:no-magic-numbers
.setSplitting(4)
.addNodes(ALL_DISCIPLINES.map(discipline =>
TreeCheckNodeModel.newBuilder()
.setLabel(discipline)
.setCollapsed(true)
.addLeafNode(MALE, GenderDto.MALE)
.addLeafNode(FEMALE, GenderDto.FEMALE)))
.build();
readonly isDisciplineRankingDownloading = this.store.select(selectIsDisciplineRankingDownloading);
constructor(
private readonly store: Store,
) {
}
ngOnInit(): void {
this.store.dispatch(loadRankingData());
}
downloadTotalRanking(): void {
const genders = createGenderListOfTree(this.totalTree);
this.store.dispatch(downloadTotalRankingAction({genders}));
}
downloadTriathlonRanking(): void {
const genders = createGenderListOfTree(this.triathlonTree);
this.store.dispatch(downloadTriathlonRankingAction({genders}));
}
downloadUbsCupRanking(): void {
const genders = createGenderListOfTree(this.ubsCupTree);
this.store.dispatch(downloadUbsCupRankingAction({genders}));
}
| (): void {
const disciplines = this.disciplinesTree.checkedNodes
.map(disciplineNode =>
disciplineNode.checkedNodes.map<DisciplineRanking>(genderNode => (
{
discipline: disciplineNode.value,
gender: genderDtoOfValue(genderNode.value),
}
)))
.reduce(flatMapping(), []);
this.store.dispatch(downloadDisciplineRankingAction({disciplines}));
}
}
function createGenderListOfTree(tree: TreeCheckNodeModel): ReadonlyArray<GenderDto> {
return tree.checkedNodes.map(node => genderDtoOfValue(node.value));
}
| downloadDisciplineRanking | identifier_name |
nuxt.config.js | module.exports = {
head: {
title: 'Encounter Tracker',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: 'Fan-Made Dungeons and Dragons 4th edition Encounter Tracker'
}
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' }
]
},
plugins: ['~/plugins/vuetify.js'],
css : [
// '~/assets/css/normalize.scss',
'~/assets/css/font-awesome.min.css',
// '~/assets/css/base.scss',
// '~/assets/css/mixins.scss',
'~/assets/style/app.styl'
],
loading: { color: '#3B8070' },
build: {
vendor: ['vuetify'],
extractCSS: true,
/*
** Run ESLINT on save
*/
// extend (config, ctx) {
// if (ctx.dev && ctx.isClient) {
// config.module.rules.push({
// enforce: 'pre',
// test: /\.(js|vue)$/, | // })
// }
// }
}
} | // loader: 'eslint-loader',
// exclude: /(node_modules)/ | random_line_split |
tests.rs | use super::rocket;
use rocket::local::Client;
use rocket::http::{ContentType, Status};
fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T)
where T: Into<Option<&'static str>>
{
let client = Client::new(rocket()).unwrap();
let query = format!("username={}&password={}&age={}", user, pass, age);
let mut response = client.post("/login")
.header(ContentType::Form)
.body(&query)
.dispatch();
assert_eq!(response.status(), status);
if let Some(expected_str) = body.into() {
let body_str = response.body_string();
assert!(body_str.map_or(false, |s| s.contains(expected_str)));
}
}
#[test]
fn test_good_login() |
#[test]
fn test_invalid_user() {
test_login("-1", "password", "30", Status::Ok, "Unrecognized user");
test_login("Mike", "password", "30", Status::Ok, "Unrecognized user");
}
#[test]
fn test_invalid_password() {
test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!");
test_login("Sergio", "ok", "30", Status::Ok, "Password is invalid: too short!");
}
#[test]
fn test_invalid_age() {
test_login("Sergio", "password", "20", Status::Ok, "must be at least 21.");
test_login("Sergio", "password", "-100", Status::Ok, "must be at least 21.");
test_login("Sergio", "password", "hi", Status::Ok, "value is not a number");
}
fn check_bad_form(form_str: &str, status: Status) {
let client = Client::new(rocket()).unwrap();
let response = client.post("/login")
.header(ContentType::Form)
.body(form_str)
.dispatch();
assert_eq!(response.status(), status);
}
#[test]
fn test_bad_form_abnromal_inputs() {
check_bad_form("&", Status::BadRequest);
check_bad_form("=", Status::BadRequest);
check_bad_form("&&&===&", Status::BadRequest);
}
#[test]
fn test_bad_form_missing_fields() {
let bad_inputs: [&str; 6] = [
"username=Sergio",
"password=pass",
"age=30",
"username=Sergio&password=pass",
"username=Sergio&age=30",
"password=pass&age=30"
];
for bad_input in bad_inputs.into_iter() {
check_bad_form(bad_input, Status::UnprocessableEntity);
}
}
#[test]
fn test_bad_form_additional_fields() {
check_bad_form("username=Sergio&password=pass&age=30&addition=1",
Status::UnprocessableEntity);
}
| {
test_login("Sergio", "password", "30", Status::SeeOther, None);
} | identifier_body |
tests.rs | use super::rocket;
use rocket::local::Client;
use rocket::http::{ContentType, Status};
fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T)
where T: Into<Option<&'static str>>
{
let client = Client::new(rocket()).unwrap();
let query = format!("username={}&password={}&age={}", user, pass, age);
let mut response = client.post("/login")
.header(ContentType::Form)
.body(&query)
.dispatch();
assert_eq!(response.status(), status);
if let Some(expected_str) = body.into() |
}
#[test]
fn test_good_login() {
test_login("Sergio", "password", "30", Status::SeeOther, None);
}
#[test]
fn test_invalid_user() {
test_login("-1", "password", "30", Status::Ok, "Unrecognized user");
test_login("Mike", "password", "30", Status::Ok, "Unrecognized user");
}
#[test]
fn test_invalid_password() {
test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!");
test_login("Sergio", "ok", "30", Status::Ok, "Password is invalid: too short!");
}
#[test]
fn test_invalid_age() {
test_login("Sergio", "password", "20", Status::Ok, "must be at least 21.");
test_login("Sergio", "password", "-100", Status::Ok, "must be at least 21.");
test_login("Sergio", "password", "hi", Status::Ok, "value is not a number");
}
fn check_bad_form(form_str: &str, status: Status) {
let client = Client::new(rocket()).unwrap();
let response = client.post("/login")
.header(ContentType::Form)
.body(form_str)
.dispatch();
assert_eq!(response.status(), status);
}
#[test]
fn test_bad_form_abnromal_inputs() {
check_bad_form("&", Status::BadRequest);
check_bad_form("=", Status::BadRequest);
check_bad_form("&&&===&", Status::BadRequest);
}
#[test]
fn test_bad_form_missing_fields() {
let bad_inputs: [&str; 6] = [
"username=Sergio",
"password=pass",
"age=30",
"username=Sergio&password=pass",
"username=Sergio&age=30",
"password=pass&age=30"
];
for bad_input in bad_inputs.into_iter() {
check_bad_form(bad_input, Status::UnprocessableEntity);
}
}
#[test]
fn test_bad_form_additional_fields() {
check_bad_form("username=Sergio&password=pass&age=30&addition=1",
Status::UnprocessableEntity);
}
| {
let body_str = response.body_string();
assert!(body_str.map_or(false, |s| s.contains(expected_str)));
} | conditional_block |
tests.rs | use super::rocket;
use rocket::local::Client;
use rocket::http::{ContentType, Status};
fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T)
where T: Into<Option<&'static str>>
{
let client = Client::new(rocket()).unwrap();
let query = format!("username={}&password={}&age={}", user, pass, age);
let mut response = client.post("/login")
.header(ContentType::Form)
.body(&query)
.dispatch();
assert_eq!(response.status(), status);
if let Some(expected_str) = body.into() {
let body_str = response.body_string();
assert!(body_str.map_or(false, |s| s.contains(expected_str)));
}
}
#[test]
fn test_good_login() {
test_login("Sergio", "password", "30", Status::SeeOther, None);
}
#[test]
fn test_invalid_user() {
test_login("-1", "password", "30", Status::Ok, "Unrecognized user");
test_login("Mike", "password", "30", Status::Ok, "Unrecognized user");
}
#[test]
fn test_invalid_password() {
test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!");
test_login("Sergio", "ok", "30", Status::Ok, "Password is invalid: too short!");
}
#[test]
fn test_invalid_age() {
test_login("Sergio", "password", "20", Status::Ok, "must be at least 21.");
test_login("Sergio", "password", "-100", Status::Ok, "must be at least 21.");
test_login("Sergio", "password", "hi", Status::Ok, "value is not a number");
}
fn check_bad_form(form_str: &str, status: Status) {
let client = Client::new(rocket()).unwrap();
let response = client.post("/login")
.header(ContentType::Form)
.body(form_str)
.dispatch();
assert_eq!(response.status(), status);
}
#[test]
fn | () {
check_bad_form("&", Status::BadRequest);
check_bad_form("=", Status::BadRequest);
check_bad_form("&&&===&", Status::BadRequest);
}
#[test]
fn test_bad_form_missing_fields() {
let bad_inputs: [&str; 6] = [
"username=Sergio",
"password=pass",
"age=30",
"username=Sergio&password=pass",
"username=Sergio&age=30",
"password=pass&age=30"
];
for bad_input in bad_inputs.into_iter() {
check_bad_form(bad_input, Status::UnprocessableEntity);
}
}
#[test]
fn test_bad_form_additional_fields() {
check_bad_form("username=Sergio&password=pass&age=30&addition=1",
Status::UnprocessableEntity);
}
| test_bad_form_abnromal_inputs | identifier_name |
tests.rs | use super::rocket;
use rocket::local::Client;
use rocket::http::{ContentType, Status};
fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T)
where T: Into<Option<&'static str>>
{
let client = Client::new(rocket()).unwrap();
let query = format!("username={}&password={}&age={}", user, pass, age);
let mut response = client.post("/login")
.header(ContentType::Form)
.body(&query)
.dispatch();
assert_eq!(response.status(), status);
if let Some(expected_str) = body.into() {
let body_str = response.body_string();
assert!(body_str.map_or(false, |s| s.contains(expected_str)));
}
}
#[test]
fn test_good_login() {
test_login("Sergio", "password", "30", Status::SeeOther, None);
}
#[test]
fn test_invalid_user() {
test_login("-1", "password", "30", Status::Ok, "Unrecognized user");
test_login("Mike", "password", "30", Status::Ok, "Unrecognized user");
}
#[test]
fn test_invalid_password() {
test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!");
test_login("Sergio", "ok", "30", Status::Ok, "Password is invalid: too short!");
}
#[test]
fn test_invalid_age() {
test_login("Sergio", "password", "20", Status::Ok, "must be at least 21.");
test_login("Sergio", "password", "-100", Status::Ok, "must be at least 21.");
test_login("Sergio", "password", "hi", Status::Ok, "value is not a number");
}
fn check_bad_form(form_str: &str, status: Status) {
let client = Client::new(rocket()).unwrap();
let response = client.post("/login")
.header(ContentType::Form)
.body(form_str)
.dispatch(); | #[test]
fn test_bad_form_abnromal_inputs() {
check_bad_form("&", Status::BadRequest);
check_bad_form("=", Status::BadRequest);
check_bad_form("&&&===&", Status::BadRequest);
}
#[test]
fn test_bad_form_missing_fields() {
let bad_inputs: [&str; 6] = [
"username=Sergio",
"password=pass",
"age=30",
"username=Sergio&password=pass",
"username=Sergio&age=30",
"password=pass&age=30"
];
for bad_input in bad_inputs.into_iter() {
check_bad_form(bad_input, Status::UnprocessableEntity);
}
}
#[test]
fn test_bad_form_additional_fields() {
check_bad_form("username=Sergio&password=pass&age=30&addition=1",
Status::UnprocessableEntity);
} |
assert_eq!(response.status(), status);
}
| random_line_split |
component.js | import type { Config } from '../src/core/config'
import type VNode from '../src/core/vdom/vnode'
import type Watcher from '../src/core/observer/watcher'
declare interface Component {
// constructor information
static cid: number;
static options: Object;
// extend
static extend: (options: Object) => Function;
static superOptions: Object;
static extendOptions: Object;
static sealedOptions: Object;
static super: Class<Component>;
// assets
static directive: (id: string, def?: Function | Object) => Function | Object | void;
static component: (id: string, def?: Class<Component> | Object) => Class<Component>;
static filter: (id: string, def?: Function) => Function | void;
// public properties
$el: any; // so that we can attach __vue__ to it
$data: Object;
$options: ComponentOptions;
$parent: Component | void;
$root: Component;
$children: Array<Component>;
$refs: { [key: string]: Component | Element | Array<Component | Element> | void };
$slots: { [key: string]: Array<VNode> };
$scopedSlots: { [key: string]: () => VNodeChildren };
$vnode: VNode; // the placeholder node for the component in parent's render tree
$isServer: boolean;
$props: Object;
// public methods
$mount: (el?: Element | string, hydrating?: boolean) => Component;
$forceUpdate: () => void;
$destroy: () => void;
$set: <T>(target: Object | Array<T>, key: string | number, val: T) => T;
$delete: <T>(target: Object | Array<T>, key: string | number) => void;
$watch: (expOrFn: string | Function, cb: Function, options?: Object) => Function;
$on: (event: string | Array<string>, fn: Function) => Component;
$once: (event: string, fn: Function) => Component;
$off: (event?: string | Array<string>, fn?: Function) => Component;
$emit: (event: string, ...args: Array<mixed>) => Component;
$nextTick: (fn: Function) => void | Promise<*>; | _uid: number;
_name: string; // this only exists in dev mode
_isVue: true;
_self: Component;
_renderProxy: Component;
_renderContext: ?Component;
_watcher: Watcher;
_watchers: Array<Watcher>;
_computedWatchers: { [key: string]: Watcher };
_data: Object;
_props: Object;
_events: Object;
_inactive: boolean | null;
_directInactive: boolean;
_isMounted: boolean;
_isDestroyed: boolean;
_isBeingDestroyed: boolean;
_vnode: ?VNode; // self root node
_staticTrees: ?Array<VNode>;
_hasHookEvent: boolean;
_provided: ?Object;
// private methods
// lifecycle
_init: Function;
_mount: (el?: Element | void, hydrating?: boolean) => Component;
_update: (vnode: VNode, hydrating?: boolean) => void;
// rendering
_render: () => VNode;
__patch__: (a: Element | VNode | void, b: VNode) => any;
// createElement
// _c is internal that accepts `normalizationType` optimization hint
_c: (vnode?: VNode, data?: VNodeData, children?: VNodeChildren, normalizationType?: number) => VNode | void;
// renderStatic
_m: (index: number, isInFor?: boolean) => VNode | VNodeChildren;
// markOnce
_o: (vnode: VNode | Array<VNode>, index: number, key: string) => VNode | VNodeChildren;
// toString
_s: (value: mixed) => string;
// text to VNode
_v: (value: string | number) => VNode;
// toNumber
_n: (value: string) => number | string;
// empty vnode
_e: () => VNode;
// loose equal
_q: (a: mixed, b: mixed) => boolean;
// loose indexOf
_i: (arr: Array<mixed>, val: mixed) => number;
// resolveFilter
_f: (id: string) => Function;
// renderList
_l: (val: mixed, render: Function) => ?Array<VNode>;
// renderSlot
_t: (name: string, fallback: ?Array<VNode>, props: ?Object) => ?Array<VNode>;
// apply v-bind object
_b: (data: any, value: any, asProp?: boolean) => VNodeData;
// check custom keyCode
_k: (eventKeyCode: number, key: string, builtInAlias: number | Array<number> | void) => boolean;
// resolve scoped slots
_u: (scopedSlots: ScopedSlotsData, res?: Object) => { [key: string]: Function };
// allow dynamic method registration
[key: string]: any
} | $createElement: (tag?: string | Component, data?: Object, children?: VNodeChildren) => VNode;
// private properties | random_line_split |
firestore.spec.ts | import { expect } from 'chai';
import { firestore, initializeApp } from 'firebase-admin';
import fft = require('../../../src/index');
describe('providers/firestore', () => {
before(() => {
initializeApp();
});
it('clears database with clearFirestoreData', async () => {
const test = fft({ projectId: 'not-a-project' });
const db = firestore();
await Promise.all([
db
.collection('test')
.doc('doc1')
.set({}),
db
.collection('test')
.doc('doc1')
.collection('test')
.doc('doc2')
.set({}),
]);
await test.firestore.clearFirestoreData({ projectId: 'not-a-project' });
const docs = await Promise.all([
db
.collection('test')
.doc('doc1')
.get(),
db
.collection('test') | .get(),
]);
expect(docs[0].exists).to.be.false;
expect(docs[1].exists).to.be.false;
});
}); | .doc('doc1')
.collection('test')
.doc('doc2') | random_line_split |
moviescanner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# === This file is part of RateItSeven ===
#
# Copyright 2015, Paolo de Vathaire <paolo.devathaire@gmail.com>
#
# RateItSeven is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RateItSeven is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with RateItSeven. If not, see <http://www.gnu.org/licenses/>.
#
import guessit
from rateItSeven.scan.legacy.filescanner import FileScanner
from rateItSeven.scan.legacy.containers.movieguess import MovieGuess
class MovieScanner(object):
"""
Scan file system directories for video files
Find info for each file wrapped into a MovieGuess
"""
def __init__(self, dir_paths: list):
self.dir_paths = dir_paths
def | (self):
return self.list_videos_in_types(["movie"])
def list_episodes(self):
return self.list_videos_in_types(["episode"])
def list_videos_in_types(self, video_types):
file_scanner = FileScanner(self.dir_paths)
for abs_path in file_scanner.absolute_file_paths():
guess = MovieGuess(guessit.guessit(abs_path), abs_path)
if guess.is_video_in_types(video_types):
yield guess
| list_movies | identifier_name |
moviescanner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# === This file is part of RateItSeven ===
#
# Copyright 2015, Paolo de Vathaire <paolo.devathaire@gmail.com>
#
# RateItSeven is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RateItSeven is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with RateItSeven. If not, see <http://www.gnu.org/licenses/>.
#
import guessit
from rateItSeven.scan.legacy.filescanner import FileScanner
from rateItSeven.scan.legacy.containers.movieguess import MovieGuess
class MovieScanner(object):
"""
Scan file system directories for video files
Find info for each file wrapped into a MovieGuess
"""
def __init__(self, dir_paths: list):
self.dir_paths = dir_paths
def list_movies(self):
return self.list_videos_in_types(["movie"])
def list_episodes(self):
return self.list_videos_in_types(["episode"])
def list_videos_in_types(self, video_types):
file_scanner = FileScanner(self.dir_paths)
for abs_path in file_scanner.absolute_file_paths():
guess = MovieGuess(guessit.guessit(abs_path), abs_path)
if guess.is_video_in_types(video_types):
| yield guess | conditional_block |
|
moviescanner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# === This file is part of RateItSeven ===
#
# Copyright 2015, Paolo de Vathaire <paolo.devathaire@gmail.com>
#
# RateItSeven is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RateItSeven is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with RateItSeven. If not, see <http://www.gnu.org/licenses/>.
#
import guessit
from rateItSeven.scan.legacy.filescanner import FileScanner
from rateItSeven.scan.legacy.containers.movieguess import MovieGuess
class MovieScanner(object):
"""
Scan file system directories for video files
Find info for each file wrapped into a MovieGuess
"""
def __init__(self, dir_paths: list):
self.dir_paths = dir_paths
def list_movies(self):
return self.list_videos_in_types(["movie"])
def list_episodes(self):
return self.list_videos_in_types(["episode"])
def list_videos_in_types(self, video_types):
| file_scanner = FileScanner(self.dir_paths)
for abs_path in file_scanner.absolute_file_paths():
guess = MovieGuess(guessit.guessit(abs_path), abs_path)
if guess.is_video_in_types(video_types):
yield guess | identifier_body |
|
moviescanner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# === This file is part of RateItSeven ===
#
# Copyright 2015, Paolo de Vathaire <paolo.devathaire@gmail.com>
#
# RateItSeven is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RateItSeven is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with RateItSeven. If not, see <http://www.gnu.org/licenses/>.
#
import guessit
from rateItSeven.scan.legacy.filescanner import FileScanner
| from rateItSeven.scan.legacy.containers.movieguess import MovieGuess
class MovieScanner(object):
"""
Scan file system directories for video files
Find info for each file wrapped into a MovieGuess
"""
def __init__(self, dir_paths: list):
self.dir_paths = dir_paths
def list_movies(self):
return self.list_videos_in_types(["movie"])
def list_episodes(self):
return self.list_videos_in_types(["episode"])
def list_videos_in_types(self, video_types):
file_scanner = FileScanner(self.dir_paths)
for abs_path in file_scanner.absolute_file_paths():
guess = MovieGuess(guessit.guessit(abs_path), abs_path)
if guess.is_video_in_types(video_types):
yield guess | random_line_split |
|
class-cast-to-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
trait noisy {
fn speak(&self);
}
struct cat {
priv meows : uint,
how_hungry : int,
name : ~str,
}
impl cat {
pub fn eat(&self) -> bool {
if self.how_hungry > 0 |
else {
error!("Not hungry!");
return false;
}
}
}
impl noisy for cat {
fn speak(&self) { self.meow(); }
}
impl cat {
fn meow(&self) {
error!("Meow");
self.meows += 1;
if self.meows % 5 == 0 {
self.how_hungry += 1;
}
}
}
fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
fn main() {
let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy;
nyan.eat(); //~ ERROR does not implement any method in scope named `eat`
}
| {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
} | conditional_block |
class-cast-to-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
trait noisy {
fn speak(&self);
}
struct cat {
priv meows : uint,
how_hungry : int,
name : ~str,
}
impl cat {
pub fn eat(&self) -> bool {
if self.how_hungry > 0 {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
error!("Not hungry!");
return false;
}
}
}
impl noisy for cat {
fn speak(&self) { self.meow(); }
}
impl cat {
fn meow(&self) |
}
fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
fn main() {
let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy;
nyan.eat(); //~ ERROR does not implement any method in scope named `eat`
}
| {
error!("Meow");
self.meows += 1;
if self.meows % 5 == 0 {
self.how_hungry += 1;
}
} | identifier_body |
class-cast-to-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
trait noisy {
fn speak(&self);
}
struct cat {
priv meows : uint,
how_hungry : int,
name : ~str,
}
impl cat {
pub fn eat(&self) -> bool {
if self.how_hungry > 0 {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
error!("Not hungry!");
return false;
}
}
}
impl noisy for cat {
fn speak(&self) { self.meow(); }
}
impl cat {
fn meow(&self) {
error!("Meow");
self.meows += 1;
if self.meows % 5 == 0 {
self.how_hungry += 1;
}
}
}
fn | (in_x : uint, in_y : int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
fn main() {
let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy;
nyan.eat(); //~ ERROR does not implement any method in scope named `eat`
}
| cat | identifier_name |
class-cast-to-trait.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[feature(managed_boxes)];
trait noisy {
fn speak(&self);
}
struct cat {
priv meows : uint,
how_hungry : int,
name : ~str,
}
impl cat {
pub fn eat(&self) -> bool {
if self.how_hungry > 0 {
error!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
error!("Not hungry!"); |
impl noisy for cat {
fn speak(&self) { self.meow(); }
}
impl cat {
fn meow(&self) {
error!("Meow");
self.meows += 1;
if self.meows % 5 == 0 {
self.how_hungry += 1;
}
}
}
fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
fn main() {
let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy;
nyan.eat(); //~ ERROR does not implement any method in scope named `eat`
} | return false;
}
}
} | random_line_split |
combineLatestWith.ts | import { ObservableInputTuple, OperatorFunction, Cons } from '../types';
import { combineLatest } from './combineLatest';
/**
* Create an observable that combines the latest values from all passed observables and the source
* into arrays and emits them.
*
* Returns an observable, that when subscribed to, will subscribe to the source observable and all
* sources provided as arguments. Once all sources emit at least one value, all of the latest values
* will be emitted as an array. After that, every time any source emits a value, all of the latest values
* will be emitted as an array.
*
* This is a useful operator for eagerly calculating values based off of changed inputs.
*
* ## Example
*
* Simple concatenation of values from two inputs
*
* ```ts
* import { fromEvent, combineLatestWith, map } from 'rxjs';
*
* // Setup: Add two inputs to the page
* const input1 = document.createElement('input');
* document.body.appendChild(input1);
* const input2 = document.createElement('input');
* document.body.appendChild(input2);
*
* // Get streams of changes
* const input1Changes$ = fromEvent(input1, 'change');
* const input2Changes$ = fromEvent(input2, 'change');
* | * // Combine the changes by adding them together
* input1Changes$.pipe(
* combineLatestWith(input2Changes$),
* map(([e1, e2]) => (<HTMLInputElement>e1.target).value + ' - ' + (<HTMLInputElement>e2.target).value)
* )
* .subscribe(x => console.log(x));
* ```
*
* @param otherSources the other sources to subscribe to.
* @return A function that returns an Observable that emits the latest
* emissions from both source and provided Observables.
*/
export function combineLatestWith<T, A extends readonly unknown[]>(
...otherSources: [...ObservableInputTuple<A>]
): OperatorFunction<T, Cons<T, A>> {
return combineLatest(...otherSources);
} | random_line_split |
|
combineLatestWith.ts | import { ObservableInputTuple, OperatorFunction, Cons } from '../types';
import { combineLatest } from './combineLatest';
/**
* Create an observable that combines the latest values from all passed observables and the source
* into arrays and emits them.
*
* Returns an observable, that when subscribed to, will subscribe to the source observable and all
* sources provided as arguments. Once all sources emit at least one value, all of the latest values
* will be emitted as an array. After that, every time any source emits a value, all of the latest values
* will be emitted as an array.
*
* This is a useful operator for eagerly calculating values based off of changed inputs.
*
* ## Example
*
* Simple concatenation of values from two inputs
*
* ```ts
* import { fromEvent, combineLatestWith, map } from 'rxjs';
*
* // Setup: Add two inputs to the page
* const input1 = document.createElement('input');
* document.body.appendChild(input1);
* const input2 = document.createElement('input');
* document.body.appendChild(input2);
*
* // Get streams of changes
* const input1Changes$ = fromEvent(input1, 'change');
* const input2Changes$ = fromEvent(input2, 'change');
*
* // Combine the changes by adding them together
* input1Changes$.pipe(
* combineLatestWith(input2Changes$),
* map(([e1, e2]) => (<HTMLInputElement>e1.target).value + ' - ' + (<HTMLInputElement>e2.target).value)
* )
* .subscribe(x => console.log(x));
* ```
*
* @param otherSources the other sources to subscribe to.
* @return A function that returns an Observable that emits the latest
* emissions from both source and provided Observables.
*/
export function | <T, A extends readonly unknown[]>(
...otherSources: [...ObservableInputTuple<A>]
): OperatorFunction<T, Cons<T, A>> {
return combineLatest(...otherSources);
}
| combineLatestWith | identifier_name |
combineLatestWith.ts | import { ObservableInputTuple, OperatorFunction, Cons } from '../types';
import { combineLatest } from './combineLatest';
/**
* Create an observable that combines the latest values from all passed observables and the source
* into arrays and emits them.
*
* Returns an observable, that when subscribed to, will subscribe to the source observable and all
* sources provided as arguments. Once all sources emit at least one value, all of the latest values
* will be emitted as an array. After that, every time any source emits a value, all of the latest values
* will be emitted as an array.
*
* This is a useful operator for eagerly calculating values based off of changed inputs.
*
* ## Example
*
* Simple concatenation of values from two inputs
*
* ```ts
* import { fromEvent, combineLatestWith, map } from 'rxjs';
*
* // Setup: Add two inputs to the page
* const input1 = document.createElement('input');
* document.body.appendChild(input1);
* const input2 = document.createElement('input');
* document.body.appendChild(input2);
*
* // Get streams of changes
* const input1Changes$ = fromEvent(input1, 'change');
* const input2Changes$ = fromEvent(input2, 'change');
*
* // Combine the changes by adding them together
* input1Changes$.pipe(
* combineLatestWith(input2Changes$),
* map(([e1, e2]) => (<HTMLInputElement>e1.target).value + ' - ' + (<HTMLInputElement>e2.target).value)
* )
* .subscribe(x => console.log(x));
* ```
*
* @param otherSources the other sources to subscribe to.
* @return A function that returns an Observable that emits the latest
* emissions from both source and provided Observables.
*/
export function combineLatestWith<T, A extends readonly unknown[]>(
...otherSources: [...ObservableInputTuple<A>]
): OperatorFunction<T, Cons<T, A>> | {
return combineLatest(...otherSources);
} | identifier_body |
|
cfg-macros-notfoo.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast compile-flags directive doesn't work for check-fast
// compile-flags:
// check that cfg correctly chooses between the macro impls (see also
// cfg-macros-foo.rs)
#[cfg(foo)]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { true }
}
}
#[cfg(not(foo))]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { false }
}
}
fn main() | {
assert!(!bar!())
} | identifier_body |
|
cfg-macros-notfoo.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast compile-flags directive doesn't work for check-fast
// compile-flags:
// check that cfg correctly chooses between the macro impls (see also
// cfg-macros-foo.rs)
#[cfg(foo)]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { true }
}
}
#[cfg(not(foo))]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { false }
}
}
fn | () {
assert!(!bar!())
}
| main | identifier_name |
cfg-macros-notfoo.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast compile-flags directive doesn't work for check-fast
// compile-flags:
// check that cfg correctly chooses between the macro impls (see also
// cfg-macros-foo.rs)
| macro_rules! bar {
() => { true }
}
}
#[cfg(not(foo))]
#[macro_escape]
mod foo {
macro_rules! bar {
() => { false }
}
}
fn main() {
assert!(!bar!())
} | #[cfg(foo)]
#[macro_escape]
mod foo { | random_line_split |
atom.rs | use pyo3::prelude::*;
use rayon::prelude::*;
use std::collections::HashMap;
use crate::becke_partitioning;
use crate::bragg;
use crate::bse;
use crate::lebedev;
use crate::radial;
#[pyfunction]
pub fn | (
basis_set: &str,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) {
let (alpha_min, alpha_max) =
bse::ang_min_and_max(basis_set, proton_charges[center_index] as usize);
atom_grid(
alpha_min,
alpha_max,
radial_precision,
min_num_angular_points,
max_num_angular_points,
proton_charges,
center_index,
center_coordinates_bohr,
hardness,
)
}
#[pyfunction]
pub fn atom_grid(
alpha_min: HashMap<usize, f64>,
alpha_max: f64,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) {
let (rs, weights_radial) = radial::radial_grid_lmg(
alpha_min,
alpha_max,
radial_precision,
proton_charges[center_index],
);
// factors match DIRAC code
let rb = bragg::get_bragg_angstrom(proton_charges[center_index]) / (5.0 * 0.529177249);
let mut coordinates = Vec::new();
let mut weights = Vec::new();
let pi = std::f64::consts::PI;
let cx = center_coordinates_bohr[center_index].0;
let cy = center_coordinates_bohr[center_index].1;
let cz = center_coordinates_bohr[center_index].2;
for (&r, &weight_radial) in rs.iter().zip(weights_radial.iter()) {
// we read the angular grid at each radial step because of pruning
// this can be optimized
let mut num_angular = max_num_angular_points;
if r < rb {
num_angular = ((max_num_angular_points as f64) * r / rb) as usize;
num_angular = lebedev::get_closest_num_angular(num_angular);
if num_angular < min_num_angular_points {
num_angular = min_num_angular_points;
}
}
let (coordinates_angular, weights_angular) = lebedev::angular_grid(num_angular);
let wt = 4.0 * pi * weight_radial;
for (&xyz, &weight_angular) in coordinates_angular.iter().zip(weights_angular.iter()) {
let x = cx + r * xyz.0;
let y = cy + r * xyz.1;
let z = cz + r * xyz.2;
coordinates.push((x, y, z));
weights.push(wt * weight_angular);
}
}
if center_coordinates_bohr.len() > 1 {
let w_partitioning: Vec<f64> = coordinates
.par_iter()
.map(|c| {
becke_partitioning::partitioning_weight(
center_index,
¢er_coordinates_bohr,
&proton_charges,
*c,
hardness,
)
})
.collect();
for (i, w) in weights.iter_mut().enumerate() {
*w *= w_partitioning[i];
}
}
(coordinates, weights)
}
| atom_grid_bse | identifier_name |
atom.rs | use pyo3::prelude::*;
use rayon::prelude::*;
use std::collections::HashMap;
use crate::becke_partitioning;
use crate::bragg;
use crate::bse;
use crate::lebedev;
use crate::radial;
#[pyfunction]
pub fn atom_grid_bse(
basis_set: &str,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) |
#[pyfunction]
pub fn atom_grid(
alpha_min: HashMap<usize, f64>,
alpha_max: f64,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) {
let (rs, weights_radial) = radial::radial_grid_lmg(
alpha_min,
alpha_max,
radial_precision,
proton_charges[center_index],
);
// factors match DIRAC code
let rb = bragg::get_bragg_angstrom(proton_charges[center_index]) / (5.0 * 0.529177249);
let mut coordinates = Vec::new();
let mut weights = Vec::new();
let pi = std::f64::consts::PI;
let cx = center_coordinates_bohr[center_index].0;
let cy = center_coordinates_bohr[center_index].1;
let cz = center_coordinates_bohr[center_index].2;
for (&r, &weight_radial) in rs.iter().zip(weights_radial.iter()) {
// we read the angular grid at each radial step because of pruning
// this can be optimized
let mut num_angular = max_num_angular_points;
if r < rb {
num_angular = ((max_num_angular_points as f64) * r / rb) as usize;
num_angular = lebedev::get_closest_num_angular(num_angular);
if num_angular < min_num_angular_points {
num_angular = min_num_angular_points;
}
}
let (coordinates_angular, weights_angular) = lebedev::angular_grid(num_angular);
let wt = 4.0 * pi * weight_radial;
for (&xyz, &weight_angular) in coordinates_angular.iter().zip(weights_angular.iter()) {
let x = cx + r * xyz.0;
let y = cy + r * xyz.1;
let z = cz + r * xyz.2;
coordinates.push((x, y, z));
weights.push(wt * weight_angular);
}
}
if center_coordinates_bohr.len() > 1 {
let w_partitioning: Vec<f64> = coordinates
.par_iter()
.map(|c| {
becke_partitioning::partitioning_weight(
center_index,
¢er_coordinates_bohr,
&proton_charges,
*c,
hardness,
)
})
.collect();
for (i, w) in weights.iter_mut().enumerate() {
*w *= w_partitioning[i];
}
}
(coordinates, weights)
}
| {
let (alpha_min, alpha_max) =
bse::ang_min_and_max(basis_set, proton_charges[center_index] as usize);
atom_grid(
alpha_min,
alpha_max,
radial_precision,
min_num_angular_points,
max_num_angular_points,
proton_charges,
center_index,
center_coordinates_bohr,
hardness,
)
} | identifier_body |
atom.rs | use pyo3::prelude::*;
use rayon::prelude::*;
use std::collections::HashMap;
use crate::becke_partitioning;
use crate::bragg;
use crate::bse;
use crate::lebedev;
use crate::radial;
#[pyfunction]
pub fn atom_grid_bse(
basis_set: &str,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) {
let (alpha_min, alpha_max) =
bse::ang_min_and_max(basis_set, proton_charges[center_index] as usize);
atom_grid(
alpha_min,
alpha_max,
radial_precision,
min_num_angular_points,
max_num_angular_points,
proton_charges,
center_index,
center_coordinates_bohr,
hardness,
)
}
#[pyfunction]
pub fn atom_grid(
alpha_min: HashMap<usize, f64>,
alpha_max: f64,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) {
let (rs, weights_radial) = radial::radial_grid_lmg(
alpha_min,
alpha_max,
radial_precision,
proton_charges[center_index],
);
// factors match DIRAC code
let rb = bragg::get_bragg_angstrom(proton_charges[center_index]) / (5.0 * 0.529177249);
let mut coordinates = Vec::new();
let mut weights = Vec::new();
let pi = std::f64::consts::PI;
let cx = center_coordinates_bohr[center_index].0;
let cy = center_coordinates_bohr[center_index].1;
let cz = center_coordinates_bohr[center_index].2;
for (&r, &weight_radial) in rs.iter().zip(weights_radial.iter()) {
// we read the angular grid at each radial step because of pruning
// this can be optimized
let mut num_angular = max_num_angular_points;
if r < rb {
num_angular = ((max_num_angular_points as f64) * r / rb) as usize;
num_angular = lebedev::get_closest_num_angular(num_angular);
if num_angular < min_num_angular_points {
num_angular = min_num_angular_points;
}
}
let (coordinates_angular, weights_angular) = lebedev::angular_grid(num_angular);
let wt = 4.0 * pi * weight_radial;
for (&xyz, &weight_angular) in coordinates_angular.iter().zip(weights_angular.iter()) {
let x = cx + r * xyz.0;
let y = cy + r * xyz.1;
let z = cz + r * xyz.2;
coordinates.push((x, y, z));
weights.push(wt * weight_angular);
}
}
if center_coordinates_bohr.len() > 1 |
(coordinates, weights)
}
| {
let w_partitioning: Vec<f64> = coordinates
.par_iter()
.map(|c| {
becke_partitioning::partitioning_weight(
center_index,
¢er_coordinates_bohr,
&proton_charges,
*c,
hardness,
)
})
.collect();
for (i, w) in weights.iter_mut().enumerate() {
*w *= w_partitioning[i];
}
} | conditional_block |
atom.rs | use pyo3::prelude::*;
use rayon::prelude::*;
use std::collections::HashMap;
use crate::becke_partitioning;
use crate::bragg;
use crate::bse;
use crate::lebedev;
use crate::radial;
#[pyfunction]
pub fn atom_grid_bse(
basis_set: &str,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) {
let (alpha_min, alpha_max) =
bse::ang_min_and_max(basis_set, proton_charges[center_index] as usize);
atom_grid(
alpha_min,
alpha_max,
radial_precision,
min_num_angular_points,
max_num_angular_points,
proton_charges,
center_index,
center_coordinates_bohr,
hardness,
)
}
#[pyfunction]
pub fn atom_grid(
alpha_min: HashMap<usize, f64>,
alpha_max: f64,
radial_precision: f64,
min_num_angular_points: usize,
max_num_angular_points: usize,
proton_charges: Vec<i32>,
center_index: usize,
center_coordinates_bohr: Vec<(f64, f64, f64)>,
hardness: usize,
) -> (Vec<(f64, f64, f64)>, Vec<f64>) {
let (rs, weights_radial) = radial::radial_grid_lmg(
alpha_min,
alpha_max,
radial_precision,
proton_charges[center_index],
);
// factors match DIRAC code
let rb = bragg::get_bragg_angstrom(proton_charges[center_index]) / (5.0 * 0.529177249);
let mut coordinates = Vec::new();
let mut weights = Vec::new();
let pi = std::f64::consts::PI;
let cx = center_coordinates_bohr[center_index].0;
let cy = center_coordinates_bohr[center_index].1;
let cz = center_coordinates_bohr[center_index].2;
for (&r, &weight_radial) in rs.iter().zip(weights_radial.iter()) {
// we read the angular grid at each radial step because of pruning
// this can be optimized
let mut num_angular = max_num_angular_points; | num_angular = lebedev::get_closest_num_angular(num_angular);
if num_angular < min_num_angular_points {
num_angular = min_num_angular_points;
}
}
let (coordinates_angular, weights_angular) = lebedev::angular_grid(num_angular);
let wt = 4.0 * pi * weight_radial;
for (&xyz, &weight_angular) in coordinates_angular.iter().zip(weights_angular.iter()) {
let x = cx + r * xyz.0;
let y = cy + r * xyz.1;
let z = cz + r * xyz.2;
coordinates.push((x, y, z));
weights.push(wt * weight_angular);
}
}
if center_coordinates_bohr.len() > 1 {
let w_partitioning: Vec<f64> = coordinates
.par_iter()
.map(|c| {
becke_partitioning::partitioning_weight(
center_index,
¢er_coordinates_bohr,
&proton_charges,
*c,
hardness,
)
})
.collect();
for (i, w) in weights.iter_mut().enumerate() {
*w *= w_partitioning[i];
}
}
(coordinates, weights)
} | if r < rb {
num_angular = ((max_num_angular_points as f64) * r / rb) as usize; | random_line_split |
application.js | import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
import config from 'ilios/config/environment';
const { inject } = Ember;
const { service } = inject;
export default Ember.Route.extend(ApplicationRouteMixin, {
flashMessages: service(),
commonAjax: service(),
i18n: service(),
moment: service(),
/**
* Leave titles as an array
* All of our routes send translations for the 'titleToken' key and we do the translating in head.hbs
* and in the application controller.
* @param Array tokens
* @return Array
*/
title(tokens){
return tokens;
},
//Override the default session invalidator so we can do auth stuff
| () {
if (!Ember.testing) {
let logoutUrl = '/auth/logout';
return this.get('commonAjax').request(logoutUrl).then(response => {
if(response.status === 'redirect'){
window.location.replace(response.logoutUrl);
} else {
this.get('flashMessages').success('general.confirmLogout');
window.location.replace(config.rootURL);
}
});
}
},
beforeModel() {
const i18n = this.get('i18n');
const moment = this.get('moment');
moment.setLocale(i18n.get('locale'));
},
actions: {
willTransition: function() {
let controller = this.controllerFor('application');
controller.set('errors', []);
controller.set('showErrorDisplay', false);
}
}
});
| sessionInvalidated | identifier_name |
application.js | import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
import config from 'ilios/config/environment';
const { inject } = Ember;
const { service } = inject;
export default Ember.Route.extend(ApplicationRouteMixin, {
flashMessages: service(),
commonAjax: service(),
i18n: service(),
moment: service(),
/**
* Leave titles as an array
* All of our routes send translations for the 'titleToken' key and we do the translating in head.hbs
* and in the application controller.
* @param Array tokens
* @return Array
*/
title(tokens){
return tokens;
},
//Override the default session invalidator so we can do auth stuff
sessionInvalidated() {
if (!Ember.testing) {
let logoutUrl = '/auth/logout';
return this.get('commonAjax').request(logoutUrl).then(response => {
if(response.status === 'redirect'){
window.location.replace(response.logoutUrl);
} else |
});
}
},
beforeModel() {
const i18n = this.get('i18n');
const moment = this.get('moment');
moment.setLocale(i18n.get('locale'));
},
actions: {
willTransition: function() {
let controller = this.controllerFor('application');
controller.set('errors', []);
controller.set('showErrorDisplay', false);
}
}
});
| {
this.get('flashMessages').success('general.confirmLogout');
window.location.replace(config.rootURL);
} | conditional_block |
application.js | import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
import config from 'ilios/config/environment';
const { inject } = Ember;
const { service } = inject;
export default Ember.Route.extend(ApplicationRouteMixin, {
flashMessages: service(),
commonAjax: service(), | * Leave titles as an array
* All of our routes send translations for the 'titleToken' key and we do the translating in head.hbs
* and in the application controller.
* @param Array tokens
* @return Array
*/
title(tokens){
return tokens;
},
//Override the default session invalidator so we can do auth stuff
sessionInvalidated() {
if (!Ember.testing) {
let logoutUrl = '/auth/logout';
return this.get('commonAjax').request(logoutUrl).then(response => {
if(response.status === 'redirect'){
window.location.replace(response.logoutUrl);
} else {
this.get('flashMessages').success('general.confirmLogout');
window.location.replace(config.rootURL);
}
});
}
},
beforeModel() {
const i18n = this.get('i18n');
const moment = this.get('moment');
moment.setLocale(i18n.get('locale'));
},
actions: {
willTransition: function() {
let controller = this.controllerFor('application');
controller.set('errors', []);
controller.set('showErrorDisplay', false);
}
}
}); | i18n: service(),
moment: service(),
/** | random_line_split |
application.js | import Ember from 'ember';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
import config from 'ilios/config/environment';
const { inject } = Ember;
const { service } = inject;
export default Ember.Route.extend(ApplicationRouteMixin, {
flashMessages: service(),
commonAjax: service(),
i18n: service(),
moment: service(),
/**
* Leave titles as an array
* All of our routes send translations for the 'titleToken' key and we do the translating in head.hbs
* and in the application controller.
* @param Array tokens
* @return Array
*/
title(tokens) | ,
//Override the default session invalidator so we can do auth stuff
sessionInvalidated() {
if (!Ember.testing) {
let logoutUrl = '/auth/logout';
return this.get('commonAjax').request(logoutUrl).then(response => {
if(response.status === 'redirect'){
window.location.replace(response.logoutUrl);
} else {
this.get('flashMessages').success('general.confirmLogout');
window.location.replace(config.rootURL);
}
});
}
},
beforeModel() {
const i18n = this.get('i18n');
const moment = this.get('moment');
moment.setLocale(i18n.get('locale'));
},
actions: {
willTransition: function() {
let controller = this.controllerFor('application');
controller.set('errors', []);
controller.set('showErrorDisplay', false);
}
}
});
| {
return tokens;
} | identifier_body |
index.js |
/**
* App routes.
*/
var homepage = require('./homepage');
var user = require('./user');
var news = require('./news');
var test = require('./test');
var passport = require('passport');
function | (req, res, next) {
if (req.isAuthenticated()) { return next(); }
req.flash('error', '抱歉,您尚未登录。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensureAdmin(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin) { return next(); }
req.flash('error', '抱歉,您不是管理员。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensurePermission(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin)
{ return next(); }
if (req.isAuthenticated() &&
req.user.username == req.params.id)
{ return next(); }
req.flash('error', '抱歉,您没有权限。');
return res.redirect('/user/signin?redirect=' + req.path);
}
module.exports = function(app) {
app.get('/', homepage.index);
app.get('/user', ensureAdmin, user.showList);
app.get('/user/page/:page(\\d+)', ensureAdmin, user.showList);
app.get('/user/register', user.showRegister);
app.post('/user/register', user.doRegister);
app.get('/user/signin', user.showSignin);
app.post('/user/signin', passport.authenticate('local',
{ successRedirect: '/',
successFlash: '登录成功,欢迎回来。',
failureRedirect: 'back',
failureFlash: '抱歉,手机号或密码错误。',
}));
app.get('/user/signout', user.doSignout);
app.get('/user/:id(\\d{8,13})/edit', ensurePermission, user.showEditUser);
app.post('/user/:id(\\d{8,13})/edit', ensurePermission, user.doEditUser);
app.get('/user/:id(\\d{8,13})/setadmin', ensureAdmin, user.setAdmin);
app.get('/news', news.showList);
app.get('/news/page/:page(\\d+)', news.showList);
app.get('/news/:id(\\d+)', news.showItem);
app.get('/news/:id(\\d+)/edit', ensureAdmin, news.showEditItem);
app.post('/news/:id(\\d+)/edit', ensureAdmin, news.doEditItem);
app.get('/news/:id(\\d+)/delete', ensureAdmin, news.doDeleteItem);
app.get('/news/post', ensureAdmin, news.showNewItem);
app.post('/news/post', ensureAdmin, news.doNewItem);
app.get('/test', test);
app.get('*', function(req, res){
return res.render('homepage', {title: '404'});
});
}
| ensureAuthenticated | identifier_name |
index.js | /**
* App routes.
*/
var homepage = require('./homepage');
var user = require('./user');
var news = require('./news');
var test = require('./test');
var passport = require('passport');
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
req.flash('error', '抱歉,您尚未登录。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensureAdmin(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin) { return next(); }
req.flash('error', '抱歉,您不是管理员。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensurePermission(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin)
{ return next(); }
if (req.isAuthenticated() &&
req.user.username == req.params.id)
{ return next(); }
req.flash('error', '抱歉,您没有权限。'); | }
module.exports = function(app) {
app.get('/', homepage.index);
app.get('/user', ensureAdmin, user.showList);
app.get('/user/page/:page(\\d+)', ensureAdmin, user.showList);
app.get('/user/register', user.showRegister);
app.post('/user/register', user.doRegister);
app.get('/user/signin', user.showSignin);
app.post('/user/signin', passport.authenticate('local',
{ successRedirect: '/',
successFlash: '登录成功,欢迎回来。',
failureRedirect: 'back',
failureFlash: '抱歉,手机号或密码错误。',
}));
app.get('/user/signout', user.doSignout);
app.get('/user/:id(\\d{8,13})/edit', ensurePermission, user.showEditUser);
app.post('/user/:id(\\d{8,13})/edit', ensurePermission, user.doEditUser);
app.get('/user/:id(\\d{8,13})/setadmin', ensureAdmin, user.setAdmin);
app.get('/news', news.showList);
app.get('/news/page/:page(\\d+)', news.showList);
app.get('/news/:id(\\d+)', news.showItem);
app.get('/news/:id(\\d+)/edit', ensureAdmin, news.showEditItem);
app.post('/news/:id(\\d+)/edit', ensureAdmin, news.doEditItem);
app.get('/news/:id(\\d+)/delete', ensureAdmin, news.doDeleteItem);
app.get('/news/post', ensureAdmin, news.showNewItem);
app.post('/news/post', ensureAdmin, news.doNewItem);
app.get('/test', test);
app.get('*', function(req, res){
return res.render('homepage', {title: '404'});
});
} | return res.redirect('/user/signin?redirect=' + req.path); | random_line_split |
index.js |
/**
* App routes.
*/
var homepage = require('./homepage');
var user = require('./user');
var news = require('./news');
var test = require('./test');
var passport = require('passport');
function ensureAuthenticated(req, res, next) | dmin(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin) { return next(); }
req.flash('error', '抱歉,您不是管理员。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensurePermission(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin)
{ return next(); }
if (req.isAuthenticated() &&
req.user.username == req.params.id)
{ return next(); }
req.flash('error', '抱歉,您没有权限。');
return res.redirect('/user/signin?redirect=' + req.path);
}
module.exports = function(app) {
app.get('/', homepage.index);
app.get('/user', ensureAdmin, user.showList);
app.get('/user/page/:page(\\d+)', ensureAdmin, user.showList);
app.get('/user/register', user.showRegister);
app.post('/user/register', user.doRegister);
app.get('/user/signin', user.showSignin);
app.post('/user/signin', passport.authenticate('local',
{ successRedirect: '/',
successFlash: '登录成功,欢迎回来。',
failureRedirect: 'back',
failureFlash: '抱歉,手机号或密码错误。',
}));
app.get('/user/signout', user.doSignout);
app.get('/user/:id(\\d{8,13})/edit', ensurePermission, user.showEditUser);
app.post('/user/:id(\\d{8,13})/edit', ensurePermission, user.doEditUser);
app.get('/user/:id(\\d{8,13})/setadmin', ensureAdmin, user.setAdmin);
app.get('/news', news.showList);
app.get('/news/page/:page(\\d+)', news.showList);
app.get('/news/:id(\\d+)', news.showItem);
app.get('/news/:id(\\d+)/edit', ensureAdmin, news.showEditItem);
app.post('/news/:id(\\d+)/edit', ensureAdmin, news.doEditItem);
app.get('/news/:id(\\d+)/delete', ensureAdmin, news.doDeleteItem);
app.get('/news/post', ensureAdmin, news.showNewItem);
app.post('/news/post', ensureAdmin, news.doNewItem);
app.get('/test', test);
app.get('*', function(req, res){
return res.render('homepage', {title: '404'});
});
}
| {
if (req.isAuthenticated()) { return next(); }
req.flash('error', '抱歉,您尚未登录。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensureA | identifier_body |
index.js |
/**
* App routes.
*/
var homepage = require('./homepage');
var user = require('./user');
var news = require('./news');
var test = require('./test');
var passport = require('passport');
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
req.flash('error', '抱歉,您尚未登录。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensureAdmin(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin) { return next(); }
req.flash('error', '抱歉,您不是管理员。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensurePermission(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin)
{ return next(); }
if (req.isAuthe | req.user.username == req.params.id)
{ return next(); }
req.flash('error', '抱歉,您没有权限。');
return res.redirect('/user/signin?redirect=' + req.path);
}
module.exports = function(app) {
app.get('/', homepage.index);
app.get('/user', ensureAdmin, user.showList);
app.get('/user/page/:page(\\d+)', ensureAdmin, user.showList);
app.get('/user/register', user.showRegister);
app.post('/user/register', user.doRegister);
app.get('/user/signin', user.showSignin);
app.post('/user/signin', passport.authenticate('local',
{ successRedirect: '/',
successFlash: '登录成功,欢迎回来。',
failureRedirect: 'back',
failureFlash: '抱歉,手机号或密码错误。',
}));
app.get('/user/signout', user.doSignout);
app.get('/user/:id(\\d{8,13})/edit', ensurePermission, user.showEditUser);
app.post('/user/:id(\\d{8,13})/edit', ensurePermission, user.doEditUser);
app.get('/user/:id(\\d{8,13})/setadmin', ensureAdmin, user.setAdmin);
app.get('/news', news.showList);
app.get('/news/page/:page(\\d+)', news.showList);
app.get('/news/:id(\\d+)', news.showItem);
app.get('/news/:id(\\d+)/edit', ensureAdmin, news.showEditItem);
app.post('/news/:id(\\d+)/edit', ensureAdmin, news.doEditItem);
app.get('/news/:id(\\d+)/delete', ensureAdmin, news.doDeleteItem);
app.get('/news/post', ensureAdmin, news.showNewItem);
app.post('/news/post', ensureAdmin, news.doNewItem);
app.get('/test', test);
app.get('*', function(req, res){
return res.render('homepage', {title: '404'});
});
}
| nticated() &&
| conditional_block |
Ix.ts | import * as assert from 'assert'
import * as _ from '../src/Ix'
import * as O from 'fp-ts/lib/Option'
import { eqString } from 'fp-ts/lib/Eq'
import * as U from './util'
describe('Ix', () => {
it('indexReadonlyMap', () => {
const index = _.indexReadonlyMap(eqString)<number>().index('a')
U.deepStrictEqual(index.getOption(new Map([])), O.none)
U.deepStrictEqual(
index.getOption(
new Map([
['a', 1],
['b', 2] | U.deepStrictEqual(
index.set(3)(
new Map([
['a', 1],
['b', 2]
])
),
new Map([
['a', 3],
['b', 2]
])
)
// should return the same reference if nothing changed
const x = new Map([
['a', 1],
['b', 2]
])
assert.strictEqual(index.set(1)(x), x)
})
}) | ])
),
O.some(1)
)
U.deepStrictEqual(index.set(3)(new Map([['b', 2]])), new Map([['b', 2]])) | random_line_split |
hikashop.js | {
window.Oby.removeClass(elementToCheck, 'invalid');
}
}
return true;
}
(function() {
function preventDefault() { this.returnValue = false; }
function stopPropagation() { this.cancelBubble = true; }
var Oby = {
version: 20140128,
ajaxEvents : {},
hasClass : function(o,n) {
if(o.className == '' ) return false;
var reg = new RegExp("(^|\\s+)"+n+"(\\s+|$)");
return reg.test(o.className);
},
addClass : function(o,n) {
if( !this.hasClass(o,n) ) {
if( o.className == '' ) {
o.className = n;
} else {
o.className += ' '+n;
}
}
},
trim : function(s) {
return (s ? '' + s : '').replace(/^\s*|\s*$/g, '');
},
removeClass : function(e, c) {
var t = this;
if( t.hasClass(e,c) ) {
var cn = ' ' + e.className + ' ';
e.className = t.trim(cn.replace(' '+c+' ',' '));
}
},
addEvent : function(d,e,f) {
if( d.attachEvent )
d.attachEvent('on' + e, f);
else if (d.addEventListener)
d.addEventListener(e, f, false);
else
d['on' + e] = f;
return f;
},
removeEvent : function(d,e,f) {
try {
if( d.detachEvent )
d.detachEvent('on' + e, f);
else if( d.removeEventListener)
d.removeEventListener(e, f, false);
else
d['on' + e] = null;
} catch(e) {}
},
cancelEvent : function(e) {
if( !e ) {
e = window.event;
if( !e )
return false;
}
if(e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
if( e.preventDefault )
e.preventDefault();
else
e.returnValue = false;
return false;
},
fireEvent : function(d,e) {
if(document.createEvent) |
else
d.fireEvent("on"+e);
},
fireAjax : function(name,params) {
var t = this, ev;
if( t.ajaxEvents[name] === undefined )
return false;
for(var e in t.ajaxEvents[name]) {
if( e != '_id' ) {
ev = t.ajaxEvents[name][e];
ev(params);
}
}
return true;
},
registerAjax : function(name, fct) {
var t = this;
if( t.ajaxEvents[name] === undefined )
t.ajaxEvents[name] = {'_id':0};
var id = t.ajaxEvents[name]['_id'];
t.ajaxEvents[name]['_id'] += 1;
t.ajaxEvents[name][id] = fct;
return id;
},
unregisterAjax : function(name, id) {
if( t.ajaxEvents[name] === undefined || t.ajaxEvents[name][id] === undefined)
return false;
t.ajaxEvents[name][id] = null;
return true;
},
ready: function(fct) {
var w = window, d = document, t = this;
if(d.readyState === "complete") {
fct();
return;
}
var done = false, top = true, root = d.documentElement,
init = function(e) {
if(e.type == 'readystatechange' && d.readyState != 'complete') return;
t.removeEvent((e.type == 'load' ? w : d), e.type, init);
if(!done && (done = true))
fct();
},
poll = function() {
try{ root.doScroll('left'); } catch(e){ setTimeout(poll, 50); return; }
init('poll');
};
if(d.createEventObject && root.doScroll) {
try{ top = !w.frameElement; } catch(e){}
if(top) poll();
}
t.addEvent(d,'DOMContentLoaded',init);
t.addEvent(d,'readystatechange',init);
t.addEvent(w,'load',init);
},
evalJSON : function(text, secure) {
if( typeof(text) != "string" || !text.length) return null;
if( secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(text.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
return eval('(' + text + ')');
},
getXHR : function() {
var xhr = null, w = window;
if(w.XMLHttpRequest || w.ActiveXObject) {
if(w.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
} else
xhr = new w.XMLHttpRequest();
}
return xhr;
},
xRequest: function(url, options, cb, cbError) {
var t = this, xhr = t.getXHR();
if(!options) options = {};
if(!cb) cb = function(){};
options.mode = options.mode || 'GET';
options.update = options.update || false;
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if( xhr.status == 200 || (xhr.status == 0 && xhr.responseText > 0) || !cbError ) {
if(cb)
cb(xhr,options.params);
if(options.update)
t.updateElem(options.update, xhr.responseText);
} else {
cbError(xhr,options.params);
}
}
};
xhr.open(options.mode, url, true);
if( options.mode.toUpperCase() == 'POST' ) {
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}
xhr.send( options.data );
},
getFormData : function(target) {
var d = document, ret = '';
if( typeof(target) == 'string' )
target = d.getElementById(target);
if( target === undefined )
target = d;
var typelist = ['input','select','textarea'];
for(var t in typelist ) {
t = typelist[t];
var inputs = target.getElementsByTagName(t);
for(var i = inputs.length - 1; i >= 0; i--) {
if( inputs[i].name && !inputs[i].disabled ) {
var evalue = inputs[i].value, etype = '';
if( t == 'input' )
etype = inputs[i].type.toLowerCase();
if( (etype == 'radio' || etype == 'checkbox') && !inputs[i].checked )
evalue = null;
if( (etype != 'file' && etype != 'submit') && evalue != null ) {
if( ret != '' ) ret += '&';
ret += encodeURI(inputs[i].name) + '=' + encodeURIComponent(evalue);
}
}
}
}
return ret;
},
updateElem : function(elem, data) {
var d = document, scripts = '';
if( typeof(elem) == 'string' )
elem = d.getElementById(elem);
var text = data.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
scripts += code + '\n';
return '';
});
elem.innerHTML = text;
if( scripts != '' ) {
var script = d.createElement('script');
script.setAttribute('type', 'text/javascript');
script.text = scripts;
d.head.appendChild(script);
d.head.removeChild(script);
}
}
};
if((typeof(window.Oby) == 'undefined') || window.Oby.version < Oby.version) {
window.Oby = Oby;
window.obscurelighty = Oby;
}
var oldHikaShop = window.hikashop || hikashop;
var hikashop = {
submitFct: null,
submitBox: function(data) {
var t = this, d = document, w = window;
if( t.submitFct ) {
try {
t.submitFct(data);
} catch(err) {}
}
t.closeBox();
},
deleteId: function(id) {
var t = this, d = document, el = id;
if( typeof(id) == "string") {
el = d.getElementById(id);
}
if(!el)
return;
el.parentNode.removeChild(el);
},
dup: function(tplName, htmlblocks, id, extraData, appendTo) {
var d = document, tplElem = d.getElementById(tplName),
container = tplElem.parentNode;
if(!tplElem) return;
elem = tplElem.cloneNode(true);
if(!appendTo) {
container.insertBefore(elem, tplElem);
} else {
| {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(e, false, true);
d.dispatchEvent(evt);
} | conditional_block |
hikashop.js |
function hikashopCheckChangeForm(type,form)
{
if(!form)
return true;
var varform = document[form];
if(typeof hikashopFieldsJs != 'undefined' && typeof hikashopFieldsJs['reqFieldsComp'] != 'undefined' && typeof hikashopFieldsJs['reqFieldsComp'][type] != 'undefined' && hikashopFieldsJs['reqFieldsComp'][type].length > 0)
{
for(var i =0;i<hikashopFieldsJs['reqFieldsComp'][type].length;i++)
{
elementName = 'data['+type+']['+hikashopFieldsJs['reqFieldsComp'][type][i]+']';
if( typeof varform.elements[elementName]=='undefined'){
elementName = type+'_'+hikashopFieldsJs['reqFieldsComp'][type][i];
}
elementToCheck = varform.elements[elementName];
elementId = 'hikashop_'+type+'_'+ hikashopFieldsJs['reqFieldsComp'][type][i];
el = document.getElementById(elementId);
if(elementToCheck && (typeof el == 'undefined' || el == null || typeof el.style == 'undefined' || el.style.display!='none') && !hikashopCheckField(elementToCheck,type,i,elementName,varform.elements)){
if(typeof hikashopFieldsJs['entry_id'] == 'undefined')
return false;
for(var j =1;j<=hikashop['entry_id'];j++){
elementName = 'data['+type+'][entry_'+j+']['+hikashopFieldsJs['reqFieldsComp'][type][i]+']';
elementToCheck = varform.elements[elementName];
elementId = 'hikashop_'+type+'_'+ hikashopFieldsJs['reqFieldsComp'][type][i] + '_' + j;
el = document.getElementById(elementId);
if(elementToCheck && (typeof el == 'undefined' || el == null || typeof el.style == 'undefined' || el.style.display!='none') && !hikashopCheckField(elementToCheck,type,i,elementName,varform.elements)){
return false;
}
}
}
}
if(type=='register'){
//check password
if(typeof varform.elements['data[register][password]'] != 'undefined' && typeof varform.elements['data[register][password2]'] != 'undefined'){
passwd = varform.elements['data[register][password]'];
passwd2 = varform.elements['data[register][password2]'];
if(passwd.value!=passwd2.value){
alert(hikashopFieldsJs['password_different']);
return false;
}
}
//check email
var emailField = varform.elements['data[register][email]'];
emailField.value = emailField.value.replace(/ /g,"");
var filter = /^([a-z0-9_'&\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,10})+$/i;
if(!emailField || !filter.test(emailField.value)){
alert(hikashopFieldsJs['valid_email']);
return false;
}
}else if(type=='address' && typeof varform.elements['data[address][address_telephone]'] != 'undefined'){
var phoneField = varform.elements['data[address][address_telephone]'], filter = /[0-9]+/i;
if(phoneField){
phoneField.value = phoneField.value.replace(/ /g,"");
if(phoneField.value.length > 0 && !filter.test(phoneField.value)){
alert(hikashopFieldsJs['valid_phone']);
return false;
}
}
}
}
return true;
}
function hikashopCheckField(elementToCheck,type,i,elementName,form){
if(elementToCheck){
var isValid = false;
if(typeof elementToCheck.value != 'undefined'){
if(elementToCheck.value==' ' && typeof form[elementName+'[]'] != 'undefined'){
if(form[elementName+'[]'].checked){
isValid = true;
}else{
for(var a=0; a < form[elementName+'[]'].length; a++){
if(form[elementName+'[]'][a].checked && form[elementName+'[]'][a].value.length>0) isValid = true;
}
}
}else{
if(elementToCheck.value.length>0) isValid = true;
}
}else{
for(var a=0; a < elementToCheck.length; a++){
if(elementToCheck[a].checked && elementToCheck[a].value.length>0) isValid = true;
}
}
//Case for the switcher display, ignore check according to the method selected
var simplified_pwd = document.getElementById('data[register][registration_method]3');
var simplified = document.getElementById('data[register][registration_method]1');
var guest = document.getElementById('data[register][registration_method]2');
if(!isValid && ((simplified && simplified.checked) || (guest && guest.checked) ) && (elementName=='data[register][password]' || elementName=='data[register][password2]')){
window.Oby.addClass(elementToCheck, 'invalid');
return true;
}
if (!isValid && ( (simplified && simplified.checked) || (guest && guest.checked) || (simplified_pwd && simplified_pwd.checked) ) && (elementName=='data[register][name]' || elementName=='data[register][username]'))
{
window.Oby.addClass(elementToCheck, 'invalid');
return true;
}
if(!isValid){
window.Oby.addClass(elementToCheck, 'invalid');
alert(hikashopFieldsJs['validFieldsComp'][type][i]);
return false;
}else{
window.Oby.removeClass(elementToCheck, 'invalid');
}
}
return true;
}
(function() {
function preventDefault() { this.returnValue = false; }
function stopPropagation() { this.cancelBubble = true; }
var Oby = {
version: 20140128,
ajaxEvents : {},
hasClass : function(o,n) {
if(o.className == '' ) return false;
var reg = new RegExp("(^|\\s+)"+n+"(\\s+|$)");
return reg.test(o.className);
},
addClass : function(o,n) {
if( !this.hasClass(o,n) ) {
if( o.className == '' ) {
o.className = n;
} else {
o.className += ' '+n;
}
}
},
trim : function(s) {
return (s ? '' + s : '').replace(/^\s*|\s*$/g, '');
},
removeClass : function(e, c) {
var t = this;
if( t.hasClass(e,c) ) {
var cn = ' ' + e.className + ' ';
e.className = t.trim(cn.replace(' '+c+' ',' '));
}
},
addEvent : function(d,e,f) {
if( d.attachEvent )
d.attachEvent('on' + e, f);
else if (d.addEventListener)
d.addEventListener(e, f, false);
else
d['on' + e] = f;
return f;
},
removeEvent : function(d,e,f) {
try {
if( d.detachEvent )
d.detachEvent('on' + e, f);
else if( d.removeEventListener)
d.removeEventListener(e, f, false);
else
d['on' + e] = null;
} catch(e) {}
},
cancelEvent : function(e) {
if( !e ) {
e = window.event;
if( !e )
return false;
}
if(e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
if( e.preventDefault )
e.preventDefault();
else
e.returnValue = false;
return false;
},
fireEvent : function(d,e) {
if(document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(e, false, true);
d.dispatchEvent(evt);
}
else
d.fireEvent("on"+e);
},
fireAjax : function(name,params) {
var t = this, ev;
if( t.ajaxEvents[name] === undefined )
return false;
for(var e in t.ajaxEvents[name]) {
if( e != '_id' ) {
ev = t.ajaxEvents[name][e];
ev(params);
}
}
return true;
},
registerAjax : function(name, fct) {
var t = this;
if( t.ajaxEvents[name] === undefined )
t.ajaxEvents[name] = {'_id':0};
var id = t.ajaxEvents | {
if (pressbutton) {
document.adminForm.task.value=pressbutton;
}
if( typeof(CodeMirror) == 'function'){
for (x in CodeMirror.instances){
document.getElementById(x).value = CodeMirror.instances[x].getCode();
}
}
if (typeof document.adminForm.onsubmit == "function") {
document.adminForm.onsubmit();
}
document.adminForm.submit();
return false;
} | identifier_body |
|
hikashop.js | ';
return '';
});
elem.innerHTML = text;
if( scripts != '' ) {
var script = d.createElement('script');
script.setAttribute('type', 'text/javascript');
script.text = scripts;
d.head.appendChild(script);
d.head.removeChild(script);
}
}
};
if((typeof(window.Oby) == 'undefined') || window.Oby.version < Oby.version) {
window.Oby = Oby;
window.obscurelighty = Oby;
}
var oldHikaShop = window.hikashop || hikashop;
var hikashop = {
submitFct: null,
submitBox: function(data) {
var t = this, d = document, w = window;
if( t.submitFct ) {
try {
t.submitFct(data);
} catch(err) {}
}
t.closeBox();
},
deleteId: function(id) {
var t = this, d = document, el = id;
if( typeof(id) == "string") {
el = d.getElementById(id);
}
if(!el)
return;
el.parentNode.removeChild(el);
},
dup: function(tplName, htmlblocks, id, extraData, appendTo) {
var d = document, tplElem = d.getElementById(tplName),
container = tplElem.parentNode;
if(!tplElem) return;
elem = tplElem.cloneNode(true);
if(!appendTo) {
container.insertBefore(elem, tplElem);
} else {
if(typeof(appendTo) == "string")
appendTo = d.getElementById(appendTo);
appendTo.appendChild(elem);
}
elem.style.display = "";
elem.id = '';
if(id)
elem.id = id;
for(var k in htmlblocks) {
elem.innerHTML = elem.innerHTML.replace(new RegExp("{"+k+"}","g"), htmlblocks[k]);
elem.innerHTML = elem.innerHTML.replace(new RegExp("%7B"+k+"%7D","g"), htmlblocks[k]);
}
if(extraData) {
for(var k in extraData) {
elem.innerHTML = elem.innerHTML.replace(new RegExp('{'+k+'}','g'), extraData[k]);
elem.innerHTML = elem.innerHTML.replace(new RegExp('%7B'+k+'%7D','g'), extraData[k]);
}
}
},
deleteRow: function(id) {
var t = this, d = document, el = id;
if( typeof(id) == "string") {
el = d.getElementById(id);
} else {
while(el != null && el.tagName.toLowerCase() != 'tr') {
el = el.parentNode;
}
}
if(!el)
return;
var table = el.parentNode;
table.removeChild(el);
if( table.tagName.toLowerCase() == 'tbody' )
table = table.parentNode;
t.cleanTableRows(table);
return;
},
dupRow: function(tplName, htmlblocks, id, extraData) {
var d = document, tplLine = d.getElementById(tplName),
tableUser = tplLine.parentNode;
if(!tplLine) return;
trLine = tplLine.cloneNode(true);
tableUser.appendChild(trLine);
trLine.style.display = "";
trLine.id = "";
if(id)
trLine.id = id;
for(var i = tplLine.cells.length - 1; i >= 0; i--) {
if(trLine.cells[i]) {
for(var k in htmlblocks) {
trLine.cells[i].innerHTML = trLine.cells[i].innerHTML.replace(new RegExp("{"+k+"}","g"), htmlblocks[k]);
trLine.cells[i].innerHTML = trLine.cells[i].innerHTML.replace(new RegExp("%7B"+k+"%7D","g"), htmlblocks[k]);
}
if(extraData) {
for(var k in extraData) {
trLine.cells[i].innerHTML = trLine.cells[i].innerHTML.replace(new RegExp('{'+k+'}','g'), extraData[k]);
trLine.cells[i].innerHTML = trLine.cells[i].innerHTML.replace(new RegExp('%7B'+k+'%7D','g'), extraData[k]);
}
}
}
}
if(tplLine.className == "row0") tplLine.className = "row1";
else if(tplLine.className == "row1") tplLine.className = "row0";
},
cleanTableRows: function(id) {
var d = document, el = id;
if(typeof(id) == "string")
el = d.getElementById(id);
if(el == null || el.tagName.toLowerCase() != 'table')
return;
var k = 0, c = '', line = null, lines = el.getElementsByTagName('tr');
for(var i = 0; i < lines.length; i++) {
line = lines[i];
if( line.style.display != "none") {
c = ' '+line.className+' ';
if( c.indexOf(' row0 ') >= 0 || c.indexOf(' row1 ') >= 0 ) {
line.className = c.replace(' row'+(1-k)+' ', ' row'+k+' ').replace(/^\s*|\s*$/g, '');
k = 1 - k;
}
}
}
},
checkRow: function(id) {
var t = this, d = document, el = id;
if(typeof(id) == "string")
el = d.getElementById(id);
if(el == null || el.tagName.toLowerCase() != 'input')
return;
if(this.clicked) {
this.clicked = null;
t.isChecked(el);
return;
}
el.checked = !el.checked;
t.isChecked(el);
},
isChecked: function(id,cancel) {
var d = document, el = id;
if(typeof(id) == "string")
el = d.getElementById(id);
if(el == null || el.tagName.toLowerCase() != 'input')
return;
if(el.form.boxchecked) {
if(el.checked)
el.form.boxchecked.value++;
else
el.form.boxchecked.value--;
}
},
checkAll: function(checkbox, stub) {
stub = stub || 'cb';
if(checkbox.form) {
var cb = checkbox.form, c = 0;
for(var i = 0, n = cb.elements.length; i < n; i++) {
var e = cb.elements[i];
if (e.type == checkbox.type) {
if ((stub && e.id.indexOf(stub) == 0) || !stub) {
e.checked = checkbox.checked;
c += (e.checked == true ? 1 : 0);
}
}
}
if (cb.boxchecked) {
cb.boxchecked.value = c;
}
return true;
}
return false;
},
submitform: function(task, form, extra) {
var d = document;
if(typeof form == 'string') {
var f = d.getElementById(form);
if(!f)
f = d.forms[form];
if(!f)
return true;
form = f;
}
if(task) {
form.task.value = task;
}
if(typeof form.onsubmit == 'function')
form.onsubmit();
form.submit();
return false;
},
get: function(elem, target) {
window.Oby.xRequest(elem.getAttribute('href'), {update: target});
return false;
},
form: function(elem, target) {
var data = window.Oby.getFormData(target);
window.Oby.xRequest(elem.getAttribute('href'), {update: target, mode: 'POST', data: data});
return false;
},
openBox: function(elem, url, jqmodal) {
var w = window;
if(typeof(elem) == "string")
elem = document.getElementById(elem);
if(!elem)
return false;
try {
if(jqmodal === undefined)
jqmodal = false;
if(!jqmodal && w.SqueezeBox !== undefined) {
if(url !== undefined && url !== null) {
elem.href = url;
}
if(w.SqueezeBox.open !== undefined)
SqueezeBox.open(elem, {parse: 'rel'});
else if(w.SqueezeBox.fromElement !== undefined)
SqueezeBox.fromElement(elem);
} else if(typeof(jQuery) != "undefined") {
var id = elem.getAttribute('id');
jQuery('#modal-' + id).modal('show');
if(url) {
jQuery('#modal-' + id + '-container').find('iframe').attr('src', url);
}
}
} catch(e) {}
return false;
},
closeBox: function(parent) {
var d = document, w = window;
if(parent) {
d = window.parent.document;
w = window.parent;
}
try {
var e = d.getElementById('sbox-window');
if(e && typeof(e.close) != "undefined") {
e.close();
}else if(typeof(w.jQuery) != "undefined" && w.jQuery('div.modal.in') && w.jQuery('div.modal.in').hasClass('in')){ | w.jQuery('div.modal.in').modal('hide');
}else if(w.SqueezeBox !== undefined) {
w.SqueezeBox.close(); | random_line_split |
|
hikashop.js | {
window.Oby.removeClass(elementToCheck, 'invalid');
}
}
return true;
}
(function() {
function preventDefault() { this.returnValue = false; }
function | () { this.cancelBubble = true; }
var Oby = {
version: 20140128,
ajaxEvents : {},
hasClass : function(o,n) {
if(o.className == '' ) return false;
var reg = new RegExp("(^|\\s+)"+n+"(\\s+|$)");
return reg.test(o.className);
},
addClass : function(o,n) {
if( !this.hasClass(o,n) ) {
if( o.className == '' ) {
o.className = n;
} else {
o.className += ' '+n;
}
}
},
trim : function(s) {
return (s ? '' + s : '').replace(/^\s*|\s*$/g, '');
},
removeClass : function(e, c) {
var t = this;
if( t.hasClass(e,c) ) {
var cn = ' ' + e.className + ' ';
e.className = t.trim(cn.replace(' '+c+' ',' '));
}
},
addEvent : function(d,e,f) {
if( d.attachEvent )
d.attachEvent('on' + e, f);
else if (d.addEventListener)
d.addEventListener(e, f, false);
else
d['on' + e] = f;
return f;
},
removeEvent : function(d,e,f) {
try {
if( d.detachEvent )
d.detachEvent('on' + e, f);
else if( d.removeEventListener)
d.removeEventListener(e, f, false);
else
d['on' + e] = null;
} catch(e) {}
},
cancelEvent : function(e) {
if( !e ) {
e = window.event;
if( !e )
return false;
}
if(e.stopPropagation)
e.stopPropagation();
else
e.cancelBubble = true;
if( e.preventDefault )
e.preventDefault();
else
e.returnValue = false;
return false;
},
fireEvent : function(d,e) {
if(document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(e, false, true);
d.dispatchEvent(evt);
}
else
d.fireEvent("on"+e);
},
fireAjax : function(name,params) {
var t = this, ev;
if( t.ajaxEvents[name] === undefined )
return false;
for(var e in t.ajaxEvents[name]) {
if( e != '_id' ) {
ev = t.ajaxEvents[name][e];
ev(params);
}
}
return true;
},
registerAjax : function(name, fct) {
var t = this;
if( t.ajaxEvents[name] === undefined )
t.ajaxEvents[name] = {'_id':0};
var id = t.ajaxEvents[name]['_id'];
t.ajaxEvents[name]['_id'] += 1;
t.ajaxEvents[name][id] = fct;
return id;
},
unregisterAjax : function(name, id) {
if( t.ajaxEvents[name] === undefined || t.ajaxEvents[name][id] === undefined)
return false;
t.ajaxEvents[name][id] = null;
return true;
},
ready: function(fct) {
var w = window, d = document, t = this;
if(d.readyState === "complete") {
fct();
return;
}
var done = false, top = true, root = d.documentElement,
init = function(e) {
if(e.type == 'readystatechange' && d.readyState != 'complete') return;
t.removeEvent((e.type == 'load' ? w : d), e.type, init);
if(!done && (done = true))
fct();
},
poll = function() {
try{ root.doScroll('left'); } catch(e){ setTimeout(poll, 50); return; }
init('poll');
};
if(d.createEventObject && root.doScroll) {
try{ top = !w.frameElement; } catch(e){}
if(top) poll();
}
t.addEvent(d,'DOMContentLoaded',init);
t.addEvent(d,'readystatechange',init);
t.addEvent(w,'load',init);
},
evalJSON : function(text, secure) {
if( typeof(text) != "string" || !text.length) return null;
if( secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(text.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
return eval('(' + text + ')');
},
getXHR : function() {
var xhr = null, w = window;
if(w.XMLHttpRequest || w.ActiveXObject) {
if(w.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
} else
xhr = new w.XMLHttpRequest();
}
return xhr;
},
xRequest: function(url, options, cb, cbError) {
var t = this, xhr = t.getXHR();
if(!options) options = {};
if(!cb) cb = function(){};
options.mode = options.mode || 'GET';
options.update = options.update || false;
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if( xhr.status == 200 || (xhr.status == 0 && xhr.responseText > 0) || !cbError ) {
if(cb)
cb(xhr,options.params);
if(options.update)
t.updateElem(options.update, xhr.responseText);
} else {
cbError(xhr,options.params);
}
}
};
xhr.open(options.mode, url, true);
if( options.mode.toUpperCase() == 'POST' ) {
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
}
xhr.send( options.data );
},
getFormData : function(target) {
var d = document, ret = '';
if( typeof(target) == 'string' )
target = d.getElementById(target);
if( target === undefined )
target = d;
var typelist = ['input','select','textarea'];
for(var t in typelist ) {
t = typelist[t];
var inputs = target.getElementsByTagName(t);
for(var i = inputs.length - 1; i >= 0; i--) {
if( inputs[i].name && !inputs[i].disabled ) {
var evalue = inputs[i].value, etype = '';
if( t == 'input' )
etype = inputs[i].type.toLowerCase();
if( (etype == 'radio' || etype == 'checkbox') && !inputs[i].checked )
evalue = null;
if( (etype != 'file' && etype != 'submit') && evalue != null ) {
if( ret != '' ) ret += '&';
ret += encodeURI(inputs[i].name) + '=' + encodeURIComponent(evalue);
}
}
}
}
return ret;
},
updateElem : function(elem, data) {
var d = document, scripts = '';
if( typeof(elem) == 'string' )
elem = d.getElementById(elem);
var text = data.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
scripts += code + '\n';
return '';
});
elem.innerHTML = text;
if( scripts != '' ) {
var script = d.createElement('script');
script.setAttribute('type', 'text/javascript');
script.text = scripts;
d.head.appendChild(script);
d.head.removeChild(script);
}
}
};
if((typeof(window.Oby) == 'undefined') || window.Oby.version < Oby.version) {
window.Oby = Oby;
window.obscurelighty = Oby;
}
var oldHikaShop = window.hikashop || hikashop;
var hikashop = {
submitFct: null,
submitBox: function(data) {
var t = this, d = document, w = window;
if( t.submitFct ) {
try {
t.submitFct(data);
} catch(err) {}
}
t.closeBox();
},
deleteId: function(id) {
var t = this, d = document, el = id;
if( typeof(id) == "string") {
el = d.getElementById(id);
}
if(!el)
return;
el.parentNode.removeChild(el);
},
dup: function(tplName, htmlblocks, id, extraData, appendTo) {
var d = document, tplElem = d.getElementById(tplName),
container = tplElem.parentNode;
if(!tplElem) return;
elem = tplElem.cloneNode(true);
if(!appendTo) {
container.insertBefore(elem, tplElem);
} else {
if | stopPropagation | identifier_name |
datepicker-input.ts | import { InputBoolean, toBoolean } from '../../util/convert';
import { HostService } from '../../common/host/host.service';
import { NglDateAdapter } from '../adapters/date-fns-adapter';
import { NGL_DATEPICKER_CONFIG, NglDatepickerConfig } from '../config';
import { DEFAULT_DROPDOWN_POSITIONS } from '../../util/overlay-position';
import { parseDate, isDisabled } from '../util';
import { IDatepickerInput } from './datepicker-input.interface';
const NGL_DATEPICKER_INPUT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NglDatepickerInput),
multi: true
};
const NGL_DATEPICKER_INPUT_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => NglDatepickerInput),
multi: true
};
@Component({
selector: 'ngl-datepicker-input',
templateUrl: './datepicker-input.html',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [NGL_DATEPICKER_INPUT_VALUE_ACCESSOR, NGL_DATEPICKER_INPUT_VALIDATOR, HostService],
})
export class NglDatepickerInput implements ControlValueAccessor, Validator, OnInit, OnChanges, OnDestroy {
/**
* Label that appears above the input.
*/
@Input() label: string | TemplateRef<any>;
/**
* Pre-defined format to use.
*/
@Input() format: 'big-endian' | 'little-endian' | 'middle-endian';
/**
* Delimiter to use on pre-defined formats.
*/
@Input() delimiter;
/**
* Disable input and calendar.
*/
@Input() @InputBoolean() disabled: boolean;
/**
* Aligns the right or left side of the dropdown menu with the respective side of the input.
*/
@Input() dropdownAlign: 'left' | 'right';
/**
* The date value.
*/
@Input() set value(value: Date | string | null) {
if (value === this._value) {
return;
}
this._value = value;
if (this.value instanceof Date) {
this.date = this.value;
this.formatInputValue();
} else {
this.updateInputValue(<string>value || '');
}
}
get value(): Date | string | null {
return this._value;
}
/**
* Whether to open the datepicker when a mouse user clicks on the input.
*/
@Input() @InputBoolean() openOnInputClick: boolean;
/**
* Emits when selected date changes.
*/
@Output() valueChange = new EventEmitter<Date | string | null>();
inputEl: IDatepickerInput;
// @ContentChild('inputEl', { static: false }) inputEl: SquareConfig;
@ViewChild('cdkOverlay') cdkOverlay: CdkConnectedOverlay;
/**
* The minimum valid date.
*/
@Input() min: Date;
/**
* The maximum valid date.
*/
@Input() max: Date;
@Input() set required(required: any) {
this.isRequired = toBoolean(required);
}
isRequired: Boolean;
/**
* Text for button to open calendar.
*/
@Input() selectDateLabel = 'Select a date';
/**
* Whether to use the accepted pattern as placeholder.
*/
@Input() @InputBoolean() patternPlaceholder: boolean;
/**
* Datepicker inputs
*/
@Input() monthNames: ReadonlyArray<string>;
@Input() dayNamesShort: ReadonlyArray<string>;
@Input() dayNamesLong: ReadonlyArray<string>;
@Input() firstDayOfWeek: number;
@Input() @InputBoolean() showToday: boolean;
@Input() dateDisabled: (date: Date) => boolean | null = null;
@Input() relativeYearFrom: number;
@Input() relativeYearTo: number;
@Input() todayLabel: string;
@Input() previousMonthLabel: string;
@Input() nextMonthLabel: string;
date: Date;
uid = uniqueId('datepicker-input');
overlayPositions: ConnectionPositionPair[];
set open(open: boolean) {
this._open.next(open);
}
get open() {
return this._open.value;
}
private _open = new BehaviorSubject(false);
private _value: Date | string | null = null;
private pattern: string;
private config: NglDatepickerConfig;
private focusTrap: FocusTrap;
constructor(@Optional() @Inject(NGL_DATEPICKER_CONFIG) defaultConfig: NglDatepickerConfig,
@Inject(LOCALE_ID) locale: string,
private element: ElementRef,
private renderer: Renderer2,
private cd: ChangeDetectorRef,
private hostService: HostService,
private ngZone: NgZone,
private focusTrapFactory: FocusTrapFactory,
private adapter: NglDateAdapter) {
this.renderer.addClass(this.element.nativeElement, 'slds-form-element');
this.renderer.addClass(this.element.nativeElement, 'slds-dropdown-trigger');
this.renderer.addClass(this.element.nativeElement, 'slds-dropdown-trigger_click');
this.config = { ...new NglDatepickerConfig(locale), ...defaultConfig };
this.format = this.config.format;
this.delimiter = this.config.delimiter;
this.setPositions(this.config.dropdownAlign);
this.monthNames = this.config.monthNames;
this.dayNamesShort = this.config.dayNamesShort;
this.dayNamesLong = this.config.dayNamesLong;
this.firstDayOfWeek = this.config.firstDayOfWeek;
this.showToday = this.config.showToday;
this.relativeYearFrom = this.config.relativeYearFrom;
this.relativeYearTo = this.config.relativeYearTo;
this.openOnInputClick = this.config.openOnInputClick;
this.todayLabel = this.config.todayLabel;
this.previousMonthLabel = this.config.previousMonthLabel;
this.nextMonthLabel = this.config.nextMonthLabel;
this.patternPlaceholder = this.config.patternPlaceholder;
}
onChange: Function | null = null;
onTouched = () => {};
validatorChange = () => {};
validate(c: AbstractControl): ValidationErrors | null {
const value = c.value;
if (!value) {
return null;
}
if (!(this.value instanceof Date)) {
return { 'nglDatepickerInput': { invalid: c.value } };
}
const date = parseDate(value);
if (isDisabled(date, this.dateDisabled, parseDate(this.min), parseDate(this.max))) {
return { 'nglDatepickerInput': { disabled: c.value } };
}
return null;
}
writeValue(value: Date) {
this.value = value;
this.cd.markForCheck();
}
registerOnChange(fn: (value: any) => any): void { this.onChange = fn; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
registerOnValidatorChange(fn: () => void): void { this.validatorChange = fn; }
setDisabledState(disabled: boolean) { this.disabled = disabled; }
onBlur() {
if (this.value instanceof Date) {
this.updateInputValue();
}
this.onTouched();
}
ngOnInit() {
this._open.subscribe(() => {
this.setHostClass();
this.cd.markForCheck();
});
}
ngOnChanges(changes: SimpleChanges) {
if (changes.format || changes.delimiter) |
if (changes.dropdownAlign) {
this.setPositions(this.dropdownAlign);
}
if (changes.min || changes.max) {
this.validatorChange();
}
if ((changes.patternPlaceholder || changes.format || changes.delimiter) && this.patternPlaceholder) {
this.inputEl.setPlaceholder(this.getPattern().toLocaleUpperCase());
}
if (changes.disabled) {
this.inputEl.setDisabled(this.disabled);
}
}
ngOnDestroy() {
this.closeCalendar(false);
}
onKeyboardInput(evt: KeyboardEvent) {
const keyCode = evt.keyCode;
if (!this.open && (keyCode === DOWN_ARROW || keyCode === UP_ARROW)) {
this.openCalendar();
}
}
onInputChange() {
const value = this.inputEl.element.nativeElement.value;
const date = this.dateParse(value);
this.emitSelection(date || value);
}
openCalendar() {
this.open = true;
}
onAttach() {
this.focusTrap = this.focusTrapFactory.create(this.cdkOverlay.overlayRef.overlayElement);
}
onDetach() {
if (this.open) {
this.closeCalendar();
}
}
closeCalendar(focusInput = true) {
this.open = false;
if (this.focusTrap) {
this.focusTrap.destroy();
this.focusTrap = null;
}
if (focusInput) {
this.inputEl.element.nativeElement.focus();
}
}
onTriggerClick(origin: 'input' | 'button') {
if (origin === 'input' && !this.openOnInputClick) {
return;
}
if (!this.open) {
this.openCalendar();
} else {
this.closeCalendar(false);
}
}
pickerSelection(date: Date) {
this.emitSelection(date);
this.closeCalendar();
}
updateDatepickerSize(width: number, height: number) {
this.ngZone.onStable.asObservable().pipe(take | {
this.setPattern();
if (this.value instanceof Date) {
this.updateInputValue();
}
} | conditional_block |
datepicker-input.ts | import { InputBoolean, toBoolean } from '../../util/convert';
import { HostService } from '../../common/host/host.service';
import { NglDateAdapter } from '../adapters/date-fns-adapter';
import { NGL_DATEPICKER_CONFIG, NglDatepickerConfig } from '../config';
import { DEFAULT_DROPDOWN_POSITIONS } from '../../util/overlay-position';
import { parseDate, isDisabled } from '../util';
import { IDatepickerInput } from './datepicker-input.interface';
const NGL_DATEPICKER_INPUT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NglDatepickerInput),
multi: true
};
const NGL_DATEPICKER_INPUT_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => NglDatepickerInput),
multi: true
};
@Component({
selector: 'ngl-datepicker-input',
templateUrl: './datepicker-input.html',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [NGL_DATEPICKER_INPUT_VALUE_ACCESSOR, NGL_DATEPICKER_INPUT_VALIDATOR, HostService],
})
export class NglDatepickerInput implements ControlValueAccessor, Validator, OnInit, OnChanges, OnDestroy {
/**
* Label that appears above the input.
*/
@Input() label: string | TemplateRef<any>;
/**
* Pre-defined format to use.
*/
@Input() format: 'big-endian' | 'little-endian' | 'middle-endian';
/**
* Delimiter to use on pre-defined formats.
*/
@Input() delimiter;
/**
* Disable input and calendar.
*/
@Input() @InputBoolean() disabled: boolean;
/**
* Aligns the right or left side of the dropdown menu with the respective side of the input.
*/
@Input() dropdownAlign: 'left' | 'right';
/**
* The date value.
*/
@Input() set value(value: Date | string | null) {
if (value === this._value) {
return;
}
this._value = value;
if (this.value instanceof Date) {
this.date = this.value;
this.formatInputValue();
} else {
this.updateInputValue(<string>value || '');
}
}
get value(): Date | string | null {
return this._value;
}
/**
* Whether to open the datepicker when a mouse user clicks on the input.
*/
@Input() @InputBoolean() openOnInputClick: boolean;
/**
* Emits when selected date changes.
*/
@Output() valueChange = new EventEmitter<Date | string | null>();
inputEl: IDatepickerInput;
// @ContentChild('inputEl', { static: false }) inputEl: SquareConfig;
@ViewChild('cdkOverlay') cdkOverlay: CdkConnectedOverlay;
/**
* The minimum valid date.
*/
@Input() min: Date;
/**
* The maximum valid date.
*/
@Input() max: Date;
@Input() set required(required: any) |
isRequired: Boolean;
/**
* Text for button to open calendar.
*/
@Input() selectDateLabel = 'Select a date';
/**
* Whether to use the accepted pattern as placeholder.
*/
@Input() @InputBoolean() patternPlaceholder: boolean;
/**
* Datepicker inputs
*/
@Input() monthNames: ReadonlyArray<string>;
@Input() dayNamesShort: ReadonlyArray<string>;
@Input() dayNamesLong: ReadonlyArray<string>;
@Input() firstDayOfWeek: number;
@Input() @InputBoolean() showToday: boolean;
@Input() dateDisabled: (date: Date) => boolean | null = null;
@Input() relativeYearFrom: number;
@Input() relativeYearTo: number;
@Input() todayLabel: string;
@Input() previousMonthLabel: string;
@Input() nextMonthLabel: string;
date: Date;
uid = uniqueId('datepicker-input');
overlayPositions: ConnectionPositionPair[];
set open(open: boolean) {
this._open.next(open);
}
get open() {
return this._open.value;
}
private _open = new BehaviorSubject(false);
private _value: Date | string | null = null;
private pattern: string;
private config: NglDatepickerConfig;
private focusTrap: FocusTrap;
constructor(@Optional() @Inject(NGL_DATEPICKER_CONFIG) defaultConfig: NglDatepickerConfig,
@Inject(LOCALE_ID) locale: string,
private element: ElementRef,
private renderer: Renderer2,
private cd: ChangeDetectorRef,
private hostService: HostService,
private ngZone: NgZone,
private focusTrapFactory: FocusTrapFactory,
private adapter: NglDateAdapter) {
this.renderer.addClass(this.element.nativeElement, 'slds-form-element');
this.renderer.addClass(this.element.nativeElement, 'slds-dropdown-trigger');
this.renderer.addClass(this.element.nativeElement, 'slds-dropdown-trigger_click');
this.config = { ...new NglDatepickerConfig(locale), ...defaultConfig };
this.format = this.config.format;
this.delimiter = this.config.delimiter;
this.setPositions(this.config.dropdownAlign);
this.monthNames = this.config.monthNames;
this.dayNamesShort = this.config.dayNamesShort;
this.dayNamesLong = this.config.dayNamesLong;
this.firstDayOfWeek = this.config.firstDayOfWeek;
this.showToday = this.config.showToday;
this.relativeYearFrom = this.config.relativeYearFrom;
this.relativeYearTo = this.config.relativeYearTo;
this.openOnInputClick = this.config.openOnInputClick;
this.todayLabel = this.config.todayLabel;
this.previousMonthLabel = this.config.previousMonthLabel;
this.nextMonthLabel = this.config.nextMonthLabel;
this.patternPlaceholder = this.config.patternPlaceholder;
}
onChange: Function | null = null;
onTouched = () => {};
validatorChange = () => {};
validate(c: AbstractControl): ValidationErrors | null {
const value = c.value;
if (!value) {
return null;
}
if (!(this.value instanceof Date)) {
return { 'nglDatepickerInput': { invalid: c.value } };
}
const date = parseDate(value);
if (isDisabled(date, this.dateDisabled, parseDate(this.min), parseDate(this.max))) {
return { 'nglDatepickerInput': { disabled: c.value } };
}
return null;
}
writeValue(value: Date) {
this.value = value;
this.cd.markForCheck();
}
registerOnChange(fn: (value: any) => any): void { this.onChange = fn; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
registerOnValidatorChange(fn: () => void): void { this.validatorChange = fn; }
setDisabledState(disabled: boolean) { this.disabled = disabled; }
onBlur() {
if (this.value instanceof Date) {
this.updateInputValue();
}
this.onTouched();
}
ngOnInit() {
this._open.subscribe(() => {
this.setHostClass();
this.cd.markForCheck();
});
}
ngOnChanges(changes: SimpleChanges) {
if (changes.format || changes.delimiter) {
this.setPattern();
if (this.value instanceof Date) {
this.updateInputValue();
}
}
if (changes.dropdownAlign) {
this.setPositions(this.dropdownAlign);
}
if (changes.min || changes.max) {
this.validatorChange();
}
if ((changes.patternPlaceholder || changes.format || changes.delimiter) && this.patternPlaceholder) {
this.inputEl.setPlaceholder(this.getPattern().toLocaleUpperCase());
}
if (changes.disabled) {
this.inputEl.setDisabled(this.disabled);
}
}
ngOnDestroy() {
this.closeCalendar(false);
}
onKeyboardInput(evt: KeyboardEvent) {
const keyCode = evt.keyCode;
if (!this.open && (keyCode === DOWN_ARROW || keyCode === UP_ARROW)) {
this.openCalendar();
}
}
onInputChange() {
const value = this.inputEl.element.nativeElement.value;
const date = this.dateParse(value);
this.emitSelection(date || value);
}
openCalendar() {
this.open = true;
}
onAttach() {
this.focusTrap = this.focusTrapFactory.create(this.cdkOverlay.overlayRef.overlayElement);
}
onDetach() {
if (this.open) {
this.closeCalendar();
}
}
closeCalendar(focusInput = true) {
this.open = false;
if (this.focusTrap) {
this.focusTrap.destroy();
this.focusTrap = null;
}
if (focusInput) {
this.inputEl.element.nativeElement.focus();
}
}
onTriggerClick(origin: 'input' | 'button') {
if (origin === 'input' && !this.openOnInputClick) {
return;
}
if (!this.open) {
this.openCalendar();
} else {
this.closeCalendar(false);
}
}
pickerSelection(date: Date) {
this.emitSelection(date);
this.closeCalendar();
}
updateDatepickerSize(width: number, height: number) {
this.ngZone.onStable.asObservable().pipe(take | {
this.isRequired = toBoolean(required);
} | identifier_body |
datepicker-input.ts | ';
import { InputBoolean, toBoolean } from '../../util/convert';
import { HostService } from '../../common/host/host.service';
import { NglDateAdapter } from '../adapters/date-fns-adapter';
import { NGL_DATEPICKER_CONFIG, NglDatepickerConfig } from '../config';
import { DEFAULT_DROPDOWN_POSITIONS } from '../../util/overlay-position';
import { parseDate, isDisabled } from '../util';
import { IDatepickerInput } from './datepicker-input.interface';
const NGL_DATEPICKER_INPUT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NglDatepickerInput),
multi: true
};
const NGL_DATEPICKER_INPUT_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => NglDatepickerInput),
multi: true
};
@Component({
selector: 'ngl-datepicker-input',
templateUrl: './datepicker-input.html',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [NGL_DATEPICKER_INPUT_VALUE_ACCESSOR, NGL_DATEPICKER_INPUT_VALIDATOR, HostService],
})
export class NglDatepickerInput implements ControlValueAccessor, Validator, OnInit, OnChanges, OnDestroy {
/**
* Label that appears above the input.
*/
@Input() label: string | TemplateRef<any>;
/**
* Pre-defined format to use.
*/
@Input() format: 'big-endian' | 'little-endian' | 'middle-endian';
/**
* Delimiter to use on pre-defined formats.
*/
@Input() delimiter;
/**
* Disable input and calendar.
*/
@Input() @InputBoolean() disabled: boolean;
/**
* Aligns the right or left side of the dropdown menu with the respective side of the input.
*/
@Input() dropdownAlign: 'left' | 'right';
/**
* The date value.
*/
@Input() set value(value: Date | string | null) {
if (value === this._value) {
return;
}
this._value = value;
if (this.value instanceof Date) {
this.date = this.value;
this.formatInputValue();
} else {
this.updateInputValue(<string>value || '');
}
}
get | (): Date | string | null {
return this._value;
}
/**
* Whether to open the datepicker when a mouse user clicks on the input.
*/
@Input() @InputBoolean() openOnInputClick: boolean;
/**
* Emits when selected date changes.
*/
@Output() valueChange = new EventEmitter<Date | string | null>();
inputEl: IDatepickerInput;
// @ContentChild('inputEl', { static: false }) inputEl: SquareConfig;
@ViewChild('cdkOverlay') cdkOverlay: CdkConnectedOverlay;
/**
* The minimum valid date.
*/
@Input() min: Date;
/**
* The maximum valid date.
*/
@Input() max: Date;
@Input() set required(required: any) {
this.isRequired = toBoolean(required);
}
isRequired: Boolean;
/**
* Text for button to open calendar.
*/
@Input() selectDateLabel = 'Select a date';
/**
* Whether to use the accepted pattern as placeholder.
*/
@Input() @InputBoolean() patternPlaceholder: boolean;
/**
* Datepicker inputs
*/
@Input() monthNames: ReadonlyArray<string>;
@Input() dayNamesShort: ReadonlyArray<string>;
@Input() dayNamesLong: ReadonlyArray<string>;
@Input() firstDayOfWeek: number;
@Input() @InputBoolean() showToday: boolean;
@Input() dateDisabled: (date: Date) => boolean | null = null;
@Input() relativeYearFrom: number;
@Input() relativeYearTo: number;
@Input() todayLabel: string;
@Input() previousMonthLabel: string;
@Input() nextMonthLabel: string;
date: Date;
uid = uniqueId('datepicker-input');
overlayPositions: ConnectionPositionPair[];
set open(open: boolean) {
this._open.next(open);
}
get open() {
return this._open.value;
}
private _open = new BehaviorSubject(false);
private _value: Date | string | null = null;
private pattern: string;
private config: NglDatepickerConfig;
private focusTrap: FocusTrap;
constructor(@Optional() @Inject(NGL_DATEPICKER_CONFIG) defaultConfig: NglDatepickerConfig,
@Inject(LOCALE_ID) locale: string,
private element: ElementRef,
private renderer: Renderer2,
private cd: ChangeDetectorRef,
private hostService: HostService,
private ngZone: NgZone,
private focusTrapFactory: FocusTrapFactory,
private adapter: NglDateAdapter) {
this.renderer.addClass(this.element.nativeElement, 'slds-form-element');
this.renderer.addClass(this.element.nativeElement, 'slds-dropdown-trigger');
this.renderer.addClass(this.element.nativeElement, 'slds-dropdown-trigger_click');
this.config = { ...new NglDatepickerConfig(locale), ...defaultConfig };
this.format = this.config.format;
this.delimiter = this.config.delimiter;
this.setPositions(this.config.dropdownAlign);
this.monthNames = this.config.monthNames;
this.dayNamesShort = this.config.dayNamesShort;
this.dayNamesLong = this.config.dayNamesLong;
this.firstDayOfWeek = this.config.firstDayOfWeek;
this.showToday = this.config.showToday;
this.relativeYearFrom = this.config.relativeYearFrom;
this.relativeYearTo = this.config.relativeYearTo;
this.openOnInputClick = this.config.openOnInputClick;
this.todayLabel = this.config.todayLabel;
this.previousMonthLabel = this.config.previousMonthLabel;
this.nextMonthLabel = this.config.nextMonthLabel;
this.patternPlaceholder = this.config.patternPlaceholder;
}
onChange: Function | null = null;
onTouched = () => {};
validatorChange = () => {};
validate(c: AbstractControl): ValidationErrors | null {
const value = c.value;
if (!value) {
return null;
}
if (!(this.value instanceof Date)) {
return { 'nglDatepickerInput': { invalid: c.value } };
}
const date = parseDate(value);
if (isDisabled(date, this.dateDisabled, parseDate(this.min), parseDate(this.max))) {
return { 'nglDatepickerInput': { disabled: c.value } };
}
return null;
}
writeValue(value: Date) {
this.value = value;
this.cd.markForCheck();
}
registerOnChange(fn: (value: any) => any): void { this.onChange = fn; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
registerOnValidatorChange(fn: () => void): void { this.validatorChange = fn; }
setDisabledState(disabled: boolean) { this.disabled = disabled; }
onBlur() {
if (this.value instanceof Date) {
this.updateInputValue();
}
this.onTouched();
}
ngOnInit() {
this._open.subscribe(() => {
this.setHostClass();
this.cd.markForCheck();
});
}
ngOnChanges(changes: SimpleChanges) {
if (changes.format || changes.delimiter) {
this.setPattern();
if (this.value instanceof Date) {
this.updateInputValue();
}
}
if (changes.dropdownAlign) {
this.setPositions(this.dropdownAlign);
}
if (changes.min || changes.max) {
this.validatorChange();
}
if ((changes.patternPlaceholder || changes.format || changes.delimiter) && this.patternPlaceholder) {
this.inputEl.setPlaceholder(this.getPattern().toLocaleUpperCase());
}
if (changes.disabled) {
this.inputEl.setDisabled(this.disabled);
}
}
ngOnDestroy() {
this.closeCalendar(false);
}
onKeyboardInput(evt: KeyboardEvent) {
const keyCode = evt.keyCode;
if (!this.open && (keyCode === DOWN_ARROW || keyCode === UP_ARROW)) {
this.openCalendar();
}
}
onInputChange() {
const value = this.inputEl.element.nativeElement.value;
const date = this.dateParse(value);
this.emitSelection(date || value);
}
openCalendar() {
this.open = true;
}
onAttach() {
this.focusTrap = this.focusTrapFactory.create(this.cdkOverlay.overlayRef.overlayElement);
}
onDetach() {
if (this.open) {
this.closeCalendar();
}
}
closeCalendar(focusInput = true) {
this.open = false;
if (this.focusTrap) {
this.focusTrap.destroy();
this.focusTrap = null;
}
if (focusInput) {
this.inputEl.element.nativeElement.focus();
}
}
onTriggerClick(origin: 'input' | 'button') {
if (origin === 'input' && !this.openOnInputClick) {
return;
}
if (!this.open) {
this.openCalendar();
} else {
this.closeCalendar(false);
}
}
pickerSelection(date: Date) {
this.emitSelection(date);
this.closeCalendar();
}
updateDatepickerSize(width: number, height: number) {
this.ngZone.onStable.asObservable().pipe(take | value | identifier_name |
datepicker-input.ts | ';
import { InputBoolean, toBoolean } from '../../util/convert';
import { HostService } from '../../common/host/host.service';
import { NglDateAdapter } from '../adapters/date-fns-adapter';
import { NGL_DATEPICKER_CONFIG, NglDatepickerConfig } from '../config';
import { DEFAULT_DROPDOWN_POSITIONS } from '../../util/overlay-position';
import { parseDate, isDisabled } from '../util';
import { IDatepickerInput } from './datepicker-input.interface';
const NGL_DATEPICKER_INPUT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NglDatepickerInput),
multi: true
};
const NGL_DATEPICKER_INPUT_VALIDATOR = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => NglDatepickerInput),
multi: true
};
@Component({
selector: 'ngl-datepicker-input',
templateUrl: './datepicker-input.html',
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [NGL_DATEPICKER_INPUT_VALUE_ACCESSOR, NGL_DATEPICKER_INPUT_VALIDATOR, HostService],
})
export class NglDatepickerInput implements ControlValueAccessor, Validator, OnInit, OnChanges, OnDestroy {
/**
* Label that appears above the input.
*/
@Input() label: string | TemplateRef<any>;
/**
* Pre-defined format to use.
*/
@Input() format: 'big-endian' | 'little-endian' | 'middle-endian';
/**
* Delimiter to use on pre-defined formats.
*/
@Input() delimiter;
/**
* Disable input and calendar.
*/
@Input() @InputBoolean() disabled: boolean;
/**
* Aligns the right or left side of the dropdown menu with the respective side of the input.
*/
@Input() dropdownAlign: 'left' | 'right';
/**
* The date value.
*/
@Input() set value(value: Date | string | null) {
if (value === this._value) {
return;
}
this._value = value; | if (this.value instanceof Date) {
this.date = this.value;
this.formatInputValue();
} else {
this.updateInputValue(<string>value || '');
}
}
get value(): Date | string | null {
return this._value;
}
/**
* Whether to open the datepicker when a mouse user clicks on the input.
*/
@Input() @InputBoolean() openOnInputClick: boolean;
/**
* Emits when selected date changes.
*/
@Output() valueChange = new EventEmitter<Date | string | null>();
inputEl: IDatepickerInput;
// @ContentChild('inputEl', { static: false }) inputEl: SquareConfig;
@ViewChild('cdkOverlay') cdkOverlay: CdkConnectedOverlay;
/**
* The minimum valid date.
*/
@Input() min: Date;
/**
* The maximum valid date.
*/
@Input() max: Date;
@Input() set required(required: any) {
this.isRequired = toBoolean(required);
}
isRequired: Boolean;
/**
* Text for button to open calendar.
*/
@Input() selectDateLabel = 'Select a date';
/**
* Whether to use the accepted pattern as placeholder.
*/
@Input() @InputBoolean() patternPlaceholder: boolean;
/**
* Datepicker inputs
*/
@Input() monthNames: ReadonlyArray<string>;
@Input() dayNamesShort: ReadonlyArray<string>;
@Input() dayNamesLong: ReadonlyArray<string>;
@Input() firstDayOfWeek: number;
@Input() @InputBoolean() showToday: boolean;
@Input() dateDisabled: (date: Date) => boolean | null = null;
@Input() relativeYearFrom: number;
@Input() relativeYearTo: number;
@Input() todayLabel: string;
@Input() previousMonthLabel: string;
@Input() nextMonthLabel: string;
date: Date;
uid = uniqueId('datepicker-input');
overlayPositions: ConnectionPositionPair[];
set open(open: boolean) {
this._open.next(open);
}
get open() {
return this._open.value;
}
private _open = new BehaviorSubject(false);
private _value: Date | string | null = null;
private pattern: string;
private config: NglDatepickerConfig;
private focusTrap: FocusTrap;
constructor(@Optional() @Inject(NGL_DATEPICKER_CONFIG) defaultConfig: NglDatepickerConfig,
@Inject(LOCALE_ID) locale: string,
private element: ElementRef,
private renderer: Renderer2,
private cd: ChangeDetectorRef,
private hostService: HostService,
private ngZone: NgZone,
private focusTrapFactory: FocusTrapFactory,
private adapter: NglDateAdapter) {
this.renderer.addClass(this.element.nativeElement, 'slds-form-element');
this.renderer.addClass(this.element.nativeElement, 'slds-dropdown-trigger');
this.renderer.addClass(this.element.nativeElement, 'slds-dropdown-trigger_click');
this.config = { ...new NglDatepickerConfig(locale), ...defaultConfig };
this.format = this.config.format;
this.delimiter = this.config.delimiter;
this.setPositions(this.config.dropdownAlign);
this.monthNames = this.config.monthNames;
this.dayNamesShort = this.config.dayNamesShort;
this.dayNamesLong = this.config.dayNamesLong;
this.firstDayOfWeek = this.config.firstDayOfWeek;
this.showToday = this.config.showToday;
this.relativeYearFrom = this.config.relativeYearFrom;
this.relativeYearTo = this.config.relativeYearTo;
this.openOnInputClick = this.config.openOnInputClick;
this.todayLabel = this.config.todayLabel;
this.previousMonthLabel = this.config.previousMonthLabel;
this.nextMonthLabel = this.config.nextMonthLabel;
this.patternPlaceholder = this.config.patternPlaceholder;
}
onChange: Function | null = null;
onTouched = () => {};
validatorChange = () => {};
validate(c: AbstractControl): ValidationErrors | null {
const value = c.value;
if (!value) {
return null;
}
if (!(this.value instanceof Date)) {
return { 'nglDatepickerInput': { invalid: c.value } };
}
const date = parseDate(value);
if (isDisabled(date, this.dateDisabled, parseDate(this.min), parseDate(this.max))) {
return { 'nglDatepickerInput': { disabled: c.value } };
}
return null;
}
writeValue(value: Date) {
this.value = value;
this.cd.markForCheck();
}
registerOnChange(fn: (value: any) => any): void { this.onChange = fn; }
registerOnTouched(fn: () => any): void { this.onTouched = fn; }
registerOnValidatorChange(fn: () => void): void { this.validatorChange = fn; }
setDisabledState(disabled: boolean) { this.disabled = disabled; }
onBlur() {
if (this.value instanceof Date) {
this.updateInputValue();
}
this.onTouched();
}
ngOnInit() {
this._open.subscribe(() => {
this.setHostClass();
this.cd.markForCheck();
});
}
ngOnChanges(changes: SimpleChanges) {
if (changes.format || changes.delimiter) {
this.setPattern();
if (this.value instanceof Date) {
this.updateInputValue();
}
}
if (changes.dropdownAlign) {
this.setPositions(this.dropdownAlign);
}
if (changes.min || changes.max) {
this.validatorChange();
}
if ((changes.patternPlaceholder || changes.format || changes.delimiter) && this.patternPlaceholder) {
this.inputEl.setPlaceholder(this.getPattern().toLocaleUpperCase());
}
if (changes.disabled) {
this.inputEl.setDisabled(this.disabled);
}
}
ngOnDestroy() {
this.closeCalendar(false);
}
onKeyboardInput(evt: KeyboardEvent) {
const keyCode = evt.keyCode;
if (!this.open && (keyCode === DOWN_ARROW || keyCode === UP_ARROW)) {
this.openCalendar();
}
}
onInputChange() {
const value = this.inputEl.element.nativeElement.value;
const date = this.dateParse(value);
this.emitSelection(date || value);
}
openCalendar() {
this.open = true;
}
onAttach() {
this.focusTrap = this.focusTrapFactory.create(this.cdkOverlay.overlayRef.overlayElement);
}
onDetach() {
if (this.open) {
this.closeCalendar();
}
}
closeCalendar(focusInput = true) {
this.open = false;
if (this.focusTrap) {
this.focusTrap.destroy();
this.focusTrap = null;
}
if (focusInput) {
this.inputEl.element.nativeElement.focus();
}
}
onTriggerClick(origin: 'input' | 'button') {
if (origin === 'input' && !this.openOnInputClick) {
return;
}
if (!this.open) {
this.openCalendar();
} else {
this.closeCalendar(false);
}
}
pickerSelection(date: Date) {
this.emitSelection(date);
this.closeCalendar();
}
updateDatepickerSize(width: number, height: number) {
this.ngZone.onStable.asObservable().pipe(take( | random_line_split |
|
router_module.ts | '@angular/common';
import {ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, ApplicationRef, Compiler, ComponentRef, Inject, InjectionToken, Injector, ModuleWithProviders, NgModule, NgModuleFactoryLoader, NgProbeToken, Optional, Provider, SkipSelf, SystemJsNgModuleLoader} from '@angular/core';
import {Route, Routes} from './config';
import {RouterLink, RouterLinkWithHref} from './directives/router_link';
import {RouterLinkActive} from './directives/router_link_active';
import {RouterOutlet} from './directives/router_outlet';
import {getDOM} from './private_import_platform-browser';
import {RouteReuseStrategy} from './route_reuse_strategy';
import {ErrorHandler, Router} from './router';
import {ROUTES} from './router_config_loader';
import {RouterOutletMap} from './router_outlet_map';
import {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader';
import {ActivatedRoute} from './router_state';
import {UrlHandlingStrategy} from './url_handling_strategy';
import {DefaultUrlSerializer, UrlSerializer} from './url_tree';
import {flatten} from './utils/collection';
/**
* @whatItDoes Contains a list of directives
* @stable
*/
const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];
/**
* @whatItDoes Is used in DI to configure the router.
* @stable
*/
export const ROUTER_CONFIGURATION = new InjectionToken<ExtraOptions>('ROUTER_CONFIGURATION');
/**
* @docsNotRequired
*/
export const ROUTER_FORROOT_GUARD = new InjectionToken<void>('ROUTER_FORROOT_GUARD');
export const ROUTER_PROVIDERS: Provider[] = [
Location,
{provide: UrlSerializer, useClass: DefaultUrlSerializer},
{
provide: Router,
useFactory: setupRouter,
deps: [
ApplicationRef, UrlSerializer, RouterOutletMap, Location, Injector, NgModuleFactoryLoader,
Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()],
[RouteReuseStrategy, new Optional()]
]
},
RouterOutletMap,
{provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]},
{provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader},
RouterPreloader,
NoPreloading,
PreloadAllModules,
{provide: ROUTER_CONFIGURATION, useValue: {enableTracing: false}},
];
export function routerNgProbeToken() {
return new NgProbeToken('Router', Router);
}
/**
* @whatItDoes Adds router directives and providers.
*
* @howToUse
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* @NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @description
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
* overview of how the router should be used.
*
* @stable
*/
@NgModule({declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES})
export class RouterModule {
constructor(@Optional() @Inject(ROUTER_FORROOT_GUARD) guard: any) {}
/**
* Creates a module with all the router providers and directives. It also optionally sets up an
* application listener to perform an initial navigation.
*
* Options:
* * `enableTracing` makes the router log all its internal events to the console.
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
* API.
* * `initialNavigation` disables the initial navigation.
* * `errorHandler` provides a custom error handler.
*/
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
provideRoutes(routes),
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new Optional(), new SkipSelf()]]
},
{provide: ROUTER_CONFIGURATION, useValue: config ? config : {}},
{
provide: LocationStrategy,
useFactory: provideLocationStrategy,
deps: [
PlatformLocation, [new Inject(APP_BASE_HREF), new Optional()], ROUTER_CONFIGURATION
]
},
{
provide: PreloadingStrategy,
useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
NoPreloading
},
{provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken},
provideRouterInitializer(),
],
};
}
/**
* Creates a module with all the router directives and a provider registering routes.
*/
static forChild(routes: Routes): ModuleWithProviders {
return {ngModule: RouterModule, providers: [provideRoutes(routes)]};
}
}
export function provideLocationStrategy(
platformLocationStrategy: PlatformLocation, baseHref: string, options: ExtraOptions = {}) {
return options.useHash ? new HashLocationStrategy(platformLocationStrategy, baseHref) :
new PathLocationStrategy(platformLocationStrategy, baseHref);
}
export function provideForRootGuard(router: Router): any {
if (router) {
throw new Error(
`RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`);
}
return 'guarded';
}
/**
* @whatItDoes Registers routes.
*
* @howToUse
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @stable
*/
export function provideRoutes(routes: Routes): any {
return [
{provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes},
{provide: ROUTES, multi: true, useValue: routes},
];
}
/**
* @whatItDoes Represents options to configure the router.
*
* @stable
*/
export interface ExtraOptions {
/**
* Makes the router log all its internal events to the console.
*/
enableTracing?: boolean;
/**
* Enables the location strategy that uses the URL fragment instead of the history API.
*/
useHash?: boolean;
/**
* Disables the initial navigation.
*/
initialNavigation?: boolean;
/**
* A custom error handler.
*/
errorHandler?: ErrorHandler;
/**
* Configures a preloading strategy. See {@link PreloadAllModules}.
*/
preloadingStrategy?: any;
}
export function setupRouter(
ref: ApplicationRef, urlSerializer: UrlSerializer, outletMap: RouterOutletMap,
location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler,
config: Route[][], opts: ExtraOptions = {}, urlHandlingStrategy?: UrlHandlingStrategy,
routeReuseStrategy?: RouteReuseStrategy) {
const router = new Router(
null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(config));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
if (routeReuseStrategy) {
router.routeReuseStrategy = routeReuseStrategy;
}
if (opts.errorHandler) {
router.errorHandler = opts.errorHandler;
}
if (opts.enableTracing) {
const dom = getDOM();
router.events.subscribe(e => {
dom.logGroup(`Router Event: ${(<any>e.constructor).name}`);
dom.log(e.toString());
dom.log(e);
dom.logGroupEnd();
});
}
return router;
}
export function rootRoute(router: Router): ActivatedRoute {
return router.routerState.root;
}
export function initialRouterNavigation(
router: Router, ref: ApplicationRef, preloader: RouterPreloader, opts: ExtraOptions) | {
return (bootstrappedComponentRef: ComponentRef<any>) => {
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
router.resetRootComponentType(ref.componentTypes[0]);
preloader.setUpPreloading();
if (opts.initialNavigation === false) {
router.setUpLocationChangeListener();
} else {
router.initialNavigation();
}
};
} | identifier_body |
|
router_module.ts | Location} from '@angular/common';
import {ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, ApplicationRef, Compiler, ComponentRef, Inject, InjectionToken, Injector, ModuleWithProviders, NgModule, NgModuleFactoryLoader, NgProbeToken, Optional, Provider, SkipSelf, SystemJsNgModuleLoader} from '@angular/core';
import {Route, Routes} from './config';
import {RouterLink, RouterLinkWithHref} from './directives/router_link';
import {RouterLinkActive} from './directives/router_link_active';
import {RouterOutlet} from './directives/router_outlet';
import {getDOM} from './private_import_platform-browser';
import {RouteReuseStrategy} from './route_reuse_strategy';
import {ErrorHandler, Router} from './router';
import {ROUTES} from './router_config_loader';
import {RouterOutletMap} from './router_outlet_map';
import {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader';
import {ActivatedRoute} from './router_state';
import {UrlHandlingStrategy} from './url_handling_strategy';
import {DefaultUrlSerializer, UrlSerializer} from './url_tree';
import {flatten} from './utils/collection';
/**
* @whatItDoes Contains a list of directives
* @stable
*/
const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];
/**
* @whatItDoes Is used in DI to configure the router.
* @stable
*/
export const ROUTER_CONFIGURATION = new InjectionToken<ExtraOptions>('ROUTER_CONFIGURATION');
/**
* @docsNotRequired
*/
export const ROUTER_FORROOT_GUARD = new InjectionToken<void>('ROUTER_FORROOT_GUARD');
export const ROUTER_PROVIDERS: Provider[] = [
Location,
{provide: UrlSerializer, useClass: DefaultUrlSerializer},
{
provide: Router,
useFactory: setupRouter,
deps: [
ApplicationRef, UrlSerializer, RouterOutletMap, Location, Injector, NgModuleFactoryLoader,
Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()],
[RouteReuseStrategy, new Optional()]
]
},
RouterOutletMap,
{provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]},
{provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader},
RouterPreloader,
NoPreloading,
PreloadAllModules,
{provide: ROUTER_CONFIGURATION, useValue: {enableTracing: false}},
];
export function routerNgProbeToken() {
return new NgProbeToken('Router', Router);
}
/**
* @whatItDoes Adds router directives and providers.
*
* @howToUse
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* @NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @description
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
* overview of how the router should be used.
*
* @stable
*/
@NgModule({declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES})
export class RouterModule {
constructor(@Optional() @Inject(ROUTER_FORROOT_GUARD) guard: any) {}
/**
* Creates a module with all the router providers and directives. It also optionally sets up an
* application listener to perform an initial navigation.
*
* Options:
* * `enableTracing` makes the router log all its internal events to the console.
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
* API.
* * `initialNavigation` disables the initial navigation.
* * `errorHandler` provides a custom error handler.
*/
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
provideRoutes(routes),
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new Optional(), new SkipSelf()]]
},
{provide: ROUTER_CONFIGURATION, useValue: config ? config : {}},
{
provide: LocationStrategy,
useFactory: provideLocationStrategy,
deps: [
PlatformLocation, [new Inject(APP_BASE_HREF), new Optional()], ROUTER_CONFIGURATION
]
},
{
provide: PreloadingStrategy,
useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
NoPreloading
},
{provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken},
provideRouterInitializer(),
],
};
}
/**
* Creates a module with all the router directives and a provider registering routes.
*/
static forChild(routes: Routes): ModuleWithProviders {
return {ngModule: RouterModule, providers: [provideRoutes(routes)]};
}
}
export function provideLocationStrategy(
platformLocationStrategy: PlatformLocation, baseHref: string, options: ExtraOptions = {}) {
return options.useHash ? new HashLocationStrategy(platformLocationStrategy, baseHref) :
new PathLocationStrategy(platformLocationStrategy, baseHref);
}
export function provideForRootGuard(router: Router): any {
if (router) {
throw new Error(
`RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`);
}
return 'guarded';
}
/**
* @whatItDoes Registers routes.
*
* @howToUse
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @stable
*/
export function provideRoutes(routes: Routes): any {
return [
{provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes},
{provide: ROUTES, multi: true, useValue: routes},
];
}
/**
* @whatItDoes Represents options to configure the router.
*
* @stable
*/
export interface ExtraOptions {
/**
* Makes the router log all its internal events to the console.
*/
enableTracing?: boolean;
/**
* Enables the location strategy that uses the URL fragment instead of the history API.
*/
useHash?: boolean;
/**
* Disables the initial navigation.
*/
initialNavigation?: boolean;
/**
* A custom error handler.
*/
errorHandler?: ErrorHandler;
/**
* Configures a preloading strategy. See {@link PreloadAllModules}.
*/
preloadingStrategy?: any;
}
export function setupRouter(
ref: ApplicationRef, urlSerializer: UrlSerializer, outletMap: RouterOutletMap,
location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler,
config: Route[][], opts: ExtraOptions = {}, urlHandlingStrategy?: UrlHandlingStrategy,
routeReuseStrategy?: RouteReuseStrategy) {
const router = new Router(
null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(config));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
if (routeReuseStrategy) {
router.routeReuseStrategy = routeReuseStrategy;
}
if (opts.errorHandler) {
router.errorHandler = opts.errorHandler;
}
if (opts.enableTracing) {
const dom = getDOM();
router.events.subscribe(e => {
dom.logGroup(`Router Event: ${(<any>e.constructor).name}`);
dom.log(e.toString());
dom.log(e);
dom.logGroupEnd();
});
}
return router;
}
export function rootRoute(router: Router): ActivatedRoute {
return router.routerState.root;
}
export function initialRouterNavigation(
router: Router, ref: ApplicationRef, preloader: RouterPreloader, opts: ExtraOptions) {
return (bootstrappedComponentRef: ComponentRef<any>) => {
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
router.resetRootComponentType(ref.componentTypes[0]);
preloader.setUpPreloading();
if (opts.initialNavigation === false) {
router.setUpLocationChangeListener();
} else | {
router.initialNavigation();
} | conditional_block |
|
router_module.ts | Location, LocationStrategy, PathLocationStrategy, PlatformLocation} from '@angular/common';
import {ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, ApplicationRef, Compiler, ComponentRef, Inject, InjectionToken, Injector, ModuleWithProviders, NgModule, NgModuleFactoryLoader, NgProbeToken, Optional, Provider, SkipSelf, SystemJsNgModuleLoader} from '@angular/core';
import {Route, Routes} from './config';
import {RouterLink, RouterLinkWithHref} from './directives/router_link';
import {RouterLinkActive} from './directives/router_link_active';
import {RouterOutlet} from './directives/router_outlet';
import {getDOM} from './private_import_platform-browser';
import {RouteReuseStrategy} from './route_reuse_strategy';
import {ErrorHandler, Router} from './router';
import {ROUTES} from './router_config_loader';
import {RouterOutletMap} from './router_outlet_map';
import {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader';
import {ActivatedRoute} from './router_state';
import {UrlHandlingStrategy} from './url_handling_strategy';
import {DefaultUrlSerializer, UrlSerializer} from './url_tree';
import {flatten} from './utils/collection';
/**
* @whatItDoes Contains a list of directives
* @stable
*/
const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];
/**
* @whatItDoes Is used in DI to configure the router.
* @stable
*/
export const ROUTER_CONFIGURATION = new InjectionToken<ExtraOptions>('ROUTER_CONFIGURATION');
/**
* @docsNotRequired
*/
export const ROUTER_FORROOT_GUARD = new InjectionToken<void>('ROUTER_FORROOT_GUARD');
export const ROUTER_PROVIDERS: Provider[] = [
Location,
{provide: UrlSerializer, useClass: DefaultUrlSerializer},
{
provide: Router,
useFactory: setupRouter,
deps: [
ApplicationRef, UrlSerializer, RouterOutletMap, Location, Injector, NgModuleFactoryLoader,
Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()],
[RouteReuseStrategy, new Optional()]
]
},
RouterOutletMap,
{provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]},
{provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader},
RouterPreloader,
NoPreloading,
PreloadAllModules,
{provide: ROUTER_CONFIGURATION, useValue: {enableTracing: false}},
];
export function routerNgProbeToken() {
return new NgProbeToken('Router', Router);
}
/**
* @whatItDoes Adds router directives and providers.
*
* @howToUse
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* @NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @description
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
* overview of how the router should be used.
*
* @stable
*/
@NgModule({declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES})
export class RouterModule {
constructor(@Optional() @Inject(ROUTER_FORROOT_GUARD) guard: any) {}
/**
* Creates a module with all the router providers and directives. It also optionally sets up an
* application listener to perform an initial navigation.
*
* Options:
* * `enableTracing` makes the router log all its internal events to the console.
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
* API.
* * `initialNavigation` disables the initial navigation.
* * `errorHandler` provides a custom error handler.
*/
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
provideRoutes(routes),
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new Optional(), new SkipSelf()]]
},
{provide: ROUTER_CONFIGURATION, useValue: config ? config : {}},
{
provide: LocationStrategy,
useFactory: provideLocationStrategy,
deps: [
PlatformLocation, [new Inject(APP_BASE_HREF), new Optional()], ROUTER_CONFIGURATION
]
},
{
provide: PreloadingStrategy,
useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
NoPreloading
},
{provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken},
provideRouterInitializer(),
],
};
}
/**
* Creates a module with all the router directives and a provider registering routes.
*/
static forChild(routes: Routes): ModuleWithProviders {
return {ngModule: RouterModule, providers: [provideRoutes(routes)]};
}
}
export function provideLocationStrategy(
platformLocationStrategy: PlatformLocation, baseHref: string, options: ExtraOptions = {}) {
return options.useHash ? new HashLocationStrategy(platformLocationStrategy, baseHref) :
new PathLocationStrategy(platformLocationStrategy, baseHref);
}
export function provideForRootGuard(router: Router): any {
if (router) {
throw new Error(
`RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`);
}
return 'guarded';
}
/**
* @whatItDoes Registers routes.
*
* @howToUse
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @stable
*/
export function provideRoutes(routes: Routes): any {
return [
{provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes},
{provide: ROUTES, multi: true, useValue: routes},
];
}
/**
* @whatItDoes Represents options to configure the router.
*
* @stable
*/
export interface ExtraOptions {
/**
* Makes the router log all its internal events to the console.
*/
enableTracing?: boolean;
/**
* Enables the location strategy that uses the URL fragment instead of the history API.
*/
useHash?: boolean;
/**
* Disables the initial navigation.
*/
initialNavigation?: boolean;
/**
* A custom error handler.
*/
errorHandler?: ErrorHandler;
/**
* Configures a preloading strategy. See {@link PreloadAllModules}.
*/
preloadingStrategy?: any;
}
export function | (
ref: ApplicationRef, urlSerializer: UrlSerializer, outletMap: RouterOutletMap,
location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler,
config: Route[][], opts: ExtraOptions = {}, urlHandlingStrategy?: UrlHandlingStrategy,
routeReuseStrategy?: RouteReuseStrategy) {
const router = new Router(
null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(config));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
if (routeReuseStrategy) {
router.routeReuseStrategy = routeReuseStrategy;
}
if (opts.errorHandler) {
router.errorHandler = opts.errorHandler;
}
if (opts.enableTracing) {
const dom = getDOM();
router.events.subscribe(e => {
dom.logGroup(`Router Event: ${(<any>e.constructor).name}`);
dom.log(e.toString());
dom.log(e);
dom.logGroupEnd();
});
}
return router;
}
export function rootRoute(router: Router): ActivatedRoute {
return router.routerState.root;
}
export function initialRouterNavigation(
router: Router, ref: ApplicationRef, preloader: RouterPreloader, opts: ExtraOptions) {
return (bootstrappedComponentRef: ComponentRef<any>) => {
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
router.resetRootComponentType(ref.componentTypes[0]);
preloader.setUpPreloading();
if (opts.initialNavigation === false) {
router.setUpLocationChangeListener();
| setupRouter | identifier_name |
router_module.ts | Location, LocationStrategy, PathLocationStrategy, PlatformLocation} from '@angular/common';
import {ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, ApplicationRef, Compiler, ComponentRef, Inject, InjectionToken, Injector, ModuleWithProviders, NgModule, NgModuleFactoryLoader, NgProbeToken, Optional, Provider, SkipSelf, SystemJsNgModuleLoader} from '@angular/core';
import {Route, Routes} from './config';
import {RouterLink, RouterLinkWithHref} from './directives/router_link';
import {RouterLinkActive} from './directives/router_link_active';
import {RouterOutlet} from './directives/router_outlet'; | import {RouteReuseStrategy} from './route_reuse_strategy';
import {ErrorHandler, Router} from './router';
import {ROUTES} from './router_config_loader';
import {RouterOutletMap} from './router_outlet_map';
import {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader';
import {ActivatedRoute} from './router_state';
import {UrlHandlingStrategy} from './url_handling_strategy';
import {DefaultUrlSerializer, UrlSerializer} from './url_tree';
import {flatten} from './utils/collection';
/**
* @whatItDoes Contains a list of directives
* @stable
*/
const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];
/**
* @whatItDoes Is used in DI to configure the router.
* @stable
*/
export const ROUTER_CONFIGURATION = new InjectionToken<ExtraOptions>('ROUTER_CONFIGURATION');
/**
* @docsNotRequired
*/
export const ROUTER_FORROOT_GUARD = new InjectionToken<void>('ROUTER_FORROOT_GUARD');
export const ROUTER_PROVIDERS: Provider[] = [
Location,
{provide: UrlSerializer, useClass: DefaultUrlSerializer},
{
provide: Router,
useFactory: setupRouter,
deps: [
ApplicationRef, UrlSerializer, RouterOutletMap, Location, Injector, NgModuleFactoryLoader,
Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()],
[RouteReuseStrategy, new Optional()]
]
},
RouterOutletMap,
{provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]},
{provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader},
RouterPreloader,
NoPreloading,
PreloadAllModules,
{provide: ROUTER_CONFIGURATION, useValue: {enableTracing: false}},
];
export function routerNgProbeToken() {
return new NgProbeToken('Router', Router);
}
/**
* @whatItDoes Adds router directives and providers.
*
* @howToUse
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* @NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @description
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
* overview of how the router should be used.
*
* @stable
*/
@NgModule({declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES})
export class RouterModule {
constructor(@Optional() @Inject(ROUTER_FORROOT_GUARD) guard: any) {}
/**
* Creates a module with all the router providers and directives. It also optionally sets up an
* application listener to perform an initial navigation.
*
* Options:
* * `enableTracing` makes the router log all its internal events to the console.
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
* API.
* * `initialNavigation` disables the initial navigation.
* * `errorHandler` provides a custom error handler.
*/
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
provideRoutes(routes),
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new Optional(), new SkipSelf()]]
},
{provide: ROUTER_CONFIGURATION, useValue: config ? config : {}},
{
provide: LocationStrategy,
useFactory: provideLocationStrategy,
deps: [
PlatformLocation, [new Inject(APP_BASE_HREF), new Optional()], ROUTER_CONFIGURATION
]
},
{
provide: PreloadingStrategy,
useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
NoPreloading
},
{provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken},
provideRouterInitializer(),
],
};
}
/**
* Creates a module with all the router directives and a provider registering routes.
*/
static forChild(routes: Routes): ModuleWithProviders {
return {ngModule: RouterModule, providers: [provideRoutes(routes)]};
}
}
export function provideLocationStrategy(
platformLocationStrategy: PlatformLocation, baseHref: string, options: ExtraOptions = {}) {
return options.useHash ? new HashLocationStrategy(platformLocationStrategy, baseHref) :
new PathLocationStrategy(platformLocationStrategy, baseHref);
}
export function provideForRootGuard(router: Router): any {
if (router) {
throw new Error(
`RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`);
}
return 'guarded';
}
/**
* @whatItDoes Registers routes.
*
* @howToUse
*
* ```
* @NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* @stable
*/
export function provideRoutes(routes: Routes): any {
return [
{provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes},
{provide: ROUTES, multi: true, useValue: routes},
];
}
/**
* @whatItDoes Represents options to configure the router.
*
* @stable
*/
export interface ExtraOptions {
/**
* Makes the router log all its internal events to the console.
*/
enableTracing?: boolean;
/**
* Enables the location strategy that uses the URL fragment instead of the history API.
*/
useHash?: boolean;
/**
* Disables the initial navigation.
*/
initialNavigation?: boolean;
/**
* A custom error handler.
*/
errorHandler?: ErrorHandler;
/**
* Configures a preloading strategy. See {@link PreloadAllModules}.
*/
preloadingStrategy?: any;
}
export function setupRouter(
ref: ApplicationRef, urlSerializer: UrlSerializer, outletMap: RouterOutletMap,
location: Location, injector: Injector, loader: NgModuleFactoryLoader, compiler: Compiler,
config: Route[][], opts: ExtraOptions = {}, urlHandlingStrategy?: UrlHandlingStrategy,
routeReuseStrategy?: RouteReuseStrategy) {
const router = new Router(
null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(config));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
if (routeReuseStrategy) {
router.routeReuseStrategy = routeReuseStrategy;
}
if (opts.errorHandler) {
router.errorHandler = opts.errorHandler;
}
if (opts.enableTracing) {
const dom = getDOM();
router.events.subscribe(e => {
dom.logGroup(`Router Event: ${(<any>e.constructor).name}`);
dom.log(e.toString());
dom.log(e);
dom.logGroupEnd();
});
}
return router;
}
export function rootRoute(router: Router): ActivatedRoute {
return router.routerState.root;
}
export function initialRouterNavigation(
router: Router, ref: ApplicationRef, preloader: RouterPreloader, opts: ExtraOptions) {
return (bootstrappedComponentRef: ComponentRef<any>) => {
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
router.resetRootComponentType(ref.componentTypes[0]);
preloader.setUpPreloading();
if (opts.initialNavigation === false) {
router.setUpLocationChangeListener();
} | import {getDOM} from './private_import_platform-browser'; | random_line_split |
watchdog.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info>
//
// 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.
//! Watchdog for Kinetis SIM module.
use util::support::nop;
#[path="../../util/ioreg.rs"] mod ioreg;
/// Watchdog state
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum State {
Disabled,
Enabled,
}
/// Init watchdog
pub fn init(state : State) {
| fn unlock() {
use self::reg::WDOG_unlock_unlock::*;
reg::WDOG.unlock.set_unlock(UnlockSeq1);
reg::WDOG.unlock.set_unlock(UnlockSeq2);
// Enforce one cycle delay
nop();
}
/// Write refresh sequence to refresh watchdog
pub fn refresh() {
use self::reg::WDOG_refresh_refresh::*;
reg::WDOG.refresh.set_refresh(RefreshSeq1);
reg::WDOG.refresh.set_refresh(RefreshSeq2);
}
#[allow(dead_code)]
mod reg {
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(WDOG = {
/// Status and Control Register High
0x0 => reg16 stctrlh
{
0 => en, //= Watchdog enable
4 => allowupdate //= Enables updates to watchdog write-once registers,
//= after the reset-triggered initial configuration window
},
/// Refresh Register
0xc => reg16 refresh {
0..15 => refresh: wo
{
0xa602 => RefreshSeq1,
0xb480 => RefreshSeq2,
},
},
/// Unlock Register
0xe => reg16 unlock {
0..15 => unlock: wo
{
0xc520 => UnlockSeq1,
0xd928 => UnlockSeq2,
},
},
});
extern {
#[link_name="k20_iomem_WDOG"] pub static WDOG: WDOG;
}
}
| use self::State::*;
unlock();
match state {
Disabled => {
reg::WDOG.stctrlh.set_en(false);
},
Enabled => {
reg::WDOG.stctrlh.set_allowupdate(true);
},
}
}
| identifier_body |
watchdog.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info>
//
// 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 | // limitations under the License.
//! Watchdog for Kinetis SIM module.
use util::support::nop;
#[path="../../util/ioreg.rs"] mod ioreg;
/// Watchdog state
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum State {
Disabled,
Enabled,
}
/// Init watchdog
pub fn init(state : State) {
use self::State::*;
unlock();
match state {
Disabled => {
reg::WDOG.stctrlh.set_en(false);
},
Enabled => {
reg::WDOG.stctrlh.set_allowupdate(true);
},
}
}
fn unlock() {
use self::reg::WDOG_unlock_unlock::*;
reg::WDOG.unlock.set_unlock(UnlockSeq1);
reg::WDOG.unlock.set_unlock(UnlockSeq2);
// Enforce one cycle delay
nop();
}
/// Write refresh sequence to refresh watchdog
pub fn refresh() {
use self::reg::WDOG_refresh_refresh::*;
reg::WDOG.refresh.set_refresh(RefreshSeq1);
reg::WDOG.refresh.set_refresh(RefreshSeq2);
}
#[allow(dead_code)]
mod reg {
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(WDOG = {
/// Status and Control Register High
0x0 => reg16 stctrlh
{
0 => en, //= Watchdog enable
4 => allowupdate //= Enables updates to watchdog write-once registers,
//= after the reset-triggered initial configuration window
},
/// Refresh Register
0xc => reg16 refresh {
0..15 => refresh: wo
{
0xa602 => RefreshSeq1,
0xb480 => RefreshSeq2,
},
},
/// Unlock Register
0xe => reg16 unlock {
0..15 => unlock: wo
{
0xc520 => UnlockSeq1,
0xd928 => UnlockSeq2,
},
},
});
extern {
#[link_name="k20_iomem_WDOG"] pub static WDOG: WDOG;
}
} | // 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 | random_line_split |
watchdog.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Dawid Ciężarkiewcz <dpc@ucore.info>
//
// 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.
//! Watchdog for Kinetis SIM module.
use util::support::nop;
#[path="../../util/ioreg.rs"] mod ioreg;
/// Watchdog state
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum State {
Disabled,
Enabled,
}
/// Init watchdog
pub fn init(state : State) {
use self::State::*;
unlock();
match state {
Disabled => {
reg::WDOG.stctrlh.set_en(false);
},
Enabled => {
reg::WDOG.stctrlh.set_allowupdate(true);
},
}
}
fn unlock() {
use self::reg::WDOG_unlock_unlock::*;
reg::WDOG.unlock.set_unlock(UnlockSeq1);
reg::WDOG.unlock.set_unlock(UnlockSeq2);
// Enforce one cycle delay
nop();
}
/// Write refresh sequence to refresh watchdog
pub fn re | {
use self::reg::WDOG_refresh_refresh::*;
reg::WDOG.refresh.set_refresh(RefreshSeq1);
reg::WDOG.refresh.set_refresh(RefreshSeq2);
}
#[allow(dead_code)]
mod reg {
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(WDOG = {
/// Status and Control Register High
0x0 => reg16 stctrlh
{
0 => en, //= Watchdog enable
4 => allowupdate //= Enables updates to watchdog write-once registers,
//= after the reset-triggered initial configuration window
},
/// Refresh Register
0xc => reg16 refresh {
0..15 => refresh: wo
{
0xa602 => RefreshSeq1,
0xb480 => RefreshSeq2,
},
},
/// Unlock Register
0xe => reg16 unlock {
0..15 => unlock: wo
{
0xc520 => UnlockSeq1,
0xd928 => UnlockSeq2,
},
},
});
extern {
#[link_name="k20_iomem_WDOG"] pub static WDOG: WDOG;
}
}
| fresh() | identifier_name |
BuiltInCommands.ts | import {Job} from "./Job";
import {existsSync, statSync} from "fs";
import {homeDirectory, pluralize, resolveDirectory, resolveFile, mapObject} from "../utils/Common";
import {readFileSync} from "fs";
import {EOL} from "os";
import {Session} from "./Session";
import {OrderedSet} from "../utils/OrderedSet";
import {parseAlias} from "./Aliases";
import {stringLiteralValue} from "./Scanner";
const executors: Dictionary<(i: Job, a: string[]) => void> = {
cd: (job: Job, args: string[]): void => {
let fullPath: string;
if (!args.length) {
fullPath = homeDirectory;
} else {
const enteredPath = args[0];
if (isHistoricalDirectory(enteredPath)) {
fullPath = expandHistoricalDirectory(enteredPath, job.session.historicalPresentDirectoriesStack);
} else {
fullPath = job.environment.cdpath
.map(path => resolveDirectory(path, enteredPath))
.filter(resolved => existsSync(resolved))
.filter(resolved => statSync(resolved).isDirectory())[0];
if (!fullPath) {
throw new Error(`The directory "${enteredPath}" doesn't exist.`);
}
}
}
job.session.directory = fullPath;
},
clear: (job: Job, _args: string[]): void => {
setTimeout(() => job.session.clearJobs(), 0);
},
exit: (job: Job, _args: string[]): void => {
job.session.close();
},
export: (job: Job, args: string[]): void => {
if (args.length === 0) {
job.output.write(job.environment.map((key, value) => `${key}=${value}`).join("\r\n"));
} else {
args.forEach(argument => {
const firstEqualIndex = argument.indexOf("=");
const key = argument.slice(0, firstEqualIndex);
const value = argument.slice(firstEqualIndex + 1);
job.session.environment.set(key, value);
});
}
},
// FIXME: make the implementation more reliable.
source: (job: Job, args: string[]): void => {
sourceFile(job.session, args[0]);
},
alias: (job: Job, args: string[]): void => {
if (args.length === 0) {
job.output.write(mapObject(job.session.aliases.toObject(), (key, value) => `${key}=${value}`).join("\r\n"));
} else if (args.length === 1) | else {
throw `Don't know what to do with ${args.length} arguments.`;
}
},
unalias: (job: Job, args: string[]): void => {
if (args.length === 1) {
const name = args[0];
if (job.session.aliases.has(name)) {
job.session.aliases.remove(args[0]);
} else {
throw `There is such alias: ${name}.`;
}
} else {
throw `Don't know what to do with ${args.length} arguments.`;
}
},
show: (job: Job, args: string[]): void => {
const imgs = args.map(argument => resolveFile(job.environment.pwd, argument));
job.output.write(imgs.join(EOL));
},
};
export function sourceFile(session: Session, fileName: string) {
const content = readFileSync(resolveFile(session.directory, fileName)).toString();
content.split(EOL).forEach(line => {
if (line.startsWith("export ")) {
const [variableName, variableValueLiteral] = line.split(" ")[1].split("=");
const variableValue = stringLiteralValue(variableValueLiteral);
if (variableValue) {
session.environment.set(variableName, variableValue);
}
}
});
}
// A class representing built in commands
export class Command {
static allCommandNames = Object.keys(executors);
static executor(command: string): (i: Job, args: string[]) => void {
return executors[command];
}
static isBuiltIn(command: string): boolean {
return this.allCommandNames.includes(command);
}
}
export function expandHistoricalDirectory(alias: string, historicalDirectories: OrderedSet<string>): string {
if (alias === "-") {
alias = "-1";
}
const index = historicalDirectories.size + parseInt(alias, 10);
if (index < 0) {
throw new Error(`Error: you only have ${historicalDirectories.size} ${pluralize("directory", historicalDirectories.size)} in the stack.`);
} else {
const directory = historicalDirectories.at(index);
if (directory) {
return directory;
} else {
throw `No directory with index ${index}`;
}
}
}
export function isHistoricalDirectory(directory: string): boolean {
return /^-\d*$/.test(directory);
}
| {
const parsed = parseAlias(args[0]);
job.session.aliases.add(parsed.name, parsed.value);
} | conditional_block |
BuiltInCommands.ts | import {Job} from "./Job";
import {existsSync, statSync} from "fs";
import {homeDirectory, pluralize, resolveDirectory, resolveFile, mapObject} from "../utils/Common";
import {readFileSync} from "fs";
import {EOL} from "os";
import {Session} from "./Session";
import {OrderedSet} from "../utils/OrderedSet";
import {parseAlias} from "./Aliases";
import {stringLiteralValue} from "./Scanner";
const executors: Dictionary<(i: Job, a: string[]) => void> = {
cd: (job: Job, args: string[]): void => {
let fullPath: string;
if (!args.length) {
fullPath = homeDirectory;
} else {
const enteredPath = args[0];
if (isHistoricalDirectory(enteredPath)) {
fullPath = expandHistoricalDirectory(enteredPath, job.session.historicalPresentDirectoriesStack);
} else {
fullPath = job.environment.cdpath
.map(path => resolveDirectory(path, enteredPath))
.filter(resolved => existsSync(resolved))
.filter(resolved => statSync(resolved).isDirectory())[0];
if (!fullPath) {
throw new Error(`The directory "${enteredPath}" doesn't exist.`);
}
}
}
job.session.directory = fullPath;
},
clear: (job: Job, _args: string[]): void => {
setTimeout(() => job.session.clearJobs(), 0);
},
exit: (job: Job, _args: string[]): void => {
job.session.close();
},
export: (job: Job, args: string[]): void => {
if (args.length === 0) {
job.output.write(job.environment.map((key, value) => `${key}=${value}`).join("\r\n"));
} else {
args.forEach(argument => {
const firstEqualIndex = argument.indexOf("=");
const key = argument.slice(0, firstEqualIndex);
const value = argument.slice(firstEqualIndex + 1);
job.session.environment.set(key, value);
});
}
},
// FIXME: make the implementation more reliable.
source: (job: Job, args: string[]): void => {
sourceFile(job.session, args[0]);
},
alias: (job: Job, args: string[]): void => {
if (args.length === 0) {
job.output.write(mapObject(job.session.aliases.toObject(), (key, value) => `${key}=${value}`).join("\r\n"));
} else if (args.length === 1) {
const parsed = parseAlias(args[0]);
job.session.aliases.add(parsed.name, parsed.value);
} else {
throw `Don't know what to do with ${args.length} arguments.`;
}
},
unalias: (job: Job, args: string[]): void => {
if (args.length === 1) {
const name = args[0];
if (job.session.aliases.has(name)) {
job.session.aliases.remove(args[0]);
} else {
throw `There is such alias: ${name}.`;
}
} else {
throw `Don't know what to do with ${args.length} arguments.`;
}
},
show: (job: Job, args: string[]): void => {
const imgs = args.map(argument => resolveFile(job.environment.pwd, argument));
job.output.write(imgs.join(EOL));
},
};
export function sourceFile(session: Session, fileName: string) {
const content = readFileSync(resolveFile(session.directory, fileName)).toString();
content.split(EOL).forEach(line => {
if (line.startsWith("export ")) {
const [variableName, variableValueLiteral] = line.split(" ")[1].split("=");
const variableValue = stringLiteralValue(variableValueLiteral);
if (variableValue) {
session.environment.set(variableName, variableValue);
}
}
});
}
// A class representing built in commands
export class Command {
static allCommandNames = Object.keys(executors);
static executor(command: string): (i: Job, args: string[]) => void {
return executors[command];
}
static isBuiltIn(command: string): boolean {
return this.allCommandNames.includes(command);
}
}
export function | (alias: string, historicalDirectories: OrderedSet<string>): string {
if (alias === "-") {
alias = "-1";
}
const index = historicalDirectories.size + parseInt(alias, 10);
if (index < 0) {
throw new Error(`Error: you only have ${historicalDirectories.size} ${pluralize("directory", historicalDirectories.size)} in the stack.`);
} else {
const directory = historicalDirectories.at(index);
if (directory) {
return directory;
} else {
throw `No directory with index ${index}`;
}
}
}
export function isHistoricalDirectory(directory: string): boolean {
return /^-\d*$/.test(directory);
}
| expandHistoricalDirectory | identifier_name |
BuiltInCommands.ts | import {Job} from "./Job";
import {existsSync, statSync} from "fs";
import {homeDirectory, pluralize, resolveDirectory, resolveFile, mapObject} from "../utils/Common";
import {readFileSync} from "fs";
import {EOL} from "os";
import {Session} from "./Session";
import {OrderedSet} from "../utils/OrderedSet";
import {parseAlias} from "./Aliases";
import {stringLiteralValue} from "./Scanner";
const executors: Dictionary<(i: Job, a: string[]) => void> = {
cd: (job: Job, args: string[]): void => {
let fullPath: string;
if (!args.length) {
fullPath = homeDirectory;
} else {
const enteredPath = args[0];
if (isHistoricalDirectory(enteredPath)) {
fullPath = expandHistoricalDirectory(enteredPath, job.session.historicalPresentDirectoriesStack);
} else {
fullPath = job.environment.cdpath
.map(path => resolveDirectory(path, enteredPath))
.filter(resolved => existsSync(resolved))
.filter(resolved => statSync(resolved).isDirectory())[0];
if (!fullPath) {
throw new Error(`The directory "${enteredPath}" doesn't exist.`);
}
}
}
job.session.directory = fullPath;
},
clear: (job: Job, _args: string[]): void => {
setTimeout(() => job.session.clearJobs(), 0);
},
exit: (job: Job, _args: string[]): void => {
job.session.close();
},
export: (job: Job, args: string[]): void => {
if (args.length === 0) {
job.output.write(job.environment.map((key, value) => `${key}=${value}`).join("\r\n"));
} else {
args.forEach(argument => {
const firstEqualIndex = argument.indexOf("=");
const key = argument.slice(0, firstEqualIndex);
const value = argument.slice(firstEqualIndex + 1);
job.session.environment.set(key, value);
});
}
},
// FIXME: make the implementation more reliable.
source: (job: Job, args: string[]): void => {
sourceFile(job.session, args[0]);
},
alias: (job: Job, args: string[]): void => {
if (args.length === 0) {
job.output.write(mapObject(job.session.aliases.toObject(), (key, value) => `${key}=${value}`).join("\r\n"));
} else if (args.length === 1) {
const parsed = parseAlias(args[0]);
job.session.aliases.add(parsed.name, parsed.value);
} else {
throw `Don't know what to do with ${args.length} arguments.`;
}
},
unalias: (job: Job, args: string[]): void => {
if (args.length === 1) {
const name = args[0];
if (job.session.aliases.has(name)) {
job.session.aliases.remove(args[0]);
} else {
throw `There is such alias: ${name}.`;
}
} else {
throw `Don't know what to do with ${args.length} arguments.`;
}
},
show: (job: Job, args: string[]): void => {
const imgs = args.map(argument => resolveFile(job.environment.pwd, argument));
job.output.write(imgs.join(EOL));
},
};
export function sourceFile(session: Session, fileName: string) {
const content = readFileSync(resolveFile(session.directory, fileName)).toString();
content.split(EOL).forEach(line => {
if (line.startsWith("export ")) {
const [variableName, variableValueLiteral] = line.split(" ")[1].split("=");
const variableValue = stringLiteralValue(variableValueLiteral);
if (variableValue) {
session.environment.set(variableName, variableValue);
}
}
}); |
static executor(command: string): (i: Job, args: string[]) => void {
return executors[command];
}
static isBuiltIn(command: string): boolean {
return this.allCommandNames.includes(command);
}
}
export function expandHistoricalDirectory(alias: string, historicalDirectories: OrderedSet<string>): string {
if (alias === "-") {
alias = "-1";
}
const index = historicalDirectories.size + parseInt(alias, 10);
if (index < 0) {
throw new Error(`Error: you only have ${historicalDirectories.size} ${pluralize("directory", historicalDirectories.size)} in the stack.`);
} else {
const directory = historicalDirectories.at(index);
if (directory) {
return directory;
} else {
throw `No directory with index ${index}`;
}
}
}
export function isHistoricalDirectory(directory: string): boolean {
return /^-\d*$/.test(directory);
} | }
// A class representing built in commands
export class Command {
static allCommandNames = Object.keys(executors); | random_line_split |
BuiltInCommands.ts | import {Job} from "./Job";
import {existsSync, statSync} from "fs";
import {homeDirectory, pluralize, resolveDirectory, resolveFile, mapObject} from "../utils/Common";
import {readFileSync} from "fs";
import {EOL} from "os";
import {Session} from "./Session";
import {OrderedSet} from "../utils/OrderedSet";
import {parseAlias} from "./Aliases";
import {stringLiteralValue} from "./Scanner";
const executors: Dictionary<(i: Job, a: string[]) => void> = {
cd: (job: Job, args: string[]): void => {
let fullPath: string;
if (!args.length) {
fullPath = homeDirectory;
} else {
const enteredPath = args[0];
if (isHistoricalDirectory(enteredPath)) {
fullPath = expandHistoricalDirectory(enteredPath, job.session.historicalPresentDirectoriesStack);
} else {
fullPath = job.environment.cdpath
.map(path => resolveDirectory(path, enteredPath))
.filter(resolved => existsSync(resolved))
.filter(resolved => statSync(resolved).isDirectory())[0];
if (!fullPath) {
throw new Error(`The directory "${enteredPath}" doesn't exist.`);
}
}
}
job.session.directory = fullPath;
},
clear: (job: Job, _args: string[]): void => {
setTimeout(() => job.session.clearJobs(), 0);
},
exit: (job: Job, _args: string[]): void => {
job.session.close();
},
export: (job: Job, args: string[]): void => {
if (args.length === 0) {
job.output.write(job.environment.map((key, value) => `${key}=${value}`).join("\r\n"));
} else {
args.forEach(argument => {
const firstEqualIndex = argument.indexOf("=");
const key = argument.slice(0, firstEqualIndex);
const value = argument.slice(firstEqualIndex + 1);
job.session.environment.set(key, value);
});
}
},
// FIXME: make the implementation more reliable.
source: (job: Job, args: string[]): void => {
sourceFile(job.session, args[0]);
},
alias: (job: Job, args: string[]): void => {
if (args.length === 0) {
job.output.write(mapObject(job.session.aliases.toObject(), (key, value) => `${key}=${value}`).join("\r\n"));
} else if (args.length === 1) {
const parsed = parseAlias(args[0]);
job.session.aliases.add(parsed.name, parsed.value);
} else {
throw `Don't know what to do with ${args.length} arguments.`;
}
},
unalias: (job: Job, args: string[]): void => {
if (args.length === 1) {
const name = args[0];
if (job.session.aliases.has(name)) {
job.session.aliases.remove(args[0]);
} else {
throw `There is such alias: ${name}.`;
}
} else {
throw `Don't know what to do with ${args.length} arguments.`;
}
},
show: (job: Job, args: string[]): void => {
const imgs = args.map(argument => resolveFile(job.environment.pwd, argument));
job.output.write(imgs.join(EOL));
},
};
export function sourceFile(session: Session, fileName: string) {
const content = readFileSync(resolveFile(session.directory, fileName)).toString();
content.split(EOL).forEach(line => {
if (line.startsWith("export ")) {
const [variableName, variableValueLiteral] = line.split(" ")[1].split("=");
const variableValue = stringLiteralValue(variableValueLiteral);
if (variableValue) {
session.environment.set(variableName, variableValue);
}
}
});
}
// A class representing built in commands
export class Command {
static allCommandNames = Object.keys(executors);
static executor(command: string): (i: Job, args: string[]) => void {
return executors[command];
}
static isBuiltIn(command: string): boolean {
return this.allCommandNames.includes(command);
}
}
export function expandHistoricalDirectory(alias: string, historicalDirectories: OrderedSet<string>): string |
export function isHistoricalDirectory(directory: string): boolean {
return /^-\d*$/.test(directory);
}
| {
if (alias === "-") {
alias = "-1";
}
const index = historicalDirectories.size + parseInt(alias, 10);
if (index < 0) {
throw new Error(`Error: you only have ${historicalDirectories.size} ${pluralize("directory", historicalDirectories.size)} in the stack.`);
} else {
const directory = historicalDirectories.at(index);
if (directory) {
return directory;
} else {
throw `No directory with index ${index}`;
}
}
} | identifier_body |
util.format.js | // I used to use `util.format()` which was massive, then I switched to
// format-util, although when using rollup I discovered that the index.js
// just exported `require('util').format`, and then had the below contents
// in another file. at any rate all I want is this function:
function format(fmt) {
fmt = String(fmt); // this is closer to util.format() behavior
var re = /(%?)(%([jds]))/g
, args = Array.prototype.slice.call(arguments, 1);
if(args.length) {
if(Array.isArray(args[0])) | var arg = args.shift();
switch(flag) {
case 's':
arg = '' + arg;
break;
case 'd':
arg = Number(arg);
break;
case 'j':
arg = JSON.stringify(arg);
break;
}
if(!escaped) {
return arg;
}
args.unshift(arg);
return match;
})
}
// arguments remain after formatting
if(args.length) {
fmt += ' ' + args.join(' ');
}
// update escaped %% values
fmt = fmt.replace(/%{2,2}/g, '%');
return '' + fmt;
}
export default format; | args = args[0];
fmt = fmt.replace(re, function(match, escaped, ptn, flag) { | random_line_split |
util.format.js | // I used to use `util.format()` which was massive, then I switched to
// format-util, although when using rollup I discovered that the index.js
// just exported `require('util').format`, and then had the below contents
// in another file. at any rate all I want is this function:
function | (fmt) {
fmt = String(fmt); // this is closer to util.format() behavior
var re = /(%?)(%([jds]))/g
, args = Array.prototype.slice.call(arguments, 1);
if(args.length) {
if(Array.isArray(args[0]))
args = args[0];
fmt = fmt.replace(re, function(match, escaped, ptn, flag) {
var arg = args.shift();
switch(flag) {
case 's':
arg = '' + arg;
break;
case 'd':
arg = Number(arg);
break;
case 'j':
arg = JSON.stringify(arg);
break;
}
if(!escaped) {
return arg;
}
args.unshift(arg);
return match;
})
}
// arguments remain after formatting
if(args.length) {
fmt += ' ' + args.join(' ');
}
// update escaped %% values
fmt = fmt.replace(/%{2,2}/g, '%');
return '' + fmt;
}
export default format;
| format | identifier_name |
util.format.js | // I used to use `util.format()` which was massive, then I switched to
// format-util, although when using rollup I discovered that the index.js
// just exported `require('util').format`, and then had the below contents
// in another file. at any rate all I want is this function:
function format(fmt) | if(!escaped) {
return arg;
}
args.unshift(arg);
return match;
})
}
// arguments remain after formatting
if(args.length) {
fmt += ' ' + args.join(' ');
}
// update escaped %% values
fmt = fmt.replace(/%{2,2}/g, '%');
return '' + fmt;
}
export default format;
| {
fmt = String(fmt); // this is closer to util.format() behavior
var re = /(%?)(%([jds]))/g
, args = Array.prototype.slice.call(arguments, 1);
if(args.length) {
if(Array.isArray(args[0]))
args = args[0];
fmt = fmt.replace(re, function(match, escaped, ptn, flag) {
var arg = args.shift();
switch(flag) {
case 's':
arg = '' + arg;
break;
case 'd':
arg = Number(arg);
break;
case 'j':
arg = JSON.stringify(arg);
break;
} | identifier_body |
Base.tpl.py | {% block meta %}
name: Base
description: SMACH base template.
language: Python
framework: SMACH
type: Base
tags: [core]
includes: []
extends: []
variables:
- - manifest:
description: ROS manifest name.
type: str
- - node_name:
description: ROS node name for the state machine.
type: str
- outcomes:
description: A list of possible outcomes of the state machine.
type: list
- - userdata:
description: Definitions for userdata needed by child states.
type: dict
- - function_name:
description: A name for the main executable state machine function.
type: str
input_keys: []
output_keys: [] |
{% set defined_headers = [] %}
{% set local_vars = [] %}
{% block base_header %}
#!/usr/bin/env python
{{ base_header }}
{% endblock base_header %}
{% block imports %}
{{ import_module(defined_headers, 'smach') }}
{{ imports }}
{% endblock imports %}
{% block defs %}
{{ defs }}
{% endblock defs %}
{% block class_defs %}
{{ class_defs }}
{% endblock class_defs %}
{% block cb_defs %}
{{ cb_defs }}
{% endblock cb_defs %}
{% if name is defined %}{% set sm_name = name | lower() %}{% else %}{% set sm_name = 'sm' %}{% endif %}
{% block main_def %}
def {% if function_name is defined %}{{ function_name | lower() }}{% else %}main{% endif %}():
{{ main_def | indent(4) }}
{% endblock main_def %}
{% block body %}
{{ sm_name }} = smach.StateMachine({{ render_outcomes(outcomes) }})
{# Container header insertion variable indexed by container state name #}
{% if name in header %}{{ header[name] | indent(4, true) }}{% endif %}
{# Render container userdata #}
{% if userdata is defined %}{{ render_userdata(name | lower(), userdata) | indent(4) }}{% endif %}
{# Render state userdata #}
{% if name in header_userdata %}{{ header_userdata[name] | indent(4, true) }}{% endif %}
with {{ sm_name }}:
{# Container body insertion variable #}
{{ body | indent(8) }}
{% endblock body %}
{% block footer %}
{{ footer | indent(8) }}
{% endblock footer %}
{% block execute %}
{{ execute | indent(4) }}
outcome = {{ sm_name }}.execute()
{% endblock execute %}
{% block base_footer %}
{{ base_footer | indent(4) }}
{% endblock base_footer %}
{% block main %}
if __name__ == '__main__':
{{ '' | indent(4, true) }}{% if function_name is defined %}{{ function_name | lower() }}{% else %}main{% endif %}()
{% endblock main %} | {% endblock meta %}
{% from "Utils.tpl.py" import import_module, render_outcomes, render_userdata %} | random_line_split |
index.js | /**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* 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.
*/
'use strict';
/**
* Compute the hyperbolic cosecant of a number.
*
* @module @stdlib/math/base/special/csch
*
* @example
* var csch = require( '@stdlib/math/base/special/csch' ); | * // returns Infinity
*
* v = csch( 2.0 );
* // returns ~0.2757
*
* v = csch( -2.0 );
* // returns ~-0.2757
*
* v = csch( NaN );
* // returns NaN
*/
// MODULES //
var main = require( './main.js' );
// EXPORTS //
module.exports = main; | *
* var v = csch( 0.0 ); | random_line_split |
grid.js | ctype: link_field.options,
fieldname: link,
qty_fieldname: qty,
target: me,
txt: ""
});
return false;
});
this.multiple_set = true;
}
});
frappe.ui.form.GridRow = Class.extend({
init: function(opts) {
$.extend(this, opts);
this.show = false;
this.make();
},
make: function() {
var me = this;
this.wrapper = $('<div class="grid-row"></div>').appendTo(this.parent).data("grid_row", this);
this.row = $('<div class="data-row" style="min-height: 26px;"></div>').appendTo(this.wrapper)
.on("click", function() {
me.toggle_view();
return false;
});
this.divider = $('<div class="divider row"></div>').appendTo(this.wrapper);
this.set_row_index();
this.make_static_display();
if(this.doc) {
this.set_data();
}
},
set_row_index: function() {
if(this.doc) {
this.wrapper
.attr("data-idx", this.doc.idx)
.find(".row-index").html(this.doc.idx)
}
},
remove: function() {
if(this.grid.is_editable()) {
var me = this;
me.wrapper.toggle(false);
frappe.model.clear_doc(me.doc.doctype, me.doc.name);
me.frm.script_manager.trigger(me.grid.df.fieldname + "_remove", me.doc.doctype, me.doc.name);
me.frm.dirty();
me.grid.refresh();
}
},
insert: function(show) {
var idx = this.doc.idx;
this.toggle_view(false);
this.grid.add_new_row(idx, null, show);
},
refresh: function() {
if(this.doc)
this.doc = locals[this.doc.doctype][this.doc.name];
// re write columns
this.grid.static_display_template = null;
this.make_static_display();
// refersh form fields
if(this.show) {
this.layout.refresh(this.doc);
}
},
make_static_display: function() {
var me = this;
this.row.empty();
$('<div class="col-xs-1 row-index">' + (this.doc ? this.doc.idx : "#")+ '</div>')
.appendTo(this.row);
if(this.grid.template) {
$('<div class="col-xs-10">').appendTo(this.row)
.html(frappe.render(this.grid.template, {
doc: this.doc ? frappe.get_format_helper(this.doc) : null,
frm: this.frm,
row: this
}));
} else {
this.add_visible_columns();
}
this.add_buttons();
$(this.frm.wrapper).trigger("grid-row-render", [this]);
},
add_buttons: function() {
var me = this;
if(this.doc && this.grid.is_editable()) {
if(!this.grid.$row_actions) {
this.grid.$row_actions = $('<div class="col-xs-1 pull-right" \
style="text-align: right; padding-right: 5px;">\
<span class="text-success grid-insert-row" style="padding: 4px;">\
<i class="icon icon-plus-sign"></i></span>\
<span class="grid-delete-row" style="padding: 4px;">\
<i class="icon icon-trash"></i></span>\
</div>');
}
$col = this.grid.$row_actions.clone().appendTo(this.row);
if($col.width() < 50) {
$col.toggle(false);
} else {
$col.toggle(true);
$col.find(".grid-insert-row").click(function() { me.insert(); return false; });
$col.find(".grid-delete-row").click(function() { me.remove(); return false; });
}
} else {
$('<div class="col-xs-1"></div>').appendTo(this.row);
}
},
add_visible_columns: function() {
this.make_static_display_template();
for(var ci in this.static_display_template) {
var df = this.static_display_template[ci][0];
var colsize = this.static_display_template[ci][1];
var txt = this.doc ?
frappe.format(this.doc[df.fieldname], df, null, this.doc) :
__(df.label);
if(this.doc && df.fieldtype === "Select") {
txt = __(txt);
}
var add_class = (["Text", "Small Text"].indexOf(df.fieldtype)===-1) ?
" grid-overflow-ellipsis" : " grid-overflow-no-ellipsis";
add_class += (["Int", "Currency", "Float"].indexOf(df.fieldtype)!==-1) ?
" text-right": "";
$col = $('<div class="col col-xs-'+colsize+add_class+'"></div>')
.html(txt)
.attr("data-fieldname", df.fieldname)
.data("df", df)
.appendTo(this.row)
if(!this.doc) $col.css({"font-weight":"bold"})
}
},
make_static_display_template: function() {
if(this.static_display_template) return;
var total_colsize = 1;
this.static_display_template = [];
for(var ci in this.docfields) {
var df = this.docfields[ci];
if(!df.hidden && df.in_list_view && this.grid.frm.get_perm(df.permlevel, "read")
&& !in_list(frappe.model.layout_fields, df.fieldtype)) {
var colsize = 2;
switch(df.fieldtype) {
case "Text":
case "Small Text":
colsize = 3;
break;
case "Check":
colsize = 1;
break;
}
total_colsize += colsize
if(total_colsize > 11)
return false;
this.static_display_template.push([df, colsize]);
}
}
// redistribute if total-col size is less than 12
var passes = 0;
while(total_colsize < 11 && passes < 10) {
for(var i in this.static_display_template) {
var df = this.static_display_template[i][0];
var colsize = this.static_display_template[i][1];
if(colsize>1 && colsize<12 && ["Int", "Currency", "Float"].indexOf(df.fieldtype)===-1) {
this.static_display_template[i][1] += 1;
total_colsize++;
}
if(total_colsize >= 11)
break;
}
passes++;
}
},
toggle_view: function(show, callback) {
if(!this.doc) return this;
this.doc = locals[this.doc.doctype][this.doc.name];
// hide other
var open_row = $(".grid-row-open").data("grid_row");
this.fields = [];
this.fields_dict = {};
this.show = show===undefined ?
show = !this.show :
show
// call blur
document.activeElement && document.activeElement.blur()
if(show && open_row) {
if(open_row==this) {
// already open, do nothing
callback();
return;
} else {
// close other views
open_row.toggle_view(false);
}
}
this.wrapper.toggleClass("grid-row-open", this.show);
if(this.show) {
if(!this.form_panel) {
this.form_panel = $('<div class="panel panel-warning" style="display: none;"></div>')
.insertBefore(this.divider);
}
this.render_form();
this.row.toggle(false);
this.form_panel.toggle(true);
if(this.frm.doc.docstatus===0) {
var first = this.form_area.find(":input:first");
if(first.length && first.attr("data-fieldtype")!="Date") {
try {
first.get(0).focus();
} catch(e) {
console.log("Dialog: unable to focus on first input: " + e);
}
}
}
} else {
if(this.form_panel)
this.form_panel.toggle(false);
this.row.toggle(true);
this.make_static_display();
}
callback && callback();
return this;
},
open_prev: function() {
if(this.grid.grid_rows[this.doc.idx-2]) {
this.grid.grid_rows[this.doc.idx-2].toggle_view(true);
}
},
open_next: function() {
if(this.grid.grid_rows[this.doc.idx]) {
this.grid.grid_rows[this.doc.idx].toggle_view(true);
} else {
this.grid.add_new_row(null, null, true);
}
},
toggle_add_delete_button_display: function($parent) {
$parent.find(".grid-delete-row, .grid-insert-row, .grid-append-row")
.toggle(this.grid.is_editable());
},
render_form: function() {
var me = this;
this.make_form();
this.form_area.empty();
this.layout = new frappe.ui.form.Layout({
fields: this.docfields,
body: this.form_area,
no_submit_on_enter: true,
frm: this.frm,
});
this.layout.make();
this.fields = this.layout.fields; | this.fields_dict = this.layout.fields_dict; | random_line_split |
|
react-redux-toastr.d.ts | // Type definitions for react-redux-toastr 3.7.0
// Project: https://github.com/diegoddox/react-redux-toastr
// Definitions by: Aleksandar Ivanov <https://github.com/Smiche>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference path="../react/react.d.ts" />
///<reference path="../redux/redux.d.ts"/>
declare module "react-redux-toastr" {
import R = __React;
import _Redux = Redux;
interface ToastrOptions {
/**
* Timeout in miliseconds.
*/
timeOut?: number,
/**
* Show newest on top or bottom.
*/
newestOnTop?: boolean,
/**
* Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right
*/
position?: string,
confirmText?: ConfirmText
}
interface ConfirmText {
okText: string,
cancelText: string
}
/**
* Toastr react component.
*/
export default class | extends R.Component<ToastrOptions, any>{ }
interface EmitterOptions {
/**
* Notification popup icon.
* icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert
*/
icon?: string,
/**
* Timeout in miliseconds.
*/
timeOut?: number,
removeOnHover?: boolean,
removeOnClick?: boolean,
component?: R.Component<any, any>,
onShowComplete?(): void;
onHideComplete?(): void;
}
interface ToastrConfirmOptions {
onOk(): void;
onCancel(): void;
}
interface ToastrEmitter {
/**
* Used to provide a large amount of information.
* It will not close unless a timeOut is provided.
*/
message(title: string, message: string, options?: EmitterOptions): void;
info(title: string, message: string, options?: EmitterOptions): void;
success(title: string, message: string, options?: EmitterOptions): void;
warning(title: string, message: string, options?: EmitterOptions): void;
error(title: string, message: string, options?: EmitterOptions): void;
/**
* Clear all notifications
*/
clean(): void;
/**
* Hook confirmation toastr with callback.
*/
confirm(message: string, options: ToastrConfirmOptions): void;
}
/**
* Possible actions to dispatch.
*/
interface Actions {
addToastrAction: Redux.Action,
clean: Redux.Action,
remove: Redux.Action,
success: Redux.Action,
info: Redux.Action,
warning: Redux.Action,
error: Redux.Action,
showConfirm: Redux.Action,
hideConfirm: Redux.Action
}
/**
* Action creator for toastr.
*/
export var actions: Redux.ActionCreator<Actions>;
/**
* Reducer for the toastr state.
* Combine with your reducers.
*/
export var reducer: Redux.Reducer<any>;
/**
* Used to issue toastr notifications.
*/
export var toastr: ToastrEmitter;
}
| ReduxToastr | identifier_name |
react-redux-toastr.d.ts | // Type definitions for react-redux-toastr 3.7.0
// Project: https://github.com/diegoddox/react-redux-toastr
// Definitions by: Aleksandar Ivanov <https://github.com/Smiche>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference path="../react/react.d.ts" />
///<reference path="../redux/redux.d.ts"/>
declare module "react-redux-toastr" {
import R = __React;
import _Redux = Redux;
interface ToastrOptions {
/**
* Timeout in miliseconds.
*/
timeOut?: number,
/**
* Show newest on top or bottom.
*/
newestOnTop?: boolean, | position?: string,
confirmText?: ConfirmText
}
interface ConfirmText {
okText: string,
cancelText: string
}
/**
* Toastr react component.
*/
export default class ReduxToastr extends R.Component<ToastrOptions, any>{ }
interface EmitterOptions {
/**
* Notification popup icon.
* icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert
*/
icon?: string,
/**
* Timeout in miliseconds.
*/
timeOut?: number,
removeOnHover?: boolean,
removeOnClick?: boolean,
component?: R.Component<any, any>,
onShowComplete?(): void;
onHideComplete?(): void;
}
interface ToastrConfirmOptions {
onOk(): void;
onCancel(): void;
}
interface ToastrEmitter {
/**
* Used to provide a large amount of information.
* It will not close unless a timeOut is provided.
*/
message(title: string, message: string, options?: EmitterOptions): void;
info(title: string, message: string, options?: EmitterOptions): void;
success(title: string, message: string, options?: EmitterOptions): void;
warning(title: string, message: string, options?: EmitterOptions): void;
error(title: string, message: string, options?: EmitterOptions): void;
/**
* Clear all notifications
*/
clean(): void;
/**
* Hook confirmation toastr with callback.
*/
confirm(message: string, options: ToastrConfirmOptions): void;
}
/**
* Possible actions to dispatch.
*/
interface Actions {
addToastrAction: Redux.Action,
clean: Redux.Action,
remove: Redux.Action,
success: Redux.Action,
info: Redux.Action,
warning: Redux.Action,
error: Redux.Action,
showConfirm: Redux.Action,
hideConfirm: Redux.Action
}
/**
* Action creator for toastr.
*/
export var actions: Redux.ActionCreator<Actions>;
/**
* Reducer for the toastr state.
* Combine with your reducers.
*/
export var reducer: Redux.Reducer<any>;
/**
* Used to issue toastr notifications.
*/
export var toastr: ToastrEmitter;
} | /**
* Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right
*/ | random_line_split |
reversi.rs |
use std::io::{Write, BufWriter};
static BOARD_SIZE: usize = 10; // 盤面のコマ+2
#[derive(Debug, Clone)]
pub enum PieceType {
Black,
White,
Sentinel,
Null,
}
fn flip_turn(t: PieceType) -> PieceType {
match t {
PieceType::Black => PieceType::White,
PieceType::White => PieceType::Black,
_ => PieceType::Null,
}
}
impl PartialEq for PieceType {
fn eq(&self, t: &PieceType) -> bool {
self == t
}
}
#[derive(Debug, Clone)]
pub struct Reversi {
board: Vec<Vec<PieceType>>,
pub turn: PieceType,
}
impl Reversi {
pub fn new() -> Self {
let mut v: Vec<Vec<PieceType>> = Vec::new();
let half = (BOARD_SIZE - 2) / 2;
for y in 0..BOARD_SIZE {
v.push(Vec::new());
for x in 0..BOARD_SIZE {
if y == 0 || x == 0 ||
y == BOARD_SIZE - 1 || x == BOARD_SIZE - 1 {
v[y].push(PieceType::Sentinel);
} else if y == half && x == half ||
y == half + 1 && x == half + 1 {
v[y | == half && x == half + 1 ||
y == half + 1 && x == half {
v[y].push(PieceType::Black);
} else {
v[y].push(PieceType::Null);
}
}
}
Reversi {
board: v,
turn: PieceType::Black,
}
}
pub fn debug_board(&self) {
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock());
for _i in 0..BOARD_SIZE {
write!(w, "+-").expect("stdout Error");
}
writeln!(w, "+").expect("stdout Error");
for y in &self.board {
write!(w, "|").expect("stdout Error");
for x in y {
write!(w, "{}|", match *x {
PieceType::Black => "x",
PieceType::White => "o",
PieceType::Null => " ",
PieceType::Sentinel => "=",
//_ => "",
}).expect("stdout Error");
}
writeln!(w, "").expect("stdout Error");
for _i in 0..BOARD_SIZE {
write!(w, "+-").expect("stdout Error");
}
writeln!(w, "+").expect("stdout Error");
}
}
pub fn show_turn(&self) {
println!("turn: {}", match self.turn {
PieceType::Black => "Black",
PieceType::White => "White",
_ => "Something wrong.",
})
}
pub fn turn_change(self) -> Self {
Reversi {
board: self.board,
turn: flip_turn(self.turn),
}
}
pub fn show_score(&self) {
let mut black = 0;
let mut white = 0;
for y in &self.board {
for x in y {
match *x {
PieceType::White => white += 1,
PieceType::Black => black += 1,
_ => {},
};
}
}
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock());
writeln!(w, "+---------+").expect("stdout Error");
writeln!(w, "| Score |").expect("stdout Error");
writeln!(w, "+---------+").expect("stdout Error");
writeln!(w, "|Black|{:03}|", black).expect("stdout Error");
writeln!(w, "+-----+---+").expect("stdout Error");
writeln!(w, "|White|{:03}|", white).expect("stdout Error");
writeln!(w, "+-----+---+").expect("stdout Error");
}
/*
fn is_placeable(&self, x: usize, y: usize, r: usize) -> bool {
let nt = flip_turn(self.turn.clone());
match self.board[y][x] {
PieceType::Null => {},
_ => return false,
};
let (iy, ix) = match r {
0 => (-1, -1), 1 => (-1, 0), 2 => (-1, 1),
3 => (0, -1), 4 => (0, 0), 5 => (0, 1),
6 => (1, -1), 7 => (1, 0), 8 => (1, 1),
_ => (0, 0),
};
let mut b = false;
let mut _y = y as isize;
let mut _x = x as isize;
loop {
_y += iy;
_x += ix;
if _y < 0 || _x < 0 {
return false;
}
if self.board[_y as usize][_x as usize] == nt {
b = true;
} else if b && self.board[_y as usize][_x as usize] == self.turn {
return true;
} else {
return false;
}
}
}
pub fn put(self, x: usize, y: usize) -> Result<Self> {
}
*/
pub fn continue_game(&self) -> bool {
let mut null = 0;
for y in &self.board {
for x in y {
match *x {
PieceType::Null => null += 1,
_ => {},
}
}
}
if null == 0 {
return false;
}
true
}
}
| ].push(PieceType::White);
} else if y | conditional_block |
reversi.rs |
use std::io::{Write, BufWriter};
static BOARD_SIZE: usize = 10; // 盤面のコマ+2
#[derive(Debug, Clone)]
pub enum PieceType {
Black,
White,
Sentinel,
Null,
}
fn flip_turn(t: PieceType) -> PieceType {
match t {
PieceType::Black => PieceType::White,
PieceType::White => PieceType::Black,
_ => PieceType::Null,
}
}
impl PartialEq for PieceType {
fn eq(&self, t: &PieceType) -> bool {
self = | ve(Debug, Clone)]
pub struct Reversi {
board: Vec<Vec<PieceType>>,
pub turn: PieceType,
}
impl Reversi {
pub fn new() -> Self {
let mut v: Vec<Vec<PieceType>> = Vec::new();
let half = (BOARD_SIZE - 2) / 2;
for y in 0..BOARD_SIZE {
v.push(Vec::new());
for x in 0..BOARD_SIZE {
if y == 0 || x == 0 ||
y == BOARD_SIZE - 1 || x == BOARD_SIZE - 1 {
v[y].push(PieceType::Sentinel);
} else if y == half && x == half ||
y == half + 1 && x == half + 1 {
v[y].push(PieceType::White);
} else if y == half && x == half + 1 ||
y == half + 1 && x == half {
v[y].push(PieceType::Black);
} else {
v[y].push(PieceType::Null);
}
}
}
Reversi {
board: v,
turn: PieceType::Black,
}
}
pub fn debug_board(&self) {
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock());
for _i in 0..BOARD_SIZE {
write!(w, "+-").expect("stdout Error");
}
writeln!(w, "+").expect("stdout Error");
for y in &self.board {
write!(w, "|").expect("stdout Error");
for x in y {
write!(w, "{}|", match *x {
PieceType::Black => "x",
PieceType::White => "o",
PieceType::Null => " ",
PieceType::Sentinel => "=",
//_ => "",
}).expect("stdout Error");
}
writeln!(w, "").expect("stdout Error");
for _i in 0..BOARD_SIZE {
write!(w, "+-").expect("stdout Error");
}
writeln!(w, "+").expect("stdout Error");
}
}
pub fn show_turn(&self) {
println!("turn: {}", match self.turn {
PieceType::Black => "Black",
PieceType::White => "White",
_ => "Something wrong.",
})
}
pub fn turn_change(self) -> Self {
Reversi {
board: self.board,
turn: flip_turn(self.turn),
}
}
pub fn show_score(&self) {
let mut black = 0;
let mut white = 0;
for y in &self.board {
for x in y {
match *x {
PieceType::White => white += 1,
PieceType::Black => black += 1,
_ => {},
};
}
}
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock());
writeln!(w, "+---------+").expect("stdout Error");
writeln!(w, "| Score |").expect("stdout Error");
writeln!(w, "+---------+").expect("stdout Error");
writeln!(w, "|Black|{:03}|", black).expect("stdout Error");
writeln!(w, "+-----+---+").expect("stdout Error");
writeln!(w, "|White|{:03}|", white).expect("stdout Error");
writeln!(w, "+-----+---+").expect("stdout Error");
}
/*
fn is_placeable(&self, x: usize, y: usize, r: usize) -> bool {
let nt = flip_turn(self.turn.clone());
match self.board[y][x] {
PieceType::Null => {},
_ => return false,
};
let (iy, ix) = match r {
0 => (-1, -1), 1 => (-1, 0), 2 => (-1, 1),
3 => (0, -1), 4 => (0, 0), 5 => (0, 1),
6 => (1, -1), 7 => (1, 0), 8 => (1, 1),
_ => (0, 0),
};
let mut b = false;
let mut _y = y as isize;
let mut _x = x as isize;
loop {
_y += iy;
_x += ix;
if _y < 0 || _x < 0 {
return false;
}
if self.board[_y as usize][_x as usize] == nt {
b = true;
} else if b && self.board[_y as usize][_x as usize] == self.turn {
return true;
} else {
return false;
}
}
}
pub fn put(self, x: usize, y: usize) -> Result<Self> {
}
*/
pub fn continue_game(&self) -> bool {
let mut null = 0;
for y in &self.board {
for x in y {
match *x {
PieceType::Null => null += 1,
_ => {},
}
}
}
if null == 0 {
return false;
}
true
}
}
| = t
}
}
#[deri | identifier_body |
reversi.rs |
use std::io::{Write, BufWriter};
static BOARD_SIZE: usize = 10; // 盤面のコマ+2
#[derive(Debug, Clone)]
pub enum PieceType {
Black,
White,
Sentinel,
Null,
}
fn flip_turn(t: PieceType) -> PieceType {
match t {
PieceType::Black => PieceType::White,
PieceType::White => PieceType::Black,
_ => PieceType::Null,
}
}
impl PartialEq for PieceType {
fn eq(&self, t: &PieceType) -> bool {
self == t
}
}
#[derive(Debug, Clone)]
pub struct Reversi {
| Vec<Vec<PieceType>>,
pub turn: PieceType,
}
impl Reversi {
pub fn new() -> Self {
let mut v: Vec<Vec<PieceType>> = Vec::new();
let half = (BOARD_SIZE - 2) / 2;
for y in 0..BOARD_SIZE {
v.push(Vec::new());
for x in 0..BOARD_SIZE {
if y == 0 || x == 0 ||
y == BOARD_SIZE - 1 || x == BOARD_SIZE - 1 {
v[y].push(PieceType::Sentinel);
} else if y == half && x == half ||
y == half + 1 && x == half + 1 {
v[y].push(PieceType::White);
} else if y == half && x == half + 1 ||
y == half + 1 && x == half {
v[y].push(PieceType::Black);
} else {
v[y].push(PieceType::Null);
}
}
}
Reversi {
board: v,
turn: PieceType::Black,
}
}
pub fn debug_board(&self) {
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock());
for _i in 0..BOARD_SIZE {
write!(w, "+-").expect("stdout Error");
}
writeln!(w, "+").expect("stdout Error");
for y in &self.board {
write!(w, "|").expect("stdout Error");
for x in y {
write!(w, "{}|", match *x {
PieceType::Black => "x",
PieceType::White => "o",
PieceType::Null => " ",
PieceType::Sentinel => "=",
//_ => "",
}).expect("stdout Error");
}
writeln!(w, "").expect("stdout Error");
for _i in 0..BOARD_SIZE {
write!(w, "+-").expect("stdout Error");
}
writeln!(w, "+").expect("stdout Error");
}
}
pub fn show_turn(&self) {
println!("turn: {}", match self.turn {
PieceType::Black => "Black",
PieceType::White => "White",
_ => "Something wrong.",
})
}
pub fn turn_change(self) -> Self {
Reversi {
board: self.board,
turn: flip_turn(self.turn),
}
}
pub fn show_score(&self) {
let mut black = 0;
let mut white = 0;
for y in &self.board {
for x in y {
match *x {
PieceType::White => white += 1,
PieceType::Black => black += 1,
_ => {},
};
}
}
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock());
writeln!(w, "+---------+").expect("stdout Error");
writeln!(w, "| Score |").expect("stdout Error");
writeln!(w, "+---------+").expect("stdout Error");
writeln!(w, "|Black|{:03}|", black).expect("stdout Error");
writeln!(w, "+-----+---+").expect("stdout Error");
writeln!(w, "|White|{:03}|", white).expect("stdout Error");
writeln!(w, "+-----+---+").expect("stdout Error");
}
/*
fn is_placeable(&self, x: usize, y: usize, r: usize) -> bool {
let nt = flip_turn(self.turn.clone());
match self.board[y][x] {
PieceType::Null => {},
_ => return false,
};
let (iy, ix) = match r {
0 => (-1, -1), 1 => (-1, 0), 2 => (-1, 1),
3 => (0, -1), 4 => (0, 0), 5 => (0, 1),
6 => (1, -1), 7 => (1, 0), 8 => (1, 1),
_ => (0, 0),
};
let mut b = false;
let mut _y = y as isize;
let mut _x = x as isize;
loop {
_y += iy;
_x += ix;
if _y < 0 || _x < 0 {
return false;
}
if self.board[_y as usize][_x as usize] == nt {
b = true;
} else if b && self.board[_y as usize][_x as usize] == self.turn {
return true;
} else {
return false;
}
}
}
pub fn put(self, x: usize, y: usize) -> Result<Self> {
}
*/
pub fn continue_game(&self) -> bool {
let mut null = 0;
for y in &self.board {
for x in y {
match *x {
PieceType::Null => null += 1,
_ => {},
}
}
}
if null == 0 {
return false;
}
true
}
}
| board: | identifier_name |
reversi.rs | use std::io::{Write, BufWriter};
static BOARD_SIZE: usize = 10; // 盤面のコマ+2
#[derive(Debug, Clone)]
pub enum PieceType {
Black,
White,
Sentinel,
Null,
}
fn flip_turn(t: PieceType) -> PieceType {
match t {
PieceType::Black => PieceType::White,
PieceType::White => PieceType::Black,
_ => PieceType::Null,
}
}
|
#[derive(Debug, Clone)]
pub struct Reversi {
board: Vec<Vec<PieceType>>,
pub turn: PieceType,
}
impl Reversi {
pub fn new() -> Self {
let mut v: Vec<Vec<PieceType>> = Vec::new();
let half = (BOARD_SIZE - 2) / 2;
for y in 0..BOARD_SIZE {
v.push(Vec::new());
for x in 0..BOARD_SIZE {
if y == 0 || x == 0 ||
y == BOARD_SIZE - 1 || x == BOARD_SIZE - 1 {
v[y].push(PieceType::Sentinel);
} else if y == half && x == half ||
y == half + 1 && x == half + 1 {
v[y].push(PieceType::White);
} else if y == half && x == half + 1 ||
y == half + 1 && x == half {
v[y].push(PieceType::Black);
} else {
v[y].push(PieceType::Null);
}
}
}
Reversi {
board: v,
turn: PieceType::Black,
}
}
pub fn debug_board(&self) {
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock());
for _i in 0..BOARD_SIZE {
write!(w, "+-").expect("stdout Error");
}
writeln!(w, "+").expect("stdout Error");
for y in &self.board {
write!(w, "|").expect("stdout Error");
for x in y {
write!(w, "{}|", match *x {
PieceType::Black => "x",
PieceType::White => "o",
PieceType::Null => " ",
PieceType::Sentinel => "=",
//_ => "",
}).expect("stdout Error");
}
writeln!(w, "").expect("stdout Error");
for _i in 0..BOARD_SIZE {
write!(w, "+-").expect("stdout Error");
}
writeln!(w, "+").expect("stdout Error");
}
}
pub fn show_turn(&self) {
println!("turn: {}", match self.turn {
PieceType::Black => "Black",
PieceType::White => "White",
_ => "Something wrong.",
})
}
pub fn turn_change(self) -> Self {
Reversi {
board: self.board,
turn: flip_turn(self.turn),
}
}
pub fn show_score(&self) {
let mut black = 0;
let mut white = 0;
for y in &self.board {
for x in y {
match *x {
PieceType::White => white += 1,
PieceType::Black => black += 1,
_ => {},
};
}
}
let w = super::std::io::stdout();
let mut w = BufWriter::new(w.lock());
writeln!(w, "+---------+").expect("stdout Error");
writeln!(w, "| Score |").expect("stdout Error");
writeln!(w, "+---------+").expect("stdout Error");
writeln!(w, "|Black|{:03}|", black).expect("stdout Error");
writeln!(w, "+-----+---+").expect("stdout Error");
writeln!(w, "|White|{:03}|", white).expect("stdout Error");
writeln!(w, "+-----+---+").expect("stdout Error");
}
/*
fn is_placeable(&self, x: usize, y: usize, r: usize) -> bool {
let nt = flip_turn(self.turn.clone());
match self.board[y][x] {
PieceType::Null => {},
_ => return false,
};
let (iy, ix) = match r {
0 => (-1, -1), 1 => (-1, 0), 2 => (-1, 1),
3 => (0, -1), 4 => (0, 0), 5 => (0, 1),
6 => (1, -1), 7 => (1, 0), 8 => (1, 1),
_ => (0, 0),
};
let mut b = false;
let mut _y = y as isize;
let mut _x = x as isize;
loop {
_y += iy;
_x += ix;
if _y < 0 || _x < 0 {
return false;
}
if self.board[_y as usize][_x as usize] == nt {
b = true;
} else if b && self.board[_y as usize][_x as usize] == self.turn {
return true;
} else {
return false;
}
}
}
pub fn put(self, x: usize, y: usize) -> Result<Self> {
}
*/
pub fn continue_game(&self) -> bool {
let mut null = 0;
for y in &self.board {
for x in y {
match *x {
PieceType::Null => null += 1,
_ => {},
}
}
}
if null == 0 {
return false;
}
true
}
} | impl PartialEq for PieceType {
fn eq(&self, t: &PieceType) -> bool {
self == t
}
} | random_line_split |
timecalc.js | true,
};
/*
* Custom jQuery function '$.timecalc()'.
*
* Example: $('#time-input').timecalc();
* Parsed time can be get with $('#time-input').timecalc('getHours');
*
* Example: $('#time-input').timecalc($('time-output-digits'));
* Parsed time is stored in the specified DOM element.
*/
$.fn.timecalc = function ( options ) {
var args = arguments;
if (options === undefined || typeof options === 'object' ) {
return this.each(function () {
// Only allow the plugin to be instantiated once,
// so we check that the element has no plugin instantiation yet
if (!$.data(this, 'plugin_timecalc')) {
// if it has no instance, create a new one,
// pass options to our plugin constructor,
// and store the plugin instance
// in the elements jQuery data object.
$.data(this, 'plugin_timecalc', new TimeCalculator( this, options ));
}
});
}
else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
// Cache the method call
// to make it possible
// to return a value
var returns;
this.each(function () {
var instance = $.data(this, 'plugin_timecalc');
// Tests that there's already a plugin-instance
// and checks that the requested public method exists
if (instance instanceof TimeCalculator && typeof instance[options] === 'function') {
// Call the method of our plugin instance,
// and pass it the supplied arguments.
returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
}
// Allow instances to be destroyed via the 'destroy' method
if (options === 'destroy') {
$.data(this, 'plugin_timecalc', null);
}
});
// If the earlier cached method
// gives a value back return the value,
// otherwise return this to preserve chainability.
return returns !== undefined ? returns : this;
}
}
$.timecalc = function (customInputString, options) {
// "stand-alone" version for parsing custom strings
if(customInputString) {
// this is not a jQuery collection / DOM-Element but a direct call to timecalc
var tempCalc,
method,
params;
if(options !== undefined) {
tempCalc = new TimeCalculator(false, options);
}
else {
tempCalc = new TimeCalculator(false);
}
return tempCalc.parseInput(customInputString);
}
else {
console.error("no input string to parse!");
return false;
}
}
/*
* constructor
*/
TimeCalculator = function (inputElement, options) {
this.$input = inputElement ? $(inputElement) : false;
this.$output = false;
this._settings = defaults;
// If we were given a jQuery object, we'll be using it as the output element.
if (options instanceof jQuery) {
this.$output = options;
}
// Otherwise some kind of settings must have been given...
else {
this._settings = $.extend( {}, defaults, options);
}
this.total = new Time();
this.init();
};
TimeCalculator.prototype = {
/*
* Init the plugin with a keyup event.
*/
init : function () {
if(this.$input) {
// Parse input on key up.
this.$input.on("keyup", $.proxy(function () {
this.parseInput();
this.update();
}, this));
}
},
/*
* Sets a value, after initialization.
*/
option: function (name, value) {
if ( value === undefined ) {
// getter
return this._settings[name];
}
else {
// setter
this._settings[name] = value;
return value;
}
},
/**
* This function parses the user's input and adds it to a time object
*
* Input will be tried to be parsed in the following order:
* 1. Values followed by name/description
* 2. Decimal representation of hours (e.g. dot- or comma-seperated)
* 3. Colon-seperated time representation (hh:mm:ss)
*
* Accepts a custom input string parameter, which can be parsed instead and independantly.
*/
parseInput : function ( customInputString ) {
var input = customInputString ? customInputString : (this.$input ? this.$input.val() : ""),
lines = input.split( this._settings['time-delimiter'] ),
hours,
mins,
secs,
i;
// reset _all_ previous calculated times.
this.total = new Time();
// iterate over lines , @todo: maybe replace with foreach
for (i = 0; i < lines.length; i++) {
hours = this.total.getHours(),
mins = this.total.getMinutes(),
secs = this.total.getSeconds();
// if values are followed by description:
if (lines[i].indexOf("hour") !== -1 || lines[i].indexOf("minute") !== -1 || lines[i].indexOf("second") !== -1) {
if(this._settings['natlang-support']) {
var stringHasRightFormat,
match,
parts,
tmpLine = lines[i],
partIdx = 0;
do {
// Search for (first) number
match = tmpLine.match(/[0-9]/g);
parts = tmpLine.split(' ');
stringHasRightFormat = match != null && partIdx + 1 < parts.length; | var currentTimeUnit = parts[partIdx + 1].toString().toLowerCase();
switch(currentTimeUnit) {
case "hour":
case "hours":
hours = parseInt(currentNumber) + hours;
break;
case "minute":
case "minutes":
mins = parseInt(currentNumber) + mins;
break;
case "second":
case "seconds":
secs = parseInt(currentNumber) + secs;
break;
}
partIdx += 2;
}
}
while (stringHasRightFormat);
}
}
// if line has comma or dot, we treat it as hours in decimal representation.
else if (lines[i].indexOf(",") !== -1 || lines[i].indexOf(".") !== -1) {
var inputNumber = parseFloat(lines[i].replace(",", "."));
mins = Math.round(inputNumber*60) + mins;
}
// try seperating by colon(s)
else {
var tmpTime = lines[i].split(":");
hours = parseInt(tmpTime[0] ? tmpTime[0] : 0) + hours;
mins = parseInt(tmpTime[1] ? tmpTime[1] : 0) + mins ;
secs = parseInt(tmpTime[2] ? tmpTime[2] : 0) + secs;
}
// add/set updated time
this.total.setTime(hours, mins, secs);
}
// return if custom input was given
if(typeof customInputString !== 'undefined') {
if(this._settings['return-formatted']) {
return this.getFormattedTime();
}
else {
return this.getTotalTime();
}
}
},
/*
* Fires 'timecalcupdate' event and outputs time to output element (if set).
*/
update : function () {
var formattedTime;
// switch over different types of (user choses) output-formats.
formattedTime = this.getFormattedTime();
if (this.$output) {
// write time to output element.
if($output.is('input, select, textarea')) {
this.$output.val(formattedTime);
}
else {
this.$output.text(formattedTime);
}
}
// fire the 'timecalcupdate' event.
this.$input.trigger({
type: 'timecalcupdate',
hours: this.total.getHours(),
minutes: this.total.getMinutes(),
seconds: this.total.getSeconds(),
formattedTime: formattedTime,
});
},
getFormattedTime : function() {
return this.total.getHours() + ':' + this.total.getMinutes() + ':' + this.total.getSeconds();
},
getTotalTime : function() {
return this.total;
}
};
/**
* Represents time.
* This object can hold hours, minutes and seconds.
* It additionaly provides simple arrangement of it's time values.
* @constructor
*/
Time = function () {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
}
Time.prototype.getHours = function () {
return this.hours;
};
Time.prototype.getMinutes = function () {
return this.minutes;
};
Time.prototype.getSeconds = function () {
return this.seconds;
};
Time.prototype.setHours = function (hours) {
this.hours = hours;
};
Time.prototype.setMinutes = function (mins) {
this.minutes = mins;
this.arrangeTime();
};
Time.prototype.setSeconds = function (secs) {
this.seconds = secs;
this.arrangeTime();
};
| if (stringHasRightFormat) {
var currentNumber = parts[partIdx]; | random_line_split |
timecalc.js | true,
};
/*
* Custom jQuery function '$.timecalc()'.
*
* Example: $('#time-input').timecalc();
* Parsed time can be get with $('#time-input').timecalc('getHours');
*
* Example: $('#time-input').timecalc($('time-output-digits'));
* Parsed time is stored in the specified DOM element.
*/
$.fn.timecalc = function ( options ) {
var args = arguments;
if (options === undefined || typeof options === 'object' ) {
return this.each(function () {
// Only allow the plugin to be instantiated once,
// so we check that the element has no plugin instantiation yet
if (!$.data(this, 'plugin_timecalc')) {
// if it has no instance, create a new one,
// pass options to our plugin constructor,
// and store the plugin instance
// in the elements jQuery data object.
$.data(this, 'plugin_timecalc', new TimeCalculator( this, options ));
}
});
}
else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
// Cache the method call
// to make it possible
// to return a value
var returns;
this.each(function () {
var instance = $.data(this, 'plugin_timecalc');
// Tests that there's already a plugin-instance
// and checks that the requested public method exists
if (instance instanceof TimeCalculator && typeof instance[options] === 'function') {
// Call the method of our plugin instance,
// and pass it the supplied arguments.
returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
}
// Allow instances to be destroyed via the 'destroy' method
if (options === 'destroy') {
$.data(this, 'plugin_timecalc', null);
}
});
// If the earlier cached method
// gives a value back return the value,
// otherwise return this to preserve chainability.
return returns !== undefined ? returns : this;
}
}
$.timecalc = function (customInputString, options) {
// "stand-alone" version for parsing custom strings
if(customInputString) {
// this is not a jQuery collection / DOM-Element but a direct call to timecalc
var tempCalc,
method,
params;
if(options !== undefined) {
tempCalc = new TimeCalculator(false, options);
}
else {
tempCalc = new TimeCalculator(false);
}
return tempCalc.parseInput(customInputString);
}
else {
console.error("no input string to parse!");
return false;
}
}
/*
* constructor
*/
TimeCalculator = function (inputElement, options) {
this.$input = inputElement ? $(inputElement) : false;
this.$output = false;
this._settings = defaults;
// If we were given a jQuery object, we'll be using it as the output element.
if (options instanceof jQuery) {
this.$output = options;
}
// Otherwise some kind of settings must have been given...
else {
this._settings = $.extend( {}, defaults, options);
}
this.total = new Time();
this.init();
};
TimeCalculator.prototype = {
/*
* Init the plugin with a keyup event.
*/
init : function () {
if(this.$input) {
// Parse input on key up.
this.$input.on("keyup", $.proxy(function () {
this.parseInput();
this.update();
}, this));
}
},
/*
* Sets a value, after initialization.
*/
option: function (name, value) {
if ( value === undefined ) {
// getter
return this._settings[name];
}
else {
// setter
this._settings[name] = value;
return value;
}
},
/**
* This function parses the user's input and adds it to a time object
*
* Input will be tried to be parsed in the following order:
* 1. Values followed by name/description
* 2. Decimal representation of hours (e.g. dot- or comma-seperated)
* 3. Colon-seperated time representation (hh:mm:ss)
*
* Accepts a custom input string parameter, which can be parsed instead and independantly.
*/
parseInput : function ( customInputString ) {
var input = customInputString ? customInputString : (this.$input ? this.$input.val() : ""),
lines = input.split( this._settings['time-delimiter'] ),
hours,
mins,
secs,
i;
// reset _all_ previous calculated times.
this.total = new Time();
// iterate over lines , @todo: maybe replace with foreach
for (i = 0; i < lines.length; i++) {
hours = this.total.getHours(),
mins = this.total.getMinutes(),
secs = this.total.getSeconds();
// if values are followed by description:
if (lines[i].indexOf("hour") !== -1 || lines[i].indexOf("minute") !== -1 || lines[i].indexOf("second") !== -1) {
if(this._settings['natlang-support']) | case "minute":
case "minutes":
mins = parseInt(currentNumber) + mins;
break;
case "second":
case "seconds":
secs = parseInt(currentNumber) + secs;
break;
}
partIdx += 2;
}
}
while (stringHasRightFormat);
}
}
// if line has comma or dot, we treat it as hours in decimal representation.
else if (lines[i].indexOf(",") !== -1 || lines[i].indexOf(".") !== -1) {
var inputNumber = parseFloat(lines[i].replace(",", "."));
mins = Math.round(inputNumber*60) + mins;
}
// try seperating by colon(s)
else {
var tmpTime = lines[i].split(":");
hours = parseInt(tmpTime[0] ? tmpTime[0] : 0) + hours;
mins = parseInt(tmpTime[1] ? tmpTime[1] : 0) + mins ;
secs = parseInt(tmpTime[2] ? tmpTime[2] : 0) + secs;
}
// add/set updated time
this.total.setTime(hours, mins, secs);
}
// return if custom input was given
if(typeof customInputString !== 'undefined') {
if(this._settings['return-formatted']) {
return this.getFormattedTime();
}
else {
return this.getTotalTime();
}
}
},
/*
* Fires 'timecalcupdate' event and outputs time to output element (if set).
*/
update : function () {
var formattedTime;
// switch over different types of (user choses) output-formats.
formattedTime = this.getFormattedTime();
if (this.$output) {
// write time to output element.
if($output.is('input, select, textarea')) {
this.$output.val(formattedTime);
}
else {
this.$output.text(formattedTime);
}
}
// fire the 'timecalcupdate' event.
this.$input.trigger({
type: 'timecalcupdate',
hours: this.total.getHours(),
minutes: this.total.getMinutes(),
seconds: this.total.getSeconds(),
formattedTime: formattedTime,
});
},
getFormattedTime : function() {
return this.total.getHours() + ':' + this.total.getMinutes() + ':' + this.total.getSeconds();
},
getTotalTime : function() {
return this.total;
}
};
/**
* Represents time.
* This object can hold hours, minutes and seconds.
* It additionaly provides simple arrangement of it's time values.
* @constructor
*/
Time = function () {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
}
Time.prototype.getHours = function () {
return this.hours;
};
Time.prototype.getMinutes = function () {
return this.minutes;
};
Time.prototype.getSeconds = function () {
return this.seconds;
};
Time.prototype.setHours = function (hours) {
this.hours = hours;
};
Time.prototype.setMinutes = function (mins) {
this.minutes = mins;
this.arrangeTime();
};
Time.prototype.setSeconds = function (secs) {
this.seconds = secs;
this.arrangeTime();
}; | {
var stringHasRightFormat,
match,
parts,
tmpLine = lines[i],
partIdx = 0;
do {
// Search for (first) number
match = tmpLine.match(/[0-9]/g);
parts = tmpLine.split(' ');
stringHasRightFormat = match != null && partIdx + 1 < parts.length;
if (stringHasRightFormat) {
var currentNumber = parts[partIdx];
var currentTimeUnit = parts[partIdx + 1].toString().toLowerCase();
switch(currentTimeUnit) {
case "hour":
case "hours":
hours = parseInt(currentNumber) + hours;
break; | conditional_block |
Resume.js | import React from 'react';
const Resume = () => {
const content = (
<span>
<h2>Curriculum Vitae</h2>
<p>
Sed quis mattis turpis. Ut vitae finibus sem. Donec scelerisque nec nisi non malesuada. Praesent mattis | finibus. Nunc non mi tincidunt, luctus purus tempus.
<br/><br/>
Vitae dignissim ante est vel erat. Maecenas auctor dolor vitae egestas aliquam. Morbi suscipit, est id malesuada
viverra, ex mauris finibus dolor, ac tincidunt justo dui auctor mi. Nunc scelerisque sapien eget tempus
fermentum. Mauris non luctus sem. Fusce et blandit odio, at tincidunt risus.
Praesent facilisis ipsum ligula, ut feugiat eros viverra a. Duis volutpat at augue non pharetra.
<br/><br/>
Morbi sed arcu vitae ligula porta gravida. Integer vel ex neque. Etiam quis elementum magna.
Duis nec tincidunt enim.
</p>
</span>
);
return content;
};
Resume.displayName = 'BlaseStuff';
export default Resume; | lacus quis diam imperdiet rhoncus. Ut porta efficitur magna, quis pretium magna. Nam venenatis convallis | random_line_split |
output_prn.py | # Copyright (C) 2012 Vivek Haldar
#
# Take in a dict containing fetched RSS data, and output to printable files in
# the current directory.
#
# Dict looks like:
# feed_title -> [list of articles]
# each article has (title, body).
#
# Author: Vivek Haldar <vh@vivekhaldar.com>
import codecs
import escpos
from datetime import datetime
import textwrap
import output
class OutputPrn(output.Output):
def output(self):
articles = self._articles
for f in articles:
| prn = escpos.Escpos('%s.prn' % f.replace('/', '_'))
for a in articles[f]:
title, body = a
# Cut body down to 100 words.
short_body = ' '.join(body.split()[:100])
prn.bigtext(f + '\n')
prn.bigtext(textwrap.fill(title, 32) + '\n')
prn.text(textwrap.fill(body, 32))
prn.text('\n\n\n')
prn.flush() | conditional_block |
|
output_prn.py | # Copyright (C) 2012 Vivek Haldar
#
# Take in a dict containing fetched RSS data, and output to printable files in
# the current directory.
#
# Dict looks like:
# feed_title -> [list of articles]
# each article has (title, body).
#
# Author: Vivek Haldar <vh@vivekhaldar.com>
import codecs
import escpos
from datetime import datetime
import textwrap
import output
class OutputPrn(output.Output):
def output(self):
| articles = self._articles
for f in articles:
prn = escpos.Escpos('%s.prn' % f.replace('/', '_'))
for a in articles[f]:
title, body = a
# Cut body down to 100 words.
short_body = ' '.join(body.split()[:100])
prn.bigtext(f + '\n')
prn.bigtext(textwrap.fill(title, 32) + '\n')
prn.text(textwrap.fill(body, 32))
prn.text('\n\n\n')
prn.flush() | identifier_body |
|
output_prn.py | # Copyright (C) 2012 Vivek Haldar
#
# Take in a dict containing fetched RSS data, and output to printable files in
# the current directory.
#
# Dict looks like:
# feed_title -> [list of articles]
# each article has (title, body).
#
# Author: Vivek Haldar <vh@vivekhaldar.com>
import codecs
import escpos
from datetime import datetime
import textwrap
import output
class OutputPrn(output.Output):
def output(self):
articles = self._articles
for f in articles:
prn = escpos.Escpos('%s.prn' % f.replace('/', '_')) | prn.bigtext(textwrap.fill(title, 32) + '\n')
prn.text(textwrap.fill(body, 32))
prn.text('\n\n\n')
prn.flush() | for a in articles[f]:
title, body = a
# Cut body down to 100 words.
short_body = ' '.join(body.split()[:100])
prn.bigtext(f + '\n') | random_line_split |
output_prn.py | # Copyright (C) 2012 Vivek Haldar
#
# Take in a dict containing fetched RSS data, and output to printable files in
# the current directory.
#
# Dict looks like:
# feed_title -> [list of articles]
# each article has (title, body).
#
# Author: Vivek Haldar <vh@vivekhaldar.com>
import codecs
import escpos
from datetime import datetime
import textwrap
import output
class | (output.Output):
def output(self):
articles = self._articles
for f in articles:
prn = escpos.Escpos('%s.prn' % f.replace('/', '_'))
for a in articles[f]:
title, body = a
# Cut body down to 100 words.
short_body = ' '.join(body.split()[:100])
prn.bigtext(f + '\n')
prn.bigtext(textwrap.fill(title, 32) + '\n')
prn.text(textwrap.fill(body, 32))
prn.text('\n\n\n')
prn.flush()
| OutputPrn | identifier_name |
index.js | 'use strict';
let router = require('koa-router')();
let navigation = require('../controllers/navigation.js');
function | () {
return function* (next) {
console.log('-----', this.user , '---- ', this.state);
if (this.state.user || this.user) {
yield next;
} else {
this.throw(401, 'Must be logged in to see this!');
}
}
};
//navigations
router.get('/', navigation.home);
router.get('/about', navigation.about);
router.get('/profile', navigation.profile);
router.get('/karaoke', navigation.karaoke);
router.get('/login', navigation.login);
router.get('/logout', navigation.logout);
router.get('/signup', navigation.signup);
router.post('/authenticate', navigation.authenticate);
router.post('/register', navigation.register);
//comments
let comments = require('../controllers/comments.js');
router.get('/comments', comments.list);
router.post('/comments', comments.add);
router.get('/comments/:id', comments.show);
router.put('/comments/:id', comments.edit);
router.del('/comments/:id', comments.delete);
//rooms
let rooms = require('../controllers/rooms.js');
router.get('/rooms', rooms.list);
router.post('/rooms', rooms.addwithMedia);
router.get('/rooms/:id', rooms.show);
router.delete('/rooms/:id', rooms.delete);
//upload files (not used)
var media = require('../controllers/media.js');
router.post('/uploads', media.uploadImage);
module.exports = router; | isAuth | identifier_name |
index.js | 'use strict';
let router = require('koa-router')();
let navigation = require('../controllers/navigation.js');
function isAuth() {
return function* (next) {
console.log('-----', this.user , '---- ', this.state);
if (this.state.user || this.user) | else {
this.throw(401, 'Must be logged in to see this!');
}
}
};
//navigations
router.get('/', navigation.home);
router.get('/about', navigation.about);
router.get('/profile', navigation.profile);
router.get('/karaoke', navigation.karaoke);
router.get('/login', navigation.login);
router.get('/logout', navigation.logout);
router.get('/signup', navigation.signup);
router.post('/authenticate', navigation.authenticate);
router.post('/register', navigation.register);
//comments
let comments = require('../controllers/comments.js');
router.get('/comments', comments.list);
router.post('/comments', comments.add);
router.get('/comments/:id', comments.show);
router.put('/comments/:id', comments.edit);
router.del('/comments/:id', comments.delete);
//rooms
let rooms = require('../controllers/rooms.js');
router.get('/rooms', rooms.list);
router.post('/rooms', rooms.addwithMedia);
router.get('/rooms/:id', rooms.show);
router.delete('/rooms/:id', rooms.delete);
//upload files (not used)
var media = require('../controllers/media.js');
router.post('/uploads', media.uploadImage);
module.exports = router; | {
yield next;
} | conditional_block |
index.js | 'use strict';
let router = require('koa-router')();
let navigation = require('../controllers/navigation.js');
function isAuth() {
return function* (next) {
console.log('-----', this.user , '---- ', this.state);
if (this.state.user || this.user) {
yield next;
} else {
this.throw(401, 'Must be logged in to see this!');
}
}
};
//navigations | router.get('/', navigation.home);
router.get('/about', navigation.about);
router.get('/profile', navigation.profile);
router.get('/karaoke', navigation.karaoke);
router.get('/login', navigation.login);
router.get('/logout', navigation.logout);
router.get('/signup', navigation.signup);
router.post('/authenticate', navigation.authenticate);
router.post('/register', navigation.register);
//comments
let comments = require('../controllers/comments.js');
router.get('/comments', comments.list);
router.post('/comments', comments.add);
router.get('/comments/:id', comments.show);
router.put('/comments/:id', comments.edit);
router.del('/comments/:id', comments.delete);
//rooms
let rooms = require('../controllers/rooms.js');
router.get('/rooms', rooms.list);
router.post('/rooms', rooms.addwithMedia);
router.get('/rooms/:id', rooms.show);
router.delete('/rooms/:id', rooms.delete);
//upload files (not used)
var media = require('../controllers/media.js');
router.post('/uploads', media.uploadImage);
module.exports = router; | random_line_split |
|
index.js | 'use strict';
let router = require('koa-router')();
let navigation = require('../controllers/navigation.js');
function isAuth() | ;
//navigations
router.get('/', navigation.home);
router.get('/about', navigation.about);
router.get('/profile', navigation.profile);
router.get('/karaoke', navigation.karaoke);
router.get('/login', navigation.login);
router.get('/logout', navigation.logout);
router.get('/signup', navigation.signup);
router.post('/authenticate', navigation.authenticate);
router.post('/register', navigation.register);
//comments
let comments = require('../controllers/comments.js');
router.get('/comments', comments.list);
router.post('/comments', comments.add);
router.get('/comments/:id', comments.show);
router.put('/comments/:id', comments.edit);
router.del('/comments/:id', comments.delete);
//rooms
let rooms = require('../controllers/rooms.js');
router.get('/rooms', rooms.list);
router.post('/rooms', rooms.addwithMedia);
router.get('/rooms/:id', rooms.show);
router.delete('/rooms/:id', rooms.delete);
//upload files (not used)
var media = require('../controllers/media.js');
router.post('/uploads', media.uploadImage);
module.exports = router; | {
return function* (next) {
console.log('-----', this.user , '---- ', this.state);
if (this.state.user || this.user) {
yield next;
} else {
this.throw(401, 'Must be logged in to see this!');
}
}
} | identifier_body |
test_commands.py | _make_scalp_surfaces, mne_maxfilter,
mne_report, mne_surf2bem, mne_watershed_bem,
mne_compare_fiff, mne_flash_bem, mne_show_fiff,
mne_show_info)
from mne.datasets import testing, sample
from mne.io import read_raw_fif
from mne.utils import (run_tests_if_main, _TempDir, requires_mne, requires_PIL,
requires_mayavi, requires_tvtk, requires_freesurfer,
ArgvSetter, slow_test, ultra_slow_test)
base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')
subjects_dir = op.join(testing.data_path(download=False), 'subjects')
warnings.simplefilter('always')
def check_usage(module, force_help=False):
"""Helper to ensure we print usage"""
args = ('--help',) if force_help else ()
with ArgvSetter(args) as out:
try:
module.run()
except SystemExit:
pass
assert_true('Usage: ' in out.stdout.getvalue())
@slow_test
def test_browse_raw():
"""Test mne browse_raw."""
check_usage(mne_browse_raw)
def | ():
"""Test mne bti2fiff."""
check_usage(mne_bti2fiff)
def test_compare_fiff():
"""Test mne compare_fiff."""
check_usage(mne_compare_fiff)
def test_show_fiff():
"""Test mne compare_fiff."""
check_usage(mne_show_fiff)
with ArgvSetter((raw_fname,)):
mne_show_fiff.run()
@requires_mne
def test_clean_eog_ecg():
"""Test mne clean_eog_ecg."""
check_usage(mne_clean_eog_ecg)
tempdir = _TempDir()
raw = concatenate_raws([read_raw_fif(f)
for f in [raw_fname, raw_fname, raw_fname]])
raw.info['bads'] = ['MEG 2443']
use_fname = op.join(tempdir, op.basename(raw_fname))
raw.save(use_fname)
with ArgvSetter(('-i', use_fname, '--quiet')):
mne_clean_eog_ecg.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 2) # two projs
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 3) # raw plus two projs
@slow_test
def test_compute_proj_ecg_eog():
"""Test mne compute_proj_ecg/eog."""
for fun in (mne_compute_proj_ecg, mne_compute_proj_eog):
check_usage(fun)
tempdir = _TempDir()
use_fname = op.join(tempdir, op.basename(raw_fname))
bad_fname = op.join(tempdir, 'bads.txt')
with open(bad_fname, 'w') as fid:
fid.write('MEG 2443\n')
shutil.copyfile(raw_fname, use_fname)
with ArgvSetter(('-i', use_fname, '--bad=' + bad_fname,
'--rej-eeg', '150')):
fun.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 1)
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 1)
def test_coreg():
"""Test mne coreg."""
assert_true(hasattr(mne_coreg, 'run'))
def test_kit2fiff():
"""Test mne kit2fiff."""
# Can't check
check_usage(mne_kit2fiff, force_help=True)
@requires_tvtk
@testing.requires_testing_data
def test_make_scalp_surfaces():
"""Test mne make_scalp_surfaces."""
check_usage(mne_make_scalp_surfaces)
# Copy necessary files to avoid FreeSurfer call
tempdir = _TempDir()
surf_path = op.join(subjects_dir, 'sample', 'surf')
surf_path_new = op.join(tempdir, 'sample', 'surf')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(surf_path_new)
subj_dir = op.join(tempdir, 'sample', 'bem')
os.mkdir(subj_dir)
shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new)
orig_fs = os.getenv('FREESURFER_HOME', None)
if orig_fs is not None:
del os.environ['FREESURFER_HOME']
cmd = ('-s', 'sample', '--subjects-dir', tempdir)
os.environ['_MNE_TESTING_SCALP'] = 'true'
dense_fname = op.join(subj_dir, 'sample-head-dense.fif')
medium_fname = op.join(subj_dir, 'sample-head-medium.fif')
try:
with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
assert_raises(RuntimeError, mne_make_scalp_surfaces.run)
os.environ['FREESURFER_HOME'] = tempdir # don't actually use it
mne_make_scalp_surfaces.run()
assert_true(op.isfile(dense_fname))
assert_true(op.isfile(medium_fname))
assert_raises(IOError, mne_make_scalp_surfaces.run) # no overwrite
finally:
if orig_fs is not None:
os.environ['FREESURFER_HOME'] = orig_fs
else:
del os.environ['FREESURFER_HOME']
del os.environ['_MNE_TESTING_SCALP']
# actually check the outputs
head_py = read_bem_surfaces(dense_fname)
assert_equal(len(head_py), 1)
head_py = head_py[0]
head_c = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem',
'sample-head-dense.fif'))[0]
assert_allclose(head_py['rr'], head_c['rr'])
def test_maxfilter():
"""Test mne maxfilter."""
check_usage(mne_maxfilter)
with ArgvSetter(('-i', raw_fname, '--st', '--movecomp', '--linefreq', '60',
'--trans', raw_fname)) as out:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
os.environ['_MNE_MAXFILTER_TEST'] = 'true'
try:
mne_maxfilter.run()
finally:
del os.environ['_MNE_MAXFILTER_TEST']
assert_true(len(w) == 1)
for check in ('maxfilter', '-trans', '-movecomp'):
assert_true(check in out.stdout.getvalue(), check)
@slow_test
@requires_mayavi
@requires_PIL
@testing.requires_testing_data
def test_report():
"""Test mne report."""
check_usage(mne_report)
tempdir = _TempDir()
use_fname = op.join(tempdir, op.basename(raw_fname))
shutil.copyfile(raw_fname, use_fname)
with ArgvSetter(('-p', tempdir, '-i', use_fname, '-d', subjects_dir,
'-s', 'sample', '--no-browser', '-m', '30')):
mne_report.run()
fnames = glob.glob(op.join(tempdir, '*.html'))
assert_true(len(fnames) == 1)
def test_surf2bem():
"""Test mne surf2bem."""
check_usage(mne_surf2bem)
@ultra_slow_test
@requires_freesurfer
@testing.requires_testing_data
def test_watershed_bem():
"""Test mne watershed bem."""
check_usage(mne_watershed_bem)
# Copy necessary files to tempdir
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', 'mri')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(mridata_path_new)
if op.exists(op.join(mridata_path, 'T1')):
shutil.copytree(op.join(mridata_path, 'T1'), op.join(mridata_path_new,
'T1'))
if op.exists(op.join(mridata_path, 'T1.mgz')):
shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
op.join(mridata_path_new, 'T1.mgz'))
with ArgvSetter(('-d', tempdir, '-s', 'sample', '-o'),
disable_stdout=False, disable_stderr=False):
mne_watershed_bem.run()
@ultra_slow_test
@requires_freesurfer
@sample.requires_sample_data
def test_flash_bem():
"""Test mne flash_bem."""
check_usage(mne_flash_bem, force_help=True)
# Using the sample dataset
subjects_dir = op.join(sample.data_path(download=False), 'subjects')
# Copy necessary files to tempdir
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', ' | test_bti2fiff | identifier_name |
test_commands.py | _make_scalp_surfaces, mne_maxfilter,
mne_report, mne_surf2bem, mne_watershed_bem,
mne_compare_fiff, mne_flash_bem, mne_show_fiff,
mne_show_info)
from mne.datasets import testing, sample
from mne.io import read_raw_fif
from mne.utils import (run_tests_if_main, _TempDir, requires_mne, requires_PIL,
requires_mayavi, requires_tvtk, requires_freesurfer,
ArgvSetter, slow_test, ultra_slow_test)
base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')
subjects_dir = op.join(testing.data_path(download=False), 'subjects')
warnings.simplefilter('always')
def check_usage(module, force_help=False):
"""Helper to ensure we print usage"""
args = ('--help',) if force_help else ()
with ArgvSetter(args) as out:
try:
module.run()
except SystemExit:
pass
assert_true('Usage: ' in out.stdout.getvalue())
@slow_test
def test_browse_raw():
"""Test mne browse_raw."""
check_usage(mne_browse_raw)
def test_bti2fiff():
"""Test mne bti2fiff."""
check_usage(mne_bti2fiff)
def test_compare_fiff():
"""Test mne compare_fiff."""
check_usage(mne_compare_fiff)
def test_show_fiff():
"""Test mne compare_fiff."""
check_usage(mne_show_fiff)
with ArgvSetter((raw_fname,)):
mne_show_fiff.run()
@requires_mne
def test_clean_eog_ecg():
"""Test mne clean_eog_ecg."""
check_usage(mne_clean_eog_ecg)
tempdir = _TempDir()
raw = concatenate_raws([read_raw_fif(f)
for f in [raw_fname, raw_fname, raw_fname]])
raw.info['bads'] = ['MEG 2443']
use_fname = op.join(tempdir, op.basename(raw_fname))
raw.save(use_fname)
with ArgvSetter(('-i', use_fname, '--quiet')):
mne_clean_eog_ecg.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 2) # two projs
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 3) # raw plus two projs
@slow_test
def test_compute_proj_ecg_eog():
"""Test mne compute_proj_ecg/eog."""
for fun in (mne_compute_proj_ecg, mne_compute_proj_eog):
check_usage(fun)
tempdir = _TempDir()
use_fname = op.join(tempdir, op.basename(raw_fname))
bad_fname = op.join(tempdir, 'bads.txt')
with open(bad_fname, 'w') as fid:
fid.write('MEG 2443\n')
shutil.copyfile(raw_fname, use_fname)
with ArgvSetter(('-i', use_fname, '--bad=' + bad_fname,
'--rej-eeg', '150')):
fun.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 1)
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 1)
def test_coreg():
"""Test mne coreg."""
assert_true(hasattr(mne_coreg, 'run'))
def test_kit2fiff():
"""Test mne kit2fiff."""
# Can't check
check_usage(mne_kit2fiff, force_help=True)
@requires_tvtk
@testing.requires_testing_data
def test_make_scalp_surfaces():
"""Test mne make_scalp_surfaces."""
check_usage(mne_make_scalp_surfaces)
# Copy necessary files to avoid FreeSurfer call
tempdir = _TempDir()
surf_path = op.join(subjects_dir, 'sample', 'surf')
surf_path_new = op.join(tempdir, 'sample', 'surf')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(surf_path_new)
subj_dir = op.join(tempdir, 'sample', 'bem')
os.mkdir(subj_dir)
shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new)
orig_fs = os.getenv('FREESURFER_HOME', None)
if orig_fs is not None:
del os.environ['FREESURFER_HOME']
cmd = ('-s', 'sample', '--subjects-dir', tempdir)
os.environ['_MNE_TESTING_SCALP'] = 'true'
dense_fname = op.join(subj_dir, 'sample-head-dense.fif')
medium_fname = op.join(subj_dir, 'sample-head-medium.fif')
try:
with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
assert_raises(RuntimeError, mne_make_scalp_surfaces.run)
os.environ['FREESURFER_HOME'] = tempdir # don't actually use it
mne_make_scalp_surfaces.run()
assert_true(op.isfile(dense_fname))
assert_true(op.isfile(medium_fname))
assert_raises(IOError, mne_make_scalp_surfaces.run) # no overwrite
finally:
if orig_fs is not None:
os.environ['FREESURFER_HOME'] = orig_fs
else:
del os.environ['FREESURFER_HOME']
del os.environ['_MNE_TESTING_SCALP']
# actually check the outputs
head_py = read_bem_surfaces(dense_fname)
assert_equal(len(head_py), 1)
head_py = head_py[0]
head_c = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem',
'sample-head-dense.fif'))[0]
assert_allclose(head_py['rr'], head_c['rr'])
def test_maxfilter():
"""Test mne maxfilter."""
check_usage(mne_maxfilter)
with ArgvSetter(('-i', raw_fname, '--st', '--movecomp', '--linefreq', '60',
'--trans', raw_fname)) as out:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
os.environ['_MNE_MAXFILTER_TEST'] = 'true'
try:
mne_maxfilter.run()
finally:
del os.environ['_MNE_MAXFILTER_TEST']
assert_true(len(w) == 1)
for check in ('maxfilter', '-trans', '-movecomp'):
assert_true(check in out.stdout.getvalue(), check)
@slow_test
@requires_mayavi
@requires_PIL
@testing.requires_testing_data
def test_report():
|
def test_surf2bem():
"""Test mne surf2bem."""
check_usage(mne_surf2bem)
@ultra_slow_test
@requires_freesurfer
@testing.requires_testing_data
def test_watershed_bem():
"""Test mne watershed bem."""
check_usage(mne_watershed_bem)
# Copy necessary files to tempdir
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', 'mri')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(mridata_path_new)
if op.exists(op.join(mridata_path, 'T1')):
shutil.copytree(op.join(mridata_path, 'T1'), op.join(mridata_path_new,
'T1'))
if op.exists(op.join(mridata_path, 'T1.mgz')):
shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
op.join(mridata_path_new, 'T1.mgz'))
with ArgvSetter(('-d', tempdir, '-s', 'sample', '-o'),
disable_stdout=False, disable_stderr=False):
mne_watershed_bem.run()
@ultra_slow_test
@requires_freesurfer
@sample.requires_sample_data
def test_flash_bem():
"""Test mne flash_bem."""
check_usage(mne_flash_bem, force_help=True)
# Using the sample dataset
subjects_dir = op.join(sample.data_path(download=False), 'subjects')
# Copy necessary files to tempdir
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', ' | """Test mne report."""
check_usage(mne_report)
tempdir = _TempDir()
use_fname = op.join(tempdir, op.basename(raw_fname))
shutil.copyfile(raw_fname, use_fname)
with ArgvSetter(('-p', tempdir, '-i', use_fname, '-d', subjects_dir,
'-s', 'sample', '--no-browser', '-m', '30')):
mne_report.run()
fnames = glob.glob(op.join(tempdir, '*.html'))
assert_true(len(fnames) == 1) | identifier_body |
test_commands.py | _make_scalp_surfaces, mne_maxfilter,
mne_report, mne_surf2bem, mne_watershed_bem,
mne_compare_fiff, mne_flash_bem, mne_show_fiff,
mne_show_info)
from mne.datasets import testing, sample
from mne.io import read_raw_fif
from mne.utils import (run_tests_if_main, _TempDir, requires_mne, requires_PIL,
requires_mayavi, requires_tvtk, requires_freesurfer,
ArgvSetter, slow_test, ultra_slow_test)
base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')
subjects_dir = op.join(testing.data_path(download=False), 'subjects')
warnings.simplefilter('always')
def check_usage(module, force_help=False):
"""Helper to ensure we print usage"""
args = ('--help',) if force_help else ()
with ArgvSetter(args) as out:
try:
module.run()
except SystemExit:
pass
assert_true('Usage: ' in out.stdout.getvalue())
@slow_test
def test_browse_raw():
"""Test mne browse_raw."""
check_usage(mne_browse_raw)
def test_bti2fiff():
"""Test mne bti2fiff."""
check_usage(mne_bti2fiff)
def test_compare_fiff():
"""Test mne compare_fiff."""
check_usage(mne_compare_fiff)
def test_show_fiff():
"""Test mne compare_fiff."""
check_usage(mne_show_fiff)
with ArgvSetter((raw_fname,)):
mne_show_fiff.run()
@requires_mne
def test_clean_eog_ecg():
"""Test mne clean_eog_ecg."""
check_usage(mne_clean_eog_ecg)
tempdir = _TempDir()
raw = concatenate_raws([read_raw_fif(f)
for f in [raw_fname, raw_fname, raw_fname]])
raw.info['bads'] = ['MEG 2443']
use_fname = op.join(tempdir, op.basename(raw_fname))
raw.save(use_fname)
with ArgvSetter(('-i', use_fname, '--quiet')):
mne_clean_eog_ecg.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 2) # two projs
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 3) # raw plus two projs
@slow_test
def test_compute_proj_ecg_eog():
"""Test mne compute_proj_ecg/eog."""
for fun in (mne_compute_proj_ecg, mne_compute_proj_eog):
check_usage(fun)
tempdir = _TempDir()
use_fname = op.join(tempdir, op.basename(raw_fname))
bad_fname = op.join(tempdir, 'bads.txt')
with open(bad_fname, 'w') as fid:
fid.write('MEG 2443\n')
shutil.copyfile(raw_fname, use_fname)
with ArgvSetter(('-i', use_fname, '--bad=' + bad_fname,
'--rej-eeg', '150')):
fun.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 1)
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 1)
def test_coreg():
"""Test mne coreg."""
assert_true(hasattr(mne_coreg, 'run'))
def test_kit2fiff():
"""Test mne kit2fiff."""
# Can't check
check_usage(mne_kit2fiff, force_help=True)
@requires_tvtk
@testing.requires_testing_data
def test_make_scalp_surfaces():
"""Test mne make_scalp_surfaces."""
check_usage(mne_make_scalp_surfaces)
# Copy necessary files to avoid FreeSurfer call
tempdir = _TempDir()
surf_path = op.join(subjects_dir, 'sample', 'surf')
surf_path_new = op.join(tempdir, 'sample', 'surf')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(surf_path_new)
subj_dir = op.join(tempdir, 'sample', 'bem')
os.mkdir(subj_dir)
shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new)
orig_fs = os.getenv('FREESURFER_HOME', None)
if orig_fs is not None:
del os.environ['FREESURFER_HOME']
cmd = ('-s', 'sample', '--subjects-dir', tempdir)
os.environ['_MNE_TESTING_SCALP'] = 'true'
dense_fname = op.join(subj_dir, 'sample-head-dense.fif')
medium_fname = op.join(subj_dir, 'sample-head-medium.fif')
try:
with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
assert_raises(RuntimeError, mne_make_scalp_surfaces.run)
os.environ['FREESURFER_HOME'] = tempdir # don't actually use it
mne_make_scalp_surfaces.run()
assert_true(op.isfile(dense_fname))
assert_true(op.isfile(medium_fname))
assert_raises(IOError, mne_make_scalp_surfaces.run) # no overwrite
finally:
if orig_fs is not None:
os.environ['FREESURFER_HOME'] = orig_fs
else:
del os.environ['FREESURFER_HOME']
del os.environ['_MNE_TESTING_SCALP']
# actually check the outputs
head_py = read_bem_surfaces(dense_fname)
assert_equal(len(head_py), 1)
head_py = head_py[0]
head_c = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem',
'sample-head-dense.fif'))[0]
assert_allclose(head_py['rr'], head_c['rr'])
def test_maxfilter():
"""Test mne maxfilter."""
check_usage(mne_maxfilter)
with ArgvSetter(('-i', raw_fname, '--st', '--movecomp', '--linefreq', '60',
'--trans', raw_fname)) as out:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
os.environ['_MNE_MAXFILTER_TEST'] = 'true'
try:
mne_maxfilter.run()
finally:
del os.environ['_MNE_MAXFILTER_TEST']
assert_true(len(w) == 1)
for check in ('maxfilter', '-trans', '-movecomp'):
|
@slow_test
@requires_mayavi
@requires_PIL
@testing.requires_testing_data
def test_report():
"""Test mne report."""
check_usage(mne_report)
tempdir = _TempDir()
use_fname = op.join(tempdir, op.basename(raw_fname))
shutil.copyfile(raw_fname, use_fname)
with ArgvSetter(('-p', tempdir, '-i', use_fname, '-d', subjects_dir,
'-s', 'sample', '--no-browser', '-m', '30')):
mne_report.run()
fnames = glob.glob(op.join(tempdir, '*.html'))
assert_true(len(fnames) == 1)
def test_surf2bem():
"""Test mne surf2bem."""
check_usage(mne_surf2bem)
@ultra_slow_test
@requires_freesurfer
@testing.requires_testing_data
def test_watershed_bem():
"""Test mne watershed bem."""
check_usage(mne_watershed_bem)
# Copy necessary files to tempdir
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', 'mri')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(mridata_path_new)
if op.exists(op.join(mridata_path, 'T1')):
shutil.copytree(op.join(mridata_path, 'T1'), op.join(mridata_path_new,
'T1'))
if op.exists(op.join(mridata_path, 'T1.mgz')):
shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
op.join(mridata_path_new, 'T1.mgz'))
with ArgvSetter(('-d', tempdir, '-s', 'sample', '-o'),
disable_stdout=False, disable_stderr=False):
mne_watershed_bem.run()
@ultra_slow_test
@requires_freesurfer
@sample.requires_sample_data
def test_flash_bem():
"""Test mne flash_bem."""
check_usage(mne_flash_bem, force_help=True)
# Using the sample dataset
subjects_dir = op.join(sample.data_path(download=False), 'subjects')
# Copy necessary files to tempdir
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', ' | assert_true(check in out.stdout.getvalue(), check) | conditional_block |
test_commands.py | ne_make_scalp_surfaces, mne_maxfilter,
mne_report, mne_surf2bem, mne_watershed_bem,
mne_compare_fiff, mne_flash_bem, mne_show_fiff,
mne_show_info)
from mne.datasets import testing, sample
from mne.io import read_raw_fif
from mne.utils import (run_tests_if_main, _TempDir, requires_mne, requires_PIL,
requires_mayavi, requires_tvtk, requires_freesurfer,
ArgvSetter, slow_test, ultra_slow_test)
base_dir = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')
subjects_dir = op.join(testing.data_path(download=False), 'subjects')
warnings.simplefilter('always')
def check_usage(module, force_help=False):
"""Helper to ensure we print usage"""
args = ('--help',) if force_help else ()
with ArgvSetter(args) as out:
try:
module.run()
except SystemExit:
pass
assert_true('Usage: ' in out.stdout.getvalue())
@slow_test
def test_browse_raw():
"""Test mne browse_raw."""
check_usage(mne_browse_raw)
def test_bti2fiff():
"""Test mne bti2fiff."""
check_usage(mne_bti2fiff)
def test_compare_fiff():
"""Test mne compare_fiff."""
check_usage(mne_compare_fiff)
def test_show_fiff():
"""Test mne compare_fiff."""
check_usage(mne_show_fiff)
with ArgvSetter((raw_fname,)):
mne_show_fiff.run()
@requires_mne
def test_clean_eog_ecg():
"""Test mne clean_eog_ecg."""
check_usage(mne_clean_eog_ecg)
tempdir = _TempDir()
raw = concatenate_raws([read_raw_fif(f)
for f in [raw_fname, raw_fname, raw_fname]])
raw.info['bads'] = ['MEG 2443']
use_fname = op.join(tempdir, op.basename(raw_fname))
raw.save(use_fname)
with ArgvSetter(('-i', use_fname, '--quiet')):
mne_clean_eog_ecg.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 2) # two projs
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 3) # raw plus two projs
@slow_test
def test_compute_proj_ecg_eog():
"""Test mne compute_proj_ecg/eog.""" | with open(bad_fname, 'w') as fid:
fid.write('MEG 2443\n')
shutil.copyfile(raw_fname, use_fname)
with ArgvSetter(('-i', use_fname, '--bad=' + bad_fname,
'--rej-eeg', '150')):
fun.run()
fnames = glob.glob(op.join(tempdir, '*proj.fif'))
assert_true(len(fnames) == 1)
fnames = glob.glob(op.join(tempdir, '*-eve.fif'))
assert_true(len(fnames) == 1)
def test_coreg():
"""Test mne coreg."""
assert_true(hasattr(mne_coreg, 'run'))
def test_kit2fiff():
"""Test mne kit2fiff."""
# Can't check
check_usage(mne_kit2fiff, force_help=True)
@requires_tvtk
@testing.requires_testing_data
def test_make_scalp_surfaces():
"""Test mne make_scalp_surfaces."""
check_usage(mne_make_scalp_surfaces)
# Copy necessary files to avoid FreeSurfer call
tempdir = _TempDir()
surf_path = op.join(subjects_dir, 'sample', 'surf')
surf_path_new = op.join(tempdir, 'sample', 'surf')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(surf_path_new)
subj_dir = op.join(tempdir, 'sample', 'bem')
os.mkdir(subj_dir)
shutil.copy(op.join(surf_path, 'lh.seghead'), surf_path_new)
orig_fs = os.getenv('FREESURFER_HOME', None)
if orig_fs is not None:
del os.environ['FREESURFER_HOME']
cmd = ('-s', 'sample', '--subjects-dir', tempdir)
os.environ['_MNE_TESTING_SCALP'] = 'true'
dense_fname = op.join(subj_dir, 'sample-head-dense.fif')
medium_fname = op.join(subj_dir, 'sample-head-medium.fif')
try:
with ArgvSetter(cmd, disable_stdout=False, disable_stderr=False):
assert_raises(RuntimeError, mne_make_scalp_surfaces.run)
os.environ['FREESURFER_HOME'] = tempdir # don't actually use it
mne_make_scalp_surfaces.run()
assert_true(op.isfile(dense_fname))
assert_true(op.isfile(medium_fname))
assert_raises(IOError, mne_make_scalp_surfaces.run) # no overwrite
finally:
if orig_fs is not None:
os.environ['FREESURFER_HOME'] = orig_fs
else:
del os.environ['FREESURFER_HOME']
del os.environ['_MNE_TESTING_SCALP']
# actually check the outputs
head_py = read_bem_surfaces(dense_fname)
assert_equal(len(head_py), 1)
head_py = head_py[0]
head_c = read_bem_surfaces(op.join(subjects_dir, 'sample', 'bem',
'sample-head-dense.fif'))[0]
assert_allclose(head_py['rr'], head_c['rr'])
def test_maxfilter():
"""Test mne maxfilter."""
check_usage(mne_maxfilter)
with ArgvSetter(('-i', raw_fname, '--st', '--movecomp', '--linefreq', '60',
'--trans', raw_fname)) as out:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
os.environ['_MNE_MAXFILTER_TEST'] = 'true'
try:
mne_maxfilter.run()
finally:
del os.environ['_MNE_MAXFILTER_TEST']
assert_true(len(w) == 1)
for check in ('maxfilter', '-trans', '-movecomp'):
assert_true(check in out.stdout.getvalue(), check)
@slow_test
@requires_mayavi
@requires_PIL
@testing.requires_testing_data
def test_report():
"""Test mne report."""
check_usage(mne_report)
tempdir = _TempDir()
use_fname = op.join(tempdir, op.basename(raw_fname))
shutil.copyfile(raw_fname, use_fname)
with ArgvSetter(('-p', tempdir, '-i', use_fname, '-d', subjects_dir,
'-s', 'sample', '--no-browser', '-m', '30')):
mne_report.run()
fnames = glob.glob(op.join(tempdir, '*.html'))
assert_true(len(fnames) == 1)
def test_surf2bem():
"""Test mne surf2bem."""
check_usage(mne_surf2bem)
@ultra_slow_test
@requires_freesurfer
@testing.requires_testing_data
def test_watershed_bem():
"""Test mne watershed bem."""
check_usage(mne_watershed_bem)
# Copy necessary files to tempdir
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', 'mri')
os.mkdir(op.join(tempdir, 'sample'))
os.mkdir(mridata_path_new)
if op.exists(op.join(mridata_path, 'T1')):
shutil.copytree(op.join(mridata_path, 'T1'), op.join(mridata_path_new,
'T1'))
if op.exists(op.join(mridata_path, 'T1.mgz')):
shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
op.join(mridata_path_new, 'T1.mgz'))
with ArgvSetter(('-d', tempdir, '-s', 'sample', '-o'),
disable_stdout=False, disable_stderr=False):
mne_watershed_bem.run()
@ultra_slow_test
@requires_freesurfer
@sample.requires_sample_data
def test_flash_bem():
"""Test mne flash_bem."""
check_usage(mne_flash_bem, force_help=True)
# Using the sample dataset
subjects_dir = op.join(sample.data_path(download=False), 'subjects')
# Copy necessary files to tempdir
tempdir = _TempDir()
mridata_path = op.join(subjects_dir, 'sample', 'mri')
mridata_path_new = op.join(tempdir, 'sample', ' | for fun in (mne_compute_proj_ecg, mne_compute_proj_eog):
check_usage(fun)
tempdir = _TempDir()
use_fname = op.join(tempdir, op.basename(raw_fname))
bad_fname = op.join(tempdir, 'bads.txt') | random_line_split |
hooks.ts | import { Observable, of, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { SharedHooks } from '../shared-hooks/hooks';
import { Attributes } from '../types';
export class IntersectionObserverHooks extends SharedHooks<{ isIntersecting: boolean }> {
private readonly observers = new WeakMap<Element | {}, IntersectionObserver>();
private readonly intersectionSubject = new Subject<IntersectionObserverEntry>();
private readonly uniqKey = {};
getObservable(attributes: Attributes<{ isIntersecting: boolean }>): Observable<{ isIntersecting: boolean }> {
if (this.skipLazyLoading(attributes)) {
return of({ isIntersecting: true });
}
if (attributes.customObservable) {
return attributes.customObservable;
}
const scrollContainerKey = attributes.scrollContainer || this.uniqKey;
const options: ObserverOptions = {
root: attributes.scrollContainer || null,
};
if (attributes.offset) {
options.rootMargin = `${attributes.offset}px`;
}
let observer = this.observers.get(scrollContainerKey);
if (!observer) {
observer = new IntersectionObserver((entrys) => this.loadingCallback(entrys), options);
this.observers.set(scrollContainerKey, observer);
}
observer.observe(attributes.element);
return Observable.create((obs: Subject<IntersectionObserverEntry>) => {
const subscription = this.intersectionSubject.pipe(filter((entry) => entry.target === attributes.element)).subscribe(obs);
return () => {
subscription.unsubscribe();
observer!.unobserve(attributes.element);
};
});
}
isVisible(event: { isIntersecting: boolean }): boolean {
return event.isIntersecting;
}
private loadingCallback(entrys: IntersectionObserverEntry[]) {
entrys.forEach((entry) => this.intersectionSubject.next(entry));
}
}
interface ObserverOptions {
root: Element | null; | rootMargin?: string;
} | random_line_split |
|
hooks.ts | import { Observable, of, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { SharedHooks } from '../shared-hooks/hooks';
import { Attributes } from '../types';
export class IntersectionObserverHooks extends SharedHooks<{ isIntersecting: boolean }> {
private readonly observers = new WeakMap<Element | {}, IntersectionObserver>();
private readonly intersectionSubject = new Subject<IntersectionObserverEntry>();
private readonly uniqKey = {};
getObservable(attributes: Attributes<{ isIntersecting: boolean }>): Observable<{ isIntersecting: boolean }> {
if (this.skipLazyLoading(attributes)) {
return of({ isIntersecting: true });
}
if (attributes.customObservable) {
return attributes.customObservable;
}
const scrollContainerKey = attributes.scrollContainer || this.uniqKey;
const options: ObserverOptions = {
root: attributes.scrollContainer || null,
};
if (attributes.offset) {
options.rootMargin = `${attributes.offset}px`;
}
let observer = this.observers.get(scrollContainerKey);
if (!observer) {
observer = new IntersectionObserver((entrys) => this.loadingCallback(entrys), options);
this.observers.set(scrollContainerKey, observer);
}
observer.observe(attributes.element);
return Observable.create((obs: Subject<IntersectionObserverEntry>) => {
const subscription = this.intersectionSubject.pipe(filter((entry) => entry.target === attributes.element)).subscribe(obs);
return () => {
subscription.unsubscribe();
observer!.unobserve(attributes.element);
};
});
}
isVisible(event: { isIntersecting: boolean }): boolean {
return event.isIntersecting;
}
private | (entrys: IntersectionObserverEntry[]) {
entrys.forEach((entry) => this.intersectionSubject.next(entry));
}
}
interface ObserverOptions {
root: Element | null;
rootMargin?: string;
}
| loadingCallback | identifier_name |
hooks.ts | import { Observable, of, Subject } from 'rxjs';
import { filter } from 'rxjs/operators';
import { SharedHooks } from '../shared-hooks/hooks';
import { Attributes } from '../types';
export class IntersectionObserverHooks extends SharedHooks<{ isIntersecting: boolean }> {
private readonly observers = new WeakMap<Element | {}, IntersectionObserver>();
private readonly intersectionSubject = new Subject<IntersectionObserverEntry>();
private readonly uniqKey = {};
getObservable(attributes: Attributes<{ isIntersecting: boolean }>): Observable<{ isIntersecting: boolean }> {
if (this.skipLazyLoading(attributes)) |
if (attributes.customObservable) {
return attributes.customObservable;
}
const scrollContainerKey = attributes.scrollContainer || this.uniqKey;
const options: ObserverOptions = {
root: attributes.scrollContainer || null,
};
if (attributes.offset) {
options.rootMargin = `${attributes.offset}px`;
}
let observer = this.observers.get(scrollContainerKey);
if (!observer) {
observer = new IntersectionObserver((entrys) => this.loadingCallback(entrys), options);
this.observers.set(scrollContainerKey, observer);
}
observer.observe(attributes.element);
return Observable.create((obs: Subject<IntersectionObserverEntry>) => {
const subscription = this.intersectionSubject.pipe(filter((entry) => entry.target === attributes.element)).subscribe(obs);
return () => {
subscription.unsubscribe();
observer!.unobserve(attributes.element);
};
});
}
isVisible(event: { isIntersecting: boolean }): boolean {
return event.isIntersecting;
}
private loadingCallback(entrys: IntersectionObserverEntry[]) {
entrys.forEach((entry) => this.intersectionSubject.next(entry));
}
}
interface ObserverOptions {
root: Element | null;
rootMargin?: string;
}
| {
return of({ isIntersecting: true });
} | conditional_block |
ShowCertification.js | const certificationUrl = '/certification/developmentuser/responsive-web-design';
const projects = {
superBlock: 'responsive-web-design',
block: 'responsive-web-design-projects',
challenges: [
{
slug: 'build-a-tribute-page',
solution: 'https://codepen.io/moT01/pen/ZpJpKp'
},
{
slug: 'build-a-survey-form',
solution: 'https://codepen.io/moT01/pen/LrrjGz?editors=1010'
},
{
slug: 'build-a-product-landing-page',
solution: 'https://codepen.io/moT01/full/qKyKYL/'
},
{
slug: 'build-a-technical-documentation-page',
solution: 'https://codepen.io/moT01/full/JBvzNL/'
},
{
slug: 'build-a-personal-portfolio-webpage',
solution: 'https://codepen.io/moT01/pen/vgOaoJ'
}
]
};
describe('A certification,', function () {
before(() => {
cy.exec('npm run seed');
cy.login();
// submit projects for certificate
const { superBlock, block, challenges } = projects;
challenges.forEach(({ slug, solution }) => {
const url = `/learn/${superBlock}/${block}/${slug}`;
cy.visit(url);
cy.get('#dynamic-front-end-form')
.get('#solution')
.type(solution, { force: true, delay: 0 });
cy.contains("I've completed this challenge")
.should('not.be.disabled')
.click();
cy.contains('Submit and go to next challenge').click().wait(1000);
});
cy.get('.donation-modal').should('be.visible');
cy.visit('/settings');
// set user settings to public to claim a cert
cy.get('label:contains(Public)>input').each(el => {
if (!/toggle-active/.test(el[0].parentElement.className)) {
cy.wrap(el).click({ force: true });
cy.wait(1000);
}
});
// if honest policy not accepted
cy.get('.honesty-policy button').then(btn => {
if (btn[0].innerText === 'Agree') {
btn[0].click({ force: true });
cy.wait(1000);
}
});
// claim certificate
cy.get('a[href*="developmentuser/responsive-web-design"]').click({
force: true
});
});
describe('while viewing your own,', function () {
before(() => {
cy.login();
cy.visit(certificationUrl);
});
it('should render a LinkedIn button', function () {
cy.contains('Add this certification to my LinkedIn profile')
.should('have.attr', 'href')
.and(
'match',
// eslint-disable-next-line max-len
/https:\/\/www\.linkedin\.com\/profile\/add\?startTask=CERTIFICATION_NAME&name=Responsive Web Design&organizationId=4831032&issueYear=\d\d\d\d&issueMonth=\d\d?&certUrl=https:\/\/freecodecamp\.org\/certification\/developmentuser\/responsive-web-design/
);
});
it('should render a Twitter button', function () {
cy.contains('Share this certification on Twitter').should(
'have.attr',
'href', | 'https://twitter.com/intent/tweet?text=I just earned the Responsive Web Design certification @freeCodeCamp! Check it out here: https://freecodecamp.org/certification/developmentuser/responsive-web-design'
);
});
it("should be issued with today's date", () => {
const date = new Date();
const issued = `Issued\xa0${new Intl.DateTimeFormat('en-US', {
month: 'long'
}).format(date)} ${date.getDate()}, ${date.getFullYear()}`;
cy.get('[data-cy=issue-date]').should('have.text', issued);
});
});
describe("while viewing someone else's,", function () {
before(() => {
cy.visit(certificationUrl);
});
it('should display certificate', function () {
cy.contains('has successfully completed the freeCodeCamp.org').should(
'exist'
);
cy.contains('Responsive Web Design').should('exist');
});
it('should not render a LinkedIn button', function () {
cy.contains('Add this certification to my LinkedIn profile').should(
'not.exist'
);
});
it('should not render a Twitter button', function () {
cy.contains('Share this certification on Twitter').should('not.exist');
});
});
}); | random_line_split |
|
ShowCertification.js | const certificationUrl = '/certification/developmentuser/responsive-web-design';
const projects = {
superBlock: 'responsive-web-design',
block: 'responsive-web-design-projects',
challenges: [
{
slug: 'build-a-tribute-page',
solution: 'https://codepen.io/moT01/pen/ZpJpKp'
},
{
slug: 'build-a-survey-form',
solution: 'https://codepen.io/moT01/pen/LrrjGz?editors=1010'
},
{
slug: 'build-a-product-landing-page',
solution: 'https://codepen.io/moT01/full/qKyKYL/'
},
{
slug: 'build-a-technical-documentation-page',
solution: 'https://codepen.io/moT01/full/JBvzNL/'
},
{
slug: 'build-a-personal-portfolio-webpage',
solution: 'https://codepen.io/moT01/pen/vgOaoJ'
}
]
};
describe('A certification,', function () {
before(() => {
cy.exec('npm run seed');
cy.login();
// submit projects for certificate
const { superBlock, block, challenges } = projects;
challenges.forEach(({ slug, solution }) => {
const url = `/learn/${superBlock}/${block}/${slug}`;
cy.visit(url);
cy.get('#dynamic-front-end-form')
.get('#solution')
.type(solution, { force: true, delay: 0 });
cy.contains("I've completed this challenge")
.should('not.be.disabled')
.click();
cy.contains('Submit and go to next challenge').click().wait(1000);
});
cy.get('.donation-modal').should('be.visible');
cy.visit('/settings');
// set user settings to public to claim a cert
cy.get('label:contains(Public)>input').each(el => {
if (!/toggle-active/.test(el[0].parentElement.className)) {
cy.wrap(el).click({ force: true });
cy.wait(1000);
}
});
// if honest policy not accepted
cy.get('.honesty-policy button').then(btn => {
if (btn[0].innerText === 'Agree') |
});
// claim certificate
cy.get('a[href*="developmentuser/responsive-web-design"]').click({
force: true
});
});
describe('while viewing your own,', function () {
before(() => {
cy.login();
cy.visit(certificationUrl);
});
it('should render a LinkedIn button', function () {
cy.contains('Add this certification to my LinkedIn profile')
.should('have.attr', 'href')
.and(
'match',
// eslint-disable-next-line max-len
/https:\/\/www\.linkedin\.com\/profile\/add\?startTask=CERTIFICATION_NAME&name=Responsive Web Design&organizationId=4831032&issueYear=\d\d\d\d&issueMonth=\d\d?&certUrl=https:\/\/freecodecamp\.org\/certification\/developmentuser\/responsive-web-design/
);
});
it('should render a Twitter button', function () {
cy.contains('Share this certification on Twitter').should(
'have.attr',
'href',
'https://twitter.com/intent/tweet?text=I just earned the Responsive Web Design certification @freeCodeCamp! Check it out here: https://freecodecamp.org/certification/developmentuser/responsive-web-design'
);
});
it("should be issued with today's date", () => {
const date = new Date();
const issued = `Issued\xa0${new Intl.DateTimeFormat('en-US', {
month: 'long'
}).format(date)} ${date.getDate()}, ${date.getFullYear()}`;
cy.get('[data-cy=issue-date]').should('have.text', issued);
});
});
describe("while viewing someone else's,", function () {
before(() => {
cy.visit(certificationUrl);
});
it('should display certificate', function () {
cy.contains('has successfully completed the freeCodeCamp.org').should(
'exist'
);
cy.contains('Responsive Web Design').should('exist');
});
it('should not render a LinkedIn button', function () {
cy.contains('Add this certification to my LinkedIn profile').should(
'not.exist'
);
});
it('should not render a Twitter button', function () {
cy.contains('Share this certification on Twitter').should('not.exist');
});
});
});
| {
btn[0].click({ force: true });
cy.wait(1000);
} | conditional_block |
MaterialUIPickers.tsx | import * as React from 'react';
import Stack from '@material-ui/core/Stack';
import TextField from '@material-ui/core/TextField';
import AdapterDateFns from '@material-ui/lab/AdapterDateFns';
import LocalizationProvider from '@material-ui/lab/LocalizationProvider';
import TimePicker from '@material-ui/lab/TimePicker';
import DesktopDatePicker from '@material-ui/lab/DesktopDatePicker';
import MobileDatePicker from '@material-ui/lab/MobileDatePicker';
export default function MaterialUIPickers() | label="Date picker mobile"
inputFormat="MM/dd/yyyy"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
<TimePicker
label="Time picker"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
</Stack>
</LocalizationProvider>
);
}
| {
const [value, setValue] = React.useState<Date | null>(
new Date('2014-08-18T21:11:54'),
);
const handleChange = (newValue: Date | null) => {
setValue(newValue);
};
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Stack spacing={3}>
<DesktopDatePicker
label="Date picker desktop"
inputFormat="MM/dd/yyyy"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
<MobileDatePicker | identifier_body |
MaterialUIPickers.tsx | import * as React from 'react';
import Stack from '@material-ui/core/Stack';
import TextField from '@material-ui/core/TextField';
import AdapterDateFns from '@material-ui/lab/AdapterDateFns';
import LocalizationProvider from '@material-ui/lab/LocalizationProvider';
import TimePicker from '@material-ui/lab/TimePicker';
import DesktopDatePicker from '@material-ui/lab/DesktopDatePicker';
import MobileDatePicker from '@material-ui/lab/MobileDatePicker';
export default function MaterialUIPickers() {
const [value, setValue] = React.useState<Date | null>(
new Date('2014-08-18T21:11:54'),
);
const handleChange = (newValue: Date | null) => {
setValue(newValue);
};
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Stack spacing={3}>
<DesktopDatePicker
label="Date picker desktop"
inputFormat="MM/dd/yyyy"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
<MobileDatePicker
label="Date picker mobile" | value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
<TimePicker
label="Time picker"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
</Stack>
</LocalizationProvider>
);
} | inputFormat="MM/dd/yyyy" | random_line_split |
MaterialUIPickers.tsx | import * as React from 'react';
import Stack from '@material-ui/core/Stack';
import TextField from '@material-ui/core/TextField';
import AdapterDateFns from '@material-ui/lab/AdapterDateFns';
import LocalizationProvider from '@material-ui/lab/LocalizationProvider';
import TimePicker from '@material-ui/lab/TimePicker';
import DesktopDatePicker from '@material-ui/lab/DesktopDatePicker';
import MobileDatePicker from '@material-ui/lab/MobileDatePicker';
export default function | () {
const [value, setValue] = React.useState<Date | null>(
new Date('2014-08-18T21:11:54'),
);
const handleChange = (newValue: Date | null) => {
setValue(newValue);
};
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Stack spacing={3}>
<DesktopDatePicker
label="Date picker desktop"
inputFormat="MM/dd/yyyy"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
<MobileDatePicker
label="Date picker mobile"
inputFormat="MM/dd/yyyy"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
<TimePicker
label="Time picker"
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} />}
/>
</Stack>
</LocalizationProvider>
);
}
| MaterialUIPickers | identifier_name |
tokens.rs | //* This file is part of the uutils coreutils package.
//*
//* (c) Roman Gafiyatullin <r.gafiyatullin@me.com>
//*
//* For the full copyright and license information, please view the LICENSE
//* file that was distributed with this source code.
//!
//! The following tokens are present in the expr grammar:
//! * integer literal;
//! * string literal;
//! * infix binary operators;
//! * prefix operators.
//!
//! According to the man-page of expr we have expression split into tokens (each token -- separate CLI-argument).
//! Hence all we need is to map the strings into the Token structures, except for some ugly fiddling with +-escaping.
//!
// spell-checker:ignore (ToDO) paren
use num_bigint::BigInt;
#[derive(Debug, Clone)]
pub enum Token {
Value {
value: String,
},
ParOpen,
ParClose,
InfixOp {
precedence: u8,
left_assoc: bool,
value: String,
},
PrefixOp {
arity: usize,
value: String,
},
}
impl Token {
fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self {
Self::InfixOp {
left_assoc,
precedence,
value: v.into(),
}
}
fn new_value(v: &str) -> Self {
Self::Value { value: v.into() }
}
fn is_infix_plus(&self) -> bool {
match self {
Self::InfixOp { value, .. } => value == "+",
_ => false,
}
}
fn is_a_number(&self) -> bool {
match self {
Self::Value { value, .. } => value.parse::<BigInt>().is_ok(),
_ => false,
}
}
fn is_a_close_paren(&self) -> bool {
matches!(*self, Token::ParClose)
}
}
pub fn | (strings: &[String]) -> Result<Vec<(usize, Token)>, String> {
let mut tokens_acc = Vec::with_capacity(strings.len());
let mut tok_idx = 1;
for s in strings {
let token_if_not_escaped = match s.as_ref() {
"(" => Token::ParOpen,
")" => Token::ParClose,
"^" => Token::new_infix_op(s, false, 7),
":" => Token::new_infix_op(s, true, 6),
"*" | "/" | "%" => Token::new_infix_op(s, true, 5),
"+" | "-" => Token::new_infix_op(s, true, 4),
"=" | "!=" | "<" | ">" | "<=" | ">=" => Token::new_infix_op(s, true, 3),
"&" => Token::new_infix_op(s, true, 2),
"|" => Token::new_infix_op(s, true, 1),
"match" | "index" => Token::PrefixOp {
arity: 2,
value: s.clone(),
},
"substr" => Token::PrefixOp {
arity: 3,
value: s.clone(),
},
"length" => Token::PrefixOp {
arity: 1,
value: s.clone(),
},
_ => Token::new_value(s),
};
push_token_if_not_escaped(&mut tokens_acc, tok_idx, token_if_not_escaped, s);
tok_idx += 1;
}
maybe_dump_tokens_acc(&tokens_acc);
Ok(tokens_acc)
}
fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) {
use std::env;
if let Ok(debug_var) = env::var("EXPR_DEBUG_TOKENS") {
if debug_var == "1" {
println!("EXPR_DEBUG_TOKENS");
for token in tokens_acc {
println!("\t{:?}", token);
}
}
}
}
fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) {
// Smells heuristics... :(
let prev_is_plus = match acc.last() {
None => false,
Some(t) => t.1.is_infix_plus(),
};
let should_use_as_escaped = if prev_is_plus && acc.len() >= 2 {
let pre_prev = &acc[acc.len() - 2];
!(pre_prev.1.is_a_number() || pre_prev.1.is_a_close_paren())
} else {
prev_is_plus
};
if should_use_as_escaped {
acc.pop();
acc.push((tok_idx, Token::new_value(s)));
} else {
acc.push((tok_idx, token));
}
}
| strings_to_tokens | identifier_name |
tokens.rs | //* This file is part of the uutils coreutils package.
//*
//* (c) Roman Gafiyatullin <r.gafiyatullin@me.com>
//*
//* For the full copyright and license information, please view the LICENSE
//* file that was distributed with this source code.
//!
//! The following tokens are present in the expr grammar:
//! * integer literal;
//! * string literal;
//! * infix binary operators;
//! * prefix operators.
//!
//! According to the man-page of expr we have expression split into tokens (each token -- separate CLI-argument).
//! Hence all we need is to map the strings into the Token structures, except for some ugly fiddling with +-escaping.
//!
// spell-checker:ignore (ToDO) paren
use num_bigint::BigInt;
#[derive(Debug, Clone)]
pub enum Token {
Value {
value: String,
},
ParOpen,
ParClose,
InfixOp {
precedence: u8,
left_assoc: bool,
value: String,
},
PrefixOp {
arity: usize,
value: String,
},
}
impl Token {
fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self {
Self::InfixOp {
left_assoc,
precedence,
value: v.into(),
}
}
fn new_value(v: &str) -> Self {
Self::Value { value: v.into() }
}
fn is_infix_plus(&self) -> bool {
match self {
Self::InfixOp { value, .. } => value == "+",
_ => false,
}
}
fn is_a_number(&self) -> bool {
match self {
Self::Value { value, .. } => value.parse::<BigInt>().is_ok(),
_ => false,
}
}
fn is_a_close_paren(&self) -> bool {
matches!(*self, Token::ParClose)
}
}
pub fn strings_to_tokens(strings: &[String]) -> Result<Vec<(usize, Token)>, String> {
let mut tokens_acc = Vec::with_capacity(strings.len());
let mut tok_idx = 1;
for s in strings {
let token_if_not_escaped = match s.as_ref() {
"(" => Token::ParOpen,
")" => Token::ParClose,
"^" => Token::new_infix_op(s, false, 7),
":" => Token::new_infix_op(s, true, 6),
"*" | "/" | "%" => Token::new_infix_op(s, true, 5),
"+" | "-" => Token::new_infix_op(s, true, 4),
"=" | "!=" | "<" | ">" | "<=" | ">=" => Token::new_infix_op(s, true, 3),
"&" => Token::new_infix_op(s, true, 2),
"|" => Token::new_infix_op(s, true, 1),
"match" | "index" => Token::PrefixOp {
arity: 2,
value: s.clone(),
},
"substr" => Token::PrefixOp {
arity: 3,
value: s.clone(),
},
"length" => Token::PrefixOp {
arity: 1,
value: s.clone(),
},
_ => Token::new_value(s),
};
push_token_if_not_escaped(&mut tokens_acc, tok_idx, token_if_not_escaped, s);
tok_idx += 1;
}
maybe_dump_tokens_acc(&tokens_acc);
Ok(tokens_acc)
}
fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) {
use std::env;
if let Ok(debug_var) = env::var("EXPR_DEBUG_TOKENS") {
if debug_var == "1" {
println!("EXPR_DEBUG_TOKENS");
for token in tokens_acc {
println!("\t{:?}", token);
}
}
}
}
fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) {
// Smells heuristics... :(
let prev_is_plus = match acc.last() {
None => false,
Some(t) => t.1.is_infix_plus(),
};
let should_use_as_escaped = if prev_is_plus && acc.len() >= 2 {
let pre_prev = &acc[acc.len() - 2];
!(pre_prev.1.is_a_number() || pre_prev.1.is_a_close_paren())
} else {
prev_is_plus
};
if should_use_as_escaped | else {
acc.push((tok_idx, token));
}
}
| {
acc.pop();
acc.push((tok_idx, Token::new_value(s)));
} | conditional_block |
tokens.rs | //* This file is part of the uutils coreutils package.
//*
//* (c) Roman Gafiyatullin <r.gafiyatullin@me.com>
//*
//* For the full copyright and license information, please view the LICENSE
//* file that was distributed with this source code.
//!
//! The following tokens are present in the expr grammar:
//! * integer literal;
//! * string literal;
//! * infix binary operators;
//! * prefix operators.
//!
//! According to the man-page of expr we have expression split into tokens (each token -- separate CLI-argument).
//! Hence all we need is to map the strings into the Token structures, except for some ugly fiddling with +-escaping.
//!
// spell-checker:ignore (ToDO) paren
use num_bigint::BigInt;
#[derive(Debug, Clone)]
pub enum Token {
Value {
value: String,
},
ParOpen,
ParClose,
InfixOp {
precedence: u8,
left_assoc: bool,
value: String,
},
PrefixOp {
arity: usize,
value: String,
},
}
impl Token {
fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self {
Self::InfixOp {
left_assoc,
precedence,
value: v.into(),
}
}
fn new_value(v: &str) -> Self {
Self::Value { value: v.into() }
}
fn is_infix_plus(&self) -> bool {
match self {
Self::InfixOp { value, .. } => value == "+",
_ => false,
}
}
fn is_a_number(&self) -> bool {
match self {
Self::Value { value, .. } => value.parse::<BigInt>().is_ok(),
_ => false,
}
}
fn is_a_close_paren(&self) -> bool |
}
pub fn strings_to_tokens(strings: &[String]) -> Result<Vec<(usize, Token)>, String> {
let mut tokens_acc = Vec::with_capacity(strings.len());
let mut tok_idx = 1;
for s in strings {
let token_if_not_escaped = match s.as_ref() {
"(" => Token::ParOpen,
")" => Token::ParClose,
"^" => Token::new_infix_op(s, false, 7),
":" => Token::new_infix_op(s, true, 6),
"*" | "/" | "%" => Token::new_infix_op(s, true, 5),
"+" | "-" => Token::new_infix_op(s, true, 4),
"=" | "!=" | "<" | ">" | "<=" | ">=" => Token::new_infix_op(s, true, 3),
"&" => Token::new_infix_op(s, true, 2),
"|" => Token::new_infix_op(s, true, 1),
"match" | "index" => Token::PrefixOp {
arity: 2,
value: s.clone(),
},
"substr" => Token::PrefixOp {
arity: 3,
value: s.clone(),
},
"length" => Token::PrefixOp {
arity: 1,
value: s.clone(),
},
_ => Token::new_value(s),
};
push_token_if_not_escaped(&mut tokens_acc, tok_idx, token_if_not_escaped, s);
tok_idx += 1;
}
maybe_dump_tokens_acc(&tokens_acc);
Ok(tokens_acc)
}
fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) {
use std::env;
if let Ok(debug_var) = env::var("EXPR_DEBUG_TOKENS") {
if debug_var == "1" {
println!("EXPR_DEBUG_TOKENS");
for token in tokens_acc {
println!("\t{:?}", token);
}
}
}
}
fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) {
// Smells heuristics... :(
let prev_is_plus = match acc.last() {
None => false,
Some(t) => t.1.is_infix_plus(),
};
let should_use_as_escaped = if prev_is_plus && acc.len() >= 2 {
let pre_prev = &acc[acc.len() - 2];
!(pre_prev.1.is_a_number() || pre_prev.1.is_a_close_paren())
} else {
prev_is_plus
};
if should_use_as_escaped {
acc.pop();
acc.push((tok_idx, Token::new_value(s)));
} else {
acc.push((tok_idx, token));
}
}
| {
matches!(*self, Token::ParClose)
} | identifier_body |
tokens.rs | //* This file is part of the uutils coreutils package.
//*
//* (c) Roman Gafiyatullin <r.gafiyatullin@me.com>
//*
//* For the full copyright and license information, please view the LICENSE
//* file that was distributed with this source code.
//!
//! The following tokens are present in the expr grammar:
//! * integer literal;
//! * string literal;
//! * infix binary operators;
//! * prefix operators.
//!
//! According to the man-page of expr we have expression split into tokens (each token -- separate CLI-argument).
//! Hence all we need is to map the strings into the Token structures, except for some ugly fiddling with +-escaping.
//!
// spell-checker:ignore (ToDO) paren
use num_bigint::BigInt;
#[derive(Debug, Clone)]
pub enum Token {
Value {
value: String,
},
ParOpen,
ParClose,
InfixOp {
precedence: u8,
left_assoc: bool,
value: String,
},
PrefixOp {
arity: usize,
value: String,
},
}
impl Token {
fn new_infix_op(v: &str, left_assoc: bool, precedence: u8) -> Self {
Self::InfixOp {
left_assoc,
precedence,
value: v.into(),
}
}
fn new_value(v: &str) -> Self {
Self::Value { value: v.into() }
}
fn is_infix_plus(&self) -> bool {
match self {
Self::InfixOp { value, .. } => value == "+",
_ => false,
}
}
fn is_a_number(&self) -> bool {
match self {
Self::Value { value, .. } => value.parse::<BigInt>().is_ok(),
_ => false,
}
}
fn is_a_close_paren(&self) -> bool {
matches!(*self, Token::ParClose)
}
}
pub fn strings_to_tokens(strings: &[String]) -> Result<Vec<(usize, Token)>, String> {
let mut tokens_acc = Vec::with_capacity(strings.len());
let mut tok_idx = 1;
for s in strings {
let token_if_not_escaped = match s.as_ref() {
"(" => Token::ParOpen,
")" => Token::ParClose,
"^" => Token::new_infix_op(s, false, 7),
":" => Token::new_infix_op(s, true, 6),
"*" | "/" | "%" => Token::new_infix_op(s, true, 5),
"+" | "-" => Token::new_infix_op(s, true, 4),
"=" | "!=" | "<" | ">" | "<=" | ">=" => Token::new_infix_op(s, true, 3),
"&" => Token::new_infix_op(s, true, 2),
"|" => Token::new_infix_op(s, true, 1),
"match" | "index" => Token::PrefixOp {
arity: 2,
value: s.clone(),
},
"substr" => Token::PrefixOp {
arity: 3,
value: s.clone(),
},
"length" => Token::PrefixOp {
arity: 1,
value: s.clone(),
},
_ => Token::new_value(s),
};
push_token_if_not_escaped(&mut tokens_acc, tok_idx, token_if_not_escaped, s);
tok_idx += 1;
}
maybe_dump_tokens_acc(&tokens_acc);
Ok(tokens_acc)
}
fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) {
use std::env;
| if debug_var == "1" {
println!("EXPR_DEBUG_TOKENS");
for token in tokens_acc {
println!("\t{:?}", token);
}
}
}
}
fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) {
// Smells heuristics... :(
let prev_is_plus = match acc.last() {
None => false,
Some(t) => t.1.is_infix_plus(),
};
let should_use_as_escaped = if prev_is_plus && acc.len() >= 2 {
let pre_prev = &acc[acc.len() - 2];
!(pre_prev.1.is_a_number() || pre_prev.1.is_a_close_paren())
} else {
prev_is_plus
};
if should_use_as_escaped {
acc.pop();
acc.push((tok_idx, Token::new_value(s)));
} else {
acc.push((tok_idx, token));
}
} | if let Ok(debug_var) = env::var("EXPR_DEBUG_TOKENS") { | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
readme = f.read()
requirements = [
'prov>=1.5.3',
]
test_requirements = [
'pydot>=1.2.0'
]
setup(
name='voprov',
version='0.0.2',
description='A library for IVOA Provenance Data Model supporting PROV-JSON, '
'PROV-XML and PROV-N',
long_description=readme,
author='Jean-Francois Sornay',
author_email='jeanfrancois.sornay@gmail.com',
url='https://github.com/sanguillon/voprov/',
packages=find_packages(),
include_package_data=True,
install_requires=requirements,
extras_require={
'dot': ['pydot>=1.2.0'],
},
license="MIT",
zip_safe=False,
keywords=[
'provenance', 'graph', 'model', 'VOPROV', 'provenance-dm', 'PROVENANCE-DM', 'PROV-JSON', 'JSON',
'PROV-XML', 'PROV-N'
],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: French',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Scientific/Engineering :: Information Analysis', | tests_require=test_requirements,
python_requires='>=2',
) | ], | random_line_split |
tweet-dump.py | """
Copyright (c) 2012 Casey Dunham <casey.dunham@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
__author__ = 'Casey Dunham <casey.dunham@gmail.com>'
__version__ = '0.1'
import argparse
import urllib
import sys
from urllib2 import (Request, urlopen, HTTPError, URLError)
try:
# Python >= 2.6
import json
except ImportError:
try:
# Python < 2.6
import simplejson as json
except ImportError:
try:
# Google App Engine
from django.utils import simplejson as json
except ImportError:
raise ImportError, "Unable to load a json library"
class TweetDumpError(Exception):
@property
def message(self):
return self.args[0]
class RateLimitError(TweetDumpError):
pass
API_URL = "https://api.twitter.com/1/statuses/user_timeline.json?%s"
# we are not authenticating so this will return the rate limit based on our IP
# see (https://dev.twitter.com/docs/api/1/get/account/rate_limit_status)
RATE_LIMIT_API_URL = "https://api.twitter.com/1/account/rate_limit_status.json"
parser = argparse.ArgumentParser(description="dump all tweets from user")
parser.add_argument("handle", type=str, help="twitter screen name")
def get_tweets(screen_name, count, maxid=None):
params = {
"screen_name": screen_name,
"count": count,
"exclude_replies": "true",
"include_rts": "true"
}
# if we include the max_id from the last tweet we retrieved, we will retrieve the same tweet again
# so decrement it by one to not retrieve duplicate tweets
if maxid:
params["max_id"] = int(maxid) - 1
encoded_params = urllib.urlencode(params)
query = API_URL % encoded_params
resp = fetch_url(query)
ratelimit_limit = resp.headers["X-RateLimit-Limit"]
ratelimit_remaining = resp.headers["X-RateLimit-Remaining"]
ratelimit_reset = resp.headers["X-RateLimit-Reset"]
tweets = json.loads(resp.read())
return ratelimit_remaining, tweets
def get_initial_rate_info():
|
def fetch_url(url):
try:
return urlopen(Request(url))
except HTTPError, e:
if e.code == 400: # twitter api limit reached
raise RateLimitError(e.code)
if e.code == 502: # Bad Gateway, sometimes get this when making requests. just try again
raise TweetDumpError(e.code)
print >> sys.stderr, "[!] HTTP Error %s: %s" % (e.code, e.msg)
except URLError, e:
print >> sys.stderr, "[!] URL Error: %s URL: %s" % (e.reason, url)
exit(1)
def print_banner():
print "tweet-dump %s (c) 2012 %s" % (__version__, __author__)
print """ .-.
(. .)__,')
/ V )
\ ( \/ .
`._`.__\\ o ,
<< `' .o..
"""
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="tweet-dump")
parser.add_argument('username', help="Twitter Screen Name")
parser.add_argument('file', help="File to write tweeets to")
parser.add_argument('--count', help="Number of tweets to retrieve per request", default=200)
parser.add_argument('--maxid', help="ID of Tweet to start dumping after", default=None)
args = parser.parse_args()
screen_name = args.username
count = args.count
maxid = args.maxid
out_file_name = args.file
out_file = None
try:
out_file = open(out_file_name, 'w')
except IOError, e:
print >> sys.stderr, "[!] error creating file %s" % out_file_name
exit(1)
print_banner()
print "[*] writing tweets to %s \n[*] dumping tweets for user %s" % (out_file_name, screen_name)
#print "[*] dumping tweets for user %s" % screen_name,
max_requests = 5
requests_made = 0
tweet_count = 0
while True:
# get initial rate information
(remaining, rst_time_s, rst_time) = get_initial_rate_info()
while remaining > 0:
try:
(remaining, tweets) = get_tweets(screen_name, count, maxid)
except RateLimitError:
pass
except TweetDumpError, e:
pass
else:
requests_made += 1
if len(tweets) > 0:
for tweet in tweets:
maxid = tweet["id"]
out_file.write(u"%s %s: %s\n" % (tweet["created_at"], maxid, repr(tweet["text"])))
tweet_count += 1
else:
print "[*] reached end of tweets"
break
break
print "[*] %d tweets dumped!" % tweet_count
| resp = fetch_url(RATE_LIMIT_API_URL)
rate_info = json.loads(resp.read())
return rate_info["remaining_hits"], rate_info["reset_time_in_seconds"], rate_info["reset_time"] | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.