file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
SearchUtility.js | /** @flow */
import { INDEX_MODES } from "./constants";
import SearchIndex from "./SearchIndex";
import type { IndexMode } from "./constants";
import type { SearchApiIndex } from "../types";
type UidMap = {
[uid: string]: boolean
};
/**
* Synchronous client-side full-text search utility.
* Forked from JS search (github.com/bvaughn/js-search).
*/
export default class SearchUtility implements SearchApiIndex {
_caseSensitive: boolean;
_indexMode: IndexMode;
_matchAnyToken: boolean;
_searchIndex: SearchIndex;
_tokenizePattern: RegExp;
_uids: UidMap;
/**
* Constructor.
*
* @param indexMode See #setIndexMode
* @param tokenizePattern See #setTokenizePattern
* @param caseSensitive See #setCaseSensitive
* @param matchAnyToken See #setMatchAnyToken
*/
constructor(
{
caseSensitive = false,
indexMode = INDEX_MODES.ALL_SUBSTRINGS,
matchAnyToken = false,
tokenizePattern = /\s+/
}: {
caseSensitive?: boolean,
indexMode?: IndexMode,
matchAnyToken?: boolean,
tokenizePattern?: RegExp
} = {}
) {
this._caseSensitive = caseSensitive;
this._indexMode = indexMode;
this._matchAnyToken = matchAnyToken;
this._tokenizePattern = tokenizePattern;
this._searchIndex = new SearchIndex();
this._uids = {};
}
/**
* Returns a constant representing the current case-sensitive bit.
*/
getCaseSensitive(): boolean {
return this._caseSensitive;
}
/**
* Returns a constant representing the current index mode.
*/
getIndexMode(): string {
return this._indexMode;
}
/**
* Returns a constant representing the current match-any-token bit.
*/
getMatchAnyToken(): boolean {
return this._matchAnyToken;
}
/**
* Returns a constant representing the current tokenize pattern.
*/
getTokenizePattern(): RegExp {
return this._tokenizePattern;
}
/**
* Adds or updates a uid in the search index and associates it with the specified text.
* Note that at this time uids can only be added or updated in the index, not removed.
*
* @param uid Uniquely identifies a searchable object
* @param text Text to associate with uid
*/
indexDocument = (uid: any, text: string): SearchApiIndex => {
this._uids[uid] = true;
var fieldTokens: Array<string> = this._tokenize(this._sanitize(text));
fieldTokens.forEach(fieldToken => {
var expandedTokens: Array<string> = this._expandToken(fieldToken);
expandedTokens.forEach(expandedToken => {
this._searchIndex.indexDocument(expandedToken, uid);
});
});
return this;
};
/**
* Searches the current index for the specified query text.
* Only uids matching all of the words within the text will be accepted,
* unless matchAny is set to true.
* If an empty query string is provided all indexed uids will be returned.
*
* Document searches are case-insensitive by default (e.g. "search" will match "Search").
* Document searches use substring matching by default (e.g. "na" and "me" will both match "name").
*
* @param query Searchable query text
* @return Array of uids
*/
search = (query: string): Array<any> => { | var tokens: Array<string> = this._tokenize(this._sanitize(query));
return this._searchIndex.search(tokens, this._matchAnyToken);
}
};
/**
* Sets a new case-sensitive bit
*/
setCaseSensitive(caseSensitive: boolean): void {
this._caseSensitive = caseSensitive;
}
/**
* Sets a new index mode.
* See util/constants/INDEX_MODES
*/
setIndexMode(indexMode: IndexMode): void {
if (Object.keys(this._uids).length > 0) {
throw Error(
"indexMode cannot be changed once documents have been indexed"
);
}
this._indexMode = indexMode;
}
/**
* Sets a new match-any-token bit
*/
setMatchAnyToken(matchAnyToken: boolean): void {
this._matchAnyToken = matchAnyToken;
}
/**
* Sets a new tokenize pattern (regular expression)
*/
setTokenizePattern(pattern: RegExp): void {
this._tokenizePattern = pattern;
}
/**
* Added to make class adhere to interface. Add cleanup code as needed.
*/
terminate = () => {};
/**
* Index strategy based on 'all-substrings-index-strategy.ts' in github.com/bvaughn/js-search/
*
* @private
*/
_expandToken(token: string): Array<string> {
switch (this._indexMode) {
case INDEX_MODES.EXACT_WORDS:
return [token];
case INDEX_MODES.PREFIXES:
return this._expandPrefixTokens(token);
case INDEX_MODES.ALL_SUBSTRINGS:
default:
return this._expandAllSubstringTokens(token);
}
}
_expandAllSubstringTokens(token: string): Array<string> {
const expandedTokens = [];
// String.prototype.charAt() may return surrogate halves instead of whole characters.
// When this happens in the context of a web-worker it can cause Chrome to crash.
// Catching the error is a simple solution for now; in the future I may try to better support non-BMP characters.
// Resources:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
// https://mathiasbynens.be/notes/javascript-unicode
try {
for (let i = 0, length = token.length; i < length; ++i) {
let substring: string = "";
for (let j = i; j < length; ++j) {
substring += token.charAt(j);
expandedTokens.push(substring);
}
}
} catch (error) {
console.error(`Unable to parse token "${token}" ${error}`);
}
return expandedTokens;
}
_expandPrefixTokens(token: string): Array<string> {
const expandedTokens = [];
// String.prototype.charAt() may return surrogate halves instead of whole characters.
// When this happens in the context of a web-worker it can cause Chrome to crash.
// Catching the error is a simple solution for now; in the future I may try to better support non-BMP characters.
// Resources:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
// https://mathiasbynens.be/notes/javascript-unicode
try {
for (let i = 0, length = token.length; i < length; ++i) {
expandedTokens.push(token.substr(0, i + 1));
}
} catch (error) {
console.error(`Unable to parse token "${token}" ${error}`);
}
return expandedTokens;
}
/**
* @private
*/
_sanitize(string: string): string {
return this._caseSensitive
? string.trim()
: string.trim().toLocaleLowerCase();
}
/**
* @private
*/
_tokenize(text: string): Array<string> {
return text.split(this._tokenizePattern).filter(text => text); // Remove empty tokens
}
} | if (!query) {
return Object.keys(this._uids);
} else { | random_line_split |
SearchUtility.js | /** @flow */
import { INDEX_MODES } from "./constants";
import SearchIndex from "./SearchIndex";
import type { IndexMode } from "./constants";
import type { SearchApiIndex } from "../types";
type UidMap = {
[uid: string]: boolean
};
/**
* Synchronous client-side full-text search utility.
* Forked from JS search (github.com/bvaughn/js-search).
*/
export default class SearchUtility implements SearchApiIndex {
_caseSensitive: boolean;
_indexMode: IndexMode;
_matchAnyToken: boolean;
_searchIndex: SearchIndex;
_tokenizePattern: RegExp;
_uids: UidMap;
/**
* Constructor.
*
* @param indexMode See #setIndexMode
* @param tokenizePattern See #setTokenizePattern
* @param caseSensitive See #setCaseSensitive
* @param matchAnyToken See #setMatchAnyToken
*/
constructor(
{
caseSensitive = false,
indexMode = INDEX_MODES.ALL_SUBSTRINGS,
matchAnyToken = false,
tokenizePattern = /\s+/
}: {
caseSensitive?: boolean,
indexMode?: IndexMode,
matchAnyToken?: boolean,
tokenizePattern?: RegExp
} = {}
) {
this._caseSensitive = caseSensitive;
this._indexMode = indexMode;
this._matchAnyToken = matchAnyToken;
this._tokenizePattern = tokenizePattern;
this._searchIndex = new SearchIndex();
this._uids = {};
}
/**
* Returns a constant representing the current case-sensitive bit.
*/
getCaseSensitive(): boolean {
return this._caseSensitive;
}
/**
* Returns a constant representing the current index mode.
*/
getIndexMode(): string {
return this._indexMode;
}
/**
* Returns a constant representing the current match-any-token bit.
*/
getMatchAnyToken(): boolean {
return this._matchAnyToken;
}
/**
* Returns a constant representing the current tokenize pattern.
*/
getTokenizePattern(): RegExp {
return this._tokenizePattern;
}
/**
* Adds or updates a uid in the search index and associates it with the specified text.
* Note that at this time uids can only be added or updated in the index, not removed.
*
* @param uid Uniquely identifies a searchable object
* @param text Text to associate with uid
*/
indexDocument = (uid: any, text: string): SearchApiIndex => {
this._uids[uid] = true;
var fieldTokens: Array<string> = this._tokenize(this._sanitize(text));
fieldTokens.forEach(fieldToken => {
var expandedTokens: Array<string> = this._expandToken(fieldToken);
expandedTokens.forEach(expandedToken => {
this._searchIndex.indexDocument(expandedToken, uid);
});
});
return this;
};
/**
* Searches the current index for the specified query text.
* Only uids matching all of the words within the text will be accepted,
* unless matchAny is set to true.
* If an empty query string is provided all indexed uids will be returned.
*
* Document searches are case-insensitive by default (e.g. "search" will match "Search").
* Document searches use substring matching by default (e.g. "na" and "me" will both match "name").
*
* @param query Searchable query text
* @return Array of uids
*/
search = (query: string): Array<any> => {
if (!query) {
return Object.keys(this._uids);
} else {
var tokens: Array<string> = this._tokenize(this._sanitize(query));
return this._searchIndex.search(tokens, this._matchAnyToken);
}
};
/**
* Sets a new case-sensitive bit
*/
setCaseSensitive(caseSensitive: boolean): void {
this._caseSensitive = caseSensitive;
}
/**
* Sets a new index mode.
* See util/constants/INDEX_MODES
*/
setIndexMode(indexMode: IndexMode): void {
if (Object.keys(this._uids).length > 0) {
throw Error(
"indexMode cannot be changed once documents have been indexed"
);
}
this._indexMode = indexMode;
}
/**
* Sets a new match-any-token bit
*/
setMatchAnyToken(matchAnyToken: boolean): void {
this._matchAnyToken = matchAnyToken;
}
/**
* Sets a new tokenize pattern (regular expression)
*/
setTokenizePattern(pattern: RegExp): void {
this._tokenizePattern = pattern;
}
/**
* Added to make class adhere to interface. Add cleanup code as needed.
*/
terminate = () => {};
/**
* Index strategy based on 'all-substrings-index-strategy.ts' in github.com/bvaughn/js-search/
*
* @private
*/
_expandToken(token: string): Array<string> {
| (this._indexMode) {
case INDEX_MODES.EXACT_WORDS:
return [token];
case INDEX_MODES.PREFIXES:
return this._expandPrefixTokens(token);
case INDEX_MODES.ALL_SUBSTRINGS:
default:
return this._expandAllSubstringTokens(token);
}
}
_expandAllSubstringTokens(token: string): Array<string> {
const expandedTokens = [];
// String.prototype.charAt() may return surrogate halves instead of whole characters.
// When this happens in the context of a web-worker it can cause Chrome to crash.
// Catching the error is a simple solution for now; in the future I may try to better support non-BMP characters.
// Resources:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
// https://mathiasbynens.be/notes/javascript-unicode
try {
for (let i = 0, length = token.length; i < length; ++i) {
let substring: string = "";
for (let j = i; j < length; ++j) {
substring += token.charAt(j);
expandedTokens.push(substring);
}
}
} catch (error) {
console.error(`Unable to parse token "${token}" ${error}`);
}
return expandedTokens;
}
_expandPrefixTokens(token: string): Array<string> {
const expandedTokens = [];
// String.prototype.charAt() may return surrogate halves instead of whole characters.
// When this happens in the context of a web-worker it can cause Chrome to crash.
// Catching the error is a simple solution for now; in the future I may try to better support non-BMP characters.
// Resources:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt
// https://mathiasbynens.be/notes/javascript-unicode
try {
for (let i = 0, length = token.length; i < length; ++i) {
expandedTokens.push(token.substr(0, i + 1));
}
} catch (error) {
console.error(`Unable to parse token "${token}" ${error}`);
}
return expandedTokens;
}
/**
* @private
*/
_sanitize(string: string): string {
return this._caseSensitive
? string.trim()
: string.trim().toLocaleLowerCase();
}
/**
* @private
*/
_tokenize(text: string): Array<string> {
return text.split(this._tokenizePattern).filter(text => text); // Remove empty tokens
}
}
| switch | identifier_name |
unban.py | from sigma.core.permission import check_ban
import discord
async def un | md, message, args):
channel = message.channel
if args:
user_q = args[0]
if message.author is not user_q:
if check_ban(message.author, channel):
ban_list = await message.guild.bans()
target_user = None
for user in ban_list:
if user.name.lower() == user_q.lower():
target_user = user
break
if target_user:
await cmd.bot.unban(message.guild, target_user)
out_content = discord.Embed(type='rich', color=0x66CC66,
title='✅ ' + target_user.name + 'Unbanned.')
await message.channel.send(None, embed=out_content)
else:
out_content = discord.Embed(type='rich', color=0xFF9900,
title='⚠ User Not Found In Ban List.')
await message.channel.send(None, embed=out_content)
else:
out_content = discord.Embed(type='rich', color=0xDB0000,
title='⛔ Insufficient Permissions. Ban Permission Required.')
await message.channel.send(None, embed=out_content)
else:
await message.channel.send(cmd.help())
| ban(c | identifier_name |
unban.py | from sigma.core.permission import check_ban
import discord
async def unban(cmd, message, args):
channel = message.channel
if args:
user_q = args[0]
if message.author is not user_q:
if check_ban(message.author, channel):
ban_list = await message.guild.bans()
target_user = None
for user in ban_list:
if user.name.lower() == user_q.lower():
target_user = user
break
if target_user:
await cmd.bot.unban(message.guild, target_user)
out_content = discord.Embed(type='rich', color=0x66CC66,
title='✅ ' + target_user.name + 'Unbanned.')
await message.channel.send(None, embed=out_content) | await message.channel.send(None, embed=out_content)
else:
out_content = discord.Embed(type='rich', color=0xDB0000,
title='⛔ Insufficient Permissions. Ban Permission Required.')
await message.channel.send(None, embed=out_content)
else:
await message.channel.send(cmd.help()) | else:
out_content = discord.Embed(type='rich', color=0xFF9900,
title='⚠ User Not Found In Ban List.') | random_line_split |
unban.py | from sigma.core.permission import check_ban
import discord
async def unban(cmd, message, args):
channel = message.channel
if args:
user_q = args[0]
if message.author is not user_q:
if | e:
await message.channel.send(cmd.help())
| check_ban(message.author, channel):
ban_list = await message.guild.bans()
target_user = None
for user in ban_list:
if user.name.lower() == user_q.lower():
target_user = user
break
if target_user:
await cmd.bot.unban(message.guild, target_user)
out_content = discord.Embed(type='rich', color=0x66CC66,
title='✅ ' + target_user.name + 'Unbanned.')
await message.channel.send(None, embed=out_content)
else:
out_content = discord.Embed(type='rich', color=0xFF9900,
title='⚠ User Not Found In Ban List.')
await message.channel.send(None, embed=out_content)
else:
out_content = discord.Embed(type='rich', color=0xDB0000,
title='⛔ Insufficient Permissions. Ban Permission Required.')
await message.channel.send(None, embed=out_content)
els | conditional_block |
unban.py | from sigma.core.permission import check_ban
import discord
async def unban(cmd, message, args):
ch | annel = message.channel
if args:
user_q = args[0]
if message.author is not user_q:
if check_ban(message.author, channel):
ban_list = await message.guild.bans()
target_user = None
for user in ban_list:
if user.name.lower() == user_q.lower():
target_user = user
break
if target_user:
await cmd.bot.unban(message.guild, target_user)
out_content = discord.Embed(type='rich', color=0x66CC66,
title='✅ ' + target_user.name + 'Unbanned.')
await message.channel.send(None, embed=out_content)
else:
out_content = discord.Embed(type='rich', color=0xFF9900,
title='⚠ User Not Found In Ban List.')
await message.channel.send(None, embed=out_content)
else:
out_content = discord.Embed(type='rich', color=0xDB0000,
title='⛔ Insufficient Permissions. Ban Permission Required.')
await message.channel.send(None, embed=out_content)
else:
await message.channel.send(cmd.help())
| identifier_body | |
_walker.py | from typing import Iterable, Callable, Optional, Any, List, Iterator
from dupescan.fs._fileentry import FileEntry
from dupescan.fs._root import Root
from dupescan.types import AnyPath
FSPredicate = Callable[[FileEntry], bool]
ErrorHandler = Callable[[EnvironmentError], Any]
def catch_filter(inner_filter: FSPredicate, error_handler_func: ErrorHandler) -> FSPredicate:
# If no filter function provided, return one that includes everything. In
# this case it will never raise an error, so error_handler_func doesn't get
# a look-in here
if inner_filter is None:
def always_true(*args, **kwargs):
return True
return always_true
# Otherwise if the filter function throws an EnvironmentError, pass it to
# the error_handler_func (if provided) and return false
def wrapped_func(*args, **kwargs):
try:
return inner_filter(*args, **kwargs)
except EnvironmentError as env_error:
if error_handler_func is not None:
error_handler_func(env_error)
return False
return wrapped_func
def noerror(_):
pass
class Walker(object):
def __init__(
self,
recursive: bool,
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
):
self._recursive = bool(recursive)
self._onerror = noerror if onerror is None else onerror
self._dir_filter = catch_filter(dir_object_filter, self._onerror)
self._file_filter = catch_filter(file_object_filter, self._onerror)
def __call__(self, paths: Iterable[AnyPath]) -> Iterator[FileEntry]:
for root_index, root_path in enumerate(paths):
root_spec = Root(root_path, root_index)
try:
root_obj = FileEntry.from_path(root_path, root_spec)
except EnvironmentError as env_error:
self._onerror(env_error)
continue
if root_obj.is_dir and self._dir_filter(root_obj):
if self._recursive:
yield from self._recurse_dir(root_obj)
else:
yield root_obj
elif root_obj.is_file and self._file_filter(root_obj):
yield root_obj
def _recurse_dir(self, root_obj: FileEntry):
|
def flat_iterator(
paths: Iterable[AnyPath],
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
) -> Iterator[FileEntry]:
return Walker(False, dir_object_filter, file_object_filter, onerror)(paths)
def recurse_iterator(
paths: Iterable[AnyPath],
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
) -> Iterator[FileEntry]:
return Walker(True, dir_object_filter, file_object_filter, onerror)(paths)
| dir_obj_q: List[FileEntry] = [ root_obj ]
next_dirs: List[FileEntry] = [ ]
while len(dir_obj_q) > 0:
dir_obj = dir_obj_q.pop()
next_dirs.clear()
try:
for child_obj in dir_obj.dir_content():
try:
if (
child_obj.is_dir and
not child_obj.is_symlink and
self._dir_filter(child_obj)
):
next_dirs.append(child_obj)
elif (
child_obj.is_file and
self._file_filter(child_obj)
):
yield child_obj
except EnvironmentError as query_error:
self._onerror(query_error)
except EnvironmentError as env_error:
self._onerror(env_error)
dir_obj_q.extend(reversed(next_dirs)) | identifier_body |
_walker.py | from typing import Iterable, Callable, Optional, Any, List, Iterator
from dupescan.fs._fileentry import FileEntry
from dupescan.fs._root import Root
from dupescan.types import AnyPath
FSPredicate = Callable[[FileEntry], bool]
ErrorHandler = Callable[[EnvironmentError], Any]
def catch_filter(inner_filter: FSPredicate, error_handler_func: ErrorHandler) -> FSPredicate:
# If no filter function provided, return one that includes everything. In
# this case it will never raise an error, so error_handler_func doesn't get
# a look-in here
if inner_filter is None:
def always_true(*args, **kwargs):
return True
return always_true
# Otherwise if the filter function throws an EnvironmentError, pass it to
# the error_handler_func (if provided) and return false
def wrapped_func(*args, **kwargs):
try:
return inner_filter(*args, **kwargs)
except EnvironmentError as env_error:
if error_handler_func is not None:
error_handler_func(env_error)
return False
return wrapped_func
def noerror(_):
pass
class Walker(object):
def __init__(
self,
recursive: bool,
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
):
self._recursive = bool(recursive)
self._onerror = noerror if onerror is None else onerror
self._dir_filter = catch_filter(dir_object_filter, self._onerror)
self._file_filter = catch_filter(file_object_filter, self._onerror)
def __call__(self, paths: Iterable[AnyPath]) -> Iterator[FileEntry]:
for root_index, root_path in enumerate(paths):
root_spec = Root(root_path, root_index)
try:
root_obj = FileEntry.from_path(root_path, root_spec)
except EnvironmentError as env_error:
self._onerror(env_error)
continue
if root_obj.is_dir and self._dir_filter(root_obj):
if self._recursive:
yield from self._recurse_dir(root_obj)
else:
yield root_obj
elif root_obj.is_file and self._file_filter(root_obj):
yield root_obj
def _recurse_dir(self, root_obj: FileEntry):
dir_obj_q: List[FileEntry] = [ root_obj ]
next_dirs: List[FileEntry] = [ ]
while len(dir_obj_q) > 0:
dir_obj = dir_obj_q.pop()
next_dirs.clear()
try:
for child_obj in dir_obj.dir_content():
try:
if (
child_obj.is_dir and
not child_obj.is_symlink and
self._dir_filter(child_obj)
):
next_dirs.append(child_obj) | child_obj.is_file and
self._file_filter(child_obj)
):
yield child_obj
except EnvironmentError as query_error:
self._onerror(query_error)
except EnvironmentError as env_error:
self._onerror(env_error)
dir_obj_q.extend(reversed(next_dirs))
def flat_iterator(
paths: Iterable[AnyPath],
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
) -> Iterator[FileEntry]:
return Walker(False, dir_object_filter, file_object_filter, onerror)(paths)
def recurse_iterator(
paths: Iterable[AnyPath],
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
) -> Iterator[FileEntry]:
return Walker(True, dir_object_filter, file_object_filter, onerror)(paths) |
elif ( | random_line_split |
_walker.py | from typing import Iterable, Callable, Optional, Any, List, Iterator
from dupescan.fs._fileentry import FileEntry
from dupescan.fs._root import Root
from dupescan.types import AnyPath
FSPredicate = Callable[[FileEntry], bool]
ErrorHandler = Callable[[EnvironmentError], Any]
def catch_filter(inner_filter: FSPredicate, error_handler_func: ErrorHandler) -> FSPredicate:
# If no filter function provided, return one that includes everything. In
# this case it will never raise an error, so error_handler_func doesn't get
# a look-in here
if inner_filter is None:
def always_true(*args, **kwargs):
return True
return always_true
# Otherwise if the filter function throws an EnvironmentError, pass it to
# the error_handler_func (if provided) and return false
def wrapped_func(*args, **kwargs):
try:
return inner_filter(*args, **kwargs)
except EnvironmentError as env_error:
if error_handler_func is not None:
error_handler_func(env_error)
return False
return wrapped_func
def noerror(_):
pass
class Walker(object):
def __init__(
self,
recursive: bool,
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
):
self._recursive = bool(recursive)
self._onerror = noerror if onerror is None else onerror
self._dir_filter = catch_filter(dir_object_filter, self._onerror)
self._file_filter = catch_filter(file_object_filter, self._onerror)
def __call__(self, paths: Iterable[AnyPath]) -> Iterator[FileEntry]:
for root_index, root_path in enumerate(paths):
root_spec = Root(root_path, root_index)
try:
root_obj = FileEntry.from_path(root_path, root_spec)
except EnvironmentError as env_error:
self._onerror(env_error)
continue
if root_obj.is_dir and self._dir_filter(root_obj):
if self._recursive:
yield from self._recurse_dir(root_obj)
else:
yield root_obj
elif root_obj.is_file and self._file_filter(root_obj):
yield root_obj
def _recurse_dir(self, root_obj: FileEntry):
dir_obj_q: List[FileEntry] = [ root_obj ]
next_dirs: List[FileEntry] = [ ]
while len(dir_obj_q) > 0:
dir_obj = dir_obj_q.pop()
next_dirs.clear()
try:
for child_obj in dir_obj.dir_content():
try:
if (
child_obj.is_dir and
not child_obj.is_symlink and
self._dir_filter(child_obj)
):
next_dirs.append(child_obj)
elif (
child_obj.is_file and
self._file_filter(child_obj)
):
|
except EnvironmentError as query_error:
self._onerror(query_error)
except EnvironmentError as env_error:
self._onerror(env_error)
dir_obj_q.extend(reversed(next_dirs))
def flat_iterator(
paths: Iterable[AnyPath],
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
) -> Iterator[FileEntry]:
return Walker(False, dir_object_filter, file_object_filter, onerror)(paths)
def recurse_iterator(
paths: Iterable[AnyPath],
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
) -> Iterator[FileEntry]:
return Walker(True, dir_object_filter, file_object_filter, onerror)(paths)
| yield child_obj | conditional_block |
_walker.py | from typing import Iterable, Callable, Optional, Any, List, Iterator
from dupescan.fs._fileentry import FileEntry
from dupescan.fs._root import Root
from dupescan.types import AnyPath
FSPredicate = Callable[[FileEntry], bool]
ErrorHandler = Callable[[EnvironmentError], Any]
def catch_filter(inner_filter: FSPredicate, error_handler_func: ErrorHandler) -> FSPredicate:
# If no filter function provided, return one that includes everything. In
# this case it will never raise an error, so error_handler_func doesn't get
# a look-in here
if inner_filter is None:
def always_true(*args, **kwargs):
return True
return always_true
# Otherwise if the filter function throws an EnvironmentError, pass it to
# the error_handler_func (if provided) and return false
def wrapped_func(*args, **kwargs):
try:
return inner_filter(*args, **kwargs)
except EnvironmentError as env_error:
if error_handler_func is not None:
error_handler_func(env_error)
return False
return wrapped_func
def noerror(_):
pass
class Walker(object):
def __init__(
self,
recursive: bool,
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
):
self._recursive = bool(recursive)
self._onerror = noerror if onerror is None else onerror
self._dir_filter = catch_filter(dir_object_filter, self._onerror)
self._file_filter = catch_filter(file_object_filter, self._onerror)
def __call__(self, paths: Iterable[AnyPath]) -> Iterator[FileEntry]:
for root_index, root_path in enumerate(paths):
root_spec = Root(root_path, root_index)
try:
root_obj = FileEntry.from_path(root_path, root_spec)
except EnvironmentError as env_error:
self._onerror(env_error)
continue
if root_obj.is_dir and self._dir_filter(root_obj):
if self._recursive:
yield from self._recurse_dir(root_obj)
else:
yield root_obj
elif root_obj.is_file and self._file_filter(root_obj):
yield root_obj
def _recurse_dir(self, root_obj: FileEntry):
dir_obj_q: List[FileEntry] = [ root_obj ]
next_dirs: List[FileEntry] = [ ]
while len(dir_obj_q) > 0:
dir_obj = dir_obj_q.pop()
next_dirs.clear()
try:
for child_obj in dir_obj.dir_content():
try:
if (
child_obj.is_dir and
not child_obj.is_symlink and
self._dir_filter(child_obj)
):
next_dirs.append(child_obj)
elif (
child_obj.is_file and
self._file_filter(child_obj)
):
yield child_obj
except EnvironmentError as query_error:
self._onerror(query_error)
except EnvironmentError as env_error:
self._onerror(env_error)
dir_obj_q.extend(reversed(next_dirs))
def flat_iterator(
paths: Iterable[AnyPath],
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
) -> Iterator[FileEntry]:
return Walker(False, dir_object_filter, file_object_filter, onerror)(paths)
def | (
paths: Iterable[AnyPath],
dir_object_filter: Optional[FSPredicate]=None,
file_object_filter: Optional[FSPredicate]=None,
onerror: Optional[ErrorHandler]=None
) -> Iterator[FileEntry]:
return Walker(True, dir_object_filter, file_object_filter, onerror)(paths)
| recurse_iterator | identifier_name |
controller.js | define([
'angular',
'../module',
'../service',
'common/services/bootstrap',
], function(angular, lazyModule, service, bootstrapService) {
'use strict';
| /**
* [homeController description]
* @param {[type]} $scope [description]
* @param {[type]} homeService [description]
* @return {[type]} [description]
*/
lazyModule.controller('ContentController', ['$scope', '$modal', '$rootScope', 'HomeService', 'ModalService',
function($scope, $modal, $rootScope, homeService, modalService) {
var self = this;
$rootScope.pageTitle = 'home';
/**
* [pageLoad description]
* @return {[type]} [description]
*/
self.pageLoad = function() {
homeService.getData().success(function(response) {
$scope.awesomeThings = response.data;
});
};
self.pageLoad();
}
]);
}); | random_line_split | |
convert.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for conversions between types.
//!
//! The traits in this module provide a general way to talk about conversions
//! from one type to another. They follow the standard Rust conventions of
//! `as`/`into`/`from`.
//!
//! Like many traits, these are often used as bounds for generic functions, to
//! support arguments of multiple types.
//!
//! See each trait for usage examples.
#![stable(feature = "rust1", since = "1.0.0")]
use marker::Sized;
/// A cheap, reference-to-reference conversion.
///
/// `AsRef` is very similar to, but different than, `Borrow`. See
/// [the book][book] for more.
///
/// [book]: ../../book/borrow-and-asref.html
///
/// # Examples
///
/// Both `String` and `&str` implement `AsRef<str>`:
///
/// ```
/// fn is_hello<T: AsRef<str>>(s: T) {
/// assert_eq!("hello", s.as_ref());
/// }
///
/// let s = "hello";
/// is_hello(s);
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T: ?Sized> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_ref(&self) -> &T;
}
/// A cheap, mutable reference-to-mutable reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsMut<T: ?Sized> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_mut(&mut self) -> &mut T;
}
/// A conversion that consumes `self`, which may or may not be expensive.
///
/// # Examples
///
/// `String` implements `Into<Vec<u8>>`:
///
/// ```
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
/// let bytes = b"hello".to_vec();
/// assert_eq!(bytes, s.into());
/// }
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn into(self) -> T;
}
/// Construct `Self` via a conversion.
///
/// # Examples
///
/// `String` implements `From<&str>`:
///
/// ```
/// let string = "hello".to_string();
/// let other_string = String::from("hello");
///
/// assert_eq!(string, other_string);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait From<T>: Sized {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn from(T) -> Self;
}
////////////////////////////////////////////////////////////////////////////////
// GENERIC IMPLS
////////////////////////////////////////////////////////////////////////////////
// As lifts over &
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
// As lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
// FIXME (#23442): replace the above impls for &/&mut with the following more general one:
// // As lifts over Deref
// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
// fn as_ref(&self) -> &U {
// self.deref().as_ref()
// }
// }
// AsMut lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
fn as_mut(&mut self) -> &mut U |
}
// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
// fn as_mut(&mut self) -> &mut U {
// self.deref_mut().as_mut()
// }
// }
// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
fn into(self) -> U {
U::from(self)
}
}
// From (and thus Into) is reflexive
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<T> for T {
fn from(t: T) -> T { t }
}
////////////////////////////////////////////////////////////////////////////////
// CONCRETE IMPLS
////////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T] {
fn as_ref(&self) -> &[T] {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T] {
fn as_mut(&mut self) -> &mut [T] {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for str {
#[inline]
fn as_ref(&self) -> &str {
self
}
}
| {
(*self).as_mut()
} | identifier_body |
convert.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for conversions between types.
//!
//! The traits in this module provide a general way to talk about conversions
//! from one type to another. They follow the standard Rust conventions of
//! `as`/`into`/`from`.
//!
//! Like many traits, these are often used as bounds for generic functions, to
//! support arguments of multiple types.
//!
//! See each trait for usage examples.
#![stable(feature = "rust1", since = "1.0.0")]
use marker::Sized;
/// A cheap, reference-to-reference conversion.
///
/// `AsRef` is very similar to, but different than, `Borrow`. See
/// [the book][book] for more.
///
/// [book]: ../../book/borrow-and-asref.html
///
/// # Examples
///
/// Both `String` and `&str` implement `AsRef<str>`:
///
/// ```
/// fn is_hello<T: AsRef<str>>(s: T) {
/// assert_eq!("hello", s.as_ref());
/// }
///
/// let s = "hello";
/// is_hello(s);
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T: ?Sized> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_ref(&self) -> &T;
}
/// A cheap, mutable reference-to-mutable reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsMut<T: ?Sized> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_mut(&mut self) -> &mut T;
}
/// A conversion that consumes `self`, which may or may not be expensive.
///
/// # Examples
///
/// `String` implements `Into<Vec<u8>>`:
///
/// ```
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
/// let bytes = b"hello".to_vec();
/// assert_eq!(bytes, s.into());
/// }
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn into(self) -> T;
}
/// Construct `Self` via a conversion.
///
/// # Examples
///
/// `String` implements `From<&str>`:
///
/// ```
/// let string = "hello".to_string();
/// let other_string = String::from("hello");
///
/// assert_eq!(string, other_string);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait From<T>: Sized {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn from(T) -> Self;
}
////////////////////////////////////////////////////////////////////////////////
// GENERIC IMPLS
////////////////////////////////////////////////////////////////////////////////
// As lifts over &
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
// As lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
// FIXME (#23442): replace the above impls for &/&mut with the following more general one:
// // As lifts over Deref
// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
// fn as_ref(&self) -> &U {
// self.deref().as_ref()
// }
// }
// AsMut lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
fn | (&mut self) -> &mut U {
(*self).as_mut()
}
}
// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
// fn as_mut(&mut self) -> &mut U {
// self.deref_mut().as_mut()
// }
// }
// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
fn into(self) -> U {
U::from(self)
}
}
// From (and thus Into) is reflexive
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<T> for T {
fn from(t: T) -> T { t }
}
////////////////////////////////////////////////////////////////////////////////
// CONCRETE IMPLS
////////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T] {
fn as_ref(&self) -> &[T] {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T] {
fn as_mut(&mut self) -> &mut [T] {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for str {
#[inline]
fn as_ref(&self) -> &str {
self
}
}
| as_mut | identifier_name |
convert.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for conversions between types.
//!
//! The traits in this module provide a general way to talk about conversions
//! from one type to another. They follow the standard Rust conventions of
//! `as`/`into`/`from`.
//!
//! Like many traits, these are often used as bounds for generic functions, to
//! support arguments of multiple types.
//!
//! See each trait for usage examples.
#![stable(feature = "rust1", since = "1.0.0")]
use marker::Sized;
/// A cheap, reference-to-reference conversion.
///
/// `AsRef` is very similar to, but different than, `Borrow`. See
/// [the book][book] for more.
///
/// [book]: ../../book/borrow-and-asref.html | /// Both `String` and `&str` implement `AsRef<str>`:
///
/// ```
/// fn is_hello<T: AsRef<str>>(s: T) {
/// assert_eq!("hello", s.as_ref());
/// }
///
/// let s = "hello";
/// is_hello(s);
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T: ?Sized> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_ref(&self) -> &T;
}
/// A cheap, mutable reference-to-mutable reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsMut<T: ?Sized> {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_mut(&mut self) -> &mut T;
}
/// A conversion that consumes `self`, which may or may not be expensive.
///
/// # Examples
///
/// `String` implements `Into<Vec<u8>>`:
///
/// ```
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
/// let bytes = b"hello".to_vec();
/// assert_eq!(bytes, s.into());
/// }
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn into(self) -> T;
}
/// Construct `Self` via a conversion.
///
/// # Examples
///
/// `String` implements `From<&str>`:
///
/// ```
/// let string = "hello".to_string();
/// let other_string = String::from("hello");
///
/// assert_eq!(string, other_string);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait From<T>: Sized {
/// Performs the conversion.
#[stable(feature = "rust1", since = "1.0.0")]
fn from(T) -> Self;
}
////////////////////////////////////////////////////////////////////////////////
// GENERIC IMPLS
////////////////////////////////////////////////////////////////////////////////
// As lifts over &
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
// As lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
// FIXME (#23442): replace the above impls for &/&mut with the following more general one:
// // As lifts over Deref
// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
// fn as_ref(&self) -> &U {
// self.deref().as_ref()
// }
// }
// AsMut lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
fn as_mut(&mut self) -> &mut U {
(*self).as_mut()
}
}
// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
// fn as_mut(&mut self) -> &mut U {
// self.deref_mut().as_mut()
// }
// }
// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
fn into(self) -> U {
U::from(self)
}
}
// From (and thus Into) is reflexive
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<T> for T {
fn from(t: T) -> T { t }
}
////////////////////////////////////////////////////////////////////////////////
// CONCRETE IMPLS
////////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T] {
fn as_ref(&self) -> &[T] {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T] {
fn as_mut(&mut self) -> &mut [T] {
self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for str {
#[inline]
fn as_ref(&self) -> &str {
self
}
} | ///
/// # Examples
/// | random_line_split |
dirichlet.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The dirichlet distribution.
#![cfg(feature = "alloc")]
use num_traits::Float;
use crate::{Distribution, Exp1, Gamma, Open01, StandardNormal};
use rand::Rng;
use core::fmt;
use alloc::{boxed::Box, vec, vec::Vec};
/// The Dirichlet distribution `Dirichlet(alpha)`.
///
/// The Dirichlet distribution is a family of continuous multivariate
/// probability distributions parameterized by a vector alpha of positive reals.
/// It is a multivariate generalization of the beta distribution.
/// | /// # Example
///
/// ```
/// use rand::prelude::*;
/// use rand_distr::Dirichlet;
///
/// let dirichlet = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
/// let samples = dirichlet.sample(&mut rand::thread_rng());
/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[derive(Clone, Debug)]
pub struct Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
/// Concentration parameters (alpha)
alpha: Box<[F]>,
}
/// Error type returned from `Dirchlet::new`.
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `alpha.len() < 2`.
AlphaTooShort,
/// `alpha <= 0.0` or `nan`.
AlphaTooSmall,
/// `size < 2`.
SizeTooSmall,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Error::AlphaTooShort | Error::SizeTooSmall => {
"less than 2 dimensions in Dirichlet distribution"
}
Error::AlphaTooSmall => "alpha is not positive in Dirichlet distribution",
})
}
}
#[cfg(feature = "std")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
impl std::error::Error for Error {}
impl<F> Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
/// Construct a new `Dirichlet` with the given alpha parameter `alpha`.
///
/// Requires `alpha.len() >= 2`.
#[inline]
pub fn new(alpha: &[F]) -> Result<Dirichlet<F>, Error> {
if alpha.len() < 2 {
return Err(Error::AlphaTooShort);
}
for &ai in alpha.iter() {
if !(ai > F::zero()) {
return Err(Error::AlphaTooSmall);
}
}
Ok(Dirichlet { alpha: alpha.to_vec().into_boxed_slice() })
}
/// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`.
///
/// Requires `size >= 2`.
#[inline]
pub fn new_with_size(alpha: F, size: usize) -> Result<Dirichlet<F>, Error> {
if !(alpha > F::zero()) {
return Err(Error::AlphaTooSmall);
}
if size < 2 {
return Err(Error::SizeTooSmall);
}
Ok(Dirichlet {
alpha: vec![alpha; size].into_boxed_slice(),
})
}
}
impl<F> Distribution<Vec<F>> for Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<F> {
let n = self.alpha.len();
let mut samples = vec![F::zero(); n];
let mut sum = F::zero();
for (s, &a) in samples.iter_mut().zip(self.alpha.iter()) {
let g = Gamma::new(a, F::one()).unwrap();
*s = g.sample(rng);
sum = sum + (*s);
}
let invacc = F::one() / sum;
for s in samples.iter_mut() {
*s = (*s)*invacc;
}
samples
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_dirichlet() {
let d = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();
}
#[test]
fn test_dirichlet_with_param() {
let alpha = 0.5f64;
let size = 2;
let d = Dirichlet::new_with_size(alpha, size).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();
}
#[test]
#[should_panic]
fn test_dirichlet_invalid_length() {
Dirichlet::new_with_size(0.5f64, 1).unwrap();
}
#[test]
#[should_panic]
fn test_dirichlet_invalid_alpha() {
Dirichlet::new_with_size(0.0f64, 2).unwrap();
}
} | random_line_split | |
dirichlet.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The dirichlet distribution.
#![cfg(feature = "alloc")]
use num_traits::Float;
use crate::{Distribution, Exp1, Gamma, Open01, StandardNormal};
use rand::Rng;
use core::fmt;
use alloc::{boxed::Box, vec, vec::Vec};
/// The Dirichlet distribution `Dirichlet(alpha)`.
///
/// The Dirichlet distribution is a family of continuous multivariate
/// probability distributions parameterized by a vector alpha of positive reals.
/// It is a multivariate generalization of the beta distribution.
///
/// # Example
///
/// ```
/// use rand::prelude::*;
/// use rand_distr::Dirichlet;
///
/// let dirichlet = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
/// let samples = dirichlet.sample(&mut rand::thread_rng());
/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[derive(Clone, Debug)]
pub struct Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
/// Concentration parameters (alpha)
alpha: Box<[F]>,
}
/// Error type returned from `Dirchlet::new`.
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `alpha.len() < 2`.
AlphaTooShort,
/// `alpha <= 0.0` or `nan`.
AlphaTooSmall,
/// `size < 2`.
SizeTooSmall,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Error::AlphaTooShort | Error::SizeTooSmall => {
"less than 2 dimensions in Dirichlet distribution"
}
Error::AlphaTooSmall => "alpha is not positive in Dirichlet distribution",
})
}
}
#[cfg(feature = "std")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
impl std::error::Error for Error {}
impl<F> Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
/// Construct a new `Dirichlet` with the given alpha parameter `alpha`.
///
/// Requires `alpha.len() >= 2`.
#[inline]
pub fn new(alpha: &[F]) -> Result<Dirichlet<F>, Error> {
if alpha.len() < 2 {
return Err(Error::AlphaTooShort);
}
for &ai in alpha.iter() {
if !(ai > F::zero()) {
return Err(Error::AlphaTooSmall);
}
}
Ok(Dirichlet { alpha: alpha.to_vec().into_boxed_slice() })
}
/// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`.
///
/// Requires `size >= 2`.
#[inline]
pub fn | (alpha: F, size: usize) -> Result<Dirichlet<F>, Error> {
if !(alpha > F::zero()) {
return Err(Error::AlphaTooSmall);
}
if size < 2 {
return Err(Error::SizeTooSmall);
}
Ok(Dirichlet {
alpha: vec![alpha; size].into_boxed_slice(),
})
}
}
impl<F> Distribution<Vec<F>> for Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<F> {
let n = self.alpha.len();
let mut samples = vec![F::zero(); n];
let mut sum = F::zero();
for (s, &a) in samples.iter_mut().zip(self.alpha.iter()) {
let g = Gamma::new(a, F::one()).unwrap();
*s = g.sample(rng);
sum = sum + (*s);
}
let invacc = F::one() / sum;
for s in samples.iter_mut() {
*s = (*s)*invacc;
}
samples
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_dirichlet() {
let d = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();
}
#[test]
fn test_dirichlet_with_param() {
let alpha = 0.5f64;
let size = 2;
let d = Dirichlet::new_with_size(alpha, size).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();
}
#[test]
#[should_panic]
fn test_dirichlet_invalid_length() {
Dirichlet::new_with_size(0.5f64, 1).unwrap();
}
#[test]
#[should_panic]
fn test_dirichlet_invalid_alpha() {
Dirichlet::new_with_size(0.0f64, 2).unwrap();
}
}
| new_with_size | identifier_name |
dirichlet.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The dirichlet distribution.
#![cfg(feature = "alloc")]
use num_traits::Float;
use crate::{Distribution, Exp1, Gamma, Open01, StandardNormal};
use rand::Rng;
use core::fmt;
use alloc::{boxed::Box, vec, vec::Vec};
/// The Dirichlet distribution `Dirichlet(alpha)`.
///
/// The Dirichlet distribution is a family of continuous multivariate
/// probability distributions parameterized by a vector alpha of positive reals.
/// It is a multivariate generalization of the beta distribution.
///
/// # Example
///
/// ```
/// use rand::prelude::*;
/// use rand_distr::Dirichlet;
///
/// let dirichlet = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
/// let samples = dirichlet.sample(&mut rand::thread_rng());
/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[derive(Clone, Debug)]
pub struct Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
/// Concentration parameters (alpha)
alpha: Box<[F]>,
}
/// Error type returned from `Dirchlet::new`.
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `alpha.len() < 2`.
AlphaTooShort,
/// `alpha <= 0.0` or `nan`.
AlphaTooSmall,
/// `size < 2`.
SizeTooSmall,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Error::AlphaTooShort | Error::SizeTooSmall => {
"less than 2 dimensions in Dirichlet distribution"
}
Error::AlphaTooSmall => "alpha is not positive in Dirichlet distribution",
})
}
}
#[cfg(feature = "std")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
impl std::error::Error for Error {}
impl<F> Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
/// Construct a new `Dirichlet` with the given alpha parameter `alpha`.
///
/// Requires `alpha.len() >= 2`.
#[inline]
pub fn new(alpha: &[F]) -> Result<Dirichlet<F>, Error> {
if alpha.len() < 2 {
return Err(Error::AlphaTooShort);
}
for &ai in alpha.iter() {
if !(ai > F::zero()) |
}
Ok(Dirichlet { alpha: alpha.to_vec().into_boxed_slice() })
}
/// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`.
///
/// Requires `size >= 2`.
#[inline]
pub fn new_with_size(alpha: F, size: usize) -> Result<Dirichlet<F>, Error> {
if !(alpha > F::zero()) {
return Err(Error::AlphaTooSmall);
}
if size < 2 {
return Err(Error::SizeTooSmall);
}
Ok(Dirichlet {
alpha: vec![alpha; size].into_boxed_slice(),
})
}
}
impl<F> Distribution<Vec<F>> for Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<F> {
let n = self.alpha.len();
let mut samples = vec![F::zero(); n];
let mut sum = F::zero();
for (s, &a) in samples.iter_mut().zip(self.alpha.iter()) {
let g = Gamma::new(a, F::one()).unwrap();
*s = g.sample(rng);
sum = sum + (*s);
}
let invacc = F::one() / sum;
for s in samples.iter_mut() {
*s = (*s)*invacc;
}
samples
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_dirichlet() {
let d = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();
}
#[test]
fn test_dirichlet_with_param() {
let alpha = 0.5f64;
let size = 2;
let d = Dirichlet::new_with_size(alpha, size).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();
}
#[test]
#[should_panic]
fn test_dirichlet_invalid_length() {
Dirichlet::new_with_size(0.5f64, 1).unwrap();
}
#[test]
#[should_panic]
fn test_dirichlet_invalid_alpha() {
Dirichlet::new_with_size(0.0f64, 2).unwrap();
}
}
| {
return Err(Error::AlphaTooSmall);
} | conditional_block |
dirichlet.rs | // Copyright 2018 Developers of the Rand project.
// Copyright 2013 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The dirichlet distribution.
#![cfg(feature = "alloc")]
use num_traits::Float;
use crate::{Distribution, Exp1, Gamma, Open01, StandardNormal};
use rand::Rng;
use core::fmt;
use alloc::{boxed::Box, vec, vec::Vec};
/// The Dirichlet distribution `Dirichlet(alpha)`.
///
/// The Dirichlet distribution is a family of continuous multivariate
/// probability distributions parameterized by a vector alpha of positive reals.
/// It is a multivariate generalization of the beta distribution.
///
/// # Example
///
/// ```
/// use rand::prelude::*;
/// use rand_distr::Dirichlet;
///
/// let dirichlet = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
/// let samples = dirichlet.sample(&mut rand::thread_rng());
/// println!("{:?} is from a Dirichlet([1.0, 2.0, 3.0]) distribution", samples);
/// ```
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[derive(Clone, Debug)]
pub struct Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
/// Concentration parameters (alpha)
alpha: Box<[F]>,
}
/// Error type returned from `Dirchlet::new`.
#[cfg_attr(doc_cfg, doc(cfg(feature = "alloc")))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// `alpha.len() < 2`.
AlphaTooShort,
/// `alpha <= 0.0` or `nan`.
AlphaTooSmall,
/// `size < 2`.
SizeTooSmall,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Error::AlphaTooShort | Error::SizeTooSmall => {
"less than 2 dimensions in Dirichlet distribution"
}
Error::AlphaTooSmall => "alpha is not positive in Dirichlet distribution",
})
}
}
#[cfg(feature = "std")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
impl std::error::Error for Error {}
impl<F> Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
/// Construct a new `Dirichlet` with the given alpha parameter `alpha`.
///
/// Requires `alpha.len() >= 2`.
#[inline]
pub fn new(alpha: &[F]) -> Result<Dirichlet<F>, Error> {
if alpha.len() < 2 {
return Err(Error::AlphaTooShort);
}
for &ai in alpha.iter() {
if !(ai > F::zero()) {
return Err(Error::AlphaTooSmall);
}
}
Ok(Dirichlet { alpha: alpha.to_vec().into_boxed_slice() })
}
/// Construct a new `Dirichlet` with the given shape parameter `alpha` and `size`.
///
/// Requires `size >= 2`.
#[inline]
pub fn new_with_size(alpha: F, size: usize) -> Result<Dirichlet<F>, Error> {
if !(alpha > F::zero()) {
return Err(Error::AlphaTooSmall);
}
if size < 2 {
return Err(Error::SizeTooSmall);
}
Ok(Dirichlet {
alpha: vec![alpha; size].into_boxed_slice(),
})
}
}
impl<F> Distribution<Vec<F>> for Dirichlet<F>
where
F: Float,
StandardNormal: Distribution<F>,
Exp1: Distribution<F>,
Open01: Distribution<F>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec<F> {
let n = self.alpha.len();
let mut samples = vec![F::zero(); n];
let mut sum = F::zero();
for (s, &a) in samples.iter_mut().zip(self.alpha.iter()) {
let g = Gamma::new(a, F::one()).unwrap();
*s = g.sample(rng);
sum = sum + (*s);
}
let invacc = F::one() / sum;
for s in samples.iter_mut() {
*s = (*s)*invacc;
}
samples
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_dirichlet() |
#[test]
fn test_dirichlet_with_param() {
let alpha = 0.5f64;
let size = 2;
let d = Dirichlet::new_with_size(alpha, size).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();
}
#[test]
#[should_panic]
fn test_dirichlet_invalid_length() {
Dirichlet::new_with_size(0.5f64, 1).unwrap();
}
#[test]
#[should_panic]
fn test_dirichlet_invalid_alpha() {
Dirichlet::new_with_size(0.0f64, 2).unwrap();
}
}
| {
let d = Dirichlet::new(&[1.0, 2.0, 3.0]).unwrap();
let mut rng = crate::test::rng(221);
let samples = d.sample(&mut rng);
let _: Vec<f64> = samples
.into_iter()
.map(|x| {
assert!(x > 0.0);
x
})
.collect();
} | identifier_body |
renderer.js | const { ipcRenderer, remote } = require('electron');
const mainProcess = remote.require('./main');
const currentWindow = remote.getCurrentWindow();
| const $directions = $('.directions-input');
const $notes = $('.notes-input');
const $saveButton = $('.save-recipe-button');
const $seeAllButton = $('.see-all-button');
const $homeButton = $('.home-button');
const $addRecipeButton = $('.add-button');
let pageNav = (page) => {
currentWindow.loadURL(`file://${__dirname}/${page}`);
};
$saveButton.on('click', () => {
let name = $name.val();
let servings = $servings.val();
let time = $time.val();
let ingredients = $ingredients.val();
let directions = $directions.val();
let notes = $notes.val();
let recipe = { name, servings, time, ingredients, directions, notes};
mainProcess.saveRecipe(recipe);
pageNav('full-recipe.html');
});
$seeAllButton.on('click', () => {
mainProcess.getRecipes();
pageNav('all-recipes.html');
});
$homeButton.on('click', () => {
pageNav('index.html');
});
$addRecipeButton.on('click', () => {
pageNav('add-recipe.html');
}); | const $name = $('.name-input');
const $servings = $('.servings-input');
const $time = $('.time-input');
const $ingredients = $('.ingredients-input'); | random_line_split |
Track.py | # -*- coding: utf-8 -*-
###############################################################################
#
# Track
# Records an event in Mixpanel.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class Track(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the Track Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(Track, self).__init__(temboo_session, '/Library/Mixpanel/Events/Track')
def new_input_set(self):
return TrackInputSet()
def _make_result_set(self, result, path):
return TrackResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return TrackChoreographyExecution(session, exec_id, path)
class TrackInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the Track
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_DistinctID(self, value):
"""
Set the value of the DistinctID input for this Choreo. ((optional, string) Used to uniquely identify a user associated with your event. When provided, you can track a given user through funnels and distinguish unique users for retention analyses.)
"""
super(TrackInputSet, self)._set_input('DistinctID', value)
def set_EventName(self, value):
"""
Set the value of the EventName input for this Choreo. ((required, string) A name for the event (e.g., Signed Up, Uploaded Photo, etc).)
"""
super(TrackInputSet, self)._set_input('EventName', value)
def set_EventProperties(self, value):
"""
Set the value of the EventProperties input for this Choreo. ((optional, json) Additional properties associated with the event formatted as name/value pairs in a JSON object. These properties can be used for segmentation and funnels.)
"""
super(TrackInputSet, self)._set_input('EventProperties', value)
def set_IP(self, value):
"""
Set the value of the IP input for this Choreo. ((optional, string) An IP address string associated with the event (e.g., 127.0.0.1). When set to 0 (the default) Mixpanel will ignore IP information.)
"""
super(TrackInputSet, self)._set_input('IP', value)
def set_Time(self, value):
"""
Set the value of the Time input for this Choreo. ((optional, date) A unix timestamp representing the time the event occurred. If not provided, Mixpanel will use the time the event arrives at the server.)
"""
super(TrackInputSet, self)._set_input('Time', value)
def set_Token(self, value):
|
def set_Verbose(self, value):
"""
Set the value of the Verbose input for this Choreo. ((optional, boolean) When set to 1, the response will contain more information describing the success or failure of the tracking call.)
"""
super(TrackInputSet, self)._set_input('Verbose', value)
class TrackResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the Track Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from Mixpanel.)
"""
return self._output.get('Response', None)
class TrackChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return TrackResultSet(response, path)
| """
Set the value of the Token input for this Choreo. ((required, string) The token provided by Mixpanel. You can find your Mixpanel token in the project settings dialog in the Mixpanel app.)
"""
super(TrackInputSet, self)._set_input('Token', value) | identifier_body |
Track.py | # -*- coding: utf-8 -*-
| # Records an event in Mixpanel.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class Track(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the Track Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(Track, self).__init__(temboo_session, '/Library/Mixpanel/Events/Track')
def new_input_set(self):
return TrackInputSet()
def _make_result_set(self, result, path):
return TrackResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return TrackChoreographyExecution(session, exec_id, path)
class TrackInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the Track
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_DistinctID(self, value):
"""
Set the value of the DistinctID input for this Choreo. ((optional, string) Used to uniquely identify a user associated with your event. When provided, you can track a given user through funnels and distinguish unique users for retention analyses.)
"""
super(TrackInputSet, self)._set_input('DistinctID', value)
def set_EventName(self, value):
"""
Set the value of the EventName input for this Choreo. ((required, string) A name for the event (e.g., Signed Up, Uploaded Photo, etc).)
"""
super(TrackInputSet, self)._set_input('EventName', value)
def set_EventProperties(self, value):
"""
Set the value of the EventProperties input for this Choreo. ((optional, json) Additional properties associated with the event formatted as name/value pairs in a JSON object. These properties can be used for segmentation and funnels.)
"""
super(TrackInputSet, self)._set_input('EventProperties', value)
def set_IP(self, value):
"""
Set the value of the IP input for this Choreo. ((optional, string) An IP address string associated with the event (e.g., 127.0.0.1). When set to 0 (the default) Mixpanel will ignore IP information.)
"""
super(TrackInputSet, self)._set_input('IP', value)
def set_Time(self, value):
"""
Set the value of the Time input for this Choreo. ((optional, date) A unix timestamp representing the time the event occurred. If not provided, Mixpanel will use the time the event arrives at the server.)
"""
super(TrackInputSet, self)._set_input('Time', value)
def set_Token(self, value):
"""
Set the value of the Token input for this Choreo. ((required, string) The token provided by Mixpanel. You can find your Mixpanel token in the project settings dialog in the Mixpanel app.)
"""
super(TrackInputSet, self)._set_input('Token', value)
def set_Verbose(self, value):
"""
Set the value of the Verbose input for this Choreo. ((optional, boolean) When set to 1, the response will contain more information describing the success or failure of the tracking call.)
"""
super(TrackInputSet, self)._set_input('Verbose', value)
class TrackResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the Track Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from Mixpanel.)
"""
return self._output.get('Response', None)
class TrackChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return TrackResultSet(response, path) | ###############################################################################
#
# Track | random_line_split |
Track.py | # -*- coding: utf-8 -*-
###############################################################################
#
# Track
# Records an event in Mixpanel.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class Track(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the Track Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(Track, self).__init__(temboo_session, '/Library/Mixpanel/Events/Track')
def new_input_set(self):
return TrackInputSet()
def _make_result_set(self, result, path):
return TrackResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return TrackChoreographyExecution(session, exec_id, path)
class TrackInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the Track
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_DistinctID(self, value):
"""
Set the value of the DistinctID input for this Choreo. ((optional, string) Used to uniquely identify a user associated with your event. When provided, you can track a given user through funnels and distinguish unique users for retention analyses.)
"""
super(TrackInputSet, self)._set_input('DistinctID', value)
def set_EventName(self, value):
"""
Set the value of the EventName input for this Choreo. ((required, string) A name for the event (e.g., Signed Up, Uploaded Photo, etc).)
"""
super(TrackInputSet, self)._set_input('EventName', value)
def set_EventProperties(self, value):
"""
Set the value of the EventProperties input for this Choreo. ((optional, json) Additional properties associated with the event formatted as name/value pairs in a JSON object. These properties can be used for segmentation and funnels.)
"""
super(TrackInputSet, self)._set_input('EventProperties', value)
def set_IP(self, value):
"""
Set the value of the IP input for this Choreo. ((optional, string) An IP address string associated with the event (e.g., 127.0.0.1). When set to 0 (the default) Mixpanel will ignore IP information.)
"""
super(TrackInputSet, self)._set_input('IP', value)
def | (self, value):
"""
Set the value of the Time input for this Choreo. ((optional, date) A unix timestamp representing the time the event occurred. If not provided, Mixpanel will use the time the event arrives at the server.)
"""
super(TrackInputSet, self)._set_input('Time', value)
def set_Token(self, value):
"""
Set the value of the Token input for this Choreo. ((required, string) The token provided by Mixpanel. You can find your Mixpanel token in the project settings dialog in the Mixpanel app.)
"""
super(TrackInputSet, self)._set_input('Token', value)
def set_Verbose(self, value):
"""
Set the value of the Verbose input for this Choreo. ((optional, boolean) When set to 1, the response will contain more information describing the success or failure of the tracking call.)
"""
super(TrackInputSet, self)._set_input('Verbose', value)
class TrackResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the Track Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. (The response from Mixpanel.)
"""
return self._output.get('Response', None)
class TrackChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return TrackResultSet(response, path)
| set_Time | identifier_name |
parser_init_mapping.py | # -*- coding: utf-8 -*-
"""Class representing the mapper for the parser init files."""
from plasoscaffolder.bll.mappings import base_mapping_helper
from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping
from plasoscaffolder.model import init_data_model
class ParserInitMapping(
base_sqliteplugin_mapping.BaseSQLitePluginMapper):
"""Class representing the parser mapper."""
_PARSER_INIT_TEMPLATE = 'parser_init_template.jinja2'
def | (self, mapping_helper: base_mapping_helper.BaseMappingHelper):
"""Initializing the init mapper class.
Args:
mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class
for the mapping
"""
super().__init__()
self._helper = mapping_helper
def GetRenderedTemplate(
self,
data: init_data_model.InitDataModel) -> str:
"""Retrieves the parser init file.
Args:
data (init_data_model.InitDataModel): the data for init file
Returns:
str: the rendered template
"""
context = {'plugin_name': data.plugin_name,
'is_create_template': data.is_create_template}
rendered = self._helper.RenderTemplate(
self._PARSER_INIT_TEMPLATE, context)
return rendered
| __init__ | identifier_name |
parser_init_mapping.py | # -*- coding: utf-8 -*-
"""Class representing the mapper for the parser init files."""
from plasoscaffolder.bll.mappings import base_mapping_helper
from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping
from plasoscaffolder.model import init_data_model
class ParserInitMapping(
base_sqliteplugin_mapping.BaseSQLitePluginMapper):
"""Class representing the parser mapper."""
_PARSER_INIT_TEMPLATE = 'parser_init_template.jinja2'
def __init__(self, mapping_helper: base_mapping_helper.BaseMappingHelper):
"""Initializing the init mapper class.
Args:
mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class
for the mapping
"""
super().__init__()
self._helper = mapping_helper
def GetRenderedTemplate(
self,
data: init_data_model.InitDataModel) -> str:
"""Retrieves the parser init file.
Args:
data (init_data_model.InitDataModel): the data for init file | context = {'plugin_name': data.plugin_name,
'is_create_template': data.is_create_template}
rendered = self._helper.RenderTemplate(
self._PARSER_INIT_TEMPLATE, context)
return rendered |
Returns:
str: the rendered template
""" | random_line_split |
parser_init_mapping.py | # -*- coding: utf-8 -*-
"""Class representing the mapper for the parser init files."""
from plasoscaffolder.bll.mappings import base_mapping_helper
from plasoscaffolder.bll.mappings import base_sqliteplugin_mapping
from plasoscaffolder.model import init_data_model
class ParserInitMapping(
base_sqliteplugin_mapping.BaseSQLitePluginMapper):
| """Class representing the parser mapper."""
_PARSER_INIT_TEMPLATE = 'parser_init_template.jinja2'
def __init__(self, mapping_helper: base_mapping_helper.BaseMappingHelper):
"""Initializing the init mapper class.
Args:
mapping_helper (base_mapping_helper.BaseMappingHelper): the helper class
for the mapping
"""
super().__init__()
self._helper = mapping_helper
def GetRenderedTemplate(
self,
data: init_data_model.InitDataModel) -> str:
"""Retrieves the parser init file.
Args:
data (init_data_model.InitDataModel): the data for init file
Returns:
str: the rendered template
"""
context = {'plugin_name': data.plugin_name,
'is_create_template': data.is_create_template}
rendered = self._helper.RenderTemplate(
self._PARSER_INIT_TEMPLATE, context)
return rendered | identifier_body | |
vxserver.py | # The MIT License (MIT)
# Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran
# 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.
from twisted.application import service
from twisted.internet.protocol import ServerFactory, Protocol
from twisted.protocols.basic import LineReceiver
from twisted.python import log
from vxcontroller import vx
import command
import json
import struct
import binascii
#
# We could run some validation on the JSON befor esending it back
# down the pipe to the Browser. Right now, we just validate that the
# JSON is proper and move it along.
#
_available_commands = frozenset(
["TXT", "ARC", "ELIP", "LI2D", "PO2D", "QUAD", "RECT", "TRI",
"BG", "CM_D","CM_F", "ST_D","ST_F", "STW", "NOST", "NOFI",
"FI_D", "FI_F","PUSH_STYLE","POP_STYLE", "SIZE", "ELIP_MODE",
"RECT_MODE", "ST_CAP", "ST_JOIN", "BEGIN_SHAPE", "END_SHAPE", "VERTEX",
"CR_FONT", "TXT_FONT", "LOAD_FONT", "PUSH_MAT", "POP_MAT", "TRANSL_2i",
"TRANSL_2f","ROTATE","REG_CB","VAR", "FIT_SCREEN", "STROKE_PALLET",
"ATTACH_LAYER", "SWITCH_SCREEN", "FILL_PALLET", "CREATE_TOOLBAR",
"ADD_BUTTON", "CREATE_PALLET", "VIDEOTAG"]
);
class VxProtocol(LineReceiver):
delimiter = "\n"
def __init__(self):
self.setLineMode()
self.id = None
def connectionMade(self):
client = self.transport.getHost()
log.msg('application at %s connected' % client)
self.id = vx.registerApplication(client, self)
self.sendEvent("EVENT PRELOAD\n") | def lineReceived(self, data):
try:
cmd = json.loads(data)
if cmd[u'name'] == 'PRELOAD':
vx.addFontPreload(self.id, cmd['args'][0], cmd['args'][1])
return
vx.pushWebSocketEvent(self.id, cmd)
except ValueError:
log.msg("Invalid JSON data received:: %s" % data)
cmd = command.process(data)
self.processCommand(cmd)
def processCommand(self, cmd):
# log.msg("In VxProtocol.processCommand:: %s" % cmd)
if cmd['name'] in _available_commands:
vx.pushWebSocketEvent(self.id, cmd)
return
if cmd['name'] == "CLEAR":
vx.pushWebSocketEvent(self.id, cmd)
# print "Removed call to EXPOSE\n" #self.sendEvent("EVENT EXPOSE\n")
return
def sendEvent(self, event):
# log.msg("VxProtocol.sendEvent:: %s" % event)
if event.startswith("EVENT"):
# log.msg("VxProtocol.sendEvent:: %s" % event)
# Prevent overflow attempts by limiting communication to the C side to 256-length buffers
event = event[0:255]
self.transport.write(event)
class VxFactory(ServerFactory):
protocol = VxProtocol
def __init__(self):
pass |
def connectionLost(self, reason):
log.msg('application (%s) disconnected' % self.id)
vx.unregisterApplication(self.id)
| random_line_split |
vxserver.py |
# The MIT License (MIT)
# Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran
# 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.
from twisted.application import service
from twisted.internet.protocol import ServerFactory, Protocol
from twisted.protocols.basic import LineReceiver
from twisted.python import log
from vxcontroller import vx
import command
import json
import struct
import binascii
#
# We could run some validation on the JSON befor esending it back
# down the pipe to the Browser. Right now, we just validate that the
# JSON is proper and move it along.
#
_available_commands = frozenset(
["TXT", "ARC", "ELIP", "LI2D", "PO2D", "QUAD", "RECT", "TRI",
"BG", "CM_D","CM_F", "ST_D","ST_F", "STW", "NOST", "NOFI",
"FI_D", "FI_F","PUSH_STYLE","POP_STYLE", "SIZE", "ELIP_MODE",
"RECT_MODE", "ST_CAP", "ST_JOIN", "BEGIN_SHAPE", "END_SHAPE", "VERTEX",
"CR_FONT", "TXT_FONT", "LOAD_FONT", "PUSH_MAT", "POP_MAT", "TRANSL_2i",
"TRANSL_2f","ROTATE","REG_CB","VAR", "FIT_SCREEN", "STROKE_PALLET",
"ATTACH_LAYER", "SWITCH_SCREEN", "FILL_PALLET", "CREATE_TOOLBAR",
"ADD_BUTTON", "CREATE_PALLET", "VIDEOTAG"]
);
class VxProtocol(LineReceiver):
delimiter = "\n"
def | (self):
self.setLineMode()
self.id = None
def connectionMade(self):
client = self.transport.getHost()
log.msg('application at %s connected' % client)
self.id = vx.registerApplication(client, self)
self.sendEvent("EVENT PRELOAD\n")
def connectionLost(self, reason):
log.msg('application (%s) disconnected' % self.id)
vx.unregisterApplication(self.id)
def lineReceived(self, data):
try:
cmd = json.loads(data)
if cmd[u'name'] == 'PRELOAD':
vx.addFontPreload(self.id, cmd['args'][0], cmd['args'][1])
return
vx.pushWebSocketEvent(self.id, cmd)
except ValueError:
log.msg("Invalid JSON data received:: %s" % data)
cmd = command.process(data)
self.processCommand(cmd)
def processCommand(self, cmd):
# log.msg("In VxProtocol.processCommand:: %s" % cmd)
if cmd['name'] in _available_commands:
vx.pushWebSocketEvent(self.id, cmd)
return
if cmd['name'] == "CLEAR":
vx.pushWebSocketEvent(self.id, cmd)
# print "Removed call to EXPOSE\n" #self.sendEvent("EVENT EXPOSE\n")
return
def sendEvent(self, event):
# log.msg("VxProtocol.sendEvent:: %s" % event)
if event.startswith("EVENT"):
# log.msg("VxProtocol.sendEvent:: %s" % event)
# Prevent overflow attempts by limiting communication to the C side to 256-length buffers
event = event[0:255]
self.transport.write(event)
class VxFactory(ServerFactory):
protocol = VxProtocol
def __init__(self):
pass
| __init__ | identifier_name |
vxserver.py |
# The MIT License (MIT)
# Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran
# 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.
from twisted.application import service
from twisted.internet.protocol import ServerFactory, Protocol
from twisted.protocols.basic import LineReceiver
from twisted.python import log
from vxcontroller import vx
import command
import json
import struct
import binascii
#
# We could run some validation on the JSON befor esending it back
# down the pipe to the Browser. Right now, we just validate that the
# JSON is proper and move it along.
#
_available_commands = frozenset(
["TXT", "ARC", "ELIP", "LI2D", "PO2D", "QUAD", "RECT", "TRI",
"BG", "CM_D","CM_F", "ST_D","ST_F", "STW", "NOST", "NOFI",
"FI_D", "FI_F","PUSH_STYLE","POP_STYLE", "SIZE", "ELIP_MODE",
"RECT_MODE", "ST_CAP", "ST_JOIN", "BEGIN_SHAPE", "END_SHAPE", "VERTEX",
"CR_FONT", "TXT_FONT", "LOAD_FONT", "PUSH_MAT", "POP_MAT", "TRANSL_2i",
"TRANSL_2f","ROTATE","REG_CB","VAR", "FIT_SCREEN", "STROKE_PALLET",
"ATTACH_LAYER", "SWITCH_SCREEN", "FILL_PALLET", "CREATE_TOOLBAR",
"ADD_BUTTON", "CREATE_PALLET", "VIDEOTAG"]
);
class VxProtocol(LineReceiver):
delimiter = "\n"
def __init__(self):
self.setLineMode()
self.id = None
def connectionMade(self):
client = self.transport.getHost()
log.msg('application at %s connected' % client)
self.id = vx.registerApplication(client, self)
self.sendEvent("EVENT PRELOAD\n")
def connectionLost(self, reason):
log.msg('application (%s) disconnected' % self.id)
vx.unregisterApplication(self.id)
def lineReceived(self, data):
try:
cmd = json.loads(data)
if cmd[u'name'] == 'PRELOAD':
vx.addFontPreload(self.id, cmd['args'][0], cmd['args'][1])
return
vx.pushWebSocketEvent(self.id, cmd)
except ValueError:
log.msg("Invalid JSON data received:: %s" % data)
cmd = command.process(data)
self.processCommand(cmd)
def processCommand(self, cmd):
# log.msg("In VxProtocol.processCommand:: %s" % cmd)
|
def sendEvent(self, event):
# log.msg("VxProtocol.sendEvent:: %s" % event)
if event.startswith("EVENT"):
# log.msg("VxProtocol.sendEvent:: %s" % event)
# Prevent overflow attempts by limiting communication to the C side to 256-length buffers
event = event[0:255]
self.transport.write(event)
class VxFactory(ServerFactory):
protocol = VxProtocol
def __init__(self):
pass
| if cmd['name'] in _available_commands:
vx.pushWebSocketEvent(self.id, cmd)
return
if cmd['name'] == "CLEAR":
vx.pushWebSocketEvent(self.id, cmd)
# print "Removed call to EXPOSE\n" #self.sendEvent("EVENT EXPOSE\n")
return | identifier_body |
vxserver.py |
# The MIT License (MIT)
# Copyright (c) 2011 Derek Ingrouville, Julien Lord, Muthucumaru Maheswaran
# 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.
from twisted.application import service
from twisted.internet.protocol import ServerFactory, Protocol
from twisted.protocols.basic import LineReceiver
from twisted.python import log
from vxcontroller import vx
import command
import json
import struct
import binascii
#
# We could run some validation on the JSON befor esending it back
# down the pipe to the Browser. Right now, we just validate that the
# JSON is proper and move it along.
#
_available_commands = frozenset(
["TXT", "ARC", "ELIP", "LI2D", "PO2D", "QUAD", "RECT", "TRI",
"BG", "CM_D","CM_F", "ST_D","ST_F", "STW", "NOST", "NOFI",
"FI_D", "FI_F","PUSH_STYLE","POP_STYLE", "SIZE", "ELIP_MODE",
"RECT_MODE", "ST_CAP", "ST_JOIN", "BEGIN_SHAPE", "END_SHAPE", "VERTEX",
"CR_FONT", "TXT_FONT", "LOAD_FONT", "PUSH_MAT", "POP_MAT", "TRANSL_2i",
"TRANSL_2f","ROTATE","REG_CB","VAR", "FIT_SCREEN", "STROKE_PALLET",
"ATTACH_LAYER", "SWITCH_SCREEN", "FILL_PALLET", "CREATE_TOOLBAR",
"ADD_BUTTON", "CREATE_PALLET", "VIDEOTAG"]
);
class VxProtocol(LineReceiver):
delimiter = "\n"
def __init__(self):
self.setLineMode()
self.id = None
def connectionMade(self):
client = self.transport.getHost()
log.msg('application at %s connected' % client)
self.id = vx.registerApplication(client, self)
self.sendEvent("EVENT PRELOAD\n")
def connectionLost(self, reason):
log.msg('application (%s) disconnected' % self.id)
vx.unregisterApplication(self.id)
def lineReceived(self, data):
try:
cmd = json.loads(data)
if cmd[u'name'] == 'PRELOAD':
vx.addFontPreload(self.id, cmd['args'][0], cmd['args'][1])
return
vx.pushWebSocketEvent(self.id, cmd)
except ValueError:
log.msg("Invalid JSON data received:: %s" % data)
cmd = command.process(data)
self.processCommand(cmd)
def processCommand(self, cmd):
# log.msg("In VxProtocol.processCommand:: %s" % cmd)
if cmd['name'] in _available_commands:
|
if cmd['name'] == "CLEAR":
vx.pushWebSocketEvent(self.id, cmd)
# print "Removed call to EXPOSE\n" #self.sendEvent("EVENT EXPOSE\n")
return
def sendEvent(self, event):
# log.msg("VxProtocol.sendEvent:: %s" % event)
if event.startswith("EVENT"):
# log.msg("VxProtocol.sendEvent:: %s" % event)
# Prevent overflow attempts by limiting communication to the C side to 256-length buffers
event = event[0:255]
self.transport.write(event)
class VxFactory(ServerFactory):
protocol = VxProtocol
def __init__(self):
pass
| vx.pushWebSocketEvent(self.id, cmd)
return | conditional_block |
disk.rs | #![feature(plugin, custom_derive, custom_attribute)]
#![plugin(serde_macros)]
extern crate drum;
extern crate serde;
use drum::*;
use std::io::*;
use std::collections::*;
use std::fs::{OpenOptions};
#[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)]
enum Value {
Array(Vec<Value>),
Object(BTreeMap<Value, Value>),
String(String),
Number(i64)
}
fn run() -> Result<()> {
let msg = "Hello World";
let file =
try!(OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open("test.db"));
let mut store = try!(Store::reopen(file));
for key in store.keys() {
println!("{}", key)
}
let previous = try!(store.get(&String::from(msg)));
try!(store.insert(
String::from(msg),
Value::Array(vec![Value::Number(100)]))
);
match previous {
Some(Value::Array(vec)) => {
match vec[0] {
Value::Number(num) => | ,
_ => panic!()
}
},
_ => ()
}
Ok(())
}
fn main() {
run().unwrap();
return;
} | {
println!("previous: {}", num);
} | conditional_block |
disk.rs | #![feature(plugin, custom_derive, custom_attribute)]
#![plugin(serde_macros)]
extern crate drum;
extern crate serde;
use drum::*;
use std::io::*;
use std::collections::*;
use std::fs::{OpenOptions};
#[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)]
enum Value {
Array(Vec<Value>),
Object(BTreeMap<Value, Value>),
String(String),
Number(i64)
}
fn run() -> Result<()> {
let msg = "Hello World";
let file =
try!(OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open("test.db"));
let mut store = try!(Store::reopen(file));
for key in store.keys() {
println!("{}", key)
}
let previous = try!(store.get(&String::from(msg)));
try!(store.insert(
String::from(msg),
Value::Array(vec![Value::Number(100)]))
);
match previous {
Some(Value::Array(vec)) => {
match vec[0] {
Value::Number(num) => {
println!("previous: {}", num);
},
_ => panic!()
}
},
_ => ()
}
Ok(())
}
fn | () {
run().unwrap();
return;
} | main | identifier_name |
disk.rs | #![feature(plugin, custom_derive, custom_attribute)]
#![plugin(serde_macros)]
extern crate drum;
extern crate serde;
use drum::*;
use std::io::*;
use std::collections::*;
use std::fs::{OpenOptions};
#[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)]
enum Value {
Array(Vec<Value>),
Object(BTreeMap<Value, Value>),
String(String),
Number(i64)
}
fn run() -> Result<()> {
let msg = "Hello World";
let file =
try!(OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open("test.db"));
let mut store = try!(Store::reopen(file));
for key in store.keys() {
println!("{}", key)
}
let previous = try!(store.get(&String::from(msg)));
try!(store.insert(
String::from(msg),
Value::Array(vec![Value::Number(100)]))
);
match previous {
Some(Value::Array(vec)) => {
match vec[0] {
Value::Number(num) => {
println!("previous: {}", num);
},
_ => panic!()
}
},
_ => ()
}
Ok(())
}
fn main() | {
run().unwrap();
return;
} | identifier_body | |
disk.rs | #![feature(plugin, custom_derive, custom_attribute)]
#![plugin(serde_macros)]
extern crate drum;
extern crate serde;
use drum::*;
use std::io::*;
use std::collections::*;
use std::fs::{OpenOptions};
#[derive(PartialEq, Ord, Eq, PartialOrd, Serialize, Deserialize)]
enum Value {
Array(Vec<Value>),
Object(BTreeMap<Value, Value>),
String(String),
Number(i64)
}
fn run() -> Result<()> {
let msg = "Hello World";
let file =
try!(OpenOptions::new()
.read(true)
.write(true)
.create(true)
.append(true)
.open("test.db"));
let mut store = try!(Store::reopen(file));
for key in store.keys() {
println!("{}", key)
}
let previous = try!(store.get(&String::from(msg)));
try!(store.insert(
String::from(msg),
Value::Array(vec![Value::Number(100)]))
);
match previous {
Some(Value::Array(vec)) => {
match vec[0] {
Value::Number(num) => {
println!("previous: {}", num);
},
_ => panic!()
}
},
_ => ()
}
Ok(())
}
fn main() {
run().unwrap();
return; | } | random_line_split | |
assignment04.py | #This line asks the user to input an integer that will be recorded as my age
my_age = input("Enter your age:")
#This line asks the user to input an integer that will be recorded as days_in_a_year
days_in_a_year = input("How many days are in a year?")
#This line states how many hours are in a day
hours_in_a_day = 24
#This line tells you how many seconds you've been alive based on the recorded integers | print "how many seconds have i been alive?", my_age * days_in_a_year * hours_in_a_day * 60 * 60
#This line says that there are 8 black cars
black_cars = 8
#This line says that there are 6 red cars
red_cars = 6
#This line states the total amount of black and red cars combined
print "What is the total number of black and red cars?", (black_cars + red_cars)
#This line tells you how many more black cars there are than red cars
print "How many more black cars are there than red cars?", (black_cars - red_cars) | random_line_split | |
setup.py | from setuptools import setup
version = '1.5.0a0'
testing_extras = ['nose', 'coverage']
docs_extras = ['Sphinx']
setup(
name='WebOb',
version=version,
description="WSGI request and response object",
long_description="""\
WebOb provides wrappers around the WSGI request environment, and an
object to help create WSGI responses.
The objects map much of the specified behavior of HTTP, including
header parsing and accessors for other standard parts of the
environment.
You may install the `in-development version of WebOb
<https://github.com/Pylons/webob/zipball/master#egg=WebOb-dev>`_ with
``pip install WebOb==dev`` (or ``easy_install WebOb==dev``).
* `WebOb reference <http://docs.webob.org/en/latest/reference.html>`_
* `Bug tracker <https://github.com/Pylons/webob/issues>`_
* `Browse source code <https://github.com/Pylons/webob>`_
* `Mailing list <http://bit.ly/paste-users>`_
* `Release news <http://docs.webob.org/en/latest/news.html>`_
* `Detailed changelog <https://github.com/Pylons/webob/commits/master>`_
""",
classifiers=[
"Development Status :: 6 - Mature",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
keywords='wsgi request web http',
author='Ian Bicking',
author_email='ianb@colorstudy.com',
maintainer='Pylons Project',
url='http://webob.org/',
license='MIT',
packages=['webob'], | 'testing':testing_extras,
'docs':docs_extras,
},
) | zip_safe=True,
test_suite='nose.collector',
tests_require=['nose'],
extras_require = { | random_line_split |
recv_and_pub.py | #!/usr/bin/env python
#-
# Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# Alternatively, this software may be distributed under the terms of the
# BSD license.
#
# See LICENSE and COPYING for more details.
#
"""Receive data over a socket and publish it."""
from blackadder.blackadder import *
from select import error
from select import select
from threading import Thread
from time import sleep
import os
import socket
def _main(argv=[]):
|
if __name__ == "__main__":
import sys
_main(sys.argv)
| strategy = NODE_LOCAL # XXX: NODE_LOCAL=0, DOMAIN_LOCAL=2
if len(argv) >= 2:
strategy = int(argv[1])
str_opt = None
local_port = 0xACDC
if len(argv) >= 3:
local_port = int(argv[2])
global publishing # XXX
publishing = False
sock = None
wfd, rfd = None, None
ba = Blackadder.Instance(True)
try:
sid = '\x0a'+6*'\x00'+'\x0b'
rid = '\x0c'+6*'\x00'+'\x0d'
id = sid + rid
ba.publish_scope(sid, "", strategy, str_opt)
ba.publish_info(rid, sid, strategy, str_opt)
def recv_and_pub(sock, ba, rfd):
try:
sock.bind(("localhost", local_port)) # XXX
sfd = sock.fileno()
buf = rwbuffer(4096)
while publishing:
rlist, wlist, xlist = select([sfd, rfd], [], [sfd, rfd])
if sfd in rlist:
n = sock.recv_into(buf)
ba.publish_data(id, strategy, str_opt,
buffer(buf, 0, n))
if rfd in rlist:
print "received from pipe"
break
elif sfd in xlist or rfd in xlist:
print "exceptional condition"
break
except error, select_error:
# select() may raise an error if fds are closed.
print "select:", select_error
print "recv_and_pub stopped"
while True:
ev = Event()
ba.getEvent(ev)
print ev
if not ev:
continue
print ev.type, "when", publishing
if ev.type == START_PUBLISH and not publishing:
print "Start publish"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rfd, wfd = os.pipe()
t = Thread(target=recv_and_pub, args=[sock, ba, rfd])
publishing = True
t.start()
print "Thread started"
sleep(0.1) # XXX: Wait for thread to start.
elif ev.type == STOP_PUBLISH and publishing:
print "Stop publish"
publishing = False
os.write(wfd, '\0')
sleep(0.1) # XXX: Wait for thread to stop.
sock.close(); sock = None
print "Socket closed"
os.close(rfd); rfd = None
os.close(wfd); wfd = None
sleep(0.1) # XXX: Wait for thread to stop.
finally:
ba.disconnect()
print "Blackadder disconnected"
if sock:
sock.close()
print "Socket closed (finally)"
if rfd:
os.close(rfd)
if wfd:
os.close(wfd) | identifier_body |
recv_and_pub.py | #!/usr/bin/env python
#-
# Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# Alternatively, this software may be distributed under the terms of the
# BSD license.
#
# See LICENSE and COPYING for more details.
#
"""Receive data over a socket and publish it."""
from blackadder.blackadder import *
from select import error
from select import select
from threading import Thread
from time import sleep
import os
import socket
def _main(argv=[]):
strategy = NODE_LOCAL # XXX: NODE_LOCAL=0, DOMAIN_LOCAL=2
if len(argv) >= 2:
strategy = int(argv[1])
str_opt = None
local_port = 0xACDC
if len(argv) >= 3:
local_port = int(argv[2])
global publishing # XXX
publishing = False
sock = None
wfd, rfd = None, None
ba = Blackadder.Instance(True)
try:
sid = '\x0a'+6*'\x00'+'\x0b'
rid = '\x0c'+6*'\x00'+'\x0d'
id = sid + rid
ba.publish_scope(sid, "", strategy, str_opt)
ba.publish_info(rid, sid, strategy, str_opt)
def | (sock, ba, rfd):
try:
sock.bind(("localhost", local_port)) # XXX
sfd = sock.fileno()
buf = rwbuffer(4096)
while publishing:
rlist, wlist, xlist = select([sfd, rfd], [], [sfd, rfd])
if sfd in rlist:
n = sock.recv_into(buf)
ba.publish_data(id, strategy, str_opt,
buffer(buf, 0, n))
if rfd in rlist:
print "received from pipe"
break
elif sfd in xlist or rfd in xlist:
print "exceptional condition"
break
except error, select_error:
# select() may raise an error if fds are closed.
print "select:", select_error
print "recv_and_pub stopped"
while True:
ev = Event()
ba.getEvent(ev)
print ev
if not ev:
continue
print ev.type, "when", publishing
if ev.type == START_PUBLISH and not publishing:
print "Start publish"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rfd, wfd = os.pipe()
t = Thread(target=recv_and_pub, args=[sock, ba, rfd])
publishing = True
t.start()
print "Thread started"
sleep(0.1) # XXX: Wait for thread to start.
elif ev.type == STOP_PUBLISH and publishing:
print "Stop publish"
publishing = False
os.write(wfd, '\0')
sleep(0.1) # XXX: Wait for thread to stop.
sock.close(); sock = None
print "Socket closed"
os.close(rfd); rfd = None
os.close(wfd); wfd = None
sleep(0.1) # XXX: Wait for thread to stop.
finally:
ba.disconnect()
print "Blackadder disconnected"
if sock:
sock.close()
print "Socket closed (finally)"
if rfd:
os.close(rfd)
if wfd:
os.close(wfd)
if __name__ == "__main__":
import sys
_main(sys.argv)
| recv_and_pub | identifier_name |
recv_and_pub.py | #!/usr/bin/env python
#-
# Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# Alternatively, this software may be distributed under the terms of the
# BSD license.
#
# See LICENSE and COPYING for more details.
#
"""Receive data over a socket and publish it."""
from blackadder.blackadder import *
from select import error
from select import select
from threading import Thread
from time import sleep
import os
import socket
def _main(argv=[]):
strategy = NODE_LOCAL # XXX: NODE_LOCAL=0, DOMAIN_LOCAL=2
if len(argv) >= 2:
strategy = int(argv[1])
str_opt = None
local_port = 0xACDC
if len(argv) >= 3:
local_port = int(argv[2])
global publishing # XXX
publishing = False
sock = None
wfd, rfd = None, None
ba = Blackadder.Instance(True)
try:
sid = '\x0a'+6*'\x00'+'\x0b'
rid = '\x0c'+6*'\x00'+'\x0d'
id = sid + rid
ba.publish_scope(sid, "", strategy, str_opt)
ba.publish_info(rid, sid, strategy, str_opt)
def recv_and_pub(sock, ba, rfd):
try:
sock.bind(("localhost", local_port)) # XXX
sfd = sock.fileno()
buf = rwbuffer(4096)
while publishing:
rlist, wlist, xlist = select([sfd, rfd], [], [sfd, rfd])
if sfd in rlist:
n = sock.recv_into(buf)
ba.publish_data(id, strategy, str_opt,
buffer(buf, 0, n))
if rfd in rlist:
print "received from pipe"
break
elif sfd in xlist or rfd in xlist:
print "exceptional condition"
break
except error, select_error:
# select() may raise an error if fds are closed. | ev = Event()
ba.getEvent(ev)
print ev
if not ev:
continue
print ev.type, "when", publishing
if ev.type == START_PUBLISH and not publishing:
print "Start publish"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rfd, wfd = os.pipe()
t = Thread(target=recv_and_pub, args=[sock, ba, rfd])
publishing = True
t.start()
print "Thread started"
sleep(0.1) # XXX: Wait for thread to start.
elif ev.type == STOP_PUBLISH and publishing:
print "Stop publish"
publishing = False
os.write(wfd, '\0')
sleep(0.1) # XXX: Wait for thread to stop.
sock.close(); sock = None
print "Socket closed"
os.close(rfd); rfd = None
os.close(wfd); wfd = None
sleep(0.1) # XXX: Wait for thread to stop.
finally:
ba.disconnect()
print "Blackadder disconnected"
if sock:
sock.close()
print "Socket closed (finally)"
if rfd:
os.close(rfd)
if wfd:
os.close(wfd)
if __name__ == "__main__":
import sys
_main(sys.argv) | print "select:", select_error
print "recv_and_pub stopped"
while True: | random_line_split |
recv_and_pub.py | #!/usr/bin/env python
#-
# Copyright (C) 2011 Oy L M Ericsson Ab, NomadicLab
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# Alternatively, this software may be distributed under the terms of the
# BSD license.
#
# See LICENSE and COPYING for more details.
#
"""Receive data over a socket and publish it."""
from blackadder.blackadder import *
from select import error
from select import select
from threading import Thread
from time import sleep
import os
import socket
def _main(argv=[]):
strategy = NODE_LOCAL # XXX: NODE_LOCAL=0, DOMAIN_LOCAL=2
if len(argv) >= 2:
strategy = int(argv[1])
str_opt = None
local_port = 0xACDC
if len(argv) >= 3:
local_port = int(argv[2])
global publishing # XXX
publishing = False
sock = None
wfd, rfd = None, None
ba = Blackadder.Instance(True)
try:
sid = '\x0a'+6*'\x00'+'\x0b'
rid = '\x0c'+6*'\x00'+'\x0d'
id = sid + rid
ba.publish_scope(sid, "", strategy, str_opt)
ba.publish_info(rid, sid, strategy, str_opt)
def recv_and_pub(sock, ba, rfd):
try:
sock.bind(("localhost", local_port)) # XXX
sfd = sock.fileno()
buf = rwbuffer(4096)
while publishing:
rlist, wlist, xlist = select([sfd, rfd], [], [sfd, rfd])
if sfd in rlist:
n = sock.recv_into(buf)
ba.publish_data(id, strategy, str_opt,
buffer(buf, 0, n))
if rfd in rlist:
print "received from pipe"
break
elif sfd in xlist or rfd in xlist:
print "exceptional condition"
break
except error, select_error:
# select() may raise an error if fds are closed.
print "select:", select_error
print "recv_and_pub stopped"
while True:
ev = Event()
ba.getEvent(ev)
print ev
if not ev:
continue
print ev.type, "when", publishing
if ev.type == START_PUBLISH and not publishing:
print "Start publish"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rfd, wfd = os.pipe()
t = Thread(target=recv_and_pub, args=[sock, ba, rfd])
publishing = True
t.start()
print "Thread started"
sleep(0.1) # XXX: Wait for thread to start.
elif ev.type == STOP_PUBLISH and publishing:
print "Stop publish"
publishing = False
os.write(wfd, '\0')
sleep(0.1) # XXX: Wait for thread to stop.
sock.close(); sock = None
print "Socket closed"
os.close(rfd); rfd = None
os.close(wfd); wfd = None
sleep(0.1) # XXX: Wait for thread to stop.
finally:
ba.disconnect()
print "Blackadder disconnected"
if sock:
sock.close()
print "Socket closed (finally)"
if rfd:
|
if wfd:
os.close(wfd)
if __name__ == "__main__":
import sys
_main(sys.argv)
| os.close(rfd) | conditional_block |
handler.ts |
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { AddonModQuizAccessRuleHandler } from '../../../providers/access-rules-delegate';
/**
* Handler to support IP address access rule.
*/
@Injectable()
export class AddonModQuizAccessIpAddressHandler implements AddonModQuizAccessRuleHandler {
name = 'AddonModQuizAccessIpAddress';
ruleName = 'quizaccess_ipaddress';
constructor() {
// Nothing to do.
}
/**
* Whether or not the handler is enabled on a site level.
*
* @return True or promise resolved with true if enabled.
*/
| (): boolean | Promise<boolean> {
return true;
}
/**
* Whether the rule requires a preflight check when prefetch/start/continue an attempt.
*
* @param quiz The quiz the rule belongs to.
* @param attempt The attempt started/continued. If not supplied, user is starting a new attempt.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Whether the rule requires a preflight check.
*/
isPreflightCheckRequired(quiz: any, attempt?: any, prefetch?: boolean, siteId?: string): boolean | Promise<boolean> {
return false;
}
}
| isEnabled | identifier_name |
handler.ts | // (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { AddonModQuizAccessRuleHandler } from '../../../providers/access-rules-delegate';
/**
* Handler to support IP address access rule.
*/
@Injectable()
export class AddonModQuizAccessIpAddressHandler implements AddonModQuizAccessRuleHandler {
name = 'AddonModQuizAccessIpAddress';
ruleName = 'quizaccess_ipaddress';
constructor() {
// Nothing to do.
}
/**
* Whether or not the handler is enabled on a site level.
*
* @return True or promise resolved with true if enabled.
*/
isEnabled(): boolean | Promise<boolean> {
return true;
}
/**
* Whether the rule requires a preflight check when prefetch/start/continue an attempt.
*
* @param quiz The quiz the rule belongs to.
* @param attempt The attempt started/continued. If not supplied, user is starting a new attempt.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Whether the rule requires a preflight check.
*/
isPreflightCheckRequired(quiz: any, attempt?: any, prefetch?: boolean, siteId?: string): boolean | Promise<boolean> {
return false;
}
} | // 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 | random_line_split |
handler.ts |
// (C) Copyright 2015 Moodle Pty Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Injectable } from '@angular/core';
import { AddonModQuizAccessRuleHandler } from '../../../providers/access-rules-delegate';
/**
* Handler to support IP address access rule.
*/
@Injectable()
export class AddonModQuizAccessIpAddressHandler implements AddonModQuizAccessRuleHandler {
name = 'AddonModQuizAccessIpAddress';
ruleName = 'quizaccess_ipaddress';
constructor() {
// Nothing to do.
}
/**
* Whether or not the handler is enabled on a site level.
*
* @return True or promise resolved with true if enabled.
*/
isEnabled(): boolean | Promise<boolean> |
/**
* Whether the rule requires a preflight check when prefetch/start/continue an attempt.
*
* @param quiz The quiz the rule belongs to.
* @param attempt The attempt started/continued. If not supplied, user is starting a new attempt.
* @param prefetch Whether the user is prefetching the quiz.
* @param siteId Site ID. If not defined, current site.
* @return Whether the rule requires a preflight check.
*/
isPreflightCheckRequired(quiz: any, attempt?: any, prefetch?: boolean, siteId?: string): boolean | Promise<boolean> {
return false;
}
}
| {
return true;
} | identifier_body |
builders.rs | use std::fmt;
use std::rc::Rc;
use quire::validate as V;
use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor};
use serde::ser::{Serializer, Serialize};
use crate::build_step::{Step, BuildStep};
use crate::builder::commands as cmd;
macro_rules! define_commands {
($($module: ident :: $item: ident,)*) => {
const COMMANDS: &'static [&'static str] = &[
$(stringify!($item),)*
];
pub enum CommandName {
$($item,)*
}
pub fn builder_validator<'x>() -> V::Enum<'x> {
V::Enum::new()
$(
.option(stringify!($item), cmd::$module::$item::config())
)*
}
impl<'a> Visitor<'a> for NameVisitor {
type Value = CommandName;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "build step is one of {}", COMMANDS.join(", "))
}
fn visit_str<E: de::Error>(self, val: &str)
-> Result<CommandName, E>
{
use self::CommandName::*;
let res = match val {
$(
stringify!($item) => $item,
)*
_ => return Err(E::custom("invalid build step")),
};
Ok(res)
}
}
impl<'a> Visitor<'a> for StepVisitor {
type Value = Step;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "build step is one of {}", COMMANDS.join(", "))
}
fn visit_enum<A>(self, data: A) -> Result<Step, A::Error>
where A: EnumAccess<'a>,
{
use self::CommandName::*;
let (tag, v) = data.variant()?;
match tag {
$(
$item => decode::<cmd::$module::$item, _>(v),
)*
}
}
}
impl Serialize for Step {
fn serialize<S: Serializer>(&self, s: S) | {
if false { unreachable!() }
$(
else if let Some(b) =
self.0.downcast_ref::<cmd::$module::$item>()
{
b.serialize(s)
}
)*
else {
unreachable!("all steps should be serializeable");
}
}
}
}
}
define_commands! {
alpine::Alpine,
alpine::AlpineRepo,
ubuntu::Ubuntu,
ubuntu::UbuntuRepo,
ubuntu::UbuntuRelease,
ubuntu::UbuntuPPA,
ubuntu::UbuntuUniverse,
ubuntu::AptTrust,
packaging::Repo,
packaging::Install,
packaging::BuildDeps,
vcs::Git,
vcs::GitInstall,
vcs::GitDescribe,
pip::PipConfig,
pip::Py2Install,
pip::Py2Requirements,
pip::Py3Install,
pip::Py3Requirements,
tarcmd::Tar,
tarcmd::TarInstall,
unzip::Unzip,
generic::Sh,
generic::Cmd,
generic::RunAs,
generic::Env,
text::Text,
copy::Copy,
download::Download,
dirs::EnsureDir,
dirs::CacheDirs,
dirs::EmptyDir,
dirs::Remove,
copy::Depends,
subcontainer::Container,
subcontainer::Build,
subcontainer::SubConfig,
npm::NpmConfig,
npm::NpmDependencies,
npm::YarnDependencies,
npm::NpmInstall,
gem::GemInstall,
gem::GemBundle,
gem::GemConfig,
composer::ComposerInstall,
composer::ComposerDependencies,
composer::ComposerConfig,
}
pub struct NameVisitor;
pub struct StepVisitor;
fn decode<'x, T, V>(v: V)
-> Result<Step, V::Error>
where
T: BuildStep + Deserialize<'x> + 'static,
V: VariantAccess<'x>,
{
v.newtype_variant::<T>().map(|x| Step(Rc::new(x) as Rc<dyn BuildStep>))
}
impl<'a> Deserialize<'a> for CommandName {
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<CommandName, D::Error>
{
d.deserialize_identifier(NameVisitor)
}
}
impl<'a> Deserialize<'a> for Step {
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Step, D::Error> {
d.deserialize_enum("BuildStep", COMMANDS, StepVisitor)
}
} | -> Result<S::Ok, S::Error> | random_line_split |
builders.rs | use std::fmt;
use std::rc::Rc;
use quire::validate as V;
use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor};
use serde::ser::{Serializer, Serialize};
use crate::build_step::{Step, BuildStep};
use crate::builder::commands as cmd;
macro_rules! define_commands {
($($module: ident :: $item: ident,)*) => {
const COMMANDS: &'static [&'static str] = &[
$(stringify!($item),)*
];
pub enum CommandName {
$($item,)*
}
pub fn builder_validator<'x>() -> V::Enum<'x> {
V::Enum::new()
$(
.option(stringify!($item), cmd::$module::$item::config())
)*
}
impl<'a> Visitor<'a> for NameVisitor {
type Value = CommandName;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "build step is one of {}", COMMANDS.join(", "))
}
fn visit_str<E: de::Error>(self, val: &str)
-> Result<CommandName, E>
{
use self::CommandName::*;
let res = match val {
$(
stringify!($item) => $item,
)*
_ => return Err(E::custom("invalid build step")),
};
Ok(res)
}
}
impl<'a> Visitor<'a> for StepVisitor {
type Value = Step;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "build step is one of {}", COMMANDS.join(", "))
}
fn visit_enum<A>(self, data: A) -> Result<Step, A::Error>
where A: EnumAccess<'a>,
{
use self::CommandName::*;
let (tag, v) = data.variant()?;
match tag {
$(
$item => decode::<cmd::$module::$item, _>(v),
)*
}
}
}
impl Serialize for Step {
fn serialize<S: Serializer>(&self, s: S)
-> Result<S::Ok, S::Error>
{
if false { unreachable!() }
$(
else if let Some(b) =
self.0.downcast_ref::<cmd::$module::$item>()
{
b.serialize(s)
}
)*
else {
unreachable!("all steps should be serializeable");
}
}
}
}
}
define_commands! {
alpine::Alpine,
alpine::AlpineRepo,
ubuntu::Ubuntu,
ubuntu::UbuntuRepo,
ubuntu::UbuntuRelease,
ubuntu::UbuntuPPA,
ubuntu::UbuntuUniverse,
ubuntu::AptTrust,
packaging::Repo,
packaging::Install,
packaging::BuildDeps,
vcs::Git,
vcs::GitInstall,
vcs::GitDescribe,
pip::PipConfig,
pip::Py2Install,
pip::Py2Requirements,
pip::Py3Install,
pip::Py3Requirements,
tarcmd::Tar,
tarcmd::TarInstall,
unzip::Unzip,
generic::Sh,
generic::Cmd,
generic::RunAs,
generic::Env,
text::Text,
copy::Copy,
download::Download,
dirs::EnsureDir,
dirs::CacheDirs,
dirs::EmptyDir,
dirs::Remove,
copy::Depends,
subcontainer::Container,
subcontainer::Build,
subcontainer::SubConfig,
npm::NpmConfig,
npm::NpmDependencies,
npm::YarnDependencies,
npm::NpmInstall,
gem::GemInstall,
gem::GemBundle,
gem::GemConfig,
composer::ComposerInstall,
composer::ComposerDependencies,
composer::ComposerConfig,
}
pub struct NameVisitor;
pub struct | ;
fn decode<'x, T, V>(v: V)
-> Result<Step, V::Error>
where
T: BuildStep + Deserialize<'x> + 'static,
V: VariantAccess<'x>,
{
v.newtype_variant::<T>().map(|x| Step(Rc::new(x) as Rc<dyn BuildStep>))
}
impl<'a> Deserialize<'a> for CommandName {
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<CommandName, D::Error>
{
d.deserialize_identifier(NameVisitor)
}
}
impl<'a> Deserialize<'a> for Step {
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Step, D::Error> {
d.deserialize_enum("BuildStep", COMMANDS, StepVisitor)
}
}
| StepVisitor | identifier_name |
builders.rs | use std::fmt;
use std::rc::Rc;
use quire::validate as V;
use serde::de::{self, Deserializer, Deserialize, EnumAccess, VariantAccess, Visitor};
use serde::ser::{Serializer, Serialize};
use crate::build_step::{Step, BuildStep};
use crate::builder::commands as cmd;
macro_rules! define_commands {
($($module: ident :: $item: ident,)*) => {
const COMMANDS: &'static [&'static str] = &[
$(stringify!($item),)*
];
pub enum CommandName {
$($item,)*
}
pub fn builder_validator<'x>() -> V::Enum<'x> {
V::Enum::new()
$(
.option(stringify!($item), cmd::$module::$item::config())
)*
}
impl<'a> Visitor<'a> for NameVisitor {
type Value = CommandName;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "build step is one of {}", COMMANDS.join(", "))
}
fn visit_str<E: de::Error>(self, val: &str)
-> Result<CommandName, E>
{
use self::CommandName::*;
let res = match val {
$(
stringify!($item) => $item,
)*
_ => return Err(E::custom("invalid build step")),
};
Ok(res)
}
}
impl<'a> Visitor<'a> for StepVisitor {
type Value = Step;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "build step is one of {}", COMMANDS.join(", "))
}
fn visit_enum<A>(self, data: A) -> Result<Step, A::Error>
where A: EnumAccess<'a>,
{
use self::CommandName::*;
let (tag, v) = data.variant()?;
match tag {
$(
$item => decode::<cmd::$module::$item, _>(v),
)*
}
}
}
impl Serialize for Step {
fn serialize<S: Serializer>(&self, s: S)
-> Result<S::Ok, S::Error>
{
if false { unreachable!() }
$(
else if let Some(b) =
self.0.downcast_ref::<cmd::$module::$item>()
{
b.serialize(s)
}
)*
else {
unreachable!("all steps should be serializeable");
}
}
}
}
}
define_commands! {
alpine::Alpine,
alpine::AlpineRepo,
ubuntu::Ubuntu,
ubuntu::UbuntuRepo,
ubuntu::UbuntuRelease,
ubuntu::UbuntuPPA,
ubuntu::UbuntuUniverse,
ubuntu::AptTrust,
packaging::Repo,
packaging::Install,
packaging::BuildDeps,
vcs::Git,
vcs::GitInstall,
vcs::GitDescribe,
pip::PipConfig,
pip::Py2Install,
pip::Py2Requirements,
pip::Py3Install,
pip::Py3Requirements,
tarcmd::Tar,
tarcmd::TarInstall,
unzip::Unzip,
generic::Sh,
generic::Cmd,
generic::RunAs,
generic::Env,
text::Text,
copy::Copy,
download::Download,
dirs::EnsureDir,
dirs::CacheDirs,
dirs::EmptyDir,
dirs::Remove,
copy::Depends,
subcontainer::Container,
subcontainer::Build,
subcontainer::SubConfig,
npm::NpmConfig,
npm::NpmDependencies,
npm::YarnDependencies,
npm::NpmInstall,
gem::GemInstall,
gem::GemBundle,
gem::GemConfig,
composer::ComposerInstall,
composer::ComposerDependencies,
composer::ComposerConfig,
}
pub struct NameVisitor;
pub struct StepVisitor;
fn decode<'x, T, V>(v: V)
-> Result<Step, V::Error>
where
T: BuildStep + Deserialize<'x> + 'static,
V: VariantAccess<'x>,
{
v.newtype_variant::<T>().map(|x| Step(Rc::new(x) as Rc<dyn BuildStep>))
}
impl<'a> Deserialize<'a> for CommandName {
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<CommandName, D::Error>
|
}
impl<'a> Deserialize<'a> for Step {
fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Step, D::Error> {
d.deserialize_enum("BuildStep", COMMANDS, StepVisitor)
}
}
| {
d.deserialize_identifier(NameVisitor)
} | identifier_body |
test_therm.py | import RPi.GPIO as GPIO
import time
import utils
import therm
GPIO.setmode(GPIO.BOARD)
#pwr = utils.PSU(13, 15)
#pwr.on() | now = time.time()
t_amb = therm.Therm('28-000004e08693')
t_c_b = therm.Therm('28-000004e0f7cc')
t_c_m = therm.Therm('28-000004e0840a')
t_c_t = therm.Therm('28-000004e08e26')
t_hs = therm.Therm('28-000004e0804f')
print time.time() - now
now = time.time()
for i in range(samples):
temp_row = [t_amb.read_temp(), t_c_b.read_temp(), t_c_m.read_temp(), t_c_t.read_temp(), t_hs.read_temp()]
print temp_row
therms.append(temp_row)
print time.time() - now
now = time.time()
print therms
#GPIO.cleanup() | #pwr.off()
adresses = therm.get_adr()
samples = 5
therms = [] | random_line_split |
test_therm.py | import RPi.GPIO as GPIO
import time
import utils
import therm
GPIO.setmode(GPIO.BOARD)
#pwr = utils.PSU(13, 15)
#pwr.on()
#pwr.off()
adresses = therm.get_adr()
samples = 5
therms = []
now = time.time()
t_amb = therm.Therm('28-000004e08693')
t_c_b = therm.Therm('28-000004e0f7cc')
t_c_m = therm.Therm('28-000004e0840a')
t_c_t = therm.Therm('28-000004e08e26')
t_hs = therm.Therm('28-000004e0804f')
print time.time() - now
now = time.time()
for i in range(samples):
|
print therms
#GPIO.cleanup()
| temp_row = [t_amb.read_temp(), t_c_b.read_temp(), t_c_m.read_temp(), t_c_t.read_temp(), t_hs.read_temp()]
print temp_row
therms.append(temp_row)
print time.time() - now
now = time.time() | conditional_block |
settings.py | # Copyright (c) 2009-2020 - Simon Conseil
# Copyright (c) 2013 - Christophe-Marie Duquesne
# Copyright (c) 2017 - Mate Lakat
# 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.
import logging
import os
from os.path import abspath, isabs, join, normpath
from pprint import pformat
_DEFAULT_CONFIG = {
'albums_sort_attr': 'name',
'albums_sort_reverse': False,
'autorotate_images': True,
'colorbox_column_size': 3,
'copy_exif_data': False,
'datetime_format': '%c',
'destination': '_build',
'files_to_copy': (),
'google_analytics': '',
'google_tag_manager': '',
'ignore_directories': [],
'ignore_files': [],
'img_extensions': ['.jpg', '.jpeg', '.png', '.gif'],
'img_processor': 'ResizeToFit',
'img_size': (640, 480),
'img_format': None,
'index_in_url': False,
'jpg_options': {'quality': 85, 'optimize': True, 'progressive': True},
'keep_orig': False,
'html_language': 'en',
'leaflet_provider': 'OpenStreetMap.Mapnik',
'links': '',
'locale': '',
'make_thumbs': True,
'medias_sort_attr': 'filename',
'medias_sort_reverse': False,
'mp4_options': ['-crf', '23', '-strict', '-2'],
'orig_dir': 'original',
'orig_link': False,
'rel_link': False,
'output_filename': 'index.html',
'piwik': {'tracker_url': '', 'site_id': 0},
'plugin_paths': [],
'plugins': [],
'site_logo': '',
'show_map': False,
'source': '',
'theme': 'colorbox',
'thumb_dir': 'thumbnails',
'thumb_fit': True,
'thumb_fit_centering': (0.5, 0.5),
'thumb_prefix': '',
'thumb_size': (200, 150),
'thumb_suffix': '',
'thumb_video_delay': '0',
'title': '',
'use_orig': False,
'video_converter': 'ffmpeg',
'video_extensions': ['.mov', '.avi', '.mp4', '.webm', '.ogv', '.3gp'],
'video_format': 'webm',
'video_size': (480, 360),
'watermark': '',
'webm_options': ['-crf', '10', '-b:v', '1.6M',
'-qmin', '4', '-qmax', '63'],
'write_html': True,
'zip_gallery': False,
'zip_media_format': 'resized',
}
class Status:
SUCCESS = 0
FAILURE = 1
def get_thumb(settings, filename):
"""Return the path to the thumb.
examples:
>>> default_settings = create_settings()
>>> get_thumb(default_settings, "bar/foo.jpg")
"bar/thumbnails/foo.jpg"
>>> get_thumb(default_settings, "bar/foo.png")
"bar/thumbnails/foo.png"
for videos, it returns a jpg file:
>>> get_thumb(default_settings, "bar/foo.webm")
"bar/thumbnails/foo.jpg"
"""
path, filen = os.path.split(filename)
name, ext = os.path.splitext(filen)
if ext.lower() in settings['video_extensions']:
ext = '.jpg'
return join(path, settings['thumb_dir'], settings['thumb_prefix'] +
name + settings['thumb_suffix'] + ext)
def | (filename=None):
"""Read settings from a config file in the source_dir root."""
logger = logging.getLogger(__name__)
logger.info("Reading settings ...")
settings = _DEFAULT_CONFIG.copy()
if filename:
logger.debug("Settings file: %s", filename)
settings_path = os.path.dirname(filename)
tempdict = {}
with open(filename) as f:
code = compile(f.read(), filename, 'exec')
exec(code, tempdict)
settings.update((k, v) for k, v in tempdict.items()
if k not in ['__builtins__'])
# Make the paths relative to the settings file
paths = ['source', 'destination', 'watermark']
if os.path.isdir(join(settings_path, settings['theme'])) and \
os.path.isdir(join(settings_path, settings['theme'],
'templates')):
paths.append('theme')
for p in paths:
path = settings[p]
if path and not isabs(path):
settings[p] = abspath(normpath(join(settings_path, path)))
logger.debug("Rewrite %s : %s -> %s", p, path, settings[p])
for key in ('img_size', 'thumb_size', 'video_size'):
w, h = settings[key]
if h > w:
settings[key] = (h, w)
logger.warning("The %s setting should be specified with the "
"largest value first.", key)
if not settings['img_processor']:
logger.info('No Processor, images will not be resized')
logger.debug('Settings:\n%s', pformat(settings, width=120))
return settings
def create_settings(**kwargs):
"""Create a new default setting copy and initialize it with kwargs."""
settings = _DEFAULT_CONFIG.copy()
settings.update(kwargs)
return settings
| read_settings | identifier_name |
settings.py | # Copyright (c) 2009-2020 - Simon Conseil
# Copyright (c) 2013 - Christophe-Marie Duquesne
# Copyright (c) 2017 - Mate Lakat
# 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.
import logging
import os
from os.path import abspath, isabs, join, normpath
from pprint import pformat
_DEFAULT_CONFIG = {
'albums_sort_attr': 'name',
'albums_sort_reverse': False,
'autorotate_images': True,
'colorbox_column_size': 3,
'copy_exif_data': False,
'datetime_format': '%c',
'destination': '_build',
'files_to_copy': (),
'google_analytics': '',
'google_tag_manager': '',
'ignore_directories': [],
'ignore_files': [],
'img_extensions': ['.jpg', '.jpeg', '.png', '.gif'],
'img_processor': 'ResizeToFit',
'img_size': (640, 480),
'img_format': None,
'index_in_url': False,
'jpg_options': {'quality': 85, 'optimize': True, 'progressive': True},
'keep_orig': False,
'html_language': 'en',
'leaflet_provider': 'OpenStreetMap.Mapnik',
'links': '',
'locale': '',
'make_thumbs': True,
'medias_sort_attr': 'filename',
'medias_sort_reverse': False,
'mp4_options': ['-crf', '23', '-strict', '-2'],
'orig_dir': 'original',
'orig_link': False,
'rel_link': False,
'output_filename': 'index.html',
'piwik': {'tracker_url': '', 'site_id': 0},
'plugin_paths': [],
'plugins': [],
'site_logo': '',
'show_map': False,
'source': '',
'theme': 'colorbox',
'thumb_dir': 'thumbnails',
'thumb_fit': True,
'thumb_fit_centering': (0.5, 0.5),
'thumb_prefix': '',
'thumb_size': (200, 150),
'thumb_suffix': '',
'thumb_video_delay': '0',
'title': '',
'use_orig': False,
'video_converter': 'ffmpeg',
'video_extensions': ['.mov', '.avi', '.mp4', '.webm', '.ogv', '.3gp'],
'video_format': 'webm',
'video_size': (480, 360),
'watermark': '',
'webm_options': ['-crf', '10', '-b:v', '1.6M',
'-qmin', '4', '-qmax', '63'],
'write_html': True,
'zip_gallery': False,
'zip_media_format': 'resized',
}
class Status:
SUCCESS = 0
FAILURE = 1
def get_thumb(settings, filename):
"""Return the path to the thumb.
examples:
>>> default_settings = create_settings()
>>> get_thumb(default_settings, "bar/foo.jpg")
"bar/thumbnails/foo.jpg"
>>> get_thumb(default_settings, "bar/foo.png")
"bar/thumbnails/foo.png"
for videos, it returns a jpg file:
>>> get_thumb(default_settings, "bar/foo.webm")
"bar/thumbnails/foo.jpg"
"""
path, filen = os.path.split(filename)
name, ext = os.path.splitext(filen)
if ext.lower() in settings['video_extensions']:
ext = '.jpg'
return join(path, settings['thumb_dir'], settings['thumb_prefix'] +
name + settings['thumb_suffix'] + ext)
def read_settings(filename=None):
"""Read settings from a config file in the source_dir root."""
logger = logging.getLogger(__name__)
logger.info("Reading settings ...")
settings = _DEFAULT_CONFIG.copy()
if filename:
logger.debug("Settings file: %s", filename)
settings_path = os.path.dirname(filename)
tempdict = {}
with open(filename) as f:
code = compile(f.read(), filename, 'exec')
exec(code, tempdict)
settings.update((k, v) for k, v in tempdict.items()
if k not in ['__builtins__'])
# Make the paths relative to the settings file
paths = ['source', 'destination', 'watermark']
if os.path.isdir(join(settings_path, settings['theme'])) and \
os.path.isdir(join(settings_path, settings['theme'],
'templates')):
paths.append('theme')
for p in paths:
path = settings[p]
if path and not isabs(path):
settings[p] = abspath(normpath(join(settings_path, path)))
logger.debug("Rewrite %s : %s -> %s", p, path, settings[p])
for key in ('img_size', 'thumb_size', 'video_size'):
|
if not settings['img_processor']:
logger.info('No Processor, images will not be resized')
logger.debug('Settings:\n%s', pformat(settings, width=120))
return settings
def create_settings(**kwargs):
"""Create a new default setting copy and initialize it with kwargs."""
settings = _DEFAULT_CONFIG.copy()
settings.update(kwargs)
return settings
| w, h = settings[key]
if h > w:
settings[key] = (h, w)
logger.warning("The %s setting should be specified with the "
"largest value first.", key) | conditional_block |
settings.py | # Copyright (c) 2009-2020 - Simon Conseil
# Copyright (c) 2013 - Christophe-Marie Duquesne
# Copyright (c) 2017 - Mate Lakat
# 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.
import logging
import os
from os.path import abspath, isabs, join, normpath
from pprint import pformat
_DEFAULT_CONFIG = {
'albums_sort_attr': 'name',
'albums_sort_reverse': False,
'autorotate_images': True,
'colorbox_column_size': 3,
'copy_exif_data': False,
'datetime_format': '%c',
'destination': '_build',
'files_to_copy': (),
'google_analytics': '',
'google_tag_manager': '',
'ignore_directories': [],
'ignore_files': [],
'img_extensions': ['.jpg', '.jpeg', '.png', '.gif'],
'img_processor': 'ResizeToFit',
'img_size': (640, 480),
'img_format': None,
'index_in_url': False,
'jpg_options': {'quality': 85, 'optimize': True, 'progressive': True},
'keep_orig': False,
'html_language': 'en',
'leaflet_provider': 'OpenStreetMap.Mapnik',
'links': '',
'locale': '',
'make_thumbs': True,
'medias_sort_attr': 'filename',
'medias_sort_reverse': False,
'mp4_options': ['-crf', '23', '-strict', '-2'],
'orig_dir': 'original',
'orig_link': False,
'rel_link': False,
'output_filename': 'index.html',
'piwik': {'tracker_url': '', 'site_id': 0},
'plugin_paths': [],
'plugins': [],
'site_logo': '',
'show_map': False,
'source': '',
'theme': 'colorbox',
'thumb_dir': 'thumbnails',
'thumb_fit': True,
'thumb_fit_centering': (0.5, 0.5),
'thumb_prefix': '',
'thumb_size': (200, 150),
'thumb_suffix': '',
'thumb_video_delay': '0',
'title': '',
'use_orig': False,
'video_converter': 'ffmpeg',
'video_extensions': ['.mov', '.avi', '.mp4', '.webm', '.ogv', '.3gp'],
'video_format': 'webm',
'video_size': (480, 360),
'watermark': '',
'webm_options': ['-crf', '10', '-b:v', '1.6M',
'-qmin', '4', '-qmax', '63'],
'write_html': True,
'zip_gallery': False,
'zip_media_format': 'resized',
}
class Status:
SUCCESS = 0
FAILURE = 1
def get_thumb(settings, filename):
"""Return the path to the thumb.
examples:
>>> default_settings = create_settings()
>>> get_thumb(default_settings, "bar/foo.jpg")
"bar/thumbnails/foo.jpg"
>>> get_thumb(default_settings, "bar/foo.png")
"bar/thumbnails/foo.png"
for videos, it returns a jpg file:
>>> get_thumb(default_settings, "bar/foo.webm")
"bar/thumbnails/foo.jpg"
"""
path, filen = os.path.split(filename)
name, ext = os.path.splitext(filen)
if ext.lower() in settings['video_extensions']:
ext = '.jpg'
return join(path, settings['thumb_dir'], settings['thumb_prefix'] +
name + settings['thumb_suffix'] + ext)
def read_settings(filename=None):
"""Read settings from a config file in the source_dir root."""
logger = logging.getLogger(__name__)
logger.info("Reading settings ...")
settings = _DEFAULT_CONFIG.copy()
if filename:
logger.debug("Settings file: %s", filename)
settings_path = os.path.dirname(filename)
tempdict = {}
with open(filename) as f:
code = compile(f.read(), filename, 'exec')
exec(code, tempdict)
settings.update((k, v) for k, v in tempdict.items()
if k not in ['__builtins__'])
# Make the paths relative to the settings file
paths = ['source', 'destination', 'watermark']
if os.path.isdir(join(settings_path, settings['theme'])) and \
os.path.isdir(join(settings_path, settings['theme'],
'templates')):
paths.append('theme')
for p in paths:
path = settings[p]
if path and not isabs(path):
settings[p] = abspath(normpath(join(settings_path, path)))
logger.debug("Rewrite %s : %s -> %s", p, path, settings[p])
for key in ('img_size', 'thumb_size', 'video_size'):
w, h = settings[key]
if h > w:
settings[key] = (h, w)
logger.warning("The %s setting should be specified with the "
"largest value first.", key)
if not settings['img_processor']:
logger.info('No Processor, images will not be resized')
logger.debug('Settings:\n%s', pformat(settings, width=120))
return settings
def create_settings(**kwargs):
| """Create a new default setting copy and initialize it with kwargs."""
settings = _DEFAULT_CONFIG.copy()
settings.update(kwargs)
return settings | identifier_body | |
settings.py | # Copyright (c) 2009-2020 - Simon Conseil
# Copyright (c) 2013 - Christophe-Marie Duquesne
# Copyright (c) 2017 - Mate Lakat
# 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.
import logging
import os
from os.path import abspath, isabs, join, normpath
from pprint import pformat
_DEFAULT_CONFIG = {
'albums_sort_attr': 'name',
'albums_sort_reverse': False,
'autorotate_images': True,
'colorbox_column_size': 3,
'copy_exif_data': False,
'datetime_format': '%c',
'destination': '_build',
'files_to_copy': (),
'google_analytics': '',
'google_tag_manager': '',
'ignore_directories': [],
'ignore_files': [],
'img_extensions': ['.jpg', '.jpeg', '.png', '.gif'],
'img_processor': 'ResizeToFit',
'img_size': (640, 480),
'img_format': None,
'index_in_url': False,
'jpg_options': {'quality': 85, 'optimize': True, 'progressive': True},
'keep_orig': False,
'html_language': 'en',
'leaflet_provider': 'OpenStreetMap.Mapnik',
'links': '',
'locale': '',
'make_thumbs': True,
'medias_sort_attr': 'filename',
'medias_sort_reverse': False,
'mp4_options': ['-crf', '23', '-strict', '-2'],
'orig_dir': 'original',
'orig_link': False,
'rel_link': False,
'output_filename': 'index.html',
'piwik': {'tracker_url': '', 'site_id': 0},
'plugin_paths': [],
'plugins': [],
'site_logo': '',
'show_map': False,
'source': '',
'theme': 'colorbox',
'thumb_dir': 'thumbnails',
'thumb_fit': True,
'thumb_fit_centering': (0.5, 0.5),
'thumb_prefix': '',
'thumb_size': (200, 150),
'thumb_suffix': '',
'thumb_video_delay': '0',
'title': '',
'use_orig': False,
'video_converter': 'ffmpeg',
'video_extensions': ['.mov', '.avi', '.mp4', '.webm', '.ogv', '.3gp'],
'video_format': 'webm',
'video_size': (480, 360),
'watermark': '',
'webm_options': ['-crf', '10', '-b:v', '1.6M',
'-qmin', '4', '-qmax', '63'],
'write_html': True,
'zip_gallery': False,
'zip_media_format': 'resized',
}
class Status:
SUCCESS = 0
FAILURE = 1
|
examples:
>>> default_settings = create_settings()
>>> get_thumb(default_settings, "bar/foo.jpg")
"bar/thumbnails/foo.jpg"
>>> get_thumb(default_settings, "bar/foo.png")
"bar/thumbnails/foo.png"
for videos, it returns a jpg file:
>>> get_thumb(default_settings, "bar/foo.webm")
"bar/thumbnails/foo.jpg"
"""
path, filen = os.path.split(filename)
name, ext = os.path.splitext(filen)
if ext.lower() in settings['video_extensions']:
ext = '.jpg'
return join(path, settings['thumb_dir'], settings['thumb_prefix'] +
name + settings['thumb_suffix'] + ext)
def read_settings(filename=None):
"""Read settings from a config file in the source_dir root."""
logger = logging.getLogger(__name__)
logger.info("Reading settings ...")
settings = _DEFAULT_CONFIG.copy()
if filename:
logger.debug("Settings file: %s", filename)
settings_path = os.path.dirname(filename)
tempdict = {}
with open(filename) as f:
code = compile(f.read(), filename, 'exec')
exec(code, tempdict)
settings.update((k, v) for k, v in tempdict.items()
if k not in ['__builtins__'])
# Make the paths relative to the settings file
paths = ['source', 'destination', 'watermark']
if os.path.isdir(join(settings_path, settings['theme'])) and \
os.path.isdir(join(settings_path, settings['theme'],
'templates')):
paths.append('theme')
for p in paths:
path = settings[p]
if path and not isabs(path):
settings[p] = abspath(normpath(join(settings_path, path)))
logger.debug("Rewrite %s : %s -> %s", p, path, settings[p])
for key in ('img_size', 'thumb_size', 'video_size'):
w, h = settings[key]
if h > w:
settings[key] = (h, w)
logger.warning("The %s setting should be specified with the "
"largest value first.", key)
if not settings['img_processor']:
logger.info('No Processor, images will not be resized')
logger.debug('Settings:\n%s', pformat(settings, width=120))
return settings
def create_settings(**kwargs):
"""Create a new default setting copy and initialize it with kwargs."""
settings = _DEFAULT_CONFIG.copy()
settings.update(kwargs)
return settings |
def get_thumb(settings, filename):
"""Return the path to the thumb. | random_line_split |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use package_id::PackageId;
use util::{CraftResult, Human, Freshness, internal, ChainError, profile, paths};
use super::job::Work;
use super::{fingerprint, Kind, Context, Unit};
/// Contains the parsed output of a custom build script.
#[derive(Clone, Debug, Hash)]
pub struct BuildOutput {
/// Paths to pass to cc with the `-L` flag
pub library_paths: Vec<PathBuf>,
/// Names and link kinds of libraries, suitable for the `-l` flag
pub library_links: Vec<String>,
/// Metadata to pass to the immediate dependencies
pub metadata: Vec<(String, String)>,
/// Glob paths to trigger a rerun of this build script.
pub rerun_if_changed: Vec<String>,
/// Warnings generated by this build,
pub warnings: Vec<String>,
}
pub type BuildMap = HashMap<(PackageId, Kind), BuildOutput>;
pub struct BuildState {
pub outputs: Mutex<BuildMap>,
overrides: HashMap<(String, Kind), BuildOutput>,
}
#[derive(Default)]
pub struct BuildScripts {
// Craft will use this `to_link` vector to add -L flags to compiles as we
// propagate them upwards towards the final build. Note, however, that we
// need to preserve the ordering of `to_link` to be topologically sorted.
// This will ensure that build scripts which print their paths properly will
// correctly pick up the files they generated (if there are duplicates
// elsewhere).
//
// To preserve this ordering, the (id, kind) is stored in two places, once
// in the `Vec` and once in `seen_to_link` for a fast lookup. We maintain
// this as we're building interactively below to ensure that the memory
// usage here doesn't blow up too much.
//
// For more information, see #2354
pub to_link: Vec<(PackageId, Kind)>,
seen_to_link: HashSet<(PackageId, Kind)>,
pub plugins: BTreeSet<PackageId>,
}
/// Prepares a `Work` that executes the target as a custom build script.
///
/// The `req` given is the requirement which this run of the build script will
/// prepare work for. If the requirement is specified as both the target and the
/// host platforms it is assumed that the two are equal and the build script is
/// only run once (not twice).
pub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CraftResult<(Work, Work, Freshness)> {
let _p = profile::start(format!("build script prepare: {}/{}", unit.pkg, unit.target.name()));
let overridden = cx.build_state.has_override(unit);
let (work_dirty, work_fresh) = if overridden {
(Work::new(|_| Ok(())), Work::new(|_| Ok(())))
} else {
build_work(cx, unit)?
};
// Now that we've prep'd our work, build the work needed to manage the
// fingerprint and then start returning that upwards.
let (freshness, dirty, fresh) = fingerprint::prepare_build_cmd(cx, unit)?;
Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness))
}
fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CraftResult<(Work, Work)> {
let host_unit = Unit { kind: Kind::Host, ..*unit };
let (script_output, build_output) = {
(cx.layout(&host_unit).build(unit.pkg), cx.layout(unit).build_out(unit.pkg))
};
// Building the command to execute
let to_exec = script_output.join(unit.target.name());
// Start preparing the process to execute, starting out with some
// environment variables. Note that the profile-related environment
// variables are not set with this the build script's profile but rather the
// package's library profile.
let profile = cx.lib_profile(unit.pkg.package_id());
let to_exec = to_exec.into_os_string();
let mut cmd = cx.compilation.host_process(to_exec, unit.pkg)?;
cmd.env("OUT_DIR", &build_output)
.env("CRAFT_MANIFEST_DIR", unit.pkg.root())
.env("NUM_JOBS", &cx.jobs().to_string())
.env("TARGET",
&match unit.kind {
Kind::Host => cx.host_triple(),
Kind::Target => cx.target_triple(),
})
.env("DEBUG", &profile.debuginfo.to_string())
.env("OPT_LEVEL", &profile.opt_level)
.env("PROFILE",
if cx.build_config.release {
"release"
} else {
"debug"
})
.env("HOST", cx.host_triple())
.env("CC", &cx.config.cc()?.path)
.env("DOC", &*cx.config.doc()?);
if let Some(links) = unit.pkg.manifest().links() {
cmd.env("CRAFT_MANIFEST_LINKS", links);
}
// Be sure to pass along all enabled features for this package, this is the
// last piece of statically known information that we have.
if let Some(features) = cx.resolve.features(unit.pkg.package_id()) {
for feat in features.iter() {
cmd.env(&format!("CRAFT_FEATURE_{}", super::envify(feat)), "1");
}
}
// Gather the set of native dependencies that this package has along with
// some other variables to close over.
//
// This information will be used at build-time later on to figure out which
// sorts of variables need to be discovered at that time.
let lib_deps = {
cx.dep_run_custom_build(unit)?
.iter()
.filter_map(|unit| {
if unit.profile.run_custom_build {
Some((unit.pkg.manifest().links().unwrap().to_string(), unit.pkg.package_id().clone()))
} else {
None
}
})
.collect::<Vec<_>>()
};
let pkg_name = unit.pkg.to_string();
let build_state = cx.build_state.clone();
let id = unit.pkg.package_id().clone();
let output_file = build_output.parent().unwrap().join("output");
let all = (id.clone(), pkg_name.clone(), build_state.clone(), output_file.clone());
let build_scripts = super::load_build_deps(cx, unit);
let kind = unit.kind;
// Check to see if the build script as already run, and if it has keep
// track of whether it has told us about some explicit dependencies
let prev_output = BuildOutput::parse_file(&output_file, &pkg_name).ok();
let rerun_if_changed = match prev_output {
Some(ref prev) => prev.rerun_if_changed.clone(),
None => Vec::new(),
};
cx.build_explicit_deps.insert(*unit, (output_file.clone(), rerun_if_changed));
fs::create_dir_all(&cx.layout(&host_unit).build(unit.pkg))?;
fs::create_dir_all(&cx.layout(unit).build(unit.pkg))?;
// Prepare the unit of "dirty work" which will actually run the custom build
// command.
//
// Note that this has to do some extra work just before running the command
// to determine extra environment variables and such.
let dirty = Work::new(move |state| {
// Make sure that OUT_DIR exists.
//
// If we have an old build directory, then just move it into place,
// otherwise create it!
if fs::metadata(&build_output).is_err() {
fs::create_dir(&build_output)
.chain_error(|| internal("failed to create script output directory for build command"))?;
}
// For all our native lib dependencies, pick up their metadata to pass
// along to this custom build command. We're also careful to augment our
// dynamic library search path in case the build script depended on any
// native dynamic libraries.
{
let build_state = build_state.outputs.lock().unwrap();
for (name, id) in lib_deps {
let key = (id.clone(), kind);
let state = build_state.get(&key)
.chain_error(|| {
internal(format!("failed to locate build state for env vars: {}/{:?}",
id,
kind))
})?;
let data = &state.metadata;
for &(ref key, ref value) in data.iter() {
cmd.env(&format!("DEP_{}_{}", super::envify(&name), super::envify(key)),
value);
}
}
if let Some(build_scripts) = build_scripts {
super::add_plugin_deps(&mut cmd, &build_state, &build_scripts)?;
}
}
// And now finally, run the build command itself!
state.running(&cmd);
let output = cmd.exec_with_streaming(&mut |out_line| {
state.stdout(out_line);
Ok(())
},
&mut |err_line| {
state.stderr(err_line);
Ok(())
})
.map_err(|mut e| {
e.desc = format!("failed to run custom build command for `{}`\n{}",
pkg_name,
e.desc);
Human(e)
})?;
paths::write(&output_file, &output.stdout)?;
// After the build command has finished running, we need to be sure to
// remember all of its output so we can later discover precisely what it
// was, even if we don't run the build command again (due to freshness).
//
// This is also the location where we provide feedback into the build
// state informing what variables were discovered via our script as
// well.
let parsed_output = BuildOutput::parse(&output.stdout, &pkg_name)?;
build_state.insert(id, kind, parsed_output);
Ok(())
});
// Now that we've prepared our work-to-do, we need to prepare the fresh work
// itself to run when we actually end up just discarding what we calculated
// above.
let fresh = Work::new(move |_tx| {
let (id, pkg_name, build_state, output_file) = all;
let output = match prev_output {
Some(output) => output,
None => BuildOutput::parse_file(&output_file, &pkg_name)?,
};
build_state.insert(id, kind, output);
Ok(())
});
Ok((dirty, fresh))
}
impl BuildState {
pub fn new(config: &super::BuildConfig) -> BuildState {
let mut overrides = HashMap::new();
let i1 = config.host.overrides.iter().map(|p| (p, Kind::Host));
let i2 = config.target.overrides.iter().map(|p| (p, Kind::Target));
for ((name, output), kind) in i1.chain(i2) {
overrides.insert((name.clone(), kind), output.clone());
}
BuildState {
outputs: Mutex::new(HashMap::new()),
overrides: overrides,
}
}
fn insert(&self, id: PackageId, kind: Kind, output: BuildOutput) {
self.outputs.lock().unwrap().insert((id, kind), output);
}
fn has_override(&self, unit: &Unit) -> bool {
let key = unit.pkg.manifest().links().map(|l| (l.to_string(), unit.kind));
match key.and_then(|k| self.overrides.get(&k)) {
Some(output) => {
self.insert(unit.pkg.package_id().clone(), unit.kind, output.clone());
true
}
None => false,
}
}
}
impl BuildOutput {
pub fn parse_file(path: &Path, pkg_name: &str) -> CraftResult<BuildOutput> |
// Parses the output of a script.
// The `pkg_name` is used for error messages.
pub fn parse(input: &[u8], pkg_name: &str) -> CraftResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
let mut metadata = Vec::new();
let mut rerun_if_changed = Vec::new();
let mut warnings = Vec::new();
let whence = format!("build script of `{}`", pkg_name);
for line in input.split(|b| *b == b'\n') {
let line = match str::from_utf8(line) {
Ok(line) => line.trim(),
Err(..) => continue,
};
let mut iter = line.splitn(2, ':');
if iter.next() != Some("craft") {
// skip this line since it doesn't start with "craft:"
continue;
}
let data = match iter.next() {
Some(val) => val,
None => continue,
};
// getting the `key=value` part of the line
let mut iter = data.splitn(2, '=');
let key = iter.next();
let value = iter.next();
let (key, value) = match (key, value) {
(Some(a), Some(b)) => (a, b.trim_right()),
// line started with `craft:` but didn't match `key=value`
_ => bail!("Wrong output in {}: `{}`", whence, line),
};
match key {
"cc-flags" => {
let (libs, links) = BuildOutput::parse_cc_flags(value, &whence)?;
library_links.extend(links.into_iter());
library_paths.extend(libs.into_iter());
}
"cc-link-lib" => library_links.push(value.to_string()),
"cc-link-search" => library_paths.push(PathBuf::from(value)),
"warning" => warnings.push(value.to_string()),
"rerun-if-changed" => rerun_if_changed.push(value.to_string()),
_ => metadata.push((key.to_string(), value.to_string())),
}
}
Ok(BuildOutput {
library_paths: library_paths,
library_links: library_links,
metadata: metadata,
rerun_if_changed: rerun_if_changed,
warnings: warnings,
})
}
pub fn parse_cc_flags(value: &str, whence: &str) -> CraftResult<(Vec<PathBuf>, Vec<String>)> {
let value = value.trim();
let mut flags_iter = value.split(|c: char| c.is_whitespace())
.filter(|w| w.chars().any(|c| !c.is_whitespace()));
let (mut library_links, mut library_paths) = (Vec::new(), Vec::new());
loop {
let flag = match flags_iter.next() {
Some(f) => f,
None => break,
};
if flag != "-l" && flag != "-L" {
bail!("Only `-l` and `-L` flags are allowed in {}: `{}`",
whence,
value)
}
let value = match flags_iter.next() {
Some(v) => v,
None => {
bail!("Flag in cc-flags has no value in {}: `{}`",
whence,
value)
}
};
match flag {
"-l" => library_links.push(value.to_string()),
"-L" => library_paths.push(PathBuf::from(value)),
// was already checked above
_ => bail!("only -l and -L flags are allowed"),
};
}
Ok((library_paths, library_links))
}
}
/// Compute the `build_scripts` map in the `Context` which tracks what build
/// scripts each package depends on.
///
/// The global `build_scripts` map lists for all (package, kind) tuples what set
/// of packages' build script outputs must be considered. For example this lists
/// all dependencies' `-L` flags which need to be propagated transitively.
///
/// The given set of targets to this function is the initial set of
/// targets/profiles which are being built.
pub fn build_map<'b, 'cfg>(cx: &mut Context<'b, 'cfg>, units: &[Unit<'b>]) -> CraftResult<()> {
let mut ret = HashMap::new();
for unit in units {
build(&mut ret, cx, unit)?;
}
cx.build_scripts.extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));
return Ok(());
// Recursive function to build up the map we're constructing. This function
// memoizes all of its return values as it goes along.
fn build<'a, 'b, 'cfg>(out: &'a mut HashMap<Unit<'b>, BuildScripts>,
cx: &Context<'b, 'cfg>,
unit: &Unit<'b>)
-> CraftResult<&'a BuildScripts> {
// Do a quick pre-flight check to see if we've already calculated the
// set of dependencies.
if out.contains_key(unit) {
return Ok(&out[unit]);
}
let mut ret = BuildScripts::default();
if !unit.target.is_custom_build() && unit.pkg.has_custom_build() {
add_to_link(&mut ret, unit.pkg.package_id(), unit.kind);
}
for unit in cx.dep_targets(unit)?.iter() {
let dep_scripts = build(out, cx, unit)?;
if unit.target.for_host() {
ret.plugins.extend(dep_scripts.to_link
.iter()
.map(|p| &p.0)
.cloned());
} else if unit.target.linkable() {
for &(ref pkg, kind) in dep_scripts.to_link.iter() {
add_to_link(&mut ret, pkg, kind);
}
}
}
let prev = out.entry(*unit).or_insert(BuildScripts::default());
for (pkg, kind) in ret.to_link {
add_to_link(prev, &pkg, kind);
}
prev.plugins.extend(ret.plugins);
Ok(prev)
}
// When adding an entry to 'to_link' we only actually push it on if the
// script hasn't seen it yet (e.g. we don't push on duplicates).
fn add_to_link(scripts: &mut BuildScripts, pkg: &PackageId, kind: Kind) {
if scripts.seen_to_link.insert((pkg.clone(), kind)) {
scripts.to_link.push((pkg.clone(), kind));
}
}
}
| {
let contents = paths::read_bytes(path)?;
BuildOutput::parse(&contents, pkg_name)
} | identifier_body |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use package_id::PackageId;
use util::{CraftResult, Human, Freshness, internal, ChainError, profile, paths};
use super::job::Work;
use super::{fingerprint, Kind, Context, Unit};
/// Contains the parsed output of a custom build script.
#[derive(Clone, Debug, Hash)]
pub struct BuildOutput {
/// Paths to pass to cc with the `-L` flag
pub library_paths: Vec<PathBuf>,
/// Names and link kinds of libraries, suitable for the `-l` flag
pub library_links: Vec<String>,
/// Metadata to pass to the immediate dependencies
pub metadata: Vec<(String, String)>,
/// Glob paths to trigger a rerun of this build script.
pub rerun_if_changed: Vec<String>,
/// Warnings generated by this build,
pub warnings: Vec<String>,
}
pub type BuildMap = HashMap<(PackageId, Kind), BuildOutput>;
pub struct BuildState {
pub outputs: Mutex<BuildMap>,
overrides: HashMap<(String, Kind), BuildOutput>,
}
#[derive(Default)]
pub struct BuildScripts {
// Craft will use this `to_link` vector to add -L flags to compiles as we
// propagate them upwards towards the final build. Note, however, that we
// need to preserve the ordering of `to_link` to be topologically sorted.
// This will ensure that build scripts which print their paths properly will
// correctly pick up the files they generated (if there are duplicates
// elsewhere).
//
// To preserve this ordering, the (id, kind) is stored in two places, once
// in the `Vec` and once in `seen_to_link` for a fast lookup. We maintain
// this as we're building interactively below to ensure that the memory
// usage here doesn't blow up too much.
//
// For more information, see #2354
pub to_link: Vec<(PackageId, Kind)>,
seen_to_link: HashSet<(PackageId, Kind)>,
pub plugins: BTreeSet<PackageId>,
}
/// Prepares a `Work` that executes the target as a custom build script.
///
/// The `req` given is the requirement which this run of the build script will
/// prepare work for. If the requirement is specified as both the target and the
/// host platforms it is assumed that the two are equal and the build script is
/// only run once (not twice).
pub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CraftResult<(Work, Work, Freshness)> {
let _p = profile::start(format!("build script prepare: {}/{}", unit.pkg, unit.target.name()));
let overridden = cx.build_state.has_override(unit);
let (work_dirty, work_fresh) = if overridden {
(Work::new(|_| Ok(())), Work::new(|_| Ok(())))
} else {
build_work(cx, unit)?
};
// Now that we've prep'd our work, build the work needed to manage the
// fingerprint and then start returning that upwards.
let (freshness, dirty, fresh) = fingerprint::prepare_build_cmd(cx, unit)?;
Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness))
}
fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CraftResult<(Work, Work)> {
let host_unit = Unit { kind: Kind::Host, ..*unit };
let (script_output, build_output) = {
(cx.layout(&host_unit).build(unit.pkg), cx.layout(unit).build_out(unit.pkg))
};
// Building the command to execute
let to_exec = script_output.join(unit.target.name());
// Start preparing the process to execute, starting out with some
// environment variables. Note that the profile-related environment
// variables are not set with this the build script's profile but rather the
// package's library profile.
let profile = cx.lib_profile(unit.pkg.package_id());
let to_exec = to_exec.into_os_string();
let mut cmd = cx.compilation.host_process(to_exec, unit.pkg)?;
cmd.env("OUT_DIR", &build_output)
.env("CRAFT_MANIFEST_DIR", unit.pkg.root())
.env("NUM_JOBS", &cx.jobs().to_string())
.env("TARGET",
&match unit.kind {
Kind::Host => cx.host_triple(),
Kind::Target => cx.target_triple(),
})
.env("DEBUG", &profile.debuginfo.to_string())
.env("OPT_LEVEL", &profile.opt_level)
.env("PROFILE",
if cx.build_config.release {
"release"
} else {
"debug"
})
.env("HOST", cx.host_triple())
.env("CC", &cx.config.cc()?.path)
.env("DOC", &*cx.config.doc()?);
if let Some(links) = unit.pkg.manifest().links() {
cmd.env("CRAFT_MANIFEST_LINKS", links);
}
// Be sure to pass along all enabled features for this package, this is the
// last piece of statically known information that we have.
if let Some(features) = cx.resolve.features(unit.pkg.package_id()) {
for feat in features.iter() {
cmd.env(&format!("CRAFT_FEATURE_{}", super::envify(feat)), "1");
}
}
// Gather the set of native dependencies that this package has along with
// some other variables to close over.
//
// This information will be used at build-time later on to figure out which
// sorts of variables need to be discovered at that time.
let lib_deps = {
cx.dep_run_custom_build(unit)?
.iter()
.filter_map(|unit| {
if unit.profile.run_custom_build {
Some((unit.pkg.manifest().links().unwrap().to_string(), unit.pkg.package_id().clone()))
} else {
None
}
})
.collect::<Vec<_>>()
};
let pkg_name = unit.pkg.to_string();
let build_state = cx.build_state.clone();
let id = unit.pkg.package_id().clone();
let output_file = build_output.parent().unwrap().join("output");
let all = (id.clone(), pkg_name.clone(), build_state.clone(), output_file.clone());
let build_scripts = super::load_build_deps(cx, unit);
let kind = unit.kind;
// Check to see if the build script as already run, and if it has keep
// track of whether it has told us about some explicit dependencies
let prev_output = BuildOutput::parse_file(&output_file, &pkg_name).ok();
let rerun_if_changed = match prev_output {
Some(ref prev) => prev.rerun_if_changed.clone(),
None => Vec::new(),
};
cx.build_explicit_deps.insert(*unit, (output_file.clone(), rerun_if_changed));
fs::create_dir_all(&cx.layout(&host_unit).build(unit.pkg))?;
fs::create_dir_all(&cx.layout(unit).build(unit.pkg))?;
// Prepare the unit of "dirty work" which will actually run the custom build
// command.
//
// Note that this has to do some extra work just before running the command
// to determine extra environment variables and such.
let dirty = Work::new(move |state| {
// Make sure that OUT_DIR exists.
//
// If we have an old build directory, then just move it into place,
// otherwise create it!
if fs::metadata(&build_output).is_err() {
fs::create_dir(&build_output)
.chain_error(|| internal("failed to create script output directory for build command"))?;
}
// For all our native lib dependencies, pick up their metadata to pass
// along to this custom build command. We're also careful to augment our
// dynamic library search path in case the build script depended on any
// native dynamic libraries.
{
let build_state = build_state.outputs.lock().unwrap();
for (name, id) in lib_deps {
let key = (id.clone(), kind);
let state = build_state.get(&key)
.chain_error(|| {
internal(format!("failed to locate build state for env vars: {}/{:?}",
id,
kind))
})?;
let data = &state.metadata;
for &(ref key, ref value) in data.iter() {
cmd.env(&format!("DEP_{}_{}", super::envify(&name), super::envify(key)),
value);
}
}
if let Some(build_scripts) = build_scripts {
super::add_plugin_deps(&mut cmd, &build_state, &build_scripts)?;
}
}
// And now finally, run the build command itself!
state.running(&cmd);
let output = cmd.exec_with_streaming(&mut |out_line| {
state.stdout(out_line);
Ok(())
},
&mut |err_line| {
state.stderr(err_line);
Ok(())
})
.map_err(|mut e| {
e.desc = format!("failed to run custom build command for `{}`\n{}",
pkg_name,
e.desc);
Human(e)
})?;
paths::write(&output_file, &output.stdout)?;
// After the build command has finished running, we need to be sure to
// remember all of its output so we can later discover precisely what it
// was, even if we don't run the build command again (due to freshness).
//
// This is also the location where we provide feedback into the build
// state informing what variables were discovered via our script as
// well.
let parsed_output = BuildOutput::parse(&output.stdout, &pkg_name)?;
build_state.insert(id, kind, parsed_output);
Ok(())
});
// Now that we've prepared our work-to-do, we need to prepare the fresh work
// itself to run when we actually end up just discarding what we calculated
// above.
let fresh = Work::new(move |_tx| {
let (id, pkg_name, build_state, output_file) = all;
let output = match prev_output {
Some(output) => output,
None => BuildOutput::parse_file(&output_file, &pkg_name)?,
};
build_state.insert(id, kind, output);
Ok(())
});
Ok((dirty, fresh))
}
impl BuildState {
pub fn new(config: &super::BuildConfig) -> BuildState {
let mut overrides = HashMap::new();
let i1 = config.host.overrides.iter().map(|p| (p, Kind::Host));
let i2 = config.target.overrides.iter().map(|p| (p, Kind::Target));
for ((name, output), kind) in i1.chain(i2) {
overrides.insert((name.clone(), kind), output.clone());
}
BuildState {
outputs: Mutex::new(HashMap::new()),
overrides: overrides,
}
}
fn insert(&self, id: PackageId, kind: Kind, output: BuildOutput) {
self.outputs.lock().unwrap().insert((id, kind), output);
}
fn has_override(&self, unit: &Unit) -> bool {
let key = unit.pkg.manifest().links().map(|l| (l.to_string(), unit.kind));
match key.and_then(|k| self.overrides.get(&k)) {
Some(output) => {
self.insert(unit.pkg.package_id().clone(), unit.kind, output.clone());
true
}
None => false,
}
}
}
impl BuildOutput {
pub fn parse_file(path: &Path, pkg_name: &str) -> CraftResult<BuildOutput> {
let contents = paths::read_bytes(path)?;
BuildOutput::parse(&contents, pkg_name)
}
// Parses the output of a script.
// The `pkg_name` is used for error messages.
pub fn parse(input: &[u8], pkg_name: &str) -> CraftResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
let mut metadata = Vec::new();
let mut rerun_if_changed = Vec::new();
let mut warnings = Vec::new();
let whence = format!("build script of `{}`", pkg_name);
for line in input.split(|b| *b == b'\n') {
let line = match str::from_utf8(line) {
Ok(line) => line.trim(),
Err(..) => continue,
};
let mut iter = line.splitn(2, ':');
if iter.next() != Some("craft") {
// skip this line since it doesn't start with "craft:"
continue;
}
let data = match iter.next() {
Some(val) => val,
None => continue,
};
// getting the `key=value` part of the line
let mut iter = data.splitn(2, '=');
let key = iter.next();
let value = iter.next();
let (key, value) = match (key, value) {
(Some(a), Some(b)) => (a, b.trim_right()),
// line started with `craft:` but didn't match `key=value`
_ => bail!("Wrong output in {}: `{}`", whence, line),
};
match key {
"cc-flags" => {
let (libs, links) = BuildOutput::parse_cc_flags(value, &whence)?;
library_links.extend(links.into_iter());
library_paths.extend(libs.into_iter());
}
"cc-link-lib" => library_links.push(value.to_string()),
"cc-link-search" => library_paths.push(PathBuf::from(value)),
"warning" => warnings.push(value.to_string()),
"rerun-if-changed" => rerun_if_changed.push(value.to_string()),
_ => metadata.push((key.to_string(), value.to_string())),
}
}
Ok(BuildOutput {
library_paths: library_paths,
library_links: library_links,
metadata: metadata,
rerun_if_changed: rerun_if_changed,
warnings: warnings,
})
}
pub fn parse_cc_flags(value: &str, whence: &str) -> CraftResult<(Vec<PathBuf>, Vec<String>)> {
let value = value.trim();
let mut flags_iter = value.split(|c: char| c.is_whitespace())
.filter(|w| w.chars().any(|c| !c.is_whitespace()));
let (mut library_links, mut library_paths) = (Vec::new(), Vec::new());
loop {
let flag = match flags_iter.next() {
Some(f) => f,
None => break,
};
if flag != "-l" && flag != "-L" {
bail!("Only `-l` and `-L` flags are allowed in {}: `{}`",
whence,
value)
}
let value = match flags_iter.next() {
Some(v) => v,
None => {
bail!("Flag in cc-flags has no value in {}: `{}`",
whence,
value)
}
};
match flag {
"-l" => library_links.push(value.to_string()),
"-L" => library_paths.push(PathBuf::from(value)),
// was already checked above
_ => bail!("only -l and -L flags are allowed"),
};
}
Ok((library_paths, library_links))
}
}
/// Compute the `build_scripts` map in the `Context` which tracks what build
/// scripts each package depends on.
///
/// The global `build_scripts` map lists for all (package, kind) tuples what set
/// of packages' build script outputs must be considered. For example this lists
/// all dependencies' `-L` flags which need to be propagated transitively.
///
/// The given set of targets to this function is the initial set of
/// targets/profiles which are being built.
pub fn build_map<'b, 'cfg>(cx: &mut Context<'b, 'cfg>, units: &[Unit<'b>]) -> CraftResult<()> {
let mut ret = HashMap::new();
for unit in units {
build(&mut ret, cx, unit)?;
}
cx.build_scripts.extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));
return Ok(());
// Recursive function to build up the map we're constructing. This function
// memoizes all of its return values as it goes along.
fn | <'a, 'b, 'cfg>(out: &'a mut HashMap<Unit<'b>, BuildScripts>,
cx: &Context<'b, 'cfg>,
unit: &Unit<'b>)
-> CraftResult<&'a BuildScripts> {
// Do a quick pre-flight check to see if we've already calculated the
// set of dependencies.
if out.contains_key(unit) {
return Ok(&out[unit]);
}
let mut ret = BuildScripts::default();
if !unit.target.is_custom_build() && unit.pkg.has_custom_build() {
add_to_link(&mut ret, unit.pkg.package_id(), unit.kind);
}
for unit in cx.dep_targets(unit)?.iter() {
let dep_scripts = build(out, cx, unit)?;
if unit.target.for_host() {
ret.plugins.extend(dep_scripts.to_link
.iter()
.map(|p| &p.0)
.cloned());
} else if unit.target.linkable() {
for &(ref pkg, kind) in dep_scripts.to_link.iter() {
add_to_link(&mut ret, pkg, kind);
}
}
}
let prev = out.entry(*unit).or_insert(BuildScripts::default());
for (pkg, kind) in ret.to_link {
add_to_link(prev, &pkg, kind);
}
prev.plugins.extend(ret.plugins);
Ok(prev)
}
// When adding an entry to 'to_link' we only actually push it on if the
// script hasn't seen it yet (e.g. we don't push on duplicates).
fn add_to_link(scripts: &mut BuildScripts, pkg: &PackageId, kind: Kind) {
if scripts.seen_to_link.insert((pkg.clone(), kind)) {
scripts.to_link.push((pkg.clone(), kind));
}
}
}
| build | identifier_name |
custom_build.rs | use std::collections::{HashMap, BTreeSet, HashSet};
use std::fs;
use std::path::{PathBuf, Path};
use std::str;
use std::sync::{Mutex, Arc};
use package_id::PackageId;
use util::{CraftResult, Human, Freshness, internal, ChainError, profile, paths};
use super::job::Work;
use super::{fingerprint, Kind, Context, Unit};
/// Contains the parsed output of a custom build script.
#[derive(Clone, Debug, Hash)]
pub struct BuildOutput {
/// Paths to pass to cc with the `-L` flag
pub library_paths: Vec<PathBuf>,
/// Names and link kinds of libraries, suitable for the `-l` flag
pub library_links: Vec<String>,
/// Metadata to pass to the immediate dependencies
pub metadata: Vec<(String, String)>,
/// Glob paths to trigger a rerun of this build script.
pub rerun_if_changed: Vec<String>,
/// Warnings generated by this build,
pub warnings: Vec<String>,
}
pub type BuildMap = HashMap<(PackageId, Kind), BuildOutput>;
pub struct BuildState {
pub outputs: Mutex<BuildMap>,
overrides: HashMap<(String, Kind), BuildOutput>,
}
#[derive(Default)]
pub struct BuildScripts {
// Craft will use this `to_link` vector to add -L flags to compiles as we
// propagate them upwards towards the final build. Note, however, that we
// need to preserve the ordering of `to_link` to be topologically sorted.
// This will ensure that build scripts which print their paths properly will
// correctly pick up the files they generated (if there are duplicates
// elsewhere).
//
// To preserve this ordering, the (id, kind) is stored in two places, once
// in the `Vec` and once in `seen_to_link` for a fast lookup. We maintain
// this as we're building interactively below to ensure that the memory
// usage here doesn't blow up too much.
//
// For more information, see #2354
pub to_link: Vec<(PackageId, Kind)>,
seen_to_link: HashSet<(PackageId, Kind)>,
pub plugins: BTreeSet<PackageId>,
}
/// Prepares a `Work` that executes the target as a custom build script.
///
/// The `req` given is the requirement which this run of the build script will
/// prepare work for. If the requirement is specified as both the target and the
/// host platforms it is assumed that the two are equal and the build script is
/// only run once (not twice).
pub fn prepare<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CraftResult<(Work, Work, Freshness)> {
let _p = profile::start(format!("build script prepare: {}/{}", unit.pkg, unit.target.name()));
let overridden = cx.build_state.has_override(unit);
let (work_dirty, work_fresh) = if overridden {
(Work::new(|_| Ok(())), Work::new(|_| Ok(())))
} else {
build_work(cx, unit)?
};
// Now that we've prep'd our work, build the work needed to manage the
// fingerprint and then start returning that upwards.
let (freshness, dirty, fresh) = fingerprint::prepare_build_cmd(cx, unit)?;
Ok((work_dirty.then(dirty), work_fresh.then(fresh), freshness))
}
fn build_work<'a, 'cfg>(cx: &mut Context<'a, 'cfg>, unit: &Unit<'a>) -> CraftResult<(Work, Work)> {
let host_unit = Unit { kind: Kind::Host, ..*unit };
let (script_output, build_output) = {
(cx.layout(&host_unit).build(unit.pkg), cx.layout(unit).build_out(unit.pkg))
};
// Building the command to execute
let to_exec = script_output.join(unit.target.name());
// Start preparing the process to execute, starting out with some
// environment variables. Note that the profile-related environment
// variables are not set with this the build script's profile but rather the
// package's library profile.
let profile = cx.lib_profile(unit.pkg.package_id());
let to_exec = to_exec.into_os_string();
let mut cmd = cx.compilation.host_process(to_exec, unit.pkg)?;
cmd.env("OUT_DIR", &build_output)
.env("CRAFT_MANIFEST_DIR", unit.pkg.root())
.env("NUM_JOBS", &cx.jobs().to_string())
.env("TARGET",
&match unit.kind {
Kind::Host => cx.host_triple(),
Kind::Target => cx.target_triple(),
})
.env("DEBUG", &profile.debuginfo.to_string())
.env("OPT_LEVEL", &profile.opt_level)
.env("PROFILE",
if cx.build_config.release {
"release"
} else {
"debug"
})
.env("HOST", cx.host_triple())
.env("CC", &cx.config.cc()?.path)
.env("DOC", &*cx.config.doc()?);
if let Some(links) = unit.pkg.manifest().links() {
cmd.env("CRAFT_MANIFEST_LINKS", links);
}
// Be sure to pass along all enabled features for this package, this is the
// last piece of statically known information that we have.
if let Some(features) = cx.resolve.features(unit.pkg.package_id()) {
for feat in features.iter() {
cmd.env(&format!("CRAFT_FEATURE_{}", super::envify(feat)), "1");
}
}
// Gather the set of native dependencies that this package has along with
// some other variables to close over.
//
// This information will be used at build-time later on to figure out which
// sorts of variables need to be discovered at that time.
let lib_deps = {
cx.dep_run_custom_build(unit)?
.iter()
.filter_map(|unit| {
if unit.profile.run_custom_build {
Some((unit.pkg.manifest().links().unwrap().to_string(), unit.pkg.package_id().clone()))
} else {
None
}
})
.collect::<Vec<_>>()
};
let pkg_name = unit.pkg.to_string();
let build_state = cx.build_state.clone();
let id = unit.pkg.package_id().clone();
let output_file = build_output.parent().unwrap().join("output");
let all = (id.clone(), pkg_name.clone(), build_state.clone(), output_file.clone());
let build_scripts = super::load_build_deps(cx, unit);
let kind = unit.kind;
// Check to see if the build script as already run, and if it has keep
// track of whether it has told us about some explicit dependencies
let prev_output = BuildOutput::parse_file(&output_file, &pkg_name).ok();
let rerun_if_changed = match prev_output {
Some(ref prev) => prev.rerun_if_changed.clone(),
None => Vec::new(),
};
cx.build_explicit_deps.insert(*unit, (output_file.clone(), rerun_if_changed));
fs::create_dir_all(&cx.layout(&host_unit).build(unit.pkg))?;
fs::create_dir_all(&cx.layout(unit).build(unit.pkg))?;
// Prepare the unit of "dirty work" which will actually run the custom build
// command.
//
// Note that this has to do some extra work just before running the command
// to determine extra environment variables and such.
let dirty = Work::new(move |state| {
// Make sure that OUT_DIR exists.
//
// If we have an old build directory, then just move it into place,
// otherwise create it!
if fs::metadata(&build_output).is_err() {
fs::create_dir(&build_output)
.chain_error(|| internal("failed to create script output directory for build command"))?;
}
// For all our native lib dependencies, pick up their metadata to pass
// along to this custom build command. We're also careful to augment our
// dynamic library search path in case the build script depended on any
// native dynamic libraries.
{
let build_state = build_state.outputs.lock().unwrap();
for (name, id) in lib_deps {
let key = (id.clone(), kind);
let state = build_state.get(&key)
.chain_error(|| { | let data = &state.metadata;
for &(ref key, ref value) in data.iter() {
cmd.env(&format!("DEP_{}_{}", super::envify(&name), super::envify(key)),
value);
}
}
if let Some(build_scripts) = build_scripts {
super::add_plugin_deps(&mut cmd, &build_state, &build_scripts)?;
}
}
// And now finally, run the build command itself!
state.running(&cmd);
let output = cmd.exec_with_streaming(&mut |out_line| {
state.stdout(out_line);
Ok(())
},
&mut |err_line| {
state.stderr(err_line);
Ok(())
})
.map_err(|mut e| {
e.desc = format!("failed to run custom build command for `{}`\n{}",
pkg_name,
e.desc);
Human(e)
})?;
paths::write(&output_file, &output.stdout)?;
// After the build command has finished running, we need to be sure to
// remember all of its output so we can later discover precisely what it
// was, even if we don't run the build command again (due to freshness).
//
// This is also the location where we provide feedback into the build
// state informing what variables were discovered via our script as
// well.
let parsed_output = BuildOutput::parse(&output.stdout, &pkg_name)?;
build_state.insert(id, kind, parsed_output);
Ok(())
});
// Now that we've prepared our work-to-do, we need to prepare the fresh work
// itself to run when we actually end up just discarding what we calculated
// above.
let fresh = Work::new(move |_tx| {
let (id, pkg_name, build_state, output_file) = all;
let output = match prev_output {
Some(output) => output,
None => BuildOutput::parse_file(&output_file, &pkg_name)?,
};
build_state.insert(id, kind, output);
Ok(())
});
Ok((dirty, fresh))
}
impl BuildState {
pub fn new(config: &super::BuildConfig) -> BuildState {
let mut overrides = HashMap::new();
let i1 = config.host.overrides.iter().map(|p| (p, Kind::Host));
let i2 = config.target.overrides.iter().map(|p| (p, Kind::Target));
for ((name, output), kind) in i1.chain(i2) {
overrides.insert((name.clone(), kind), output.clone());
}
BuildState {
outputs: Mutex::new(HashMap::new()),
overrides: overrides,
}
}
fn insert(&self, id: PackageId, kind: Kind, output: BuildOutput) {
self.outputs.lock().unwrap().insert((id, kind), output);
}
fn has_override(&self, unit: &Unit) -> bool {
let key = unit.pkg.manifest().links().map(|l| (l.to_string(), unit.kind));
match key.and_then(|k| self.overrides.get(&k)) {
Some(output) => {
self.insert(unit.pkg.package_id().clone(), unit.kind, output.clone());
true
}
None => false,
}
}
}
impl BuildOutput {
pub fn parse_file(path: &Path, pkg_name: &str) -> CraftResult<BuildOutput> {
let contents = paths::read_bytes(path)?;
BuildOutput::parse(&contents, pkg_name)
}
// Parses the output of a script.
// The `pkg_name` is used for error messages.
pub fn parse(input: &[u8], pkg_name: &str) -> CraftResult<BuildOutput> {
let mut library_paths = Vec::new();
let mut library_links = Vec::new();
let mut metadata = Vec::new();
let mut rerun_if_changed = Vec::new();
let mut warnings = Vec::new();
let whence = format!("build script of `{}`", pkg_name);
for line in input.split(|b| *b == b'\n') {
let line = match str::from_utf8(line) {
Ok(line) => line.trim(),
Err(..) => continue,
};
let mut iter = line.splitn(2, ':');
if iter.next() != Some("craft") {
// skip this line since it doesn't start with "craft:"
continue;
}
let data = match iter.next() {
Some(val) => val,
None => continue,
};
// getting the `key=value` part of the line
let mut iter = data.splitn(2, '=');
let key = iter.next();
let value = iter.next();
let (key, value) = match (key, value) {
(Some(a), Some(b)) => (a, b.trim_right()),
// line started with `craft:` but didn't match `key=value`
_ => bail!("Wrong output in {}: `{}`", whence, line),
};
match key {
"cc-flags" => {
let (libs, links) = BuildOutput::parse_cc_flags(value, &whence)?;
library_links.extend(links.into_iter());
library_paths.extend(libs.into_iter());
}
"cc-link-lib" => library_links.push(value.to_string()),
"cc-link-search" => library_paths.push(PathBuf::from(value)),
"warning" => warnings.push(value.to_string()),
"rerun-if-changed" => rerun_if_changed.push(value.to_string()),
_ => metadata.push((key.to_string(), value.to_string())),
}
}
Ok(BuildOutput {
library_paths: library_paths,
library_links: library_links,
metadata: metadata,
rerun_if_changed: rerun_if_changed,
warnings: warnings,
})
}
pub fn parse_cc_flags(value: &str, whence: &str) -> CraftResult<(Vec<PathBuf>, Vec<String>)> {
let value = value.trim();
let mut flags_iter = value.split(|c: char| c.is_whitespace())
.filter(|w| w.chars().any(|c| !c.is_whitespace()));
let (mut library_links, mut library_paths) = (Vec::new(), Vec::new());
loop {
let flag = match flags_iter.next() {
Some(f) => f,
None => break,
};
if flag != "-l" && flag != "-L" {
bail!("Only `-l` and `-L` flags are allowed in {}: `{}`",
whence,
value)
}
let value = match flags_iter.next() {
Some(v) => v,
None => {
bail!("Flag in cc-flags has no value in {}: `{}`",
whence,
value)
}
};
match flag {
"-l" => library_links.push(value.to_string()),
"-L" => library_paths.push(PathBuf::from(value)),
// was already checked above
_ => bail!("only -l and -L flags are allowed"),
};
}
Ok((library_paths, library_links))
}
}
/// Compute the `build_scripts` map in the `Context` which tracks what build
/// scripts each package depends on.
///
/// The global `build_scripts` map lists for all (package, kind) tuples what set
/// of packages' build script outputs must be considered. For example this lists
/// all dependencies' `-L` flags which need to be propagated transitively.
///
/// The given set of targets to this function is the initial set of
/// targets/profiles which are being built.
pub fn build_map<'b, 'cfg>(cx: &mut Context<'b, 'cfg>, units: &[Unit<'b>]) -> CraftResult<()> {
let mut ret = HashMap::new();
for unit in units {
build(&mut ret, cx, unit)?;
}
cx.build_scripts.extend(ret.into_iter().map(|(k, v)| (k, Arc::new(v))));
return Ok(());
// Recursive function to build up the map we're constructing. This function
// memoizes all of its return values as it goes along.
fn build<'a, 'b, 'cfg>(out: &'a mut HashMap<Unit<'b>, BuildScripts>,
cx: &Context<'b, 'cfg>,
unit: &Unit<'b>)
-> CraftResult<&'a BuildScripts> {
// Do a quick pre-flight check to see if we've already calculated the
// set of dependencies.
if out.contains_key(unit) {
return Ok(&out[unit]);
}
let mut ret = BuildScripts::default();
if !unit.target.is_custom_build() && unit.pkg.has_custom_build() {
add_to_link(&mut ret, unit.pkg.package_id(), unit.kind);
}
for unit in cx.dep_targets(unit)?.iter() {
let dep_scripts = build(out, cx, unit)?;
if unit.target.for_host() {
ret.plugins.extend(dep_scripts.to_link
.iter()
.map(|p| &p.0)
.cloned());
} else if unit.target.linkable() {
for &(ref pkg, kind) in dep_scripts.to_link.iter() {
add_to_link(&mut ret, pkg, kind);
}
}
}
let prev = out.entry(*unit).or_insert(BuildScripts::default());
for (pkg, kind) in ret.to_link {
add_to_link(prev, &pkg, kind);
}
prev.plugins.extend(ret.plugins);
Ok(prev)
}
// When adding an entry to 'to_link' we only actually push it on if the
// script hasn't seen it yet (e.g. we don't push on duplicates).
fn add_to_link(scripts: &mut BuildScripts, pkg: &PackageId, kind: Kind) {
if scripts.seen_to_link.insert((pkg.clone(), kind)) {
scripts.to_link.push((pkg.clone(), kind));
}
}
} | internal(format!("failed to locate build state for env vars: {}/{:?}",
id,
kind))
})?; | random_line_split |
featured_thumbnail.js | function featured_thumb() |
window.onload = featured_thumb; | {
jQuery('ul.thumbnails').each(function(index, element) {
var get_class=jQuery(this).attr('class');
var get_parent=jQuery(this).closest('div');
var wt=jQuery(this).closest('div').width();//width total
var col=jQuery(this).attr('data-columns');//columns
var dt=Math.floor(wt/col);
var mt=6;
var wa=dt-mt;
var mg=3;
var ft_size=jQuery(this).attr('data-ftsize');
jQuery(this).css('font-size',ft_size+'px');
get_parent.find('ul.thumbnails li').css({'max-width':wa+'px','margin':mg+'px','padding':'0'});
get_parent.find('ul.thumbnails li h5').css({'font-size':ft_size+'px','font-weight':'bold','padding':'0 0 5px','margin':'0'});
get_parent.find('ul.thumbnails li img').css({'height':wa+'px','margin':'0'});
get_parent.find('ul.thumbnails li p').css({'margin':'0'});
});
} | identifier_body |
featured_thumbnail.js | function | (){
jQuery('ul.thumbnails').each(function(index, element) {
var get_class=jQuery(this).attr('class');
var get_parent=jQuery(this).closest('div');
var wt=jQuery(this).closest('div').width();//width total
var col=jQuery(this).attr('data-columns');//columns
var dt=Math.floor(wt/col);
var mt=6;
var wa=dt-mt;
var mg=3;
var ft_size=jQuery(this).attr('data-ftsize');
jQuery(this).css('font-size',ft_size+'px');
get_parent.find('ul.thumbnails li').css({'max-width':wa+'px','margin':mg+'px','padding':'0'});
get_parent.find('ul.thumbnails li h5').css({'font-size':ft_size+'px','font-weight':'bold','padding':'0 0 5px','margin':'0'});
get_parent.find('ul.thumbnails li img').css({'height':wa+'px','margin':'0'});
get_parent.find('ul.thumbnails li p').css({'margin':'0'});
});
}
window.onload = featured_thumb; | featured_thumb | identifier_name |
featured_thumbnail.js | function featured_thumb(){
jQuery('ul.thumbnails').each(function(index, element) {
var get_class=jQuery(this).attr('class');
var get_parent=jQuery(this).closest('div');
var wt=jQuery(this).closest('div').width();//width total
var col=jQuery(this).attr('data-columns');//columns
var dt=Math.floor(wt/col);
var mt=6; | var mg=3;
var ft_size=jQuery(this).attr('data-ftsize');
jQuery(this).css('font-size',ft_size+'px');
get_parent.find('ul.thumbnails li').css({'max-width':wa+'px','margin':mg+'px','padding':'0'});
get_parent.find('ul.thumbnails li h5').css({'font-size':ft_size+'px','font-weight':'bold','padding':'0 0 5px','margin':'0'});
get_parent.find('ul.thumbnails li img').css({'height':wa+'px','margin':'0'});
get_parent.find('ul.thumbnails li p').css({'margin':'0'});
});
}
window.onload = featured_thumb; | var wa=dt-mt; | random_line_split |
hierarchical-menu.tsx | /** @jsx h */
import { h, render } from 'preact';
import cx from 'classnames';
import RefinementList from '../../components/RefinementList/RefinementList';
import type {
HierarchicalMenuItem,
HierarchicalMenuConnectorParams,
HierarchicalMenuRenderState,
HierarchicalMenuWidgetDescription,
} from '../../connectors/hierarchical-menu/connectHierarchicalMenu';
import connectHierarchicalMenu from '../../connectors/hierarchical-menu/connectHierarchicalMenu';
import defaultTemplates from './defaultTemplates';
import type { PreparedTemplateProps } from '../../lib/utils/prepareTemplateProps';
import {
prepareTemplateProps,
getContainerNode,
createDocumentationMessageGenerator,
} from '../../lib/utils';
import type {
TransformItems,
Template,
WidgetFactory,
RendererOptions,
SortBy,
ComponentCSSClasses,
} from '../../types';
import { component } from '../../lib/suit';
const withUsage = createDocumentationMessageGenerator({
name: 'hierarchical-menu',
});
const suit = component('HierarchicalMenu');
type HierarchicalMenuTemplates = Partial<{
/**
* Item template, provided with `name`, `count`, `isRefined`, `url` data properties.
*/
item: Template<{
name: string;
count: number;
isRefined: boolean;
url: string;
}>;
/**
* Template used for the show more text, provided with `isShowingMore` data property.
*/
showMoreText: Template<{ isShowingMore: boolean }>;
}>;
export type HierarchicalMenuCSSClasses = Partial<{
/**
* CSS class to add to the root element.
*/
root: string | string[];
/**
* CSS class to add to the root element when no refinements.
*/
noRefinementRoot: string | string[];
/**
* CSS class to add to the list element.
*/
list: string | string[];
/**
* CSS class to add to the child list element.
*/
childList: string | string[];
/**
* CSS class to add to each item element.
*/
item: string | string[];
/**
* CSS class to add to each selected item element.
*/
selectedItem: string | string[];
/**
* CSS class to add to each parent item element.
*/
parentItem: string | string[];
/**
* CSS class to add to each link (when using the default template).
*/
link: string | string[];
/**
* CSS class to add to each label (when using the default template).
*/
label: string | string[];
/**
* CSS class to add to each count element (when using the default template).
*/
count: string | string[];
/**
* CSS class to add to the show more element.
*/
showMore: string | string[];
/**
* CSS class to add to the disabled show more element.
*/
disabledShowMore: string | string[];
}>;
export type HierarchicalMenuComponentCSSClasses =
ComponentCSSClasses<HierarchicalMenuCSSClasses>;
export type HierarchicalMenuComponentTemplates =
Required<HierarchicalMenuTemplates>;
export type HierarchicalMenuWidgetParams = {
/**
* CSS Selector or HTMLElement to insert the widget.
*/
container: string | HTMLElement;
/**
* Array of attributes to use to generate the hierarchy of the menu.
*/
attributes: string[];
/**
* Separator used in the attributes to separate level values.
*/
separator?: string;
/**
* Prefix path to use if the first level is not the root level.
*/
rootPath?: string;
/**
* Show the siblings of the selected parent level of the current refined value.
*
* With `showParentLevel` set to `true` (default):
* - Parent lvl0
* - **lvl1**
* - **lvl2**
* - lvl2
* - lvl2
* - lvl 1
* - lvl 1
* - Parent lvl0
* - Parent lvl0
*
* With `showParentLevel` set to `false`:
* - Parent lvl0
* - **lvl1**
* - **lvl2**
* - Parent lvl0
* - Parent lvl0
*/
showParentLevel?: boolean;
/**
* Max number of values to display.
*/
limit?: number;
/**
* Whether to display the "show more" button.
*/
showMore?: boolean;
/**
* Max number of values to display when showing more.
* does not impact the root level.
*/
showMoreLimit?: number;
/**
* How to sort refinements. Possible values: `count|isRefined|name:asc|name:desc`.
* You can also use a sort function that behaves like the standard Javascript [compareFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax).
*/
sortBy?: SortBy<HierarchicalMenuItem>;
/**
* Function to transform the items passed to the templates.
*/
transformItems?: TransformItems<HierarchicalMenuItem>;
/**
* Templates to use for the widget.
*/
templates?: HierarchicalMenuTemplates;
/**
* CSS classes to add to the wrapping elements.
*/
cssClasses?: HierarchicalMenuCSSClasses;
};
const renderer =
({
cssClasses,
containerNode,
showMore,
templates,
renderState,
}: {
cssClasses: HierarchicalMenuComponentCSSClasses;
containerNode: HTMLElement;
showMore: boolean;
templates: HierarchicalMenuTemplates;
renderState: {
templateProps?: PreparedTemplateProps<HierarchicalMenuComponentTemplates>;
};
}) =>
(
{
createURL,
items,
refine,
instantSearchInstance,
isShowingMore,
toggleShowMore,
canToggleShowMore,
}: HierarchicalMenuRenderState &
RendererOptions<HierarchicalMenuConnectorParams>,
isFirstRendering: boolean
) => {
if (isFirstRendering) {
renderState.templateProps = prepareTemplateProps({
defaultTemplates,
templatesConfig: instantSearchInstance.templatesConfig,
templates,
});
return;
}
render(
<RefinementList
createURL={createURL}
cssClasses={cssClasses}
facetValues={items}
templateProps={renderState.templateProps!}
toggleRefinement={refine}
showMore={showMore}
toggleShowMore={toggleShowMore}
isShowingMore={isShowingMore}
canToggleShowMore={canToggleShowMore}
/>,
containerNode
);
};
/**
* The hierarchical menu widget is used to create a navigation based on a hierarchy of facet attributes.
*
* It is commonly used for categories with subcategories.
*
* All attributes (lvl0, lvl1 here) must be declared as [attributes for faceting](https://www.algolia.com/doc/guides/searching/faceting/#declaring-attributes-for-faceting) in your
* Algolia settings.
*
* By default, the separator we expect is ` > ` (with spaces) but you can use
* a different one by using the `separator` option.
* @requirements
* Your objects must be formatted in a specific way to be
* able to display hierarchical menus. Here's an example:
*
* ```javascript
* {
* "objectID": "123",
* "name": "orange",
* "categories": {
* "lvl0": "fruits",
* "lvl1": "fruits > citrus"
* }
* }
* ```
*
* Every level must be specified entirely.
* It's also possible to have multiple values per level, for example:
*
* ```javascript
* {
* "objectID": "123",
* "name": "orange",
* "categories": {
* "lvl0": ["fruits", "vitamins"],
* "lvl1": ["fruits > citrus", "vitamins > C"]
* }
* }
* ```
* @type {WidgetFactory}
* @devNovel HierarchicalMenu
* @category filter
* @param {HierarchicalMenuWidgetParams} widgetParams The HierarchicalMenu widget options.
* @return {Widget} A new HierarchicalMenu widget instance.
* @example
* search.addWidgets([
* instantsearch.widgets.hierarchicalMenu({
* container: '#hierarchical-categories',
* attributes: ['hierarchicalCategories.lvl0', 'hierarchicalCategories.lvl1', 'hierarchicalCategories.lvl2'],
* })
* ]);
*/
export type HierarchicalMenuWidget = WidgetFactory<
HierarchicalMenuWidgetDescription & { $$widgetType: 'ais.hierarchicalMenu' },
HierarchicalMenuConnectorParams,
HierarchicalMenuWidgetParams
>;
const hierarchicalMenu: HierarchicalMenuWidget = function hierarchicalMenu(
widgetParams
) {
const {
container,
attributes,
separator,
rootPath,
showParentLevel,
limit,
showMore = false,
showMoreLimit,
sortBy,
transformItems,
templates = {},
cssClasses: userCssClasses = {},
} = widgetParams || {};
if (!container) {
throw new Error(withUsage('The `container` option is required.'));
}
const containerNode = getContainerNode(container);
const cssClasses = {
root: cx(suit(), userCssClasses.root),
noRefinementRoot: cx(
suit({ modifierName: 'noRefinement' }),
userCssClasses.noRefinementRoot
),
list: cx(suit({ descendantName: 'list' }), userCssClasses.list),
childList: cx(
suit({ descendantName: 'list', modifierName: 'child' }),
userCssClasses.childList
),
item: cx(suit({ descendantName: 'item' }), userCssClasses.item),
selectedItem: cx(
suit({ descendantName: 'item', modifierName: 'selected' }),
userCssClasses.selectedItem
),
parentItem: cx(
suit({ descendantName: 'item', modifierName: 'parent' }),
userCssClasses.parentItem
),
link: cx(suit({ descendantName: 'link' }), userCssClasses.link),
label: cx(suit({ descendantName: 'label' }), userCssClasses.label),
count: cx(suit({ descendantName: 'count' }), userCssClasses.count),
showMore: cx(suit({ descendantName: 'showMore' }), userCssClasses.showMore),
disabledShowMore: cx(
suit({ descendantName: 'showMore', modifierName: 'disabled' }),
userCssClasses.disabledShowMore
),
};
const specializedRenderer = renderer({
cssClasses,
containerNode,
templates,
showMore,
renderState: {},
});
const makeWidget = connectHierarchicalMenu(specializedRenderer, () =>
render(null, containerNode)
);
return {
...makeWidget({
attributes,
separator, | sortBy,
transformItems,
}),
$$widgetType: 'ais.hierarchicalMenu',
};
};
export default hierarchicalMenu; | rootPath,
showParentLevel,
limit,
showMore,
showMoreLimit, | random_line_split |
hierarchical-menu.tsx | /** @jsx h */
import { h, render } from 'preact';
import cx from 'classnames';
import RefinementList from '../../components/RefinementList/RefinementList';
import type {
HierarchicalMenuItem,
HierarchicalMenuConnectorParams,
HierarchicalMenuRenderState,
HierarchicalMenuWidgetDescription,
} from '../../connectors/hierarchical-menu/connectHierarchicalMenu';
import connectHierarchicalMenu from '../../connectors/hierarchical-menu/connectHierarchicalMenu';
import defaultTemplates from './defaultTemplates';
import type { PreparedTemplateProps } from '../../lib/utils/prepareTemplateProps';
import {
prepareTemplateProps,
getContainerNode,
createDocumentationMessageGenerator,
} from '../../lib/utils';
import type {
TransformItems,
Template,
WidgetFactory,
RendererOptions,
SortBy,
ComponentCSSClasses,
} from '../../types';
import { component } from '../../lib/suit';
const withUsage = createDocumentationMessageGenerator({
name: 'hierarchical-menu',
});
const suit = component('HierarchicalMenu');
type HierarchicalMenuTemplates = Partial<{
/**
* Item template, provided with `name`, `count`, `isRefined`, `url` data properties.
*/
item: Template<{
name: string;
count: number;
isRefined: boolean;
url: string;
}>;
/**
* Template used for the show more text, provided with `isShowingMore` data property.
*/
showMoreText: Template<{ isShowingMore: boolean }>;
}>;
export type HierarchicalMenuCSSClasses = Partial<{
/**
* CSS class to add to the root element.
*/
root: string | string[];
/**
* CSS class to add to the root element when no refinements.
*/
noRefinementRoot: string | string[];
/**
* CSS class to add to the list element.
*/
list: string | string[];
/**
* CSS class to add to the child list element.
*/
childList: string | string[];
/**
* CSS class to add to each item element.
*/
item: string | string[];
/**
* CSS class to add to each selected item element.
*/
selectedItem: string | string[];
/**
* CSS class to add to each parent item element.
*/
parentItem: string | string[];
/**
* CSS class to add to each link (when using the default template).
*/
link: string | string[];
/**
* CSS class to add to each label (when using the default template).
*/
label: string | string[];
/**
* CSS class to add to each count element (when using the default template).
*/
count: string | string[];
/**
* CSS class to add to the show more element.
*/
showMore: string | string[];
/**
* CSS class to add to the disabled show more element.
*/
disabledShowMore: string | string[];
}>;
export type HierarchicalMenuComponentCSSClasses =
ComponentCSSClasses<HierarchicalMenuCSSClasses>;
export type HierarchicalMenuComponentTemplates =
Required<HierarchicalMenuTemplates>;
export type HierarchicalMenuWidgetParams = {
/**
* CSS Selector or HTMLElement to insert the widget.
*/
container: string | HTMLElement;
/**
* Array of attributes to use to generate the hierarchy of the menu.
*/
attributes: string[];
/**
* Separator used in the attributes to separate level values.
*/
separator?: string;
/**
* Prefix path to use if the first level is not the root level.
*/
rootPath?: string;
/**
* Show the siblings of the selected parent level of the current refined value.
*
* With `showParentLevel` set to `true` (default):
* - Parent lvl0
* - **lvl1**
* - **lvl2**
* - lvl2
* - lvl2
* - lvl 1
* - lvl 1
* - Parent lvl0
* - Parent lvl0
*
* With `showParentLevel` set to `false`:
* - Parent lvl0
* - **lvl1**
* - **lvl2**
* - Parent lvl0
* - Parent lvl0
*/
showParentLevel?: boolean;
/**
* Max number of values to display.
*/
limit?: number;
/**
* Whether to display the "show more" button.
*/
showMore?: boolean;
/**
* Max number of values to display when showing more.
* does not impact the root level.
*/
showMoreLimit?: number;
/**
* How to sort refinements. Possible values: `count|isRefined|name:asc|name:desc`.
* You can also use a sort function that behaves like the standard Javascript [compareFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax).
*/
sortBy?: SortBy<HierarchicalMenuItem>;
/**
* Function to transform the items passed to the templates.
*/
transformItems?: TransformItems<HierarchicalMenuItem>;
/**
* Templates to use for the widget.
*/
templates?: HierarchicalMenuTemplates;
/**
* CSS classes to add to the wrapping elements.
*/
cssClasses?: HierarchicalMenuCSSClasses;
};
const renderer =
({
cssClasses,
containerNode,
showMore,
templates,
renderState,
}: {
cssClasses: HierarchicalMenuComponentCSSClasses;
containerNode: HTMLElement;
showMore: boolean;
templates: HierarchicalMenuTemplates;
renderState: {
templateProps?: PreparedTemplateProps<HierarchicalMenuComponentTemplates>;
};
}) =>
(
{
createURL,
items,
refine,
instantSearchInstance,
isShowingMore,
toggleShowMore,
canToggleShowMore,
}: HierarchicalMenuRenderState &
RendererOptions<HierarchicalMenuConnectorParams>,
isFirstRendering: boolean
) => {
if (isFirstRendering) {
renderState.templateProps = prepareTemplateProps({
defaultTemplates,
templatesConfig: instantSearchInstance.templatesConfig,
templates,
});
return;
}
render(
<RefinementList
createURL={createURL}
cssClasses={cssClasses}
facetValues={items}
templateProps={renderState.templateProps!}
toggleRefinement={refine}
showMore={showMore}
toggleShowMore={toggleShowMore}
isShowingMore={isShowingMore}
canToggleShowMore={canToggleShowMore}
/>,
containerNode
);
};
/**
* The hierarchical menu widget is used to create a navigation based on a hierarchy of facet attributes.
*
* It is commonly used for categories with subcategories.
*
* All attributes (lvl0, lvl1 here) must be declared as [attributes for faceting](https://www.algolia.com/doc/guides/searching/faceting/#declaring-attributes-for-faceting) in your
* Algolia settings.
*
* By default, the separator we expect is ` > ` (with spaces) but you can use
* a different one by using the `separator` option.
* @requirements
* Your objects must be formatted in a specific way to be
* able to display hierarchical menus. Here's an example:
*
* ```javascript
* {
* "objectID": "123",
* "name": "orange",
* "categories": {
* "lvl0": "fruits",
* "lvl1": "fruits > citrus"
* }
* }
* ```
*
* Every level must be specified entirely.
* It's also possible to have multiple values per level, for example:
*
* ```javascript
* {
* "objectID": "123",
* "name": "orange",
* "categories": {
* "lvl0": ["fruits", "vitamins"],
* "lvl1": ["fruits > citrus", "vitamins > C"]
* }
* }
* ```
* @type {WidgetFactory}
* @devNovel HierarchicalMenu
* @category filter
* @param {HierarchicalMenuWidgetParams} widgetParams The HierarchicalMenu widget options.
* @return {Widget} A new HierarchicalMenu widget instance.
* @example
* search.addWidgets([
* instantsearch.widgets.hierarchicalMenu({
* container: '#hierarchical-categories',
* attributes: ['hierarchicalCategories.lvl0', 'hierarchicalCategories.lvl1', 'hierarchicalCategories.lvl2'],
* })
* ]);
*/
export type HierarchicalMenuWidget = WidgetFactory<
HierarchicalMenuWidgetDescription & { $$widgetType: 'ais.hierarchicalMenu' },
HierarchicalMenuConnectorParams,
HierarchicalMenuWidgetParams
>;
const hierarchicalMenu: HierarchicalMenuWidget = function hierarchicalMenu(
widgetParams
) {
const {
container,
attributes,
separator,
rootPath,
showParentLevel,
limit,
showMore = false,
showMoreLimit,
sortBy,
transformItems,
templates = {},
cssClasses: userCssClasses = {},
} = widgetParams || {};
if (!container) |
const containerNode = getContainerNode(container);
const cssClasses = {
root: cx(suit(), userCssClasses.root),
noRefinementRoot: cx(
suit({ modifierName: 'noRefinement' }),
userCssClasses.noRefinementRoot
),
list: cx(suit({ descendantName: 'list' }), userCssClasses.list),
childList: cx(
suit({ descendantName: 'list', modifierName: 'child' }),
userCssClasses.childList
),
item: cx(suit({ descendantName: 'item' }), userCssClasses.item),
selectedItem: cx(
suit({ descendantName: 'item', modifierName: 'selected' }),
userCssClasses.selectedItem
),
parentItem: cx(
suit({ descendantName: 'item', modifierName: 'parent' }),
userCssClasses.parentItem
),
link: cx(suit({ descendantName: 'link' }), userCssClasses.link),
label: cx(suit({ descendantName: 'label' }), userCssClasses.label),
count: cx(suit({ descendantName: 'count' }), userCssClasses.count),
showMore: cx(suit({ descendantName: 'showMore' }), userCssClasses.showMore),
disabledShowMore: cx(
suit({ descendantName: 'showMore', modifierName: 'disabled' }),
userCssClasses.disabledShowMore
),
};
const specializedRenderer = renderer({
cssClasses,
containerNode,
templates,
showMore,
renderState: {},
});
const makeWidget = connectHierarchicalMenu(specializedRenderer, () =>
render(null, containerNode)
);
return {
...makeWidget({
attributes,
separator,
rootPath,
showParentLevel,
limit,
showMore,
showMoreLimit,
sortBy,
transformItems,
}),
$$widgetType: 'ais.hierarchicalMenu',
};
};
export default hierarchicalMenu;
| {
throw new Error(withUsage('The `container` option is required.'));
} | conditional_block |
FakeGame.ts | /// <reference path="../../../Phaser/Game.ts" />
/// <reference path="../../../Phaser/State.ts" />
class FakeGame extends State {
| (game: Game) {
super(game);
}
private car: Phaser.Sprite;
private bigCam: Phaser.Camera;
public init() {
this.load.image('track', '../../assets/games/f1/track.png');
this.load.image('car', '../../assets/games/f1/car1.png');
this.load.start();
}
public create() {
this.camera.setBounds(0, 0, this.stage.width, this.stage.height);
this.add.sprite(0, 0, 'track');
this.car = this.game.add.sprite(180, 298, 'car');
this.car.rotation = 180;
this.car.maxVelocity.setTo(150, 150);
this.bigCam = this.add.camera(640, 0, 100, 200);
this.bigCam.follow(this.car, Camera.STYLE_LOCKON);
this.bigCam.setBounds(0, 0, this.stage.width, this.stage.height);
this.bigCam.showBorder = true;
this.bigCam.borderColor = 'rgb(0,0,0)';
this.bigCam.scale.setTo(2, 2);
}
public update() {
if (this.input.keyboard.isDown(Keyboard.LEFT))
{
this.car.rotation -= 4;
}
else if (this.input.keyboard.isDown(Keyboard.RIGHT))
{
this.car.rotation += 4;
}
if (this.game.input.keyboard.isDown(Keyboard.UP))
{
this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 150));
}
else
{
this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 60));
}
}
}
| constructor | identifier_name |
FakeGame.ts | /// <reference path="../../../Phaser/Game.ts" />
/// <reference path="../../../Phaser/State.ts" />
class FakeGame extends State {
constructor(game: Game) {
super(game);
}
private car: Phaser.Sprite;
private bigCam: Phaser.Camera;
public init() {
this.load.image('track', '../../assets/games/f1/track.png');
this.load.image('car', '../../assets/games/f1/car1.png');
this.load.start();
}
public create() {
this.camera.setBounds(0, 0, this.stage.width, this.stage.height);
this.add.sprite(0, 0, 'track');
this.car = this.game.add.sprite(180, 298, 'car');
this.car.rotation = 180;
this.car.maxVelocity.setTo(150, 150);
this.bigCam = this.add.camera(640, 0, 100, 200);
this.bigCam.follow(this.car, Camera.STYLE_LOCKON);
this.bigCam.setBounds(0, 0, this.stage.width, this.stage.height);
this.bigCam.showBorder = true;
this.bigCam.borderColor = 'rgb(0,0,0)';
this.bigCam.scale.setTo(2, 2);
}
public update() {
if (this.input.keyboard.isDown(Keyboard.LEFT))
|
else if (this.input.keyboard.isDown(Keyboard.RIGHT))
{
this.car.rotation += 4;
}
if (this.game.input.keyboard.isDown(Keyboard.UP))
{
this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 150));
}
else
{
this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 60));
}
}
}
| {
this.car.rotation -= 4;
} | conditional_block |
FakeGame.ts | /// <reference path="../../../Phaser/Game.ts" />
/// <reference path="../../../Phaser/State.ts" />
class FakeGame extends State {
constructor(game: Game) {
super(game);
}
private car: Phaser.Sprite;
private bigCam: Phaser.Camera;
public init() {
this.load.image('track', '../../assets/games/f1/track.png');
this.load.image('car', '../../assets/games/f1/car1.png');
this.load.start();
}
public create() {
this.camera.setBounds(0, 0, this.stage.width, this.stage.height);
this.add.sprite(0, 0, 'track');
this.car = this.game.add.sprite(180, 298, 'car');
this.car.rotation = 180;
this.car.maxVelocity.setTo(150, 150);
this.bigCam = this.add.camera(640, 0, 100, 200);
this.bigCam.follow(this.car, Camera.STYLE_LOCKON);
this.bigCam.setBounds(0, 0, this.stage.width, this.stage.height);
this.bigCam.showBorder = true;
this.bigCam.borderColor = 'rgb(0,0,0)';
this.bigCam.scale.setTo(2, 2);
}
public update() |
}
| {
if (this.input.keyboard.isDown(Keyboard.LEFT))
{
this.car.rotation -= 4;
}
else if (this.input.keyboard.isDown(Keyboard.RIGHT))
{
this.car.rotation += 4;
}
if (this.game.input.keyboard.isDown(Keyboard.UP))
{
this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 150));
}
else
{
this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 60));
}
} | identifier_body |
FakeGame.ts | /// <reference path="../../../Phaser/Game.ts" />
/// <reference path="../../../Phaser/State.ts" />
class FakeGame extends State {
constructor(game: Game) {
super(game); | private car: Phaser.Sprite;
private bigCam: Phaser.Camera;
public init() {
this.load.image('track', '../../assets/games/f1/track.png');
this.load.image('car', '../../assets/games/f1/car1.png');
this.load.start();
}
public create() {
this.camera.setBounds(0, 0, this.stage.width, this.stage.height);
this.add.sprite(0, 0, 'track');
this.car = this.game.add.sprite(180, 298, 'car');
this.car.rotation = 180;
this.car.maxVelocity.setTo(150, 150);
this.bigCam = this.add.camera(640, 0, 100, 200);
this.bigCam.follow(this.car, Camera.STYLE_LOCKON);
this.bigCam.setBounds(0, 0, this.stage.width, this.stage.height);
this.bigCam.showBorder = true;
this.bigCam.borderColor = 'rgb(0,0,0)';
this.bigCam.scale.setTo(2, 2);
}
public update() {
if (this.input.keyboard.isDown(Keyboard.LEFT))
{
this.car.rotation -= 4;
}
else if (this.input.keyboard.isDown(Keyboard.RIGHT))
{
this.car.rotation += 4;
}
if (this.game.input.keyboard.isDown(Keyboard.UP))
{
this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 150));
}
else
{
this.car.velocity.copyFrom(this.math.velocityFromAngle(this.car.angle, 60));
}
}
} |
}
| random_line_split |
cucumber.d.ts | // Type definitions for cucumber 0.4.7
// Project: https://github.com/cucumber/cucumber-js
// Definitions by: Matt Frantz <https://github.com/mhfrantz/> |
export interface StepCallback {
(error?: string | Error, result?: any): void;
pending(reason?: any): void;
fail(failureReason?: Error): void;
// This signature should not be necessary, it is equivalent to the first signature above in the degenerate case.
// We include it because otherwise bluebird Promise.done(callback) will not accept a StepCallback.
(value: void): void;
}
export interface Scenario {
getName(): string;
getUri(): string;
}
export interface DataTable<Row> {
hashes(): Row[];
}
// TODO: More of this interface
} | // Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module cucumber {
// TODO: Is there a way to put type safety on the interface of the "this" object in a step definitions file? | random_line_split |
plugin_settings.ts | /*
* Copyright 2018 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as _ from "lodash";
import {Validatable} from "models/mixins/validatable";
export interface ConfigValue {
getValue(): string;
setValue(value: string): void;
isEncrypted(): boolean;
}
export class EncryptedValue implements ConfigValue {
private val: string;
constructor(val: string) {
this.val = val;
}
getValue(): string {
return this.val;
}
setValue(value: string): void {
this.val = value;
}
isEncrypted(): boolean {
return true;
}
}
export class PlainTextValue implements ConfigValue {
private val: string;
constructor(val: string) {
this.val = val;
}
getValue(): string {
return this.val;
}
setValue(value: string): void {
this.val = value;
}
isEncrypted(): boolean {
return false;
}
}
export class Configuration {
readonly key: string;
readonly errors?: string[];
private _value: ConfigValue;
constructor(key: string, value: EncryptedValue | PlainTextValue, errors?: string[]) {
this.key = key;
this._value = value;
this.errors = errors;
}
static fromJSON(config: any): Configuration {
let errors;
if (config.errors) |
let value;
if (config.encrypted_value) {
value = new EncryptedValue(config.encrypted_value);
} else {
value = new PlainTextValue(config.value || "");
}
return new Configuration(config.key, value, errors);
}
get value(): string {
if (this._value) {
return this._value.getValue();
} else {
return "";
}
}
set value(val: string) {
if (val === this._value.getValue()) {
return;
}
this._value = new PlainTextValue(val);
}
toJSON() {
if (this._value.isEncrypted()) {
return {
key: this.key,
encrypted_value: this.value
};
} else {
return {
key: this.key,
value: this.value
};
}
}
}
export class PluginSettings extends Validatable {
public static readonly API_VERSION: string = "v1";
readonly plugin_id: string;
configuration: Configuration[];
constructor(plugin_id: string, configuration?: Configuration[]) {
super();
this.plugin_id = plugin_id;
this.configuration = configuration || [];
}
static fromJSON(json: any): PluginSettings {
return new PluginSettings(json.plugin_id, json.configuration.map((config: any) => Configuration.fromJSON(config)));
}
findConfiguration(key: string): Configuration | undefined {
return _.find(this.configuration, (config) => config.key === key);
}
valueFor(key: string) {
const config = this.findConfiguration(key);
return config ? config.value : undefined;
}
setConfiguration(key: string, value: string) {
const config = this.findConfiguration(key);
if (config) {
config.value = value;
} else {
this.configuration.push(new Configuration(key, new PlainTextValue(value)));
}
}
toJSON(): any {
return {
plugin_id: this.plugin_id,
configuration: this.configuration.map((config) => config.toJSON())
};
}
}
| {
errors = config.errors[config.key];
} | conditional_block |
plugin_settings.ts | /*
* Copyright 2018 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as _ from "lodash";
import {Validatable} from "models/mixins/validatable";
export interface ConfigValue {
getValue(): string;
setValue(value: string): void;
isEncrypted(): boolean;
}
export class EncryptedValue implements ConfigValue {
private val: string;
constructor(val: string) {
this.val = val;
}
getValue(): string {
return this.val;
}
setValue(value: string): void {
this.val = value;
}
isEncrypted(): boolean {
return true;
}
}
export class PlainTextValue implements ConfigValue {
private val: string;
constructor(val: string) {
this.val = val;
}
getValue(): string {
return this.val;
}
setValue(value: string): void {
this.val = value;
}
isEncrypted(): boolean {
return false;
}
}
export class Configuration {
readonly key: string;
readonly errors?: string[];
private _value: ConfigValue;
constructor(key: string, value: EncryptedValue | PlainTextValue, errors?: string[]) {
this.key = key;
this._value = value;
this.errors = errors;
}
static fromJSON(config: any): Configuration {
let errors;
if (config.errors) {
errors = config.errors[config.key];
}
let value;
if (config.encrypted_value) {
value = new EncryptedValue(config.encrypted_value);
} else {
value = new PlainTextValue(config.value || "");
}
return new Configuration(config.key, value, errors);
}
get value(): string {
if (this._value) {
return this._value.getValue();
} else {
return "";
}
}
set value(val: string) {
if (val === this._value.getValue()) {
return;
}
this._value = new PlainTextValue(val);
}
toJSON() {
if (this._value.isEncrypted()) {
return {
key: this.key,
encrypted_value: this.value
};
} else {
return {
key: this.key,
value: this.value
};
}
}
}
export class PluginSettings extends Validatable {
public static readonly API_VERSION: string = "v1";
readonly plugin_id: string;
configuration: Configuration[];
constructor(plugin_id: string, configuration?: Configuration[]) {
super();
this.plugin_id = plugin_id;
this.configuration = configuration || [];
}
static fromJSON(json: any): PluginSettings {
return new PluginSettings(json.plugin_id, json.configuration.map((config: any) => Configuration.fromJSON(config)));
}
findConfiguration(key: string): Configuration | undefined {
return _.find(this.configuration, (config) => config.key === key);
}
valueFor(key: string) {
const config = this.findConfiguration(key);
return config ? config.value : undefined;
}
| (key: string, value: string) {
const config = this.findConfiguration(key);
if (config) {
config.value = value;
} else {
this.configuration.push(new Configuration(key, new PlainTextValue(value)));
}
}
toJSON(): any {
return {
plugin_id: this.plugin_id,
configuration: this.configuration.map((config) => config.toJSON())
};
}
}
| setConfiguration | identifier_name |
plugin_settings.ts | /*
* Copyright 2018 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as _ from "lodash";
import {Validatable} from "models/mixins/validatable";
export interface ConfigValue {
getValue(): string;
setValue(value: string): void;
isEncrypted(): boolean;
}
export class EncryptedValue implements ConfigValue {
private val: string;
constructor(val: string) {
this.val = val;
}
getValue(): string {
return this.val;
}
setValue(value: string): void {
this.val = value;
}
isEncrypted(): boolean {
return true;
}
}
export class PlainTextValue implements ConfigValue {
private val: string;
constructor(val: string) {
this.val = val;
}
getValue(): string {
return this.val;
}
setValue(value: string): void {
this.val = value;
}
isEncrypted(): boolean {
return false;
}
}
export class Configuration {
readonly key: string;
readonly errors?: string[];
private _value: ConfigValue;
constructor(key: string, value: EncryptedValue | PlainTextValue, errors?: string[]) {
this.key = key;
this._value = value;
this.errors = errors;
}
static fromJSON(config: any): Configuration {
let errors;
if (config.errors) {
errors = config.errors[config.key];
}
let value;
if (config.encrypted_value) {
value = new EncryptedValue(config.encrypted_value);
} else {
value = new PlainTextValue(config.value || "");
}
return new Configuration(config.key, value, errors);
}
get value(): string {
if (this._value) {
return this._value.getValue();
} else {
return "";
}
}
set value(val: string) { | }
this._value = new PlainTextValue(val);
}
toJSON() {
if (this._value.isEncrypted()) {
return {
key: this.key,
encrypted_value: this.value
};
} else {
return {
key: this.key,
value: this.value
};
}
}
}
export class PluginSettings extends Validatable {
public static readonly API_VERSION: string = "v1";
readonly plugin_id: string;
configuration: Configuration[];
constructor(plugin_id: string, configuration?: Configuration[]) {
super();
this.plugin_id = plugin_id;
this.configuration = configuration || [];
}
static fromJSON(json: any): PluginSettings {
return new PluginSettings(json.plugin_id, json.configuration.map((config: any) => Configuration.fromJSON(config)));
}
findConfiguration(key: string): Configuration | undefined {
return _.find(this.configuration, (config) => config.key === key);
}
valueFor(key: string) {
const config = this.findConfiguration(key);
return config ? config.value : undefined;
}
setConfiguration(key: string, value: string) {
const config = this.findConfiguration(key);
if (config) {
config.value = value;
} else {
this.configuration.push(new Configuration(key, new PlainTextValue(value)));
}
}
toJSON(): any {
return {
plugin_id: this.plugin_id,
configuration: this.configuration.map((config) => config.toJSON())
};
}
} | if (val === this._value.getValue()) {
return; | random_line_split |
wrapper.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! Wrapper definitions on top of Gecko types in order to be used in the style
//! system.
//!
//! This really follows the Servo pattern in
//! `components/script/layout_wrapper.rs`.
//!
//! This theoretically should live in its own crate, but now it lives in the
//! style system it's kind of pointless in the Stylo case, and only Servo forces
//! the separation between the style system implementation and everything else.
use atomic_refcell::AtomicRefCell;
use data::ElementData;
use dom::{AnimationRules, LayoutIterator, NodeInfo, TElement, TNode, UnsafeNode};
use dom::{OpaqueNode, PresentationalHintsSynthetizer};
use element_state::ElementState;
use error_reporting::StdoutErrorReporter;
use gecko::selector_parser::{SelectorImpl, NonTSPseudoClass, PseudoElement};
use gecko::snapshot_helpers;
use gecko_bindings::bindings;
use gecko_bindings::bindings::{Gecko_DropStyleChildrenIterator, Gecko_MaybeCreateStyleChildrenIterator};
use gecko_bindings::bindings::{Gecko_ElementState, Gecko_GetLastChild, Gecko_GetNextStyleChild};
use gecko_bindings::bindings::{Gecko_GetServoDeclarationBlock, Gecko_IsHTMLElementInHTMLDocument};
use gecko_bindings::bindings::{Gecko_IsLink, Gecko_IsRootElement, Gecko_MatchesElement};
use gecko_bindings::bindings::{Gecko_IsUnvisitedLink, Gecko_IsVisitedLink, Gecko_Namespace};
use gecko_bindings::bindings::{Gecko_SetNodeFlags, Gecko_UnsetNodeFlags};
use gecko_bindings::bindings::Gecko_ClassOrClassList;
use gecko_bindings::bindings::Gecko_GetAnimationRule;
use gecko_bindings::bindings::Gecko_GetStyleContext;
use gecko_bindings::structs;
use gecko_bindings::structs::{RawGeckoElement, RawGeckoNode};
use gecko_bindings::structs::{nsIAtom, nsIContent, nsStyleContext};
use gecko_bindings::structs::EffectCompositor_CascadeLevel as CascadeLevel;
use gecko_bindings::structs::NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO;
use gecko_bindings::structs::NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE;
use parking_lot::RwLock;
use parser::ParserContextExtraData;
use properties::{ComputedValues, parse_style_attribute};
use properties::PropertyDeclarationBlock;
use selector_parser::{ElementExt, Snapshot};
use selectors::Element;
use selectors::parser::{AttrSelector, NamespaceConstraint};
use servo_url::ServoUrl;
use sink::Push;
use std::fmt;
use std::ptr;
use std::sync::Arc;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
use stylist::ApplicableDeclarationBlock;
/// A simple wrapper over a non-null Gecko node (`nsINode`) pointer.
///
/// Important: We don't currently refcount the DOM, because the wrapper lifetime
/// magic guarantees that our LayoutFoo references won't outlive the root, and
/// we don't mutate any of the references on the Gecko side during restyle.
///
/// We could implement refcounting if need be (at a potentially non-trivial
/// performance cost) by implementing Drop and making LayoutFoo non-Copy.
#[derive(Clone, Copy)]
pub struct GeckoNode<'ln>(pub &'ln RawGeckoNode);
impl<'ln> fmt::Debug for GeckoNode<'ln> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(el) = self.as_element() {
el.fmt(f)
} else {
if self.is_text_node() {
write!(f, "<text node> ({:#x})", self.opaque().0)
} else {
write!(f, "<non-text node> ({:#x})", self.opaque().0)
}
}
}
}
impl<'ln> GeckoNode<'ln> {
fn from_content(content: &'ln nsIContent) -> Self {
GeckoNode(&content._base)
}
fn node_info(&self) -> &structs::NodeInfo {
debug_assert!(!self.0.mNodeInfo.mRawPtr.is_null());
unsafe { &*self.0.mNodeInfo.mRawPtr }
}
fn first_child(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mFirstChild.as_ref().map(GeckoNode::from_content) }
}
fn last_child(&self) -> Option<GeckoNode<'ln>> {
unsafe { Gecko_GetLastChild(self.0).map(GeckoNode) }
}
fn prev_sibling(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mPreviousSibling.as_ref().map(GeckoNode::from_content) }
}
fn next_sibling(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mNextSibling.as_ref().map(GeckoNode::from_content) }
}
}
impl<'ln> NodeInfo for GeckoNode<'ln> {
fn is_element(&self) -> bool {
use gecko_bindings::structs::nsINode_BooleanFlag;
self.0.mBoolFlags & (1u32 << nsINode_BooleanFlag::NodeIsElement as u32) != 0
}
fn is_text_node(&self) -> bool {
// This is a DOM constant that isn't going to change.
const TEXT_NODE: u16 = 3;
self.node_info().mInner.mNodeType == TEXT_NODE
}
}
impl<'ln> TNode for GeckoNode<'ln> {
type ConcreteElement = GeckoElement<'ln>;
type ConcreteChildrenIterator = GeckoChildrenIterator<'ln>;
fn to_unsafe(&self) -> UnsafeNode {
(self.0 as *const _ as usize, 0)
}
unsafe fn from_unsafe(n: &UnsafeNode) -> Self {
GeckoNode(&*(n.0 as *mut RawGeckoNode))
}
fn children(self) -> LayoutIterator<GeckoChildrenIterator<'ln>> {
let maybe_iter = unsafe { Gecko_MaybeCreateStyleChildrenIterator(self.0) };
if let Some(iter) = maybe_iter.into_owned_opt() {
LayoutIterator(GeckoChildrenIterator::GeckoIterator(iter))
} else {
LayoutIterator(GeckoChildrenIterator::Current(self.first_child()))
}
}
fn opaque(&self) -> OpaqueNode {
let ptr: usize = self.0 as *const _ as usize;
OpaqueNode(ptr)
}
fn debug_id(self) -> usize {
unimplemented!()
}
fn as_element(&self) -> Option<GeckoElement<'ln>> {
if self.is_element() {
unsafe { Some(GeckoElement(&*(self.0 as *const _ as *const RawGeckoElement))) }
} else {
None
}
}
fn can_be_fragmented(&self) -> bool {
// FIXME(SimonSapin): Servo uses this to implement CSS multicol / fragmentation
// Maybe this isn’t useful for Gecko?
false
}
unsafe fn set_can_be_fragmented(&self, _value: bool) {
// FIXME(SimonSapin): Servo uses this to implement CSS multicol / fragmentation
// Maybe this isn’t useful for Gecko?
}
fn parent_node(&self) -> Option<Self> {
unsafe { bindings::Gecko_GetParentNode(self.0).map(GeckoNode) }
}
fn is_in_doc(&self) -> bool {
unsafe { bindings::Gecko_IsInDocument(self.0) }
}
fn needs_dirty_on_viewport_size_changed(&self) -> bool {
// Gecko's node doesn't have the DIRTY_ON_VIEWPORT_SIZE_CHANGE flag,
// so we force them to be dirtied on viewport size change, regardless if
// they use viewport percentage size or not.
// TODO(shinglyu): implement this in Gecko: https://github.com/servo/servo/pull/11890
true
}
// TODO(shinglyu): implement this in Gecko: https://github.com/servo/servo/pull/11890
unsafe fn set_dirty_on_viewport_size_changed(&self) {}
}
/// A wrapper on top of two kind of iterators, depending on the parent being
/// iterated.
///
/// We generally iterate children by traversing the light-tree siblings of the
/// first child like Servo does.
///
/// However, for nodes with anonymous children, we use a custom (heavier-weight)
/// Gecko-implemented iterator.
///
/// FIXME(emilio): If we take into account shadow DOM, we're going to need the
/// flat tree pretty much always. We can try to optimize the case where there's
/// no shadow root sibling, probably.
pub enum GeckoChildrenIterator<'a> {
/// A simple iterator that tracks the current node being iterated and
/// replaces it with the next sibling when requested.
Current(Option<GeckoNode<'a>>),
/// A Gecko-implemented iterator we need to drop appropriately.
GeckoIterator(bindings::StyleChildrenIteratorOwned),
}
impl<'a> Drop for GeckoChildrenIterator<'a> {
fn drop(&mut self) {
if let GeckoChildrenIterator::GeckoIterator(ref it) = *self {
unsafe {
Gecko_DropStyleChildrenIterator(ptr::read(it as *const _));
}
}
}
}
impl<'a> Iterator for GeckoChildrenIterator<'a> {
type Item = GeckoNode<'a>;
fn next(&mut self) -> Option<GeckoNode<'a>> {
match *self {
GeckoChildrenIterator::Current(curr) => {
let next = curr.and_then(|node| node.next_sibling());
*self = GeckoChildrenIterator::Current(next);
curr
},
GeckoChildrenIterator::GeckoIterator(ref mut it) => unsafe {
Gecko_GetNextStyleChild(it).map(GeckoNode)
}
}
}
}
/// A simple wrapper over a non-null Gecko `Element` pointer.
#[derive(Clone, Copy)]
pub struct GeckoElement<'le>(pub &'le RawGeckoElement);
impl<'le> fmt::Debug for GeckoElement<'le> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "<{}", self.get_local_name()));
if let Some(id) = self.get_id() {
try!(write!(f, " id={}", id));
}
write!(f, "> ({:#x})", self.as_node().opaque().0)
}
}
impl<'le> GeckoElement<'le> {
/// Parse the style attribute of an element.
pub fn parse_style_attribute(value: &str) -> PropertyDeclarationBlock {
// FIXME(bholley): Real base URL and error reporter.
let base_url = &*DUMMY_BASE_URL;
// FIXME(heycam): Needs real ParserContextExtraData so that URLs parse
// properly.
let extra_data = ParserContextExtraData::default();
parse_style_attribute(value, &base_url, Box::new(StdoutErrorReporter), extra_data)
}
fn flags(&self) -> u32 {
self.raw_node()._base._base_1.mFlags
}
fn raw_node(&self) -> &RawGeckoNode {
&(self.0)._base._base._base
}
// FIXME: We can implement this without OOL calls, but we can't easily given
// GeckoNode is a raw reference.
//
// We can use a Cell<T>, but that's a bit of a pain.
fn set_flags(&self, flags: u32) {
unsafe { Gecko_SetNodeFlags(self.as_node().0, flags) }
}
fn unset_flags(&self, flags: u32) {
unsafe { Gecko_UnsetNodeFlags(self.as_node().0, flags) }
}
/// Clear the element data for a given element.
pub fn clear_data(&self) {
let ptr = self.0.mServoData.get();
if !ptr.is_null() {
debug!("Dropping ElementData for {:?}", self);
let data = unsafe { Box::from_raw(self.0.mServoData.get()) };
self.0.mServoData.set(ptr::null_mut());
// Perform a mutable borrow of the data in debug builds. This
// serves as an assertion that there are no outstanding borrows
// when we destroy the data.
debug_assert!({ let _ = data.borrow_mut(); true });
}
}
/// Ensures the element has data, returning the existing data or allocating
/// it.
///
/// Only safe to call with exclusive access to the element, given otherwise
/// it could race to allocate and leak.
pub unsafe fn ensure_data(&self) -> &AtomicRefCell<ElementData> {
match self.get_data() {
Some(x) => x,
None => {
debug!("Creating ElementData for {:?}", self);
let ptr = Box::into_raw(Box::new(AtomicRefCell::new(ElementData::new(None))));
self.0.mServoData.set(ptr);
unsafe { &* ptr }
},
}
}
/// Creates a blank snapshot for this element.
pub fn create_snapshot(&self) -> Snapshot {
Snapshot::new(*self)
}
}
lazy_static! {
/// A dummy base url in order to get it where we don't have any available.
///
/// We need to get rid of this sooner than later.
pub static ref DUMMY_BASE_URL: ServoUrl = {
ServoUrl::parse("http://www.example.org").unwrap()
};
}
impl<'le> TElement for GeckoElement<'le> {
type ConcreteNode = GeckoNode<'le>;
fn as_node(&self) -> Self::ConcreteNode {
unsafe { GeckoNode(&*(self.0 as *const _ as *const RawGeckoNode)) }
}
fn style_attribute(&self) -> Option<&Arc<RwLock<PropertyDeclarationBlock>>> {
let declarations = unsafe { Gecko_GetServoDeclarationBlock(self.0) };
declarations.map(|s| s.as_arc_opt()).unwrap_or(None)
}
fn get_animation_rules(&self, pseudo: Option<&PseudoElement>) -> AnimationRules {
let atom_ptr = pseudo.map(|p| p.as_atom().as_ptr()).unwrap_or(ptr::null_mut());
unsafe {
AnimationRules(
Gecko_GetAnimationRule(self.0, atom_ptr, CascadeLevel::Animations).into_arc_opt(),
Gecko_GetAnimationRule(self.0, atom_ptr, CascadeLevel::Transitions).into_arc_opt())
}
}
fn get_state(&self) -> ElementState {
unsafe {
ElementState::from_bits_truncate(Gecko_ElementState(self.0))
}
}
#[inline]
fn has_attr(&self, namespace: &Namespace, attr: &Atom) -> bool {
unsafe {
bindings::Gecko_HasAttr(self.0,
namespace.0.as_ptr(),
attr.as_ptr())
}
}
#[inline]
fn attr_equals(&self, namespace: &Namespace, attr: &Atom, val: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
namespace.0.as_ptr(),
attr.as_ptr(),
val.as_ptr(),
/* ignoreCase = */ false)
}
}
fn existing_style_for_restyle_damage<'a>(&'a self,
current_cv: Option<&'a Arc<ComputedValues>>,
pseudo: Option<&PseudoElement>)
-> Option<&'a nsStyleContext> {
if current_cv.is_none() {
// Don't bother in doing an ffi call to get null back.
return None;
}
unsafe {
let atom_ptr = pseudo.map(|p| p.as_atom().as_ptr())
.unwrap_or(ptr::null_mut());
let context_ptr = Gecko_GetStyleContext(self.as_node().0, atom_ptr);
context_ptr.as_ref()
}
}
fn has_dirty_descendants(&self) -> bool {
self.flags() & (NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32) != 0
}
unsafe fn set_dirty_descendants(&self) {
debug!("Setting dirty descendants: {:?}", self);
self.set_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32)
}
unsafe fn unset_dirty_descendants(&self) {
self.unset_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32)
}
fn store_children_to_process(&self, _: isize) {
// This is only used for bottom-up traversal, and is thus a no-op for Gecko.
}
fn did_process_child(&self) -> isize {
panic!("Atomic child count not implemented in Gecko");
}
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>> {
unsafe { self.0.mServoData.get().as_ref() }
}
fn skip_root_and_item_based_display_fixup(&self) -> bool {
// We don't want to fix up display values of native anonymous content.
// Additionally, we want to skip root-based display fixup for document
// level native anonymous content subtree roots, since they're not
// really roots from the style fixup perspective. Checking that we
// are NAC handles both cases.
self.flags() & (NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE as u32) != 0
}
}
impl<'le> PartialEq for GeckoElement<'le> {
fn eq(&self, other: &Self) -> bool {
self.0 as *const _ == other.0 as *const _
}
}
impl<'le> PresentationalHintsSynthetizer for GeckoElement<'le> {
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, _hints: &mut V)
where V: Push<ApplicableDeclarationBlock>,
{
// FIXME(bholley) - Need to implement this.
}
}
impl<'le> ::selectors::Element for GeckoElement<'le> {
fn parent_element(&self) -> Option<Self> {
unsafe { bindings::Gecko_GetParentElement(self.0).map(GeckoElement) }
}
fn first_child_element(&self) -> Option<Self> {
let mut child = self.as_node().first_child();
while let Some(child_node) = child {
if let Some(el) = child_node.as_element() {
return Some(el)
}
child = child_node.next_sibling();
}
None
}
fn last_child_element(&self) -> Option<Self> {
let mut child = self.as_node().last_child();
while let Some(child_node) = child {
if let Some(el) = child_node.as_element() {
return Some(el)
}
child = child_node.prev_sibling();
}
None
}
fn prev_sibling_element(&self) -> Option<Self> {
let mut sibling = self.as_node().prev_sibling();
while let Some(sibling_node) = sibling {
if let Some(el) = sibling_node.as_element() {
return Some(el)
}
sibling = sibling_node.prev_sibling();
}
None
}
fn next_sibling_element(&self) -> Option<Self> {
let mut sibling = self.as_node().next_sibling();
while let Some(sibling_node) = sibling {
if let Some(el) = sibling_node.as_element() {
return Some(el)
}
sibling = sibling_node.next_sibling();
}
None
}
fn is_root(&self) -> bool {
unsafe {
Gecko_IsRootElement(self.0)
}
}
fn is_empty(&self) -> bool {
// XXX(emilio): Implement this properly.
false
}
fn get_local_name(&self) -> &WeakAtom {
unsafe {
WeakAtom::new(self.as_node().node_info().mInner.mName.raw())
}
}
fn get_namespace(&self) -> &WeakNamespace {
unsafe {
WeakNamespace::new(Gecko_Namespace(self.0))
}
}
fn match_non_ts_pseudo_class(&self, pseudo_class: NonTSPseudoClass) -> bool {
match pseudo_class {
// https://github.com/servo/servo/issues/8718
NonTSPseudoClass::AnyLink => unsafe { Gecko_IsLink(self.0) },
NonTSPseudoClass::Link => unsafe { Gecko_IsUnvisitedLink(self.0) },
NonTSPseudoClass::Visited => unsafe { Gecko_IsVisitedLink(self.0) },
NonTSPseudoClass::Active |
NonTSPseudoClass::Focus |
NonTSPseudoClass::Hover |
NonTSPseudoClass::Enabled |
NonTSPseudoClass::Disabled |
NonTSPseudoClass::Checked |
NonTSPseudoClass::ReadWrite |
NonTSPseudoClass::Fullscreen |
NonTSPseudoClass::Indeterminate => {
self.get_state().contains(pseudo_class.state_flag())
},
NonTSPseudoClass::ReadOnly => {
!self.get_state().contains(pseudo_class.state_flag())
}
NonTSPseudoClass::MozBrowserFrame => unsafe {
Gecko_MatchesElement(pseudo_class.to_gecko_pseudoclasstype().unwrap(), self.0)
}
}
}
fn get_id(&self) -> Option<Atom> {
let ptr = unsafe {
bindings::Gecko_AtomAttrValue(self.0,
atom!("id").as_ptr())
};
if ptr.is_null() {
None
} else {
Some(Atom::from(ptr))
}
}
fn has_class(&self, name: &Atom) -> bool {
snapshot_helpers::has_class(self.0,
name,
Gecko_ClassOrClassList)
}
fn each_class<F>(&self, callback: F)
where F: FnMut(&Atom)
{
snapshot_helpers::each_class(self.0,
callback,
Gecko_ClassOrClassList)
}
fn is_html_element_in_html_document(&self) -> bool {
unsafe {
Gecko_IsHTMLElementInHTMLDocument(self.0)
}
}
}
/// A few helpers to help with attribute selectors and snapshotting.
pub trait AttrSelectorHelpers {
/// Returns the namespace of the selector, or null otherwise.
fn ns_or_null(&self) -> *mut nsIAtom;
/// Returns the proper selector name depending on whether the requesting
/// element is an HTML element in an HTML document or not.
fn select_name(&self, is_html_element_in_html_document: bool) -> *mut nsIAtom;
}
impl AttrSelectorHelpers for AttrSelector<SelectorImpl> {
fn ns_or_null(&self) -> *mut nsIAtom {
match self.namespace {
NamespaceConstraint::Any => ptr::null_mut(),
NamespaceConstraint::Specific(ref ns) => ns.url.0.as_ptr(),
}
}
fn select_name(&self, is_html_element_in_html_document: bool) -> *mut nsIAtom {
if is_html_element_in_html_document {
self.lower_name.as_ptr()
} else {
self.name.as_ptr()
}
}
}
impl<'le> ::selectors::MatchAttr for GeckoElement<'le> {
type Impl = SelectorImpl;
fn match_attr_has(&self, attr: &AttrSelector<Self::Impl>) -> bool {
unsafe {
bindings::Gecko_HasAttr(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()))
}
}
fn match_attr_equals(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr(),
/* ignoreCase = */ false)
}
}
fn match_attr_equals_ignore_ascii_case(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr(),
/* ignoreCase = */ false)
}
}
fn match_attr_includes(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrIncludes(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn matc | lf, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrDashEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_prefix(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasPrefix(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_substring(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasSubstring(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_suffix(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasSuffix(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
}
impl<'le> ElementExt for GeckoElement<'le> {
#[inline]
fn is_link(&self) -> bool {
self.match_non_ts_pseudo_class(NonTSPseudoClass::AnyLink)
}
#[inline]
fn matches_user_and_author_rules(&self) -> bool {
self.flags() & (NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE as u32) == 0
}
}
| h_attr_dash(&se | identifier_name |
wrapper.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! Wrapper definitions on top of Gecko types in order to be used in the style
//! system.
//!
//! This really follows the Servo pattern in
//! `components/script/layout_wrapper.rs`.
//!
//! This theoretically should live in its own crate, but now it lives in the
//! style system it's kind of pointless in the Stylo case, and only Servo forces
//! the separation between the style system implementation and everything else.
use atomic_refcell::AtomicRefCell;
use data::ElementData;
use dom::{AnimationRules, LayoutIterator, NodeInfo, TElement, TNode, UnsafeNode};
use dom::{OpaqueNode, PresentationalHintsSynthetizer};
use element_state::ElementState;
use error_reporting::StdoutErrorReporter;
use gecko::selector_parser::{SelectorImpl, NonTSPseudoClass, PseudoElement};
use gecko::snapshot_helpers;
use gecko_bindings::bindings;
use gecko_bindings::bindings::{Gecko_DropStyleChildrenIterator, Gecko_MaybeCreateStyleChildrenIterator};
use gecko_bindings::bindings::{Gecko_ElementState, Gecko_GetLastChild, Gecko_GetNextStyleChild};
use gecko_bindings::bindings::{Gecko_GetServoDeclarationBlock, Gecko_IsHTMLElementInHTMLDocument};
use gecko_bindings::bindings::{Gecko_IsLink, Gecko_IsRootElement, Gecko_MatchesElement};
use gecko_bindings::bindings::{Gecko_IsUnvisitedLink, Gecko_IsVisitedLink, Gecko_Namespace};
use gecko_bindings::bindings::{Gecko_SetNodeFlags, Gecko_UnsetNodeFlags};
use gecko_bindings::bindings::Gecko_ClassOrClassList;
use gecko_bindings::bindings::Gecko_GetAnimationRule;
use gecko_bindings::bindings::Gecko_GetStyleContext;
use gecko_bindings::structs;
use gecko_bindings::structs::{RawGeckoElement, RawGeckoNode};
use gecko_bindings::structs::{nsIAtom, nsIContent, nsStyleContext};
use gecko_bindings::structs::EffectCompositor_CascadeLevel as CascadeLevel;
use gecko_bindings::structs::NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO;
use gecko_bindings::structs::NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE;
use parking_lot::RwLock;
use parser::ParserContextExtraData;
use properties::{ComputedValues, parse_style_attribute};
use properties::PropertyDeclarationBlock;
use selector_parser::{ElementExt, Snapshot};
use selectors::Element;
use selectors::parser::{AttrSelector, NamespaceConstraint};
use servo_url::ServoUrl;
use sink::Push;
use std::fmt;
use std::ptr;
use std::sync::Arc;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
use stylist::ApplicableDeclarationBlock;
/// A simple wrapper over a non-null Gecko node (`nsINode`) pointer.
///
/// Important: We don't currently refcount the DOM, because the wrapper lifetime
/// magic guarantees that our LayoutFoo references won't outlive the root, and
/// we don't mutate any of the references on the Gecko side during restyle.
///
/// We could implement refcounting if need be (at a potentially non-trivial
/// performance cost) by implementing Drop and making LayoutFoo non-Copy.
#[derive(Clone, Copy)]
pub struct GeckoNode<'ln>(pub &'ln RawGeckoNode);
impl<'ln> fmt::Debug for GeckoNode<'ln> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(el) = self.as_element() {
el.fmt(f)
} else {
if self.is_text_node() {
write!(f, "<text node> ({:#x})", self.opaque().0)
} else {
write!(f, "<non-text node> ({:#x})", self.opaque().0)
}
}
}
}
impl<'ln> GeckoNode<'ln> {
fn from_content(content: &'ln nsIContent) -> Self {
GeckoNode(&content._base)
}
fn node_info(&self) -> &structs::NodeInfo {
debug_assert!(!self.0.mNodeInfo.mRawPtr.is_null());
unsafe { &*self.0.mNodeInfo.mRawPtr }
}
fn first_child(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mFirstChild.as_ref().map(GeckoNode::from_content) }
}
fn last_child(&self) -> Option<GeckoNode<'ln>> {
unsafe { Gecko_GetLastChild(self.0).map(GeckoNode) }
}
fn prev_sibling(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mPreviousSibling.as_ref().map(GeckoNode::from_content) }
}
fn next_sibling(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mNextSibling.as_ref().map(GeckoNode::from_content) }
}
}
impl<'ln> NodeInfo for GeckoNode<'ln> {
fn is_element(&self) -> bool {
use gecko_bindings::structs::nsINode_BooleanFlag;
self.0.mBoolFlags & (1u32 << nsINode_BooleanFlag::NodeIsElement as u32) != 0
}
fn is_text_node(&self) -> bool {
// This is a DOM constant that isn't going to change.
const TEXT_NODE: u16 = 3;
self.node_info().mInner.mNodeType == TEXT_NODE
}
}
impl<'ln> TNode for GeckoNode<'ln> {
type ConcreteElement = GeckoElement<'ln>;
type ConcreteChildrenIterator = GeckoChildrenIterator<'ln>;
fn to_unsafe(&self) -> UnsafeNode {
(self.0 as *const _ as usize, 0)
}
unsafe fn from_unsafe(n: &UnsafeNode) -> Self {
GeckoNode(&*(n.0 as *mut RawGeckoNode))
}
fn children(self) -> LayoutIterator<GeckoChildrenIterator<'ln>> {
let maybe_iter = unsafe { Gecko_MaybeCreateStyleChildrenIterator(self.0) };
if let Some(iter) = maybe_iter.into_owned_opt() {
LayoutIterator(GeckoChildrenIterator::GeckoIterator(iter))
} else {
LayoutIterator(GeckoChildrenIterator::Current(self.first_child()))
}
}
fn opaque(&self) -> OpaqueNode {
let ptr: usize = self.0 as *const _ as usize;
OpaqueNode(ptr)
}
fn debug_id(self) -> usize {
unimplemented!()
}
fn as_element(&self) -> Option<GeckoElement<'ln>> {
if self.is_element() {
unsafe { Some(GeckoElement(&*(self.0 as *const _ as *const RawGeckoElement))) }
} else {
None
}
}
fn can_be_fragmented(&self) -> bool {
// FIXME(SimonSapin): Servo uses this to implement CSS multicol / fragmentation
// Maybe this isn’t useful for Gecko?
false
}
unsafe fn set_can_be_fragmented(&self, _value: bool) {
// FIXME(SimonSapin): Servo uses this to implement CSS multicol / fragmentation
// Maybe this isn’t useful for Gecko?
}
fn parent_node(&self) -> Option<Self> {
unsafe { bindings::Gecko_GetParentNode(self.0).map(GeckoNode) }
}
fn is_in_doc(&self) -> bool {
unsafe { bindings::Gecko_IsInDocument(self.0) }
}
fn needs_dirty_on_viewport_size_changed(&self) -> bool {
// Gecko's node doesn't have the DIRTY_ON_VIEWPORT_SIZE_CHANGE flag,
// so we force them to be dirtied on viewport size change, regardless if
// they use viewport percentage size or not.
// TODO(shinglyu): implement this in Gecko: https://github.com/servo/servo/pull/11890
true
}
// TODO(shinglyu): implement this in Gecko: https://github.com/servo/servo/pull/11890
unsafe fn set_dirty_on_viewport_size_changed(&self) {}
}
/// A wrapper on top of two kind of iterators, depending on the parent being
/// iterated.
///
/// We generally iterate children by traversing the light-tree siblings of the
/// first child like Servo does.
///
/// However, for nodes with anonymous children, we use a custom (heavier-weight)
/// Gecko-implemented iterator.
///
/// FIXME(emilio): If we take into account shadow DOM, we're going to need the
/// flat tree pretty much always. We can try to optimize the case where there's
/// no shadow root sibling, probably.
pub enum GeckoChildrenIterator<'a> {
/// A simple iterator that tracks the current node being iterated and
/// replaces it with the next sibling when requested.
Current(Option<GeckoNode<'a>>),
/// A Gecko-implemented iterator we need to drop appropriately.
GeckoIterator(bindings::StyleChildrenIteratorOwned),
}
impl<'a> Drop for GeckoChildrenIterator<'a> {
fn drop(&mut self) {
if let GeckoChildrenIterator::GeckoIterator(ref it) = *self {
unsafe {
Gecko_DropStyleChildrenIterator(ptr::read(it as *const _));
}
}
}
}
impl<'a> Iterator for GeckoChildrenIterator<'a> {
type Item = GeckoNode<'a>;
fn next(&mut self) -> Option<GeckoNode<'a>> {
match *self {
GeckoChildrenIterator::Current(curr) => {
let next = curr.and_then(|node| node.next_sibling());
*self = GeckoChildrenIterator::Current(next);
curr
},
GeckoChildrenIterator::GeckoIterator(ref mut it) => unsafe {
Gecko_GetNextStyleChild(it).map(GeckoNode)
}
}
}
}
/// A simple wrapper over a non-null Gecko `Element` pointer.
#[derive(Clone, Copy)]
pub struct GeckoElement<'le>(pub &'le RawGeckoElement);
impl<'le> fmt::Debug for GeckoElement<'le> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "<{}", self.get_local_name()));
if let Some(id) = self.get_id() {
try!(write!(f, " id={}", id));
}
write!(f, "> ({:#x})", self.as_node().opaque().0)
}
}
impl<'le> GeckoElement<'le> {
/// Parse the style attribute of an element.
pub fn parse_style_attribute(value: &str) -> PropertyDeclarationBlock {
// FIXME(bholley): Real base URL and error reporter.
let base_url = &*DUMMY_BASE_URL;
// FIXME(heycam): Needs real ParserContextExtraData so that URLs parse
// properly.
let extra_data = ParserContextExtraData::default();
parse_style_attribute(value, &base_url, Box::new(StdoutErrorReporter), extra_data)
}
fn flags(&self) -> u32 {
self.raw_node()._base._base_1.mFlags
}
fn raw_node(&self) -> &RawGeckoNode {
&(self.0)._base._base._base
}
// FIXME: We can implement this without OOL calls, but we can't easily given
// GeckoNode is a raw reference.
//
// We can use a Cell<T>, but that's a bit of a pain.
fn set_flags(&self, flags: u32) {
unsafe { Gecko_SetNodeFlags(self.as_node().0, flags) }
}
fn unset_flags(&self, flags: u32) {
unsafe { Gecko_UnsetNodeFlags(self.as_node().0, flags) }
}
/// Clear the element data for a given element.
pub fn clear_data(&self) {
let ptr = self.0.mServoData.get();
if !ptr.is_null() {
debug!("Dropping ElementData for {:?}", self);
let data = unsafe { Box::from_raw(self.0.mServoData.get()) };
self.0.mServoData.set(ptr::null_mut());
// Perform a mutable borrow of the data in debug builds. This
// serves as an assertion that there are no outstanding borrows
// when we destroy the data.
debug_assert!({ let _ = data.borrow_mut(); true });
}
}
/// Ensures the element has data, returning the existing data or allocating
/// it.
///
/// Only safe to call with exclusive access to the element, given otherwise
/// it could race to allocate and leak.
pub unsafe fn ensure_data(&self) -> &AtomicRefCell<ElementData> {
match self.get_data() {
Some(x) => x,
None => {
debug!("Creating ElementData for {:?}", self);
let ptr = Box::into_raw(Box::new(AtomicRefCell::new(ElementData::new(None))));
self.0.mServoData.set(ptr);
unsafe { &* ptr }
},
}
}
/// Creates a blank snapshot for this element.
pub fn create_snapshot(&self) -> Snapshot {
Snapshot::new(*self)
}
}
lazy_static! {
/// A dummy base url in order to get it where we don't have any available.
///
/// We need to get rid of this sooner than later.
pub static ref DUMMY_BASE_URL: ServoUrl = {
ServoUrl::parse("http://www.example.org").unwrap()
};
}
impl<'le> TElement for GeckoElement<'le> {
type ConcreteNode = GeckoNode<'le>;
fn as_node(&self) -> Self::ConcreteNode {
unsafe { GeckoNode(&*(self.0 as *const _ as *const RawGeckoNode)) }
}
fn style_attribute(&self) -> Option<&Arc<RwLock<PropertyDeclarationBlock>>> {
let declarations = unsafe { Gecko_GetServoDeclarationBlock(self.0) };
declarations.map(|s| s.as_arc_opt()).unwrap_or(None)
}
fn get_animation_rules(&self, pseudo: Option<&PseudoElement>) -> AnimationRules {
let atom_ptr = pseudo.map(|p| p.as_atom().as_ptr()).unwrap_or(ptr::null_mut());
unsafe {
AnimationRules(
Gecko_GetAnimationRule(self.0, atom_ptr, CascadeLevel::Animations).into_arc_opt(),
Gecko_GetAnimationRule(self.0, atom_ptr, CascadeLevel::Transitions).into_arc_opt())
}
}
fn get_state(&self) -> ElementState {
unsafe {
ElementState::from_bits_truncate(Gecko_ElementState(self.0))
}
}
#[inline]
fn has_attr(&self, namespace: &Namespace, attr: &Atom) -> bool {
unsafe {
bindings::Gecko_HasAttr(self.0,
namespace.0.as_ptr(),
attr.as_ptr())
}
}
#[inline]
fn attr_equals(&self, namespace: &Namespace, attr: &Atom, val: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
namespace.0.as_ptr(),
attr.as_ptr(),
val.as_ptr(),
/* ignoreCase = */ false)
}
}
fn existing_style_for_restyle_damage<'a>(&'a self,
current_cv: Option<&'a Arc<ComputedValues>>,
pseudo: Option<&PseudoElement>)
-> Option<&'a nsStyleContext> {
if current_cv.is_none() {
// Don't bother in doing an ffi call to get null back.
return None;
}
unsafe {
let atom_ptr = pseudo.map(|p| p.as_atom().as_ptr())
.unwrap_or(ptr::null_mut());
let context_ptr = Gecko_GetStyleContext(self.as_node().0, atom_ptr);
context_ptr.as_ref()
}
}
fn has_dirty_descendants(&self) -> bool {
self.flags() & (NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32) != 0
}
unsafe fn set_dirty_descendants(&self) { | self.set_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32)
}
unsafe fn unset_dirty_descendants(&self) {
self.unset_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32)
}
fn store_children_to_process(&self, _: isize) {
// This is only used for bottom-up traversal, and is thus a no-op for Gecko.
}
fn did_process_child(&self) -> isize {
panic!("Atomic child count not implemented in Gecko");
}
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>> {
unsafe { self.0.mServoData.get().as_ref() }
}
fn skip_root_and_item_based_display_fixup(&self) -> bool {
// We don't want to fix up display values of native anonymous content.
// Additionally, we want to skip root-based display fixup for document
// level native anonymous content subtree roots, since they're not
// really roots from the style fixup perspective. Checking that we
// are NAC handles both cases.
self.flags() & (NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE as u32) != 0
}
}
impl<'le> PartialEq for GeckoElement<'le> {
fn eq(&self, other: &Self) -> bool {
self.0 as *const _ == other.0 as *const _
}
}
impl<'le> PresentationalHintsSynthetizer for GeckoElement<'le> {
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, _hints: &mut V)
where V: Push<ApplicableDeclarationBlock>,
{
// FIXME(bholley) - Need to implement this.
}
}
impl<'le> ::selectors::Element for GeckoElement<'le> {
fn parent_element(&self) -> Option<Self> {
unsafe { bindings::Gecko_GetParentElement(self.0).map(GeckoElement) }
}
fn first_child_element(&self) -> Option<Self> {
let mut child = self.as_node().first_child();
while let Some(child_node) = child {
if let Some(el) = child_node.as_element() {
return Some(el)
}
child = child_node.next_sibling();
}
None
}
fn last_child_element(&self) -> Option<Self> {
let mut child = self.as_node().last_child();
while let Some(child_node) = child {
if let Some(el) = child_node.as_element() {
return Some(el)
}
child = child_node.prev_sibling();
}
None
}
fn prev_sibling_element(&self) -> Option<Self> {
let mut sibling = self.as_node().prev_sibling();
while let Some(sibling_node) = sibling {
if let Some(el) = sibling_node.as_element() {
return Some(el)
}
sibling = sibling_node.prev_sibling();
}
None
}
fn next_sibling_element(&self) -> Option<Self> {
let mut sibling = self.as_node().next_sibling();
while let Some(sibling_node) = sibling {
if let Some(el) = sibling_node.as_element() {
return Some(el)
}
sibling = sibling_node.next_sibling();
}
None
}
fn is_root(&self) -> bool {
unsafe {
Gecko_IsRootElement(self.0)
}
}
fn is_empty(&self) -> bool {
// XXX(emilio): Implement this properly.
false
}
fn get_local_name(&self) -> &WeakAtom {
unsafe {
WeakAtom::new(self.as_node().node_info().mInner.mName.raw())
}
}
fn get_namespace(&self) -> &WeakNamespace {
unsafe {
WeakNamespace::new(Gecko_Namespace(self.0))
}
}
fn match_non_ts_pseudo_class(&self, pseudo_class: NonTSPseudoClass) -> bool {
match pseudo_class {
// https://github.com/servo/servo/issues/8718
NonTSPseudoClass::AnyLink => unsafe { Gecko_IsLink(self.0) },
NonTSPseudoClass::Link => unsafe { Gecko_IsUnvisitedLink(self.0) },
NonTSPseudoClass::Visited => unsafe { Gecko_IsVisitedLink(self.0) },
NonTSPseudoClass::Active |
NonTSPseudoClass::Focus |
NonTSPseudoClass::Hover |
NonTSPseudoClass::Enabled |
NonTSPseudoClass::Disabled |
NonTSPseudoClass::Checked |
NonTSPseudoClass::ReadWrite |
NonTSPseudoClass::Fullscreen |
NonTSPseudoClass::Indeterminate => {
self.get_state().contains(pseudo_class.state_flag())
},
NonTSPseudoClass::ReadOnly => {
!self.get_state().contains(pseudo_class.state_flag())
}
NonTSPseudoClass::MozBrowserFrame => unsafe {
Gecko_MatchesElement(pseudo_class.to_gecko_pseudoclasstype().unwrap(), self.0)
}
}
}
fn get_id(&self) -> Option<Atom> {
let ptr = unsafe {
bindings::Gecko_AtomAttrValue(self.0,
atom!("id").as_ptr())
};
if ptr.is_null() {
None
} else {
Some(Atom::from(ptr))
}
}
fn has_class(&self, name: &Atom) -> bool {
snapshot_helpers::has_class(self.0,
name,
Gecko_ClassOrClassList)
}
fn each_class<F>(&self, callback: F)
where F: FnMut(&Atom)
{
snapshot_helpers::each_class(self.0,
callback,
Gecko_ClassOrClassList)
}
fn is_html_element_in_html_document(&self) -> bool {
unsafe {
Gecko_IsHTMLElementInHTMLDocument(self.0)
}
}
}
/// A few helpers to help with attribute selectors and snapshotting.
pub trait AttrSelectorHelpers {
/// Returns the namespace of the selector, or null otherwise.
fn ns_or_null(&self) -> *mut nsIAtom;
/// Returns the proper selector name depending on whether the requesting
/// element is an HTML element in an HTML document or not.
fn select_name(&self, is_html_element_in_html_document: bool) -> *mut nsIAtom;
}
impl AttrSelectorHelpers for AttrSelector<SelectorImpl> {
fn ns_or_null(&self) -> *mut nsIAtom {
match self.namespace {
NamespaceConstraint::Any => ptr::null_mut(),
NamespaceConstraint::Specific(ref ns) => ns.url.0.as_ptr(),
}
}
fn select_name(&self, is_html_element_in_html_document: bool) -> *mut nsIAtom {
if is_html_element_in_html_document {
self.lower_name.as_ptr()
} else {
self.name.as_ptr()
}
}
}
impl<'le> ::selectors::MatchAttr for GeckoElement<'le> {
type Impl = SelectorImpl;
fn match_attr_has(&self, attr: &AttrSelector<Self::Impl>) -> bool {
unsafe {
bindings::Gecko_HasAttr(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()))
}
}
fn match_attr_equals(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr(),
/* ignoreCase = */ false)
}
}
fn match_attr_equals_ignore_ascii_case(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr(),
/* ignoreCase = */ false)
}
}
fn match_attr_includes(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrIncludes(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_dash(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrDashEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_prefix(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasPrefix(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_substring(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasSubstring(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_suffix(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasSuffix(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
}
impl<'le> ElementExt for GeckoElement<'le> {
#[inline]
fn is_link(&self) -> bool {
self.match_non_ts_pseudo_class(NonTSPseudoClass::AnyLink)
}
#[inline]
fn matches_user_and_author_rules(&self) -> bool {
self.flags() & (NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE as u32) == 0
}
} | debug!("Setting dirty descendants: {:?}", self); | random_line_split |
wrapper.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! Wrapper definitions on top of Gecko types in order to be used in the style
//! system.
//!
//! This really follows the Servo pattern in
//! `components/script/layout_wrapper.rs`.
//!
//! This theoretically should live in its own crate, but now it lives in the
//! style system it's kind of pointless in the Stylo case, and only Servo forces
//! the separation between the style system implementation and everything else.
use atomic_refcell::AtomicRefCell;
use data::ElementData;
use dom::{AnimationRules, LayoutIterator, NodeInfo, TElement, TNode, UnsafeNode};
use dom::{OpaqueNode, PresentationalHintsSynthetizer};
use element_state::ElementState;
use error_reporting::StdoutErrorReporter;
use gecko::selector_parser::{SelectorImpl, NonTSPseudoClass, PseudoElement};
use gecko::snapshot_helpers;
use gecko_bindings::bindings;
use gecko_bindings::bindings::{Gecko_DropStyleChildrenIterator, Gecko_MaybeCreateStyleChildrenIterator};
use gecko_bindings::bindings::{Gecko_ElementState, Gecko_GetLastChild, Gecko_GetNextStyleChild};
use gecko_bindings::bindings::{Gecko_GetServoDeclarationBlock, Gecko_IsHTMLElementInHTMLDocument};
use gecko_bindings::bindings::{Gecko_IsLink, Gecko_IsRootElement, Gecko_MatchesElement};
use gecko_bindings::bindings::{Gecko_IsUnvisitedLink, Gecko_IsVisitedLink, Gecko_Namespace};
use gecko_bindings::bindings::{Gecko_SetNodeFlags, Gecko_UnsetNodeFlags};
use gecko_bindings::bindings::Gecko_ClassOrClassList;
use gecko_bindings::bindings::Gecko_GetAnimationRule;
use gecko_bindings::bindings::Gecko_GetStyleContext;
use gecko_bindings::structs;
use gecko_bindings::structs::{RawGeckoElement, RawGeckoNode};
use gecko_bindings::structs::{nsIAtom, nsIContent, nsStyleContext};
use gecko_bindings::structs::EffectCompositor_CascadeLevel as CascadeLevel;
use gecko_bindings::structs::NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO;
use gecko_bindings::structs::NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE;
use parking_lot::RwLock;
use parser::ParserContextExtraData;
use properties::{ComputedValues, parse_style_attribute};
use properties::PropertyDeclarationBlock;
use selector_parser::{ElementExt, Snapshot};
use selectors::Element;
use selectors::parser::{AttrSelector, NamespaceConstraint};
use servo_url::ServoUrl;
use sink::Push;
use std::fmt;
use std::ptr;
use std::sync::Arc;
use string_cache::{Atom, Namespace, WeakAtom, WeakNamespace};
use stylist::ApplicableDeclarationBlock;
/// A simple wrapper over a non-null Gecko node (`nsINode`) pointer.
///
/// Important: We don't currently refcount the DOM, because the wrapper lifetime
/// magic guarantees that our LayoutFoo references won't outlive the root, and
/// we don't mutate any of the references on the Gecko side during restyle.
///
/// We could implement refcounting if need be (at a potentially non-trivial
/// performance cost) by implementing Drop and making LayoutFoo non-Copy.
#[derive(Clone, Copy)]
pub struct GeckoNode<'ln>(pub &'ln RawGeckoNode);
impl<'ln> fmt::Debug for GeckoNode<'ln> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(el) = self.as_element() {
el.fmt(f)
} else {
if self.is_text_node() {
write!(f, "<text node> ({:#x})", self.opaque().0)
} else {
write!(f, "<non-text node> ({:#x})", self.opaque().0)
}
}
}
}
impl<'ln> GeckoNode<'ln> {
fn from_content(content: &'ln nsIContent) -> Self {
GeckoNode(&content._base)
}
fn node_info(&self) -> &structs::NodeInfo {
debug_assert!(!self.0.mNodeInfo.mRawPtr.is_null());
unsafe { &*self.0.mNodeInfo.mRawPtr }
}
fn first_child(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mFirstChild.as_ref().map(GeckoNode::from_content) }
}
fn last_child(&self) -> Option<GeckoNode<'ln>> {
unsafe { Gecko_GetLastChild(self.0).map(GeckoNode) }
}
fn prev_sibling(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mPreviousSibling.as_ref().map(GeckoNode::from_content) }
}
fn next_sibling(&self) -> Option<GeckoNode<'ln>> {
unsafe { self.0.mNextSibling.as_ref().map(GeckoNode::from_content) }
}
}
impl<'ln> NodeInfo for GeckoNode<'ln> {
fn is_element(&self) -> bool {
use gecko_bindings::structs::nsINode_BooleanFlag;
self.0.mBoolFlags & (1u32 << nsINode_BooleanFlag::NodeIsElement as u32) != 0
}
fn is_text_node(&self) -> bool {
// This is a DOM constant that isn't going to change.
const TEXT_NODE: u16 = 3;
self.node_info().mInner.mNodeType == TEXT_NODE
}
}
impl<'ln> TNode for GeckoNode<'ln> {
type ConcreteElement = GeckoElement<'ln>;
type ConcreteChildrenIterator = GeckoChildrenIterator<'ln>;
fn to_unsafe(&self) -> UnsafeNode {
(self.0 as *const _ as usize, 0)
}
unsafe fn from_unsafe(n: &UnsafeNode) -> Self {
GeckoNode(&*(n.0 as *mut RawGeckoNode))
}
fn children(self) -> LayoutIterator<GeckoChildrenIterator<'ln>> {
let maybe_iter = unsafe { Gecko_MaybeCreateStyleChildrenIterator(self.0) };
if let Some(iter) = maybe_iter.into_owned_opt() {
LayoutIterator(GeckoChildrenIterator::GeckoIterator(iter))
} else {
LayoutIterator(GeckoChildrenIterator::Current(self.first_child()))
}
}
fn opaque(&self) -> OpaqueNode {
let ptr: usize = self.0 as *const _ as usize;
OpaqueNode(ptr)
}
fn debug_id(self) -> usize {
unimplemented!()
}
fn as_element(&self) -> Option<GeckoElement<'ln>> {
if self.is_element() {
unsafe { Some(GeckoElement(&*(self.0 as *const _ as *const RawGeckoElement))) }
} else {
None
}
}
fn can_be_fragmented(&self) -> bool {
// FIXME(SimonSapin): Servo uses this to implement CSS multicol / fragmentation
// Maybe this isn’t useful for Gecko?
false
}
unsafe fn set_can_be_fragmented(&self, _value: bool) {
// FIXME(SimonSapin): Servo uses this to implement CSS multicol / fragmentation
// Maybe this isn’t useful for Gecko?
}
fn parent_node(&self) -> Option<Self> {
unsafe { bindings::Gecko_GetParentNode(self.0).map(GeckoNode) }
}
fn is_in_doc(&self) -> bool {
unsafe { bindings::Gecko_IsInDocument(self.0) }
}
fn needs_dirty_on_viewport_size_changed(&self) -> bool {
// Gecko's node doesn't have the DIRTY_ON_VIEWPORT_SIZE_CHANGE flag,
// so we force them to be dirtied on viewport size change, regardless if
// they use viewport percentage size or not.
// TODO(shinglyu): implement this in Gecko: https://github.com/servo/servo/pull/11890
true
}
// TODO(shinglyu): implement this in Gecko: https://github.com/servo/servo/pull/11890
unsafe fn set_dirty_on_viewport_size_changed(&self) {}
}
/// A wrapper on top of two kind of iterators, depending on the parent being
/// iterated.
///
/// We generally iterate children by traversing the light-tree siblings of the
/// first child like Servo does.
///
/// However, for nodes with anonymous children, we use a custom (heavier-weight)
/// Gecko-implemented iterator.
///
/// FIXME(emilio): If we take into account shadow DOM, we're going to need the
/// flat tree pretty much always. We can try to optimize the case where there's
/// no shadow root sibling, probably.
pub enum GeckoChildrenIterator<'a> {
/// A simple iterator that tracks the current node being iterated and
/// replaces it with the next sibling when requested.
Current(Option<GeckoNode<'a>>),
/// A Gecko-implemented iterator we need to drop appropriately.
GeckoIterator(bindings::StyleChildrenIteratorOwned),
}
impl<'a> Drop for GeckoChildrenIterator<'a> {
fn drop(&mut self) {
if let GeckoChildrenIterator::GeckoIterator(ref it) = *self {
unsafe {
Gecko_DropStyleChildrenIterator(ptr::read(it as *const _));
}
}
}
}
impl<'a> Iterator for GeckoChildrenIterator<'a> {
type Item = GeckoNode<'a>;
fn next(&mut self) -> Option<GeckoNode<'a>> {
match *self {
GeckoChildrenIterator::Current(curr) => {
let next = curr.and_then(|node| node.next_sibling());
*self = GeckoChildrenIterator::Current(next);
curr
},
GeckoChildrenIterator::GeckoIterator(ref mut it) => unsafe {
Gecko_GetNextStyleChild(it).map(GeckoNode)
}
}
}
}
/// A simple wrapper over a non-null Gecko `Element` pointer.
#[derive(Clone, Copy)]
pub struct GeckoElement<'le>(pub &'le RawGeckoElement);
impl<'le> fmt::Debug for GeckoElement<'le> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "<{}", self.get_local_name()));
if let Some(id) = self.get_id() {
try!(write!(f, " id={}", id));
}
write!(f, "> ({:#x})", self.as_node().opaque().0)
}
}
impl<'le> GeckoElement<'le> {
/// Parse the style attribute of an element.
pub fn parse_style_attribute(value: &str) -> PropertyDeclarationBlock {
// FIXME(bholley): Real base URL and error reporter.
let base_url = &*DUMMY_BASE_URL;
// FIXME(heycam): Needs real ParserContextExtraData so that URLs parse
// properly.
let extra_data = ParserContextExtraData::default();
parse_style_attribute(value, &base_url, Box::new(StdoutErrorReporter), extra_data)
}
fn flags(&self) -> u32 {
self.raw_node()._base._base_1.mFlags
}
fn raw_node(&self) -> &RawGeckoNode {
&(self.0)._base._base._base
}
// FIXME: We can implement this without OOL calls, but we can't easily given
// GeckoNode is a raw reference.
//
// We can use a Cell<T>, but that's a bit of a pain.
fn set_flags(&self, flags: u32) {
unsafe { Gecko_SetNodeFlags(self.as_node().0, flags) }
}
fn unset_flags(&self, flags: u32) {
unsafe { Gecko_UnsetNodeFlags(self.as_node().0, flags) }
}
/// Clear the element data for a given element.
pub fn clear_data(&self) {
| /// Ensures the element has data, returning the existing data or allocating
/// it.
///
/// Only safe to call with exclusive access to the element, given otherwise
/// it could race to allocate and leak.
pub unsafe fn ensure_data(&self) -> &AtomicRefCell<ElementData> {
match self.get_data() {
Some(x) => x,
None => {
debug!("Creating ElementData for {:?}", self);
let ptr = Box::into_raw(Box::new(AtomicRefCell::new(ElementData::new(None))));
self.0.mServoData.set(ptr);
unsafe { &* ptr }
},
}
}
/// Creates a blank snapshot for this element.
pub fn create_snapshot(&self) -> Snapshot {
Snapshot::new(*self)
}
}
lazy_static! {
/// A dummy base url in order to get it where we don't have any available.
///
/// We need to get rid of this sooner than later.
pub static ref DUMMY_BASE_URL: ServoUrl = {
ServoUrl::parse("http://www.example.org").unwrap()
};
}
impl<'le> TElement for GeckoElement<'le> {
type ConcreteNode = GeckoNode<'le>;
fn as_node(&self) -> Self::ConcreteNode {
unsafe { GeckoNode(&*(self.0 as *const _ as *const RawGeckoNode)) }
}
fn style_attribute(&self) -> Option<&Arc<RwLock<PropertyDeclarationBlock>>> {
let declarations = unsafe { Gecko_GetServoDeclarationBlock(self.0) };
declarations.map(|s| s.as_arc_opt()).unwrap_or(None)
}
fn get_animation_rules(&self, pseudo: Option<&PseudoElement>) -> AnimationRules {
let atom_ptr = pseudo.map(|p| p.as_atom().as_ptr()).unwrap_or(ptr::null_mut());
unsafe {
AnimationRules(
Gecko_GetAnimationRule(self.0, atom_ptr, CascadeLevel::Animations).into_arc_opt(),
Gecko_GetAnimationRule(self.0, atom_ptr, CascadeLevel::Transitions).into_arc_opt())
}
}
fn get_state(&self) -> ElementState {
unsafe {
ElementState::from_bits_truncate(Gecko_ElementState(self.0))
}
}
#[inline]
fn has_attr(&self, namespace: &Namespace, attr: &Atom) -> bool {
unsafe {
bindings::Gecko_HasAttr(self.0,
namespace.0.as_ptr(),
attr.as_ptr())
}
}
#[inline]
fn attr_equals(&self, namespace: &Namespace, attr: &Atom, val: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
namespace.0.as_ptr(),
attr.as_ptr(),
val.as_ptr(),
/* ignoreCase = */ false)
}
}
fn existing_style_for_restyle_damage<'a>(&'a self,
current_cv: Option<&'a Arc<ComputedValues>>,
pseudo: Option<&PseudoElement>)
-> Option<&'a nsStyleContext> {
if current_cv.is_none() {
// Don't bother in doing an ffi call to get null back.
return None;
}
unsafe {
let atom_ptr = pseudo.map(|p| p.as_atom().as_ptr())
.unwrap_or(ptr::null_mut());
let context_ptr = Gecko_GetStyleContext(self.as_node().0, atom_ptr);
context_ptr.as_ref()
}
}
fn has_dirty_descendants(&self) -> bool {
self.flags() & (NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32) != 0
}
unsafe fn set_dirty_descendants(&self) {
debug!("Setting dirty descendants: {:?}", self);
self.set_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32)
}
unsafe fn unset_dirty_descendants(&self) {
self.unset_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32)
}
fn store_children_to_process(&self, _: isize) {
// This is only used for bottom-up traversal, and is thus a no-op for Gecko.
}
fn did_process_child(&self) -> isize {
panic!("Atomic child count not implemented in Gecko");
}
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>> {
unsafe { self.0.mServoData.get().as_ref() }
}
fn skip_root_and_item_based_display_fixup(&self) -> bool {
// We don't want to fix up display values of native anonymous content.
// Additionally, we want to skip root-based display fixup for document
// level native anonymous content subtree roots, since they're not
// really roots from the style fixup perspective. Checking that we
// are NAC handles both cases.
self.flags() & (NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE as u32) != 0
}
}
impl<'le> PartialEq for GeckoElement<'le> {
fn eq(&self, other: &Self) -> bool {
self.0 as *const _ == other.0 as *const _
}
}
impl<'le> PresentationalHintsSynthetizer for GeckoElement<'le> {
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, _hints: &mut V)
where V: Push<ApplicableDeclarationBlock>,
{
// FIXME(bholley) - Need to implement this.
}
}
impl<'le> ::selectors::Element for GeckoElement<'le> {
fn parent_element(&self) -> Option<Self> {
unsafe { bindings::Gecko_GetParentElement(self.0).map(GeckoElement) }
}
fn first_child_element(&self) -> Option<Self> {
let mut child = self.as_node().first_child();
while let Some(child_node) = child {
if let Some(el) = child_node.as_element() {
return Some(el)
}
child = child_node.next_sibling();
}
None
}
fn last_child_element(&self) -> Option<Self> {
let mut child = self.as_node().last_child();
while let Some(child_node) = child {
if let Some(el) = child_node.as_element() {
return Some(el)
}
child = child_node.prev_sibling();
}
None
}
fn prev_sibling_element(&self) -> Option<Self> {
let mut sibling = self.as_node().prev_sibling();
while let Some(sibling_node) = sibling {
if let Some(el) = sibling_node.as_element() {
return Some(el)
}
sibling = sibling_node.prev_sibling();
}
None
}
fn next_sibling_element(&self) -> Option<Self> {
let mut sibling = self.as_node().next_sibling();
while let Some(sibling_node) = sibling {
if let Some(el) = sibling_node.as_element() {
return Some(el)
}
sibling = sibling_node.next_sibling();
}
None
}
fn is_root(&self) -> bool {
unsafe {
Gecko_IsRootElement(self.0)
}
}
fn is_empty(&self) -> bool {
// XXX(emilio): Implement this properly.
false
}
fn get_local_name(&self) -> &WeakAtom {
unsafe {
WeakAtom::new(self.as_node().node_info().mInner.mName.raw())
}
}
fn get_namespace(&self) -> &WeakNamespace {
unsafe {
WeakNamespace::new(Gecko_Namespace(self.0))
}
}
fn match_non_ts_pseudo_class(&self, pseudo_class: NonTSPseudoClass) -> bool {
match pseudo_class {
// https://github.com/servo/servo/issues/8718
NonTSPseudoClass::AnyLink => unsafe { Gecko_IsLink(self.0) },
NonTSPseudoClass::Link => unsafe { Gecko_IsUnvisitedLink(self.0) },
NonTSPseudoClass::Visited => unsafe { Gecko_IsVisitedLink(self.0) },
NonTSPseudoClass::Active |
NonTSPseudoClass::Focus |
NonTSPseudoClass::Hover |
NonTSPseudoClass::Enabled |
NonTSPseudoClass::Disabled |
NonTSPseudoClass::Checked |
NonTSPseudoClass::ReadWrite |
NonTSPseudoClass::Fullscreen |
NonTSPseudoClass::Indeterminate => {
self.get_state().contains(pseudo_class.state_flag())
},
NonTSPseudoClass::ReadOnly => {
!self.get_state().contains(pseudo_class.state_flag())
}
NonTSPseudoClass::MozBrowserFrame => unsafe {
Gecko_MatchesElement(pseudo_class.to_gecko_pseudoclasstype().unwrap(), self.0)
}
}
}
fn get_id(&self) -> Option<Atom> {
let ptr = unsafe {
bindings::Gecko_AtomAttrValue(self.0,
atom!("id").as_ptr())
};
if ptr.is_null() {
None
} else {
Some(Atom::from(ptr))
}
}
fn has_class(&self, name: &Atom) -> bool {
snapshot_helpers::has_class(self.0,
name,
Gecko_ClassOrClassList)
}
fn each_class<F>(&self, callback: F)
where F: FnMut(&Atom)
{
snapshot_helpers::each_class(self.0,
callback,
Gecko_ClassOrClassList)
}
fn is_html_element_in_html_document(&self) -> bool {
unsafe {
Gecko_IsHTMLElementInHTMLDocument(self.0)
}
}
}
/// A few helpers to help with attribute selectors and snapshotting.
pub trait AttrSelectorHelpers {
/// Returns the namespace of the selector, or null otherwise.
fn ns_or_null(&self) -> *mut nsIAtom;
/// Returns the proper selector name depending on whether the requesting
/// element is an HTML element in an HTML document or not.
fn select_name(&self, is_html_element_in_html_document: bool) -> *mut nsIAtom;
}
impl AttrSelectorHelpers for AttrSelector<SelectorImpl> {
fn ns_or_null(&self) -> *mut nsIAtom {
match self.namespace {
NamespaceConstraint::Any => ptr::null_mut(),
NamespaceConstraint::Specific(ref ns) => ns.url.0.as_ptr(),
}
}
fn select_name(&self, is_html_element_in_html_document: bool) -> *mut nsIAtom {
if is_html_element_in_html_document {
self.lower_name.as_ptr()
} else {
self.name.as_ptr()
}
}
}
impl<'le> ::selectors::MatchAttr for GeckoElement<'le> {
type Impl = SelectorImpl;
fn match_attr_has(&self, attr: &AttrSelector<Self::Impl>) -> bool {
unsafe {
bindings::Gecko_HasAttr(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()))
}
}
fn match_attr_equals(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr(),
/* ignoreCase = */ false)
}
}
fn match_attr_equals_ignore_ascii_case(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr(),
/* ignoreCase = */ false)
}
}
fn match_attr_includes(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrIncludes(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_dash(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrDashEquals(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_prefix(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasPrefix(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_substring(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasSubstring(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
fn match_attr_suffix(&self, attr: &AttrSelector<Self::Impl>, value: &Atom) -> bool {
unsafe {
bindings::Gecko_AttrHasSuffix(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr())
}
}
}
impl<'le> ElementExt for GeckoElement<'le> {
#[inline]
fn is_link(&self) -> bool {
self.match_non_ts_pseudo_class(NonTSPseudoClass::AnyLink)
}
#[inline]
fn matches_user_and_author_rules(&self) -> bool {
self.flags() & (NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE as u32) == 0
}
}
| let ptr = self.0.mServoData.get();
if !ptr.is_null() {
debug!("Dropping ElementData for {:?}", self);
let data = unsafe { Box::from_raw(self.0.mServoData.get()) };
self.0.mServoData.set(ptr::null_mut());
// Perform a mutable borrow of the data in debug builds. This
// serves as an assertion that there are no outstanding borrows
// when we destroy the data.
debug_assert!({ let _ = data.borrow_mut(); true });
}
}
| identifier_body |
auth.js | var passport = require('passport');
module.exports = {
login: function(req, res) {
var auth = passport.authenticate('local', function(err, user) {
var errorsMessage = '';
if(err) |
if (!user) {
errorsMessage += 'Incorrect login data';
}
if(errorsMessage.length > 0){
res.render('home', {
loginErrors: errorsMessage
});
return;
}
req.logIn(user, function(err) {
if (err) return next(err);
res.redirect('/home');
});
res.end();
});
auth(req, res);
},
logout: function(req, res, next) {
req.logout();
res.redirect('/home');
},
isAuthenticated: function(req, res, next) {
if (!req.isAuthenticated()) {
res.status(403);
res.redirect('/unauthorized');
res.end();
}
else {
next();
}
},
isInRole: function(role) {
return function(req, res, next) {
if (req.isAuthenticated() && req.user.roles.indexOf(role) > -1) {
next();
}
else {
res.redirect('/unauthorized');
res.end();
}
}
}
}; | {
errorsMessage += 'Could not fetch user';
} | conditional_block |
auth.js | var passport = require('passport');
module.exports = {
login: function(req, res) {
var auth = passport.authenticate('local', function(err, user) {
var errorsMessage = '';
if(err) {
errorsMessage += 'Could not fetch user';
}
if (!user) {
errorsMessage += 'Incorrect login data';
}
if(errorsMessage.length > 0){
res.render('home', {
loginErrors: errorsMessage
});
return;
}
req.logIn(user, function(err) {
if (err) return next(err);
res.redirect('/home');
});
res.end();
});
auth(req, res);
},
logout: function(req, res, next) {
req.logout();
res.redirect('/home');
},
isAuthenticated: function(req, res, next) {
if (!req.isAuthenticated()) {
res.status(403);
res.redirect('/unauthorized');
res.end();
}
else {
next();
}
},
isInRole: function(role) {
return function(req, res, next) {
if (req.isAuthenticated() && req.user.roles.indexOf(role) > -1) {
next();
} | else {
res.redirect('/unauthorized');
res.end();
}
}
}
}; | random_line_split | |
icon.py | import base64
from jarr.bootstrap import conf, session
from jarr.models import Icon
from jarr.utils import jarr_get
from .abstract import AbstractController
class IconController(AbstractController):
_db_cls = Icon
_user_id_key = None # type: str
@staticmethod
def _build_from_url(attrs):
if 'url' in attrs and 'content' not in attrs:
try:
resp = jarr_get(attrs['url'], timeout=conf.crawler.timeout,
user_agent=conf.crawler.user_agent)
except Exception:
return attrs
attrs.update({'url': resp.url,
'mimetype': resp.headers.get('content-type', None),
'content': base64.b64encode(resp.content).decode('utf8')})
return attrs
def create(self, **attrs):
return super().create(**self._build_from_url(attrs))
def update(self, filters, attrs, return_objs=False, commit=True):
attrs = self._build_from_url(attrs)
return super().update(filters, attrs, return_objs, commit)
def delete(self, obj_id, commit=True):
obj = self.get(url=obj_id)
session.delete(obj)
if commit:
|
return obj
| session.flush()
session.commit() | conditional_block |
icon.py | import base64
from jarr.bootstrap import conf, session
from jarr.models import Icon
from jarr.utils import jarr_get
from .abstract import AbstractController
class IconController(AbstractController):
_db_cls = Icon
_user_id_key = None # type: str
@staticmethod
def _build_from_url(attrs):
if 'url' in attrs and 'content' not in attrs:
try:
resp = jarr_get(attrs['url'], timeout=conf.crawler.timeout,
user_agent=conf.crawler.user_agent)
except Exception:
return attrs
attrs.update({'url': resp.url,
'mimetype': resp.headers.get('content-type', None),
'content': base64.b64encode(resp.content).decode('utf8')})
return attrs
def create(self, **attrs):
return super().create(**self._build_from_url(attrs))
def update(self, filters, attrs, return_objs=False, commit=True):
attrs = self._build_from_url(attrs)
return super().update(filters, attrs, return_objs, commit)
| session.commit()
return obj | def delete(self, obj_id, commit=True):
obj = self.get(url=obj_id)
session.delete(obj)
if commit:
session.flush() | random_line_split |
icon.py | import base64
from jarr.bootstrap import conf, session
from jarr.models import Icon
from jarr.utils import jarr_get
from .abstract import AbstractController
class | (AbstractController):
_db_cls = Icon
_user_id_key = None # type: str
@staticmethod
def _build_from_url(attrs):
if 'url' in attrs and 'content' not in attrs:
try:
resp = jarr_get(attrs['url'], timeout=conf.crawler.timeout,
user_agent=conf.crawler.user_agent)
except Exception:
return attrs
attrs.update({'url': resp.url,
'mimetype': resp.headers.get('content-type', None),
'content': base64.b64encode(resp.content).decode('utf8')})
return attrs
def create(self, **attrs):
return super().create(**self._build_from_url(attrs))
def update(self, filters, attrs, return_objs=False, commit=True):
attrs = self._build_from_url(attrs)
return super().update(filters, attrs, return_objs, commit)
def delete(self, obj_id, commit=True):
obj = self.get(url=obj_id)
session.delete(obj)
if commit:
session.flush()
session.commit()
return obj
| IconController | identifier_name |
icon.py | import base64
from jarr.bootstrap import conf, session
from jarr.models import Icon
from jarr.utils import jarr_get
from .abstract import AbstractController
class IconController(AbstractController):
_db_cls = Icon
_user_id_key = None # type: str
@staticmethod
def _build_from_url(attrs):
if 'url' in attrs and 'content' not in attrs:
try:
resp = jarr_get(attrs['url'], timeout=conf.crawler.timeout,
user_agent=conf.crawler.user_agent)
except Exception:
return attrs
attrs.update({'url': resp.url,
'mimetype': resp.headers.get('content-type', None),
'content': base64.b64encode(resp.content).decode('utf8')})
return attrs
def create(self, **attrs):
|
def update(self, filters, attrs, return_objs=False, commit=True):
attrs = self._build_from_url(attrs)
return super().update(filters, attrs, return_objs, commit)
def delete(self, obj_id, commit=True):
obj = self.get(url=obj_id)
session.delete(obj)
if commit:
session.flush()
session.commit()
return obj
| return super().create(**self._build_from_url(attrs)) | identifier_body |
websocket_test.py | from tornado.concurrent import Future
from tornado import gen
from tornado.httpclient import HTTPError
from tornado.log import gen_log
from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog
from tornado.web import Application, RequestHandler
from tornado.websocket import WebSocketHandler, websocket_connect, WebSocketError
class EchoHandler(WebSocketHandler):
def initialize(self, close_future):
self.close_future = close_future
def on_message(self, message):
self.write_message(message, isinstance(message, bytes))
def on_close(self):
self.close_future.set_result(None)
class NonWebSocketHandler(RequestHandler):
def get(self):
self.write('ok')
class WebSocketTest(AsyncHTTPTestCase):
def get_app(self):
self.close_future = Future()
return Application([
('/echo', EchoHandler, dict(close_future=self.close_future)),
('/non_ws', NonWebSocketHandler),
])
@gen_test
def test_websocket_gen(self):
ws = yield websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port(),
io_loop=self.io_loop)
ws.write_message('hello')
response = yield ws.read_message()
self.assertEqual(response, 'hello')
def test_websocket_callbacks(self):
websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port(),
io_loop=self.io_loop, callback=self.stop)
ws = self.wait().result()
ws.write_message('hello')
ws.read_message(self.stop)
response = self.wait().result()
self.assertEqual(response, 'hello')
@gen_test
def test_websocket_http_fail(self):
with self.assertRaises(HTTPError) as cm: | 'ws://localhost:%d/notfound' % self.get_http_port(),
io_loop=self.io_loop)
self.assertEqual(cm.exception.code, 404)
@gen_test
def test_websocket_http_success(self):
with self.assertRaises(WebSocketError):
yield websocket_connect(
'ws://localhost:%d/non_ws' % self.get_http_port(),
io_loop=self.io_loop)
@gen_test
def test_websocket_network_fail(self):
sock, port = bind_unused_port()
sock.close()
with self.assertRaises(HTTPError) as cm:
with ExpectLog(gen_log, ".*"):
yield websocket_connect(
'ws://localhost:%d/' % port,
io_loop=self.io_loop,
connect_timeout=0.01)
self.assertEqual(cm.exception.code, 599)
@gen_test
def test_websocket_close_buffered_data(self):
ws = yield websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port())
ws.write_message('hello')
ws.write_message('world')
ws.stream.close()
yield self.close_future | yield websocket_connect( | random_line_split |
websocket_test.py | from tornado.concurrent import Future
from tornado import gen
from tornado.httpclient import HTTPError
from tornado.log import gen_log
from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog
from tornado.web import Application, RequestHandler
from tornado.websocket import WebSocketHandler, websocket_connect, WebSocketError
class EchoHandler(WebSocketHandler):
def initialize(self, close_future):
|
def on_message(self, message):
self.write_message(message, isinstance(message, bytes))
def on_close(self):
self.close_future.set_result(None)
class NonWebSocketHandler(RequestHandler):
def get(self):
self.write('ok')
class WebSocketTest(AsyncHTTPTestCase):
def get_app(self):
self.close_future = Future()
return Application([
('/echo', EchoHandler, dict(close_future=self.close_future)),
('/non_ws', NonWebSocketHandler),
])
@gen_test
def test_websocket_gen(self):
ws = yield websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port(),
io_loop=self.io_loop)
ws.write_message('hello')
response = yield ws.read_message()
self.assertEqual(response, 'hello')
def test_websocket_callbacks(self):
websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port(),
io_loop=self.io_loop, callback=self.stop)
ws = self.wait().result()
ws.write_message('hello')
ws.read_message(self.stop)
response = self.wait().result()
self.assertEqual(response, 'hello')
@gen_test
def test_websocket_http_fail(self):
with self.assertRaises(HTTPError) as cm:
yield websocket_connect(
'ws://localhost:%d/notfound' % self.get_http_port(),
io_loop=self.io_loop)
self.assertEqual(cm.exception.code, 404)
@gen_test
def test_websocket_http_success(self):
with self.assertRaises(WebSocketError):
yield websocket_connect(
'ws://localhost:%d/non_ws' % self.get_http_port(),
io_loop=self.io_loop)
@gen_test
def test_websocket_network_fail(self):
sock, port = bind_unused_port()
sock.close()
with self.assertRaises(HTTPError) as cm:
with ExpectLog(gen_log, ".*"):
yield websocket_connect(
'ws://localhost:%d/' % port,
io_loop=self.io_loop,
connect_timeout=0.01)
self.assertEqual(cm.exception.code, 599)
@gen_test
def test_websocket_close_buffered_data(self):
ws = yield websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port())
ws.write_message('hello')
ws.write_message('world')
ws.stream.close()
yield self.close_future
| self.close_future = close_future | identifier_body |
websocket_test.py | from tornado.concurrent import Future
from tornado import gen
from tornado.httpclient import HTTPError
from tornado.log import gen_log
from tornado.testing import AsyncHTTPTestCase, gen_test, bind_unused_port, ExpectLog
from tornado.web import Application, RequestHandler
from tornado.websocket import WebSocketHandler, websocket_connect, WebSocketError
class EchoHandler(WebSocketHandler):
def | (self, close_future):
self.close_future = close_future
def on_message(self, message):
self.write_message(message, isinstance(message, bytes))
def on_close(self):
self.close_future.set_result(None)
class NonWebSocketHandler(RequestHandler):
def get(self):
self.write('ok')
class WebSocketTest(AsyncHTTPTestCase):
def get_app(self):
self.close_future = Future()
return Application([
('/echo', EchoHandler, dict(close_future=self.close_future)),
('/non_ws', NonWebSocketHandler),
])
@gen_test
def test_websocket_gen(self):
ws = yield websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port(),
io_loop=self.io_loop)
ws.write_message('hello')
response = yield ws.read_message()
self.assertEqual(response, 'hello')
def test_websocket_callbacks(self):
websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port(),
io_loop=self.io_loop, callback=self.stop)
ws = self.wait().result()
ws.write_message('hello')
ws.read_message(self.stop)
response = self.wait().result()
self.assertEqual(response, 'hello')
@gen_test
def test_websocket_http_fail(self):
with self.assertRaises(HTTPError) as cm:
yield websocket_connect(
'ws://localhost:%d/notfound' % self.get_http_port(),
io_loop=self.io_loop)
self.assertEqual(cm.exception.code, 404)
@gen_test
def test_websocket_http_success(self):
with self.assertRaises(WebSocketError):
yield websocket_connect(
'ws://localhost:%d/non_ws' % self.get_http_port(),
io_loop=self.io_loop)
@gen_test
def test_websocket_network_fail(self):
sock, port = bind_unused_port()
sock.close()
with self.assertRaises(HTTPError) as cm:
with ExpectLog(gen_log, ".*"):
yield websocket_connect(
'ws://localhost:%d/' % port,
io_loop=self.io_loop,
connect_timeout=0.01)
self.assertEqual(cm.exception.code, 599)
@gen_test
def test_websocket_close_buffered_data(self):
ws = yield websocket_connect(
'ws://localhost:%d/echo' % self.get_http_port())
ws.write_message('hello')
ws.write_message('world')
ws.stream.close()
yield self.close_future
| initialize | identifier_name |
lib.rs | // Copyright 2017 The Grin Developers
//
// 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. |
//! # Overview
//!
//! <b>cuckoo-miner</b> is a Rust wrapper around John Tromp's Cuckoo Miner
//! C implementations, intended primarily for use in the Grin MimbleWimble
//! blockhain development project. However, it is also suitable for use as
//! a standalone miner or by any other project needing to use the
//! cuckoo cycle proof of work. cuckoo-miner is plugin based, and provides
//! a high level interface to load and work with C mining implementations.
//!
//! A brief description of basic operations follows, as well as some
//! examples of how cuckoo miner should be called.
//!
//! ## Interfaces
//!
//! The library provides 2 high level interfaces:
//!
//! The [CuckooPluginManager](struct.CuckooPluginManager.html)
//! takes care of querying and loading plugins. A caller can provide a directory
//! for the plugin manager to scan, and the manager will load each plugin and
//! populate a [CuckooPluginCapabilities](struct.CuckooPluginCapabilities.html)
//! for each, which will contain a description of the plugin as well as any parameters
//! that can be configured.
//!
//! The [CuckooMiner](struct.CuckooMiner.html) struct provides a
//! high-level interface that a caller can use to load and run one or many
//! simultaneous plugin mining implementations.
//!
//! ## Operational Modes
//!
//! The miner can be run in either synchronous or asynchronous mode.
//!
//! Syncronous mode uses the [`mine`](struct.CuckooMiner.html#method.mine) function,
//! which takes a complete hash, processes it within the calling thread via the plugin's
//! [`call_cuckoo`](struct.PluginLibrary.html#method.call_cuckoo) function,
//! and returns the result.
//!
//! Asynchronous mode uses the [`notify`](struct.CuckoMiner.html#method.notify)
//! function, which takes the pre-nonce and
//! post-nonce parts of a block header, mutates it internally with a nonce, and
//! inserts the resulting hash into the plugin's internal queue for processing.
//! Solutions are placed into an output queue, which the calling thread can
//! read ascynronously via a [job handle](struct.CuckooMinerJobHandle.html).
//!
//! Examples of using either mode follow:
//!
//! ## Example - Sync mode
//! ```
//! extern crate cuckoo_miner as cuckoo;
//! extern crate time;
//!
//! use std::path::PathBuf;
//!
//! let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
//! d.push("target/debug/plugins/");
//!
//! // load plugin manager
//! let mut plugin_manager = cuckoo::CuckooPluginManager::new().unwrap();
//! plugin_manager
//! .load_plugin_dir(String::from(d.to_str().unwrap()))
//! .expect("");
//!
//! // Load a single plugin using a filter
//! let caps=plugin_manager.get_available_plugins("lean_cpu_16").unwrap();
//! let mut config_vec=Vec::new();
//! let mut config = cuckoo::CuckooMinerConfig::new();
//! config.plugin_full_path = caps[0].full_path.clone();
//! config_vec.push(config);
//!
//! let duration_in_seconds=60;
//! let stat_check_interval = 3;
//! let deadline = time::get_time().sec + duration_in_seconds;
//! let mut next_stat_check = time::get_time().sec + stat_check_interval;
//!
//! let mut i=0;
//! println!("Test mining for {} seconds, looking for difficulty > 0", duration_in_seconds);
//! for c in config_vec.clone().into_iter(){
//! println!("Plugin (Sync Mode): {}", c.plugin_full_path);
//! }
//!
//! while time::get_time().sec < deadline {
//! let miner = cuckoo::CuckooMiner::new(config_vec.clone()).expect("");
//! //Mining with a dummy header here, but in reality this would be a passed in
//! //header hash
//! let mut header:[u8; 32] = [0;32];
//! let mut iterations=0;
//! let mut solution = cuckoo::CuckooMinerSolution::new();
//! loop {
//! header[0]=i;
//! //Mine on plugin loaded at index 0 (which should be only one loaded in
//! //Sync mode
//! let result = miner.mine(&header, &mut solution, 0).unwrap();
//! iterations+=1;
//! if result == true {
//! println!("Solution found after {} iterations: {}", i, solution);
//! println!("For hash: {:?}", header);
//! break;
//! }
//! if time::get_time().sec > deadline {
//! println!("Exiting after {} iterations", iterations);
//! break;
//! }
//! if time::get_time().sec >= next_stat_check {
//! let stats_vec=miner.get_stats(0).unwrap();
//! for s in stats_vec.into_iter() {
//! let last_solution_time_secs = s.last_solution_time as f64 / 1000.0;
//! let last_hashes_per_sec = 1.0 / last_solution_time_secs;
//! println!("Plugin 0 - Device {} ({}) - Last Solution time: {}; Solutions per second: {:.*}",
//! s.device_id, s.device_name, last_solution_time_secs, 3, last_hashes_per_sec);
//! }
//! next_stat_check = time::get_time().sec + stat_check_interval;
//! }
//! i+=1;
//! if i==255 {
//! i=0;
//! }
//! # break;
//! }
//! # break;
//! }
//! ```
//!
//! ## Example - Async mode
//! ```
//! extern crate cuckoo_miner as cuckoo;
//! extern crate time;
//!
//! use std::path::PathBuf;
//!
//! //Grin Pre and Post headers, into which a nonce is to be insterted for mutation
//! let SAMPLE_GRIN_PRE_HEADER_1:&str = "00000000000000118e0fe6bcfaa76c6795592339f27b6d330d8f9c4ac8e86171a66357d1\
//! d0fce808000000005971f14f0000000000000000000000000000000000000000000000000000000000000000\
//! 3e1fcdd453ce51ffbb16dd200aeb9ef7375aec196e97094868428a7325e4a19b00";
//!
//! let SAMPLE_GRIN_POST_HEADER_1:&str = "010a020364";
//!
//! let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
//! d.push("target/debug/plugins/");
//!
//! // load plugin manager
//! let mut plugin_manager = cuckoo::CuckooPluginManager::new().unwrap();
//! plugin_manager
//! .load_plugin_dir(String::from(d.to_str().unwrap()))
//! .expect("");
//!
//! // Load a single pugin using a filter
//! let caps=plugin_manager.get_available_plugins("lean_cpu_16").unwrap();
//! let mut config_vec=Vec::new();
//! let mut config = cuckoo::CuckooMinerConfig::new();
//! config.plugin_full_path = caps[0].full_path.clone();
//! config_vec.push(config);
//!
//! let duration_in_seconds=60;
//! let stat_check_interval = 3;
//! let deadline = time::get_time().sec + duration_in_seconds;
//! let mut next_stat_check = time::get_time().sec + stat_check_interval;
//! let mut stats_updated=false;
//!
//! while time::get_time().sec < deadline {
//!
//! println!("Test mining for {} seconds, looking for difficulty > 0", duration_in_seconds);
//! let mut i=0;
//! for c in config_vec.clone().into_iter(){
//! println!("Plugin {}: {}", i, c.plugin_full_path);
//! i+=1;
//! }
//!
//! // these always get consumed after a notify
//! let miner = cuckoo::CuckooMiner::new(config_vec.clone()).expect("");
//! let job_handle = miner.notify(1, SAMPLE_GRIN_PRE_HEADER_1, SAMPLE_GRIN_POST_HEADER_1, 0).unwrap();
//!
//! loop {
//! if let Some(s) = job_handle.get_solution() {
//! println!("Sol found: {}, {:?}", s.get_nonce_as_u64(), s);
//! // up to you to read it and check difficulty
//! continue;
//! }
//! if time::get_time().sec >= next_stat_check {
//! let mut sps_total=0.0;
//! for index in 0..config_vec.len() {
//! let stats_vec=job_handle.get_stats(index).unwrap();
//! for s in stats_vec.into_iter() {
//! let last_solution_time_secs = s.last_solution_time as f64 / 1000.0;
//! let last_hashes_per_sec = 1.0 / last_solution_time_secs;
//! println!("Plugin {} - Device {} ({}) - Last Solution time: {}; Solutions per second: {:.*}",
//! index,s.device_id, s.device_name, last_solution_time_secs, 3, last_hashes_per_sec);
//! if last_hashes_per_sec.is_finite() {
//! sps_total+=last_hashes_per_sec;
//! }
//! if last_solution_time_secs > 0.0 {
//! stats_updated = true;
//! }
//! i+=1;
//! }
//! }
//! println!("Total solutions per second: {}", sps_total);
//! next_stat_check = time::get_time().sec + stat_check_interval;
//! }
//! if time::get_time().sec > deadline {
//! println!("Stopping jobs and waiting for cleanup");
//! job_handle.stop_jobs();
//! break;
//! }
//! # break;
//! }
//! # break;
//! }
//! ```
#![deny(non_upper_case_globals)]
#![deny(non_camel_case_types)]
#![deny(non_snake_case)]
#![deny(unused_mut)]
#![warn(missing_docs)]
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate regex;
extern crate rand;
extern crate byteorder;
extern crate crypto;
extern crate blake2_rfc as blake2;
extern crate libloading as libloading;
extern crate libc;
extern crate glob;
mod error;
mod miner;
mod manager;
mod cuckoo_sys;
pub use error::error::CuckooMinerError;
pub use miner::miner::{CuckooMinerConfig, CuckooMiner, CuckooMinerSolution, CuckooMinerJobHandle,
CuckooMinerDeviceStats};
pub use manager::manager::{CuckooPluginManager, CuckooPluginCapabilities};
pub use cuckoo_sys::manager::PluginLibrary; | // See the License for the specific language governing permissions and
// limitations under the License. | random_line_split |
package.py | import ckan.controllers.package as package
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.model as model
from ckan.common import c
class MapactionPackageController(package.PackageController):
def groups(self, id):
q = model.Session.query(model.Group) \
.filter(model.Group.is_organization == False) \
.filter(model.Group.state == 'active')
groups = q.all()
'''
package = c.get('package')
if package:
groups = set(groups) - set(package.get_groups())
''' | 'auth_user_obj': c.userobj, 'use_cache': False}
group_list = model_dictize.group_list_dictize(groups, context)
c.event_dropdown = [[group['id'], group['display_name']]
for group in group_list]
return super(MapactionPackageController, self).groups(id) |
context = {'model': model, 'session': model.Session,
'user': c.user or c.author, 'for_view': True, | random_line_split |
package.py | import ckan.controllers.package as package
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.model as model
from ckan.common import c
class | (package.PackageController):
def groups(self, id):
q = model.Session.query(model.Group) \
.filter(model.Group.is_organization == False) \
.filter(model.Group.state == 'active')
groups = q.all()
'''
package = c.get('package')
if package:
groups = set(groups) - set(package.get_groups())
'''
context = {'model': model, 'session': model.Session,
'user': c.user or c.author, 'for_view': True,
'auth_user_obj': c.userobj, 'use_cache': False}
group_list = model_dictize.group_list_dictize(groups, context)
c.event_dropdown = [[group['id'], group['display_name']]
for group in group_list]
return super(MapactionPackageController, self).groups(id) | MapactionPackageController | identifier_name |
package.py | import ckan.controllers.package as package
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.model as model
from ckan.common import c
class MapactionPackageController(package.PackageController):
| def groups(self, id):
q = model.Session.query(model.Group) \
.filter(model.Group.is_organization == False) \
.filter(model.Group.state == 'active')
groups = q.all()
'''
package = c.get('package')
if package:
groups = set(groups) - set(package.get_groups())
'''
context = {'model': model, 'session': model.Session,
'user': c.user or c.author, 'for_view': True,
'auth_user_obj': c.userobj, 'use_cache': False}
group_list = model_dictize.group_list_dictize(groups, context)
c.event_dropdown = [[group['id'], group['display_name']]
for group in group_list]
return super(MapactionPackageController, self).groups(id) | identifier_body | |
autoscale_setting_resource_paged.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.paging import Paged
class | (Paged):
"""
A paging container for iterating over a list of :class:`AutoscaleSettingResource <azure.mgmt.monitor.models.AutoscaleSettingResource>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[AutoscaleSettingResource]'}
}
def __init__(self, *args, **kwargs):
super(AutoscaleSettingResourcePaged, self).__init__(*args, **kwargs)
| AutoscaleSettingResourcePaged | identifier_name |
autoscale_setting_resource_paged.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.paging import Paged
class AutoscaleSettingResourcePaged(Paged):
"""
A paging container for iterating over a list of :class:`AutoscaleSettingResource <azure.mgmt.monitor.models.AutoscaleSettingResource>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[AutoscaleSettingResource]'}
}
def __init__(self, *args, **kwargs):
| super(AutoscaleSettingResourcePaged, self).__init__(*args, **kwargs) | identifier_body | |
autoscale_setting_resource_paged.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.paging import Paged | """
A paging container for iterating over a list of :class:`AutoscaleSettingResource <azure.mgmt.monitor.models.AutoscaleSettingResource>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[AutoscaleSettingResource]'}
}
def __init__(self, *args, **kwargs):
super(AutoscaleSettingResourcePaged, self).__init__(*args, **kwargs) |
class AutoscaleSettingResourcePaged(Paged): | random_line_split |
pyunit_automl_regression.py | from __future__ import print_function
from __future__ import print_function
import sys, os
sys.path.insert(1, os.path.join("..","..","..",".."))
import h2o
from h2o.automl import H2OAutoML
from tests import pyunit_utils as pu
from _automl_utils import import_dataset
def test_default_automl_with_regression_task():
ds = import_dataset('regression')
aml = H2OAutoML(max_models=2,
project_name='aml_regression')
aml.train(y=ds.target, training_frame=ds.train, validation_frame=ds.valid, leaderboard_frame=ds.test)
print(aml.leader)
print(aml.leaderboard)
assert aml.leaderboard.columns == ["model_id", "mean_residual_deviance", "rmse", "mse", "mae", "rmsle"]
def test_workaround_for_distribution():
try:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "true"))
ds = import_dataset('regression')
aml = H2OAutoML(project_name="py_test", | family='poisson',
),
exclude_algos=['StackedEnsemble'],
max_runtime_secs=60,
seed=1)
aml.train(y=ds.target, training_frame=ds.train)
model_names = [aml.leaderboard[i, 0] for i in range(0, (aml.leaderboard.nrows))]
for mn in model_names:
m = h2o.get_model(mn)
dist = m.params['distribution'] if 'distribution' in m.params else m.params['family'] if 'family' in m.params else None
print("{}: distribution = {}".format(mn, dist))
except:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "false"))
pu.run_tests([
test_default_automl_with_regression_task,
test_workaround_for_distribution,
]) | algo_parameters=dict(
distribution='poisson', | random_line_split |
pyunit_automl_regression.py | from __future__ import print_function
from __future__ import print_function
import sys, os
sys.path.insert(1, os.path.join("..","..","..",".."))
import h2o
from h2o.automl import H2OAutoML
from tests import pyunit_utils as pu
from _automl_utils import import_dataset
def | ():
ds = import_dataset('regression')
aml = H2OAutoML(max_models=2,
project_name='aml_regression')
aml.train(y=ds.target, training_frame=ds.train, validation_frame=ds.valid, leaderboard_frame=ds.test)
print(aml.leader)
print(aml.leaderboard)
assert aml.leaderboard.columns == ["model_id", "mean_residual_deviance", "rmse", "mse", "mae", "rmsle"]
def test_workaround_for_distribution():
try:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "true"))
ds = import_dataset('regression')
aml = H2OAutoML(project_name="py_test",
algo_parameters=dict(
distribution='poisson',
family='poisson',
),
exclude_algos=['StackedEnsemble'],
max_runtime_secs=60,
seed=1)
aml.train(y=ds.target, training_frame=ds.train)
model_names = [aml.leaderboard[i, 0] for i in range(0, (aml.leaderboard.nrows))]
for mn in model_names:
m = h2o.get_model(mn)
dist = m.params['distribution'] if 'distribution' in m.params else m.params['family'] if 'family' in m.params else None
print("{}: distribution = {}".format(mn, dist))
except:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "false"))
pu.run_tests([
test_default_automl_with_regression_task,
test_workaround_for_distribution,
])
| test_default_automl_with_regression_task | identifier_name |
pyunit_automl_regression.py | from __future__ import print_function
from __future__ import print_function
import sys, os
sys.path.insert(1, os.path.join("..","..","..",".."))
import h2o
from h2o.automl import H2OAutoML
from tests import pyunit_utils as pu
from _automl_utils import import_dataset
def test_default_automl_with_regression_task():
ds = import_dataset('regression')
aml = H2OAutoML(max_models=2,
project_name='aml_regression')
aml.train(y=ds.target, training_frame=ds.train, validation_frame=ds.valid, leaderboard_frame=ds.test)
print(aml.leader)
print(aml.leaderboard)
assert aml.leaderboard.columns == ["model_id", "mean_residual_deviance", "rmse", "mse", "mae", "rmsle"]
def test_workaround_for_distribution():
try:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "true"))
ds = import_dataset('regression')
aml = H2OAutoML(project_name="py_test",
algo_parameters=dict(
distribution='poisson',
family='poisson',
),
exclude_algos=['StackedEnsemble'],
max_runtime_secs=60,
seed=1)
aml.train(y=ds.target, training_frame=ds.train)
model_names = [aml.leaderboard[i, 0] for i in range(0, (aml.leaderboard.nrows))]
for mn in model_names:
|
except:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "false"))
pu.run_tests([
test_default_automl_with_regression_task,
test_workaround_for_distribution,
])
| m = h2o.get_model(mn)
dist = m.params['distribution'] if 'distribution' in m.params else m.params['family'] if 'family' in m.params else None
print("{}: distribution = {}".format(mn, dist)) | conditional_block |
pyunit_automl_regression.py | from __future__ import print_function
from __future__ import print_function
import sys, os
sys.path.insert(1, os.path.join("..","..","..",".."))
import h2o
from h2o.automl import H2OAutoML
from tests import pyunit_utils as pu
from _automl_utils import import_dataset
def test_default_automl_with_regression_task():
|
def test_workaround_for_distribution():
try:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "true"))
ds = import_dataset('regression')
aml = H2OAutoML(project_name="py_test",
algo_parameters=dict(
distribution='poisson',
family='poisson',
),
exclude_algos=['StackedEnsemble'],
max_runtime_secs=60,
seed=1)
aml.train(y=ds.target, training_frame=ds.train)
model_names = [aml.leaderboard[i, 0] for i in range(0, (aml.leaderboard.nrows))]
for mn in model_names:
m = h2o.get_model(mn)
dist = m.params['distribution'] if 'distribution' in m.params else m.params['family'] if 'family' in m.params else None
print("{}: distribution = {}".format(mn, dist))
except:
h2o.rapids("(setproperty \"{}\" \"{}\")".format("sys.ai.h2o.automl.algo_parameters.all.enabled", "false"))
pu.run_tests([
test_default_automl_with_regression_task,
test_workaround_for_distribution,
])
| ds = import_dataset('regression')
aml = H2OAutoML(max_models=2,
project_name='aml_regression')
aml.train(y=ds.target, training_frame=ds.train, validation_frame=ds.valid, leaderboard_frame=ds.test)
print(aml.leader)
print(aml.leaderboard)
assert aml.leaderboard.columns == ["model_id", "mean_residual_deviance", "rmse", "mse", "mae", "rmsle"] | identifier_body |
mem_map.rs | const BOOT_ROM_START: u16 = 0x0000;
const BOOT_ROM_END: u16 = 0x00FF;
const CART_ROM_START: u16 = 0x0000;
const CART_ROM_END: u16 = 0x7FFF;
const CART_ENTRY_POINT: u16 = 0x0100;
const CART_HEADER_START: u16 = 0x0100;
const CART_HEADER_END: u16 = 0x014F;
const CART_FIXED_START: u16 = 0x0150;
const CART_FIXED_END: u16 = 0x3FFF;
const CART_SWITCH_START: u16 = 0x4000;
const CART_SWITCH_END: u16 = 0x7FFF;
const VIDEO_RAM_START: u16 = 0x8000;
const VIDEO_RAM_END: u16 = 0x9FFF;
const SOUND_REG_START: u16 = 0xFF10;
const SOUND_REG_END: u16 = 0xFF3F;
// http://gbdev.gg8.se/wiki/articles/Video_Display
const LCD_CONTROL_REGISTER: u16 = 0xFF40; // R/W
const LCD_STATUS_REGISTER: u16 = 0xFF41; // R/W
const SCROLL_Y: u16 = 0xFF42; // R/W
const SCROLL_X: u16 = 0xFF43; // R/W
const LCD_LY: u16 = 0xFF44; // R
const LCD_LYC: u16 = 0xFF45; // R/W
const LCD_WY: u16 = 0xFF4A; // R/W
const LCD_WX: u16 = 0xFF4B; // R/W
const BG_PALETTE_DATA: u16 = 0xFF47; // R/W
const OBJECT_PALETTE_0: u16 = 0xFF48; // R/W
const OBJECT_PALETTE_1: u16 = 0xFF49; // R/W
const HIGH_RAM_START: u16 = 0xFF80;
const HIGH_RAM_END: u16 = 0xFFFE;
pub fn map_addr(addr: u16) -> Addr {
match addr {
BOOT_ROM_START...BOOT_ROM_END => Addr::BootRom(addr - BOOT_ROM_START),
CART_HEADER_START...CART_HEADER_END => Addr::CartHeader(addr - CART_ROM_START),
CART_FIXED_START...CART_FIXED_END => Addr::CartFixed(addr - CART_ROM_START),
CART_SWITCH_START...CART_SWITCH_END => Addr::CartSwitch(addr - CART_ROM_START),
VIDEO_RAM_START...VIDEO_RAM_END => Addr::VideoRam(addr - VIDEO_RAM_START),
SOUND_REG_START...SOUND_REG_END => Addr::SoundRegister(addr - SOUND_REG_START),
HIGH_RAM_START...HIGH_RAM_END => Addr::HighRam(addr - HIGH_RAM_START),
_ => panic!("Unrecognised physical address: {:#x}", addr),
}
}
pub enum Addr {
BootRom(u16),
CartHeader(u16),
CartFixed(u16),
CartSwitch(u16),
VideoRam(u16),
SoundRegister(u16),
HighRam(u16),
}
pub fn cartridge_type(byte: u8) -> &'static str {
match byte {
0x00 => "ROM ONLY",
0x01 => "MBC1",
0x02 => "MBC1+RAM",
0x03 => "MBC1+RAM+BATTERY",
0x05 => "MBC2",
0x06 => "MBC2+BATTERY",
0x08 => "ROM+RAM",
0x09 => "ROM+RAM+BATTERY",
0x0B => "MMM01",
0x0C => "MMM01+RAM",
0x0D => "MMM01+RAM+BATTERY",
0x0F => "MBC3+TIMER+BATTERY",
0x10 => "MBC3+TIMER+RAM+BATTERY",
0x11 => "MBC3",
0x12 => "MBC3+RAM",
0x13 => "MBC3+RAM+BATTERY",
0x15 => "MBC4",
0x16 => "MBC4+RAM",
0x17 => "MBC4+RAM+BATTERY",
0x19 => "MBC5",
0x1A => "MBC5+RAM",
0x1B => "MBC5+RAM+BATTERY",
0x1C => "MBC5+RUMBLE",
0x1D => "MBC5+RUMBLE+RAM",
0x1E => "MBC5+RUMBLE+RAM+BATTERY",
0x20 => "MBC6",
0x22 => "MBC7+SENSOR+RUMBLE+RAM+BATTERY",
0xFC => "POCKET CAMERA",
0xFD => "BANDAI TAMA5",
0xFE => "HuC3",
0xFF => "HuC1+RAM+BATTERY",
_ => panic!("Unknown Cartridge Type"),
}
}
pub fn rom_size(byte: u8) -> &'static str |
pub fn ram_size(byte: u8) -> &'static str {
match byte {
0x00 => "None",
0x01 => "2 KBytes",
0x02 => "8 Kbytes",
0x03 => "32 KBytes (4 banks of 8KBytes each)",
0x04 => "128 KBytes (16 banks of 8KBytes each)",
0x05 => "64 KBytes (8 banks of 8KBytes each)",
_ => panic!("Unknown RAM Size")
}
}
| {
match byte {
0x00 => "32KByte (no ROM banking)",
0x01 => "64KByte (4 banks)",
0x02 => "128KByte (8 banks)",
0x03 => "256KByte (16 banks)",
0x04 => "512KByte (32 banks)",
0x05 => "1MByte (64 banks)",
0x06 => "2MByte (128 banks)",
0x07 => "4MByte (256 banks)",
0x52 => "1.1MByte (72 banks)",
0x53 => "1.2MByte (80 banks)",
0x54 => "1.5MByte (96 banks)",
_ => panic!("Unknown ROM Size")
}
} | identifier_body |
mem_map.rs | const BOOT_ROM_START: u16 = 0x0000;
const BOOT_ROM_END: u16 = 0x00FF;
const CART_ROM_START: u16 = 0x0000;
const CART_ROM_END: u16 = 0x7FFF;
const CART_ENTRY_POINT: u16 = 0x0100;
const CART_HEADER_START: u16 = 0x0100;
const CART_HEADER_END: u16 = 0x014F;
const CART_FIXED_START: u16 = 0x0150;
const CART_FIXED_END: u16 = 0x3FFF;
const CART_SWITCH_START: u16 = 0x4000;
const CART_SWITCH_END: u16 = 0x7FFF;
const VIDEO_RAM_START: u16 = 0x8000;
const VIDEO_RAM_END: u16 = 0x9FFF;
const SOUND_REG_START: u16 = 0xFF10;
const SOUND_REG_END: u16 = 0xFF3F;
// http://gbdev.gg8.se/wiki/articles/Video_Display
const LCD_CONTROL_REGISTER: u16 = 0xFF40; // R/W
const LCD_STATUS_REGISTER: u16 = 0xFF41; // R/W
const SCROLL_Y: u16 = 0xFF42; // R/W
const SCROLL_X: u16 = 0xFF43; // R/W
const LCD_LY: u16 = 0xFF44; // R
const LCD_LYC: u16 = 0xFF45; // R/W
const LCD_WY: u16 = 0xFF4A; // R/W
const LCD_WX: u16 = 0xFF4B; // R/W
const BG_PALETTE_DATA: u16 = 0xFF47; // R/W
const OBJECT_PALETTE_0: u16 = 0xFF48; // R/W
const OBJECT_PALETTE_1: u16 = 0xFF49; // R/W
const HIGH_RAM_START: u16 = 0xFF80;
const HIGH_RAM_END: u16 = 0xFFFE;
pub fn map_addr(addr: u16) -> Addr {
match addr {
BOOT_ROM_START...BOOT_ROM_END => Addr::BootRom(addr - BOOT_ROM_START),
CART_HEADER_START...CART_HEADER_END => Addr::CartHeader(addr - CART_ROM_START),
CART_FIXED_START...CART_FIXED_END => Addr::CartFixed(addr - CART_ROM_START),
CART_SWITCH_START...CART_SWITCH_END => Addr::CartSwitch(addr - CART_ROM_START),
VIDEO_RAM_START...VIDEO_RAM_END => Addr::VideoRam(addr - VIDEO_RAM_START),
SOUND_REG_START...SOUND_REG_END => Addr::SoundRegister(addr - SOUND_REG_START),
HIGH_RAM_START...HIGH_RAM_END => Addr::HighRam(addr - HIGH_RAM_START),
_ => panic!("Unrecognised physical address: {:#x}", addr),
}
}
pub enum | {
BootRom(u16),
CartHeader(u16),
CartFixed(u16),
CartSwitch(u16),
VideoRam(u16),
SoundRegister(u16),
HighRam(u16),
}
pub fn cartridge_type(byte: u8) -> &'static str {
match byte {
0x00 => "ROM ONLY",
0x01 => "MBC1",
0x02 => "MBC1+RAM",
0x03 => "MBC1+RAM+BATTERY",
0x05 => "MBC2",
0x06 => "MBC2+BATTERY",
0x08 => "ROM+RAM",
0x09 => "ROM+RAM+BATTERY",
0x0B => "MMM01",
0x0C => "MMM01+RAM",
0x0D => "MMM01+RAM+BATTERY",
0x0F => "MBC3+TIMER+BATTERY",
0x10 => "MBC3+TIMER+RAM+BATTERY",
0x11 => "MBC3",
0x12 => "MBC3+RAM",
0x13 => "MBC3+RAM+BATTERY",
0x15 => "MBC4",
0x16 => "MBC4+RAM",
0x17 => "MBC4+RAM+BATTERY",
0x19 => "MBC5",
0x1A => "MBC5+RAM",
0x1B => "MBC5+RAM+BATTERY",
0x1C => "MBC5+RUMBLE",
0x1D => "MBC5+RUMBLE+RAM",
0x1E => "MBC5+RUMBLE+RAM+BATTERY",
0x20 => "MBC6",
0x22 => "MBC7+SENSOR+RUMBLE+RAM+BATTERY",
0xFC => "POCKET CAMERA",
0xFD => "BANDAI TAMA5",
0xFE => "HuC3",
0xFF => "HuC1+RAM+BATTERY",
_ => panic!("Unknown Cartridge Type"),
}
}
pub fn rom_size(byte: u8) -> &'static str {
match byte {
0x00 => "32KByte (no ROM banking)",
0x01 => "64KByte (4 banks)",
0x02 => "128KByte (8 banks)",
0x03 => "256KByte (16 banks)",
0x04 => "512KByte (32 banks)",
0x05 => "1MByte (64 banks)",
0x06 => "2MByte (128 banks)",
0x07 => "4MByte (256 banks)",
0x52 => "1.1MByte (72 banks)",
0x53 => "1.2MByte (80 banks)",
0x54 => "1.5MByte (96 banks)",
_ => panic!("Unknown ROM Size")
}
}
pub fn ram_size(byte: u8) -> &'static str {
match byte {
0x00 => "None",
0x01 => "2 KBytes",
0x02 => "8 Kbytes",
0x03 => "32 KBytes (4 banks of 8KBytes each)",
0x04 => "128 KBytes (16 banks of 8KBytes each)",
0x05 => "64 KBytes (8 banks of 8KBytes each)",
_ => panic!("Unknown RAM Size")
}
}
| Addr | identifier_name |
mem_map.rs | const BOOT_ROM_START: u16 = 0x0000;
const BOOT_ROM_END: u16 = 0x00FF;
const CART_ROM_START: u16 = 0x0000;
const CART_ROM_END: u16 = 0x7FFF;
const CART_ENTRY_POINT: u16 = 0x0100;
const CART_HEADER_START: u16 = 0x0100;
const CART_HEADER_END: u16 = 0x014F;
const CART_FIXED_START: u16 = 0x0150;
const CART_FIXED_END: u16 = 0x3FFF;
const CART_SWITCH_START: u16 = 0x4000;
const CART_SWITCH_END: u16 = 0x7FFF;
const VIDEO_RAM_START: u16 = 0x8000;
const VIDEO_RAM_END: u16 = 0x9FFF;
const SOUND_REG_START: u16 = 0xFF10;
const SOUND_REG_END: u16 = 0xFF3F;
// http://gbdev.gg8.se/wiki/articles/Video_Display
const LCD_CONTROL_REGISTER: u16 = 0xFF40; // R/W
const LCD_STATUS_REGISTER: u16 = 0xFF41; // R/W
const SCROLL_Y: u16 = 0xFF42; // R/W
const SCROLL_X: u16 = 0xFF43; // R/W
const LCD_LY: u16 = 0xFF44; // R
const LCD_LYC: u16 = 0xFF45; // R/W
const LCD_WY: u16 = 0xFF4A; // R/W
const LCD_WX: u16 = 0xFF4B; // R/W
const BG_PALETTE_DATA: u16 = 0xFF47; // R/W
const OBJECT_PALETTE_0: u16 = 0xFF48; // R/W
const OBJECT_PALETTE_1: u16 = 0xFF49; // R/W
const HIGH_RAM_START: u16 = 0xFF80;
const HIGH_RAM_END: u16 = 0xFFFE;
pub fn map_addr(addr: u16) -> Addr {
match addr {
BOOT_ROM_START...BOOT_ROM_END => Addr::BootRom(addr - BOOT_ROM_START),
CART_HEADER_START...CART_HEADER_END => Addr::CartHeader(addr - CART_ROM_START),
CART_FIXED_START...CART_FIXED_END => Addr::CartFixed(addr - CART_ROM_START),
CART_SWITCH_START...CART_SWITCH_END => Addr::CartSwitch(addr - CART_ROM_START),
VIDEO_RAM_START...VIDEO_RAM_END => Addr::VideoRam(addr - VIDEO_RAM_START),
SOUND_REG_START...SOUND_REG_END => Addr::SoundRegister(addr - SOUND_REG_START),
HIGH_RAM_START...HIGH_RAM_END => Addr::HighRam(addr - HIGH_RAM_START),
_ => panic!("Unrecognised physical address: {:#x}", addr),
}
}
pub enum Addr {
BootRom(u16),
CartHeader(u16),
CartFixed(u16),
CartSwitch(u16),
VideoRam(u16),
SoundRegister(u16),
HighRam(u16),
}
pub fn cartridge_type(byte: u8) -> &'static str {
match byte {
0x00 => "ROM ONLY",
0x01 => "MBC1",
0x02 => "MBC1+RAM",
0x03 => "MBC1+RAM+BATTERY",
0x05 => "MBC2",
0x06 => "MBC2+BATTERY",
0x08 => "ROM+RAM",
0x09 => "ROM+RAM+BATTERY",
0x0B => "MMM01",
0x0C => "MMM01+RAM",
0x0D => "MMM01+RAM+BATTERY",
0x0F => "MBC3+TIMER+BATTERY",
0x10 => "MBC3+TIMER+RAM+BATTERY",
0x11 => "MBC3",
0x12 => "MBC3+RAM",
0x13 => "MBC3+RAM+BATTERY",
0x15 => "MBC4",
0x16 => "MBC4+RAM",
0x17 => "MBC4+RAM+BATTERY",
0x19 => "MBC5",
0x1A => "MBC5+RAM",
0x1B => "MBC5+RAM+BATTERY",
0x1C => "MBC5+RUMBLE",
0x1D => "MBC5+RUMBLE+RAM",
0x1E => "MBC5+RUMBLE+RAM+BATTERY",
0x20 => "MBC6",
0x22 => "MBC7+SENSOR+RUMBLE+RAM+BATTERY",
0xFC => "POCKET CAMERA",
0xFD => "BANDAI TAMA5",
0xFE => "HuC3", |
pub fn rom_size(byte: u8) -> &'static str {
match byte {
0x00 => "32KByte (no ROM banking)",
0x01 => "64KByte (4 banks)",
0x02 => "128KByte (8 banks)",
0x03 => "256KByte (16 banks)",
0x04 => "512KByte (32 banks)",
0x05 => "1MByte (64 banks)",
0x06 => "2MByte (128 banks)",
0x07 => "4MByte (256 banks)",
0x52 => "1.1MByte (72 banks)",
0x53 => "1.2MByte (80 banks)",
0x54 => "1.5MByte (96 banks)",
_ => panic!("Unknown ROM Size")
}
}
pub fn ram_size(byte: u8) -> &'static str {
match byte {
0x00 => "None",
0x01 => "2 KBytes",
0x02 => "8 Kbytes",
0x03 => "32 KBytes (4 banks of 8KBytes each)",
0x04 => "128 KBytes (16 banks of 8KBytes each)",
0x05 => "64 KBytes (8 banks of 8KBytes each)",
_ => panic!("Unknown RAM Size")
}
} | 0xFF => "HuC1+RAM+BATTERY",
_ => panic!("Unknown Cartridge Type"),
}
} | random_line_split |
load_more.py | def action_comment_load_more(context, action, entity_type, entity_id, last_id, parent_id, **args):
| try:
entity = IN.entitier.load_single(entity_type, int(entity_id))
if not entity:
return
output = Object()
db = IN.db
connection = db.connection
container_id = IN.commenter.get_container_id(entity)
# TODO: paging
# get total
total = 0
limit = 10
cursor = db.select({
'table' : 'entity.comment',
'columns' : ['count(id)'],
'where' : [
['container_id', container_id],
['id', '<', int(last_id)], # load previous
['parent_id', parent_id],
['status', 1],
],
}).execute()
if cursor.rowcount >= 0:
total = int(cursor.fetchone()[0])
more_id = '_'.join(('more-commens', entity_type, str(entity_id), str(parent_id)))
if total > 0:
cursor = db.select({
'table' : 'entity.comment',
'columns' : ['id'],
'where' : [
['container_id', container_id],
['id', '<', int(last_id)],
['parent_id', parent_id], # add main level comments only
['status', 1],
],
'order' : {'created' : 'DESC'},
'limit' : limit,
}).execute()
ids = []
last_id = 0
if cursor.rowcount >= 0:
for row in cursor:
ids.append(row['id'])
last_id = ids[-1] # last id
comments = IN.entitier.load_multiple('Comment', ids)
for id, comment in comments.items():
comment.weight = id # keep asc order
output.add(comment)
remaining = total - limit
if remaining > 0 and last_id > 0:
output.add('TextDiv', {
'id' : more_id,
'value' : str(remaining) + ' more comments',
'css' : ['ajax i-text-center i-text-danger pointer'],
'attributes' : {
'data-href' : ''.join(('/comment/more/!Content/', str(entity_id), '/', str(last_id), '/', str(parent_id)))
},
'weight' : -1,
})
#if not output:
#output.add(type = 'TextDiv', data = {})
output = {more_id : output}
context.response = In.core.response.PartialResponse(output = output)
except:
IN.logger.debug() | identifier_body | |
load_more.py | def action_comment_load_more(context, action, entity_type, entity_id, last_id, parent_id, **args):
try:
entity = IN.entitier.load_single(entity_type, int(entity_id))
if not entity:
return
output = Object()
db = IN.db
connection = db.connection
container_id = IN.commenter.get_container_id(entity)
# TODO: paging
# get total
total = 0
limit = 10
cursor = db.select({
'table' : 'entity.comment',
'columns' : ['count(id)'],
'where' : [
['container_id', container_id],
['id', '<', int(last_id)], # load previous
['parent_id', parent_id],
['status', 1],
],
}).execute()
if cursor.rowcount >= 0:
total = int(cursor.fetchone()[0])
more_id = '_'.join(('more-commens', entity_type, str(entity_id), str(parent_id)))
if total > 0:
|
#if not output:
#output.add(type = 'TextDiv', data = {})
output = {more_id : output}
context.response = In.core.response.PartialResponse(output = output)
except:
IN.logger.debug()
| cursor = db.select({
'table' : 'entity.comment',
'columns' : ['id'],
'where' : [
['container_id', container_id],
['id', '<', int(last_id)],
['parent_id', parent_id], # add main level comments only
['status', 1],
],
'order' : {'created' : 'DESC'},
'limit' : limit,
}).execute()
ids = []
last_id = 0
if cursor.rowcount >= 0:
for row in cursor:
ids.append(row['id'])
last_id = ids[-1] # last id
comments = IN.entitier.load_multiple('Comment', ids)
for id, comment in comments.items():
comment.weight = id # keep asc order
output.add(comment)
remaining = total - limit
if remaining > 0 and last_id > 0:
output.add('TextDiv', {
'id' : more_id,
'value' : str(remaining) + ' more comments',
'css' : ['ajax i-text-center i-text-danger pointer'],
'attributes' : {
'data-href' : ''.join(('/comment/more/!Content/', str(entity_id), '/', str(last_id), '/', str(parent_id)))
},
'weight' : -1,
}) | conditional_block |
load_more.py | def | (context, action, entity_type, entity_id, last_id, parent_id, **args):
try:
entity = IN.entitier.load_single(entity_type, int(entity_id))
if not entity:
return
output = Object()
db = IN.db
connection = db.connection
container_id = IN.commenter.get_container_id(entity)
# TODO: paging
# get total
total = 0
limit = 10
cursor = db.select({
'table' : 'entity.comment',
'columns' : ['count(id)'],
'where' : [
['container_id', container_id],
['id', '<', int(last_id)], # load previous
['parent_id', parent_id],
['status', 1],
],
}).execute()
if cursor.rowcount >= 0:
total = int(cursor.fetchone()[0])
more_id = '_'.join(('more-commens', entity_type, str(entity_id), str(parent_id)))
if total > 0:
cursor = db.select({
'table' : 'entity.comment',
'columns' : ['id'],
'where' : [
['container_id', container_id],
['id', '<', int(last_id)],
['parent_id', parent_id], # add main level comments only
['status', 1],
],
'order' : {'created' : 'DESC'},
'limit' : limit,
}).execute()
ids = []
last_id = 0
if cursor.rowcount >= 0:
for row in cursor:
ids.append(row['id'])
last_id = ids[-1] # last id
comments = IN.entitier.load_multiple('Comment', ids)
for id, comment in comments.items():
comment.weight = id # keep asc order
output.add(comment)
remaining = total - limit
if remaining > 0 and last_id > 0:
output.add('TextDiv', {
'id' : more_id,
'value' : str(remaining) + ' more comments',
'css' : ['ajax i-text-center i-text-danger pointer'],
'attributes' : {
'data-href' : ''.join(('/comment/more/!Content/', str(entity_id), '/', str(last_id), '/', str(parent_id)))
},
'weight' : -1,
})
#if not output:
#output.add(type = 'TextDiv', data = {})
output = {more_id : output}
context.response = In.core.response.PartialResponse(output = output)
except:
IN.logger.debug()
| action_comment_load_more | identifier_name |
load_more.py | def action_comment_load_more(context, action, entity_type, entity_id, last_id, parent_id, **args):
try:
entity = IN.entitier.load_single(entity_type, int(entity_id))
if not entity:
return
output = Object()
db = IN.db
connection = db.connection
container_id = IN.commenter.get_container_id(entity)
# TODO: paging
# get total
total = 0
limit = 10
cursor = db.select({
'table' : 'entity.comment',
'columns' : ['count(id)'],
'where' : [
['container_id', container_id],
['id', '<', int(last_id)], # load previous
['parent_id', parent_id],
['status', 1],
],
}).execute()
if cursor.rowcount >= 0:
total = int(cursor.fetchone()[0])
more_id = '_'.join(('more-commens', entity_type, str(entity_id), str(parent_id)))
if total > 0:
cursor = db.select({
'table' : 'entity.comment',
'columns' : ['id'],
'where' : [
['container_id', container_id],
['id', '<', int(last_id)],
['parent_id', parent_id], # add main level comments only
['status', 1],
],
'order' : {'created' : 'DESC'},
'limit' : limit,
}).execute()
ids = []
last_id = 0
if cursor.rowcount >= 0:
for row in cursor:
ids.append(row['id'])
last_id = ids[-1] # last id
comments = IN.entitier.load_multiple('Comment', ids)
for id, comment in comments.items():
comment.weight = id # keep asc order
output.add(comment)
remaining = total - limit
if remaining > 0 and last_id > 0:
output.add('TextDiv', {
'id' : more_id,
'value' : str(remaining) + ' more comments',
'css' : ['ajax i-text-center i-text-danger pointer'],
'attributes' : { | })
#if not output:
#output.add(type = 'TextDiv', data = {})
output = {more_id : output}
context.response = In.core.response.PartialResponse(output = output)
except:
IN.logger.debug() | 'data-href' : ''.join(('/comment/more/!Content/', str(entity_id), '/', str(last_id), '/', str(parent_id)))
},
'weight' : -1, | random_line_split |
ent.rs | use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize)]
pub struct PutRequest {
pub blobs: Vec<Vec<u8>>,
}
#[derive(Serialize, Deserialize)]
pub struct GetRequest {
pub items: Vec<GetItem>,
}
#[derive(Serialize, Deserialize)]
pub struct GetItem {
pub root: String,
// pub path: Vec<Selector>,
}
#[derive(Serialize, Deserialize)]
pub struct GetResponse {
pub items: HashMap<String, String>,
}
pub const API_URL_LOCALHOST: &str = "http://127.0.0.1:8088";
pub const API_URL_REMOTE: &str = "https://multiverse-312721.nw.r.appspot.com";
pub struct | {
pub api_url: String,
}
impl EntClient {
pub async fn upload_blob(&self, content: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
let req = PutRequest {
blobs: vec![content.to_vec()],
};
self.upload_blobs(&req).await?;
Ok(())
}
pub async fn upload_blobs(&self, req: &PutRequest) -> Result<(), Box<dyn std::error::Error>> {
let req_json = serde_json::to_string(&req)?;
reqwasm::http::Request::post(&format!("{}/api/v1/blobs/put", self.api_url))
.body(req_json)
.send()
.await
.map(|res| ())
.map_err(|e| e.into())
}
pub async fn get_blobs(
&self,
req: &GetRequest,
) -> Result<GetResponse, Box<dyn std::error::Error>> {
let req_json = serde_json::to_string(&req)?;
let res = reqwasm::http::Request::post(&format!("{}/api/v1/blobs/get", self.api_url))
.body(req_json)
.send()
.await?;
let res_json = res.json().await?;
Ok(res_json)
}
}
| EntClient | identifier_name |
ent.rs | use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize)]
pub struct PutRequest {
pub blobs: Vec<Vec<u8>>,
}
#[derive(Serialize, Deserialize)]
pub struct GetRequest {
pub items: Vec<GetItem>,
}
#[derive(Serialize, Deserialize)]
pub struct GetItem {
pub root: String,
// pub path: Vec<Selector>,
}
#[derive(Serialize, Deserialize)]
pub struct GetResponse {
pub items: HashMap<String, String>,
}
pub const API_URL_LOCALHOST: &str = "http://127.0.0.1:8088";
pub const API_URL_REMOTE: &str = "https://multiverse-312721.nw.r.appspot.com";
pub struct EntClient {
pub api_url: String,
}
impl EntClient {
pub async fn upload_blob(&self, content: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
let req = PutRequest {
blobs: vec![content.to_vec()],
}; | }
pub async fn upload_blobs(&self, req: &PutRequest) -> Result<(), Box<dyn std::error::Error>> {
let req_json = serde_json::to_string(&req)?;
reqwasm::http::Request::post(&format!("{}/api/v1/blobs/put", self.api_url))
.body(req_json)
.send()
.await
.map(|res| ())
.map_err(|e| e.into())
}
pub async fn get_blobs(
&self,
req: &GetRequest,
) -> Result<GetResponse, Box<dyn std::error::Error>> {
let req_json = serde_json::to_string(&req)?;
let res = reqwasm::http::Request::post(&format!("{}/api/v1/blobs/get", self.api_url))
.body(req_json)
.send()
.await?;
let res_json = res.json().await?;
Ok(res_json)
}
} | self.upload_blobs(&req).await?;
Ok(()) | random_line_split |
file_path_generator.py | # Copyright 2018-present Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
import os
from artificialproject.field_generators import (
GenerationFailedException,
StringGenerator,
)
from artificialproject.random import weighted_choice
class FilePathGenerator:
BUILD_FILE_NAME = "BUCK"
def __init__(self):
self._component_generator = StringGenerator()
self._file_samples = collections.defaultdict(
lambda: collections.defaultdict(set)
)
self._file_samples_dirty = False
self._package_depths = collections.Counter()
self._file_depths_in_package = collections.Counter()
self._sizes_by_depth = collections.defaultdict(collections.Counter)
self._sizes_by_depth_in_package = collections.defaultdict(collections.Counter)
self._build_file_sizes = collections.Counter()
self._root = {}
self._package_paths = {}
self._available_directories = {}
self._last_package_path = None
self._last_package_remaining_targets = None
def analyze_project_data(self, project_data):
dir_entries = collections.defaultdict(set)
build_file_entries = collections.defaultdict(set)
for target_data in project_data.values():
base_path = target_data["buck.base_path"]
build_file_entries[base_path].add(target_data["name"])
components = self._split_path_into_components(base_path)
# TODO(jakubzika): Targets in the root of the repo are ignored
# because _generate_path does not handle depth == 0.
if components:
self._package_depths.update([len(components)])
for component in components:
self._component_generator.add_string_sample(component)
for i, name in enumerate(components):
prefix = components[:i]
dir_entries[tuple(prefix)].add(name)
for base_path, names in build_file_entries.items():
self._build_file_sizes.update([len(names)])
for path, entries in dir_entries.items():
self._sizes_by_depth[len(path)].update([len(entries)])
def add_package_file_sample(self, package_path, relative_path):
components = self._split_path_into_components(relative_path)
self._file_depths_in_package.update([len(components)])
for i, name in enumerate(components):
prefix = components[:i]
self._file_samples[package_path][tuple(prefix)].add(name)
self._file_samples_dirty = True
def generate_package_path(self):
if self._last_package_path is not None:
path = self._last_package_path
self._last_package_remaining_targets -= 1
if self._last_package_remaining_targets <= 0:
|
return path
depth = weighted_choice(self._package_depths)
path, parent_dir = self._generate_path(
"//", self._root, depth, self._sizes_by_depth, self._component_generator
)
directory = {self.BUILD_FILE_NAME.lower(): None}
parent_dir[os.path.basename(path).lower()] = directory
self._last_package_path = path
self._last_package_remaining_targets = (
weighted_choice(self._build_file_sizes) - 1
)
return path
def generate_path_in_package(
self, package_path, depth, component_generator, extension
):
if depth == 0:
return ""
if self._file_samples_dirty:
self._sizes_by_depth_in_package.clear()
for dir_entries in self._file_samples.values():
for path, entries in dir_entries.items():
self._sizes_by_depth_in_package[len(path)].update([len(entries)])
self._file_samples_dirty = False
root = self._root
components = self._split_path_into_components(package_path)
for component in components:
root = root[component.lower()]
path, parent_dir = self._generate_path(
package_path,
root,
depth,
self._sizes_by_depth_in_package,
component_generator,
extension,
)
parent_dir[os.path.basename(path).lower()] = None
return path
def register_path(self, path):
directory = self._root
existed = True
for component in self._split_path_into_components(path):
if component not in directory:
directory[component] = {}
existed = False
directory = directory[component]
if directory is None:
raise GenerationFailedException()
if existed:
raise GenerationFailedException()
def _split_path_into_components(self, path):
components = []
while path:
path, component = os.path.split(path)
components.append(component)
return components[::-1]
def _generate_path(
self,
package_key,
root,
depth,
sizes_by_depth,
component_generator,
extension=None,
):
assert depth >= 1
parent_path, parent_dir = self._generate_parent(
package_key, root, depth - 1, sizes_by_depth, component_generator
)
name = self._generate_name(parent_dir, component_generator, extension)
return os.path.join(parent_path, name), parent_dir
def _generate_parent(
self, package_key, root, depth, sizes_by_depth, component_generator
):
if depth == 0:
return "", root
key = (package_key, depth)
value = self._available_directories.get(key)
if value is not None:
key_found = True
path, directory, size = value
else:
key_found = False
parent_path, parent_dir = self._generate_parent(
package_key, root, depth - 1, sizes_by_depth, component_generator
)
name = self._generate_name(parent_dir, component_generator)
path = os.path.join(parent_path, name)
directory = {}
parent_dir[name.lower()] = directory
size = weighted_choice(sizes_by_depth[depth])
size -= 1
if size > 0:
self._available_directories[key] = (path, directory, size)
elif key_found:
del self._available_directories[key]
return path, directory
def _generate_name(self, directory, generator, extension=None):
for i in range(1000):
name = generator.generate_string()
if extension is not None:
name += extension
if (
name.lower() not in directory
and name.lower() != self.BUILD_FILE_NAME.lower()
):
return name
raise GenerationFailedException()
| self._last_package_path = None | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.