text
stringlengths
2
1.04M
meta
dict
// This may look like C code, but it's really -*- C++ -*- #ifndef STD_GRID_LAYOUT_IMPL2_H_ #define STD_GRID_LAYOUT_IMPL2_H_ #include <Wt/WGridLayout> #include "StdLayoutImpl.h" namespace Wt { class WApplication; class WLayout; class WStringStream; class StdGridLayoutImpl2 : public StdLayoutImpl { public: StdGridLayoutImpl2(WLayout *layout, Impl::Grid& grid); virtual ~StdGridLayoutImpl2(); virtual int minimumWidth() const; virtual int minimumHeight() const; virtual void updateAddItem(WLayoutItem *); virtual void updateRemoveItem(WLayoutItem *); virtual void update(WLayoutItem *); virtual DomElement *createDomElement(bool fitWidth, bool fitHeight, WApplication *app); virtual void updateDom(DomElement& parent); static bool useJavaScriptHeights(WApplication *app); virtual void setHint(const std::string& name, const std::string& value); // Does not really belong here, but who cares ? static const char* childrenResizeJS(); virtual bool itemResized(WLayoutItem *item); virtual bool parentResized(); protected: virtual void containerAddWidgets(WContainerWidget *container); private: Impl::Grid& grid_; bool needAdjust_, needRemeasure_, needConfigUpdate_; std::vector<WLayoutItem *> addedItems_; std::vector<std::string> removedItems_; int nextRowWithItem(int row, int c) const; int nextColumnWithItem(int row, int col) const; bool hasItem(int row, int col) const; int minimumHeightForRow(int row) const; int minimumWidthForColumn(int column) const; static int pixelSize(const WLength& size); void streamConfig(WStringStream& js, const std::vector<Impl::Grid::Section>& sections, bool rows, WApplication *app); void streamConfig(WStringStream& js, WApplication *app); DomElement *createElement(WLayoutItem *item, WApplication *app); }; } #endif // STD_GRID_LAYOUT_IMPL2_H_
{ "content_hash": "8c6e233d2885c96fef6fb307d38e6d41", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 74, "avg_line_length": 28.515151515151516, "alnum_prop": 0.7401700318809776, "repo_name": "sanathkumarv/RestAPIWt", "id": "4eabcc529e0c5b2c49971a0afe832c5b17cce94e", "size": "1987", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "tools/wt-3.3.5-rc1/src/Wt/StdGridLayoutImpl2.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "134" }, { "name": "C++", "bytes": "154043" }, { "name": "CSS", "bytes": "59649" }, { "name": "HTML", "bytes": "2674" }, { "name": "Makefile", "bytes": "6608" }, { "name": "Shell", "bytes": "634" } ], "symlink_target": "" }
module Aladin class Book < OpenStruct def initialize(hash = {}) super(nil) hash.each do |key, value| send("#{key.to_s.underscore}=", value) end end end end
{ "content_hash": "8f731034ae523be60a9ce80a65f6bfdc", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 46, "avg_line_length": 19.3, "alnum_prop": 0.5751295336787565, "repo_name": "aproxacs/aladin-books", "id": "f2fa556ca69d995f70c1e3956581a5f2aa1fd87f", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/aladin/book.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "8779" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- Copyright 2014 Karlsruhe Institute of Technology. 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. --> <html> <head> <title>REST-Audit</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p>Service implementation of the KIT Data Manager Audit REST service.</p> </body> </html>
{ "content_hash": "6245d2965a3ca9ed007596d12db53ffd", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 77, "avg_line_length": 34.15384615384615, "alnum_prop": 0.7195945945945946, "repo_name": "kit-data-manager/base", "id": "d1bf6a04f0e84a73aacb2d91ed4a611b0a83ceae", "size": "888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MetaDataManagement/REST-Audit/src/main/java/edu/kit/dama/rest/audit/services/impl/package.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "402" }, { "name": "CSS", "bytes": "504470" }, { "name": "HTML", "bytes": "29793" }, { "name": "Java", "bytes": "5770625" }, { "name": "JavaScript", "bytes": "19166" }, { "name": "PLpgSQL", "bytes": "189351" }, { "name": "Shell", "bytes": "7423" }, { "name": "TSQL", "bytes": "14486" } ], "symlink_target": "" }
import { Component } from 'react'; import logoPaths from '../utils/logoPaths'; class Logo extends Component { state = { logoNumber: 0, }; componentDidMount() { this.animateIcon(); } animateIcon = () => { setInterval(() => { this.setState(({ logoNumber }) => ({ logoNumber: logoNumber === logoPaths.length - 1 ? 0 : logoNumber + 1, })); }, 400); }; renderLogo = () => logoPaths[this.state.logoNumber]; render() { return this.renderLogo(); } } export default Logo;
{ "content_hash": "4030fbc56d4c963b4ef4ca06dac0e9b7", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 77, "avg_line_length": 18.20689655172414, "alnum_prop": 0.5795454545454546, "repo_name": "MathMesquita/conf", "id": "9b1a7cbd79436980e3f75acc069c00cc58cfda36", "size": "528", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/Logo.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "5271" }, { "name": "JavaScript", "bytes": "91745" } ], "symlink_target": "" }
<?php // Composer autoloading if( file_exists( 'vendor/autoload.php' ) ) { include 'vendor/autoload.php'; } function __autoload( $pClassName ) { require_once( 'src/' . str_replace( "\\", "/", $pClassName . '.php' ) ); } //$autoLoader = new \Aura\Autoload\Loader; //$autoLoader->register(); //$autoLoader->addPrefix( 'Scraper', 'src/Scraper' );
{ "content_hash": "734cdb9997c72f80ca99c146f1a8cbbe", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 76, "avg_line_length": 22.1875, "alnum_prop": 0.6281690140845071, "repo_name": "fraserreed/meme-puush", "id": "574a8957dc1e804d844deaf178ab4eba64538084", "size": "355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "init_autoloader.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "78455" } ], "symlink_target": "" }
This application makes use of the following third party libraries: ## JSQMessagesViewController MIT License Copyright (c) 2013-present Jesse Squires http://www.jessesquires.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## JSQSystemSoundPlayer MIT License Copyright (c) 2013 Jesse Squires http://www.hexedbits.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## SVProgressHUD Copyright (c) 2011-2016 Sam Vermette, Tobias Tiemerding and contributors. 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. A different license may apply to other resources included in this package, including Freepik Icons. Please consult their respective headers for the terms of their individual licenses. Generated by CocoaPods - https://cocoapods.org
{ "content_hash": "1add3f7dbcca5688f919a134c61962fc", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 111, "avg_line_length": 46.0125, "alnum_prop": 0.8049443086117902, "repo_name": "seansguo/SheepChat", "id": "b58f18c506d7a387db876ef8e1e9c9b3a672576a", "size": "3700", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pods/Target Support Files/Pods-SheepChat/Pods-SheepChat-acknowledgements.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "493" }, { "name": "Swift", "bytes": "86048" } ], "symlink_target": "" }
call git reset --soft %1 SHIFT call git commit -m "%*"
{ "content_hash": "9e3a034b7bc568278741f8dde03966f0", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 24, "avg_line_length": 18.666666666666668, "alnum_prop": 0.6428571428571429, "repo_name": "RyanCavanaugh/scripts", "id": "fc59c0feb0b7b51ccafb058bdb752e2259d50601", "size": "56", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "squash.cmd", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3060" }, { "name": "PowerShell", "bytes": "831" }, { "name": "Shell", "bytes": "675" } ], "symlink_target": "" }
// 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. using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Apache.Arrow.Ipc { /// <summary> /// Represents a reader that can read Arrow streams. /// </summary> public class ArrowStreamReader : IArrowReader, IDisposable { private protected readonly ArrowReaderImplementation _implementation; public Schema Schema => _implementation.Schema; public ArrowStreamReader(Stream stream) : this(stream, leaveOpen: false) { } public ArrowStreamReader(Stream stream, bool leaveOpen) { if (stream == null) throw new ArgumentNullException(nameof(stream)); _implementation = new ArrowStreamReaderImplementation(stream, leaveOpen); } public ArrowStreamReader(ReadOnlyMemory<byte> buffer) { _implementation = new ArrowMemoryReaderImplementation(buffer); } private protected ArrowStreamReader(ArrowReaderImplementation implementation) { _implementation = implementation; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _implementation.Dispose(); } } public Task<RecordBatch> ReadNextRecordBatchAsync(CancellationToken cancellationToken = default) { return _implementation.ReadNextRecordBatchAsync(cancellationToken); } public RecordBatch ReadNextRecordBatch() { return _implementation.ReadNextRecordBatch(); } } }
{ "content_hash": "6b1028842fe51c3fd3f23afcfb1d7769", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 104, "avg_line_length": 32.10126582278481, "alnum_prop": 0.6597003154574133, "repo_name": "itaiin/arrow", "id": "a399056d14adffb792096fa506299a0bf62c9b8e", "size": "2538", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "csharp/src/Apache.Arrow/Ipc/ArrowStreamReader.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "73655" }, { "name": "Awk", "bytes": "3683" }, { "name": "Batchfile", "bytes": "31917" }, { "name": "C", "bytes": "328104" }, { "name": "C#", "bytes": "399342" }, { "name": "C++", "bytes": "7227843" }, { "name": "CMake", "bytes": "401580" }, { "name": "CSS", "bytes": "3946" }, { "name": "Dockerfile", "bytes": "42193" }, { "name": "FreeMarker", "bytes": "2274" }, { "name": "Go", "bytes": "364102" }, { "name": "HTML", "bytes": "23047" }, { "name": "Java", "bytes": "2296962" }, { "name": "JavaScript", "bytes": "84850" }, { "name": "Lua", "bytes": "8741" }, { "name": "M4", "bytes": "8713" }, { "name": "MATLAB", "bytes": "9068" }, { "name": "Makefile", "bytes": "44853" }, { "name": "Meson", "bytes": "36931" }, { "name": "Objective-C", "bytes": "7559" }, { "name": "PLpgSQL", "bytes": "56995" }, { "name": "Perl", "bytes": "3799" }, { "name": "Python", "bytes": "1548321" }, { "name": "R", "bytes": "155922" }, { "name": "Ruby", "bytes": "679269" }, { "name": "Rust", "bytes": "1592353" }, { "name": "Shell", "bytes": "251833" }, { "name": "Thrift", "bytes": "137291" }, { "name": "TypeScript", "bytes": "932690" } ], "symlink_target": "" }
package com.sicdlib.service.pythonService.imple; import com.sicdlib.dao.pyhtonDAO.IBBSChinaPostDAO; import com.sicdlib.dto.entity.BbsChinaPostEntity; import com.sicdlib.service.pythonService.IBBSChinaPostService; import com.sicdlib.util.UUIDUtil.UUIDUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.List; /** * Created by init on 2017/5/26. */ @Service("bbsChinaPostService") public class BBSChinaPostService implements IBBSChinaPostService{ @Autowired @Qualifier("bbsChinaPostDAO") private IBBSChinaPostDAO bbsChinaPostDAO; @Override public boolean saveBBSChinaPost(BbsChinaPostEntity bbsChinaPost) { if(bbsChinaPost.getId() == null){ String uuid = UUIDUtil.getUUID(); bbsChinaPost.setId(uuid); } return bbsChinaPostDAO.saveBBSChinaPost(bbsChinaPost); } @Override public BbsChinaPostEntity getBbsChinaPost(String id) { return bbsChinaPostDAO.getBbsChinaPost(id); } @Override public List<BbsChinaPostEntity> getbbsChinaPost(String authorID) { return bbsChinaPostDAO.getbbsChinaPost(authorID); } @Override public BbsChinaPostEntity getBbsChinaPostInfoByID(String postID) { return bbsChinaPostDAO.getBbsChinaPostInfoByID(postID); } }
{ "content_hash": "b850dbf71e9e9a08ee3341e7822025b1", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 70, "avg_line_length": 30.891304347826086, "alnum_prop": 0.7551020408163265, "repo_name": "V119/spidersManager", "id": "b4e9debc2497754f4a72c2cfbccc794b0aea8133", "size": "1421", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/sicdlib/service/pythonService/imple/BBSChinaPostService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "842465" }, { "name": "HTML", "bytes": "899634" }, { "name": "Java", "bytes": "2224968" }, { "name": "JavaScript", "bytes": "2213968" }, { "name": "SQLPL", "bytes": "857" } ], "symlink_target": "" }
<?php session_start(); include "db_connect.php"; $db = PDOFactory::getConnection(); $box_token = $_GET["box_token"]; $box_status = $db->query("SELECT room_name, box_token, room_active, room_creator, room_play_type, room_submission_rights, user_pseudo, stat_visitors, stat_followers, user_pp, room_protection, room_description FROM rooms r JOIN user u ON r.room_creator = u.user_token JOIN user_stats us ON r.room_creator = us.user_token WHERE box_token = '$box_token'")->fetch(); if(isset($_SESSION["username"]) && $box_status["user_pseudo"] != $_SESSION["username"]){ $userFollow = $db->query("SELECT * FROM user_follow uf WHERE user_following = '$_SESSION[token]' AND user_followed = '$box_status[room_creator]'")->rowCount(); $box_status["following_creator"] = $userFollow; } echo json_encode($box_status); ?>
{ "content_hash": "c2ff9327fbe417910d452c4c2c92c848", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 208, "avg_line_length": 39.04545454545455, "alnum_prop": 0.6682188591385332, "repo_name": "AngelZatch/Berrybox", "id": "45b4cb24153dfd1f5fe258879535d281cec8d22f", "size": "859", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "functions/get_box_details.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1270" }, { "name": "CSS", "bytes": "15115" }, { "name": "HTML", "bytes": "53" }, { "name": "JavaScript", "bytes": "104658" }, { "name": "PHP", "bytes": "203382" } ], "symlink_target": "" }
import random import math import subprocess import codecs import numbers import base64, StringIO ### maybe someday convert to cElementTree output rather than string concatenation # try: # import xml.etree.cElementTree as ElementTree # except ImportError: # import xml.etree.cElementTree as ElementTree # Special dependencies import PIL.Image # sudo apt-get install python-imaging # Cassius interdependencies import mathtools import utilities import color import containers try: import _svgview except ImportError: _svgview = None # these can be re-set by the user on a per-session basis defaults = { "width": 1000, "height": 1000, "background": True, } default_frameargs = { "leftmargin": 0.12, "rightmargin": 0.05, "topmargin": 0.05, "bottommargin": 0.08, "textscale": 1., "xlabel": None, "ylabel": None, "rightlabel": None, "toplabel": None, "xlabeloffset": 0.08, "ylabeloffset": -0.10, "rightlabeloffset": 0., "toplabeloffset": 0., "xlog": False, "ylog": False, "xticks": containers.Auto, "yticks": containers.Auto, "rightticks": containers.Auto, "topticks": containers.Auto, "show_topticklabels": containers.Auto, "show_rightticklabels": containers.Auto, "xmin": containers.Auto, "ymin": containers.Auto, "xmax": containers.Auto, "ymax": containers.Auto, "xmargin": 0.1, "ymargin": 0.1, } # represents an SVG document filled by drawing commands class SVG: def __init__(self, width, height, background): self.width, self.height = width, height self.header = """<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg style="stroke-linejoin:miter; stroke:black; stroke-width:2.5; text-anchor:middle; fill:none" xmlns="http://www.w3.org/2000/svg" font-family="Helvetica, Arial, FreeSans, Sans, sans, sans-serif" width="%(width)dpx" height="%(height)dpx" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 %(width)d %(height)d"> """ % vars() self.footer = "</svg>\n" self.names = {} self.defs = {} self.body = [] if background: self.body.append("""<rect id="background" x="0" y="0" width="%(width)g" height="%(height)g" stroke="none" fill="white" />""" % vars()) def uniquename(self, base): if base not in self.names: self.names[base] = 0 else: self.names[base] += 1 return "%s_%d" % (base, self.names[base]) def write(self, fileName): f = codecs.open(fileName, "w", "utf-8") f.write(self.header) if len(self.defs) > 0: f.write("<defs>\n") keys = self.defs.keys() keys.sort() # for readability for key in keys: f.write(self.defs[key]); f.write("\n") f.write("</defs>\n") f.write("<g id=\"whole_document\">\n") for line in self.body: f.write(line); f.write("\n") f.write("</g>\n") f.write(self.footer) def tostring(self): f = StringIO.StringIO() f.write(self.header) if len(self.defs) > 0: f.write("<defs>") for value in self.defs.values(): f.write(value) f.write("</defs>") for line in self.body: f.write(line) f.write(self.footer) return f.getvalue() # this is what the user calls def view(obj, **kwds): if _svgview is None: raise RuntimeError, "The '_svgview' extension module has not been compiled; use \"draw(object, fileName='...')\" instead." svg = kwds.get("svg", None) # actual drawing is done in internal subcommands try: subcommand = eval("_draw_%s" % obj.__class__.__name__) except NameError: raise NotImplementedError, "A '_draw_%s' function has not been implemented in backends.svg" % obj.__class__.__name__ if svg is None: # set the defaults (if not already overridden with explicit keyword arguments) for arg, value in defaults.items(): if arg not in kwds: kwds[arg] = value # the following are derived arguments svg = SVG(kwds["width"], kwds["height"], kwds["background"]) kwds["svg"] = svg kwds["x1"], kwds["y1"], kwds["x2"], kwds["y2"] = 0., 0., float(kwds["width"]), float(kwds["height"]) # run the command and view the SVG subcommand(obj, **kwds) _svgview.str(svg.tostring()) else: # not working on a new SVG; add to the existing one subcommand(obj, **kwds) # this is what the user calls def draw(obj, **kwds): svg = kwds.get("svg", None) # actual drawing is done in internal subcommands try: subcommand = eval("_draw_%s" % obj.__class__.__name__) except NameError: raise NotImplementedError, "A '_draw_%s' function has not been implemented in backends.svg" % obj.__class__.__name__ if svg is None: try: fileName = kwds["fileName"] except KeyError: raise TypeError, "The 'svgdraw.draw' function requires fileName='...'" # set the defaults (if not already overridden with explicit keyword arguments) for arg, value in defaults.items(): if arg not in kwds: kwds[arg] = value # the following are derived arguments svg = SVG(kwds["width"], kwds["height"], kwds["background"]) kwds["svg"] = svg kwds["x1"], kwds["y1"], kwds["x2"], kwds["y2"] = 0., 0., float(kwds["width"]), float(kwds["height"]) # run the command and write the SVG subcommand(obj, **kwds) svg.write(fileName) else: # not working on a new SVG; add to the existing one subcommand(obj, **kwds) # this draws a PDF by invoking inkscape on an intermediary SVG file def drawpdf(obj, fileName, tmpFileName="/tmp/tmp.svg", **kwds): kwds["fileName"] = tmpFileName draw(obj, **kwds) proc = subprocess.Popen(["inkscape", tmpFileName, "--export-pdf=" + fileName]) proc.wait() ###################################################### utilities def _svgopacity(obj): if isinstance(obj, color.AbstractColor): return obj.opacity else: return 1. def _svgcolor(obj): if obj is None: return "none" elif isinstance(obj, basestring): return obj else: return str(obj) def _svglinestyle(obj, linewidth=1.): if obj is None or obj == "solid": return "" elif obj == "dashed": return _svglinestyle((15.*linewidth, 15.*linewidth)) elif obj == "dotted": return _svglinestyle((3.*linewidth, 3.*linewidth)) elif isinstance(obj, (list, tuple)): allnumbers = True for i in obj: if not isinstance(i, numbers.Number): allnumbers = False break if allnumbers: return " ".join(map(str, obj)) else: return obj def _svglinewidth(obj): return obj*3. def _svgmarkersize(obj): return obj*7.5 def _transformX(x, wx1, wx2, xmin, xmax, xlog): if xlog: return wx1 + (math.log10(x) - math.log10(xmin))*(wx2 - wx1)/(math.log10(xmax) - math.log10(xmin)) else: return wx1 + (x - xmin)*(wx2 - wx1)/(xmax - xmin) def _transformY(y, wy1, wy2, ymin, ymax, ylog): if ylog: return wy2 - (math.log10(y) - math.log10(ymin))*(wy2 - wy1)/(math.log10(ymax) - math.log10(ymin)) else: return wy2 - (y - ymin)*(wy2 - wy1)/(ymax - ymin) ###################################################### draw_frame def _get_frameargs(obj, **kwds): output = obj._frameargs() try: subcommand = eval("_frameargs_prehook_%s" % obj.__class__.__name__) except NameError: subcommand = None if subcommand is not None: output = subcommand(obj, output, **kwds) # framearg precedence: # 1. draw(..., framearg=something) # 2. draw(obj(..., framearg=something)) # 3. default_frameargs[framearg] = something for i in default_frameargs: if i in kwds: output[i] = kwds[i] #1 else: if i in output: pass #2 (it's already in there) else: output[i] = default_frameargs[i] #3 if output["leftmargin"] is None: output["leftmargin"] = 0. if output["rightmargin"] is None: output["rightmargin"] = 0. if output["topmargin"] is None: output["topmargin"] = 0. if output["bottommargin"] is None: output["bottommargin"] = 0. if output["xmargin"] is None: output["xmargin"] = 0. if output["ymargin"] is None: output["ymargin"] = 0. if output["xmin"] is containers.Auto or output["ymin"] is containers.Auto or output["xmax"] is containers.Auto or output["ymax"] is containers.Auto: def goget(attrib, default): out = output.get(attrib, default) if isinstance(out, numbers.Number): return out else: return default xmin, ymin, xmax, ymax = obj.ranges(output["xlog"], output["ylog"]) xmargin = output["xmargin"]*(goget("xmax", xmax) - goget("xmin", xmin)) ymargin = output["ymargin"]*(goget("ymax", ymax) - goget("ymin", ymin)) xmin = xmin - xmargin xmax = xmax + xmargin ymin = ymin - ymargin ymax = ymax + ymargin if output["xmin"] is containers.Auto: output["xmin"] = xmin if output["ymin"] is containers.Auto: output["ymin"] = ymin if output["xmax"] is containers.Auto: output["xmax"] = xmax if output["ymax"] is containers.Auto: output["ymax"] = ymax if output["xticks"] is None: output["xticks"] = {} elif callable(output["xticks"]): output["xticks"] = output["xticks"](output["xmin"], output["xmax"]) elif output["xticks"] is containers.Auto: if output["xlog"]: output["xticks"] = utilities.tickmarks(logbase=10)(output["xmin"], output["xmax"]) else: output["xticks"] = utilities.tickmarks()(output["xmin"], output["xmax"]) elif callable(output["xticks"]): vals = output["xticks"](output["xmin"], output["xmax"]) output["xticks"] = dict(map(lambda x: (x, unumber(x)), vals)) elif isinstance(output["xticks"], (tuple, list)) and len(output["xticks"]) == 2 and callable(output["xticks"][0]) and callable(output["xticks"][1]): if output["xticks"][0].func_name == "timeticks" and output["xticks"][1].func_name == "timeminiticks": major = output["xticks"][0](output["xmin"], output["xmax"]) minor = output["xticks"][1](output["xmin"], output["xmax"]) else: major = dict(map(lambda x: (x, unumber(x)), output["xticks"][0](output["xmin"], output["xmax"]))) minor = dict(map(lambda x: (x, None), output["xticks"][1](output["xmin"], output["xmax"]))) minor.update(major) output["xticks"] = minor if output["yticks"] is None: output["yticks"] = {} elif callable(output["yticks"]): output["yticks"] = output["yticks"](output["ymin"], output["ymax"]) elif output["yticks"] is containers.Auto: if output["ylog"]: output["yticks"] = utilities.tickmarks(logbase=10)(output["ymin"], output["ymax"]) else: output["yticks"] = utilities.tickmarks()(output["ymin"], output["ymax"]) elif callable(output["yticks"]): vals = output["yticks"](output["ymin"], output["ymax"]) output["yticks"] = dict(map(lambda x: (x, unumber(x)), vals)) elif isinstance(output["yticks"], (tuple, list)) and len(output["yticks"]) == 2 and callable(output["yticks"][0]) and callable(output["yticks"][1]): major = dict(map(lambda x: (x, unumber(x)), output["yticks"][0](output["ymin"], output["ymax"]))) minor = dict(map(lambda x: (x, None), output["yticks"][1](output["ymin"], output["ymax"]))) minor.update(major) output["yticks"] = minor if output["topticks"] is None: output["topticks"] = {} elif output["topticks"] is containers.Auto: output["topticks"] = output["xticks"] if output["show_topticklabels"] is containers.Auto: output["show_topticklabels"] = False else: if output["show_topticklabels"] is containers.Auto: output["show_topticklabels"] = True if output["rightticks"] is None: output["rightticks"] = {} elif output["rightticks"] is containers.Auto: output["rightticks"] = output["yticks"] if output["show_rightticklabels"] is containers.Auto: output["show_rightticklabels"] = False else: if output["show_rightticklabels"] is containers.Auto: output["show_rightticklabels"] = True try: subcommand = eval("_frameargs_posthook_%s" % obj.__class__.__name__) except NameError: subcommand = None if subcommand is not None: output = subcommand(obj, output, **kwds) return output def _get_window(**kwds): x1, y1, x2, y2, f = kwds["x1"], kwds["y1"], kwds["x2"], kwds["y2"], kwds["frameargs"] wx1, wx2 = x1 + f["leftmargin"]*(x2 - x1), x2 - f["rightmargin"]*(x2 - x1) wy1, wy2 = y1 + f["topmargin"]*(y2 - y1), y2 - f["bottommargin"]*(y2 - y1) return wx1, wy1, wx2, wy2 def _draw_frame(**kwds): svg, x1, y1, x2, y2 = kwds["svg"], kwds["x1"], kwds["y1"], kwds["x2"], kwds["y2"] f = kwds["frameargs"] wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 font_size = f["textscale"]*30. xmin, ymin, xmax, ymax = f["xmin"], f["ymin"], f["xmax"], f["ymax"] xlog, ylog = f["xlog"], f["ylog"] framename = svg.uniquename("frame") svg.body.append(u"""<g id="%(framename)s">""" % vars()) svg.body.append(u""" <rect id="%(framename)s_border" x="%(wx1)g" y="%(wy1)g" width="%(windowwidth)g" height="%(windowheight)g" />""" % vars()) # bottom-axis label and ticks if f["xlabel"] is not None: tx, ty, text = wx1 + (wx2 - wx1)/2., wy2 + f["xlabeloffset"]*windowheight, f["xlabel"] svg.body.append(u""" <text id="%(framename)s_bottomlabel" font-size="%(font_size)g" transform="translate(%(tx)g, %(ty)g)" text-anchor="middle" dominant-baseline="middle" stroke="none" fill="black">%(text)s</text>""" % vars()) svg.body.append(u""" <g id="%(framename)s_bottomticks">""" % vars()) tickend, minitickend, textmid = wy2 - 20., wy2 - 10., wy2 + 30. for x, label in f["xticks"].items(): hpos = _transformX(x, wx1, wx2, xmin, xmax, xlog) if label is not None: svg.body.append(u""" <path d="M %(hpos)g %(wy2)g L %(hpos)g %(tickend)g" />""" % vars()) svg.body.append(u""" <text font-size="%(font_size)g" transform="translate(%(hpos)g, %(textmid)g)" text-anchor="middle" dominant-baseline="middle" stroke="none" fill="black">%(label)s</text>""" % vars()) else: svg.body.append(u""" <path d="M %(hpos)g %(wy2)g L %(hpos)g %(minitickend)g" />""" % vars()) svg.body.append(u""" </g>""") # left-axis label and ticks if f["ylabel"] is not None: tx, ty, text = wx1 + f["ylabeloffset"]*windowwidth, wy1 + (wy2 - wy1)/2., f["ylabel"] svg.body.append(u""" <text id="%(framename)s_leftlabel" font-size="%(font_size)g" transform="translate(%(tx)g, %(ty)g) rotate(-90)" text-anchor="middle" dominant-baseline="middle" stroke="none" fill="black">%(text)s</text>""" % vars()) svg.body.append(u""" <g id="%(framename)s_leftticks">""" % vars()) tickend, minitickend, textmid = wx1 + 20., wx1 + 10., wx1 - 10. for y, label in f["yticks"].items(): vpos = _transformY(y, wy1, wy2, ymin, ymax, ylog) vpostext = vpos + 10. if label is not None: svg.body.append(u""" <path d="M %(wx1)g %(vpos)g L %(tickend)g %(vpos)g" />""" % vars()) svg.body.append(u""" <text font-size="%(font_size)g" transform="translate(%(textmid)g, %(vpostext)g)" text-anchor="end" dominant-baseline="middle" stroke="none" fill="black">%(label)s</text>""" % vars()) else: svg.body.append(u""" <path d="M %(wx1)g %(vpos)g L %(minitickend)g %(vpos)g" />""" % vars()) svg.body.append(u""" </g>""") # top-axis label and ticks if f["toplabel"] is not None: tx, ty, text = wx1 + (wx2 - wx1)/2., wy1 + f["toplabeloffset"]*windowheight, f["toplabel"] svg.body.append(u""" <text id="%(framename)s_toplabel" font-size="%(font_size)g" transform="translate(%(tx)g, %(ty)g)" text-anchor="middle" dominant-baseline="middle" stroke="none" fill="black">%(text)s</text>""" % vars()) svg.body.append(u""" <g id="%(framename)s_topticks">""" % vars()) tickend, minitickend, textmid = wy1 + 20., wy1 + 10., wy1 - 30. for x, label in f["topticks"].items(): hpos = _transformX(x, wx1, wx2, xmin, xmax, xlog) if label is not None: svg.body.append(u""" <path d="M %(hpos)g %(wy1)g L %(hpos)g %(tickend)g" />""" % vars()) if f["show_topticklabels"]: svg.body.append(u""" <text font-size="%(font_size)g" transform="translate(%(hpos)g, %(textmid)g)" text-anchor="middle" dominant-baseline="middle" stroke="none" fill="black">%(label)s</text>""" % vars()) else: svg.body.append(u""" <path d="M %(hpos)g %(wy1)g L %(hpos)g %(minitickend)g" />""" % vars()) svg.body.append(u""" </g>""") # right-axis label and ticks if f["rightlabel"] is not None: tx, ty, text = wx2 + f["rightlabeloffset"]*windowwidth, wy1 + (wy2 - wy1)/2., f["rightlabel"] svg.body.append(u""" <text id="%(framename)s_rightlabel" font-size="%(font_size)g" transform="translate(%(tx)g, %(ty)g) rotate(90)" text-anchor="middle" dominant-baseline="middle" stroke="none" fill="black">%(text)s</text>""" % vars()) svg.body.append(u""" <g id="%(framename)s_rightticks">""" % vars()) tickend, minitickend, textmid = wx2 - 20., wx2 - 10., wx2 + 10. for y, label in f["rightticks"].items(): vpos = _transformY(y, wy1, wy2, ymin, ymax, ylog) vpostext = vpos + 10. if label is not None: svg.body.append(u""" <path d="M %(wx2)g %(vpos)g L %(tickend)g %(vpos)g" />""" % vars()) if f["show_rightticklabels"]: svg.body.append(u""" <text font-size="%(font_size)g" transform="translate(%(textmid)g, %(vpostext)g)" text-anchor="start" dominant-baseline="middle" stroke="none" fill="black">%(label)s</text>""" % vars()) else: svg.body.append(u""" <path d="M %(wx2)g %(vpos)g L %(minitickend)g %(vpos)g" />""" % vars()) svg.body.append(u""" </g>""") svg.body.append(u"""</g>""") ###################################################### actions for particular classes def _draw_NoneType(obj, **kwds): ### debugging code # svg, x1, y1, x2, y2 = kwds["svg"], kwds["x1"], kwds["y1"], kwds["x2"], kwds["y2"] # width = x2 - x1 # height = y2 - y1 # color = rgbcolor(random.gauss(0.5, 0.3), random.gauss(0.5, 0.3), random.gauss(0.5, 0.3)) # svg.body.append(u"""<rect x="%(x1)g" y="%(y1)g" width="%(width)g" height="%(height)g" stroke="none" fill="%(color)s" />""" % vars()) pass def _draw_Layout(obj, **kwds): svg, x1, y1, x2, y2 = kwds["svg"], kwds["x1"], kwds["y1"], kwds["x2"], kwds["y2"] # TODO: possibly need to change the margins for different layouts # by passing down a multiplier? width = (x2 - x1)/float(obj.ncols) height = (y2 - y1)/float(obj.nrows) for i in xrange(obj.nrows): kwds["y1"], kwds["y2"] = (y1 + i*height), (y1 + (i+1)*height) for j in xrange(obj.ncols): kwds["x1"], kwds["x2"] = (x1 + j*width), (x1 + (j+1)*width) draw(obj[i,j], **kwds) def _draw_Overlay(obj, **kwds): svg, x1, y1, x2, y2 = kwds["svg"], kwds["x1"], kwds["y1"], kwds["x2"], kwds["y2"] drawframe = kwds.get("drawframe", True) def findframe(obj): if isinstance(obj, containers.Stack): obj._prepare() return findframe(obj._overlay) elif isinstance(obj, containers.Overlay): if "frame" in obj.__dict__ and obj.frame is not None: if obj.frame >= len(obj.plots): raise containers.ContainerException, "Overlay.frame points to a non-existent plot (%d <= %d)" % (obj.frame, len(obj.plots)) return findframe(obj.plots[obj.frame]) else: return _get_frameargs(obj, **kwds) else: return _get_frameargs(obj, **kwds) foundframe = findframe(obj) # to evaluate all Stacks if drawframe: kwds["frameargs"] = foundframe kwds["drawframe"] = False # for the contained objects # flatten any Overlay nesting and draw Legends _above_ the frame def recurse(plotsin, nonlegends, legends): for plot in plotsin: if isinstance(plot, containers.Stack): recurse(plot._overlay.plots, nonlegends, legends) elif isinstance(plot, containers.Overlay): recurse(plot.plots, nonlegends, legends) elif isinstance(plot, containers.Legend): legends.append(plot) else: nonlegends.append(plot) nonlegends = [] legends = [] recurse(obj.plots, nonlegends, legends) for plot in nonlegends: draw(plot, **kwds) if drawframe: _draw_frame(**kwds) for plot in legends: draw(plot, **kwds) def _draw_Stack(obj, **kwds): obj._prepare() draw(obj._overlay, **kwds) def _frameargs_prehook_Histogram(obj, output, **kwds): if "ymin" not in output or output["ymin"] is None or output["ymin"] is containers.Auto: if "ylog" not in output or not output["ylog"]: output["ymin"] = 0. if "xmargin" not in output: output["xmargin"] = 0. return output def _frameargs_prehook_HistogramAbstract(obj, output, **kwds): return _frameargs_prehook_Histogram(obj, output, **kwds) def _frameargs_prehook_HistogramNonUniform(obj, output, **kwds): return _frameargs_prehook_Histogram(obj, output, **kwds) def _frameargs_prehook_HistogramCategorical(obj, output, **kwds): return _frameargs_prehook_Histogram(obj, output, **kwds) def _draw_HistogramAbstract(obj, **kwds): _draw_Histogram(obj, **kwds) def _draw_Histogram(obj, **kwds): svg = kwds["svg"] if kwds.get("drawframe", True): kwds["frameargs"] = _get_frameargs(obj, **kwds) f = kwds["frameargs"] linewidth = _svglinewidth(obj.linewidth) linestyle = _svglinestyle(obj.linestyle, obj.linewidth) lineopacity = _svgopacity(obj.linecolor) linecolor = _svgcolor(obj.linecolor) fillopacity = _svgopacity(obj.fillcolor) fillcolor = _svgcolor(obj.fillcolor) wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 xmin, ymin, xmax, ymax, xlog, ylog = f["xmin"], f["ymin"], f["xmax"], f["ymax"], f["xlog"], f["ylog"] def t(x, y): return _transformX(x, wx1, wx2, xmin, xmax, xlog), _transformY(y, wy1, wy2, ymin, ymax, ylog) xepsilon = mathtools.epsilon * (xmax - xmin) yepsilon = mathtools.epsilon * (ymax - ymin) bins = obj.binedges() gap = obj.gap*(_transformX(xmax, wx1, wx2, xmin, xmax, xlog) - _transformX(xmin, wx1, wx2, xmin, xmax, xlog))/len(obj.bins) line = [] # in data coordinates pathdata = [] # in SVG coordinates with gaps for (binlow, binhigh), value in zip(bins, obj.values): if len(line) == 0: line.append((binlow, 0.)) pathdata.append("M %g %g" % t(*line[-1])) if gap > mathtools.epsilon: line.append((binlow, 0.)) x, y = t(*line[-1]) x += gap/2. pathdata.append("L %g %g" % (x, y)) elif abs(line[-1][0] - binlow) > xepsilon or gap > mathtools.epsilon: line.append((line[-1][0], 0.)) line.append((binlow, 0.)) if gap > mathtools.epsilon: x, y = t(*line[-2]) x -= gap/2. pathdata.append("L %g %g" % (x, y)) x, y = t(*line[-1]) x += gap/2. pathdata.append("L %g %g" % (x, y)) else: pathdata.append("L %g %g" % t(*line[-2])) pathdata.append("L %g %g" % t(*line[-1])) line.append((binlow, value)) line.append((binhigh, value)) if gap > mathtools.epsilon: x, y = t(*line[-2]) x += gap/2. pathdata.append("L %g %g" % (x, y)) x, y = t(*line[-1]) x -= gap/2. pathdata.append("L %g %g" % (x, y)) else: pathdata.append("L %g %g" % t(*line[-2])) pathdata.append("L %g %g" % t(*line[-1])) if gap > mathtools.epsilon: line.append((line[-1][0], 0.)) x, y = t(*line[-1]) x -= gap/2. pathdata.append("L %g %g" % (x, y)) line.append((line[-1][0], 0.)) pathdata.append("L %g %g" % t(*line[-1])) pathdata = " ".join(pathdata) plotname = svg.uniquename(obj.__class__.__name__) plotclipname = "%s_clip" % plotname svg.defs[plotclipname] = u""" <clipPath id="%(plotclipname)s"> <rect x="%(wx1)g" y="%(wy1)g" width="%(windowwidth)g" height="%(windowheight)g" /> </clipPath>""" % vars() h = "#" svg.body.append(u"""<g id="%(plotname)s" clip-path="url(%(h)s%(plotclipname)s)">""" % vars()) svg.body.append(u""" <path d="%(pathdata)s" stroke-width="%(linewidth)g" stroke-dasharray="%(linestyle)s" stroke="%(linecolor)s" stroke-opacity="%(lineopacity)g" fill="%(fillcolor)s" fill-opacity="%(fillopacity)g" />""" % vars()) svg.body.append(u"""</g>""") if kwds.get("drawframe", True): _draw_frame(**kwds) def _draw_HistogramNonUniform(obj, **kwds): _draw_Histogram(obj, **kwds) def _draw_HistogramCategorical(obj, **kwds): _draw_Histogram(obj, **kwds) def _frameargs_posthook_HistogramCategorical(obj, output, **kwds): f = obj._frameargs() if f.get("xticks", containers.Auto) is containers.Auto: output["xticks"] = dict(enumerate(obj.bins)) return output def _draw_Scatter(obj, **kwds): svg = kwds["svg"] if kwds.get("drawframe", True): kwds["frameargs"] = _get_frameargs(obj, **kwds) f = kwds["frameargs"] obj._prepare(f["xmin"], f["ymin"], f["xmax"], f["ymax"]) wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 xmin, ymin, xmax, ymax, xlog, ylog = f["xmin"], f["ymin"], f["xmax"], f["ymax"], f["xlog"], f["ylog"] def t(x, y): return _transformX(x, wx1, wx2, xmin, xmax, xlog), _transformY(y, wy1, wy2, ymin, ymax, ylog) plotname = svg.uniquename(obj.__class__.__name__) plotclipname = "%s_clip" % plotname plotmarkname = "%s_mark" % plotname svg.defs[plotclipname] = u""" <clipPath id="%(plotclipname)s"> <rect x="%(wx1)g" y="%(wy1)g" width="%(windowwidth)g" height="%(windowheight)g" /> </clipPath>""" % vars() markeropacity = _svgopacity(obj.markercolor) markercolor = _svgcolor(obj.markercolor) markeroutlineopacity = _svgopacity(obj.markeroutline) markeroutline = _svgcolor(obj.markeroutline) # TODO: handle shapes other than circles (in a centralized way) if obj.marker == "circle": radius = _svgmarkersize(obj.markersize) svg.defs[plotmarkname] = u""" <circle id="%(plotmarkname)s" cx="0" cy="0" r="%(radius)g" stroke="%(markeroutline)s" stroke-opacity="%(markeroutlineopacity)g" fill="%(markercolor)s" fill-opacity="%(markeropacity)g" />""" % vars() else: pass h = "#" svg.body.append(u"""<g id="%(plotname)s" clip-path="url(%(h)s%(plotclipname)s)">""" % vars()) xindex = obj.index()["x"] yindex = obj.index()["y"] if obj.linecolor is not None: linewidth = _svglinewidth(obj.linewidth) linestyle = _svglinestyle(obj.linestyle, obj.linewidth) lineopacity = _svgopacity(obj.linecolor) linecolor = _svgcolor(obj.linecolor) pathdata = [] for value in obj._xlimited_values: if len(pathdata) == 0: pathdata.append("M %g %g" % t(value[xindex], value[yindex])) else: pathdata.append("L %g %g" % t(value[xindex], value[yindex])) pathdata = " ".join(pathdata) svg.body.append(u""" <path d="%(pathdata)s" stroke-width="%(linewidth)g" stroke-dasharray="%(linestyle)s" stroke="%(linecolor)s" stroke-opacity="%(lineopacity)g" fill="none" />""" % vars()) if "ex" in obj.sig: lineopacity = _svgopacity(obj.linecolor) linecolor = _svgcolor(obj.linecolor) if "exl" in obj.sig: exlindex = obj.index()["exl"] else: exlindex = obj.index()["ex"] exindex = obj.index()["ex"] def down(x, y): return x, y - 5. def up(x, y): return x, y + 5. for value in obj._limited_values: x, y, exl, ex = value[xindex], value[yindex], abs(value[exlindex]), abs(value[exindex]) pathdata = ["M %g %g" % t(x - exl, y), "L %g %g" % t(x + ex, y), "M %g %g" % down(*t(x - exl, y)), "L %g %g" % up(*t(x - exl, y)), "M %g %g" % down(*t(x + ex, y)), "L %g %g" % up(*t(x + ex, y))] pathdata = " ".join(pathdata) svg.body.append(u""" <path d="%(pathdata)s" stroke="%(linecolor)s" stroke-opacity="%(lineopacity)g" fill="none" />""" % vars()) if "ey" in obj.sig: lineopacity = _svgopacity(obj.linecolor) linecolor = _svgcolor(obj.linecolor) if "eyl" in obj.sig: eylindex = obj.index()["eyl"] else: eylindex = obj.index()["ey"] eyindex = obj.index()["ey"] def down(x, y): return x - 5., y def up(x, y): return x + 5., y for value in obj._limited_values: x, y, eyl, ey = value[xindex], value[yindex], abs(value[eylindex]), abs(value[eyindex]) pathdata = ["M %g %g" % t(x, y - eyl), "L %g %g" % t(x, y + ey), "M %g %g" % down(*t(x, y - eyl)), "L %g %g" % up(*t(x, y - eyl)), "M %g %g" % down(*t(x, y + ey)), "L %g %g" % up(*t(x, y + ey))] pathdata = " ".join(pathdata) svg.body.append(u""" <path d="%(pathdata)s" stroke="%(linecolor)s" stroke-opacity="%(lineopacity)g" fill="none" />""" % vars()) if obj.marker is not None: for value in obj._limited_values: x, y = t(value[xindex], value[yindex]) svg.body.append(u""" <use x="%(x)g" y="%(y)g" xlink:href="%(h)s%(plotmarkname)s" />""" % vars()) svg.body.append(u"""</g>""") if kwds.get("drawframe", True): _draw_frame(**kwds) def _frameargs_posthook_Scatter(obj, output, **kwds): f = obj._frameargs() if f.get("xticks", containers.Auto) is containers.Auto and getattr(obj, "_xticks", None) is not None: output["xticks"] = obj._xticks if f.get("yticks", containers.Auto) is containers.Auto and getattr(obj, "_yticks", None) is not None: output["yticks"] = obj._yticks return output def _draw_TimeSeries(obj, **kwds): _draw_Scatter(obj, **kwds) def _frameargs_prehook_TimeSeries(obj, output, **kwds): if "xmin" in output and output["xmin"] is not None and output["xmin"] is not containers.Auto and isinstance(output["xmin"], basestring): output["xmin"] = obj.fromtimestring(output["xmin"]) if "xmax" in output and output["xmax"] is not None and output["xmax"] is not containers.Auto and isinstance(output["xmax"], basestring): output["xmax"] = obj.fromtimestring(output["xmax"]) return output def _frameargs_posthook_TimeSeries(obj, output, **kwds): f = obj._frameargs() if "xticks" not in f or f["xticks"] is containers.Auto: xticks = output["xticks"] for value, name in xticks.items(): if name is not None: xticks[value] = obj.totimestring(value) output["xticks"] = xticks return output def _draw_ColorField(obj, **kwds): svg = kwds["svg"] if kwds.get("drawframe", True): kwds["frameargs"] = _get_frameargs(obj, **kwds) f = kwds["frameargs"] wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 xmin, ymin, xmax, ymax, xlog, ylog = f["xmin"], f["ymin"], f["xmax"], f["ymax"], f["xlog"], f["ylog"] xbins, ybins = obj.xbins(), obj.ybins() zmin, zmax = obj.zranges() if obj.zmin is not containers.Auto: zmin = obj.zmin if obj.zmax is not containers.Auto: zmax = obj.zmax image = PIL.Image.new("RGBA", (xbins, ybins), (0, 0, 0, 255)) for i in xrange(xbins): for j in xrange(ybins): col = obj.tocolor(obj.values[i,j], zmin, zmax) if isinstance(col, color.RGB): col = col.ints() elif isinstance(col, (color.AbstractColor, basestring)): col = color.RGB(col).ints() image.putpixel((i, ybins-j-1), col) buff = StringIO.StringIO() image.save(buff, "PNG") encoded = base64.b64encode(buff.getvalue()) if obj.smooth: smooth = "optimizeQuality" else: smooth = "optimizeSpeed" xpos = _transformX(obj.xmin, wx1, wx2, xmin, xmax, xlog) xpos2 = _transformX(obj.xmax, wx1, wx2, xmin, xmax, xlog) ypos = _transformY(obj.ymin, wy1, wy2, ymin, ymax, ylog) ypos2 = _transformY(obj.ymax, wy1, wy2, ymin, ymax, ylog) width = xpos2 - xpos height = ypos - ypos2 plotname = svg.uniquename(obj.__class__.__name__) plotclipname = "%s_clip" % plotname svg.defs[plotclipname] = u""" <clipPath id="%(plotclipname)s"> <rect x="%(wx1)g" y="%(wy1)g" width="%(windowwidth)g" height="%(windowheight)g" /> </clipPath>""" % vars() h = "#" svg.body.append(u"""<g id="%(plotname)s" clip-path="url(%(h)s%(plotclipname)s)">""" % vars()) svg.body.append(u""" <image xlink:href="data:image/png;base64,%(encoded)s" x="%(xpos)g" y="%(ypos2)g" width="%(width)g" height="%(height)g" image-rendering="%(smooth)s" preserveAspectRatio="none" />""" % vars()) svg.body.append(u"""</g>""") if kwds.get("drawframe", True): _draw_frame(**kwds) def _draw_Region(obj, **kwds): svg = kwds["svg"] if kwds.get("drawframe", True): kwds["frameargs"] = _get_frameargs(obj, **kwds) f = kwds["frameargs"] fillopacity = _svgopacity(obj.fillcolor) fillcolor = _svgcolor(obj.fillcolor) wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 xmin, ymin, xmax, ymax, xlog, ylog = f["xmin"], f["ymin"], f["xmax"], f["ymax"], f["xlog"], f["ylog"] plotname = svg.uniquename(obj.__class__.__name__) plotclipname = "%s_clip" % plotname svg.defs[plotclipname] = u""" <clipPath id="%(plotclipname)s"> <rect x="%(wx1)g" y="%(wy1)g" width="%(windowwidth)g" height="%(windowheight)g" /> </clipPath>""" % vars() pathdata = [] for command in obj.commands: if not isinstance(command, containers.RegionCommand): raise containers.ContainerException, "Commands passed to Region must all be RegionCommands (MoveTo, EdgeTo, ClosePolygon)" if isinstance(command, (containers.MoveTo, containers.EdgeTo)): x, y = command.x, command.y if isinstance(x, mathtools.InfiniteType): x = (wx1 + wx2)/2. + windowwidth/mathtools.epsilon * x._multiplier else: x = _transformX(x, wx1, wx2, xmin, xmax, xlog) if isinstance(y, mathtools.InfiniteType): y = (wy1 + wy2)/2. - windowwidth/mathtools.epsilon * y._multiplier else: y = _transformY(y, wy1, wy2, ymin, ymax, ylog) if isinstance(command, containers.MoveTo): pathdata.append("M %g %g" % (x, y)) if isinstance(command, containers.EdgeTo): pathdata.append("L %g %g" % (x, y)) elif isinstance(command, containers.ClosePolygon): pathdata.append("Z") pathdata = " ".join(pathdata) h = "#" svg.body.append(u"""<g id="%(plotname)s" clip-path="url(%(h)s%(plotclipname)s)">""" % vars()) svg.body.append(u""" <path d="%(pathdata)s" stroke-width="5." stroke="%(fillcolor)s" fill="%(fillcolor)s" fill-opacity="%(fillopacity)g" />""" % vars()) svg.body.append(u"""</g>""") if kwds.get("drawframe", True): _draw_frame(**kwds) def _draw_RegionMap(obj, **kwds): svg = kwds["svg"] if kwds.get("drawframe", True): kwds["frameargs"] = _get_frameargs(obj, **kwds) f = kwds["frameargs"] wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 xmin, ymin, xmax, ymax, xlog, ylog = f["xmin"], f["ymin"], f["xmax"], f["ymax"], f["xlog"], f["ylog"] obj._prepare() image = PIL.Image.new("RGBA", (obj.xbins, obj.ybins), (0, 0, 0, 255)) for i in xrange(obj.xbins): for j in xrange(obj.ybins): image.putpixel((i, obj.ybins-j-1), obj._values[i][j]) buff = StringIO.StringIO() image.save(buff, "PNG") encoded = base64.b64encode(buff.getvalue()) xpos = _transformX(obj.xmin, wx1, wx2, xmin, xmax, xlog) xpos2 = _transformX(obj.xmax, wx1, wx2, xmin, xmax, xlog) ypos = _transformY(obj.ymin, wy1, wy2, ymin, ymax, ylog) ypos2 = _transformY(obj.ymax, wy1, wy2, ymin, ymax, ylog) width = xpos2 - xpos height = ypos - ypos2 plotname = svg.uniquename(obj.__class__.__name__) plotclipname = "%s_clip" % plotname svg.defs[plotclipname] = u""" <clipPath id="%(plotclipname)s"> <rect x="%(wx1)g" y="%(wy1)g" width="%(windowwidth)g" height="%(windowheight)g" /> </clipPath>""" % vars() h = "#" svg.body.append(u"""<g id="%(plotname)s" clip-path="url(%(h)s%(plotclipname)s)">""" % vars()) svg.body.append(u""" <image xlink:href="data:image/png;base64,%(encoded)s" x="%(xpos)g" y="%(ypos2)g" width="%(width)g" height="%(height)g" image-rendering="optimizeQuality" preserveAspectRatio="none" />""" % vars()) svg.body.append(u"""</g>""") if kwds.get("drawframe", True): _draw_frame(**kwds) def _draw_ConsumerRegionMap(obj, **kwds): _draw_RegionMap(obj, **kwds) def _frameargs_prehook_Curve(obj, output, **kwds): obj._prepare(output.get("xlog", False)) output = obj._scatter._frameargs() return output def _draw_Curve(obj, **kwds): if "_scatter" not in obj.__dict__ or obj._scatter is None: if not kwds.get("drawframe", True): xmin = kwds["frameargs"]["xmin"] xmax = kwds["frameargs"]["xmax"] xlog = kwds["frameargs"]["xlog"] else: if "xlog" in kwds: xlog = kwds["xlog"] elif "xlog" in obj.__dict__: xlog = obj.xlog else: xlog = default_frameargs["xlog"] if "xmin" in kwds: xmin = kwds["xmin"] elif "xmin" in obj.__dict__: xmin = obj.xmin else: if xlog: xmin = 0.1 else: xmin = 0. if "xmax" in kwds: xmax = kwds["xmax"] elif "xmax" in obj.__dict__: xmax = obj.xmax else: xmax = 1. obj._prepare(xmin=xmin, xmax=xmax, xlog=xlog) _draw_Scatter(obj._scatter, **kwds) obj._scatter = None def _draw_Line(obj, **kwds): svg = kwds["svg"] if kwds.get("drawframe", True): kwds["frameargs"] = _get_frameargs(obj, **kwds) f = kwds["frameargs"] linewidth = _svglinewidth(obj.linewidth) linestyle = _svglinestyle(obj.linestyle, obj.linewidth) lineopacity = _svgopacity(obj.linecolor) linecolor = _svgcolor(obj.linecolor) wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 xmin, ymin, xmax, ymax, xlog, ylog = f["xmin"], f["ymin"], f["xmax"], f["ymax"], f["xlog"], f["ylog"] def t(x, y): return _transformX(x, wx1, wx2, xmin, xmax, xlog), _transformY(y, wy1, wy2, ymin, ymax, ylog) plotname = svg.uniquename(obj.__class__.__name__) plotclipname = "%s_clip" % plotname svg.defs[plotclipname] = u""" <clipPath id="%(plotclipname)s"> <rect x="%(wx1)g" y="%(wy1)g" width="%(windowwidth)g" height="%(windowheight)g" /> </clipPath>""" % vars() pathdata = [] if (isinstance(obj.x1, mathtools.InfiniteType) or isinstance(obj.y1, mathtools.InfiniteType)) and \ (isinstance(obj.x2, mathtools.InfiniteType) or isinstance(obj.y2, mathtools.InfiniteType)): raise containers.ContainerException, "Only one of the two points can be at Infinity" elif isinstance(obj.x1, mathtools.InfiniteType) or isinstance(obj.y1, mathtools.InfiniteType): pathdata.append("M %g %g" % t(obj.x2, obj.y2)) if isinstance(obj.x1, mathtools.InfiniteType): x = (wx1 + wx2)/2. + windowwidth/mathtools.epsilon * obj.x1._multiplier else: x = _transformX(obj.x1, wx1, wx2, xmin, xmax, xlog) if isinstance(obj.y1, mathtools.InfiniteType): y = (wy1 + wy2)/2. - windowwidth/mathtools.epsilon * obj.y1._multiplier else: y = _transformY(obj.y1, wy1, wy2, ymin, ymax, ylog) pathdata.append("L %g %g" % (x, y)) elif isinstance(obj.x2, mathtools.InfiniteType) or isinstance(obj.y2, mathtools.InfiniteType): pathdata.append("M %g %g" % t(obj.x1, obj.y1)) if isinstance(obj.x2, mathtools.InfiniteType): x = (wx1 + wx2)/2. + windowwidth/mathtools.epsilon * obj.x2._multiplier else: x = _transformX(obj.x2, wx1, wx2, xmin, xmax, xlog) if isinstance(obj.y2, mathtools.InfiniteType): y = (wy1 + wy2)/2. - windowwidth/mathtools.epsilon * obj.y2._multiplier else: y = _transformY(obj.y2, wy1, wy2, ymin, ymax, ylog) pathdata.append("L %g %g" % (x, y)) else: pathdata.append("M %g %g L %g %g" % tuple(list(t(obj.x1, obj.y1)) + list(t(obj.x2, obj.y2)))) pathdata = " ".join(pathdata) h = "#" svg.body.append(u"""<g id="%(plotname)s" clip-path="url(%(h)s%(plotclipname)s)">""" % vars()) svg.body.append(u""" <path d="%(pathdata)s" stroke-width="%(linewidth)g" stroke-dasharray="%(linestyle)s" stroke="%(linecolor)s" stroke-opacity="%(lineopacity)g" fill="none" />""" % vars()) svg.body.append(u"""</g>""") if kwds.get("drawframe", True): _draw_frame(**kwds) def _draw_Grid(obj, **kwds): svg = kwds["svg"] if kwds.get("drawframe", True): kwds["frameargs"] = _get_frameargs(obj, **kwds) f = kwds["frameargs"] linewidth = _svglinewidth(obj.linewidth) linestyle = _svglinestyle(obj.linestyle, obj.linewidth) lineopacity = _svgopacity(obj.linecolor) linecolor = _svgcolor(obj.linecolor) wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 xmin, ymin, xmax, ymax, xlog, ylog = f["xmin"], f["ymin"], f["xmax"], f["ymax"], f["xlog"], f["ylog"] def t(x, y): return _transformX(x, wx1, wx2, xmin, xmax, xlog), _transformY(y, wy1, wy2, ymin, ymax, ylog) obj._prepare(xmin, ymin, xmax, ymax) plotname = svg.uniquename(obj.__class__.__name__) plotclipname = "%s_clip" % plotname svg.defs[plotclipname] = u""" <clipPath id="%(plotclipname)s"> <rect x="%(wx1)g" y="%(wy1)g" width="%(windowwidth)g" height="%(windowheight)g" /> </clipPath>""" % vars() pathdata = [] for x in obj._vert: pathdata.append("M %g %g L %g %g" % tuple(list(t(x, ymin)) + list(t(x, ymax)))) for y in obj._horiz: pathdata.append("M %g %g L %g %g" % tuple(list(t(xmin, y)) + list(t(xmax, y)))) pathdata = " ".join(pathdata) h = "#" svg.body.append(u"""<g id="%(plotname)s" clip-path="url(%(h)s%(plotclipname)s)">""" % vars()) svg.body.append(u""" <path d="%(pathdata)s" stroke-width="%(linewidth)g" stroke-dasharray="%(linestyle)s" stroke="%(linecolor)s" stroke-opacity="%(lineopacity)g" fill="none" />""" % vars()) svg.body.append(u"""</g>""") if kwds.get("drawframe", True): _draw_frame(**kwds) def _draw_Legend(obj, **kwds): svg, svgwidth, svgheight = kwds["svg"], kwds["width"], kwds["height"] if kwds.get("drawframe", True): kwds["frameargs"] = _get_frameargs(obj, **kwds) f = kwds["frameargs"] linewidth = _svglinewidth(obj.linewidth) linestyle = _svglinestyle(obj.linestyle, obj.linewidth) lineopacity = _svgopacity(obj.linecolor) linecolor = _svgcolor(obj.linecolor) fillopacity = _svgopacity(obj.fillcolor) fillcolor = _svgcolor(obj.fillcolor) wx1, wy1, wx2, wy2 = _get_window(**kwds) windowwidth, windowheight = wx2 - wx1, wy2 - wy1 obj._prepare() if obj.height is containers.Auto: # no top-padding # objheight = (2.*obj.padding + obj._rows*obj.baselineskip)*svgheight / windowheight objheight = (obj.padding + obj._rows*obj.baselineskip)*svgheight / windowheight else: objheight = obj.height width = obj.width * windowwidth height = objheight * windowheight x = wx1 + obj.x*windowwidth y = wy2 - obj.y*windowheight if obj._anchor[1] == "m": x -= width/2. elif obj._anchor[1] == "r": x -= width if obj._anchor[0] == "m": y -= height/2. elif obj._anchor[0] == "b": y -= height plotname = svg.uniquename(obj.__class__.__name__) plotclipname = "%s_clip" % plotname svg.defs[plotclipname] = u""" <clipPath id="%(plotclipname)s"> <rect x="%(x)g" y="%(y)g" width="%(width)g" height="%(height)g" /> </clipPath>""" % vars() if kwds.get("drawframe", True): _draw_frame(**kwds) h = "#" svg.body.append(u"""<g id="%(plotname)s">""" % vars()) svg.body.append(u""" <rect x="%(x)g" y="%(y)g" width="%(width)g" height="%(height)g" stroke-width="%(linewidth)g" stroke-dasharray="%(linestyle)s" stroke="%(linecolor)s" stroke-opacity="%(lineopacity)g" fill="%(fillcolor)s" fill-opacity="%(fillopacity)g" />""" % vars()) svg.body.append(u""" <g id="%(plotname)s_content" clip-path="url(%(h)s%(plotclipname)s)">""" % vars()) # no top-padding # penx, peny = x + obj.padding * svgwidth, y + obj.padding * svgheight penx, peny = x + obj.padding * svgwidth, y width -= 2. * obj.padding * svgwidth for i in range(len(obj._fields)): peny += obj.baselineskip * svgheight penxstart = penx for j in range(len(obj._fields[i])): drawable = obj._fields[i][j] drawn = False might_have_style = False try: drawable.__dict__ might_have_style = True except AttributeError: pass if might_have_style: if "linecolor" in drawable.__dict__ and drawable.linecolor is not None: lstyle = u" stroke-width=\"%g\" stroke-dasharray=\"%s\" stroke=\"%s\" stroke-opacity=\"%g\"" % (_svglinewidth(drawable.linewidth), _svglinestyle(drawable.linestyle, drawable.linewidth), _svgcolor(drawable.linecolor), _svgopacity(drawable.linecolor)) else: lstyle = u" stroke=\"none\"" if "fillcolor" in drawable.__dict__ and drawable.fillcolor is not None: drawable_fillopacity = _svgopacity(drawable.fillcolor) drawable_fillcolor = _svgcolor(drawable.fillcolor) rectwidth, rectheight = 1.5 * obj.baselineskip * svgheight, 0.75 * obj.baselineskip * svgheight rectx, recty = penx, peny - rectheight if obj._justify[j] == "l": rectx += obj.padding * svgwidth elif obj._justify[j] in ("m", "c"): rectx += (obj._colwid[j] * width - rectwidth - obj.padding * svgwidth)/2. elif obj._justify[j] == "r": rectx += obj._colwid[j] * width - rectwidth - obj.padding * svgwidth svg.body.append(u""" <rect x="%(rectx)g" y="%(recty)g" width="%(rectwidth)g" height="%(rectheight)g"%(lstyle)s fill="%(drawable_fillcolor)s" fill-opacity="%(drawable_fillopacity)g" />""" % vars()) drawn = True elif "linecolor" in drawable.__dict__ and drawable.linecolor is not None: linelength = 1.5 * obj.baselineskip * svgheight linex1, liney1 = penx, peny - 0.3 * obj.baselineskip * svgheight if obj._justify[j] == "l": linex1 += obj.padding * svgwidth elif obj._justify[j] in ("m", "c"): linex1 += (obj._colwid[j] * width - linelength - obj.padding * svgwidth)/2. elif obj._justify[j] == "r": linex1 += obj._colwid[j] * width - linelength - obj.padding * svgwidth linex2, liney2 = linex1 + linelength, liney1 svg.body.append(u""" <line x1="%(linex1)g" y1="%(liney1)g" x2="%(linex2)g" y2="%(liney2)g"%(lstyle)s />""" % vars()) drawn = True if "marker" in drawable.__dict__ and drawable.marker is not None: # TODO: handle shapes other than circles (in a centralized way) plotmarkname = svg.uniquename("%s_mark" % plotname) radius, markeroutlineopacity, markeroutline, markeropacity, markercolor = _svgmarkersize(drawable.markersize), _svgopacity(drawable.markeroutline), _svgcolor(drawable.markeroutline), _svgopacity(drawable.markercolor), _svgcolor(drawable.markercolor) svg.defs[plotmarkname] = u""" <circle id="%(plotmarkname)s" cx="0" cy="0" r="%(radius)g" stroke="%(markeroutline)s" stroke-opacity="%(markeroutlineopacity)g" fill="%(markercolor)s" fill-opacity="%(markeropacity)g" />""" % vars() linelength = 1.5 * obj.baselineskip * svgheight withline = (("fillcolor" in drawable.__dict__ and drawable.fillcolor is not None) or ("linecolor" in drawable.__dict__ and drawable.linecolor is not None)) markx, marky = penx, peny - 0.375 * obj.baselineskip * svgheight if obj._justify[j] == "l": markx += obj.padding * svgwidth if withline: markx += linelength / 2. elif obj._justify[j] in ("m", "c"): markx += (obj._colwid[j] * width - obj.padding * svgwidth)/2. elif obj._justify[j] == "r": markx += obj._colwid[j] * width - obj.padding * svgwidth if withline: markx -= linelength / 2. svg.body.append(u""" <use x="%(markx)g" y="%(marky)g" xlink:href="%(h)s%(plotmarkname)s" />""" % vars()) drawn = True if not drawn and drawable is not None: astext = unicode(drawable) font_size = obj.textscale*30. if obj._justify[j] == "l": placement = penx text_anchor = "start" elif obj._justify[j] in ("m", "c"): placement = penx + 0.5 * obj._colwid[j] * width text_anchor = "middle" elif obj._justify[j] == "r": placement = penx + obj._colwid[j] * width text_anchor = "end" svg.body.append(u""" <text font-size="%(font_size)g" transform="translate(%(placement)g, %(peny)g)" text-anchor="%(text_anchor)s" dominant-baseline="middle" stroke="none" fill="black">%(astext)s</text>""" % vars()) penx += obj._colwid[j] * width penx = penxstart svg.body.append(u""" </g>""") svg.body.append(u"""</g>""")
{ "content_hash": "515832c98bda09ba8689ca2b3e9477eb", "timestamp": "", "source": "github", "line_count": 1246, "max_line_length": 332, "avg_line_length": 42.170144462279296, "alnum_prop": 0.5648599269183922, "repo_name": "opendatagroup/cassius", "id": "1fb34f5abd6b6d6fafef0450f71d55a5a05a7387", "size": "52571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tags/cassius-0_1_0_0/cassius/svgdraw.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "15656" }, { "name": "JavaScript", "bytes": "12775" }, { "name": "Python", "bytes": "1187698" } ], "symlink_target": "" }
"""SOAP client.""" import os.path from pkg_resources import get_distribution, DistributionNotFound RINSE_DIR = os.path.dirname(__file__) ENVELOPE_XSD = 'soap-1.1_envelope.xsd' NS_SOAPENV = 'http://schemas.xmlsoap.org/soap/envelope/' NS_MAP = { 'soapenv': NS_SOAPENV, } try: _dist = get_distribution('rinse') if not __file__.startswith(os.path.join(_dist.location, 'rinse', '')): # not installed, but there is another version that *is* raise DistributionNotFound except DistributionNotFound: __version__ = 'development' else: __version__ = _dist.version
{ "content_hash": "e7367d68cbd029d0f2bb6fac6153f025", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 74, "avg_line_length": 25.82608695652174, "alnum_prop": 0.6750841750841751, "repo_name": "tysonclugg/rinse", "id": "748c3198018fee66139d0e8cdab4aaabb4928940", "size": "594", "binary": false, "copies": "5", "ref": "refs/heads/develop", "path": "rinse/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "743" }, { "name": "Python", "bytes": "24343" }, { "name": "Shell", "bytes": "194" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Cutlass: nv_std::is_base_of&lt; BaseT, DerivedT &gt; Struct Template Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" async src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Cutlass </div> <div id="projectbrief">CUDA Templates for Linear Algebra Subroutines and Solvers</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacenv__std.html">nv_std</a></li><li class="navelem"><a class="el" href="structnv__std_1_1is__base__of.html">is_base_of</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="structnv__std_1_1is__base__of-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">nv_std::is_base_of&lt; BaseT, DerivedT &gt; Struct Template Reference</div> </div> </div><!--header--> <div class="contents"> <p>std::is_base_of </p> <p><code>#include &lt;<a class="el" href="nv__std_8h_source.html">nv_std.h</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for nv_std::is_base_of&lt; BaseT, DerivedT &gt;:</div> <div class="dyncontent"> <div class="center"> <img src="structnv__std_1_1is__base__of.png" usemap="#nv_5Fstd::is_5Fbase_5Fof_3C_20BaseT_2C_20DerivedT_20_3E_map" alt=""/> <map id="nv_5Fstd::is_5Fbase_5Fof_3C_20BaseT_2C_20DerivedT_20_3E_map" name="nv_5Fstd::is_5Fbase_5Fof_3C_20BaseT_2C_20DerivedT_20_3E_map"> <area href="structnv__std_1_1integral__constant.html" alt="nv_std::integral_constant&lt; bool,(is_base_of_helper&lt; remove_cv&lt; BaseT &gt;::type, remove_cv&lt; DerivedT &gt;::type &gt;::value)||(is_same&lt; remove_cv&lt; BaseT &gt;::type, remove_cv&lt; DerivedT &gt;::type &gt;::value)&gt;" shape="rect" coords="0,0,1151,24"/> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a> Additional Inherited Members</h2></td></tr> <tr class="inherit_header pub_types_structnv__std_1_1integral__constant"><td colspan="2" onclick="javascript:toggleInherit('pub_types_structnv__std_1_1integral__constant')"><img src="closed.png" alt="-"/>&#160;Public Types inherited from <a class="el" href="structnv__std_1_1integral__constant.html">nv_std::integral_constant&lt; bool,(is_base_of_helper&lt; remove_cv&lt; BaseT &gt;::type, remove_cv&lt; DerivedT &gt;::type &gt;::value)||(is_same&lt; remove_cv&lt; BaseT &gt;::type, remove_cv&lt; DerivedT &gt;::type &gt;::value)&gt;</a></td></tr> <tr class="memitem:adf091ff78fd0c320dd2bf14d0440e498 inherit pub_types_structnv__std_1_1integral__constant"><td class="memItemLeft" align="right" valign="top">typedef bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structnv__std_1_1integral__constant.html#adf091ff78fd0c320dd2bf14d0440e498">value_type</a></td></tr> <tr class="separator:adf091ff78fd0c320dd2bf14d0440e498 inherit pub_types_structnv__std_1_1integral__constant"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae025d21db95bdca5abe83daae9190642 inherit pub_types_structnv__std_1_1integral__constant"><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="structnv__std_1_1integral__constant.html">integral_constant</a>&lt; bool, V &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structnv__std_1_1integral__constant.html#ae025d21db95bdca5abe83daae9190642">type</a></td></tr> <tr class="separator:ae025d21db95bdca5abe83daae9190642 inherit pub_types_structnv__std_1_1integral__constant"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_structnv__std_1_1integral__constant"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_structnv__std_1_1integral__constant')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="structnv__std_1_1integral__constant.html">nv_std::integral_constant&lt; bool,(is_base_of_helper&lt; remove_cv&lt; BaseT &gt;::type, remove_cv&lt; DerivedT &gt;::type &gt;::value)||(is_same&lt; remove_cv&lt; BaseT &gt;::type, remove_cv&lt; DerivedT &gt;::type &gt;::value)&gt;</a></td></tr> <tr class="memitem:a910949c03c7c6627d4b560bcacf44448 inherit pub_methods_structnv__std_1_1integral__constant"><td class="memItemLeft" align="right" valign="top"><a class="el" href="cutlass_8h.html#a28c2443a142676d3d71effdae1a986b1">CUTLASS_HOST_DEVICE</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structnv__std_1_1integral__constant.html#a910949c03c7c6627d4b560bcacf44448">operator value_type</a> () const</td></tr> <tr class="separator:a910949c03c7c6627d4b560bcacf44448 inherit pub_methods_structnv__std_1_1integral__constant"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a1932bf7ecdb19870703cb4303c8d6d43 inherit pub_methods_structnv__std_1_1integral__constant"><td class="memItemLeft" align="right" valign="top"><a class="el" href="cutlass_8h.html#a28c2443a142676d3d71effdae1a986b1">CUTLASS_HOST_DEVICE</a> const <a class="el" href="structnv__std_1_1integral__constant.html#adf091ff78fd0c320dd2bf14d0440e498">value_type</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structnv__std_1_1integral__constant.html#a1932bf7ecdb19870703cb4303c8d6d43">operator()</a> () const</td></tr> <tr class="separator:a1932bf7ecdb19870703cb4303c8d6d43 inherit pub_methods_structnv__std_1_1integral__constant"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_static_attribs_structnv__std_1_1integral__constant"><td colspan="2" onclick="javascript:toggleInherit('pub_static_attribs_structnv__std_1_1integral__constant')"><img src="closed.png" alt="-"/>&#160;Static Public Attributes inherited from <a class="el" href="structnv__std_1_1integral__constant.html">nv_std::integral_constant&lt; bool,(is_base_of_helper&lt; remove_cv&lt; BaseT &gt;::type, remove_cv&lt; DerivedT &gt;::type &gt;::value)||(is_same&lt; remove_cv&lt; BaseT &gt;::type, remove_cv&lt; DerivedT &gt;::type &gt;::value)&gt;</a></td></tr> <tr class="memitem:a3879783ef09dffa3de649ec22d961f7a inherit pub_static_attribs_structnv__std_1_1integral__constant"><td class="memItemLeft" align="right" valign="top">static const bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structnv__std_1_1integral__constant.html#a3879783ef09dffa3de649ec22d961f7a">value</a></td></tr> <tr class="separator:a3879783ef09dffa3de649ec22d961f7a inherit pub_static_attribs_structnv__std_1_1integral__constant"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this struct was generated from the following file:<ul> <li><a class="el" href="nv__std_8h_source.html">nv_std.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Fri Apr 20 2018 16:16:55 for Cutlass by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.14 </small></address> </body> </html>
{ "content_hash": "3f04cdb001aaacaa7d1266090f09bf81", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 577, "avg_line_length": 77.3170731707317, "alnum_prop": 0.7160883280757098, "repo_name": "tgrogers/gpgpu-sim_simulations", "id": "9f39064c2aba127b000d9d502d1295727df92a17", "size": "9510", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "benchmarks/src/cuda/cutlass-bench/docs/structnv__std_1_1is__base__of.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "1351" }, { "name": "C", "bytes": "1317472" }, { "name": "C++", "bytes": "203275" }, { "name": "Cuda", "bytes": "522593" }, { "name": "Makefile", "bytes": "169109" }, { "name": "Python", "bytes": "61700" }, { "name": "Roff", "bytes": "2936" }, { "name": "Shell", "bytes": "21162" } ], "symlink_target": "" }
#pragma once #include <qglobal.h> #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) #include <QtWidgets/QGraphicsView> #else #include <QtGui/QGraphicsView> #endif class QGraphicsScene; class GraphicsView : public QGraphicsView { Q_OBJECT public: GraphicsView(QWidget *parent = 0); virtual void wheelEvent(QWheelEvent* event); public slots: void setScale(int scale); signals: void scaleChanged(int); protected: qreal mScale; void setScale(qreal scale); };
{ "content_hash": "51eb9f5330b8cce481e9586b791ac025", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 48, "avg_line_length": 16.689655172413794, "alnum_prop": 0.7148760330578512, "repo_name": "salshaaban/BidiRenderer", "id": "f44685a1a6627f4ef806f52f00211482fcde9b1f", "size": "1856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "graphicsview.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "92658" }, { "name": "QMake", "bytes": "1073" } ], "symlink_target": "" }
namespace bond { template <typename... T> struct Protocols; template <typename BufferT> class CompactBinaryReader; template <typename BufferT, typename MarshaledBondedProtocolsT = Protocols<CompactBinaryReader<BufferT> > > class SimpleBinaryReader; BOND_CONSTEXPR_OR_CONST uint16_t v1 = 0x0001; BOND_CONSTEXPR_OR_CONST uint16_t v2 = 0x0002; template <typename T> struct default_version : std::integral_constant<uint16_t, v1> {}; }
{ "content_hash": "be65de06b9c3207e9ce37acdcde18855", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 111, "avg_line_length": 26.833333333333332, "alnum_prop": 0.7060041407867494, "repo_name": "gencer/bond", "id": "5375cba94165e56f154158a22028e1540e08e2f0", "size": "793", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "cpp/inc/bond/core/bond_version.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "137" }, { "name": "C", "bytes": "597" }, { "name": "C#", "bytes": "1479030" }, { "name": "C++", "bytes": "2518581" }, { "name": "CMake", "bytes": "58443" }, { "name": "Emacs Lisp", "bytes": "298" }, { "name": "Groovy", "bytes": "4087" }, { "name": "Haskell", "bytes": "281441" }, { "name": "Java", "bytes": "1426040" }, { "name": "PowerShell", "bytes": "5273" }, { "name": "Python", "bytes": "20958" } ], "symlink_target": "" }
package org.arakhne.afc.math.geometry.d1.d; import java.lang.ref.WeakReference; import java.util.Objects; import org.eclipse.xtext.xbase.lib.Pure; import org.arakhne.afc.math.geometry.d1.GeomFactory1D; import org.arakhne.afc.math.geometry.d1.Point1D; import org.arakhne.afc.math.geometry.d1.Segment1D; import org.arakhne.afc.math.geometry.d1.Vector1D; import org.arakhne.afc.math.geometry.d2.Tuple2D; import org.arakhne.afc.vmutil.asserts.AssertMessages; import org.arakhne.afc.vmutil.json.JsonBuffer; /** 1.5D tuple with 2 double precision floating-point numbers. * * @param <RT> is the type of the data returned by the tuple. * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ * @since 14.0 */ public class Tuple1d<RT extends Tuple1d<? super RT>> implements Tuple2D<RT> { private static final long serialVersionUID = -7422015889188383352L; /** x coordinate. */ protected WeakReference<Segment1D<?, ?>> segment; /** x coordinate. */ protected double x; /** y coordinate. */ protected double y; /** Construct a zero tuple. */ public Tuple1d() { this.segment = new WeakReference<>(null); } /** Construct a zero tuple. * * @param segment the segment. */ public Tuple1d(Segment1D<?, ?> segment) { assert segment != null : AssertMessages.notNullParameter(); this.segment = new WeakReference<>(segment); } /** Constructor. * @param segment the segment. * @param tuple is the tuple to copy. */ public Tuple1d(Segment1D<?, ?> segment, Tuple2D<?> tuple) { assert tuple != null : AssertMessages.notNullParameter(); assert segment != null : AssertMessages.notNullParameter(); this.segment = new WeakReference<>(segment); this.x = tuple.getX(); this.y = tuple.getY(); } /** Constructor. * @param segment the segment. * @param tuple is the tuple to copy. */ public Tuple1d(Segment1D<?, ?> segment, int[] tuple) { assert tuple != null : AssertMessages.notNullParameter(); assert tuple.length >= 2 : AssertMessages.tooSmallArrayParameter(tuple.length, 2); assert segment != null : AssertMessages.notNullParameter(); this.segment = new WeakReference<>(segment); this.x = tuple[0]; this.y = tuple[1]; } /** Constructor. * @param segment the segment. * @param tuple is the tuple to copy. */ public Tuple1d(Segment1D<?, ?> segment, double[] tuple) { assert tuple != null : AssertMessages.notNullParameter(); assert tuple.length >= 2 : AssertMessages.tooSmallArrayParameter(tuple.length, 2); assert segment != null : AssertMessages.notNullParameter(); this.segment = new WeakReference<>(segment); this.x = tuple[0]; this.y = tuple[1]; } /** Construct a tuple with the given coordinates. * @param segment the segment. * @param x x coordinate. * @param y y coordinate. */ public Tuple1d(Segment1D<?, ?> segment, int x, int y) { assert segment != null : AssertMessages.notNullParameter(); this.segment = new WeakReference<>(segment); this.x = x; this.y = y; } /** Construct a tuple with the given coordinates. * @param segment the segment. * @param x x coordinate. * @param y y coordinate. */ public Tuple1d(Segment1D<?, ?> segment, double x, double y) { assert segment != null : AssertMessages.notNullParameter(); this.segment = new WeakReference<>(segment); this.x = x; this.y = y; } /** Replies the geometry factory. * * @return the factory. */ @SuppressWarnings("static-method") public GeomFactory1D<Vector1d, Point1d> getGeomFactory() { return GeomFactory1d.SINGLETON; } /** Replies the segment. * * @return the segment or <code>null</code> if the weak reference has lost the segment. */ @Pure public Segment1D<?, ?> getSegment() { return this.segment.get(); } /** Set the segment. * * @param segment is the segment. */ public void setSegment(Segment1D<?, ?> segment) { this.segment = new WeakReference<>(segment); } @SuppressWarnings("unchecked") @Pure @Override public RT clone() { try { final RT clone = (RT) super.clone(); clone.segment = new WeakReference<>(this.segment.get()); return clone; } catch (CloneNotSupportedException e) { throw new InternalError(e); } } @Override public void absolute() { this.x = Math.abs(this.x); this.y = Math.abs(this.y); } @Override public void absolute(Tuple2D<?> tuple) { assert tuple != null : AssertMessages.notNullParameter(); tuple.set(Math.abs(this.x), Math.abs(this.y)); } @Override public void add(int x, int y) { this.x += x; this.y += y; } @Override public void add(double x, double y) { this.x += x; this.y += y; } @Override public void addX(int x) { this.x += x; } @Override public void addX(double x) { this.x += x; } @Override public void addY(int y) { this.y += y; } @Override public void addY(double y) { this.y += y; } @Override public void negate(Tuple2D<?> tuple) { assert tuple != null : AssertMessages.notNullParameter(); this.x = -tuple.getX(); this.y = -tuple.getY(); } @Override public void negate() { this.x = -this.x; this.y = -this.y; } @Override public void scale(int scale, Tuple2D<?> tuple) { assert tuple != null : AssertMessages.notNullParameter(1); this.x = scale * tuple.getX(); this.y = scale * tuple.getY(); } @Override public void scale(double scale, Tuple2D<?> tuple) { assert tuple != null : AssertMessages.notNullParameter(1); this.x = scale * tuple.getX(); this.y = scale * tuple.getY(); } @Override public void scale(int scale) { this.x = scale * this.x; this.y = scale * this.y; } @Override public void scale(double scale) { this.x = scale * this.x; this.y = scale * this.y; } /** Change the attributes of the tuple. * * @param segment the segment. * @param curviline the curviline coordinate. * @param shift the shift distance. */ public void set(Segment1D<?, ?> segment, double curviline, double shift) { assert segment != null : AssertMessages.notNullParameter(0); this.segment = new WeakReference<>(segment); this.x = curviline; this.y = shift; } @Override public void set(Tuple2D<?> tuple) { assert tuple != null : AssertMessages.notNullParameter(); this.x = tuple.getX(); this.y = tuple.getY(); } @Override public void set(int x, int y) { this.x = x; this.y = y; } @Override public void set(double x, double y) { this.x = x; this.y = y; } @Override public void set(int[] tuple) { assert tuple != null : AssertMessages.notNullParameter(); assert tuple.length >= 2 : AssertMessages.tooSmallArrayParameter(tuple.length, 2); this.x = tuple[0]; this.y = tuple[1]; } @Override public void set(double[] tuple) { assert tuple != null : AssertMessages.notNullParameter(); assert tuple.length >= 2 : AssertMessages.tooSmallArrayParameter(tuple.length, 2); this.x = tuple[0]; this.y = tuple[1]; } @Pure @Override public double getX() { return this.x; } @Pure @Override public int ix() { return (int) this.x; } @Override public void setX(int x) { this.x = x; } @Override public void setX(double x) { this.x = x; } @Pure @Override public double getY() { return this.y; } @Pure @Override public int iy() { return (int) this.y; } @Override public void setY(int y) { this.y = y; } @Override public void setY(double y) { this.y = y; } @Override public void sub(int x, int y) { this.x -= x; this.y -= y; } @Override public void sub(double x, double y) { this.x -= x; this.y -= y; } @Override public void subX(int x) { this.x -= x; } @Override public void subX(double x) { this.x -= x; } @Override public void subY(int y) { this.y -= y; } @Override public void subY(double y) { this.y -= y; } @Pure @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof Vector1D<?, ?, ?>) { final Point1D<?, ?, ?> tuple = (Point1D<?, ?, ?>) object; return tuple.getSegment() == getSegment() && tuple.getX() == getX() && tuple.getY() == getY(); } if (object instanceof Point1D<?, ?, ?>) { final Point1D<?, ?, ?> tuple = (Point1D<?, ?, ?>) object; return tuple.getSegment() == getSegment() && tuple.getX() == getX() && tuple.getY() == getY(); } if (object instanceof Tuple2D<?>) { final Tuple2D<?> tuple = (Tuple2D<?>) object; return tuple.getX() == getX() && tuple.getY() == getY(); } return false; } @Pure @Override public int hashCode() { int bits = 1; bits = 31 * bits + Objects.hashCode(this.segment.get()); bits = 31 * bits + Double.hashCode(this.x); bits = 31 * bits + Double.hashCode(this.y); return bits ^ (bits >> 31); } @Pure @Override public String toString() { final JsonBuffer objectDescription = new JsonBuffer(); toJson(objectDescription); return objectDescription.toString(); } @Override public void toJson(JsonBuffer buffer) { buffer.add("segment", getSegment()); //$NON-NLS-1$ buffer.add("x", getX()); //$NON-NLS-1$ buffer.add("y", getY()); //$NON-NLS-1$ } }
{ "content_hash": "b5c78bec0dc4bbed84410d73309eca11", "timestamp": "", "source": "github", "line_count": 412, "max_line_length": 97, "avg_line_length": 22.104368932038835, "alnum_prop": 0.6529043592840672, "repo_name": "gallandarakhneorg/afc", "id": "6e1710629d795142cb5d2735eed473048964aeca", "size": "10025", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/maths/mathgeom/src/main/java/org/arakhne/afc/math/geometry/d1/d/Tuple1d.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "62" }, { "name": "HTML", "bytes": "35" }, { "name": "Java", "bytes": "15844113" }, { "name": "MATLAB", "bytes": "3002" }, { "name": "Perl", "bytes": "637" }, { "name": "Shell", "bytes": "4656" }, { "name": "Visual Basic .NET", "bytes": "50562" } ], "symlink_target": "" }
package net.stickycode.deploy.bootstrap; import static org.fest.assertions.Assertions.assertThat; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import org.junit.Test; public class BootstrapFunctionalTest { static { System.setProperty("debug", "true"); System.setProperty("verbose", "true"); } @Test public void jarsWithDodgyStructures() throws ClassNotFoundException { StickyClasspath b = new ZipScanningStickyClasspath().loadZip(new File("src/test/samples/sticky-deployer-embedded-sample.jar")); assertThat(b.getLibraries()).hasSize(2); assertThat(b.getLibraries().iterator().next().getClasses()).hasSize(1); assertThat(b.getLibraries().iterator().next().getResources()).hasSize(4); } @Test public void jars() throws ClassNotFoundException { StickyClasspath b = new ZipScanningStickyClasspath().loadZip(new File("src/test/samples/sticky-deployer-sample-2jar-1.2-sample.jar")); assertThat(b.getLibraries()).hasSize(2); assertThat(b.getLibraries().get(0).getClasses()).hasSize(1); assertThat(b.getLibraries().get(0).getResources()).hasSize(8); assertThat(b.getLibraries().get(1).getClasses()).hasSize(1); assertThat(b.getLibraries().get(1).getResources()).hasSize(5); } @Test public void lookingUpResources() throws IOException, ClassNotFoundException { File file = new File("src/test/samples/sticky-deployer-sample-2jar-1.2-sample.jar"); StickyClasspath classpath = new ZipScanningStickyClasspath().loadZip(file); StickyEmbedder b = new StickyEmbedder(); b.initialise(new URLClassLoader(new URL[] { new URL("file://" + file.getAbsolutePath()) }, ClassLoader.getSystemClassLoader()), classpath); assertThat(classpath.getLibraries()).hasSize(2); assertThat(classpath.getLibraries().iterator().next().getClasses()).hasSize(1); assertThat(classpath.getLibraries().iterator().next().getResources()).hasSize(8); URL url = b.getClassLoader().findResource("net/stickycode/deploy/sample/babysteps/run.properties"); assertThat(url).isNotNull(); InputStream i = url.openStream(); assertThat(i).isNotNull(); assertThat(new BufferedReader(new InputStreamReader(i)).readLine()).isEqualTo("run=running is step 3"); Enumeration<URL> e = b.getClassLoader().findResources("net/stickycode/deploy/sample/babysteps/run.properties"); assertThat(e.hasMoreElements()).isTrue(); assertThat(e.nextElement()).isNotNull(); assertThat(e.hasMoreElements()).isFalse(); Enumeration<URL> manifests = b.getClassLoader().findResources("net/stickycode/deploy/sample/duplicate.properties"); assertThat(manifests.hasMoreElements()).isTrue(); assertThat(manifests.nextElement()).isNotNull(); assertThat(manifests.hasMoreElements()).isTrue(); assertThat(manifests.nextElement()).isNotNull(); assertThat(manifests.hasMoreElements()).isFalse(); assertThat(b.getClassLoader().findResource("nothing/here")).isNull(); } @Test public void lookingUpClasses() throws IOException, ClassNotFoundException { File file = new File("src/test/samples/sticky-deployer-sample-2jar-1.2-sample.jar"); StickyClasspath classpath = new ZipScanningStickyClasspath().loadZip(file); StickyEmbedder b = new StickyEmbedder(); b.initialise(new URLClassLoader(new URL[] { new URL("file://" + file.getAbsolutePath()) }, ClassLoader.getSystemClassLoader()), classpath); assertThat(classpath.getLibraries()).hasSize(2); assertThat(classpath.getLibraries().iterator().next().getClasses()).hasSize(1); assertThat(classpath.getLibraries().iterator().next().getResources()).hasSize(8); Class<?> type = b.getClassLoader().findClass("net.stickycode.deploy.sample.helloworld.HelloWorld"); assertThat(type.getSimpleName()).isEqualTo("HelloWorld"); } @Test(expected = ClassNotFoundException.class) public void classNotFound() throws IOException, ClassNotFoundException { File file = new File("src/test/samples/sticky-deployer-sample-2jar-1.2-sample.jar"); StickyClasspath classpath = new ZipScanningStickyClasspath().loadZip(file); StickyEmbedder b = new StickyEmbedder(); b.initialise(new URLClassLoader(new URL[] { new URL("file://" + file.getAbsolutePath()) }, ClassLoader.getSystemClassLoader()), classpath); assertThat(classpath.getLibraries()).hasSize(2); assertThat(classpath.getLibraries().iterator().next().getClasses()).hasSize(1); assertThat(classpath.getLibraries().iterator().next().getResources()).hasSize(8); b.getClassLoader().findClass("net.stickycode.deploy.sample.helloworld.HelloWorldNotHere"); } }
{ "content_hash": "6d1efddab3d27d81638383401f0fca6b", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 143, "avg_line_length": 44.94392523364486, "alnum_prop": 0.7361197754210854, "repo_name": "tectronics/stickycode", "id": "720558e87256fe27f805ed8ce80d41702da2c47f", "size": "5528", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "net.stickycode.deploy/sticky-deployer-embedded/src/test/java/net/stickycode/deploy/bootstrap/BootstrapFunctionalTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "126" }, { "name": "Java", "bytes": "1935493" }, { "name": "Shell", "bytes": "23016" } ], "symlink_target": "" }
<component name="libraryTable"> <library name="SBT: org.scala-tools.testing:test-interface:0.5"> <CLASSES> <root url="jar://$USER_HOME$/.ivy2/cache/org.scala-tools.testing/test-interface/jars/test-interface-0.5.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component>
{ "content_hash": "0e95221e211fc218074f406010680b98", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 119, "avg_line_length": 33.888888888888886, "alnum_prop": 0.6557377049180327, "repo_name": "jarekratajski/paintscreen", "id": "3a84d872dfdd54d76f2dd1c5c7aada5e9867d758", "size": "305", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "server/.idea/libraries/SBT__org_scala_tools_testing_test_interface_0_5.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11316" }, { "name": "JavaScript", "bytes": "17357" }, { "name": "Scala", "bytes": "16360" } ], "symlink_target": "" }
#ifndef LIBOPENCM3_USB_DESC #define LIBOPENCM3_USB_DESC /* Descriptor types */ #define USB_DT_DEVICE 0x01 #define USB_DT_CONF 0x02 #define USB_DT_STRING 0x03 #define USB_DT_INTERFACE 0x04 #define USB_DT_ENDPOINT 0x05 struct usb_desc_head { u8 length; /* Descriptor size 0x012 */ u8 type; /* Descriptor type ID */ }; struct usb_device_desc { struct usb_desc_head h; /* Size 0x12, ID 0x01 */ u16 bcd_usb; /* USB Version */ u8 class; /* Device class */ u8 sub_class; /* Subclass code */ u8 protocol; /* Protocol code */ u8 max_psize; /* Maximum packet size -> 64bytes */ u16 vendor; /* Vendor number */ u16 product; /* Device number */ u16 bcd_dev; /* Device version */ u8 man_desc; /* Index of manufacturer string desc */ u8 prod_desc; /* Index of product string desc */ u8 sn_desc; /* Index of serial number string desc */ u8 num_conf; /* Number of possible configurations */ }; struct usb_conf_desc_header { struct usb_desc_head h; /* Size 0x09, Id 0x02 */ u16 tot_leng; /* Total length of data */ u8 num_int; /* Number of interfaces */ u8 conf_val; /* Configuration selector */ u8 conf_desc; /* Index of conf string desc */ u8 attr; /* Attribute bitmap: * 7 : Bus powered * 6 : Self powered * 5 : Remote wakeup * 4..0 : Reserved -> 0000 */ u8 max_power; /* Maximum power consumption in 2mA steps */ }; struct usb_int_desc_header { struct usb_desc_head h; /* Size 0x09, Id 0x04 */ u8 iface_num; /* Interface id number */ u8 alt_setting; /* Alternative setting selector */ u8 num_endp; /* Endpoints used */ u8 class; /* Interface class */ u8 sub_class; /* Subclass code */ u8 protocol; /* Protocol code */ u8 iface_desc; /* Index of interface string desc */ }; struct usb_ep_desc { struct usb_desc_head h; /* Size 0x07, Id 0x05 */ u8 ep_addr; /* Endpoint address: 0..3 : Endpoint Number 4..6 : Reserved -> 0 7 : Direction 0=out 1=in */ u8 ep_attr; /* Endpoint attributes */ u16 max_psize; /* Maximum packet size -> 64bytes */ u8 interval; /* Interval for polling endpoint data. Ignored for bulk & control endpoints. */ }; struct usb_conf_desc { struct usb_conf_desc_header cdh; struct usb_int_desc_header idh; struct usb_ep_desc ep[]; }; struct usb_string_desc { struct usb_desc_head h; /* Size > 0x02, Id 0x03 */ u16 string[]; /* String UTF16 encoded */ }; #endif
{ "content_hash": "31f1aad937858da0b37930b11a07e0b3", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 60, "avg_line_length": 28.928571428571427, "alnum_prop": 0.6390946502057613, "repo_name": "GliderWinchCommons/mc", "id": "da99bb025ec8e8e3ee53492902b59b87486840c4", "size": "3196", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "sw_discoveryf4/trunk/lib/libopencm3/stm32/f1/usb_desc.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "205365" }, { "name": "C", "bytes": "4672211" }, { "name": "C++", "bytes": "133286" }, { "name": "Makefile", "bytes": "54903" }, { "name": "PHP", "bytes": "46" }, { "name": "Shell", "bytes": "14562" } ], "symlink_target": "" }
layout: tutorial section-type: tutorial title: tutorial --- ##Tutorial
{ "content_hash": "7643d2cef1cb1d125e79791afd732eb5", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 22, "avg_line_length": 14.2, "alnum_prop": 0.7605633802816901, "repo_name": "Parsion/parsion", "id": "30b6a0835742565f1a70d56f18e64455d68697fa", "size": "75", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "en/tutorial/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11764" }, { "name": "HTML", "bytes": "25759" }, { "name": "Ruby", "bytes": "1720" }, { "name": "Shell", "bytes": "58" } ], "symlink_target": "" }
package toml import ( "bytes" "encoding/json" "fmt" "reflect" "testing" "time" "github.com/davecgh/go-spew/spew" ) func testgenInvalid(t *testing.T, input string) { t.Logf("Input TOML:\n%s", input) tree, err := Load(input) if err != nil { return } typedTree := testgenTranslate(*tree) buf := new(bytes.Buffer) if err := json.NewEncoder(buf).Encode(typedTree); err != nil { return } t.Fatalf("test did not fail. resulting tree:\n%s", buf.String()) } func testgenValid(t *testing.T, input string, jsonRef string) { t.Logf("Input TOML:\n%s", input) tree, err := Load(input) if err != nil { t.Fatalf("failed parsing toml: %s", err) } typedTree := testgenTranslate(*tree) buf := new(bytes.Buffer) if err := json.NewEncoder(buf).Encode(typedTree); err != nil { t.Fatalf("failed translating to JSON: %s", err) } var jsonTest interface{} if err := json.NewDecoder(buf).Decode(&jsonTest); err != nil { t.Logf("translated JSON:\n%s", buf.String()) t.Fatalf("failed decoding translated JSON: %s", err) } var jsonExpected interface{} if err := json.NewDecoder(bytes.NewBufferString(jsonRef)).Decode(&jsonExpected); err != nil { t.Logf("reference JSON:\n%s", jsonRef) t.Fatalf("failed decoding reference JSON: %s", err) } if !reflect.DeepEqual(jsonExpected, jsonTest) { t.Logf("Diff:\n%s", spew.Sdump(jsonExpected, jsonTest)) t.Fatal("parsed TOML tree is different than expected structure") } } func testgenTranslate(tomlData interface{}) interface{} { switch orig := tomlData.(type) { case map[string]interface{}: typed := make(map[string]interface{}, len(orig)) for k, v := range orig { typed[k] = testgenTranslate(v) } return typed case *Tree: return testgenTranslate(*orig) case Tree: keys := orig.Keys() typed := make(map[string]interface{}, len(keys)) for _, k := range keys { typed[k] = testgenTranslate(orig.GetPath([]string{k})) } return typed case []*Tree: typed := make([]map[string]interface{}, len(orig)) for i, v := range orig { typed[i] = testgenTranslate(v).(map[string]interface{}) } return typed case []map[string]interface{}: typed := make([]map[string]interface{}, len(orig)) for i, v := range orig { typed[i] = testgenTranslate(v).(map[string]interface{}) } return typed case []interface{}: typed := make([]interface{}, len(orig)) for i, v := range orig { typed[i] = testgenTranslate(v) } return testgenTag("array", typed) case time.Time: return testgenTag("datetime", orig.Format("2006-01-02T15:04:05Z")) case bool: return testgenTag("bool", fmt.Sprintf("%v", orig)) case int64: return testgenTag("integer", fmt.Sprintf("%d", orig)) case float64: return testgenTag("float", fmt.Sprintf("%v", orig)) case string: return testgenTag("string", orig) } panic(fmt.Sprintf("Unknown type: %T", tomlData)) } func testgenTag(typeName string, data interface{}) map[string]interface{} { return map[string]interface{}{ "type": typeName, "value": data, } }
{ "content_hash": "8b32268dd07c5b4c541edd0cad26e3f0", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 94, "avg_line_length": 25.5, "alnum_prop": 0.6660019940179461, "repo_name": "anpingli/origin", "id": "eef9b9faa892e306fdd5b77f32a3b17b5df29f8d", "size": "3060", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/github.com/pelletier/go-toml/toml_testgen_support_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "921" }, { "name": "DIGITAL Command Language", "bytes": "117" }, { "name": "Dockerfile", "bytes": "1668" }, { "name": "Go", "bytes": "11764612" }, { "name": "Makefile", "bytes": "8555" }, { "name": "Python", "bytes": "16765" }, { "name": "Shell", "bytes": "770466" } ], "symlink_target": "" }
nlglib\.realisation package =========================== Subpackages ----------- .. toctree:: nlglib.realisation.simplenlg Submodules ---------- nlglib\.realisation\.basic module --------------------------------- .. automodule:: nlglib.realisation.basic :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: nlglib.realisation :members: :undoc-members: :show-inheritance:
{ "content_hash": "b026385dc20cc575aeb9992fe082252f", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 40, "avg_line_length": 15.413793103448276, "alnum_prop": 0.5525727069351231, "repo_name": "roman-kutlak/nlglib", "id": "abb69cee4f8ac60d757af77534f51407bac40258", "size": "447", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/nlglib.realisation.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "264797" } ], "symlink_target": "" }
<?xml version="1.0" ?> <!-- 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. --> <Root> <TestCase name="testExplainDataStreamScan[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithAgg[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(EXPR$0=[$1]) +- LogicalAggregate(group=[{0}], EXPR$0=[COUNT()]) +- LogicalProject(a=[$0]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == Calc(select=[EXPR$0], changelogMode=[I,UA]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- GroupAggregate(groupBy=[a], select=[a, COUNT(*) AS EXPR$0], changelogMode=[I,UA]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Exchange(distribution=[hash[a]], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Calc(select=[a], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : Calc(select=[a]) ship_strategy : FORWARD : Operator content : GroupAggregate(groupBy=[a], select=[a, COUNT(*) AS EXPR$0]) ship_strategy : HASH : Operator content : Calc(select=[EXPR$0]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainDataStreamScan[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainTableSourceScan[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c)]]]) == Optimized Logical Plan == LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable, source: [TestTableSource(a, b, c)]], fields=[a, b, c]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainTableSourceScan[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c)]]]) == Optimized Logical Plan == LegacyTableSourceScan(table=[[default_catalog, default_database, MyTable, source: [TestTableSource(a, b, c)]]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable, source: [TestTableSource(a, b, c)]], fields=[a, b, c]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithAgg[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(EXPR$0=[$1]) +- LogicalAggregate(group=[{0}], EXPR$0=[COUNT()]) +- LogicalProject(a=[$0]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == Calc(select=[EXPR$0]) +- GroupAggregate(groupBy=[a], select=[a, COUNT(*) AS EXPR$0]) +- Exchange(distribution=[hash[a]]) +- Calc(select=[a]) +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : Calc(select=[a]) ship_strategy : FORWARD : Operator content : GroupAggregate(groupBy=[a], select=[a, COUNT(*) AS EXPR$0]) ship_strategy : HASH : Operator content : Calc(select=[EXPR$0]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithFilter[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalFilter(condition=[=(MOD($0, 2), 0)]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == Calc(select=[a, b, c], where=[=(MOD(a, 2), 0)]) +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : Calc(select=[a, b, c], where=[((a MOD 2) = 0)]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithFilter[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalFilter(condition=[=(MOD($0, 2), 0)]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == Calc(select=[a, b, c], where=[=(MOD(a, 2), 0)], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : Calc(select=[a, b, c], where=[((a MOD 2) = 0)]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithJoin[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(a=[$0], b=[$1], c=[$2], e=[$4], f=[$5]) +- LogicalFilter(condition=[=($0, $3)]) +- LogicalJoin(condition=[true], joinType=[inner]) :- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable2]]) == Optimized Logical Plan == Calc(select=[a, b, c, e, f]) +- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey]) :- Exchange(distribution=[hash[a]]) : +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c]) +- Exchange(distribution=[hash[d]]) +- DataStreamScan(table=[[default_catalog, default_database, MyTable2]], fields=[d, e, f]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable2], fields=[d, e, f]) ship_strategy : FORWARD : Operator content : Join(joinType=[InnerJoin], where=[(a = d)], select=[a, b, c, d, e, f], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey]) ship_strategy : HASH : Operator content : Calc(select=[a, b, c, e, f]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithUnion[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalUnion(all=[true]) :- LogicalProject(a=[$0], b=[$1], c=[$2]) : +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) +- LogicalProject(d=[$0], e=[$1], f=[$2]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable2]]) == Optimized Logical Plan == Union(all=[true], union=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} :- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- DataStreamScan(table=[[default_catalog, default_database, MyTable2]], fields=[d, e, f], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} == Physical Execution Plan == : Data Source content : Source: Collection Source : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable2], fields=[d, e, f]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithJoin[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalProject(a=[$0], b=[$1], c=[$2], e=[$4], f=[$5]) +- LogicalFilter(condition=[=($0, $3)]) +- LogicalJoin(condition=[true], joinType=[inner]) :- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable2]]) == Optimized Logical Plan == Calc(select=[a, b, c, e, f], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Join(joinType=[InnerJoin], where=[=(a, d)], select=[a, b, c, d, e, f], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} :- Exchange(distribution=[hash[a]], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} : +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Exchange(distribution=[hash[d]], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- DataStreamScan(table=[[default_catalog, default_database, MyTable2]], fields=[d, e, f], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} == Physical Execution Plan == : Data Source content : Source: Collection Source : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable2], fields=[d, e, f]) ship_strategy : FORWARD : Operator content : Join(joinType=[InnerJoin], where=[(a = d)], select=[a, b, c, d, e, f], leftInputSpec=[NoUniqueKey], rightInputSpec=[NoUniqueKey]) ship_strategy : HASH : Operator content : Calc(select=[a, b, c, e, f]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithMultiSinks[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalLegacySink(name=[`default_catalog`.`default_database`.`upsertSink1`], fields=[a, cnt]) +- LogicalProject(a=[$0], cnt=[$1]) +- LogicalFilter(condition=[>($1, 10)]) +- LogicalAggregate(group=[{0}], cnt=[COUNT()]) +- LogicalProject(a=[$0]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) LogicalLegacySink(name=[`default_catalog`.`default_database`.`upsertSink2`], fields=[a, cnt]) +- LogicalProject(a=[$0], cnt=[$1]) +- LogicalFilter(condition=[<($1, 10)]) +- LogicalAggregate(group=[{0}], cnt=[COUNT()]) +- LogicalProject(a=[$0]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == GroupAggregate(groupBy=[a], select=[a, COUNT(*) AS cnt], reuse_id=[1]) +- Exchange(distribution=[hash[a]]) +- Calc(select=[a]) +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c]) LegacySink(name=[`default_catalog`.`default_database`.`upsertSink1`], fields=[a, cnt]) +- Calc(select=[a, cnt], where=[>(cnt, 10)]) +- Reused(reference_id=[1]) LegacySink(name=[`default_catalog`.`default_database`.`upsertSink2`], fields=[a, cnt]) +- Calc(select=[a, cnt], where=[<(cnt, 10)]) +- Reused(reference_id=[1]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : Calc(select=[a]) ship_strategy : FORWARD : Operator content : GroupAggregate(groupBy=[a], select=[a, COUNT(*) AS cnt]) ship_strategy : HASH : Operator content : Calc(select=[a, cnt], where=[(cnt > 10)]) ship_strategy : FORWARD : Operator content : SinkConversionToTuple2 ship_strategy : FORWARD : Operator content : Map ship_strategy : FORWARD : Operator content : Calc(select=[a, cnt], where=[(cnt < 10)]) ship_strategy : FORWARD : Operator content : SinkConversionToTuple2 ship_strategy : FORWARD : Operator content : Map ship_strategy : FORWARD : Data Sink content : Sink: TestingUpsertTableSink(keys=(0)) ship_strategy : FORWARD : Data Sink content : Sink: TestingUpsertTableSink(keys=(0)) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithMultiSinks[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalLegacySink(name=[`default_catalog`.`default_database`.`upsertSink1`], fields=[a, cnt]) +- LogicalProject(a=[$0], cnt=[$1]) +- LogicalFilter(condition=[>($1, 10)]) +- LogicalAggregate(group=[{0}], cnt=[COUNT()]) +- LogicalProject(a=[$0]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) LogicalLegacySink(name=[`default_catalog`.`default_database`.`upsertSink2`], fields=[a, cnt]) +- LogicalProject(a=[$0], cnt=[$1]) +- LogicalFilter(condition=[<($1, 10)]) +- LogicalAggregate(group=[{0}], cnt=[COUNT()]) +- LogicalProject(a=[$0]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == GroupAggregate(groupBy=[a], select=[a, COUNT(*) AS cnt], changelogMode=[I,UB,UA], reuse_id=[1]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Exchange(distribution=[hash[a]], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Calc(select=[a], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} LegacySink(name=[`default_catalog`.`default_database`.`upsertSink1`], fields=[a, cnt], changelogMode=[NONE]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Calc(select=[a, cnt], where=[>(cnt, 10)], changelogMode=[I,UB,UA]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Reused(reference_id=[1]) LegacySink(name=[`default_catalog`.`default_database`.`upsertSink2`], fields=[a, cnt], changelogMode=[NONE]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Calc(select=[a, cnt], where=[<(cnt, 10)], changelogMode=[I,UB,UA]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Reused(reference_id=[1]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : Calc(select=[a]) ship_strategy : FORWARD : Operator content : GroupAggregate(groupBy=[a], select=[a, COUNT(*) AS cnt]) ship_strategy : HASH : Operator content : Calc(select=[a, cnt], where=[(cnt > 10)]) ship_strategy : FORWARD : Operator content : SinkConversionToTuple2 ship_strategy : FORWARD : Operator content : Map ship_strategy : FORWARD : Operator content : Calc(select=[a, cnt], where=[(cnt < 10)]) ship_strategy : FORWARD : Operator content : SinkConversionToTuple2 ship_strategy : FORWARD : Operator content : Map ship_strategy : FORWARD : Data Sink content : Sink: TestingUpsertTableSink(keys=(0)) ship_strategy : FORWARD : Data Sink content : Sink: TestingUpsertTableSink(keys=(0)) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithSingleSink[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalLegacySink(name=[`default_catalog`.`default_database`.`appendSink`], fields=[a, b, c]) +- LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalFilter(condition=[>($0, 10)]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == LegacySink(name=[`default_catalog`.`default_database`.`appendSink`], fields=[a, b, c]) +- Calc(select=[a, b, c], where=[>(a, 10)]) +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : Calc(select=[a, b, c], where=[(a > 10)]) ship_strategy : FORWARD : Operator content : SinkConversionToRow ship_strategy : FORWARD : Data Sink content : Sink: TestingAppendTableSink ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithSingleSink[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalLegacySink(name=[`default_catalog`.`default_database`.`appendSink`], fields=[a, b, c]) +- LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalFilter(condition=[>($0, 10)]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == LegacySink(name=[`default_catalog`.`default_database`.`appendSink`], fields=[a, b, c], changelogMode=[NONE]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Calc(select=[a, b, c], where=[>(a, 10)], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : Calc(select=[a, b, c], where=[(a > 10)]) ship_strategy : FORWARD : Operator content : SinkConversionToRow ship_strategy : FORWARD : Data Sink content : Sink: TestingAppendTableSink ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithSort[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalSort(sort0=[$0], dir0=[ASC-nulls-first], fetch=[5]) +- LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == SortLimit(orderBy=[a ASC], offset=[0], fetch=[5], strategy=[AppendFastStrategy]) +- Exchange(distribution=[single]) +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : SortLimit(orderBy=[a ASC], offset=[0], fetch=[5], strategy=[AppendFastStrategy]) ship_strategy : GLOBAL ]]> </Resource> </TestCase> <TestCase name="testExplainWithSort[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalSort(sort0=[$0], dir0=[ASC-nulls-first], fetch=[5]) +- LogicalProject(a=[$0], b=[$1], c=[$2]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) == Optimized Logical Plan == SortLimit(orderBy=[a ASC], offset=[0], fetch=[5], strategy=[AppendFastStrategy], changelogMode=[I,UA,D]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Exchange(distribution=[single], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} == Physical Execution Plan == : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : SortLimit(orderBy=[a ASC], offset=[0], fetch=[5], strategy=[AppendFastStrategy]) ship_strategy : GLOBAL ]]> </Resource> </TestCase> <TestCase name="testMiniBatchIntervalInfer[extended=true]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalLegacySink(name=[`default_catalog`.`default_database`.`appendSink1`], fields=[a, b]) +- LogicalProject(id1=[$0], EXPR$1=[$2]) +- LogicalAggregate(group=[{0, 1}], EXPR$1=[LISTAGG($2, $3)]) +- LogicalProject(id1=[$0], $f1=[$TUMBLE($2, 8000:INTERVAL SECOND)], text=[$1], $f3=[_UTF-16LE'#']) +- LogicalFilter(condition=[AND(=($0, $3), >($2, -($7, 300000:INTERVAL MINUTE)), <($2, +($7, 180000:INTERVAL MINUTE)))]) +- LogicalJoin(condition=[true], joinType=[inner]) :- LogicalWatermarkAssigner(rowtime=[rowtime], watermark=[-($2, 0:INTERVAL MILLISECOND)]) : +- LogicalTableScan(table=[[default_catalog, default_database, T1]]) +- LogicalWatermarkAssigner(rowtime=[rowtime], watermark=[-($4, 0:INTERVAL MILLISECOND)]) +- LogicalTableScan(table=[[default_catalog, default_database, T2]]) LogicalLegacySink(name=[`default_catalog`.`default_database`.`appendSink2`], fields=[a, b]) +- LogicalProject(id1=[$0], EXPR$1=[$2]) +- LogicalAggregate(group=[{0, 1}], EXPR$1=[LISTAGG($2, $3)]) +- LogicalProject(id1=[$0], $f1=[HOP($2, 12000:INTERVAL SECOND, 6000:INTERVAL SECOND)], text=[$1], $f3=[_UTF-16LE'*']) +- LogicalFilter(condition=[AND(=($0, $3), >($2, -($7, 300000:INTERVAL MINUTE)), <($2, +($7, 180000:INTERVAL MINUTE)))]) +- LogicalJoin(condition=[true], joinType=[inner]) :- LogicalWatermarkAssigner(rowtime=[rowtime], watermark=[-($2, 0:INTERVAL MILLISECOND)]) : +- LogicalTableScan(table=[[default_catalog, default_database, T1]]) +- LogicalWatermarkAssigner(rowtime=[rowtime], watermark=[-($4, 0:INTERVAL MILLISECOND)]) +- LogicalTableScan(table=[[default_catalog, default_database, T2]]) == Optimized Logical Plan == IntervalJoin(joinType=[InnerJoin], windowBounds=[isRowTime=true, leftLowerBound=-299999, leftUpperBound=179999, leftTimeIndex=2, rightTimeIndex=4], where=[AND(=(id1, id2), >(CAST(rowtime), -(CAST(rowtime0), 300000:INTERVAL MINUTE)), <(CAST(rowtime), +(CAST(rowtime0), 180000:INTERVAL MINUTE)))], select=[id1, text, rowtime, id2, cnt, name, goods, rowtime0], changelogMode=[I], reuse_id=[1]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} :- Exchange(distribution=[hash[id1]], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} : +- WatermarkAssigner(rowtime=[rowtime], watermark=[-(rowtime, 0:INTERVAL MILLISECOND)], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} : +- DataStreamScan(table=[[default_catalog, default_database, T1]], fields=[id1, text, rowtime], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Exchange(distribution=[hash[id2]], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- WatermarkAssigner(rowtime=[rowtime], watermark=[-(rowtime, 0:INTERVAL MILLISECOND)], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- DataStreamScan(table=[[default_catalog, default_database, T2]], fields=[id2, cnt, name, goods, rowtime], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} LegacySink(name=[`default_catalog`.`default_database`.`appendSink1`], fields=[a, b], changelogMode=[NONE]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- GroupWindowAggregate(groupBy=[id1], window=[TumblingGroupWindow('w$, rowtime, 8000)], select=[id1, LISTAGG(text, $f3) AS EXPR$1], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Exchange(distribution=[hash[id1]], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Calc(select=[id1, rowtime, text, _UTF-16LE'#' AS $f3], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Reused(reference_id=[1]) LegacySink(name=[`default_catalog`.`default_database`.`appendSink2`], fields=[a, b], changelogMode=[NONE]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- GroupWindowAggregate(groupBy=[id1], window=[SlidingGroupWindow('w$, rowtime, 6000, 12000)], select=[id1, LISTAGG(text, $f3) AS EXPR$1], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Exchange(distribution=[hash[id1]], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Calc(select=[id1, rowtime, text, _UTF-16LE'*' AS $f3], changelogMode=[I]): rowcount = , cumulative cost = {rows, cpu, io, network, memory} +- Reused(reference_id=[1]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.T1], fields=[id1, text, rowtime]) ship_strategy : FORWARD : Operator content : WatermarkAssigner(rowtime=[rowtime], watermark=[(rowtime - 0:INTERVAL MILLISECOND)]) ship_strategy : FORWARD : Operator content : SourceConversion(table=[default_catalog.default_database.T2], fields=[id2, cnt, name, goods, rowtime]) ship_strategy : FORWARD : Operator content : WatermarkAssigner(rowtime=[rowtime], watermark=[(rowtime - 0:INTERVAL MILLISECOND)]) ship_strategy : FORWARD : Operator content : IntervalJoin(joinType=[InnerJoin], windowBounds=[isRowTime=true, leftLowerBound=-299999, leftUpperBound=179999, leftTimeIndex=2, rightTimeIndex=4], where=[((id1 = id2) AND (CAST(rowtime) > (CAST(rowtime0) - 300000:INTERVAL MINUTE)) AND (CAST(rowtime) < (CAST(rowtime0) + 180000:INTERVAL MINUTE)))], select=[id1, text, rowtime, id2, cnt, name, goods, rowtime0]) ship_strategy : HASH : Operator content : Calc(select=[id1, rowtime, text, _UTF-16LE'#' AS $f3]) ship_strategy : FORWARD : Operator content : GroupWindowAggregate(groupBy=[id1], window=[TumblingGroupWindow('w$, rowtime, 8000)], select=[id1, LISTAGG(text, $f3) AS EXPR$1]) ship_strategy : HASH : Operator content : SinkConversionToRow ship_strategy : FORWARD : Operator content : Calc(select=[id1, rowtime, text, _UTF-16LE'*' AS $f3]) ship_strategy : FORWARD : Operator content : GroupWindowAggregate(groupBy=[id1], window=[SlidingGroupWindow('w$, rowtime, 6000, 12000)], select=[id1, LISTAGG(text, $f3) AS EXPR$1]) ship_strategy : HASH : Operator content : SinkConversionToRow ship_strategy : FORWARD : Data Sink content : Sink: TestingAppendTableSink ship_strategy : FORWARD : Data Sink content : Sink: TestingAppendTableSink ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testExplainWithUnion[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalUnion(all=[true]) :- LogicalProject(a=[$0], b=[$1], c=[$2]) : +- LogicalTableScan(table=[[default_catalog, default_database, MyTable1]]) +- LogicalProject(d=[$0], e=[$1], f=[$2]) +- LogicalTableScan(table=[[default_catalog, default_database, MyTable2]]) == Optimized Logical Plan == Union(all=[true], union=[a, b, c]) :- DataStreamScan(table=[[default_catalog, default_database, MyTable1]], fields=[a, b, c]) +- DataStreamScan(table=[[default_catalog, default_database, MyTable2]], fields=[d, e, f]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable1], fields=[a, b, c]) ship_strategy : FORWARD : Operator content : SourceConversion(table=[default_catalog.default_database.MyTable2], fields=[d, e, f]) ship_strategy : FORWARD ]]> </Resource> </TestCase> <TestCase name="testMiniBatchIntervalInfer[extended=false]"> <Resource name="explain"> <![CDATA[== Abstract Syntax Tree == LogicalLegacySink(name=[`default_catalog`.`default_database`.`appendSink1`], fields=[a, b]) +- LogicalProject(id1=[$0], EXPR$1=[$2]) +- LogicalAggregate(group=[{0, 1}], EXPR$1=[LISTAGG($2, $3)]) +- LogicalProject(id1=[$0], $f1=[$TUMBLE($2, 8000:INTERVAL SECOND)], text=[$1], $f3=[_UTF-16LE'#']) +- LogicalFilter(condition=[AND(=($0, $3), >($2, -($7, 300000:INTERVAL MINUTE)), <($2, +($7, 180000:INTERVAL MINUTE)))]) +- LogicalJoin(condition=[true], joinType=[inner]) :- LogicalWatermarkAssigner(rowtime=[rowtime], watermark=[-($2, 0:INTERVAL MILLISECOND)]) : +- LogicalTableScan(table=[[default_catalog, default_database, T1]]) +- LogicalWatermarkAssigner(rowtime=[rowtime], watermark=[-($4, 0:INTERVAL MILLISECOND)]) +- LogicalTableScan(table=[[default_catalog, default_database, T2]]) LogicalLegacySink(name=[`default_catalog`.`default_database`.`appendSink2`], fields=[a, b]) +- LogicalProject(id1=[$0], EXPR$1=[$2]) +- LogicalAggregate(group=[{0, 1}], EXPR$1=[LISTAGG($2, $3)]) +- LogicalProject(id1=[$0], $f1=[HOP($2, 12000:INTERVAL SECOND, 6000:INTERVAL SECOND)], text=[$1], $f3=[_UTF-16LE'*']) +- LogicalFilter(condition=[AND(=($0, $3), >($2, -($7, 300000:INTERVAL MINUTE)), <($2, +($7, 180000:INTERVAL MINUTE)))]) +- LogicalJoin(condition=[true], joinType=[inner]) :- LogicalWatermarkAssigner(rowtime=[rowtime], watermark=[-($2, 0:INTERVAL MILLISECOND)]) : +- LogicalTableScan(table=[[default_catalog, default_database, T1]]) +- LogicalWatermarkAssigner(rowtime=[rowtime], watermark=[-($4, 0:INTERVAL MILLISECOND)]) +- LogicalTableScan(table=[[default_catalog, default_database, T2]]) == Optimized Logical Plan == IntervalJoin(joinType=[InnerJoin], windowBounds=[isRowTime=true, leftLowerBound=-299999, leftUpperBound=179999, leftTimeIndex=2, rightTimeIndex=4], where=[AND(=(id1, id2), >(CAST(rowtime), -(CAST(rowtime0), 300000:INTERVAL MINUTE)), <(CAST(rowtime), +(CAST(rowtime0), 180000:INTERVAL MINUTE)))], select=[id1, text, rowtime, id2, cnt, name, goods, rowtime0], reuse_id=[1]) :- Exchange(distribution=[hash[id1]]) : +- WatermarkAssigner(rowtime=[rowtime], watermark=[-(rowtime, 0:INTERVAL MILLISECOND)]) : +- DataStreamScan(table=[[default_catalog, default_database, T1]], fields=[id1, text, rowtime]) +- Exchange(distribution=[hash[id2]]) +- WatermarkAssigner(rowtime=[rowtime], watermark=[-(rowtime, 0:INTERVAL MILLISECOND)]) +- DataStreamScan(table=[[default_catalog, default_database, T2]], fields=[id2, cnt, name, goods, rowtime]) LegacySink(name=[`default_catalog`.`default_database`.`appendSink1`], fields=[a, b]) +- GroupWindowAggregate(groupBy=[id1], window=[TumblingGroupWindow('w$, rowtime, 8000)], select=[id1, LISTAGG(text, $f3) AS EXPR$1]) +- Exchange(distribution=[hash[id1]]) +- Calc(select=[id1, rowtime, text, _UTF-16LE'#' AS $f3]) +- Reused(reference_id=[1]) LegacySink(name=[`default_catalog`.`default_database`.`appendSink2`], fields=[a, b]) +- GroupWindowAggregate(groupBy=[id1], window=[SlidingGroupWindow('w$, rowtime, 6000, 12000)], select=[id1, LISTAGG(text, $f3) AS EXPR$1]) +- Exchange(distribution=[hash[id1]]) +- Calc(select=[id1, rowtime, text, _UTF-16LE'*' AS $f3]) +- Reused(reference_id=[1]) == Physical Execution Plan == : Data Source content : Source: Collection Source : Data Source content : Source: Collection Source : Operator content : SourceConversion(table=[default_catalog.default_database.T1], fields=[id1, text, rowtime]) ship_strategy : FORWARD : Operator content : WatermarkAssigner(rowtime=[rowtime], watermark=[(rowtime - 0:INTERVAL MILLISECOND)]) ship_strategy : FORWARD : Operator content : SourceConversion(table=[default_catalog.default_database.T2], fields=[id2, cnt, name, goods, rowtime]) ship_strategy : FORWARD : Operator content : WatermarkAssigner(rowtime=[rowtime], watermark=[(rowtime - 0:INTERVAL MILLISECOND)]) ship_strategy : FORWARD : Operator content : IntervalJoin(joinType=[InnerJoin], windowBounds=[isRowTime=true, leftLowerBound=-299999, leftUpperBound=179999, leftTimeIndex=2, rightTimeIndex=4], where=[((id1 = id2) AND (CAST(rowtime) > (CAST(rowtime0) - 300000:INTERVAL MINUTE)) AND (CAST(rowtime) < (CAST(rowtime0) + 180000:INTERVAL MINUTE)))], select=[id1, text, rowtime, id2, cnt, name, goods, rowtime0]) ship_strategy : HASH : Operator content : Calc(select=[id1, rowtime, text, _UTF-16LE'#' AS $f3]) ship_strategy : FORWARD : Operator content : GroupWindowAggregate(groupBy=[id1], window=[TumblingGroupWindow('w$, rowtime, 8000)], select=[id1, LISTAGG(text, $f3) AS EXPR$1]) ship_strategy : HASH : Operator content : SinkConversionToRow ship_strategy : FORWARD : Operator content : Calc(select=[id1, rowtime, text, _UTF-16LE'*' AS $f3]) ship_strategy : FORWARD : Operator content : GroupWindowAggregate(groupBy=[id1], window=[SlidingGroupWindow('w$, rowtime, 6000, 12000)], select=[id1, LISTAGG(text, $f3) AS EXPR$1]) ship_strategy : HASH : Operator content : SinkConversionToRow ship_strategy : FORWARD : Data Sink content : Sink: TestingAppendTableSink ship_strategy : FORWARD : Data Sink content : Sink: TestingAppendTableSink ship_strategy : FORWARD ]]> </Resource> </TestCase> </Root>
{ "content_hash": "99f0d81d16c808c9175c39d5678dc0b7", "timestamp": "", "source": "github", "line_count": 883, "max_line_length": 455, "avg_line_length": 42.9445073612684, "alnum_prop": 0.660996835443038, "repo_name": "tzulitai/flink", "id": "569e5fccc397f9f5ac483b5091f6242398380d30", "size": "37920", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "flink-table/flink-table-planner-blink/src/test/resources/org/apache/flink/table/api/stream/ExplainTest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5718" }, { "name": "CSS", "bytes": "57936" }, { "name": "Clojure", "bytes": "90539" }, { "name": "Dockerfile", "bytes": "10807" }, { "name": "FreeMarker", "bytes": "11389" }, { "name": "HTML", "bytes": "224454" }, { "name": "Java", "bytes": "46348883" }, { "name": "JavaScript", "bytes": "1829" }, { "name": "Makefile", "bytes": "5134" }, { "name": "Python", "bytes": "731653" }, { "name": "Scala", "bytes": "12432812" }, { "name": "Shell", "bytes": "463267" }, { "name": "TypeScript", "bytes": "243702" } ], "symlink_target": "" }
package me.panavtec.cleancontacts.repository.contacts.datasources.exceptions; public class InvalidCacheException extends Exception { }
{ "content_hash": "d72ff2ccd989ee2a382b724e7676e330", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 77, "avg_line_length": 34, "alnum_prop": 0.8602941176470589, "repo_name": "0359xiaodong/Clean-Contacts", "id": "34c5f43dfadf522734ccb8537a7b4df5d21c7d4b", "size": "136", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "repository/src/main/java/me/panavtec/cleancontacts/repository/contacts/datasources/exceptions/InvalidCacheException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "136586" } ], "symlink_target": "" }
package views.html package account import lila.api.Context import lila.app.templating.Environment._ import lila.app.ui.ScalatagsTemplate._ import controllers.routes object username { def apply(u: lila.user.User, form: play.api.data.Form[_])(implicit ctx: Context) = account.layout( title = s"${u.username} - ${trans.editProfile.txt()}", active = "username" ) { div(cls := "account box box-pad")( h1(trans.changeUsername()), standardFlash(), postForm(cls := "form3", action := routes.Account.usernameApply)( form3.globalError(form), form3.group(form("username"), trans.username(), help = trans.changeUsernameDescription().some)( form3.input(_)(autofocus, required, autocomplete := "username") ), form3.action(form3.submit(trans.apply())) ) ) } }
{ "content_hash": "bec9010059f20a84cff65a2a577c0a87", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 105, "avg_line_length": 30.03448275862069, "alnum_prop": 0.6291618828932262, "repo_name": "luanlv/lila", "id": "37811b0e372ccd1b52997291c26aadbeaf4ee71e", "size": "871", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/views/account/username.scala", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "849" }, { "name": "CSS", "bytes": "228239" }, { "name": "Cycript", "bytes": "3701" }, { "name": "Emacs Lisp", "bytes": "31342" }, { "name": "Erlang", "bytes": "19825" }, { "name": "Fancy", "bytes": "119" }, { "name": "GAP", "bytes": "11334" }, { "name": "GLSL", "bytes": "2434" }, { "name": "HTML", "bytes": "332219" }, { "name": "Hy", "bytes": "20591" }, { "name": "Io", "bytes": "4943" }, { "name": "Java", "bytes": "21183" }, { "name": "JavaScript", "bytes": "434326" }, { "name": "Makefile", "bytes": "15207" }, { "name": "Mathematica", "bytes": "18454" }, { "name": "NewLisp", "bytes": "19130" }, { "name": "OCaml", "bytes": "1709" }, { "name": "Perl6", "bytes": "19794" }, { "name": "PostScript", "bytes": "2604" }, { "name": "Python", "bytes": "1959" }, { "name": "Ruby", "bytes": "31020" }, { "name": "Scala", "bytes": "1673987" }, { "name": "Shell", "bytes": "9946" }, { "name": "Slash", "bytes": "18065" }, { "name": "Smalltalk", "bytes": "18999" }, { "name": "SystemVerilog", "bytes": "17827" } ], "symlink_target": "" }
 #pragma once #include <aws/alexaforbusiness/AlexaForBusiness_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace AlexaForBusiness { namespace Model { enum class DeviceEventType { NOT_SET, CONNECTION_STATUS, DEVICE_STATUS }; namespace DeviceEventTypeMapper { AWS_ALEXAFORBUSINESS_API DeviceEventType GetDeviceEventTypeForName(const Aws::String& name); AWS_ALEXAFORBUSINESS_API Aws::String GetNameForDeviceEventType(DeviceEventType value); } // namespace DeviceEventTypeMapper } // namespace Model } // namespace AlexaForBusiness } // namespace Aws
{ "content_hash": "5357a2b3b07a2c880ac1fd6eb56ac8cc", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 92, "avg_line_length": 21.607142857142858, "alnum_prop": 0.7834710743801653, "repo_name": "awslabs/aws-sdk-cpp", "id": "b6d14772e64bbba5131675d1ef7b630cc6437a66", "size": "724", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "aws-cpp-sdk-alexaforbusiness/include/aws/alexaforbusiness/model/DeviceEventType.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7596" }, { "name": "C++", "bytes": "61740540" }, { "name": "CMake", "bytes": "337520" }, { "name": "Java", "bytes": "223122" }, { "name": "Python", "bytes": "47357" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>ActionDispatch::RailsEntityStore::Rack::Cache::EntityStore</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../../../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../../../css/github.css" type="text/css" media="screen" /> <script src="../../../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.0.0</span><br /> <h1> <span class="type">Module</span> ActionDispatch::RailsEntityStore::Rack::Cache::EntityStore </h1> <ul class="files"> <li><a href="../../../../../files/__/__/_rvm/gems/ruby-2_1_2/gems/actionpack-4_0_0/lib/action_dispatch/http/rack_cache_rb.html">/Users/alec/.rvm/gems/ruby-2.1.2/gems/actionpack-4.0.0/lib/action_dispatch/http/rack_cache.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <!-- Section constants --> <div class="sectiontitle">Constants</div> <table border='0' cellpadding='5'> <tr valign='top'> <td class="attr-name">RAILS</td> <td>=</td> <td class="attr-value">self</td> </tr> <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc"></td> </tr> </table> <!-- Methods --> </div> </div> </body> </html>
{ "content_hash": "9b7cf325b81cc75e94f673002db2c8f6", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 242, "avg_line_length": 25.77777777777778, "alnum_prop": 0.5142241379310345, "repo_name": "alombardo4/Agendue", "id": "ca2cfbf6c72dfe97447c4d86bdd8e606e585e5bb", "size": "2320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AgendueWeb/doc/api/classes/ActionDispatch/RailsEntityStore/Rack/Cache/EntityStore.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "138782" }, { "name": "CoffeeScript", "bytes": "3689" }, { "name": "HTML", "bytes": "13251982" }, { "name": "Java", "bytes": "308126" }, { "name": "JavaScript", "bytes": "15185870" }, { "name": "Objective-C", "bytes": "361506" }, { "name": "Perl", "bytes": "1361" }, { "name": "Ruby", "bytes": "150857" } ], "symlink_target": "" }
<?php namespace Dzangocart\Bundle\SubscriptionBundle\Form\Type; use Propel\PropelBundle\Form\BaseAbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class FeaturePlansFormType extends BaseAbstractType { protected $locale; public function __construct($locale) { $this->locale = $locale; } public function getLocale() { return $this->locale; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'translation_domain' => 'dzangocart_subscription', 'data_class' => 'Dzangocart\Bundle\SubscriptionBundle\Propel\Feature', 'name' => 'dzangocart_subscription_feature_plans', 'intention' => 'feature_plans', )); } /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add( 'plan_features', 'collection', array( 'label' => false, 'type' => new PlanFeatureFormType($this->getLocale()), 'allow_add' => false, 'allow_delete' => false, ) ); $builder->add('save', SubmitType::class, array( 'label' => 'feature.plans.submit', )); } }
{ "content_hash": "747862f67806de8da0c579dd30a57cb6", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 82, "avg_line_length": 27.14814814814815, "alnum_prop": 0.5989085948158254, "repo_name": "opichon/DzangocartSubscriptionBundle", "id": "ed8057883ab195527303dbe1af1808e5b6c3ffd1", "size": "1466", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Form/Type/FeaturePlansFormType.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6666" }, { "name": "HTML", "bytes": "24213" }, { "name": "JavaScript", "bytes": "11331" }, { "name": "PHP", "bytes": "73986" } ], "symlink_target": "" }
var buster = typeof window !== 'undefined' ? window.buster : require('buster'); var assert = buster.assert; var fail = buster.referee.fail; var when = require('../when'); var callbacks = require('../callbacks'); var sentinel = { value: 'sentinel' }; function assertIsPromise(arg) { assert(when.isPromiseLike(arg)); } buster.testCase('when/callbacks', { 'apply': { 'should return a promise': function() { assertIsPromise(callbacks.apply(function() {})); }, 'should preserve thisArg': function() { return callbacks.apply.call(sentinel, function(cb) { assert.same(this, sentinel); cb(); }); }, 'should resolve with the callback arguments': function(done) { var promise = callbacks.apply(function(cb) { cb(sentinel); }); promise.then(function(val) { assert.same(val, sentinel); }, fail).ensure(done); }, 'should reject with the errback arguments': function(done) { var promise = callbacks.apply(function(cb, eb){ eb(sentinel); }); promise.then(fail, function(reason) { assert.same(reason, sentinel); }).ensure(done); }, 'should turn exceptions into rejections': function(done) { var error = new Error(); var promise = callbacks.apply(function(){ throw error; }); promise.then(fail, function(reason) { assert.equals(reason, error); }).ensure(done); }, 'should forward its second argument to the function': function(done) { var async = function(a, b, cb/*, eb*/) { cb(a + b); }; var promise = callbacks.apply(async, [10, 15]); promise.then(function(result) { assert.equals(result, 25); }, fail).ensure(done); }, 'should turn multiple callback values into an array': function(done) { var async = function(a, b, cb/*, eb*/) { cb(a * 10, b * 20); }; var promise = callbacks.apply(async, [10, 20]); promise.then(function(results) { assert.equals(results, [100, 400]); }, fail).ensure(done); }, 'should accept promises on the extra arguments': function(done) { var async = function(a, b, cb/*, eb*/) { cb(a + b); }; var promise = callbacks.apply(async, [when(10), 15]); promise.then(function(result) { assert.equals(result, 25); }, fail).ensure(done); } }, 'call': { 'should return a promise': function() { assertIsPromise(callbacks.call(function() {})); }, 'should preserve thisArg': function() { return callbacks.call.call(sentinel, function(cb) { assert.same(this, sentinel); cb(); }); }, 'should resolve with the callback arguments': function(done) { var promise = callbacks.apply(function(cb) { cb(sentinel); }); promise.then(function(val) { assert.same(val, sentinel); }, fail).ensure(done); }, 'should reject with the errback arguments': function(done) { var promise = callbacks.apply(function(cb, eb){ eb(sentinel); }); promise.then(fail, function(reason) { assert.same(reason, sentinel); }).ensure(done); }, 'should turn exceptions into rejections': function(done) { var error = new Error(); var promise = callbacks.call(function(){ throw error; }); promise.then(fail, function(reason) { assert.equals(reason, error); }).ensure(done); }, 'should forward its extra arguments to the function': function(done) { var async = function(a, b, cb/*, eb*/) { cb(a + b); }; var promise = callbacks.call(async, 10, 15); promise.then(function(result) { assert.equals(result, 25); }, fail).ensure(done); }, 'should turn multiple callback values into an array': function(done) { var async = function(a, b, cb/*, eb*/) { cb(a * 10, b * 20); }; var promise = callbacks.call(async, 10, 20); promise.then(function(results) { assert.equals(results, [100, 400]); }, fail).ensure(done); }, 'should accept promises on the extra arguments': function(done) { var async = function(a, b, cb/*, eb*/) { cb(a + b); }; var promise = callbacks.call(async, when(10), 15); promise.then(function(result) { assert.equals(result, 25); }, fail).ensure(done); } }, 'lift': { 'should return a function': function() { assert.isFunction(callbacks.lift(function() {})); }, 'the returned function': { 'should return a promise': function() { var result = callbacks.lift(function() {}); assertIsPromise(result()); }, 'should preserve thisArg': function() { return callbacks.lift(function(cb) { assert.same(this, sentinel); cb(); }).call(sentinel); }, 'should resolve the promise with the callback value': function(done) { var result = callbacks.lift(function(cb) { cb(10); }); result().then(function(value) { assert.equals(value, 10); }, fail).ensure(done); }, 'should forward arguments to the original function': function(done) { var result = callbacks.lift(function(a, b, cb) { cb(a + b); }); result(10, 15).then(function(value) { assert.equals(value, 25); }, fail).ensure(done); }, 'should reject the promise with the errback value': function(done) { var error = new Error(); var result = callbacks.lift(function(cb, eb) { eb(error); }); result().then(fail, function(reason) { assert.same(reason, error); }).ensure(done); }, 'should turn exceptions into rejections': function(done) { var error = new Error(); var result = callbacks.lift(function(){ throw error; }); result().then(fail, function(reason) { assert.equals(reason, error); }).ensure(done); }, 'should turn multiple callback values into an array': function(done) { var result = callbacks.lift(function(a, b, cb/*, eb*/) { cb(a * 10, b * 20); }); result(10, 20).then(function(results) { assert.equals(results, [100, 400]); }, fail).ensure(done); }, 'should accept promises as arguments': function(done) { var result = callbacks.lift(function(a, b, cb/*, eb*/) { cb(a + b); }); result(when(10), 15).then(function(result) { assert.equals(result, 25); }, fail).ensure(done); } }, 'should accept leading arguments': function(done) { function fancySum(x, y, callback) { callback(x + y); } var partiallyApplied = callbacks.lift(fancySum, 5); partiallyApplied(10).then(function(value) { assert.equals(value, 15); }, fail).ensure(done); }, 'should accept promises as leading arguments': function(done) { function fancySum(x, y, callback) { callback(x + y); } var partiallyApplied = callbacks.lift(fancySum, when(5)); partiallyApplied(10).then(function(value) { assert.equals(value, 15); }, fail).ensure(done); } }, 'promisify': { 'should preserve thisArg': function() { return callbacks.promisify(function(cb) { assert.same(this, sentinel); cb(); }, { callback: 0 }).call(sentinel); }, 'should support callbacks in any position': function(done) { function weirdAsync(a, callback, b) { callback(a + b); } var promisified = callbacks.promisify(weirdAsync, { callback: 1 }); promisified(10, 5).then(function(result) { assert.equals(result, 15); }, fail).ensure(done); }, 'should support errbacks in any position': function(done) { function weirdAsync(errback, a, callback, b) { errback(a + b); } var promisified = callbacks.promisify(weirdAsync, { callback: 2, errback: 0 }); promisified(10, 5).then(fail, function(reason) { assert.equals(reason, 15); }).ensure(done); }, 'should turn multiple callback values into an array': function(done) { function invert(cb, eb, a, b) { cb(b, a); } var promisified = callbacks.promisify(invert, { callback: 0, errback: 1 }); promisified(10, 20).then(function(results) { assert.equals(results, [20, 10]); }, fail).ensure(done); }, 'should turn exceptions into rejections': function(done) { var error = new Error(); var result = callbacks.promisify(function(){ throw error; }, {}); result().then(fail, function(reason) { assert.equals(reason, error); }).ensure(done); }, 'should accept promises as arguments': function(done) { var result = callbacks.promisify(function(a, b, cb/*, eb*/) { cb(a + b); }, { callback: -2, errback: -1 }); result(when(10), 15).then(function(result) { assert.equals(result, 25); }, fail).ensure(done); }, 'should understand -1 as "the last argument"': function(done) { function asyncSum(/*n1, n2, n3...errback, callback*/) { arguments[arguments.length - 1](sentinel); } var promisified = callbacks.promisify(asyncSum, { errback: -2, callback: -1 }); promisified(0, 1, 2).then( function(val) { assert.same(val, sentinel); }, fail ).ensure(done); }, 'should understand -2 as "the penultimate argument"': function(done) { function asyncConcat(/*str1, str2, str3...errback, callback*/) { arguments[arguments.length - 2](sentinel); } var promisified = callbacks.promisify(asyncConcat, { errback: -2, callback: -1 }); promisified(0, 1, 2).then( fail, function(val) { assert.same(val, sentinel); } ).ensure(done); } } });
{ "content_hash": "6efcd8c6f41a1e02176d4fd79289baeb", "timestamp": "", "source": "github", "line_count": 391, "max_line_length": 79, "avg_line_length": 23.861892583120206, "alnum_prop": 0.615112540192926, "repo_name": "DJDNS/when.js", "id": "521b8ff93a6171bfbddcfe156942763a4d77b37b", "size": "9330", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/callbacks-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "285369" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace NeuroSpeech.XamlToPDF.Objects { public class PDFPage : PDFChildObject { #region protected internal override void Initialize() protected internal override void Initialize() { MediaBox = new PDFRect { Width = 612, Height=792 }; SetValue<PDFResources>("Resources", Document.Resources); SetValue<PDFContents>("Contents", Document.CreateObject<PDFContents>()); } #endregion public PDFRect MediaBox { get { return GetValue<PDFRect>("MediaBox"); } set { SetValue<PDFRect>("MediaBox", value); } } public PDFResources Resources { get { return GetValue<PDFResources>("Resources"); } } public PDFContents Contents { get { return GetValue<PDFContents>("Contents"); } } public PDFAnnotations Annotations { get { var pa = GetValue<PDFAnnotations>("Annots"); if (pa == null) { pa = Document.CreateObject<PDFAnnotations>(); SetValue<PDFAnnotations>("Annots", pa); } return pa; } } public TextWriter ContentStream { get { return Contents.ContentWriter; } } //public void DrawString(int x, int y, string text) //{ // PDFFont font = Document.CreateObject<PDFFont>(); // Resources.Font["F1"] = font; // font.Subtype = "Type1"; // font.BaseFont = "Helvetica"; // font.Encoding = "MacRomanEncoding"; // Resources.HasText = true; // ContentStream.WriteLine("BT"); // ContentStream.WriteLine("/F1 12 Tf"); // ContentStream.WriteLine("{0} {1} Td", x, y); // ContentStream.WriteLine("({0}) Tj",text); // ContentStream.WriteLine("ET"); //} private Stack<int> YCutOff = new Stack<int>(); public bool IsTransformOn { get { return YCutOff.Count > 0; } } public int ViewPortHeight { get { return YCutOff.Count > 0 ? YCutOff.Peek() : MediaBox.Height; } } public void StartTransform(int yCutOff) { //if (IsTransformOn) { // ContentStream.WriteLine("Q"); //} ContentStream.WriteLine("q"); if (!IsTransformOn) { YCutOff.Push(ViewPortHeight - yCutOff); } else { YCutOff.Push(yCutOff); } } public void EndTransform() { //if (IsTransformOn) ContentStream.WriteLine("Q"); YCutOff.Pop(); } } public class PDFPages : PDFObjectCollection<PDFPage> { } }
{ "content_hash": "e632ad6396840f9f82a4bf2eb8dc0cd1", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 75, "avg_line_length": 21.39830508474576, "alnum_prop": 0.6102970297029703, "repo_name": "neurospeech/xaml-to-pdf", "id": "ecb74a346fee5ff0234ebd0f93e8146f7a818baa", "size": "2525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "NeuroSpeech.XamlToPDF/Objects/PDFPage.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "85497" } ], "symlink_target": "" }
import React from 'react'; import { storiesOf } from '@storybook/react'; import { withReadme } from 'storybook-readme'; // Stories import Main from "../main.jsx"; import Styling from "./styling.jsx"; import ServerSideData from "./server-side-data.jsx"; // Readme import MainReadme from "./main.md"; import JSONReadme from "./json.md"; import StylingReadme from "./styling.md"; import ServerRenderReadme from "./server-render.md"; // Data import tableJSON from "./tableJSON.mock.json"; storiesOf('Welcome', module) .add("Default", withReadme(MainReadme, () => <Main />)) .add("Json", withReadme(JSONReadme, () => <Main data={tableJSON} />)) .add("Styling", withReadme(StylingReadme, () => <Styling />)) .add("Server Side Data", withReadme(ServerRenderReadme, () => <ServerSideData />));
{ "content_hash": "b0d775c4805bfb6234273e35a7ceeb1e", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 85, "avg_line_length": 30.807692307692307, "alnum_prop": 0.6928838951310862, "repo_name": "Edgesyntax/tableComponent", "id": "43d9d923da409d26f963ea6adc667bf41c05fe65", "size": "801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "stories/welcome/welcome.stories.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3325" }, { "name": "JavaScript", "bytes": "42537" } ], "symlink_target": "" }
import sys import os import glob import tempfile import shutil import errno from gerapy import get_logger from gerapy.cmd.init import PROJECTS_FOLDER from gerapy.server.core.config import config from os.path import join from subprocess import check_call logger = get_logger(__name__) def build_project(project): """ build project :param project: :return: """ egg = build_egg(project) logger.info('successfully build project %s to egg file %s', project, egg) return egg _SETUP_PY_TEMPLATE = \ '''# Automatically created by: gerapy from setuptools import setup, find_packages setup( name='%(project)s', version='1.0', packages=find_packages(), entry_points={'scrapy':['settings=%(settings)s']}, )''' def retry_on_eintr(function, *args, **kw): """Run a function and retry it while getting EINTR errors""" while True: try: return function(*args, **kw) except IOError as e: if e.errno != errno.EINTR: raise # build Egg def build_egg(project): ''' build project to egg file :param project: :return: ''' work_path = os.getcwd() try: path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER)) project_path = join(path, project) os.chdir(project_path) settings = config(project_path, 'settings', 'default') setup_file_path = join(project_path, 'setup.py') create_default_setup_py( setup_file_path, settings=settings, project=project) d = tempfile.mkdtemp(prefix='gerapy-') o = open(os.path.join(d, 'stdout'), 'wb') e = open(os.path.join(d, 'stderr'), 'wb') retry_on_eintr(check_call, [sys.executable, 'setup.py', 'clean', '-a', 'bdist_egg', '-d', d], stdout=o, stderr=e) o.close() e.close() egg = glob.glob(os.path.join(d, '*.egg'))[0] # Delete Origin file if find_egg(project_path): os.remove(join(project_path, find_egg(project_path))) shutil.move(egg, project_path) return join(project_path, find_egg(project_path)) except Exception as e: logger.error('error occurred %s', e.args) finally: os.chdir(work_path) def find_egg(path): """ find egg from path :param path: :return: """ items = os.listdir(path) for name in items: if name.endswith('.egg'): return name def create_default_setup_py(path, **kwargs): """ create setup.py file to path :param path: :param kwargs: :return: """ if os.path.exists(path): logger.debug('setup.py file already exists at %s', path) else: with open(path, 'w', encoding='utf-8') as f: file = _SETUP_PY_TEMPLATE % kwargs f.write(file) f.close() logger.debug('successfully created setup.py file at %s', path)
{ "content_hash": "629e90c231e22befcae3173d4cbc9510", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 101, "avg_line_length": 26.96330275229358, "alnum_prop": 0.5923783599863899, "repo_name": "Gerapy/Gerapy", "id": "986a83a34c5e9480d9b518db304e0e45f773b484", "size": "2939", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gerapy/server/core/build.py", "mode": "33261", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "198" }, { "name": "HTML", "bytes": "3111" }, { "name": "JavaScript", "bytes": "27475" }, { "name": "Python", "bytes": "1723424" }, { "name": "SCSS", "bytes": "10276" }, { "name": "Shell", "bytes": "257" }, { "name": "Vue", "bytes": "185910" } ], "symlink_target": "" }
rm -rf ../../deploy/normal/ node r.js -o build.js
{ "content_hash": "cc15902be8a83e8905d86f77505f7ac0", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 27, "avg_line_length": 25, "alnum_prop": 0.62, "repo_name": "openjavascript/NewJC", "id": "d6f84c0d653653bdbdb81cc3199433d565e4ccff", "size": "50", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/build/build.sh", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "185739" }, { "name": "HTML", "bytes": "14860218" }, { "name": "JavaScript", "bytes": "6024232" }, { "name": "PHP", "bytes": "442329" }, { "name": "Prolog", "bytes": "344" }, { "name": "Shell", "bytes": "114" } ], "symlink_target": "" }
/////////////////////////////////////////////////////////////////////////////// // Name: msw/checklst.cpp // Purpose: implementation of wxCheckListBox class // Author: Vadim Zeitlin // Modified by: // Created: 16.11.97 // RCS-ID: $Id: checklst.cpp,v 1.65 2005/06/10 08:39:19 JS Exp $ // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "checklst.h" #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_CHECKLISTBOX && wxUSE_OWNER_DRAWN #ifndef WX_PRECOMP #include "wx/object.h" #include "wx/colour.h" #include "wx/font.h" #include "wx/bitmap.h" #include "wx/window.h" #include "wx/listbox.h" #include "wx/dcmemory.h" #include "wx/settings.h" #include "wx/log.h" #endif #include "wx/ownerdrw.h" #include "wx/checklst.h" #include "wx/msw/wrapwin.h" #include <windowsx.h> #include "wx/msw/private.h" // ---------------------------------------------------------------------------- // private functions // ---------------------------------------------------------------------------- // get item (converted to right type) #define GetItem(n) ((wxCheckListBoxItem *)(GetItem(n))) // ============================================================================ // implementation // ============================================================================ #if wxUSE_EXTENDED_RTTI WX_DEFINE_FLAGS( wxCheckListBoxStyle ) wxBEGIN_FLAGS( wxCheckListBoxStyle ) // new style border flags, we put them first to // use them for streaming out wxFLAGS_MEMBER(wxBORDER_SIMPLE) wxFLAGS_MEMBER(wxBORDER_SUNKEN) wxFLAGS_MEMBER(wxBORDER_DOUBLE) wxFLAGS_MEMBER(wxBORDER_RAISED) wxFLAGS_MEMBER(wxBORDER_STATIC) wxFLAGS_MEMBER(wxBORDER_NONE) // old style border flags wxFLAGS_MEMBER(wxSIMPLE_BORDER) wxFLAGS_MEMBER(wxSUNKEN_BORDER) wxFLAGS_MEMBER(wxDOUBLE_BORDER) wxFLAGS_MEMBER(wxRAISED_BORDER) wxFLAGS_MEMBER(wxSTATIC_BORDER) wxFLAGS_MEMBER(wxBORDER) // standard window styles wxFLAGS_MEMBER(wxTAB_TRAVERSAL) wxFLAGS_MEMBER(wxCLIP_CHILDREN) wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW) wxFLAGS_MEMBER(wxWANTS_CHARS) wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE) wxFLAGS_MEMBER(wxALWAYS_SHOW_SB ) wxFLAGS_MEMBER(wxVSCROLL) wxFLAGS_MEMBER(wxHSCROLL) wxFLAGS_MEMBER(wxLB_SINGLE) wxFLAGS_MEMBER(wxLB_MULTIPLE) wxFLAGS_MEMBER(wxLB_EXTENDED) wxFLAGS_MEMBER(wxLB_HSCROLL) wxFLAGS_MEMBER(wxLB_ALWAYS_SB) wxFLAGS_MEMBER(wxLB_NEEDED_SB) wxFLAGS_MEMBER(wxLB_SORT) wxFLAGS_MEMBER(wxLB_OWNERDRAW) wxEND_FLAGS( wxCheckListBoxStyle ) IMPLEMENT_DYNAMIC_CLASS_XTI(wxCheckListBox, wxListBox,"wx/checklst.h") wxBEGIN_PROPERTIES_TABLE(wxCheckListBox) wxEVENT_PROPERTY( Toggle , wxEVT_COMMAND_CHECKLISTBOX_TOGGLED , wxCommandEvent ) wxPROPERTY_FLAGS( WindowStyle , wxCheckListBoxStyle , long , SetWindowStyleFlag , GetWindowStyleFlag , EMPTY_MACROVALUE , wxLB_OWNERDRAW /*flags*/ , wxT("Helpstring") , wxT("group")) // style wxEND_PROPERTIES_TABLE() wxBEGIN_HANDLERS_TABLE(wxCheckListBox) wxEND_HANDLERS_TABLE() wxCONSTRUCTOR_4( wxCheckListBox , wxWindow* , Parent , wxWindowID , Id , wxPoint , Position , wxSize , Size ) #else IMPLEMENT_DYNAMIC_CLASS(wxCheckListBox, wxListBox) #endif // ---------------------------------------------------------------------------- // declaration and implementation of wxCheckListBoxItem class // ---------------------------------------------------------------------------- class wxCheckListBoxItem : public wxOwnerDrawn { friend class WXDLLEXPORT wxCheckListBox; public: // ctor wxCheckListBoxItem(wxCheckListBox *pParent, size_t nIndex); // drawing functions virtual bool OnDrawItem(wxDC& dc, const wxRect& rc, wxODAction act, wxODStatus stat); // simple accessors and operations bool IsChecked() const { return m_bChecked; } void Check(bool bCheck); void Toggle() { Check(!IsChecked()); } void SendEvent(); private: bool m_bChecked; wxCheckListBox *m_pParent; size_t m_nIndex; DECLARE_NO_COPY_CLASS(wxCheckListBoxItem) }; wxCheckListBoxItem::wxCheckListBoxItem(wxCheckListBox *pParent, size_t nIndex) : wxOwnerDrawn(wxEmptyString, true) // checkable { m_bChecked = false; m_pParent = pParent; m_nIndex = nIndex; // we don't initialize m_nCheckHeight/Width vars because it's // done in OnMeasure while they are used only in OnDraw and we // know that there will always be OnMeasure before OnDraw // fix appearance for check list boxes: they don't look quite the same as // menu icons SetMarginWidth(::GetSystemMetrics(SM_CXMENUCHECK) - 2*wxSystemSettings::GetMetric(wxSYS_EDGE_X) + 1); SetBackgroundColour(pParent->GetBackgroundColour()); } bool wxCheckListBoxItem::OnDrawItem(wxDC& dc, const wxRect& rc, wxODAction act, wxODStatus stat) { // first draw the label if ( IsChecked() ) stat = (wxOwnerDrawn::wxODStatus)(stat | wxOwnerDrawn::wxODChecked); if ( !wxOwnerDrawn::OnDrawItem(dc, rc, act, stat) ) return false; // now draw the check mark part size_t nCheckWidth = GetDefaultMarginWidth(), nCheckHeight = m_pParent->GetItemHeight(); int x = rc.GetX(), y = rc.GetY(); HDC hdc = (HDC)dc.GetHDC(); // create pens, brushes &c COLORREF colBg = ::GetSysColor(COLOR_WINDOW); AutoHPEN hpenBack(colBg), hpenGray(RGB(0xc0, 0xc0, 0xc0)); SelectInHDC selPen(hdc, (HGDIOBJ)hpenBack); AutoHBRUSH hbrBack(colBg); SelectInHDC selBrush(hdc, hbrBack); // erase the background: it could have been filled with the selected colour Rectangle(hdc, x, y, x + nCheckWidth + 1, rc.GetBottom() + 1); // shift check mark 1 pixel to the right, looks better like this x++; if ( IsChecked() ) { // first create a monochrome bitmap in a memory DC MemoryHDC hdcMem(hdc); MonoBitmap hbmpCheck(nCheckWidth, nCheckHeight); SelectInHDC selBmp(hdcMem, hbmpCheck); // then draw a check mark into it RECT rect = { 0, 0, nCheckWidth, nCheckHeight }; ::DrawFrameControl(hdcMem, &rect, #ifdef __WXWINCE__ DFC_BUTTON, DFCS_BUTTONCHECK #else DFC_MENU, DFCS_MENUCHECK #endif ); // finally copy it to screen DC ::BitBlt(hdc, x, y, nCheckWidth, nCheckHeight, hdcMem, 0, 0, SRCCOPY); } // now we draw the smaller rectangle y++; nCheckWidth -= 2; nCheckHeight -= 2; // draw hollow gray rectangle (void)::SelectObject(hdc, (HGDIOBJ)hpenGray); SelectInHDC selBrush2(hdc, ::GetStockObject(NULL_BRUSH)); Rectangle(hdc, x, y, x + nCheckWidth, y + nCheckHeight); return true; } // change the state of the item and redraw it void wxCheckListBoxItem::Check(bool check) { m_bChecked = check; // index may be changed because new items were added/deleted if ( m_pParent->GetItemIndex(this) != (int)m_nIndex ) { // update it int index = m_pParent->GetItemIndex(this); wxASSERT_MSG( index != wxNOT_FOUND, wxT("what does this item do here?") ); m_nIndex = (size_t)index; } HWND hwndListbox = (HWND)m_pParent->GetHWND(); RECT rcUpdate; if ( ::SendMessage(hwndListbox, LB_GETITEMRECT, m_nIndex, (LPARAM)&rcUpdate) == LB_ERR ) { wxLogDebug(wxT("LB_GETITEMRECT failed")); } ::InvalidateRect(hwndListbox, &rcUpdate, FALSE); } // send an "item checked" event void wxCheckListBoxItem::SendEvent() { wxCommandEvent event(wxEVT_COMMAND_CHECKLISTBOX_TOGGLED, m_pParent->GetId()); event.SetInt(m_nIndex); event.SetEventObject(m_pParent); m_pParent->ProcessCommand(event); } // ---------------------------------------------------------------------------- // implementation of wxCheckListBox class // ---------------------------------------------------------------------------- // define event table // ------------------ BEGIN_EVENT_TABLE(wxCheckListBox, wxListBox) EVT_KEY_DOWN(wxCheckListBox::OnKeyDown) EVT_LEFT_DOWN(wxCheckListBox::OnLeftClick) END_EVENT_TABLE() // control creation // ---------------- // def ctor: use Create() to really create the control wxCheckListBox::wxCheckListBox() { } // ctor which creates the associated control wxCheckListBox::wxCheckListBox(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, int nStrings, const wxString choices[], long style, const wxValidator& val, const wxString& name) { Create(parent, id, pos, size, nStrings, choices, style, val, name); } wxCheckListBox::wxCheckListBox(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, const wxArrayString& choices, long style, const wxValidator& val, const wxString& name) { Create(parent, id, pos, size, choices, style, val, name); } bool wxCheckListBox::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, int n, const wxString choices[], long style, const wxValidator& validator, const wxString& name) { return wxListBox::Create(parent, id, pos, size, n, choices, style | wxLB_OWNERDRAW, validator, name); } bool wxCheckListBox::Create(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, const wxArrayString& choices, long style, const wxValidator& validator, const wxString& name) { return wxListBox::Create(parent, id, pos, size, choices, style | wxLB_OWNERDRAW, validator, name); } // misc overloaded methods // ----------------------- void wxCheckListBox::Delete(int N) { wxCHECK_RET( N >= 0 && N < m_noItems, wxT("invalid index in wxListBox::Delete") ); wxListBox::Delete(N); // free memory delete m_aItems[N]; m_aItems.RemoveAt(N); } bool wxCheckListBox::SetFont( const wxFont &font ) { size_t i; for ( i = 0; i < m_aItems.GetCount(); i++ ) m_aItems[i]->SetFont(font); wxListBox::SetFont(font); return true; } // create/retrieve item // -------------------- // create a check list box item wxOwnerDrawn *wxCheckListBox::CreateLboxItem(size_t nIndex) { wxCheckListBoxItem *pItem = new wxCheckListBoxItem(this, nIndex); return pItem; } // return item size // ---------------- bool wxCheckListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT *item) { if ( wxListBox::MSWOnMeasure(item) ) { MEASUREITEMSTRUCT *pStruct = (MEASUREITEMSTRUCT *)item; // save item height m_nItemHeight = pStruct->itemHeight; // add place for the check mark pStruct->itemWidth += wxOwnerDrawn::GetDefaultMarginWidth(); return true; } return false; } // check items // ----------- bool wxCheckListBox::IsChecked(size_t uiIndex) const { wxCHECK_MSG( uiIndex < (size_t)GetCount(), false, _T("bad wxCheckListBox index") ); return GetItem(uiIndex)->IsChecked(); } void wxCheckListBox::Check(size_t uiIndex, bool bCheck) { wxCHECK_RET( uiIndex < (size_t)GetCount(), _T("bad wxCheckListBox index") ); GetItem(uiIndex)->Check(bCheck); } // process events // -------------- void wxCheckListBox::OnKeyDown(wxKeyEvent& event) { // what do we do? enum { None, Toggle, Set, Clear } oper; switch ( event.GetKeyCode() ) { case WXK_SPACE: oper = Toggle; break; case WXK_NUMPAD_ADD: case '+': oper = Set; break; case WXK_NUMPAD_SUBTRACT: case '-': oper = Clear; break; default: oper = None; } if ( oper != None ) { wxArrayInt selections; int count = 0; if ( HasMultipleSelection() ) { count = GetSelections(selections); } else { int sel = GetSelection(); if (sel != -1) { count = 1; selections.Add(sel); } } for ( int i = 0; i < count; i++ ) { wxCheckListBoxItem *item = GetItem(selections[i]); if ( !item ) { wxFAIL_MSG( _T("no wxCheckListBoxItem?") ); continue; } switch ( oper ) { case Toggle: item->Toggle(); break; case Set: case Clear: item->Check( oper == Set ); break; default: wxFAIL_MSG( _T("what should this key do?") ); } // we should send an event as this has been done by the user and // not by the program item->SendEvent(); } } else // nothing to do { event.Skip(); } } void wxCheckListBox::OnLeftClick(wxMouseEvent& event) { // clicking on the item selects it, clicking on the checkmark toggles if ( event.GetX() <= wxOwnerDrawn::GetDefaultMarginWidth() ) { int nItem = HitTest(event.GetX(), event.GetY()); if ( nItem != wxNOT_FOUND ) { wxCheckListBoxItem *item = GetItem(nItem); item->Toggle(); item->SendEvent(); } //else: it's not an error, just click outside of client zone } else { // implement default behaviour: clicking on the item selects it event.Skip(); } } int wxCheckListBox::DoHitTestItem(wxCoord x, wxCoord y) const { int nItem = (int)::SendMessage ( (HWND)GetHWND(), LB_ITEMFROMPOINT, 0, MAKELPARAM(x, y) ); return nItem >= m_noItems ? wxNOT_FOUND : nItem; } wxSize wxCheckListBox::DoGetBestSize() const { wxSize best = wxListBox::DoGetBestSize(); best.x += wxOwnerDrawn::GetDefaultMarginWidth(); // add room for the checkbox CacheBestSize(best); return best; } #endif
{ "content_hash": "214db0c523c2a1d09e6453617ab3f4ac", "timestamp": "", "source": "github", "line_count": 541, "max_line_length": 195, "avg_line_length": 28.155268022181147, "alnum_prop": 0.5594143907563025, "repo_name": "SickheadGames/Torsion", "id": "43891cd4e39039c950b62276370e09408ea5ea27", "size": "15232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/wxWidgets/src/msw/checklst.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "74209" }, { "name": "C", "bytes": "6906504" }, { "name": "C#", "bytes": "1624" }, { "name": "C++", "bytes": "30405718" }, { "name": "CSS", "bytes": "591" }, { "name": "DIGITAL Command Language", "bytes": "4055" }, { "name": "Groff", "bytes": "280584" }, { "name": "HTML", "bytes": "148434" }, { "name": "Inno Setup", "bytes": "9684" }, { "name": "Lex", "bytes": "4201" }, { "name": "Makefile", "bytes": "147895" }, { "name": "Module Management System", "bytes": "48825" }, { "name": "Objective-C", "bytes": "143389" }, { "name": "Objective-C++", "bytes": "430038" }, { "name": "PHP", "bytes": "35873" }, { "name": "Perl", "bytes": "105033" }, { "name": "Perl6", "bytes": "107551" }, { "name": "Prolog", "bytes": "421" }, { "name": "Python", "bytes": "5849" }, { "name": "R", "bytes": "7779" }, { "name": "Rebol", "bytes": "732" }, { "name": "Scala", "bytes": "4674" }, { "name": "Scheme", "bytes": "154" }, { "name": "Shell", "bytes": "269793" }, { "name": "SourcePawn", "bytes": "8637" }, { "name": "TeX", "bytes": "194986" } ], "symlink_target": "" }
<?php namespace Mage\Newsletter\Test\Constraint; use Mage\Customer\Test\Fixture\Customer; use Mage\Newsletter\Test\Page\Adminhtml\SubscriberIndex; use Magento\Mtf\Constraint\AbstractConstraint; /** * Check that customer is subscribed to newsletter. */ class AssertCustomerIsSubscribedToNewsletter extends AbstractConstraint { /** * Constraint severeness. * * @var string */ protected $severeness = 'low'; /** * Assert customer is subscribed to newsletter. * * @param Customer $customer * @param SubscriberIndex $subscriberIndex * @return void */ public function processAssert(Customer $customer, SubscriberIndex $subscriberIndex) { $filter = [ 'email' => $customer->getEmail(), 'firstname' => $customer->getFirstname(), 'lastname' => $customer->getLastname(), 'status' => 'Subscribed' ]; $subscriberIndex->open(); \PHPUnit_Framework_Assert::assertTrue( $subscriberIndex->getSubscriberGrid()->isRowVisible($filter), "Customer with email " . $customer->getEmail() . " is absent in Newsletter Subscribers grid." ); } /** * Text of successful customer's subscription to newsletter. * * @return string */ public function toString() { return "Customer is subscribed to newsletter."; } }
{ "content_hash": "a852e40c423df232d000c8a865ce6bdf", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 105, "avg_line_length": 26.296296296296298, "alnum_prop": 0.6267605633802817, "repo_name": "portchris/NaturalRemedyCompany", "id": "a092db6ea592419028ef0e295b6a9b7de9ac2d4e", "size": "2361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/dev/tests/functional/tests/app/Mage/Newsletter/Test/Constraint/AssertCustomerIsSubscribedToNewsletter.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "20009" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "2584823" }, { "name": "Dockerfile", "bytes": "828" }, { "name": "HTML", "bytes": "8762252" }, { "name": "JavaScript", "bytes": "2932806" }, { "name": "PHP", "bytes": "66466458" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Ruby", "bytes": "576" }, { "name": "Shell", "bytes": "40066" }, { "name": "XSLT", "bytes": "2135" } ], "symlink_target": "" }
require 'polytrix' Polytrix.configure do |polytrix| polytrix.implementor name: 'pacto', basedir: "#{Dir.pwd}/samples" end
{ "content_hash": "9fb5d33ad92cd8066034210acf2637db", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 67, "avg_line_length": 25, "alnum_prop": 0.744, "repo_name": "farismosman/pacto", "id": "fc3aaa263e8c828e28d1de59f00ca890d414f2c4", "size": "125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "polytrix.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Cucumber", "bytes": "13306" }, { "name": "Ruby", "bytes": "163539" } ], "symlink_target": "" }
.. _quickinstall: =================== Quick Install Guide =================== This quick install guide outlines the basic steps needed to install OpenMC on your computer. For more detailed instructions on configuring and installing OpenMC, see :ref:`usersguide_install` in the User's Manual. -------------------------------- Installing on Ubuntu through PPA -------------------------------- For users with Ubuntu 11.10 or later, a binary package for OpenMC is available through a `Personal Package Archive`_ (PPA) and can be installed through the `APT package manager`_. Simply enter the following commands into the terminal: .. code-block:: sh sudo apt-add-repository ppa:paulromano/staging sudo apt-get update sudo apt-get install openmc Currently, the binary package does not allow for parallel simulations, HDF5_, or CMFD acceleration through PETSc_. Users who need such capabilities should build OpenMC from source as is described in :ref:`usersguide_install`. .. _Personal Package Archive: https://launchpad.net/~paulromano/+archive/staging .. _APT package manager: https://help.ubuntu.com/community/AptGet/Howto .. _HDF5: http://www.hdfgroup.org/HDF5/ .. _PETSc: http://www.mcs.anl.gov/petsc/ ------------------------------------------- Installing from Source on Linux or Mac OS X ------------------------------------------- All OpenMC source code is hosted on GitHub_. If you have git_ and the gfortran_ compiler installed, you can download and install OpenMC be entering the following commands in a terminal: .. code-block:: sh git clone git://github.com/mit-crpg/openmc.git cd openmc/src git checkout -b master origin/master make sudo make install This will build an executable named ``openmc`` and install it (by default in /usr/local/bin). If you do not have administrator privileges, the last command can be replaced with a local install, e.g. .. code-block:: sh make install -e prefix=$HOME/.local .. _GitHub: https://github.com/mit-crpg/openmc .. _git: http://git-scm.com .. _gfortran: http://gcc.gnu.org/wiki/GFortran
{ "content_hash": "8742475e9170bb0913a7d31733da4e26", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 81, "avg_line_length": 34.766666666666666, "alnum_prop": 0.6831255992329818, "repo_name": "nhorelik/openmc", "id": "9dd6be6d1ddcda614d06e638f9bbc0e0a010ffb0", "size": "2086", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "docs/source/quickinstall.rst", "mode": "33188", "license": "mit", "language": [ { "name": "FORTRAN", "bytes": "1337345" }, { "name": "Makefile", "bytes": "5169" }, { "name": "Python", "bytes": "387884" }, { "name": "Shell", "bytes": "374" } ], "symlink_target": "" }
class RemoveSlugColumnFromShortenedUrl < ActiveRecord::Migration def change remove_column :shortened_urls, :slug end end
{ "content_hash": "10e17caa9ffa2b4f7e25ab197a79428e", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 64, "avg_line_length": 25.8, "alnum_prop": 0.7906976744186046, "repo_name": "jmptrader/promdash", "id": "3b3400e39a4357ac04ca6143ca575598fc5f8879", "size": "129", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "db/migrate/20140327001343_remove_slug_column_from_shortened_url.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "14549" }, { "name": "HTML", "bytes": "85019" }, { "name": "JavaScript", "bytes": "17370" }, { "name": "Makefile", "bytes": "959" }, { "name": "Ruby", "bytes": "88551" }, { "name": "Shell", "bytes": "184" } ], "symlink_target": "" }
'use strict'; angular.module('bhendi') .controller('computerCtrl', function ($scope) { }) .config(function ($stateProvider) { $stateProvider .state('home.BB_dept_Computer', { url: '/computer', views: { '': { templateUrl: 'app/bulletinboard/departments/computer/computer.html', controller: 'computerCtrl' }, 'heading': { template: 'Computer' } }, }); });
{ "content_hash": "adb183a4bf31ddf56e9fa75a8ff107ff", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 100, "avg_line_length": 34.80952380952381, "alnum_prop": 0.33515731874145005, "repo_name": "DrBATU/bhendi", "id": "c54f7cd6b27230a633de562b9802f45c66c4c1cd", "size": "731", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/app/bulletinboard/departments/computer/computer.controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3278" }, { "name": "HTML", "bytes": "14390" }, { "name": "JavaScript", "bytes": "38438" } ], "symlink_target": "" }
require 'spec_helper' describe "Customer Details", type: :feature, js: true do stub_authorization! let(:country) { create(:country, name: "Kangaland") } let(:state) { create(:state, name: "Alabama", country: country) } let!(:shipping_method) { create(:shipping_method) } let!(:order) { create(:order, ship_address: ship_address, bill_address: bill_address, state: 'complete', completed_at: "2011-02-01 12:36:15") } let!(:product) { create(:product_in_stock) } # We need a unique name that will appear for the customer dropdown let!(:ship_address) { create(:address, country: country, state: state, first_name: "Rumpelstiltskin") } let!(:bill_address) { create(:address, country: country, state: state, first_name: "Rumpelstiltskin") } let!(:user) { create(:user, email: 'foobar@example.com', ship_address: ship_address, bill_address: bill_address) } context "brand new order" do let(:quantity) { 1 } before do visit spree.admin_path click_link "Orders" click_link "New Order" click_on 'Cart' select2_search product.name, from: Spree.t(:name_or_sku) within("table.stock-levels") do find('.variant_quantity').set(quantity) end click_button 'Add' expect(page).to have_css('.line-item') click_link "Customer" targetted_select2 "foobar@example.com", from: "#s2id_customer_search" end # Regression test for https://github.com/spree/spree/issues/3335 and https://github.com/spree/spree/issues/5317 it "associates a user when not using guest checkout" do # 5317 - Address prefills using user's default. expect(page).to have_field('First Name', with: user.bill_address.firstname) expect(page).to have_field('Last Name', with: user.bill_address.lastname) expect(page).to have_field('Street Address', with: user.bill_address.address1) expect(page).to have_field("Street Address (cont'd)", with: user.bill_address.address2) expect(page).to have_field('City', with: user.bill_address.city) expect(page).to have_field('Zip', with: user.bill_address.zipcode) expect(page).to have_field('Country', with: user.bill_address.country_id) expect(page).to have_field('State', with: user.bill_address.state_id) expect(page).to have_field('Phone', with: user.bill_address.phone) click_button "Update" expect(Spree::Order.last.user).not_to be_nil end context "when required quantity is more than available" do let(:quantity) { 11 } let!(:product) { create(:product_not_backorderable) } it "displays an error" do click_button "Update" expect(page).to have_content Spree.t(:insufficient_stock_for_order) end end end context "editing an order" do before do configure_spree_preferences do |config| config.default_country_iso = country.iso config.company = true end visit spree.admin_path click_link "Orders" within('table#listing_orders') { click_icon(:edit) } end context "selected country has no state" do before { create(:country, iso: "BRA", name: "Brazil") } it "changes state field to text input" do click_link "Customer" within("#billing") do targetted_select2 "Brazil", from: "#s2id_order_bill_address_attributes_country_id" fill_in "order_bill_address_attributes_state_name", with: "Piaui" end click_button "Update" expect(page).to have_content "Customer Details Updated" click_link "Customer" expect(page).to have_field("order_bill_address_attributes_state_name", with: "Piaui") end end it "should be able to update customer details for an existing order" do order.ship_address = create(:address) order.save! click_link "Customer" within("#shipping") { fill_in_address "ship" } within("#billing") { fill_in_address "bill" } click_button "Update" click_link "Customer" # Regression test for https://github.com/spree/spree/issues/2950 and https://github.com/spree/spree/issues/2433 # This act should transition the state of the order as far as it will go too within("#order_tab_summary") do expect(find("dt#order_status + dd")).to have_content("complete") end end it "should show validation errors" do order.update_attributes!(ship_address_id: nil) click_link "Customer" click_button "Update" expect(page).to have_content("Shipping address first name can't be blank") end it "updates order email for an existing order with a user" do order.update_columns(ship_address_id: ship_address.id, bill_address_id: bill_address.id, state: "confirm", completed_at: nil) previous_user = order.user click_link "Customer" fill_in "order_email", with: "newemail@example.com" expect { click_button "Update" }.to change { order.reload.email }.to "newemail@example.com" expect(order.user_id).to eq previous_user.id expect(order.user.email).to eq previous_user.email end context "country associated was removed" do let(:brazil) { create(:country, iso: "BR", name: "Brazil") } before do order.bill_address.country.destroy configure_spree_preferences do |config| config.default_country_iso = brazil.iso end end it "sets default country when displaying form" do click_link "Customer" expect(page).to have_field("order_bill_address_attributes_country_id", with: brazil.id) end end # Regression test for https://github.com/spree/spree/issues/942 context "errors when no shipping methods are available" do before do Spree::ShippingMethod.delete_all end specify do click_link "Customer" # Need to fill in valid information so it passes validations fill_in "order_ship_address_attributes_firstname", with: "John 99" fill_in "order_ship_address_attributes_lastname", with: "Doe" fill_in "order_ship_address_attributes_lastname", with: "Company" fill_in "order_ship_address_attributes_address1", with: "100 first lane" fill_in "order_ship_address_attributes_address2", with: "#101" fill_in "order_ship_address_attributes_city", with: "Bethesda" fill_in "order_ship_address_attributes_zipcode", with: "20170" page.select('Alabama', from: 'order_ship_address_attributes_state_id') fill_in "order_ship_address_attributes_phone", with: "123-456-7890" click_button "Update" end end end def fill_in_address(kind = "bill") fill_in "First Name", with: "John 99" fill_in "Last Name", with: "Doe" fill_in "Company", with: "Company" fill_in "Street Address", with: "100 first lane" fill_in "Street Address (cont'd)", with: "#101" fill_in "City", with: "Bethesda" fill_in "Zip", with: "20170" targetted_select2 "Alabama", from: "#s2id_order_#{kind}_address_attributes_state_id" fill_in "Phone", with: "123-456-7890" end end
{ "content_hash": "2e7ab374579078b46540a6b9d73283d5", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 145, "avg_line_length": 40.547486033519554, "alnum_prop": 0.6467346376412235, "repo_name": "Arpsara/solidus", "id": "7af11cbcd3bd59de0ebce2932fd529be2b2ef1b1", "size": "7258", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backend/spec/features/admin/orders/customer_details_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "133108" }, { "name": "CoffeeScript", "bytes": "48438" }, { "name": "HTML", "bytes": "463016" }, { "name": "JavaScript", "bytes": "46189" }, { "name": "Ruby", "bytes": "2833451" }, { "name": "Shell", "bytes": "2371" } ], "symlink_target": "" }
title: "Recuerdos de Nica" layout: post published: true soundcloud-url: 279635195 author: "Breaking Español" images: - image_path: /images/ep10/1.jpg - image_path: /images/ep10/2.jpg - image_path: /images/ep10/3.jpg - image_path: /images/ep10/4.jpg - image_path: /images/ep10/5.jpg - image_path: /images/ep10/6.jpg - image_path: /images/ep10/7.jpg - image_path: /images/ep10/8.jpg - image_path: /images/ep10/9.jpg - image_path: /images/ep10/10.jpg - image_path: /images/ep10/11.jpg - image_path: /images/ep10/12.jpg - image_path: /images/ep10/13.jpg - image_path: /images/ep10/14.jpg - image_path: /images/ep10/15.jpg --- This week we recount a trip we went on early in our Spanish learning journey to Nicaragua. Often for Jennie’s birthday the weather here in San Diego is pretty rainy so we end up traveling, this time to an amazing tropical destination and surf paradise. The trip was five days in a small town called Playa Gigante at the Papaya Wellness surf and yoga retreat. During the five days we had many opportunities to advance our Spanish speaking as well as interact with many locals and make new memories in an amazing country. Enjoy! ## Palabras Espanolas (Spanish Words) - ¿Que Tal? = What’s up? - Nica = Nicaragua - Gallo Pinto = Rice and Beans Nica style - Tu turno = Your turn - Esposa/o = wife/husband - Un poquito = a little bit - No tengo tiempo = I don’t have time - Vamo = Let’s go ## Mas - [www.papayawellness.com](http://www.papayawellness.com) ## Fotos de Nuestra Viaje (Photos from Our Trip) <ul class="photo-gallery"> {% for image in page.images %} <li><img src="{{ image.image_path }}" /></li> {% endfor %} </ul>
{ "content_hash": "f8c5453b9c06925121bce4e6cd942001", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 273, "avg_line_length": 36.65217391304348, "alnum_prop": 0.7099644128113879, "repo_name": "breakingespanol/breakingespanol.github.io", "id": "6b0bc46202166b3f9f1cddad5b7c2bb13013f00d", "size": "1700", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2016-08-23-10.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "69076" }, { "name": "HTML", "bytes": "20808" }, { "name": "Ruby", "bytes": "4235" } ], "symlink_target": "" }
/* * 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.cloudsearch.v1.model; /** * Model definition for PollItemsResponse. * * <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 Cloud Search 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 PollItemsResponse extends com.google.api.client.json.GenericJson { /** * Set of items from the queue available for connector to process. These items have the following * subset of fields populated: version metadata.hash structured_data.hash content.hash payload * status queue * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Item> items; static { // hack to force ProGuard to consider Item used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Item.class); } /** * Set of items from the queue available for connector to process. These items have the following * subset of fields populated: version metadata.hash structured_data.hash content.hash payload * status queue * @return value or {@code null} for none */ public java.util.List<Item> getItems() { return items; } /** * Set of items from the queue available for connector to process. These items have the following * subset of fields populated: version metadata.hash structured_data.hash content.hash payload * status queue * @param items items or {@code null} for none */ public PollItemsResponse setItems(java.util.List<Item> items) { this.items = items; return this; } @Override public PollItemsResponse set(String fieldName, Object value) { return (PollItemsResponse) super.set(fieldName, value); } @Override public PollItemsResponse clone() { return (PollItemsResponse) super.clone(); } }
{ "content_hash": "5971c83d16c969103ed12ca520a1ec95", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 182, "avg_line_length": 36.717948717948715, "alnum_prop": 0.7300977653631285, "repo_name": "googleapis/google-api-java-client-services", "id": "37ef8f12f1e859107587baa0dc12710962f7807c", "size": "2864", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "clients/google-api-services-cloudsearch/v1/1.30.1/com/google/api/services/cloudsearch/v1/model/PollItemsResponse.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.jetbrains.plugins.scala package editor.smartEnter.fixers import com.intellij.openapi.editor.Editor import com.intellij.psi._ import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.plugins.scala.editor.smartEnter.ScalaSmartEnterProcessor import org.jetbrains.plugins.scala.lang.psi.api.expr.{ScBlockExpr, ScForStatement} /** * @author Dmitry.Naydanov * @author Ksenia.Sautina * @since 1/29/13 */ @SuppressWarnings(Array("HardCodedStringLiteral")) class ScalaForStatementFixer extends ScalaFixer { def apply(editor: Editor, processor: ScalaSmartEnterProcessor, psiElement: PsiElement): OperationPerformed = { val forStatement = PsiTreeUtil.getParentOfType(psiElement, classOf[ScForStatement], false) if (forStatement == null) return NoOperation val doc = editor.getDocument val leftParenthesis = forStatement.getLeftParenthesis.orNull val rightParenthesis = forStatement.getRightParenthesis.orNull forStatement.enumerators match { case None if leftParenthesis == null && rightParenthesis == null => val forStartOffset = forStatement.getTextRange.getStartOffset val stopOffset = doc.getLineEndOffset(doc.getLineNumber(forStartOffset)) doc.replaceString(forStartOffset, stopOffset, "for () {\n}") editor.getCaretModel moveToOffset forStartOffset WithReformat(5) case None if leftParenthesis != null && rightParenthesis == null => doc.insertString(forStatement.getTextRange.getEndOffset, ") {\n\n}") WithReformat(0) case None if leftParenthesis != null && rightParenthesis != null => moveToStart(editor, rightParenthesis) doc.insertString(rightParenthesis.getTextRange.getEndOffset, " {\n\n}") WithReformat(0) case Some(cond) if rightParenthesis == null => doc.insertString(cond.getTextRange.getEndOffset, ")") WithReformat(0) case Some(_) if rightParenthesis != null && forStatement.body.exists(_.isInstanceOf[ScBlockExpr]) => placeInWholeBlock(forStatement.body.get.asInstanceOf[ScBlockExpr], editor) case _ => NoOperation } } }
{ "content_hash": "72b81dcc56ad81cd4e1bfe1335752a3e", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 112, "avg_line_length": 41.745098039215684, "alnum_prop": 0.7374354156881164, "repo_name": "triplequote/intellij-scala", "id": "e550823843bfb7fec7bda470d61ca22a714ac4e5", "size": "2129", "binary": false, "copies": "4", "ref": "refs/heads/hydra-integration", "path": "scala/scala-impl/src/org/jetbrains/plugins/scala/editor/smartEnter/fixers/ScalaForStatementFixer.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "56364" }, { "name": "Java", "bytes": "1315289" }, { "name": "Lex", "bytes": "35728" }, { "name": "Scala", "bytes": "11638641" }, { "name": "Shell", "bytes": "537" } ], "symlink_target": "" }
// Copyright 2011-2016 Google LLC // // 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.google.security.zynamics.binnavi.debug.connection.packets.replyparsers; import com.google.security.zynamics.binnavi.debug.connection.DebugCommandType; import com.google.security.zynamics.binnavi.debug.connection.interfaces.ClientReader; import com.google.security.zynamics.binnavi.debug.connection.packets.replies.ThreadClosedReply; import java.io.IOException; /** * Parser responsible for parsing Thread Closed replies. */ public final class ThreadClosedParser extends AbstractReplyParser<ThreadClosedReply> { /** * Creates a new Thread Closed reply parser. * * @param clientReader Used to read messages sent by the debug client. */ public ThreadClosedParser(final ClientReader clientReader) { super(clientReader, DebugCommandType.RESP_THREAD_CLOSED); } @Override protected ThreadClosedReply parseError(final int packetId) { // TODO: There is no proper handling of errors on the side of the // client yet. throw new IllegalStateException("IE01091: Received invalid reply from the debug client"); } @Override public ThreadClosedReply parseSuccess(final int packetId, final int argumentCount) throws IOException { return new ThreadClosedReply(packetId, 0, parseThreadId()); } }
{ "content_hash": "e37c245d692e5dfa283d106ca8bb5ed0", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 95, "avg_line_length": 38.354166666666664, "alnum_prop": 0.7696903856599674, "repo_name": "google/binnavi", "id": "e2750ca1cd28b12a286171293a6ad5e3bd9fb774", "size": "1841", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/google/security/zynamics/binnavi/debug/connection/packets/replyparsers/ThreadClosedParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1489" }, { "name": "C", "bytes": "8997" }, { "name": "C++", "bytes": "982064" }, { "name": "CMake", "bytes": "1953" }, { "name": "CSS", "bytes": "12843" }, { "name": "GAP", "bytes": "3637" }, { "name": "HTML", "bytes": "437459" }, { "name": "Java", "bytes": "21714625" }, { "name": "Makefile", "bytes": "3498" }, { "name": "PLpgSQL", "bytes": "180849" }, { "name": "Python", "bytes": "23981" }, { "name": "Shell", "bytes": "713" } ], "symlink_target": "" }
module Azure::DevSpaces::Mgmt::V2018_06_01_preview module Models # # Model object. # # class OrchestratorSpecificConnectionDetails include MsRestAzure @@discriminatorMap = Hash.new @@discriminatorMap["Kubernetes"] = "KubernetesConnectionDetails" def initialize @instanceType = "OrchestratorSpecificConnectionDetails" end attr_accessor :instanceType # # Mapper for OrchestratorSpecificConnectionDetails class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'OrchestratorSpecificConnectionDetails', type: { name: 'Composite', polymorphic_discriminator: 'instanceType', uber_parent: 'OrchestratorSpecificConnectionDetails', class_name: 'OrchestratorSpecificConnectionDetails', model_properties: { } } } end end end end
{ "content_hash": "1654251dda0616d5b5d32e947176578a", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 76, "avg_line_length": 25.595238095238095, "alnum_prop": 0.6213953488372093, "repo_name": "Azure/azure-sdk-for-ruby", "id": "f6ed05f9fa91c1b29a42b0d4aafe14ff06204a9c", "size": "1239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "management/azure_mgmt_dev_spaces/lib/2018-06-01-preview/generated/azure_mgmt_dev_spaces/models/orchestrator_specific_connection_details.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "345216400" }, { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
package wasdev.sample; /** * Represents a Visitor document stored in Cloudant. */ public class Visitor { private String _id; private String _rev; private String name = null; public Visitor() { this.name = ""; } /** * Gets the ID. * * @return The ID. */ public String get_id() { return _id; } /** * Sets the ID * * @param _id * The ID to set. */ public void set_id(String _id) { this._id = _id; } /** * Gets the revision of the document. * * @return The revision of the document. */ public String get_rev() { return _rev; } /** * Sets the revision. * * @param _rev * The revision to set. */ public void set_rev(String _rev) { this._rev = _rev; } /** * Gets the visitorName of the document. * * @return The name of the document. */ public String getName() { return name; } /** * Sets the name * * @param name * The visitorName to set. */ public void setName(String visitorName) { this.name = visitorName; } }
{ "content_hash": "244925a10cbd6c4fe8c683ba1f2d04ab", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 52, "avg_line_length": 14.18918918918919, "alnum_prop": 0.5628571428571428, "repo_name": "markroberts0830/SimpleJavaApp-MR01", "id": "e4daee17aeb17ccf3b091bb36b9217b5cd0589fd", "size": "1641", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/main/java/wasdev/sample/Visitor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "64" }, { "name": "HTML", "bytes": "4827" }, { "name": "Java", "bytes": "15016" } ], "symlink_target": "" }
package io.netty.handler.codec.dns; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; import java.net.SocketAddress; import static io.netty.util.internal.ObjectUtil.checkNotNull; abstract class DnsResponseDecoder<A extends SocketAddress> { private final DnsRecordDecoder recordDecoder; /** * Creates a new decoder with the specified {@code recordDecoder}. */ DnsResponseDecoder(DnsRecordDecoder recordDecoder) { this.recordDecoder = checkNotNull(recordDecoder, "recordDecoder"); } final DnsResponse decode(A sender, A recipient, ByteBuf buffer) throws Exception { final int id = buffer.readUnsignedShort(); final int flags = buffer.readUnsignedShort(); if (flags >> 15 == 0) { throw new CorruptedFrameException("not a response"); } final DnsResponse response = newResponse( sender, recipient, id, DnsOpCode.valueOf((byte) (flags >> 11 & 0xf)), DnsResponseCode.valueOf((byte) (flags & 0xf))); response.setRecursionDesired((flags >> 8 & 1) == 1); response.setAuthoritativeAnswer((flags >> 10 & 1) == 1); response.setTruncated((flags >> 9 & 1) == 1); response.setRecursionAvailable((flags >> 7 & 1) == 1); response.setZ(flags >> 4 & 0x7); boolean success = false; try { final int questionCount = buffer.readUnsignedShort(); final int answerCount = buffer.readUnsignedShort(); final int authorityRecordCount = buffer.readUnsignedShort(); final int additionalRecordCount = buffer.readUnsignedShort(); decodeQuestions(response, buffer, questionCount); decodeRecords(response, DnsSection.ANSWER, buffer, answerCount); decodeRecords(response, DnsSection.AUTHORITY, buffer, authorityRecordCount); decodeRecords(response, DnsSection.ADDITIONAL, buffer, additionalRecordCount); success = true; return response; } finally { if (!success) { response.release(); } } } protected abstract DnsResponse newResponse(A sender, A recipient, int id, DnsOpCode opCode, DnsResponseCode responseCode) throws Exception; private void decodeQuestions(DnsResponse response, ByteBuf buf, int questionCount) throws Exception { for (int i = questionCount; i > 0; i --) { response.addRecord(DnsSection.QUESTION, recordDecoder.decodeQuestion(buf)); } } private void decodeRecords( DnsResponse response, DnsSection section, ByteBuf buf, int count) throws Exception { for (int i = count; i > 0; i --) { final DnsRecord r = recordDecoder.decodeRecord(buf); if (r == null) { // Truncated response break; } response.addRecord(section, r); } } }
{ "content_hash": "c2fde1c9267e56628da72aa4ad544b76", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 112, "avg_line_length": 36.78313253012048, "alnum_prop": 0.6180805764821488, "repo_name": "jchambers/netty", "id": "fd5a1bed91ca7c3e81da9824be296ad8f00d0d62", "size": "3687", "binary": false, "copies": "2", "ref": "refs/heads/4.1", "path": "codec-dns/src/main/java/io/netty/handler/codec/dns/DnsResponseDecoder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "174426" }, { "name": "C++", "bytes": "1637" }, { "name": "CSS", "bytes": "49" }, { "name": "Groovy", "bytes": "1755" }, { "name": "HTML", "bytes": "1466" }, { "name": "Java", "bytes": "15422769" }, { "name": "Makefile", "bytes": "1577" }, { "name": "Shell", "bytes": "8541" } ], "symlink_target": "" }
package org.apache.accumulo.shell.commands; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import jline.console.ConsoleReader; import jline.console.history.History; import jline.console.history.MemoryHistory; import org.apache.accumulo.shell.Shell; import org.apache.commons.cli.CommandLine; import org.junit.Assume; import org.junit.Before; import org.junit.Test; public class HistoryCommandTest { HistoryCommand command; CommandLine cl; ByteArrayOutputStream baos; ConsoleReader reader; Shell shell; @Before public void setUp() throws Exception { command = new HistoryCommand(); command.getOptions(); // Make sure everything is initialized cl = createMock(CommandLine.class); expect(cl.hasOption("c")).andReturn(false); expect(cl.hasOption("np")).andReturn(true); replay(cl); History history = new MemoryHistory(); history.add("foo"); history.add("bar"); baos = new ByteArrayOutputStream(); String input = String.format("!1%n"); // Construct a platform dependent new-line reader = new ConsoleReader(new ByteArrayInputStream(input.getBytes()), baos); reader.setHistory(history); shell = new Shell(reader, null); } @Test public void testCorrectNumbering() throws IOException { command.execute("", cl, shell); reader.flush(); assertTrue(baos.toString().contains("2: bar")); } @Test public void testEventExpansion() throws IOException { // If we use an unsupported terminal, then history expansion doesn't work because JLine can't do magic buffer manipulations. // This has been observed to be the case on certain versions of Eclipse. However, mvn is usually fine. Assume.assumeTrue(reader.getTerminal().isSupported()); reader.readLine(); assertTrue(baos.toString().trim().endsWith("foo")); } }
{ "content_hash": "385fb67f85ca12586a9646177d7c3501", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 128, "avg_line_length": 27.89189189189189, "alnum_prop": 0.7364341085271318, "repo_name": "adamjshook/accumulo", "id": "638af3f48aca4606111344c55f98fde9873b1eda", "size": "2865", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shell/src/test/java/org/apache/accumulo/shell/commands/HistoryCommandTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2423" }, { "name": "C++", "bytes": "1414083" }, { "name": "CSS", "bytes": "5933" }, { "name": "Groovy", "bytes": "1385" }, { "name": "HTML", "bytes": "11698" }, { "name": "Java", "bytes": "20215877" }, { "name": "JavaScript", "bytes": "249594" }, { "name": "Makefile", "bytes": "2865" }, { "name": "Perl", "bytes": "28190" }, { "name": "Protocol Buffer", "bytes": "1325" }, { "name": "Python", "bytes": "729147" }, { "name": "Ruby", "bytes": "211593" }, { "name": "Shell", "bytes": "194340" }, { "name": "Thrift", "bytes": "55653" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <gradient android:startColor="@color/grass" android:endColor="@color/grass_transparent" android:dither="true"/> </shape>
{ "content_hash": "87b7059f2a1fdc2d53ce670ebb81db71", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 66, "avg_line_length": 33.857142857142854, "alnum_prop": 0.7088607594936709, "repo_name": "ognev-zair/Kotlin-AgendaCalendarView", "id": "8518571a78372056566d3e544642f09f72aa8ee5", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kotlin-agendacalendarview/src/main/res/drawable/gradient_grass.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Kotlin", "bytes": "87975" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Mon Aug 17 17:12:12 IST 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Uses of Class org.apache.solr.morphlines.solr.SolrClientDocumentLoader (Solr 5.3.0 API)</title> <meta name="date" content="2015-08-17"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.morphlines.solr.SolrClientDocumentLoader (Solr 5.3.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../../../../../../org/apache/solr/morphlines/solr/package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/morphlines/solr/SolrClientDocumentLoader.html" title="class in org.apache.solr.morphlines.solr">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/morphlines/solr/class-use/SolrClientDocumentLoader.html" target="_top">Frames</a></li> <li><a href="SolrClientDocumentLoader.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</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="header"> <h2 title="Uses of Class org.apache.solr.morphlines.solr.SolrClientDocumentLoader" class="title">Uses of Class<br>org.apache.solr.morphlines.solr.SolrClientDocumentLoader</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.solr.morphlines.solr"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/solr/morphlines/solr/SolrClientDocumentLoader.html" title="class in org.apache.solr.morphlines.solr">SolrClientDocumentLoader</a> in <a href="../../../../../../org/apache/solr/morphlines/solr/package-summary.html">org.apache.solr.morphlines.solr</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../org/apache/solr/morphlines/solr/SolrClientDocumentLoader.html" title="class in org.apache.solr.morphlines.solr">SolrClientDocumentLoader</a> in <a href="../../../../../../org/apache/solr/morphlines/solr/package-summary.html">org.apache.solr.morphlines.solr</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/morphlines/solr/SolrServerDocumentLoader.html" title="class in org.apache.solr.morphlines.solr">SolrServerDocumentLoader</a></strong></code> <div class="block"><strong>Deprecated.</strong>&nbsp; <div class="block"><i>Use <a href="../../../../../../org/apache/solr/morphlines/solr/SolrClientDocumentLoader.html" title="class in org.apache.solr.morphlines.solr"><code>SolrClientDocumentLoader</code></a></i></div> </div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../../../../../../org/apache/solr/morphlines/solr/package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/morphlines/solr/SolrClientDocumentLoader.html" title="class in org.apache.solr.morphlines.solr">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/morphlines/solr/class-use/SolrClientDocumentLoader.html" target="_top">Frames</a></li> <li><a href="SolrClientDocumentLoader.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</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 ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2015 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
{ "content_hash": "c90b30f0f1c0c3b3035b1df7894e1e4d", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 367, "avg_line_length": 42.0375, "alnum_prop": 0.6236990782039845, "repo_name": "changwu/mqa", "id": "80b9a79cc7db4540d4f4aef22b96f829e31b57e1", "size": "6726", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "solr-5.3.0/docs/solr-morphlines-core/org/apache/solr/morphlines/solr/class-use/SolrClientDocumentLoader.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "291" }, { "name": "Batchfile", "bytes": "46111" }, { "name": "CSS", "bytes": "418498" }, { "name": "HTML", "bytes": "60871995" }, { "name": "Java", "bytes": "1263530" }, { "name": "JavaScript", "bytes": "1227196" }, { "name": "Python", "bytes": "3829" }, { "name": "Shell", "bytes": "321650" }, { "name": "XSLT", "bytes": "271109" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>htmlroot</title> <link rel="stylesheet" href="/override.css"> </head> <body> <div id="battleground"></div> </body> </html>
{ "content_hash": "6559bbeadcdf6fe7a0aa67259c8caeb6", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 52, "avg_line_length": 21.90909090909091, "alnum_prop": 0.5228215767634855, "repo_name": "webdev1001/uncss", "id": "389d0ba454ab11d3569bca196a08f77738b98a8f", "size": "241", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "tests/coverage/htmlroot.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31047" }, { "name": "HTML", "bytes": "22310" }, { "name": "JavaScript", "bytes": "52951" } ], "symlink_target": "" }
/** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; if (timeShiftOrScheduler === undefined) { timeShift = timeSpan; } if (scheduler === undefined) { scheduler = timeoutScheduler; } if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (typeof timeShiftOrScheduler === 'object') { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onNext(x); } }, function (e) { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onError(e); } observer.onError(e); }, function () { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); };
{ "content_hash": "da25a4b048030db6b615fb0fa66e7d0c", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 298, "avg_line_length": 42.39, "alnum_prop": 0.48242510025949514, "repo_name": "haghard/splanet", "id": "5e7c1f65172bf4a8769a117817f18819c6170df5", "size": "4239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/bootstrap/RxJS/src/core/linq/observable/windowwithtime.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "184136" }, { "name": "Groovy", "bytes": "15020" }, { "name": "Java", "bytes": "29622" }, { "name": "JavaScript", "bytes": "936649" }, { "name": "PHP", "bytes": "448" }, { "name": "Python", "bytes": "3515" }, { "name": "Scala", "bytes": "74848" }, { "name": "Shell", "bytes": "2101" } ], "symlink_target": "" }
from pexdoc.ptypes import real_num, positive_real_num, offset_range, function from peng.ptypes import real_numpy_vector, increasing_real_numpy_vector # Intra-package imports from .basic_source import BasicSource from .csv_source import CsvSource from .series import Series from .panel import Panel from .figure import Figure from .functions import parameterized_color_space, DataSource from pplot.ptypes import interpolation_option, line_style_option, color_space_option from .constants import ( AXIS_LABEL_FONT_SIZE, AXIS_TICKS_FONT_SIZE, LEGEND_SCALE, LINE_WIDTH, MARKER_SIZE, MIN_TICKS, PRECISION, SUGGESTED_MAX_TICKS, TITLE_FONT_SIZE, )
{ "content_hash": "fb104ac729f602c15cd3b4aaff58f888", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 84, "avg_line_length": 30.818181818181817, "alnum_prop": 0.7654867256637168, "repo_name": "pmacosta/pplot", "id": "d24483c15100646920d51aad62839a22ef4e9e3e", "size": "818", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pplot/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "3515" }, { "name": "Python", "bytes": "407899" }, { "name": "Shell", "bytes": "14220" } ], "symlink_target": "" }
<resources> <!-- BASE COLORS --> <color name="white">#FFFFFF</color> <color name="black">#000000</color> <color name="grey">#808080</color> <color name="grey_text">#dadada</color> <color name="grey_text_to">#878787</color> <color name="blue">#5dfffe</color> <color name="blue_grey">#92a6a6</color> <color name="blue_alpha">#AA5dfffe</color> <color name="blue_green">#9fe0e0</color> <!-- TRANSPARENCY --> <color name="transparent">#00ffffff</color> <color name="alpha_white">#55ffffff</color> <color name="alpha_black">#66000000</color> <!-- BACKGROUND --> <color name="background">#fcfcfc</color> </resources>
{ "content_hash": "0219ee9e41b2142a07c292261a8e88c6", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 47, "avg_line_length": 30.772727272727273, "alnum_prop": 0.621861152141802, "repo_name": "kimhansen/Fairphone---DEPRECATED", "id": "be75c4b9f079133e5ec2f1110ec21f355cdff5b0", "size": "677", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "FairPhonePeaceOfMind/res/values/colors.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1621885" }, { "name": "Python", "bytes": "5738" } ], "symlink_target": "" }
import {CONFIG_TAG, SERVICE_TAG, TAG} from './vars'; import {Layout} from '../../../src/layout'; import {dev, user} from '../../../src/log'; import {escapeCssSelectorIdent} from '../../../src/dom'; import {getServiceForDoc} from '../../../src/service'; import {parseUrl} from '../../../src/url'; /** @enum {string} */ export const WebPushConfigAttributes = { HELPER_FRAME_URL: 'helper-iframe-url', PERMISSION_DIALOG_URL: 'permission-dialog-url', SERVICE_WORKER_URL: 'service-worker-url', }; /** @enum {string} */ export const WebPushWidgetActions = { SUBSCRIBE: 'subscribe', UNSUBSCRIBE: 'unsubscribe', }; /** @typedef {{ * 'helper-iframe-url': (?string|undefined), * 'permission-dialog-url': (?string|undefined), * 'service-worker-url': (?string|undefined), * }} */ export let AmpWebPushConfig; /** * @fileoverview * The element that exposes attributes for publishers to configure the web push * service. * * On buildCallback(), the element starts the web push service. * * Only a single element of this kind is allowed in the document, and it must * have the ID "amp-web-push". Subscribe and unsubscribe actions dispatched from * various widget elements are all processed by this element which then forwards * the event to the web push service. */ export class WebPushConfig extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); } /** @override */ isLayoutSupported(layout) { return layout == Layout.NODISPLAY; } /** * Validates that this element instance has an ID attribute of 'amp-web-push' * and that there are no other elements of the same tag name. */ validate() { this.ensureSpecificElementId_(); this.ensureUniqueElement_(); const config = { 'helper-iframe-url': null, 'permission-dialog-url': null, 'service-worker-url': null, }; for (const attribute in WebPushConfigAttributes) { const value = WebPushConfigAttributes[attribute]; user().assert( this.element.getAttribute(value), `The ${value} attribute is required for <${CONFIG_TAG}>` ); config[value] = this.element.getAttribute(value); } if ( !this.isValidHelperOrPermissionDialogUrl_(config['helper-iframe-url']) ) { throw user().createError( `<${CONFIG_TAG}> must have a valid ` + 'helper-iframe-url attribute. It should begin with ' + 'the https:// protocol and point to the provided lightweight ' + 'template page provided for AMP messaging.' ); } if ( !this.isValidHelperOrPermissionDialogUrl_(config['permission-dialog-url']) ) { throw user().createError( `<${CONFIG_TAG}> must have a valid ` + 'permission-dialog-url attribute. It should begin with ' + 'the https:// protocol and point to the provided template page ' + 'for showing the permission prompt.' ); } if (parseUrl(config['service-worker-url']).protocol !== 'https:') { throw user().createError( `<${CONFIG_TAG}> must have a valid ` + 'service-worker-url attribute. It should begin with the ' + 'https:// protocol and point to the service worker JavaScript file ' + 'to be installed.' ); } if ( parseUrl(config['service-worker-url']).origin !== parseUrl(config['permission-dialog-url']).origin || parseUrl(config['permission-dialog-url']).origin !== parseUrl(config['helper-iframe-url']).origin ) { throw user().createError( `<${CONFIG_TAG}> URL attributes ` + 'service-worker-url, permission-dialog-url, and ' + 'helper-iframe-url must all share the same origin.' ); } } /** * Parses the JSON configuration and returns a JavaScript object. * @return {AmpWebPushConfig} */ parseConfig() { const config = {}; for (const attribute in WebPushConfigAttributes) { const value = WebPushConfigAttributes[attribute]; config[value] = this.element.getAttribute(value); } return config; } /** @override */ buildCallback() { this.validate(); const config = this.parseConfig(); const webPushService = getServiceForDoc(this.getAmpDoc(), SERVICE_TAG); webPushService.start(config).catch(() => {}); this.registerAction( WebPushWidgetActions.SUBSCRIBE, this.onSubscribe_.bind(this) ); this.registerAction( WebPushWidgetActions.UNSUBSCRIBE, this.onUnsubscribe_.bind(this) ); } /** * Ensures this element is defined with TAG id. * @private */ ensureSpecificElementId_() { if (this.element.getAttribute('id') !== TAG) { throw user().createError( `<${CONFIG_TAG}> must have an id ` + "attribute with value '" + TAG + "'." ); } } /** * Ensures there isn't another page element with the same id. * @private */ ensureUniqueElement_() { const webPushConfigElements = this.getAmpDoc() .getRootNode() .querySelectorAll(`#${escapeCssSelectorIdent(CONFIG_TAG)}`); if (webPushConfigElements.length > 1) { throw user().createError( `Only one <${CONFIG_TAG}> element may exist on a page.` ); } } /** * @param {!../../../src/service/action-impl.ActionInvocation} invocation * @private */ onSubscribe_(invocation) { // Disable the widget temporarily to prevent multiple clicks The widget will // be re-enabled when the popup is closed, or the user interacts with the // prompt const widget = dev().assertElement(invocation.event.target); this.setWidgetDisabled_(widget, true); const webPushService = getServiceForDoc(this.getAmpDoc(), SERVICE_TAG); webPushService .subscribe(() => { // On popup closed this.setWidgetDisabled_(widget, false); }) .then(() => { // On browser notification permission granted, denied, or dismissed this.setWidgetDisabled_(widget, false); }); } /** * * @param {!Element} widget * @param {boolean} isDisabled * @private */ setWidgetDisabled_(widget, isDisabled) { widget.disabled = isDisabled; } /** * @param {!../../../src/service/action-impl.ActionInvocation} invocation * @private */ onUnsubscribe_(invocation) { const widget = dev().assertElement(invocation.event.target); this.setWidgetDisabled_(widget, true); const webPushService = getServiceForDoc(this.getAmpDoc(), SERVICE_TAG); webPushService.unsubscribe().then(() => { this.setWidgetDisabled_(widget, false); }); } /** * @private * @param {string} url * @return {boolean} */ isValidHelperOrPermissionDialogUrl_(url) { try { const parsedUrl = parseUrl(url); /* The helper-iframe-url must be to a specific lightweight page on the user's site for handling AMP postMessage calls without loading push vendor-specific SDKs or other resources. It should not be the site root. The permission-dialog-url can load push vendor-specific SDKs, but it should still not be the site root and should be a dedicated page for subscribing. */ const isNotRootUrl = parsedUrl.pathname.length > 1; /* Similar to <amp-form> and <amp-iframe>, the helper and subscribe URLs must be HTTPS. This is because most AMP caches serve pages over HTTPS, and an HTTP iframe URL would not load due to insecure resources being blocked on a secure page. */ const isSecureUrl = parsedUrl.protocol === 'https:'; return isSecureUrl && isNotRootUrl; } catch (e) { return false; } } }
{ "content_hash": "d94d1aaf8b27d6b7068136120f4996a6", "timestamp": "", "source": "github", "line_count": 263, "max_line_length": 80, "avg_line_length": 29.779467680608366, "alnum_prop": 0.6288304392236976, "repo_name": "yieldmo/amphtml", "id": "2c50575359d108259a72035f27d7eeb519f344e7", "size": "8459", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "extensions/amp-web-push/0.1/amp-web-push-config.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "206113" }, { "name": "Go", "bytes": "15254" }, { "name": "HTML", "bytes": "1104594" }, { "name": "Java", "bytes": "36670" }, { "name": "JavaScript", "bytes": "10018090" }, { "name": "Python", "bytes": "80081" }, { "name": "Ruby", "bytes": "15912" }, { "name": "Shell", "bytes": "12162" }, { "name": "Yacc", "bytes": "22292" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_17a.html">Class Test_AbaRouteValidator_17a</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_35840_bad </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a.html?line=18181#src-18181" >testAbaNumberCheck_35840_bad</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:46:07 </td> <td> 0.0 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_35840_bad</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=7409#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a> </td> <td> <span class="sortValue">0.5714286</span>57.1% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td> </tr> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=7409#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a> </td> <td> <span class="sortValue">0.5714286</span>57.1% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td> </tr> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=7409#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.29411766</span>29.4% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
{ "content_hash": "2d8076a6a0d14209b88c2e2bd02499d7", "timestamp": "", "source": "github", "line_count": 235, "max_line_length": 358, "avg_line_length": 46.753191489361704, "alnum_prop": 0.5303540547920269, "repo_name": "dcarda/aba.route.validator", "id": "4b39fc2d0b602caa4bcd6069d63043d2afcbafa2", "size": "10987", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_17a_testAbaNumberCheck_35840_bad_5pt.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18715254" } ], "symlink_target": "" }
package com.amazonaws.services.costexplorer.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Details about the Amazon EC2 instances that Amazon Web Services recommends that you purchase. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ce-2017-10-25/EC2InstanceDetails" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class EC2InstanceDetails implements Serializable, Cloneable, StructuredPojo { /** * <p> * The instance family of the recommended reservation. * </p> */ private String family; /** * <p> * The type of instance that Amazon Web Services recommends. * </p> */ private String instanceType; /** * <p> * The Amazon Web Services Region of the recommended reservation. * </p> */ private String region; /** * <p> * The Availability Zone of the recommended reservation. * </p> */ private String availabilityZone; /** * <p> * The platform of the recommended reservation. The platform is the specific combination of operating system, * license model, and software on an instance. * </p> */ private String platform; /** * <p> * Determines whether the recommended reservation is dedicated or shared. * </p> */ private String tenancy; /** * <p> * Determines whether the recommendation is for a current-generation instance. * </p> */ private Boolean currentGeneration; /** * <p> * Determines whether the recommended reservation is size flexible. * </p> */ private Boolean sizeFlexEligible; /** * <p> * The instance family of the recommended reservation. * </p> * * @param family * The instance family of the recommended reservation. */ public void setFamily(String family) { this.family = family; } /** * <p> * The instance family of the recommended reservation. * </p> * * @return The instance family of the recommended reservation. */ public String getFamily() { return this.family; } /** * <p> * The instance family of the recommended reservation. * </p> * * @param family * The instance family of the recommended reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public EC2InstanceDetails withFamily(String family) { setFamily(family); return this; } /** * <p> * The type of instance that Amazon Web Services recommends. * </p> * * @param instanceType * The type of instance that Amazon Web Services recommends. */ public void setInstanceType(String instanceType) { this.instanceType = instanceType; } /** * <p> * The type of instance that Amazon Web Services recommends. * </p> * * @return The type of instance that Amazon Web Services recommends. */ public String getInstanceType() { return this.instanceType; } /** * <p> * The type of instance that Amazon Web Services recommends. * </p> * * @param instanceType * The type of instance that Amazon Web Services recommends. * @return Returns a reference to this object so that method calls can be chained together. */ public EC2InstanceDetails withInstanceType(String instanceType) { setInstanceType(instanceType); return this; } /** * <p> * The Amazon Web Services Region of the recommended reservation. * </p> * * @param region * The Amazon Web Services Region of the recommended reservation. */ public void setRegion(String region) { this.region = region; } /** * <p> * The Amazon Web Services Region of the recommended reservation. * </p> * * @return The Amazon Web Services Region of the recommended reservation. */ public String getRegion() { return this.region; } /** * <p> * The Amazon Web Services Region of the recommended reservation. * </p> * * @param region * The Amazon Web Services Region of the recommended reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public EC2InstanceDetails withRegion(String region) { setRegion(region); return this; } /** * <p> * The Availability Zone of the recommended reservation. * </p> * * @param availabilityZone * The Availability Zone of the recommended reservation. */ public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; } /** * <p> * The Availability Zone of the recommended reservation. * </p> * * @return The Availability Zone of the recommended reservation. */ public String getAvailabilityZone() { return this.availabilityZone; } /** * <p> * The Availability Zone of the recommended reservation. * </p> * * @param availabilityZone * The Availability Zone of the recommended reservation. * @return Returns a reference to this object so that method calls can be chained together. */ public EC2InstanceDetails withAvailabilityZone(String availabilityZone) { setAvailabilityZone(availabilityZone); return this; } /** * <p> * The platform of the recommended reservation. The platform is the specific combination of operating system, * license model, and software on an instance. * </p> * * @param platform * The platform of the recommended reservation. The platform is the specific combination of operating system, * license model, and software on an instance. */ public void setPlatform(String platform) { this.platform = platform; } /** * <p> * The platform of the recommended reservation. The platform is the specific combination of operating system, * license model, and software on an instance. * </p> * * @return The platform of the recommended reservation. The platform is the specific combination of operating * system, license model, and software on an instance. */ public String getPlatform() { return this.platform; } /** * <p> * The platform of the recommended reservation. The platform is the specific combination of operating system, * license model, and software on an instance. * </p> * * @param platform * The platform of the recommended reservation. The platform is the specific combination of operating system, * license model, and software on an instance. * @return Returns a reference to this object so that method calls can be chained together. */ public EC2InstanceDetails withPlatform(String platform) { setPlatform(platform); return this; } /** * <p> * Determines whether the recommended reservation is dedicated or shared. * </p> * * @param tenancy * Determines whether the recommended reservation is dedicated or shared. */ public void setTenancy(String tenancy) { this.tenancy = tenancy; } /** * <p> * Determines whether the recommended reservation is dedicated or shared. * </p> * * @return Determines whether the recommended reservation is dedicated or shared. */ public String getTenancy() { return this.tenancy; } /** * <p> * Determines whether the recommended reservation is dedicated or shared. * </p> * * @param tenancy * Determines whether the recommended reservation is dedicated or shared. * @return Returns a reference to this object so that method calls can be chained together. */ public EC2InstanceDetails withTenancy(String tenancy) { setTenancy(tenancy); return this; } /** * <p> * Determines whether the recommendation is for a current-generation instance. * </p> * * @param currentGeneration * Determines whether the recommendation is for a current-generation instance. */ public void setCurrentGeneration(Boolean currentGeneration) { this.currentGeneration = currentGeneration; } /** * <p> * Determines whether the recommendation is for a current-generation instance. * </p> * * @return Determines whether the recommendation is for a current-generation instance. */ public Boolean getCurrentGeneration() { return this.currentGeneration; } /** * <p> * Determines whether the recommendation is for a current-generation instance. * </p> * * @param currentGeneration * Determines whether the recommendation is for a current-generation instance. * @return Returns a reference to this object so that method calls can be chained together. */ public EC2InstanceDetails withCurrentGeneration(Boolean currentGeneration) { setCurrentGeneration(currentGeneration); return this; } /** * <p> * Determines whether the recommendation is for a current-generation instance. * </p> * * @return Determines whether the recommendation is for a current-generation instance. */ public Boolean isCurrentGeneration() { return this.currentGeneration; } /** * <p> * Determines whether the recommended reservation is size flexible. * </p> * * @param sizeFlexEligible * Determines whether the recommended reservation is size flexible. */ public void setSizeFlexEligible(Boolean sizeFlexEligible) { this.sizeFlexEligible = sizeFlexEligible; } /** * <p> * Determines whether the recommended reservation is size flexible. * </p> * * @return Determines whether the recommended reservation is size flexible. */ public Boolean getSizeFlexEligible() { return this.sizeFlexEligible; } /** * <p> * Determines whether the recommended reservation is size flexible. * </p> * * @param sizeFlexEligible * Determines whether the recommended reservation is size flexible. * @return Returns a reference to this object so that method calls can be chained together. */ public EC2InstanceDetails withSizeFlexEligible(Boolean sizeFlexEligible) { setSizeFlexEligible(sizeFlexEligible); return this; } /** * <p> * Determines whether the recommended reservation is size flexible. * </p> * * @return Determines whether the recommended reservation is size flexible. */ public Boolean isSizeFlexEligible() { return this.sizeFlexEligible; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFamily() != null) sb.append("Family: ").append(getFamily()).append(","); if (getInstanceType() != null) sb.append("InstanceType: ").append(getInstanceType()).append(","); if (getRegion() != null) sb.append("Region: ").append(getRegion()).append(","); if (getAvailabilityZone() != null) sb.append("AvailabilityZone: ").append(getAvailabilityZone()).append(","); if (getPlatform() != null) sb.append("Platform: ").append(getPlatform()).append(","); if (getTenancy() != null) sb.append("Tenancy: ").append(getTenancy()).append(","); if (getCurrentGeneration() != null) sb.append("CurrentGeneration: ").append(getCurrentGeneration()).append(","); if (getSizeFlexEligible() != null) sb.append("SizeFlexEligible: ").append(getSizeFlexEligible()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof EC2InstanceDetails == false) return false; EC2InstanceDetails other = (EC2InstanceDetails) obj; if (other.getFamily() == null ^ this.getFamily() == null) return false; if (other.getFamily() != null && other.getFamily().equals(this.getFamily()) == false) return false; if (other.getInstanceType() == null ^ this.getInstanceType() == null) return false; if (other.getInstanceType() != null && other.getInstanceType().equals(this.getInstanceType()) == false) return false; if (other.getRegion() == null ^ this.getRegion() == null) return false; if (other.getRegion() != null && other.getRegion().equals(this.getRegion()) == false) return false; if (other.getAvailabilityZone() == null ^ this.getAvailabilityZone() == null) return false; if (other.getAvailabilityZone() != null && other.getAvailabilityZone().equals(this.getAvailabilityZone()) == false) return false; if (other.getPlatform() == null ^ this.getPlatform() == null) return false; if (other.getPlatform() != null && other.getPlatform().equals(this.getPlatform()) == false) return false; if (other.getTenancy() == null ^ this.getTenancy() == null) return false; if (other.getTenancy() != null && other.getTenancy().equals(this.getTenancy()) == false) return false; if (other.getCurrentGeneration() == null ^ this.getCurrentGeneration() == null) return false; if (other.getCurrentGeneration() != null && other.getCurrentGeneration().equals(this.getCurrentGeneration()) == false) return false; if (other.getSizeFlexEligible() == null ^ this.getSizeFlexEligible() == null) return false; if (other.getSizeFlexEligible() != null && other.getSizeFlexEligible().equals(this.getSizeFlexEligible()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFamily() == null) ? 0 : getFamily().hashCode()); hashCode = prime * hashCode + ((getInstanceType() == null) ? 0 : getInstanceType().hashCode()); hashCode = prime * hashCode + ((getRegion() == null) ? 0 : getRegion().hashCode()); hashCode = prime * hashCode + ((getAvailabilityZone() == null) ? 0 : getAvailabilityZone().hashCode()); hashCode = prime * hashCode + ((getPlatform() == null) ? 0 : getPlatform().hashCode()); hashCode = prime * hashCode + ((getTenancy() == null) ? 0 : getTenancy().hashCode()); hashCode = prime * hashCode + ((getCurrentGeneration() == null) ? 0 : getCurrentGeneration().hashCode()); hashCode = prime * hashCode + ((getSizeFlexEligible() == null) ? 0 : getSizeFlexEligible().hashCode()); return hashCode; } @Override public EC2InstanceDetails clone() { try { return (EC2InstanceDetails) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.costexplorer.model.transform.EC2InstanceDetailsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
{ "content_hash": "9b46a9d96e9391a607e8ea29a7c35e6a", "timestamp": "", "source": "github", "line_count": 527, "max_line_length": 138, "avg_line_length": 31.381404174573056, "alnum_prop": 0.6179102672632725, "repo_name": "aws/aws-sdk-java", "id": "e36a9f640b76958b8a6f90260bad8148f6618638", "size": "17118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-costexplorer/src/main/java/com/amazonaws/services/costexplorer/model/EC2InstanceDetails.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace google_apis { const char kAPIKeysDevelopersHowToURL[] = "http://www.chromium.org/developers/how-tos/api-keys"; // This is used as a lazy instance to determine keys once and cache them. class APIKeyCache { public: APIKeyCache() { scoped_ptr<base::Environment> environment(base::Environment::Create()); base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); api_key_ = CalculateKeyValue(GOOGLE_API_KEY, STRINGIZE_NO_EXPANSION(GOOGLE_API_KEY), NULL, std::string(), environment.get(), command_line); api_key_safesites_ = CalculateKeyValue(GOOGLE_API_KEY_SAFESITES, STRINGIZE_NO_EXPANSION(GOOGLE_API_KEY_SAFESITES), NULL, std::string(), environment.get(), command_line); std::string default_client_id = CalculateKeyValue(GOOGLE_DEFAULT_CLIENT_ID, STRINGIZE_NO_EXPANSION(GOOGLE_DEFAULT_CLIENT_ID), NULL, std::string(), environment.get(), command_line); std::string default_client_secret = CalculateKeyValue(GOOGLE_DEFAULT_CLIENT_SECRET, STRINGIZE_NO_EXPANSION(GOOGLE_DEFAULT_CLIENT_SECRET), NULL, std::string(), environment.get(), command_line); // We currently only allow overriding the baked-in values for the // default OAuth2 client ID and secret using a command-line // argument, since that is useful to enable testing against // staging servers, and since that was what was possible and // likely practiced by the QA team before this implementation was // written. client_ids_[CLIENT_MAIN] = CalculateKeyValue( GOOGLE_CLIENT_ID_MAIN, STRINGIZE_NO_EXPANSION(GOOGLE_CLIENT_ID_MAIN), switches::kOAuth2ClientID, default_client_id, environment.get(), command_line); client_secrets_[CLIENT_MAIN] = CalculateKeyValue( GOOGLE_CLIENT_SECRET_MAIN, STRINGIZE_NO_EXPANSION(GOOGLE_CLIENT_SECRET_MAIN), switches::kOAuth2ClientSecret, default_client_secret, environment.get(), command_line); client_ids_[CLIENT_CLOUD_PRINT] = CalculateKeyValue( GOOGLE_CLIENT_ID_CLOUD_PRINT, STRINGIZE_NO_EXPANSION(GOOGLE_CLIENT_ID_CLOUD_PRINT), NULL, default_client_id, environment.get(), command_line); client_secrets_[CLIENT_CLOUD_PRINT] = CalculateKeyValue( GOOGLE_CLIENT_SECRET_CLOUD_PRINT, STRINGIZE_NO_EXPANSION(GOOGLE_CLIENT_SECRET_CLOUD_PRINT), NULL, default_client_secret, environment.get(), command_line); client_ids_[CLIENT_REMOTING] = CalculateKeyValue( GOOGLE_CLIENT_ID_REMOTING, STRINGIZE_NO_EXPANSION(GOOGLE_CLIENT_ID_REMOTING), NULL, default_client_id, environment.get(), command_line); client_secrets_[CLIENT_REMOTING] = CalculateKeyValue( GOOGLE_CLIENT_SECRET_REMOTING, STRINGIZE_NO_EXPANSION(GOOGLE_CLIENT_SECRET_REMOTING), NULL, default_client_secret, environment.get(), command_line); client_ids_[CLIENT_REMOTING_HOST] = CalculateKeyValue( GOOGLE_CLIENT_ID_REMOTING_HOST, STRINGIZE_NO_EXPANSION(GOOGLE_CLIENT_ID_REMOTING_HOST), NULL, default_client_id, environment.get(), command_line); client_secrets_[CLIENT_REMOTING_HOST] = CalculateKeyValue( GOOGLE_CLIENT_SECRET_REMOTING_HOST, STRINGIZE_NO_EXPANSION(GOOGLE_CLIENT_SECRET_REMOTING_HOST), NULL, default_client_secret, environment.get(), command_line); } std::string api_key() const { return api_key_; } std::string api_key_safesites() const { return api_key_safesites_; } std::string GetClientID(OAuth2Client client) const { DCHECK_LT(client, CLIENT_NUM_ITEMS); return client_ids_[client]; } std::string GetClientSecret(OAuth2Client client) const { DCHECK_LT(client, CLIENT_NUM_ITEMS); return client_secrets_[client]; } std::string GetSpdyProxyAuthValue() { #if defined(SPDY_PROXY_AUTH_VALUE) return SPDY_PROXY_AUTH_VALUE; #else return std::string(); #endif } private: // Gets a value for a key. In priority order, this will be the value // provided via a command-line switch, the value provided via an // environment variable, or finally a value baked into the build. // |command_line_switch| may be NULL. static std::string CalculateKeyValue(const char* baked_in_value, const char* environment_variable_name, const char* command_line_switch, const std::string& default_if_unset, base::Environment* environment, base::CommandLine* command_line) { std::string key_value = baked_in_value; std::string temp; if (environment->GetVar(environment_variable_name, &temp)) { key_value = temp; VLOG(1) << "Overriding API key " << environment_variable_name << " with value " << key_value << " from environment variable."; } if (command_line_switch && command_line->HasSwitch(command_line_switch)) { key_value = command_line->GetSwitchValueASCII(command_line_switch); VLOG(1) << "Overriding API key " << environment_variable_name << " with value " << key_value << " from command-line switch."; } if (key_value == DUMMY_API_TOKEN) { #if defined(GOOGLE_CHROME_BUILD) // No key should be unset in an official build except the // GOOGLE_DEFAULT_* keys. The default keys don't trigger this // check as their "unset" value is not DUMMY_API_TOKEN. CHECK(false); #endif if (default_if_unset.size() > 0) { VLOG(1) << "Using default value \"" << default_if_unset << "\" for API key " << environment_variable_name; key_value = default_if_unset; } } // This should remain a debug-only log. DVLOG(1) << "API key " << environment_variable_name << "=" << key_value; return key_value; } std::string api_key_; std::string api_key_safesites_; std::string client_ids_[CLIENT_NUM_ITEMS]; std::string client_secrets_[CLIENT_NUM_ITEMS]; }; static base::LazyInstance<APIKeyCache> g_api_key_cache = LAZY_INSTANCE_INITIALIZER; bool HasKeysConfigured() { if (GetAPIKey() == DUMMY_API_TOKEN) return false; for (size_t client_id = 0; client_id < CLIENT_NUM_ITEMS; ++client_id) { OAuth2Client client = static_cast<OAuth2Client>(client_id); if (GetOAuth2ClientID(client) == DUMMY_API_TOKEN || GetOAuth2ClientSecret(client) == DUMMY_API_TOKEN) { return false; } } return true; } std::string GetAPIKey() { return g_api_key_cache.Get().api_key(); } std::string GetSafeSitesAPIKey() { return g_api_key_cache.Get().api_key_safesites(); } std::string GetOAuth2ClientID(OAuth2Client client) { return g_api_key_cache.Get().GetClientID(client); } std::string GetOAuth2ClientSecret(OAuth2Client client) { return g_api_key_cache.Get().GetClientSecret(client); } std::string GetSpdyProxyAuthValue() { return g_api_key_cache.Get().GetSpdyProxyAuthValue(); } bool IsGoogleChromeAPIKeyUsed() { #if defined(GOOGLE_CHROME_BUILD) || defined(USE_OFFICIAL_GOOGLE_API_KEYS) return true; #else return false; #endif } } // namespace google_apis
{ "content_hash": "e2ed42453d8796826469737c69be5a20", "timestamp": "", "source": "github", "line_count": 228, "max_line_length": 79, "avg_line_length": 34.71052631578947, "alnum_prop": 0.6086681829668941, "repo_name": "Workday/OpenFrame", "id": "f919630f40d2c84b6656a51d48864ac9abc049a1", "size": "10255", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "google_apis/google_api_keys.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
Mortal Kombat 11 is one of the most impressive looking games to come out in 2019, with amazing facial animations, subsurface scattering, shadows, lighting, and postprocessing effects. Similar to other frame analysis blog posts like those of Adrian Courreges' DOOM Graphics Study, GTA V Graphics Study, etc. [^courreges2016], I took the time to review each draw call and render pass of the latest Mortal Kombat 11 (2019) and I'm eager to share what's in it: > I'm in no way associated with Netherealm Studios or Mortal Kombat. Please support Mortal Kombat 11 by purchasing a copy of it to see this tech in action, it's an amazing game! ## How to capture I used NVIDIA NSight Graphics to capture Mortal Kombat, first I attached it to Steam and set it so that it would only attach if I requested it. This allows NSight Graphics to attach to child processes of Steam (so any game). I then opened Mortal Kombat in steam and was able to debug it. ## Shadow Pass Each frame starts with a **Shadow Pass**, and uses cascading Moment Shadow Maps [^peters2016] to do it. Each shadow map is composed of a 4x multi-sampled (MSAA) shadow depth stencil map, which is first determined by rendering each primitive (I'll be using the [GLTF 2.0 definition of primitives](https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#meshes) in this blog post), then down-sampling the current segment of the multi-sampled image, and finally converted into cascades. ### Primitive Shadow Depth Map Shader Every primitive in the scene is rendered using the following shader program (translated from the captured [HLSL bytecode](https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl)): ```glsl /** * Fragment Shader */ #version 310 core precision mediump float; precision highp int; struct FragUBO { float meshDepthBias; float shadowDepthBias; float inverseMaxSubjectDepth; }; layout (binding = 0) uniform FragUBO ubo; void main() { float bias = ubo.meshDepthBias + ubo.shadowDepthBias; gl_FragDepth = saturate(gl_FragCoord.z * ubo.inverseMaxSubjectDepth + bias); } ``` ### 4x MSAA Piece-meal composition ![Shadow MSAA Process](assets/shadow-msaa.gif) during multi-sampling the depth and stencil maps are separated and the final multi-sampled output is made piecemeal in order of top left to bottom right via a compute shader. ```glsl /** * 4x MSAA Compute Shader */ ``` For each shadowed light 4x msaa shadow map 1. Shadow map 2. compute downsampled depth and stencil OutTileOccupancyMap from stencil buffer OutTileOcuupancyMapWithBorders write to structured buffers that handle primary, border, and clear tiles Take shadow map ndc depth buffer, tile list, output uavBuffers for xy and zw convert that to uavOutputXYZW shadow array (cascades?) --- ## G-Pass The **G-Pass** (General Pass) stood out for looking pretty strange in Mortal Kombat 11. There are 4 G-Buffers, with each channel corresponding to a wide range of data: ### Inputs Every input in the G-Pass is in a compress format such as BC1_UNORM, BC7_UNORM, BC7_SRGB, etc. save for a color lookup texture that's 256x2, with most textures maxing out at 1024x1024, with some detail normal maps at 256x256. - **Tangent Space Normal Map** ### G-Buffer 0 **Type** RGBAUINT16 **Channels** - Gloss (R), noisy AO (G), depth fract (B), tangent or directional light (A) Stencil IDs (R16UINT) AO R8 Eye(R) SkinHair(G), Haireyesarmor(G), black skingrayeyes(A), --- Build AO from blue noise, downsampeled normal and depth (RG16), and a hierarchical z buffer use material data AO (so baked) Jittered Velocity Buffer (for TAA?, maybe w/ current jitter) Build Shadow Resolve Buffers --- dispatchInderect IBL map, dynamic reflection IBL map, Specular BRDF LookupTable, linearDepthBuffer, GBuffer3, environmentprobe irradiance buffer, tile cubemap indirection list dynamic reflection ibl mask, and calculate specular --- dispatchInderect WorldDepth,GBuffer0-4 stencilTex, contactShadowTex, ShadowResolveTex, List of Point/Spot/ShadowedSpot/DirectionalLights and calculate spec/diffuse irradiance rgb+diffuseexposure array of 3 --- take shadow texture array (12-16), world depth texture, cascade screen to shadow matricies buffer, cascade entries buffer, cascade splits buffer multisampledmap summed area table texture array structured buffer[9] of light data --- Take VolumetricFogScattering Transmission ID Tex Linear NDC Depth Direct Lit Color Indirect Color Direct Spec Indirect Spec Ambient Occlusion and combine diffuse light --- downsample output image a few times bloom texture and world color texture cs --- take current and previous color texture and velocity texture, output LumaSurface OutHistoryBuffer --- Take Tonemapping Look Up Texture LUT, UI, and color ## Primitives Each primitive rendered tends to be have a decent number of polygons, with individual draw calls of 55K, 91K, 69K, 49K, 172K, indices for characters, and 19K for assets. ## Conclusion And following some pretty basic UI draw calls, that's a frame in Mortal Kombat 11!
{ "content_hash": "090beb37b00ecd90e7176f22c13bc040", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 456, "avg_line_length": 29.50581395348837, "alnum_prop": 0.7726108374384236, "repo_name": "alaingalvan/alain.xyz", "id": "a40ea538577a72163cae2b828523e99ecb76a724", "size": "5075", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/portfolio/blog/drafts/frame-analysis-mk11/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "221" }, { "name": "CSS", "bytes": "9398" }, { "name": "GLSL", "bytes": "17578" }, { "name": "Rust", "bytes": "8962" }, { "name": "TypeScript", "bytes": "492357" } ], "symlink_target": "" }
<strings> <string name="date_format" value="dd/MMMM/EEEE" /> <string name="emergency_call" value="Acil Çağrı"/> </strings>
{ "content_hash": "763618824e2234cb614a8e7fa7c7aa76", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 54, "avg_line_length": 32.75, "alnum_prop": 0.6564885496183206, "repo_name": "raoc999/MA-XML-9.0-TURKISH", "id": "642da3b03eb36a4e1c7c2598afd9f2c859256698", "size": "134", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Turkish/extras/lockscreen/advance/strings/strings_tr.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "2659" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Javadoc API documentation for Fresco 1.1.0." /> <link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" /> <title> ImagePipelineNativeLoader - Fresco 1.1.0 API | Fresco 1.1.0 </title> <link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" /> <link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" /> <script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script> <script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script> <script src="../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script> <script src="../../../../../assets/prettify.js" type="text/javascript"></script> <script type="text/javascript"> setToRoot("../../../../", "../../../../../assets/"); </script> <script src="../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script> <script src="../../../../../assets/navtree_data.js" type="text/javascript"></script> <script src="../../../../../assets/customizations.js" type="text/javascript"></script> <noscript> <style type="text/css"> html,body{overflow:auto;} #body-content{position:relative; top:0;} #doc-content{overflow:visible;border-left:3px solid #666;} #side-nav{padding:0;} #side-nav .toggle-list ul {display:block;} #resize-packages-nav{border-bottom:3px solid #666;} </style> </noscript> </head> <body class=""> <div id="header"> <div id="headerLeft"> <span id="masthead-title"><a href="../../../../packages.html">Fresco 1.1.0</a></span> </div> <div id="headerRight"> <div id="search" > <div id="searchForm"> <form accept-charset="utf-8" class="gsc-search-box" onsubmit="return submit_search()"> <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody> <tr> <td class="gsc-input"> <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off" title="search developer docs" name="q" value="search developer docs" onFocus="search_focus_changed(this, true)" onBlur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../../')" onkeyup="return search_changed(event, false, '../../../../')" /> <div id="search_filtered_div" class="no-display"> <table id="search_filtered" cellspacing=0> </table> </div> </td> <!-- <td class="gsc-search-button"> <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" /> </td> <td class="gsc-clear-button"> <div title="clear results" class="gsc-clear-button">&nbsp;</div> </td> --> </tr></tbody> </table> </form> </div><!-- searchForm --> </div><!-- search --> </div> </div><!-- header --> <div class="g-section g-tpl-240" id="body-content"> <div class="g-unit g-first side-nav-resizable" id="side-nav"> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> <ul> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/soloader/package-summary.html">com.facebook.common.soloader</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/volley/package-summary.html">com.facebook.drawee.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/wrapper/package-summary.html">com.facebook.fresco.animation.wrapper</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li> <li class="selected api apilevel-"> <a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li> </ul><br/> </div> <!-- end packages --> </div> <!-- end resize-packages --> <div id="classes-nav"> <ul> <li><h2>Interfaces</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoder.html">WebpTranscoder</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/Bitmaps.html">Bitmaps</a></li> <li class="selected api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html">ImagePipelineNativeLoader</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/JpegTranscoder.html">JpegTranscoder</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/NativeBlurFilter.html">NativeBlurFilter</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/StaticWebpNativeLoader.html">StaticWebpNativeLoader</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoderFactory.html">WebpTranscoderFactory</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/nativecode/WebpTranscoderImpl.html">WebpTranscoderImpl</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> </div><!-- end nav-tree --> </div><!-- end swapper --> </div> <!-- end side-nav --> <script> if (!isMobile) { //$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav"); chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../../"); } else { addLoadEvent(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); } //$("#swapper").css({borderBottom:"2px solid #aaa"}); } else { swapNav(); // tree view should be used on mobile } </script> <div class="g-unit" id="doc-content"> <div id="api-info-block"> <div class="sum-details-links"> Summary: <a href="#constants">Constants</a> &#124; <a href="#lfields">Fields</a> &#124; <a href="#pubctors">Ctors</a> &#124; <a href="#pubmethods">Methods</a> &#124; <a href="#inhmethods">Inherited Methods</a> &#124; <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a> </div><!-- end sum-details-links --> <div class="api-level"> </div> </div><!-- end api-info-block --> <!-- ======== START OF CLASS DATA ======== --> <div id="jd-header"> public class <h1>ImagePipelineNativeLoader</h1> extends Object<br/> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-"> <table class="jd-inheritance-table"> <tr> <td colspan="2" class="jd-inheritance-class-cell">java.lang.Object</td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="1" class="jd-inheritance-class-cell">com.facebook.imagepipeline.nativecode.ImagePipelineNativeLoader</td> </tr> </table> <div class="jd-descr"> <h2>Class Overview</h2> <p>Single place responsible for loading libimagepipeline.so and its dependencies. If your class has a native method whose implementation lives in libimagepipeline.so then call <code><a href="../../../../com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html#load()">load()</a></code> in its static initializer: <code> public class ClassWithNativeMethod { static { ImagePipelineNativeLoader.load(); } private static native void aNativeMethod(); } </code> </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <table id="constants" class="jd-sumtable"><tr><th colspan="12">Constants</th></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol">String</td> <td class="jd-linkcol"><a href="../../../../com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html#DSO_NAME">DSO_NAME</a></td> <td class="jd-descrcol" width="100%"></td> </tr> </table> <!-- =========== FIELD SUMMARY =========== --> <table id="lfields" class="jd-sumtable"><tr><th colspan="12">Fields</th></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> public static final List&lt;String&gt;</td> <td class="jd-linkcol"><a href="../../../../com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html#DEPENDENCIES">DEPENDENCIES</a></td> <td class="jd-descrcol" width="100%"></td> </tr> </table> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> </td> <td class="jd-linkcol" width="100%"> <span class="sympad"><a href="../../../../com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html#ImagePipelineNativeLoader()">ImagePipelineNativeLoader</a></span>() </td></tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> static void </td> <td class="jd-linkcol" width="100%"> <span class="sympad"><a href="../../../../com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html#load()">load</a></span>() </td></tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="inhmethods" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Methods</div></th></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed" ><img id="inherited-methods-java.lang.Object-trigger" src="../../../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From class java.lang.Object <div id="inherited-methods-java.lang.Object"> <div id="inherited-methods-java.lang.Object-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-java.lang.Object-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> Object </td> <td class="jd-linkcol" width="100%"> <span class="sympad">clone</span>() </td></tr> <tr class=" api apilevel-" > <td class="jd-typecol"> boolean </td> <td class="jd-linkcol" width="100%"> <span class="sympad">equals</span>(Object arg0) </td></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> void </td> <td class="jd-linkcol" width="100%"> <span class="sympad">finalize</span>() </td></tr> <tr class=" api apilevel-" > <td class="jd-typecol"> final Class&lt;?&gt; </td> <td class="jd-linkcol" width="100%"> <span class="sympad">getClass</span>() </td></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> int </td> <td class="jd-linkcol" width="100%"> <span class="sympad">hashCode</span>() </td></tr> <tr class=" api apilevel-" > <td class="jd-typecol"> final void </td> <td class="jd-linkcol" width="100%"> <span class="sympad">notify</span>() </td></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> final void </td> <td class="jd-linkcol" width="100%"> <span class="sympad">notifyAll</span>() </td></tr> <tr class=" api apilevel-" > <td class="jd-typecol"> String </td> <td class="jd-linkcol" width="100%"> <span class="sympad">toString</span>() </td></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> final void </td> <td class="jd-linkcol" width="100%"> <span class="sympad">wait</span>(long arg0, int arg1) </td></tr> <tr class=" api apilevel-" > <td class="jd-typecol"> final void </td> <td class="jd-linkcol" width="100%"> <span class="sympad">wait</span>(long arg0) </td></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> final void </td> <td class="jd-linkcol" width="100%"> <span class="sympad">wait</span>() </td></tr> </table> </div> </div> </td></tr> </table> </div><!-- jd-descr (summary) --> <!-- Details --> <!-- XML Attributes --> <!-- Enum Values --> <!-- Constants --> <!-- ========= ENUM CONSTANTS DETAIL ======== --> <h2>Constants</h2> <a id="DSO_NAME"></a> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public static final String </span> DSO_NAME </h4> <div class="api-level"> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> <div class="jd-tagdata"> <span class="jd-tagtitle">Constant Value: </span> <span> "imagepipeline" </span> </div> </div> </div> <!-- Fields --> <!-- ========= FIELD DETAIL ======== --> <h2>Fields</h2> <a id="DEPENDENCIES"></a> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public static final List&lt;String&gt; </span> DEPENDENCIES </h4> <div class="api-level"> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <!-- Public ctors --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <h2>Public Constructors</h2> <a id="ImagePipelineNativeLoader()"></a> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public </span> <span class="sympad">ImagePipelineNativeLoader</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> </div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- Protected ctors --> <!-- ========= METHOD DETAIL ======== --> <!-- Public methdos --> <h2>Public Methods</h2> <a id="load()"></a> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public static void </span> <span class="sympad">load</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> </div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <!-- ========= METHOD DETAIL ======== --> <!-- ========= END OF CLASS DATA ========= --> <a id="navbar_top"></a> <div id="footer"> +Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>. +</div> <!-- end footer - @generated --> </div> <!-- jd-content --> </div><!-- end doc-content --> </div> <!-- end body-content --> <script type="text/javascript"> init(); /* initialize doclava-developer-docs.js */ </script> </body> </html>
{ "content_hash": "6e8708738eecf0761b4791624bd336ba", "timestamp": "", "source": "github", "line_count": 1039, "max_line_length": 296, "avg_line_length": 27.02213666987488, "alnum_prop": 0.5593033195611911, "repo_name": "desmond1121/fresco", "id": "892c3ae2cf84ef242d91bb6bdd56f3c394715367", "size": "28076", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/javadoc/reference/com/facebook/imagepipeline/nativecode/ImagePipelineNativeLoader.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "22418" }, { "name": "C++", "bytes": "212041" }, { "name": "IDL", "bytes": "1003" }, { "name": "Java", "bytes": "2750756" }, { "name": "Makefile", "bytes": "7247" }, { "name": "Prolog", "bytes": "153" }, { "name": "Python", "bytes": "10351" }, { "name": "Shell", "bytes": "102" } ], "symlink_target": "" }
package org.apache.cloudstack.network; public interface NetworkOrchestrator { /** * Prepares for a VM to join a network * @param vm vm * @param reservationId reservation id */ void prepare(String vm, String reservationId); /** * Release all reservation */ void release(String vm, String reservationId); /** * Cancel a previous reservation * @param reservationId */ void cancel(String reservationId); }
{ "content_hash": "61b263bb87d1fc1a002d8c91ca79848e", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 50, "avg_line_length": 20.695652173913043, "alnum_prop": 0.6407563025210085, "repo_name": "jcshen007/cloudstack", "id": "8b6b6e431d30608c4c4edaf2fcf3c8f13f3572bb", "size": "1283", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "engine/network/src/main/java/org/apache/cloudstack/network/NetworkOrchestrator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "1451" }, { "name": "Batchfile", "bytes": "11926" }, { "name": "C#", "bytes": "2356211" }, { "name": "CSS", "bytes": "336634" }, { "name": "FreeMarker", "bytes": "4917" }, { "name": "Groovy", "bytes": "153137" }, { "name": "HTML", "bytes": "151248" }, { "name": "Java", "bytes": "34084304" }, { "name": "JavaScript", "bytes": "7687141" }, { "name": "Python", "bytes": "11154323" }, { "name": "Ruby", "bytes": "896" }, { "name": "Shell", "bytes": "770550" } ], "symlink_target": "" }
package dao import java.sql.Timestamp import javax.inject.{Inject, Singleton} import com.toscaruntime.constant.ExecutionConstant._ import com.toscaruntime.exception.deployment.execution.ConcurrentWorkflowExecutionException import models.ExecutionEntity import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider} import play.api.libs.concurrent.Execution.Implicits.defaultContext import slick.driver.JdbcProfile import scala.concurrent.Future trait ExecutionsComponent { self: HasDatabaseConfigProvider[JdbcProfile] => import driver.api._ class ExecutionTable(tag: Tag) extends Table[ExecutionEntity](tag, "EXECUTION") { def id = column[String]("ID", O.PrimaryKey) def workflowId = column[String]("WORKFLOW_ID") def startTime = column[Timestamp]("START_TIME") def endTime = column[Option[Timestamp]]("END_TIME") def error = column[Option[String]]("ERROR") def status = column[String]("STATUS") def * = (id, workflowId, startTime, endTime, error, status) <>(ExecutionEntity.tupled, ExecutionEntity.unapply) } } @Singleton() class ExecutionDAO @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends ExecutionsComponent with HasDatabaseConfigProvider[JdbcProfile] { import driver.api._ private val Executions = TableQuery[ExecutionTable] def get(executionId: String): Future[Seq[ExecutionEntity]] = db.run(Executions.filter(_.id === executionId).result) def all(): Future[Seq[ExecutionEntity]] = db.run(Executions.sortBy(_.endTime.desc.nullsFirst).result) def getRunningExecution: Future[Option[ExecutionEntity]] = { db.run(Executions.filter(_.endTime.isEmpty).result.headOption) } def insert(executionEntity: ExecutionEntity): Future[Int] = { val insertAction = Executions.filter { execution => execution.endTime.isEmpty }.result.flatMap { runningExecutions => if (runningExecutions.isEmpty) { Executions += executionEntity } else { throw new ConcurrentWorkflowExecutionException(s"Cannot start execution for workflow ${executionEntity.workflowId} because deployment has unfinished executions, consider running it in transient mode if this option is available") } } db.run(insertAction.transactionally) } def stop(error: Option[String]) = { db.run(Executions.filter(_.endTime.isEmpty).map { ex => (ex.status, ex.error) }.update((STOPPED, error))) } def resume() = { db.run(Executions.filter(_.endTime.isEmpty).map { ex => (ex.status, ex.error) }.update((RUNNING, None))) } def finish(status: String, error: Option[String]) = { db.run(Executions.filter(_.endTime.isEmpty).map { ex => (ex.status, ex.endTime, ex.error) }.update((status, Some(new Timestamp(System.currentTimeMillis())), error))) } }
{ "content_hash": "19886926cf2eec3c084d5b5f6ccbb5b8", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 236, "avg_line_length": 35.76923076923077, "alnum_prop": 0.7383512544802867, "repo_name": "vuminhkh/tosca-runtime", "id": "9bc195426e7b9a62b59a1e68f49ad3770f68e9d5", "size": "2790", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deployer/app/dao/ExecutionDAO.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "505" }, { "name": "HTML", "bytes": "8288" }, { "name": "Java", "bytes": "532920" }, { "name": "Scala", "bytes": "504690" }, { "name": "Shell", "bytes": "6775" }, { "name": "Smarty", "bytes": "2651" } ], "symlink_target": "" }
package br.com.softplan.security.zap.api.authentication; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import br.com.softplan.security.zap.api.model.AuthenticationInfo; import br.com.softplan.security.zap.commons.ZapInfo; import br.com.softplan.security.zap.zaproxy.clientapi.core.ClientApi; /** * Class to handle authentication via Selenium. * <p> * This will try to mimic the regular authentication process with Selenium. * It is particularly useful for more complex cases where it's easier to * just open the browser and perform the authentication. * * @author pdsec */ public class SeleniumAuthenticationHandler extends AbstractAuthenticationHandler { private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumAuthenticationHandler.class); protected SeleniumAuthenticationHandler(ClientApi api, ZapInfo zapInfo, AuthenticationInfo authenticationInfo) { super(api, zapInfo, authenticationInfo); } @Override protected void setupAuthentication(String targetUrl) { addHttpSessionTokens(targetUrl); triggerAuthenticationViaWebDriver(); setHttpSessionAsActive(targetUrl); } private void triggerAuthenticationViaWebDriver() { AuthenticationInfo authenticationInfo = getAuthenticationInfo(); LOGGER.info("--- Performing authentication via Selenium ({}) ---", authenticationInfo.getSeleniumDriver()); WebDriver driver = WebDriverFactory.makeWebDriver(getZapInfo(), authenticationInfo); driver.get(authenticationInfo.getLoginUrl()); WebElement usernameField = driver.findElement(By.id(authenticationInfo.getUsernameParameter())); usernameField.sendKeys(authenticationInfo.getUsername()); WebElement passwordField = driver.findElement(By.id(authenticationInfo.getPasswordParameter())); passwordField.sendKeys(authenticationInfo.getPassword()); passwordField.submit(); driver.quit(); LOGGER.info("--- Finished performing authentication via Selenium ---\n"); } }
{ "content_hash": "982aed06b3b5e2ed2e5f0b91fbe4c5a6", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 113, "avg_line_length": 36.785714285714285, "alnum_prop": 0.7951456310679612, "repo_name": "pdsoftplan/zap-maven-plugin", "id": "60e0cd65948ca36f7cf4c1f84d91c42bccbd29be", "size": "2060", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zap-client-api/src/main/java/br/com/softplan/security/zap/api/authentication/SeleniumAuthenticationHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "348738" }, { "name": "JavaScript", "bytes": "7307" } ], "symlink_target": "" }
#ifndef Magnum_MeshTools_RemoveDuplicates_h #define Magnum_MeshTools_RemoveDuplicates_h /** @file * @brief Function @ref Magnum::MeshTools::removeDuplicates() */ #include <limits> #include <numeric> #include <unordered_map> #include <vector> #include <Corrade/Utility/MurmurHash2.h> #include "Magnum/Magnum.h" #include "Magnum/Math/Functions.h" namespace Magnum { namespace MeshTools { namespace Implementation { template<std::size_t size> class VectorHash { public: std::size_t operator()(const Math::Vector<size, std::size_t>& data) const { return *reinterpret_cast<const std::size_t*>(Utility::MurmurHash2()(reinterpret_cast<const char*>(&data), sizeof(data)).byteArray()); } }; } /** @brief Remove duplicate floating-point vector data from given array @param[in,out] data Input data array @param[out] epsilon Epsilon value, vertices nearer than this distance will be melt together @return Index array and unique data Removes duplicate data from the array by collapsing them into buckets of size @p epsilon. First vector in given bucket is used, other ones are thrown away, no interpolation is done. Note that this function is meant to be used for floating-point data (or generally with non-zero @p epsilon), for discrete data the usual sorting method is much more efficient. If you want to remove duplicate data from already indexed array, first remove duplicates as if the array wasn't indexed at all and then use @ref duplicate() to combine the two index arrays: @code std::vector<UnsignedInt> indices; std::vector<Vector3> positions; indices = MeshTools::duplicate(indices, MeshTools::removeDuplicates(positions)); @endcode Removing duplicates in multiple indcidental arrays is also possible -- first remove duplicates in each array separately and then use @ref combineIndexedArrays() to combine the resulting index arrays to single index array and reorder the data accordingly: @code std::vector<Vector3> positions; std::vector<Vector2> texCoords; std::vector<UnsignedInt> positionIndices; std::tie(positionIndices, positions) = MeshTools::removeDuplicates(positions); std::vector<UnsignedInt> texCoordIndices; std::tie(texCoordIndices, texCoords) = MeshTools::removeDuplicates(texCoords); std::vector<UnsignedInt> indices = MeshTools::combineIndexedArrays( std::make_pair(std::cref(positionIndices), std::ref(positions)), std::make_pair(std::cref(texCoordIndices), std::ref(texCoords)) ); @endcode */ template<class Vector> std::vector<UnsignedInt> removeDuplicates(std::vector<Vector>& data, typename Vector::Type epsilon = Math::TypeTraits<typename Vector::Type>::epsilon()) { /* Get bounds */ Vector min = data[0], max = data[0]; for(const auto& v: data) { min = Math::min(v, min); max = Math::max(v, max); } /* Make epsilon so large that std::size_t can index all vectors inside the bounds. */ epsilon = Math::max(epsilon, typename Vector::Type((max-min).max()/std::numeric_limits<std::size_t>::max())); /* Resulting index array */ std::vector<UnsignedInt> resultIndices(data.size()); std::iota(resultIndices.begin(), resultIndices.end(), 0); /* Table containing original vector index for each discretized vector. Reserving more buckets than necessary (i.e. as if each vector was unique). */ std::unordered_map<Math::Vector<Vector::Size, std::size_t>, UnsignedInt, Implementation::VectorHash<Vector::Size>> table(data.size()); /* Index array for each pass, new data array */ std::vector<UnsignedInt> indices; indices.reserve(data.size()); /* First go with original coordinates, then move them by epsilon/2 in each direction. */ Vector moved; for(std::size_t moving = 0; moving <= Vector::Size; ++moving) { /* Go through all vectors */ for(std::size_t i = 0; i != data.size(); ++i) { /* Try to insert new vertex to the table */ const Math::Vector<Vector::Size, std::size_t> v((data[i] + moved - min)/epsilon); const auto result = table.emplace(v, table.size()); /* Add the (either new or already existing) index to index array */ indices.push_back(result.first->second); /* If this is new combination, copy the data to new (earlier) possition in the array */ if(result.second && i != table.size()-1) data[table.size()-1] = data[i]; } /* Shrink the data array */ CORRADE_INTERNAL_ASSERT(data.size() >= table.size()); data.resize(table.size()); /* Remap the resulting index array */ for(auto& i: resultIndices) i = indices[i]; /* Finished */ if(moving == Vector::Size) continue; /* Move vertex coordinates by epsilon/2 in next direction */ moved = Vector(); moved[moving] = epsilon/2; /* Clear the structures for next pass */ table.clear(); indices.clear(); } return resultIndices; } }} #endif
{ "content_hash": "de6d0624e99c0f72a431ef87618f9c68", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 177, "avg_line_length": 36.330935251798564, "alnum_prop": 0.6796039603960397, "repo_name": "ashimidashajia/magnum", "id": "51e9e5cc578dd1a0df0f73d93c43292a4d0b1548", "size": "6277", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Magnum/MeshTools/RemoveDuplicates.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "541084" }, { "name": "C++", "bytes": "4982510" }, { "name": "CMake", "bytes": "225535" }, { "name": "CSS", "bytes": "805" }, { "name": "GLSL", "bytes": "47398" }, { "name": "HTML", "bytes": "1181" }, { "name": "JavaScript", "bytes": "2571" }, { "name": "Makefile", "bytes": "554" }, { "name": "Shell", "bytes": "3868" } ], "symlink_target": "" }
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.spring.batch; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class SpringBatchComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("jobLauncher", org.springframework.batch.core.launch.JobLauncher.class); map.put("jobRegistry", org.springframework.batch.core.configuration.JobRegistry.class); map.put("lazyStartProducer", boolean.class); map.put("basicPropertyBinding", boolean.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { SpringBatchComponent target = (SpringBatchComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "basicpropertybinding": case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true; case "joblauncher": case "jobLauncher": target.setJobLauncher(property(camelContext, org.springframework.batch.core.launch.JobLauncher.class, value)); return true; case "jobregistry": case "jobRegistry": target.setJobRegistry(property(camelContext, org.springframework.batch.core.configuration.JobRegistry.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { SpringBatchComponent target = (SpringBatchComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "basicpropertybinding": case "basicPropertyBinding": return target.isBasicPropertyBinding(); case "joblauncher": case "jobLauncher": return target.getJobLauncher(); case "jobregistry": case "jobRegistry": return target.getJobRegistry(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); default: return null; } } }
{ "content_hash": "c9b406daf480a7776f6b4878e6c3b133", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 158, "avg_line_length": 44.15384615384615, "alnum_prop": 0.7222996515679443, "repo_name": "alvinkwekel/camel", "id": "7265958b9f1835abbd6c4254e5258d6c64ca0e07", "size": "2870", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/camel-spring-batch/src/generated/java/org/apache/camel/component/spring/batch/SpringBatchComponentConfigurer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6521" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "20838" }, { "name": "HTML", "bytes": "915675" }, { "name": "Java", "bytes": "86780964" }, { "name": "JavaScript", "bytes": "100326" }, { "name": "Makefile", "bytes": "513" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Shell", "bytes": "17295" }, { "name": "TSQL", "bytes": "28835" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "280849" } ], "symlink_target": "" }
""" Django settings for {{ project_name }} project. Generated by 'django-admin startproject' using Django {{ django_version }}. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/ """ from __future__ import absolute_import, unicode_literals # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/{{ docs_version }}/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'home', 'search', 'wagtail.wagtailforms', 'wagtail.wagtailredirects', 'wagtail.wagtailembeds', 'wagtail.wagtailsites', 'wagtail.wagtailusers', 'wagtail.wagtailsnippets', 'wagtail.wagtaildocs', 'wagtail.wagtailimages', 'wagtail.wagtailsearch', 'wagtail.wagtailadmin', 'wagtail.wagtailcore', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware', ] ROOT_URLCONF = '{{ project_name }}.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(PROJECT_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = '{{ project_name }}.wsgi.application' # Database # https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/{{ docs_version }}/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/{{ docs_version }}/howto/static-files/ STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # Wagtail settings WAGTAIL_SITE_NAME = "{{ project_name }}"
{ "content_hash": "1c9674ed85100253eacd9125c7c63542", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 86, "avg_line_length": 26.043478260869566, "alnum_prop": 0.6822481914301614, "repo_name": "hamsterbacke23/wagtail", "id": "c9756393734591525d24d7c9cd641d171825484b", "size": "3594", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "wagtail/project_template/project_name/settings/base.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "172736" }, { "name": "HTML", "bytes": "291553" }, { "name": "JavaScript", "bytes": "116387" }, { "name": "Makefile", "bytes": "548" }, { "name": "Python", "bytes": "2243460" }, { "name": "Shell", "bytes": "7387" } ], "symlink_target": "" }
#ifndef OS_CPU_WINDOWS_X86_VM_PREFETCH_WINDOWS_X86_INLINE_HPP #define OS_CPU_WINDOWS_X86_VM_PREFETCH_WINDOWS_X86_INLINE_HPP #include "runtime/prefetch.hpp" inline void Prefetch::read (void *loc, intx interval) {} inline void Prefetch::write(void *loc, intx interval) {} #endif // OS_CPU_WINDOWS_X86_VM_PREFETCH_WINDOWS_X86_INLINE_HPP
{ "content_hash": "1eacfd7747c50aafbfc4e6d438edef7b", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 63, "avg_line_length": 30.818181818181817, "alnum_prop": 0.7581120943952803, "repo_name": "fengshao0907/Open-Source-Research", "id": "a09c1947755b2b3443e35073cfb04ec8401b99bd", "size": "1398", "binary": false, "copies": "101", "ref": "refs/heads/master", "path": "HotSpot1.7/src/os_cpu/windows_x86/vm/prefetch_windows_x86.inline.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "146130" }, { "name": "Batchfile", "bytes": "75552" }, { "name": "C", "bytes": "926153" }, { "name": "C++", "bytes": "53181927" }, { "name": "CSS", "bytes": "10690" }, { "name": "D", "bytes": "25797" }, { "name": "DTrace", "bytes": "64398" }, { "name": "HTML", "bytes": "70715" }, { "name": "Java", "bytes": "32378710" }, { "name": "JavaScript", "bytes": "39651" }, { "name": "Makefile", "bytes": "158575" }, { "name": "Mathematica", "bytes": "18238" }, { "name": "Protocol Buffer", "bytes": "1449" }, { "name": "Shell", "bytes": "215485" }, { "name": "XSLT", "bytes": "351083" } ], "symlink_target": "" }
#pragma once #include <stdint.h> #include "il2cpp-object-internals.h" #include "il2cpp-config.h" struct Il2CppObject; struct Il2CppDelegate; struct Il2CppReflectionType; struct Il2CppReflectionMethod; struct Il2CppReflectionField; struct Il2CppArray; struct Il2CppException; struct Il2CppReflectionModule; struct Il2CppAssembly; struct Il2CppAssemblyName; struct Il2CppAppDomain; struct Il2CppNativeOverlapped; namespace il2cpp { namespace icalls { namespace mscorlib { namespace System { namespace Threading { class LIBIL2CPP_CODEGEN_API ThreadPool { public: static void GetAvailableThreads(int32_t* workerThreads, int32_t* completionPortThreads); static void GetMinThreads(int32_t* workerThreads, int32_t* completionPortThreads); static bool SetMaxThreads(int32_t workerThreads, int32_t completionPortThreads); static bool SetMinThreads(int32_t workerThreads, int32_t completionPortThreads); static void GetMaxThreads(int32_t* workerThreads, int32_t* completionPortThreads); }; } /* namespace Threading */ } /* namespace System */ } /* namespace mscorlib */ } /* namespace icalls */ } /* namespace il2cpp */
{ "content_hash": "83e1b2b4cee2e53903c3fcd1ec50f18e", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 96, "avg_line_length": 27.186046511627907, "alnum_prop": 0.7715996578272027, "repo_name": "googlecreativelab/lines-of-play", "id": "288126d01c2172d73cc963912e131fe53dd066ce", "size": "1169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Builds/iOS/linesofplay/Libraries/libil2cpp/include/icalls/mscorlib/System.Threading/ThreadPool.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "25625933" }, { "name": "C#", "bytes": "228681" }, { "name": "C++", "bytes": "137545371" }, { "name": "HLSL", "bytes": "9089" }, { "name": "Objective-C", "bytes": "584897" }, { "name": "Objective-C++", "bytes": "387959" }, { "name": "ShaderLab", "bytes": "72592" }, { "name": "Shell", "bytes": "1177" } ], "symlink_target": "" }
/***************************************************************************/ /* */ /* ftinit.c */ /* */ /* FreeType initialization layer (body). */ /* */ /* Copyright 1996-2001, 2002, 2005, 2007, 2009, 2012 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* The purpose of this file is to implement the following two */ /* functions: */ /* */ /* FT_Add_Default_Modules(): */ /* This function is used to add the set of default modules to a */ /* fresh new library object. The set is taken from the header file */ /* `freetype/config/ftmodule.h'. See the document `FreeType 2.0 */ /* Build System' for more information. */ /* */ /* FT_Init_FreeType(): */ /* This function creates a system object for the current platform, */ /* builds a library out of it, then calls FT_Default_Drivers(). */ /* */ /* Note that even if FT_Init_FreeType() uses the implementation of the */ /* system object defined at build time, client applications are still */ /* able to provide their own `ftsystem.c'. */ /* */ /*************************************************************************/ #include <ft2build.h> #include FT_CONFIG_CONFIG_H #include FT_INTERNAL_OBJECTS_H #include FT_INTERNAL_DEBUG_H #include FT_MODULE_H #include "basepic.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_init #ifndef FT_CONFIG_OPTION_PIC #undef FT_USE_MODULE #ifdef __cplusplus #define FT_USE_MODULE( type, x ) extern "C" const type x; #else #define FT_USE_MODULE( type, x ) extern const type x; #endif #include FT_CONFIG_MODULES_H #undef FT_USE_MODULE #define FT_USE_MODULE( type, x ) (const FT_Module_Class*)&(x), static const FT_Module_Class* const ft_default_modules[] = { #include FT_CONFIG_MODULES_H 0 }; #else /* FT_CONFIG_OPTION_PIC */ #ifdef __cplusplus #define FT_EXTERNC extern "C" #else #define FT_EXTERNC extern #endif /* declare the module's class creation/destruction functions */ #undef FT_USE_MODULE #define FT_USE_MODULE( type, x ) \ FT_EXTERNC FT_Error \ FT_Create_Class_ ## x( FT_Library library, \ FT_Module_Class* *output_class ); \ FT_EXTERNC void \ FT_Destroy_Class_ ## x( FT_Library library, \ FT_Module_Class* clazz ); #include FT_CONFIG_MODULES_H /* count all module classes */ #undef FT_USE_MODULE #define FT_USE_MODULE( type, x ) MODULE_CLASS_ ## x, enum { #include FT_CONFIG_MODULES_H FT_NUM_MODULE_CLASSES }; /* destroy all module classes */ #undef FT_USE_MODULE #define FT_USE_MODULE( type, x ) \ if ( classes[i] ) \ { \ FT_Destroy_Class_ ## x( library, classes[i] ); \ } \ i++; FT_BASE_DEF( void ) ft_destroy_default_module_classes( FT_Library library ) { FT_Module_Class* *classes; FT_Memory memory; FT_UInt i; BasePIC* pic_container = (BasePIC*)library->pic_container.base; if ( !pic_container->default_module_classes ) return; memory = library->memory; classes = pic_container->default_module_classes; i = 0; #include FT_CONFIG_MODULES_H FT_FREE( classes ); pic_container->default_module_classes = 0; } /* initialize all module classes and the pointer table */ #undef FT_USE_MODULE #define FT_USE_MODULE( type, x ) \ error = FT_Create_Class_ ## x( library, &clazz ); \ if ( error ) \ goto Exit; \ classes[i++] = clazz; FT_BASE_DEF( FT_Error ) ft_create_default_module_classes( FT_Library library ) { FT_Error error; FT_Memory memory; FT_Module_Class* *classes; FT_Module_Class* clazz; FT_UInt i; BasePIC* pic_container = (BasePIC*)library->pic_container.base; memory = library->memory; pic_container->default_module_classes = 0; if ( FT_ALLOC( classes, sizeof ( FT_Module_Class* ) * ( FT_NUM_MODULE_CLASSES + 1 ) ) ) return error; /* initialize all pointers to 0, especially the last one */ for ( i = 0; i < FT_NUM_MODULE_CLASSES; i++ ) classes[i] = 0; classes[FT_NUM_MODULE_CLASSES] = 0; i = 0; #include FT_CONFIG_MODULES_H Exit: if ( error ) ft_destroy_default_module_classes( library ); else pic_container->default_module_classes = classes; return error; } #endif /* FT_CONFIG_OPTION_PIC */ /* documentation is in ftmodapi.h */ FT_EXPORT_DEF( void ) FT_Add_Default_Modules( FT_Library library ) { FT_Error error; const FT_Module_Class* const* cur; /* FT_DEFAULT_MODULES_GET dereferences `library' in PIC mode */ #ifdef FT_CONFIG_OPTION_PIC if ( !library ) return; #endif /* GCC 4.6 warns the type difference: * FT_Module_Class** != const FT_Module_Class* const* */ cur = (const FT_Module_Class* const*)FT_DEFAULT_MODULES_GET; /* test for valid `library' delayed to FT_Add_Module() */ while ( *cur ) { error = FT_Add_Module( library, *cur ); /* notify errors, but don't stop */ if ( error ) FT_TRACE0(( "FT_Add_Default_Module:" " Cannot install `%s', error = 0x%x\n", (*cur)->module_name, error )); cur++; } } /* documentation is in freetype.h */ FT_EXPORT_DEF( FT_Error ) FT_Init_FreeType( FT_Library *alibrary ) { FT_Error error; FT_Memory memory; /* First of all, allocate a new system object -- this function is part */ /* of the system-specific component, i.e. `ftsystem.c'. */ memory = FT_New_Memory(); if ( !memory ) { FT_ERROR(( "FT_Init_FreeType: cannot find memory manager\n" )); return FT_Err_Unimplemented_Feature; } /* build a library out of it, then fill it with the set of */ /* default drivers. */ error = FT_New_Library( memory, alibrary ); if ( error ) FT_Done_Memory( memory ); else FT_Add_Default_Modules( *alibrary ); return error; } /* documentation is in freetype.h */ FT_EXPORT_DEF( FT_Error ) FT_Done_FreeType( FT_Library library ) { if ( library ) { FT_Memory memory = library->memory; /* Discard the library object */ FT_Done_Library( library ); /* discard memory manager */ FT_Done_Memory( memory ); } return FT_Err_Ok; } /* END */
{ "content_hash": "b1fe623ca11c2f66af77b15f5faad573", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 77, "avg_line_length": 32.840425531914896, "alnum_prop": 0.444336464744628, "repo_name": "xsilium-frameworks/xsilium-engine", "id": "96b87f8f87024369c88e414eaecd4b9706f18dab", "size": "9261", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Library/Dependencies/Source/freetype/src/base/ftinit.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "8314" }, { "name": "Awk", "bytes": "4270" }, { "name": "Batchfile", "bytes": "45943" }, { "name": "C", "bytes": "35748417" }, { "name": "C++", "bytes": "52618762" }, { "name": "CMake", "bytes": "745497" }, { "name": "CSS", "bytes": "8196" }, { "name": "DIGITAL Command Language", "bytes": "232950" }, { "name": "Groff", "bytes": "1277205" }, { "name": "HTML", "bytes": "2460232" }, { "name": "Java", "bytes": "6289" }, { "name": "Lex", "bytes": "83193" }, { "name": "Lua", "bytes": "130225" }, { "name": "Makefile", "bytes": "19477" }, { "name": "Objective-C", "bytes": "174863" }, { "name": "Objective-C++", "bytes": "314715" }, { "name": "Perl", "bytes": "453317" }, { "name": "Perl6", "bytes": "7864" }, { "name": "Python", "bytes": "304260" }, { "name": "Shell", "bytes": "1096571" }, { "name": "TeX", "bytes": "149642" }, { "name": "Visual Basic", "bytes": "11291" }, { "name": "Yacc", "bytes": "40113" } ], "symlink_target": "" }
package edu.gemini.rollover.servlet import edu.gemini.pot.sp.ISPObservation import edu.gemini.spModel.obs.{ObservationStatus, ObsClassService} import edu.gemini.spModel.obsclass.ObsClass.SCIENCE /** * A predicate that determines whether a given observation should be * considered when making the rollover report. Observations that should be * included are * * <ul> * <li>Science observations</li> * <li>Not yet fully observed according to their observation status</li> * </ul> */ object IncludeObservation extends (ISPObservation => Boolean) with Serializable { private def isScience(obsShell: ISPObservation): Boolean = ObsClassService.lookupObsClass(obsShell) == SCIENCE private def isActive(obsShell: ISPObservation): Boolean = ObservationStatus.computeFor(obsShell).isActive def apply(obsShell: ISPObservation): Boolean = isScience(obsShell) && isActive(obsShell) }
{ "content_hash": "c910f2efe85924c599f2be984ef1534d", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 81, "avg_line_length": 33.407407407407405, "alnum_prop": 0.7738359201773836, "repo_name": "arturog8m/ocs", "id": "28ac565575dd2049d61b9320b2a591ae7ad5a82e", "size": "902", "binary": false, "copies": "9", "ref": "refs/heads/develop", "path": "bundle/edu.gemini.spdb.rollover.servlet/src/main/scala/edu/gemini/rollover/servlet/IncludeObservation.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7919" }, { "name": "HTML", "bytes": "490242" }, { "name": "Java", "bytes": "14504312" }, { "name": "JavaScript", "bytes": "7962" }, { "name": "Scala", "bytes": "4967047" }, { "name": "Shell", "bytes": "4989" }, { "name": "Tcl", "bytes": "2841" } ], "symlink_target": "" }
CREATE CLASS ddl_0001; ALTER ddl_0001 add col1 string default '***'; ALTER CLASS ddl_0001 modify col1 string default '*****'; drop class ddl_0001;
{ "content_hash": "87e195c692fbca6eead7895b4ae53bda", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 56, "avg_line_length": 18.75, "alnum_prop": 0.7066666666666667, "repo_name": "hongwoo-nam/cubrid-testcases", "id": "6237d3bf41419b435ee0d31708ea3a8e7b66c747", "size": "282", "binary": false, "copies": "2", "ref": "refs/heads/develop_inlineView_update", "path": "sql/_01_object/_07_alteration/_003_class_change/cases/1014.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PLSQL", "bytes": "444579" }, { "name": "PLpgSQL", "bytes": "5669" }, { "name": "SQLPL", "bytes": "11049" }, { "name": "eC", "bytes": "710" } ], "symlink_target": "" }
using System; using System.IO; using System.Net; class DownloadFileFromNet { static void Main() { Console.Write("Enter URL of file: "); string url = Console.ReadLine(); Console.Write("Enter saved file name: "); string myFile = Console.ReadLine(); Console.WriteLine("\n\rDownloading file. Please wait..."); try { WebClient webClient = new WebClient(); webClient.DownloadFile(url, myFile); } catch (UnauthorizedAccessException) { Console.WriteLine("You do not have permission to current directory."); } catch (NotSupportedException) { Console.WriteLine("Your OS does not support GetCurrentDirectory()."); } catch (WebException) { Console.WriteLine("Your URL is not valid."); } finally { Console.WriteLine("\n\rThank you for using this simple downloader! :) \n\rIf you like this program, please donate for a beer: PoorCSharpCoder@Paypal.com\n\r"); } } }
{ "content_hash": "39b72f9b072a7a4d972b551e9b261840", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 171, "avg_line_length": 29.64864864864865, "alnum_prop": 0.5806745670009116, "repo_name": "iliyaST/TelerikAcademy", "id": "ac4bf0a4bc6ec75e128b8dd3daef8ce09995fb0f", "size": "1099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "C#2/7-Exception-Handling/04.DownloadFile/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "303" }, { "name": "C#", "bytes": "2931171" }, { "name": "CSS", "bytes": "169885" }, { "name": "CoffeeScript", "bytes": "1076" }, { "name": "HTML", "bytes": "8977397" }, { "name": "JavaScript", "bytes": "1658788" }, { "name": "PLSQL", "bytes": "4342" } ], "symlink_target": "" }
var protoclass = require("protoclass"), janitor = require("janitorjs"), _ = require("underscore"); function EventsDecorator (view, events) { this.view = view; this.events = events; this.render = _.bind(this.render, this); this.remove = _.bind(this.remove, this); view.once("render", this.render); view.once("dispose", this.remove); } protoclass(EventsDecorator, { /** */ render: function () { e = this._events(); this._disposeBindings(); this._janitor = janitor(); for (var selector in e) { this._addBinding(selector, e[selector]); } }, /** */ remove: function () { this._disposeBindings(); }, /** */ _addBinding: function (selector, viewMethod) { var selectorParts = selector.split(" "), actions = selectorParts.shift().split(/\//g).join(" "), selectors = selectorParts.join(","), self = this, elements; // TODO - use JS traverse instead function cb () { var ref; if (typeof viewMethod === "function") { ref = viewMethod; } else { ref = self.view.get(viewMethod); } ref.apply(self.view, arguments); } if (!selectors.length) { elements = this.view.$(); } else { elements = this.view.$(selectors); } elements.bind(lowerActions = actions.toLowerCase(), cb); actions.split(" ").forEach(function (action) { self._janitor.add(self.view.on(action, function() { cb.apply(self, [$.Event(action)].concat(Array.prototype.slice.call(arguments))); })); }); this._janitor.add(function () { elements.unbind(actions, cb); elements.unbind(lowerActions, cb); }); }, /** */ _disposeBindings: function () { if (!this._janitor) return; this._janitor.dispose(); this._janitor = undefined; }, /** */ _events: function () { return this.events; } }); EventsDecorator.priority = "display"; EventsDecorator.getOptions = function (view) { return view.events; } EventsDecorator.decorate = function (view, options) { return new EventsDecorator(view, options); } module.exports = EventsDecorator;
{ "content_hash": "23c2e95ee3425ae669ebc113abf4f527", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 88, "avg_line_length": 20.48148148148148, "alnum_prop": 0.581374321880651, "repo_name": "crcn/mojo-views", "id": "93f953332d837ecb20c06f7ffee070a784acf239", "size": "2212", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/plugins/decor/events.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "63207" }, { "name": "Makefile", "bytes": "541" } ], "symlink_target": "" }
/* * 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 io.trino.operator.unnest; import io.airlift.slice.Slice; import io.trino.spi.block.Block; import io.trino.spi.block.DictionaryBlock; import org.testng.annotations.Test; import java.util.Collections; import static io.airlift.slice.Slices.utf8Slice; import static io.trino.block.ColumnarTestUtils.assertBlock; import static io.trino.operator.unnest.TestingUnnesterUtil.createReplicatedOutputSlice; import static io.trino.operator.unnest.TestingUnnesterUtil.createSimpleBlock; import static io.trino.operator.unnest.TestingUnnesterUtil.toSlices; import static io.trino.operator.unnest.UnnestOperatorBlockUtil.calculateNewArraySize; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestReplicatedBlockBuilder { @Test public void testReplicateOutput() { String[] values = {"a", "b", "c", null, null, "e"}; int[] count = {1, 0, 2, 2, 0, 3}; testReplication(toSlices(values), count); } @Test public void testReplicateEmptyOutput() { String[] values = {"a", null, "b"}; int[] count = {0, 0, 0}; testReplication(toSlices(values), count); } private static void testReplication(Slice[] values, int[] counts) { assertEquals(values.length, counts.length); ReplicatedBlockBuilder replicateBlockBuilder = new ReplicatedBlockBuilder(); Block valuesBlock = createSimpleBlock(values); replicateBlockBuilder.resetInputBlock(valuesBlock); replicateBlockBuilder.startNewOutput(100); for (int i = 0; i < counts.length; i++) { replicateBlockBuilder.appendRepeated(i, counts[i]); } Block outputBlock = replicateBlockBuilder.buildOutputAndFlush(); assertBlock(outputBlock, createReplicatedOutputSlice(values, counts)); assertTrue(outputBlock instanceof DictionaryBlock); } @Test public void testCapacityIncrease() { assertSmallCapacityIncrease(4, 1, 4); assertBigCapacityIncrease(50, 49, 100); } /** * verify capacity increase when required new capacity is <= the value returned from {@link UnnestOperatorBlockUtil#calculateNewArraySize} */ private static void assertSmallCapacityIncrease(int initialSize, int firstAppendCount, int secondAppendCount) { assertTrue(firstAppendCount <= initialSize); assertTrue(firstAppendCount + secondAppendCount > initialSize); assertTrue(firstAppendCount + secondAppendCount <= calculateNewArraySize(initialSize)); assertCapacityIncrease(initialSize, firstAppendCount, secondAppendCount, new ReplicatedBlockBuilder()); } /** * verify capacity increase when required new capacity is > the value returned from {@link UnnestOperatorBlockUtil#calculateNewArraySize} */ private static void assertBigCapacityIncrease(int initialSize, int firstAppendCount, int secondAppendCount) { assertTrue(firstAppendCount <= initialSize); assertTrue(firstAppendCount + secondAppendCount > initialSize); assertTrue(firstAppendCount + secondAppendCount > calculateNewArraySize(initialSize)); assertCapacityIncrease(initialSize, firstAppendCount, secondAppendCount, new ReplicatedBlockBuilder()); } private static void assertCapacityIncrease(int initialSize, int firstAppendCount, int secondAppendCount, ReplicatedBlockBuilder replicatedBlockBuilder) { Slice[] values = {null, utf8Slice("a")}; Block inputBlock = createSimpleBlock(values); int repeatingIndex = 1; replicatedBlockBuilder.resetInputBlock(inputBlock); replicatedBlockBuilder.startNewOutput(initialSize); replicatedBlockBuilder.appendRepeated(repeatingIndex, firstAppendCount); replicatedBlockBuilder.appendRepeated(repeatingIndex, secondAppendCount); Block output = replicatedBlockBuilder.buildOutputAndFlush(); int totalCount = firstAppendCount + secondAppendCount; assertBlock(output, Collections.nCopies(totalCount, values[repeatingIndex]).toArray(new Slice[totalCount])); } }
{ "content_hash": "c5f7610ba8ef68dc2637fcc445b08861", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 155, "avg_line_length": 41.557522123893804, "alnum_prop": 0.735732538330494, "repo_name": "losipiuk/presto", "id": "f53a8aa6e1fae3a94a2416a55ceba3604af0a765", "size": "4696", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "core/trino-main/src/test/java/io/trino/operator/unnest/TestReplicatedBlockBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "17768" }, { "name": "HTML", "bytes": "44136" }, { "name": "Java", "bytes": "11610150" }, { "name": "JavaScript", "bytes": "1431" }, { "name": "Makefile", "bytes": "6819" }, { "name": "PLSQL", "bytes": "3849" }, { "name": "Python", "bytes": "4481" }, { "name": "SQLPL", "bytes": "6363" }, { "name": "Shell", "bytes": "2069" } ], "symlink_target": "" }
FROM balenalib/amd64-fedora:34-build RUN dnf -y update \ && dnf clean all \ && dnf -y install \ gzip \ java-1.8.0-openjdk \ java-1.8.0-openjdk-devel \ tar \ && dnf clean all # set JAVA_HOME ENV JAVA_HOME /usr/lib/jvm/java-openjdk CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Fedora 34 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v8-jdk \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "f3d0db2daaedf6c021f553a5c0e9ddf0", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 690, "avg_line_length": 59.5, "alnum_prop": 0.7097020626432391, "repo_name": "resin-io-library/base-images", "id": "52eb474522189af3334face5cdd65c74838dc56e", "size": "1330", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "balena-base-images/openjdk/amd64/fedora/34/8-jdk/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
#ifndef _INC_WSDXMLDOM #define _INC_WSDXMLDOM #ifndef _INC_WSDAPI #error Please include wsdapi.h instead of this header. This header cannot be used directly. #endif #if (_WIN32_WINNT >= 0x0600) #ifdef __cplusplus extern "C" { #endif typedef struct _WSDXML_TYPE { WCHAR *Uri; BYTE *Table; } WSDXML_TYPE; typedef const WSDXML_TYPE *PCWSDXML_TYPE; typedef struct _WSDXML_NAMESPACE { const WCHAR *Uri; const WCHAR *PreferredPrefix; WSDXML_NAME *Names; WORD NamesCount; WORD Encoding; } WSDXML_NAMESPACE; typedef const WSDXML_NAMESPACE *PCWSDXML_NAMESPACE; typedef struct _WSDXML_NAME { WSDXML_NAMESPACE *Space; WCHAR *LocalName; } WSDXML_NAME; typedef struct _WSDXML_NODE { enum DUMMYUNIONNAME { ElementType, TextType } Type; WSDXML_ELEMENT *Parent; WSDXML_NODE *Next; } WSDXML_NODE; typedef struct _WSDXML_TEXT { WSDXML_NODE Node; WCHAR *Text; } WSDXML_TEXT; typedef struct _WSDXML_ATTRIBUTE { WSDXML_ELEMENT *Element; WSDXML_ATTRIBUTE *Next; WSDXML_NAME *Name; WCHAR *Value; } WSDXML_ATTRIBUTE; typedef struct _WSDXML_PREFIX_MAPPING { DWORD Refs; WSDXML_PREFIX_MAPPING *Next; WSDXML_NAMESPACE *Space; WCHAR *Prefix; } WSDXML_PREFIX_MAPPING; typedef struct _WSDXML_ELEMENT { WSDXML_NODE Node; WSDXML_NAME *Name; WSDXML_ATTRIBUTE *FirstAttribute; WSDXML_NODE *FirstChild; WSDXML_PREFIX_MAPPING *PrefixMappings; } WSDXML_ELEMENT; typedef struct _WSDXML_ELEMENT_LIST { WSDXML_ELEMENT_LIST *Next; WSDXML_ELEMENT *Element; } WSDXML_ELEMENT_LIST; #ifdef __cplusplus } #endif #endif /*(_WIN32_WINNT >= 0x0600)*/ #endif /*_INC_WSDXMLDOM*/
{ "content_hash": "d4c698ffa9e0d81535fcf066205e9678", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 91, "avg_line_length": 21.390243902439025, "alnum_prop": 0.6659064994298746, "repo_name": "espadrine/opera", "id": "c2ac83ee60741a83809cd6089ed8a6e3723f3ac3", "size": "1969", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "chromium/src/third_party/perl/c/i686-w64-mingw32/include/wsdxmldom.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
/* This is the default Tooltipster theme (feel free to modify or duplicate and create multiple themes!): */ .tooltipster-default { border-radius: 5px; border: 2px solid #000; background: #4c4c4c; color: #fff; } /* Use this next selector to style things like font-size and line-height: */ .tooltipster-default .tooltipster-content { font-family: Arial, sans-serif; font-size: 14px; line-height: 16px; padding: 8px 10px; overflow: hidden; } /* This next selector defines the color of the border on the outside of the arrow. This will automatically match the color and size of the border set on the main tooltip styles. Set display: none; if you would like a border around the tooltip but no border around the arrow */ .tooltipster-default .tooltipster-arrow .tooltipster-arrow-border { /* border-color: ... !important; */ } /* If you're using the icon option, use this next selector to style them */ .tooltipster-icon { cursor: help; margin-left: 4px; } /* This is the base styling required to make all Tooltipsters work */ .tooltipster-base { padding: 0; font-size: 0; line-height: 0; position: absolute; left: 0; top: 0; z-index: 9999999; pointer-events: none; width: auto; overflow: visible; } .tooltipster-base .tooltipster-content { overflow: hidden; } /* These next classes handle the styles for the little arrow attached to the tooltip. By default, the arrow will inherit the same colors and border as what is set on the main tooltip itself. */ .tooltipster-arrow { display: block; text-align: center; width: 100%; height: 100%; position: absolute; top: 0; left: 0; z-index: -1; } .tooltipster-arrow span, .tooltipster-arrow-border { display: block; width: 0; height: 0; position: absolute; } .tooltipster-arrow-top span, .tooltipster-arrow-top-right span, .tooltipster-arrow-top-left span { border-left: 8px solid transparent !important; border-right: 8px solid transparent !important; border-top: 8px solid; bottom: -7px; } .tooltipster-arrow-top .tooltipster-arrow-border, .tooltipster-arrow-top-right .tooltipster-arrow-border, .tooltipster-arrow-top-left .tooltipster-arrow-border { border-left: 9px solid transparent !important; border-right: 9px solid transparent !important; border-top: 9px solid; bottom: -7px; } .tooltipster-arrow-bottom span, .tooltipster-arrow-bottom-right span, .tooltipster-arrow-bottom-left span { border-left: 8px solid transparent !important; border-right: 8px solid transparent !important; border-bottom: 8px solid; top: -7px; } .tooltipster-arrow-bottom .tooltipster-arrow-border, .tooltipster-arrow-bottom-right .tooltipster-arrow-border, .tooltipster-arrow-bottom-left .tooltipster-arrow-border { border-left: 9px solid transparent !important; border-right: 9px solid transparent !important; border-bottom: 9px solid; top: -7px; } .tooltipster-arrow-top span, .tooltipster-arrow-top .tooltipster-arrow-border, .tooltipster-arrow-bottom span, .tooltipster-arrow-bottom .tooltipster-arrow-border { left: 0; right: 0; margin: 0 auto; } .tooltipster-arrow-top-left span, .tooltipster-arrow-bottom-left span { left: 6px; } .tooltipster-arrow-top-left .tooltipster-arrow-border, .tooltipster-arrow-bottom-left .tooltipster-arrow-border { left: 5px; } .tooltipster-arrow-top-right span, .tooltipster-arrow-bottom-right span { right: 6px; } .tooltipster-arrow-top-right .tooltipster-arrow-border, .tooltipster-arrow-bottom-right .tooltipster-arrow-border { right: 5px; } .tooltipster-arrow-left span, .tooltipster-arrow-left .tooltipster-arrow-border { border-top: 8px solid transparent !important; border-bottom: 8px solid transparent !important; border-left: 8px solid; top: 50%; margin-top: -7px; right: -7px; } .tooltipster-arrow-left .tooltipster-arrow-border { border-top: 9px solid transparent !important; border-bottom: 9px solid transparent !important; border-left: 9px solid; margin-top: -8px; } .tooltipster-arrow-right span, .tooltipster-arrow-right .tooltipster-arrow-border { border-top: 8px solid transparent !important; border-bottom: 8px solid transparent !important; border-right: 8px solid; top: 50%; margin-top: -7px; left: -7px; } .tooltipster-arrow-right .tooltipster-arrow-border { border-top: 9px solid transparent !important; border-bottom: 9px solid transparent !important; border-right: 9px solid; margin-top: -8px; } /* Some CSS magic for the awesome animations - feel free to make your own custom animations and reference it in your Tooltipster settings! */ .tooltipster-fade { opacity: 0; -webkit-transition-property: opacity; -moz-transition-property: opacity; -o-transition-property: opacity; -ms-transition-property: opacity; transition-property: opacity; } .tooltipster-fade-show { opacity: 1; } .tooltipster-grow { -webkit-transform: scale(0,0); -moz-transform: scale(0,0); -o-transform: scale(0,0); -ms-transform: scale(0,0); transform: scale(0,0); -webkit-transition-property: -webkit-transform; -moz-transition-property: -moz-transform; -o-transition-property: -o-transform; -ms-transition-property: -ms-transform; transition-property: transform; -webkit-backface-visibility: hidden; } .tooltipster-grow-show { -webkit-transform: scale(1,1); -moz-transform: scale(1,1); -o-transform: scale(1,1); -ms-transform: scale(1,1); transform: scale(1,1); -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1); -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); } .tooltipster-swing { opacity: 0; -webkit-transform: rotateZ(4deg); -moz-transform: rotateZ(4deg); -o-transform: rotateZ(4deg); -ms-transform: rotateZ(4deg); transform: rotateZ(4deg); -webkit-transition-property: -webkit-transform, opacity; -moz-transition-property: -moz-transform; -o-transition-property: -o-transform; -ms-transition-property: -ms-transform; transition-property: transform; } .tooltipster-swing-show { opacity: 1; -webkit-transform: rotateZ(0deg); -moz-transform: rotateZ(0deg); -o-transform: rotateZ(0deg); -ms-transform: rotateZ(0deg); transform: rotateZ(0deg); -webkit-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 1); -webkit-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); -moz-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); -ms-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); -o-transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); transition-timing-function: cubic-bezier(0.230, 0.635, 0.495, 2.4); } .tooltipster-fall { top: 0; -webkit-transition-property: top; -moz-transition-property: top; -o-transition-property: top; -ms-transition-property: top; transition-property: top; -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1); -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); } .tooltipster-fall-show { } .tooltipster-fall.tooltipster-dying { -webkit-transition-property: all; -moz-transition-property: all; -o-transition-property: all; -ms-transition-property: all; transition-property: all; top: 0px !important; opacity: 0; } .tooltipster-slide { left: -40px; -webkit-transition-property: left; -moz-transition-property: left; -o-transition-property: left; -ms-transition-property: left; transition-property: left; -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1); -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -moz-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -ms-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); -o-transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); transition-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1.15); } .tooltipster-slide.tooltipster-slide-show { } .tooltipster-slide.tooltipster-dying { -webkit-transition-property: all; -moz-transition-property: all; -o-transition-property: all; -ms-transition-property: all; transition-property: all; left: 0px !important; opacity: 0; } /* CSS transition for when contenting is changing in a tooltip that is still open. The only properties that will NOT transition are: width, height, top, and left */ .tooltipster-content-changing { opacity: 0.5; -webkit-transform: scale(1.1, 1.1); -moz-transform: scale(1.1, 1.1); -o-transform: scale(1.1, 1.1); -ms-transform: scale(1.1, 1.1); transform: scale(1.1, 1.1); }
{ "content_hash": "67ac7bd1538f812b6717e08b0623d0f7", "timestamp": "", "source": "github", "line_count": 266, "max_line_length": 276, "avg_line_length": 33.96616541353384, "alnum_prop": 0.7333702268954068, "repo_name": "adelriosantiago/minimalist-dude", "id": "8c713e4c5089c4c72f4f6311f0b00ae0589ca978", "size": "9035", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/stylesheets/tooltipster.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "53393" }, { "name": "HTML", "bytes": "21444" }, { "name": "JavaScript", "bytes": "155251" } ], "symlink_target": "" }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.io.*; import java.net.*; import java.util.Objects; import javax.swing.*; import javax.swing.text.*; public final class MainPanel extends JPanel { private final JTextPane textpane = new JTextPane(); public MainPanel() { super(new BorderLayout()); Font font = makeFont(getClass().getResource("mona.ttf")); //Document doc = makeDocument(getClass().getResource("bar.utf8.txt"), "UTF-8"); if (Objects.nonNull(font)) { System.out.println(font.toString()); textpane.setFont(font.deriveFont(10f)); //textpane.setDocument(doc); } URL url = getClass().getResource("bar.utf8.txt"); try (Reader reader = new InputStreamReader(url.openStream(), "UTF-8")) { textpane.read(reader, "text"); } catch (IOException ex) { ex.printStackTrace(); } add(new JScrollPane(textpane)); setPreferredSize(new Dimension(320, 240)); } // TreeMap fontMap = new TreeMap(); // fontMap.put(font.getFamily(), font); // StyleContext sc = new StyleContext(); // Style style = sc.addStyle("Mona Style", null); // StyleConstants.setFontFamily(style, font.getFamily()); // StyleConstants.setFontSize(style, 12); // FontDocument doc = new FontDocument(sc); // doc.setLogicalStyle(0, style); // textpane.setDocument(doc); // private static Font makeFont(URL url) { // Font font = null; // InputStream is = null; // try { // is = url.openStream(); // font = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(12f); // is.close(); // } catch (IOException ioe) { // ioe.printStackTrace(); // } catch (FontFormatException ffe) { // ffe.printStackTrace(); // } finally { // if (is != null) { // try { // is.close(); // } catch (IOException ex) { // ex.printStackTrace(); // } // } // } // return font; // } private static Font makeFont(URL url) { Font font = null; try (InputStream is = url.openStream()) { font = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(12f); } catch (IOException | FontFormatException ex) { ex.printStackTrace(); } return font; } // private static Document makeDocument(URL url, String encoding) { // DefaultStyledDocument doc = new DefaultStyledDocument(); // try (Reader reader = new InputStreamReader(url.openStream(), encoding); // Scanner scanner = new Scanner(reader)) { // while (scanner.hasNextLine()) { // doc.insertString(doc.getLength(), String.format("%s%n", scanner.nextLine()), null); // } // // char[] buff = new char[4096]; // // int nch; // // while ((nch = reader.read(buff, 0, buff.length)) != -1) { // // doc.insertString(doc.getLength(), new String(buff, 0, nch), null); // // } // //reader.close(); // } catch (IOException | BadLocationException ex) { // ex.printStackTrace(); // } // return doc; // } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
{ "content_hash": "3ab3ed6a686153b085efb4b8288a2f82", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 102, "avg_line_length": 36.34453781512605, "alnum_prop": 0.5445086705202312, "repo_name": "mhcrnl/java-swing-tips", "id": "d87848a08e59956816f3afd756916d487eefec7e", "size": "4325", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CreateFont/src/java/example/MainPanel.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "404976" }, { "name": "HTML", "bytes": "213180" }, { "name": "Java", "bytes": "3865671" }, { "name": "Shell", "bytes": "456768" } ], "symlink_target": "" }
import { BaseEntity, Column, Entity, JoinColumn, ManyToOne } from 'typeorm'; import { Player } from '../player/player.entity'; import { Game } from './game.entity'; @Entity('player_game') export class PlayerGame extends BaseEntity { @Column({ default: 0, name: 'break_and_run', nullable: false, type: 'smallint', }) public breakAndRun: number; @Column({ default: () => 'CURRENT_TIMESTAMP', name: 'created_at', nullable: false, type: 'timestamptz', }) public createdAt: Date; @Column({ default: 0, nullable: false, type: 'smallint', }) public defense: number; @ManyToOne(type => Game, game => game.players, { primary: true }) @JoinColumn({ name: 'game_id', }) public gameId: Game; @Column({ default: 0, name: 'nine_on_snap', nullable: false, type: 'smallint', }) public nineOnSnap: number; @ManyToOne(type => Player, player => player.games, { primary: true }) @JoinColumn({ name: 'player_id', }) public playerId: Player; @Column({ default: 0, name: 'player_score', nullable: false, type: 'smallint', }) public playerScore: number; @Column({ default: 0, name: 'points_scored', nullable: false, type: 'smallint', }) public pointsScored: number; @Column({ default: false, nullable: false, type: 'boolean', }) public skunk: boolean; @Column({ default: 0, nullable: false, type: 'smallint', }) public timeout: number; @Column({ default: null, name: 'updated_at', nullable: true, type: 'timestamptz', }) public updatedAt: Date; @Column({ default: false, nullable: false, type: 'boolean', }) public won: boolean; }
{ "content_hash": "9f129d111e4542a34a638d681ea09ca0", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 76, "avg_line_length": 18.4, "alnum_prop": 0.5978260869565217, "repo_name": "Chingu-Dolphins-3/9ball-scoring-app", "id": "18ee646834e5b9565b0032d195480a00c90814fd", "size": "1748", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/entity/player-game.entity.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1743" }, { "name": "HTML", "bytes": "1599" }, { "name": "TypeScript", "bytes": "22963" } ], "symlink_target": "" }
.available-shelters-container { display: flex; flex-direction: column; } .available-shelters-header { background-color: white; text-align: center; padding: 20px 110px; color: #35343D; font-family: Poppins; font-size: 16px; } .available-shelters-map-container { height: 100vh; width: 100%; }
{ "content_hash": "acb5875a0bd233115b69363b9d6ed7af", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 35, "avg_line_length": 17.38888888888889, "alnum_prop": 0.6964856230031949, "repo_name": "CrashHere/react-frontend", "id": "57ce6b6d5d618bf72043afc6bf4e81b461299126", "size": "313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/AvailableShelters/availableShelters.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5028" }, { "name": "HTML", "bytes": "2461" }, { "name": "JavaScript", "bytes": "23297" } ], "symlink_target": "" }
class AddPaypalAndContactInfoToFarms < ActiveRecord::Migration def self.up add_column :farms, :paypal_link, :string add_column :farms, :contact_email, :string add_column :farms, :contact_name, :string end def self.down remove_column :farms, :contact_name remove_column :farms, :contact_email remove_column :farms, :paypal_link end end
{ "content_hash": "336cafb359ddbf17d66fa6635f5860bc", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 62, "avg_line_length": 28.307692307692307, "alnum_prop": 0.7119565217391305, "repo_name": "kathrynaaker/eggs", "id": "1f4a898870f2bb5bccea916e032a7699f66c578a", "size": "368", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "db/migrate/20100326200535_add_paypal_and_contact_info_to_farms.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "239039" }, { "name": "Ruby", "bytes": "333584" } ], "symlink_target": "" }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
{ "content_hash": "d2d6e30203b5609a1a1d53bd2e457e6a", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 90, "avg_line_length": 31.6, "alnum_prop": 0.6582278481012658, "repo_name": "Rogue24/MyProjectDemo", "id": "e5914ec1252b31c6de41dbf3f8cbc40e91d6b985", "size": "329", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "QQ音乐/QQ音乐/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "54687" }, { "name": "Objective-C", "bytes": "2784448" }, { "name": "Objective-C++", "bytes": "124423" }, { "name": "Ruby", "bytes": "334" }, { "name": "Shell", "bytes": "16418" } ], "symlink_target": "" }
(function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Support: Firefox 18+ // Can't be in strict mode, several libs including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) //"use strict"; var arr = []; var document = window.document; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "2.2.5-pre b14ce54334a568eaaa107be4c441660a57c3db24", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = jQuery.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) var realStringObj = obj && obj.toString(); return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; }, isPlainObject: function( obj ) { var key; // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call( obj, "constructor" ) && !hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android<4.0, iOS<6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf( "use strict" ) === 1 ) { script = document.createElement( "script" ); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Support: IE9-11+ // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); // JSHint would error on this code due to the Symbol not being defined in ES5. // Defining this global in .jshintrc would create a danger of using the global // unguarded in another place, it seems safer to just disable JSHint for these // three lines. /* jshint ignore: start */ if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } /* jshint ignore: end */ // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: iOS 8.2 (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.1 * http://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2015-10-17 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, nidselect, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // ID selector if ( (m = match[1]) ) { // Document context if ( nodeType === 9 ) { if ( (elem = context.getElementById( m )) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && (elem = newContext.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // Capture the context ID, setting it first if necessary if ( (nid = context.getAttribute( "id" )) ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", (nid = expando) ); } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; while ( i-- ) { groups[i] = nidselect + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9-11, Edge // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) if ( (parent = document.defaultView) && parent.top !== parent ) { // Support: IE 11 if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); return m ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === document ? -1 : b === document ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || (node[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || (outerCache[ node.uniqueID ] = {}); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); if ( (oldCache = uniqueCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context === document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; if ( !context && elem.ownerDocument !== document ) { setDocument( elem ); xml = !documentIsHTML; } while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context || document, xml) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; } ); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); // Support: Blackberry 4.6 // gEBID returns nodes no longer in the document (#6963) if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[ 0 ] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( pos ? pos.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnotwhite = ( /\S+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ], [ "notify", "progress", jQuery.Callbacks( "memory" ) ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. // If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // Add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .progress( updateFunc( i, progressContexts, progressValues ) ) .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ); } else { --remaining; } } } // If we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } } ); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } } ); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE9-10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[ 0 ], key ) : emptyGet; }; var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { register: function( owner, initial ) { var value = initial || {}; // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable, non-writable property // configurability must be true to allow the property to be // deleted with the delete operator } else { Object.defineProperty( owner, this.expando, { value: value, writable: true, configurable: true } ); } return owner[ this.expando ]; }, cache: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( !acceptData( owner ) ) { return {}; } // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ prop ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : owner[ this.expando ] && owner[ this.expando ][ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase( key ) ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key === undefined ) { this.register( owner ); } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <= 35-45+ // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://code.google.com/p/chromium/issues/detail?id=378607 if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data, camelKey; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = dataUser.get( elem, key ) || // Try to find dashed key if it exists (gh-2779) // This is for 2.2.x only dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() ); if ( data !== undefined ) { return data; } camelKey = jQuery.camelCase( key ); // Attempt to get data from the cache // with the key camelized data = dataUser.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... camelKey = jQuery.camelCase( key ); this.each( function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = dataUser.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* dataUser.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf( "-" ) > -1 && data !== undefined ) { dataUser.set( this, key, value ); } } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([\w:-]+)/ ); var rscriptType = ( /^$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE9 option: [ 1, "<select multiple='multiple'>", "</select>" ], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting <tbody> or other required elements. thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { // Support: IE9-11+ // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: Android<4.1, PhantomJS<2 // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android<4.1, PhantomJS<2 // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0-4.3, Safari<=5.1 // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari<=5.1, Android<4.2 // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<=11+ // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; } )(); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE9 // See #13393 for more info function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = {}; } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Support (at least): Chrome, IE9 // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // // Support: Firefox<=42+ // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) if ( delegateCount && cur.nodeType && ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push( { elem: cur, handlers: matches } ); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split( " " ), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: ( "button buttons clientX clientY offsetX offsetY pageX pageY " + "screenX screenY toElement" ).split( " " ), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome<28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android<4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://code.google.com/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, // Support: IE 10-11, Edge 10240+ // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName( "tbody" )[ 0 ] || elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android<4.1, PhantomJS<2 // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1></$2>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <= 35-45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <= 35-45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { // Keep domManip exposed until 3.0 (gh-2225) domManip: domManip, detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var iframe, elemdisplay = { // Support: Firefox // We have to pre-define these values for FF (#10227) HTML: "block", BODY: "block" }; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" ) ) .appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = ( /^margin/ ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; var swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var documentElement = document.documentElement; ( function() { var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE9-11+ // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; div.innerHTML = ""; documentElement.appendChild( container ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; reliableMarginLeftVal = divStyle.marginLeft === "2px"; boxSizingReliableVal = divStyle.width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = divStyle.marginRight === "4px"; documentElement.removeChild( container ); } jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computeStyleTests(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelMarginRight: function() { // Support: Android 4.0-4.3 // We're checking for boxSizingReliableVal here instead of pixelMarginRightVal // since that compresses better and they're computed together anyway. if ( boxSizingReliableVal == null ) { computeStyleTests(); } return pixelMarginRightVal; }, reliableMarginLeft: function() { // Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37 if ( boxSizingReliableVal == null ) { computeStyleTests(); } return reliableMarginLeftVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;box-sizing:content-box;" + "display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; documentElement.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv ).marginRight ); documentElement.removeChild( container ); div.removeChild( marginDiv ); return ret; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; // Support: Opera 12.1x only // Fall back to style even without computed // computed is undefined for elems on document fragments if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: IE9 // getPropertyValue is only needed for .css('filter') (#12537) if ( computed ) { // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // http://dev.w3.org/csswg/cssom/#resolved-values if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE9-11+ // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // Shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return name; } // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } function setPositiveNumber( elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test( val ) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = dataPriv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = dataPriv.access( elem, "olddisplay", defaultDisplay( elem.nodeName ) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { dataPriv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) if ( type === "number" ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // Support: IE9-11+ // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName ); // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); } ) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var matches, styles = extra && getStyles( elem ), subtract = extra && augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ); // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ name ] = value; value = jQuery.css( elem, name ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { return swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? dataPriv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show // and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", {} ); } // Store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done( function() { jQuery( elem ).hide(); } ); } anim.done( function() { var prop; dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( ( display === "none" ? defaultDisplay( elem.nodeName ) : display ) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, result ); } return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnotwhite ); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { window.clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS<=5.1, Android<=4.2+ // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE<=11+ // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: Android<=2.3 // Options inside disabled selects are incorrectly marked as disabled select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<=11+ // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); var rclass = /[\t\r\n\f]/g; function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnotwhite ) || []; while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + curValue + " " ).replace( rclass, " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( type === "string" ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = value.match( rnotwhite ) || []; while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + getClass( elem ) + " " ).replace( rclass, " " ) .indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g, rspaces = /[\x20\t\r\n\f]+/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, isFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // Handle most common string cases ret.replace( rreturn, "" ) : // Handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); jQuery.each( ( "blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu" ).split( " " ), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); jQuery.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); support.focusin = "onfocusin" in window; // Support: Firefox // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome, Safari // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = jQuery.now(); var rquery = ( /\?/ ); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ).replace( rhash, "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE8-11+ // IE throws exception if url is malformed, e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE8-11+ // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( state === 2 ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery._evalUrl = function( url ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", async: false, global: false, "throws": true } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapAll( html.call( this, i ) ); } ); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); } ); }, unwrap: function() { return this.parent().each( function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } } ).end(); } } ); jQuery.expr.filters.hidden = function( elem ) { return !jQuery.expr.filters.visible( elem ); }; jQuery.expr.filters.visible = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements // Use OR instead of AND as the element is not visible if either is true // See tickets #10406 and #13132 return elem.offsetWidth > 0 || elem.offsetHeight > 0 || elem.getClientRects().length > 0; }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ) .filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ) .map( function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE9 // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = callback( "error" ); // Support: IE9 // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "<script>" ).prop( { charset: s.scriptCharset, src: s.url } ).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); // Use native DOM manipulation to avoid our domManip AJAX trickery document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } } ); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup( { jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } } ); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && ( s.contentType || "" ) .indexOf( "application/x-www-form-urlencoded" ) === 0 && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters[ "script json" ] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // Force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always( function() { // If previous value didn't exist - remove it if ( overwritten === undefined ) { jQuery( window ).removeProp( callbackName ); // Otherwise restore preexisting value } else { window[ callbackName ] = overwritten; } // Save back as free if ( s[ callbackName ] ) { // Make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // Save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; } ); // Delegate to script return "script"; } } ); // Argument "data" should be string of html // context (optional): If specified, the fragment will be created in this context, // defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf( " " ); if ( off > -1 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax( { url: url, // If "type" variable is undefined, then "GET" method will be used. // Make value of this field explicit since // user can override it through ajaxSetup method type: type || "GET", dataType: "html", data: params } ).done( function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); // If the request succeeds, this function gets "data", "status", "jqXHR" // but they are ignored because response was set above. // If it fails, this function gets "jqXHR", "status", "error" } ).always( callback && function( jqXHR, status ) { self.each( function() { callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] ); } ); } ); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; } ); jQuery.expr.filters.animated = function( elem ) { return jQuery.grep( jQuery.timers, function( fn ) { return elem === fn.elem; } ).length; }; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend( { offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } box = elem.getBoundingClientRect(); win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume getBoundingClientRect is there when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); // Support: Safari<7-8+, Chrome<37-44+ // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); } ); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; } ); } ); jQuery.fn.extend( { bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, size: function() { return this.length; } } ); jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; } ); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( !noGlobal ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
{ "content_hash": "278476e6aca758d11d4028ca878fcbc1", "timestamp": "", "source": "github", "line_count": 9802, "max_line_length": 161, "avg_line_length": 26.252907569883696, "alnum_prop": 0.610412270577583, "repo_name": "rameshrathod/Mysite", "id": "f65c893cc7e09ffac50d453651a284a0111dfc43", "size": "257640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/jquery.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "8524" }, { "name": "HTML", "bytes": "5633" }, { "name": "JavaScript", "bytes": "11244" }, { "name": "PHP", "bytes": "1785510" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Sylius\Component\Product\Resolver; use Sylius\Component\Product\Model\ProductInterface; use Sylius\Component\Product\Model\ProductVariantInterface; final class DefaultProductVariantResolver implements ProductVariantResolverInterface { /** * {@inheritdoc} */ public function getVariant(ProductInterface $subject): ?ProductVariantInterface { if ($subject->getVariants()->isEmpty()) { return null; } return $subject->getVariants()->first(); } }
{ "content_hash": "0705264e9626894805135ae8e0958e93", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 84, "avg_line_length": 22.08, "alnum_prop": 0.6992753623188406, "repo_name": "NeverResponse/Sylius", "id": "17da20de67617770ab26d7b7b641e34608081dfd", "size": "763", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "src/Sylius/Component/Product/Resolver/DefaultProductVariantResolver.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "601" }, { "name": "CSS", "bytes": "2150" }, { "name": "Gherkin", "bytes": "791414" }, { "name": "HTML", "bytes": "303676" }, { "name": "JavaScript", "bytes": "71083" }, { "name": "PHP", "bytes": "6688446" }, { "name": "Shell", "bytes": "28860" } ], "symlink_target": "" }
var fs = require('fs'), path = require('path'); var stream = require('stream'); var browserify = require('browserify'); var babelify = require('babelify').configure({loose: 'all'}); process.chdir(path.resolve(__dirname, '..')); // make ./dist if not exist if (!fs.existsSync('dist')) { fs.mkdirSync('dist'); } // build for web browserify({standalone: 'calcium', debug: true}) .transform(babelify) .require('./lib/infer.js', {entry: true}) .bundle() .on('error', function (err) { console.log('Error: ' + err.message) }) .pipe(fs.createWriteStream('dist/calcium.js'));
{ "content_hash": "2723a2a27d2b46007a7ad6ce27ae4793", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 73, "avg_line_length": 29.75, "alnum_prop": 0.6386554621848739, "repo_name": "happibum/calcium", "id": "c4157dd1e8482b58952165ebe2ac5c6d2d5e0b88", "size": "595", "binary": false, "copies": "4", "ref": "refs/heads/dev", "path": "bin/build.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1125" }, { "name": "JavaScript", "bytes": "1050429" } ], "symlink_target": "" }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class TiEye extends React.Component<IconBaseProps, any> { }
{ "content_hash": "89799cb65aa1a749bd2ecae0bcf00ac7", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 74, "avg_line_length": 51.666666666666664, "alnum_prop": 0.7612903225806451, "repo_name": "progre/DefinitelyTyped", "id": "7d834667facc3754f4e09f019b9101e5e1d5f0f8", "size": "183", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "react-icons/ti/eye.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "HTML", "bytes": "308" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "20620621" } ], "symlink_target": "" }
// // UIDevice+JS.m // timeboy // // Created by wenghengcong on 15/6/6. // Copyright (c) 2015年 JungleSong. All rights reserved. // #import "UIDevice+JS.h" #include <sys/socket.h> // Per msqr #include <sys/sysctl.h> #include <net/if.h> #include <net/if_dl.h> #include <sys/utsname.h> static float _pointsPerCentimeter; static float _pointsPerInch; @implementation UIDevice(JS) + (NSString *) getSysInfoByName:(char *)typeSpecifier { size_t size; sysctlbyname(typeSpecifier, NULL, &size, NULL, 0); char *answer = malloc(size); sysctlbyname(typeSpecifier, answer, &size, NULL, 0); NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding]; free(answer); return results; } + (NSString *) platform { return [self getSysInfoByName:"hw.machine"]; } // Thanks, Atomicbird + (NSString *) hwmodel { return [self getSysInfoByName:"hw.model"]; } #pragma mark sysctl utils + (NSUInteger) getSysInfo: (uint) typeSpecifier { size_t size = sizeof(int); int results; int mib[2] = {CTL_HW, typeSpecifier}; sysctl(mib, 2, &results, &size, NULL, 0); return (NSUInteger) results; } + (NSUInteger) cpuFrequency { return [self getSysInfo:HW_CPU_FREQ]; } + (NSUInteger) busFrequency { return [self getSysInfo:HW_BUS_FREQ]; } + (NSUInteger) totalMemory { return [self getSysInfo:HW_PHYSMEM]; } + (NSUInteger) userMemory { return [self getSysInfo:HW_USERMEM]; } + (NSUInteger) maxSocketBufferSize { return [self getSysInfo:KIPC_MAXSOCKBUF]; } #pragma mark file system -- Thanks Joachim Bean! + (NSNumber *) totalDiskSpace { NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil]; return [fattributes objectForKey:NSFileSystemSize]; } + (NSNumber *) freeDiskSpace { NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil]; return [fattributes objectForKey:NSFileSystemFreeSize]; } #pragma mark platform type and name utils + (NSUInteger) platformType { NSString *platform = [self platform]; // if ([platform isEqualToString:@"XX"]) return UIDeviceUnknown; if ([platform isEqualToString:@"iFPGA"]) return UIDeviceIFPGA; if ([platform isEqualToString:@"iPhone1,1"]) return UIDevice1GiPhone; if ([platform isEqualToString:@"iPhone1,2"]) return UIDevice3GiPhone; if ([platform hasPrefix:@"iPhone2"]) return UIDevice3GSiPhone; if ([platform hasPrefix:@"iPhone3"]) return UIDevice4iPhone; if ([platform hasPrefix:@"iPhone4"]) return UIDevice4siPhone; if ([platform hasPrefix:@"iPhone5,2"] ||[platform hasPrefix:@"iPhone5,1"]) return UIDevice5iPhone; if ([platform hasPrefix:@"iPhone5,4"] ||[platform hasPrefix:@"iPhone5,3"]) return UIDevice5cPhone; if ([platform hasPrefix:@"iPhone6,1"] ||[platform hasPrefix:@"iPhone6,2"]) return UIDevice5siPhone; if ([platform hasPrefix:@"iPhone7,1"]) return UIDevice6PiPhone; if ([platform hasPrefix:@"iPhone7,2"]) return UIDevice6iPhone; if ([platform isEqualToString:@"iPod1,1"]) return UIDevice1GiPod; if ([platform isEqualToString:@"iPod2,1"]) return UIDevice2GiPod; if ([platform isEqualToString:@"iPod3,1"]) return UIDevice3GiPod; if ([platform isEqualToString:@"iPod4,1"]) return UIDevice4GiPod; if ([platform isEqualToString:@"iPod5,1"]) return UIDevice5GiPod; if ([platform isEqualToString:@"iPad1,1"]) return UIDevice1GiPad; if ([platform isEqualToString:@"iPad2,1"] ||[platform isEqualToString:@"iPad2,2"] ||[platform isEqualToString:@"iPad2,3"] ||[platform isEqualToString:@"iPad2,4"]) return UIDevice2GiPad; if ([platform isEqualToString:@"iPad3,1"] ||[platform isEqualToString:@"iPad3,2"] ||[platform isEqualToString:@"iPad3,3"]) return UIDevice3GiPad; if ([platform isEqualToString:@"iPad3,4"] ||[platform isEqualToString:@"iPad3,5"] ||[platform isEqualToString:@"iPad3,6"]) return UIDevice4GiPad; if ([platform isEqualToString:@"iPad4,1"] ||[platform isEqualToString:@"iPad4,2"] ||[platform isEqualToString:@"iPad4,3"]) return UIDeviceAirGiPad; if ([platform isEqualToString:@"iPad5,3"] || [platform isEqualToString:@"iPad5,4"])return UIDeviceAir2GiPad; if ([platform isEqualToString:@"iPad2,5"] ||[platform isEqualToString:@"iPad2,6"] ||[platform isEqualToString:@"iPad2,7"]) return UIDeviceiPadMini; if ([platform isEqualToString:@"iPad4,4"] ||[platform isEqualToString:@"iPad4,5"] ||[platform isEqualToString:@"iPad4,6"]) return UIDeviceiPadMini2; if ([platform isEqualToString:@"iPad4,7"] ||[platform isEqualToString:@"iPad4,8"] ||[platform isEqualToString:@"iPad4,9"]) return UIDeviceiPadMini3; if ([platform isEqualToString:@"AppleTV2,1"]) return UIDeviceAppleTV2; if ([platform isEqualToString:@"AppleTV3,1"]) return UIDeviceAppleTV3; if ([platform isEqualToString:@"AppleTV3,2"]) return UIDeviceAppleTV3; /* MISSING A SOLUTION HERE TO DATE TO DIFFERENTIATE iPAD and iPAD 3G.... SORRY! */ if ([platform hasPrefix:@"iPhone"]) return UIDeviceUnknowniPhone; if ([platform hasPrefix:@"iPod"]) return UIDeviceUnknowniPod; if ([platform hasPrefix:@"iPad"]) return UIDeviceUnknowniPad; if ([platform hasSuffix:@"86"] || [platform isEqual:@"x86_64"]) // thanks Jordan Breeding { if ([[UIScreen mainScreen] bounds].size.width < 768) return UIDeviceiPhoneSimulatoriPhone; else return UIDeviceiPhoneSimulatoriPad; return UIDeviceiPhoneSimulator; } return UIDeviceUnknown; } + (NSString *) platformString { switch ([self platformType]) { case UIDevice1GiPhone: return IPHONE_1G_NAMESTRING; case UIDevice3GiPhone: return IPHONE_3G_NAMESTRING; case UIDevice3GSiPhone: return IPHONE_3GS_NAMESTRING; case UIDevice4iPhone: return IPHONE_4_NAMESTRING; case UIDevice4siPhone: return IPHONE_4s_NAMESTRING; case UIDevice5iPhone: return IPHONE_5_NAMESTRING; case UIDevice5cPhone: return IPHONE_5c_NAMESTRING; case UIDevice5siPhone: return IPHONE_5s_NAMESTRING; case UIDevice6iPhone: return IPHONE_6_NAMESTRING; case UIDevice6PiPhone: return IPHONE_6_P_NAMESTRING; case UIDeviceUnknowniPhone: return IPHONE_UNKNOWN_NAMESTRING; case UIDevice1GiPod: return IPOD_1G_NAMESTRING; case UIDevice2GiPod: return IPOD_2G_NAMESTRING; case UIDevice3GiPod: return IPOD_3G_NAMESTRING; case UIDevice4GiPod: return IPOD_4G_NAMESTRING; case UIDevice5GiPod: return IPOD_5G_NAMESTRING; case UIDeviceUnknowniPod: return IPOD_UNKNOWN_NAMESTRING; case UIDevice1GiPad : return IPAD_1G_NAMESTRING; case UIDevice2GiPad : return IPAD_2G_NAMESTRING; case UIDevice3GiPad : return IPAD_3G_NAMESTRING; case UIDevice4GiPad : return IPAD_4G_NAMESTRING; case UIDeviceAirGiPad : return IPAD_Air_NAMESTRING; case UIDeviceAir2GiPad : return IPAD_Air2_NAMESTRING; case UIDeviceiPadMini : return IPAD_Mini_NAMESTRING; case UIDeviceiPadMini2 : return IPAD_Mini2_NAMESTRING; case UIDeviceiPadMini3 : return IPAD_Mini3_NAMESTRING; case UIDeviceAppleTV2 : return APPLETV_2G_NAMESTRING; case UIDeviceAppleTV3 : return APPLETV_3G_NAMESTRING; case UIDeviceiPhoneSimulator: return IPHONE_SIMULATOR_NAMESTRING; case UIDeviceiPhoneSimulatoriPhone: return IPHONE_SIMULATOR_IPHONE_NAMESTRING; case UIDeviceiPhoneSimulatoriPad: return IPHONE_SIMULATOR_IPAD_NAMESTRING; case UIDeviceIFPGA: return IFPGA_NAMESTRING; default: return IPOD_FAMILY_UNKNOWN_DEVICE; } } #pragma mark MAC addy // Return the local MAC addy // Courtesy of FreeBSD hackers email list // Accidentally munged during previous update. Fixed thanks to mlamb. + (NSString *) macaddress { int mib[6]; size_t len; char *buf; unsigned char *ptr; struct if_msghdr *ifm; struct sockaddr_dl *sdl; mib[0] = CTL_NET; mib[1] = AF_ROUTE; mib[2] = 0; mib[3] = AF_LINK; mib[4] = NET_RT_IFLIST; if ((mib[5] = if_nametoindex("en0")) == 0) { printf("Error: if_nametoindex error\n"); return NULL; } if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { printf("Error: sysctl, take 1\n"); return NULL; } if ((buf = malloc(len)) == NULL) { printf("Could not allocate memory. error!\n"); return NULL; } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { printf("Error: sysctl, take 2"); return NULL; } ifm = (struct if_msghdr *)buf; sdl = (struct sockaddr_dl *)(ifm + 1); ptr = (unsigned char *)LLADDR(sdl); // NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)]; free(buf); return [outstring uppercaseString]; } + (NSString *) platformCode { switch ([self platformType]) { case UIDevice1GiPhone: return @"M68"; case UIDevice3GiPhone: return @"N82"; case UIDevice3GSiPhone: return @"N88"; case UIDevice4iPhone: return @"N89"; case UIDevice5iPhone: return IPHONE_UNKNOWN_NAMESTRING; case UIDeviceUnknowniPhone: return IPHONE_UNKNOWN_NAMESTRING; case UIDevice1GiPod: return @"N45"; case UIDevice2GiPod: return @"N72"; case UIDevice3GiPod: return @"N18"; case UIDevice4GiPod: return @"N80"; case UIDeviceUnknowniPod: return IPOD_UNKNOWN_NAMESTRING; case UIDevice1GiPad: return @"K48"; case UIDevice2GiPad: return IPAD_UNKNOWN_NAMESTRING; case UIDeviceUnknowniPad: return IPAD_UNKNOWN_NAMESTRING; case UIDeviceAppleTV2: return @"K66"; case UIDeviceiPhoneSimulator: return IPHONE_SIMULATOR_NAMESTRING; default: return IPOD_FAMILY_UNKNOWN_DEVICE; } } + (NSString *)systemVersion { return [[UIDevice currentDevice] systemVersion]; } + (BOOL)hasCamera { return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]; } #pragma mark - #pragma mark Public Methods + (NSString *) uniqueDeviceIdentifier{ NSString *macaddress = [UIDevice macaddress]; NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier]; NSString *stringToHash = [NSString stringWithFormat:@"%@%@",macaddress,bundleIdentifier]; NSString *uniqueIdentifier = [UIDevice md5Sum:stringToHash]; return uniqueIdentifier; } + (NSString *) uniqueGlobalDeviceIdentifier{ NSString *macaddress = [UIDevice macaddress]; NSString *uniqueIdentifier = [UIDevice md5Sum:macaddress]; return uniqueIdentifier; } + (BOOL)isMCOK{ __block BOOL ok = YES; if ([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission:)]) { if ([self isIOS7]) { [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) { if (granted) { ok = YES; NSLog(@"允许使用麦克风!"); } else { NSLog(@"不允许使用麦克风!"); ok = NO; } }]; } } return ok; } + (BOOL)isIOS7 { NSString *str =[[UIDevice currentDevice] systemVersion]; NSArray *array = [str componentsSeparatedByString:@"."]; if ([array[0] intValue] >= 7) { return YES; }else{ return NO; } } + (BOOL)isIOS8 { NSString *str =[[UIDevice currentDevice] systemVersion]; NSArray *array = [str componentsSeparatedByString:@"."]; if ([array[0] intValue] >= 8) { return YES; }else{ return NO; } } + (BOOL)isiPhone6 { return [self platformType] == UIDevice6iPhone; } + (BOOL)isiPhone6P { return [self platformType] == UIDevice6PiPhone; } + (float)mathiPhoneType:(float)f { if ([self isiPhone6]) { return f; }else if ([self isiPhone6P]){ return f*1.104; }else { return f*0.853333333; } } + (BOOL)isIphone5 { if (([self platformType] == UIDevice5iPhone) ||([self platformType] == UIDevice5cPhone) || ([self platformType] == UIDevice5siPhone)) { return YES; } return NO; } + (BOOL)isJailbroken { BOOL jailbroken = NO; NSString *cydiaPath = @"/Applications/Cydia.app"; NSString *aptPath = @"/private/var/lib/apt/"; if ([[NSFileManager defaultManager] fileExistsAtPath:cydiaPath]) { jailbroken = YES; } if ([[NSFileManager defaultManager] fileExistsAtPath:aptPath]) { jailbroken = YES; } return jailbroken; } #pragma mark- screen resolution +(void)initializeScreenParameter { struct utsname sysinfo; if (uname(&sysinfo) == 0) { NSString *identifier = [NSString stringWithUTF8String:sysinfo.machine]; // group devices with same points-density NSArray *iDevices = @[@{@"identifiers": @[@"iPad1,1", // iPad @"iPad2,1", @"iPad2,2", @"iPad2,3", @"iPad2,4", // iPad 2 @"iPad3,1", @"iPad3,2", @"iPad3,3", // iPad 3 @"iPad3,4", @"iPad3,5", @"iPad3,6", // iPad 4 @"iPad4,1", @"iPad4,2", @"iPad4,3", // iPad Air @"iPad5,3", @"iPad5,4"], // iPad Air 2 @"pointsPerCentimeter": @52.0f, @"pointsPerInch": @132.0f}, @{@"identifiers": @[@"iPod5,1", // iPod Touch 5th generation @"iPhone1,1", // iPhone 2G @"iPhone1,2", // iPhone 3G @"iPhone2,1", // iPhone 3GS @"iPhone3,1", @"iPhone3,2", @"iPhone3,3", // iPhone 4 @"iPhone4,1", // iPhone 4S @"iPhone5,1", @"iPhone5,2", // iPhone 5 @"iPhone5,3", @"iPhone5,4", // iPhone 5C @"iPhone6,1", @"iPhone6,2", // iPhone 5S @"iPad2,5", @"iPad2,6", @"iPad2,7", // iPad Mini @"i386", @"x86_64"], // iOS simulator (assuming iPad Mini simulator) @"pointsPerCentimeter": @64.0f, @"pointsPerInch": @163.0f}, @{@"identifiers": @[@"iPhone7,1"], // iPhone 6 Plus @"pointsPerCentimeter": @158.0f, @"pointsPerInch": @401.0f}, @{@"identifiers": @[@"iPhone7,2", // iPhone 6 @"iPad4,4", @"iPad4,5", @"iPad4,6", // iPad Mini Retina (2) @"iPad4,7", @"iPad4,8", @"iPad4,9"], // iPad Mini 3 @"pointsPerCentimeter": @128.0f, @"pointsPerInch": @326.0f} ]; for (id deviceClass in iDevices) for (NSString *deviceId in [deviceClass objectForKey:@"identifiers"]) if ([identifier isEqualToString:deviceId]) { _pointsPerCentimeter = [[deviceClass objectForKey:@"pointsPerCentimeter"] floatValue]; _pointsPerInch = [[deviceClass objectForKey:@"pointsPerInch"] floatValue]; break; } } NSAssert(_pointsPerCentimeter > 0.0f || _pointsPerInch > 0.0f, @"Unknown device: %s", sysinfo.machine); } + (float)pointsPerCentimeter { [UIDevice initializeScreenParameter]; return _pointsPerCentimeter; } + (float)pixelsPerCentimeter { [UIDevice initializeScreenParameter]; return _pointsPerCentimeter * [[UIScreen mainScreen] scale]; } // map from POINTS to PIXELS + (float)pointsPerInch { [UIDevice initializeScreenParameter]; return _pointsPerInch; } + (float)pixelsPerInch { [UIDevice initializeScreenParameter]; return _pointsPerInch * [[UIScreen mainScreen] scale]; } // map from POINTS to PIXELS + (NSString *)md5Sum:(NSString *)str { unsigned char digest[CC_MD5_DIGEST_LENGTH], i; CC_MD5([str UTF8String], (uint32_t)[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding], digest); NSMutableString *ms = [NSMutableString string]; for (i=0;i<CC_MD5_DIGEST_LENGTH;i++) { [ms appendFormat: @"%02x", (int)(digest[i])]; } return [ms copy]; } @end
{ "content_hash": "7b9ad70748ed08d2b523a323a14f7858", "timestamp": "", "source": "github", "line_count": 511, "max_line_length": 146, "avg_line_length": 35.545988258317024, "alnum_prop": 0.5767452103060999, "repo_name": "wenghengcong/JSBProjectBase", "id": "f1ca20695807d38bacb9974ef4409626d82926ce", "size": "18200", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "JSBProjectBase/Category/temp/UIDevice+JS.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1366192" }, { "name": "C++", "bytes": "98860" }, { "name": "HTML", "bytes": "4555" }, { "name": "Objective-C", "bytes": "906442" }, { "name": "Ruby", "bytes": "375" } ], "symlink_target": "" }
import scala.reflect.runtime.universe._ object Test extends App { def classManifestIsnotTypeTag[T: ClassManifest] = { println(implicitly[TypeTag[T]]) } classManifestIsnotTypeTag[Int] classManifestIsnotTypeTag[String] classManifestIsnotTypeTag[Array[Int]] }
{ "content_hash": "d649a9722f6d3a1faeedc562d95bfb3e", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 53, "avg_line_length": 24.727272727272727, "alnum_prop": 0.7794117647058824, "repo_name": "shimib/scala", "id": "29d03a8ec8a7186a994fbdff8cf88c20ec885d5d", "size": "272", "binary": false, "copies": "5", "ref": "refs/heads/2.12.x", "path": "test/files/neg/interop_classmanifests_arenot_typetags.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Awk", "bytes": "1379" }, { "name": "Batchfile", "bytes": "2970" }, { "name": "C", "bytes": "141" }, { "name": "CSS", "bytes": "57699" }, { "name": "HTML", "bytes": "6291" }, { "name": "Java", "bytes": "344757" }, { "name": "JavaScript", "bytes": "54567" }, { "name": "Ruby", "bytes": "142" }, { "name": "Scala", "bytes": "15828866" }, { "name": "Shell", "bytes": "46895" } ], "symlink_target": "" }
<div class="form-group form-download"> <label class="col-md-2 control-label" for="{{attributes.name}}">{{fieldInfo.label}}</label> <div class="col-md-10"> <select-objectids class="col-md-6" selected="selectedObject" widgetmodel="mod" fieldinfo="fieldInfo"></select-objectids> <div class="buttonlist col-md-6"> <material-button class="material-button-fab fab-sm" ng-click="addToSet()" tabindex="-1" aria-label=""> <i class="fa fa-plus"></i> </material-button> </div> <p class="col-md-12 help-block">{{fieldInfo.options.help || 'Drag and Drop elements for the correct position'}}</p> <ul ui-sortable class="list-group" ng-model="renderedData"> <li class="col-md-12 list-group-item" ng-repeat="item in renderedData"> <div class="col-md-6">{{ item.text }}</div> <div class="col-md-6 buttonlist"> <material-button class="material-button-fab fab-sm" ng-click="removeFromSet(item)" tabindex="-1" aria-label=""> <i class="fa fa-minus"></i> </material-button> </div> </li> </ul> </div> </div>
{ "content_hash": "ad98271da7cea2c122e1b0facba67670", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 126, "avg_line_length": 51.63636363636363, "alnum_prop": 0.6065140845070423, "repo_name": "molecuel/mlcl_forms", "id": "3525482fded633dc7ef6e37511cf26e66edcf299", "size": "1136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/plugins/field_array_objectid/field_array_objectid.tpl.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3937" }, { "name": "JavaScript", "bytes": "258675" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>huffman: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.15.1 / huffman - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> huffman <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-25 08:14:50 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-25 08:14:50 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.15.1 Formal proof management system dune 3.2.0 Fast, portable, and opinionated build system ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;palmskog@gmail.com&quot; homepage: &quot;https://github.com/coq-community/huffman&quot; dev-repo: &quot;git+https://github.com/coq-community/huffman.git&quot; bug-reports: &quot;https://github.com/coq-community/huffman/issues&quot; license: &quot;LGPL-2.1-or-later&quot; synopsis: &quot;A Coq proof of the correctness of the Huffman coding algorithm&quot; description: &quot;&quot;&quot; This projects contains a Coq proof of the correctness of the Huffman coding algorithm, as described in David A. Huffman&#39;s paper A Method for the Construction of Minimum-Redundancy Codes, Proc. IRE, pp. 1098-1101, September 1952. &quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;category:Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms&quot; &quot;category:Miscellaneous/Extracted Programs/Combinatorics&quot; &quot;keyword:data compression&quot; &quot;keyword:code&quot; &quot;keyword:huffman tree&quot; &quot;logpath:Huffman&quot; &quot;date:2019-05-15&quot; ] authors: [ &quot;Laurent Théry&quot; ] url { src: &quot;https://github.com/coq-community/huffman/archive/v8.9.0.tar.gz&quot; checksum: &quot;sha256=20b63eae0d17a23646446fcca22de945d6a19a03246bec8b5b4c8da6d6f3184b&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-huffman.8.9.0 coq.8.15.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.15.1). The following dependencies couldn&#39;t be met: - coq-huffman -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-huffman.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "5468cc5a32bd76151d5996c03675551e", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 159, "avg_line_length": 41.11931818181818, "alnum_prop": 0.5546497167334531, "repo_name": "coq-bench/coq-bench.github.io", "id": "4a760488fd2738dfc463c26b9002e3c012efab87", "size": "7263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.15.1/huffman/8.9.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"> <meta name="fragment" content="!"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.css"> <title>Finite state machine demo</title> </head> <body> <div id="app"></div> <script src="./lib/demo.js"></script> </body> </html>
{ "content_hash": "d055602332a21f9fbca73f8e503f16e7", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 124, "avg_line_length": 33.5625, "alnum_prop": 0.659217877094972, "repo_name": "brucou/component-combinators", "id": "9d79fa03c3b54b25accf4aec4e75a071791929e3", "size": "537", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/volunteerApplication/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "762578" }, { "name": "HTML", "bytes": "5316" }, { "name": "JavaScript", "bytes": "606893" } ], "symlink_target": "" }
'use strict'; const config = require('config'); const debug = require('debug')('routes:brackets'); const fs = require('fs'); const http = require('http'); const https = require('https'); const httpMock = require('node-mocks-http'); const path = require('path'); const urlUtil = require('url'); const brackets = require('../libs/brackets-server'); const bracketsDist = path.join(process.cwd(), 'libs', 'brackets-server', 'brackets-dist'); const Project = require('../models/project'); const util = require('../libs/util'); const zipped = { '.js': 'application/javascript', '.css': 'text/css'}; module.exports = function(express, server, wsServer) { const router = express.Router(); router.get('/*', util.isLoggedIn, (req, res, next) => { const url = req.url; if (url.startsWith('/proxy/')) { const reqUrl = decodeURIComponent(url.substr('/proxy/'.length)); let options = urlUtil.parse(reqUrl); const httpClient = options.protocol === 'http' ? http : https; if (config.util.getEnv('NODE_ENV') === 'test') { httpClient = httpMock; } delete options.protocol; options.method = 'GET'; req.pause(); const connector = httpClient.request(options, (_res) => { _res.pause(); res.writeHead(_res.statusCode, _res.headers); _res.pipe(res); _res.resume(); }); req.pipe(connector); req.resume(); return; } const cntType = zipped[path.extname(url)]; let cntPath = path.join(bracketsDist, url); if (cntType) { cntPath = cntPath + '.gz'; if (fs.existsSync(cntPath)) { res.set('Content-Encoding', 'gzip'); res.set('Content-Type', cntType); res.sendFile(cntPath); } else { debug(cntPath + ' is not found.'); next(); } } else { if (fs.existsSync(cntPath)) { res.sendFile(path.join(bracketsDist, url)); } else { // Try to connect index.html if the basename of the url is project Id const projectId = path.basename(url); Project.findOne({'_id': projectId }, (err, project) => { if (project) { util.isProjectCreatedByUser(projectId, req.user, function(createdByCurrentUser) { if (!createdByCurrentUser) { return res.sendStatus(403); } // Save project to notify project updates project.save(); const bracketsOpts = { httpRoot: '/brackets/' + projectId, projectsDir: path.join(process.cwd(), 'projects', projectId), supportDir: path.join(process.cwd(), 'projects', 'support', projectId) }; brackets(server, wsServer, bracketsOpts); res.sendFile(path.join(bracketsDist, 'index.html')); }); } else { debug(cntPath + ' is not found.'); next(); } }); } } }); return router; };
{ "content_hash": "47b8861bf8eac9b0ac68a96834a4066a", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 93, "avg_line_length": 31.526315789473685, "alnum_prop": 0.5659432387312187, "repo_name": "HunseopJeong/WATT", "id": "2289b3fbdc745635aa903c3e538d115b92554929", "size": "2995", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "routes/brackets.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "19228" }, { "name": "C++", "bytes": "440774" }, { "name": "CSS", "bytes": "179387" }, { "name": "Dockerfile", "bytes": "4607" }, { "name": "GLSL", "bytes": "489" }, { "name": "HTML", "bytes": "3258501" }, { "name": "JavaScript", "bytes": "5789927" }, { "name": "Makefile", "bytes": "89145" }, { "name": "Python", "bytes": "84688" }, { "name": "Shell", "bytes": "8725" } ], "symlink_target": "" }
import numpy as np from numpy.testing import assert_array_equal, assert_allclose import pytest from sklearn.ensemble._hist_gradient_boosting.binning import ( _BinMapper, _find_binning_thresholds, _map_to_bins, ) from sklearn.ensemble._hist_gradient_boosting.common import X_DTYPE from sklearn.ensemble._hist_gradient_boosting.common import X_BINNED_DTYPE from sklearn.ensemble._hist_gradient_boosting.common import ALMOST_INF from sklearn.utils._openmp_helpers import _openmp_effective_n_threads n_threads = _openmp_effective_n_threads() DATA = ( np.random.RandomState(42) .normal(loc=[0, 10], scale=[1, 0.01], size=(int(1e6), 2)) .astype(X_DTYPE) ) def test_find_binning_thresholds_regular_data(): data = np.linspace(0, 10, 1001) bin_thresholds = _find_binning_thresholds(data, max_bins=10) assert_allclose(bin_thresholds, [1, 2, 3, 4, 5, 6, 7, 8, 9]) bin_thresholds = _find_binning_thresholds(data, max_bins=5) assert_allclose(bin_thresholds, [2, 4, 6, 8]) def test_find_binning_thresholds_small_regular_data(): data = np.linspace(0, 10, 11) bin_thresholds = _find_binning_thresholds(data, max_bins=5) assert_allclose(bin_thresholds, [2, 4, 6, 8]) bin_thresholds = _find_binning_thresholds(data, max_bins=10) assert_allclose(bin_thresholds, [1, 2, 3, 4, 5, 6, 7, 8, 9]) bin_thresholds = _find_binning_thresholds(data, max_bins=11) assert_allclose(bin_thresholds, np.arange(10) + 0.5) bin_thresholds = _find_binning_thresholds(data, max_bins=255) assert_allclose(bin_thresholds, np.arange(10) + 0.5) def test_find_binning_thresholds_random_data(): bin_thresholds = [ _find_binning_thresholds(DATA[:, i], max_bins=255) for i in range(2) ] for i in range(len(bin_thresholds)): assert bin_thresholds[i].shape == (254,) # 255 - 1 assert bin_thresholds[i].dtype == DATA.dtype assert_allclose( bin_thresholds[0][[64, 128, 192]], np.array([-0.7, 0.0, 0.7]), atol=1e-1 ) assert_allclose( bin_thresholds[1][[64, 128, 192]], np.array([9.99, 10.00, 10.01]), atol=1e-2 ) def test_find_binning_thresholds_low_n_bins(): bin_thresholds = [ _find_binning_thresholds(DATA[:, i], max_bins=128) for i in range(2) ] for i in range(len(bin_thresholds)): assert bin_thresholds[i].shape == (127,) # 128 - 1 assert bin_thresholds[i].dtype == DATA.dtype @pytest.mark.parametrize("n_bins", (2, 257)) def test_invalid_n_bins(n_bins): err_msg = "n_bins={} should be no smaller than 3 and no larger than 256".format( n_bins ) with pytest.raises(ValueError, match=err_msg): _BinMapper(n_bins=n_bins).fit(DATA) def test_bin_mapper_n_features_transform(): mapper = _BinMapper(n_bins=42, random_state=42).fit(DATA) err_msg = "This estimator was fitted with 2 features but 4 got passed" with pytest.raises(ValueError, match=err_msg): mapper.transform(np.repeat(DATA, 2, axis=1)) @pytest.mark.parametrize("max_bins", [16, 128, 255]) def test_map_to_bins(max_bins): bin_thresholds = [ _find_binning_thresholds(DATA[:, i], max_bins=max_bins) for i in range(2) ] binned = np.zeros_like(DATA, dtype=X_BINNED_DTYPE, order="F") last_bin_idx = max_bins _map_to_bins(DATA, bin_thresholds, last_bin_idx, n_threads, binned) assert binned.shape == DATA.shape assert binned.dtype == np.uint8 assert binned.flags.f_contiguous min_indices = DATA.argmin(axis=0) max_indices = DATA.argmax(axis=0) for feature_idx, min_idx in enumerate(min_indices): assert binned[min_idx, feature_idx] == 0 for feature_idx, max_idx in enumerate(max_indices): assert binned[max_idx, feature_idx] == max_bins - 1 @pytest.mark.parametrize("max_bins", [5, 10, 42]) def test_bin_mapper_random_data(max_bins): n_samples, n_features = DATA.shape expected_count_per_bin = n_samples // max_bins tol = int(0.05 * expected_count_per_bin) # max_bins is the number of bins for non-missing values n_bins = max_bins + 1 mapper = _BinMapper(n_bins=n_bins, random_state=42).fit(DATA) binned = mapper.transform(DATA) assert binned.shape == (n_samples, n_features) assert binned.dtype == np.uint8 assert_array_equal(binned.min(axis=0), np.array([0, 0])) assert_array_equal(binned.max(axis=0), np.array([max_bins - 1, max_bins - 1])) assert len(mapper.bin_thresholds_) == n_features for bin_thresholds_feature in mapper.bin_thresholds_: assert bin_thresholds_feature.shape == (max_bins - 1,) assert bin_thresholds_feature.dtype == DATA.dtype assert np.all(mapper.n_bins_non_missing_ == max_bins) # Check that the binned data is approximately balanced across bins. for feature_idx in range(n_features): for bin_idx in range(max_bins): count = (binned[:, feature_idx] == bin_idx).sum() assert abs(count - expected_count_per_bin) < tol @pytest.mark.parametrize("n_samples, max_bins", [(5, 5), (5, 10), (5, 11), (42, 255)]) def test_bin_mapper_small_random_data(n_samples, max_bins): data = np.random.RandomState(42).normal(size=n_samples).reshape(-1, 1) assert len(np.unique(data)) == n_samples # max_bins is the number of bins for non-missing values n_bins = max_bins + 1 mapper = _BinMapper(n_bins=n_bins, random_state=42) binned = mapper.fit_transform(data) assert binned.shape == data.shape assert binned.dtype == np.uint8 assert_array_equal(binned.ravel()[np.argsort(data.ravel())], np.arange(n_samples)) @pytest.mark.parametrize( "max_bins, n_distinct, multiplier", [ (5, 5, 1), (5, 5, 3), (255, 12, 42), ], ) def test_bin_mapper_identity_repeated_values(max_bins, n_distinct, multiplier): data = np.array(list(range(n_distinct)) * multiplier).reshape(-1, 1) # max_bins is the number of bins for non-missing values n_bins = max_bins + 1 binned = _BinMapper(n_bins=n_bins).fit_transform(data) assert_array_equal(data, binned) @pytest.mark.parametrize("n_distinct", [2, 7, 42]) def test_bin_mapper_repeated_values_invariance(n_distinct): rng = np.random.RandomState(42) distinct_values = rng.normal(size=n_distinct) assert len(np.unique(distinct_values)) == n_distinct repeated_indices = rng.randint(low=0, high=n_distinct, size=1000) data = distinct_values[repeated_indices] rng.shuffle(data) assert_array_equal(np.unique(data), np.sort(distinct_values)) data = data.reshape(-1, 1) mapper_1 = _BinMapper(n_bins=n_distinct + 1) binned_1 = mapper_1.fit_transform(data) assert_array_equal(np.unique(binned_1[:, 0]), np.arange(n_distinct)) # Adding more bins to the mapper yields the same results (same thresholds) mapper_2 = _BinMapper(n_bins=min(256, n_distinct * 3) + 1) binned_2 = mapper_2.fit_transform(data) assert_allclose(mapper_1.bin_thresholds_[0], mapper_2.bin_thresholds_[0]) assert_array_equal(binned_1, binned_2) @pytest.mark.parametrize( "max_bins, scale, offset", [ (3, 2, -1), (42, 1, 0), (255, 0.3, 42), ], ) def test_bin_mapper_identity_small(max_bins, scale, offset): data = np.arange(max_bins).reshape(-1, 1) * scale + offset # max_bins is the number of bins for non-missing values n_bins = max_bins + 1 binned = _BinMapper(n_bins=n_bins).fit_transform(data) assert_array_equal(binned, np.arange(max_bins).reshape(-1, 1)) @pytest.mark.parametrize( "max_bins_small, max_bins_large", [ (2, 2), (3, 3), (4, 4), (42, 42), (255, 255), (5, 17), (42, 255), ], ) def test_bin_mapper_idempotence(max_bins_small, max_bins_large): assert max_bins_large >= max_bins_small data = np.random.RandomState(42).normal(size=30000).reshape(-1, 1) mapper_small = _BinMapper(n_bins=max_bins_small + 1) mapper_large = _BinMapper(n_bins=max_bins_small + 1) binned_small = mapper_small.fit_transform(data) binned_large = mapper_large.fit_transform(binned_small) assert_array_equal(binned_small, binned_large) @pytest.mark.parametrize("n_bins", [10, 100, 256]) @pytest.mark.parametrize("diff", [-5, 0, 5]) def test_n_bins_non_missing(n_bins, diff): # Check that n_bins_non_missing is n_unique_values when # there are not a lot of unique values, else n_bins - 1. n_unique_values = n_bins + diff X = list(range(n_unique_values)) * 2 X = np.array(X).reshape(-1, 1) mapper = _BinMapper(n_bins=n_bins).fit(X) assert np.all(mapper.n_bins_non_missing_ == min(n_bins - 1, n_unique_values)) def test_subsample(): # Make sure bin thresholds are different when applying subsampling mapper_no_subsample = _BinMapper(subsample=None, random_state=0).fit(DATA) mapper_subsample = _BinMapper(subsample=256, random_state=0).fit(DATA) for feature in range(DATA.shape[1]): assert not np.allclose( mapper_no_subsample.bin_thresholds_[feature], mapper_subsample.bin_thresholds_[feature], rtol=1e-4, ) @pytest.mark.parametrize( "n_bins, n_bins_non_missing, X_trans_expected", [ ( 256, [4, 2, 2], [ [0, 0, 0], # 255 <=> missing value [255, 255, 0], [1, 0, 0], [255, 1, 1], [2, 1, 1], [3, 0, 0], ], ), ( 3, [2, 2, 2], [ [0, 0, 0], # 2 <=> missing value [2, 2, 0], [0, 0, 0], [2, 1, 1], [1, 1, 1], [1, 0, 0], ], ), ], ) def test_missing_values_support(n_bins, n_bins_non_missing, X_trans_expected): # check for missing values: make sure nans are mapped to the last bin # and that the _BinMapper attributes are correct X = [ [1, 1, 0], [np.NaN, np.NaN, 0], [2, 1, 0], [np.NaN, 2, 1], [3, 2, 1], [4, 1, 0], ] X = np.array(X) mapper = _BinMapper(n_bins=n_bins) mapper.fit(X) assert_array_equal(mapper.n_bins_non_missing_, n_bins_non_missing) for feature_idx in range(X.shape[1]): assert ( len(mapper.bin_thresholds_[feature_idx]) == n_bins_non_missing[feature_idx] - 1 ) assert mapper.missing_values_bin_idx_ == n_bins - 1 X_trans = mapper.transform(X) assert_array_equal(X_trans, X_trans_expected) def test_infinite_values(): # Make sure infinite values are properly handled. bin_mapper = _BinMapper() X = np.array([-np.inf, 0, 1, np.inf]).reshape(-1, 1) bin_mapper.fit(X) assert_allclose(bin_mapper.bin_thresholds_[0], [-np.inf, 0.5, ALMOST_INF]) assert bin_mapper.n_bins_non_missing_ == [4] expected_binned_X = np.array([0, 1, 2, 3]).reshape(-1, 1) assert_array_equal(bin_mapper.transform(X), expected_binned_X) @pytest.mark.parametrize("n_bins", [15, 256]) def test_categorical_feature(n_bins): # Basic test for categorical features # we make sure that categories are mapped into [0, n_categories - 1] and # that nans are mapped to the last bin X = np.array( [[4] * 500 + [1] * 3 + [10] * 4 + [0] * 4 + [13] + [7] * 5 + [np.nan] * 2], dtype=X_DTYPE, ).T known_categories = [np.unique(X[~np.isnan(X)])] bin_mapper = _BinMapper( n_bins=n_bins, is_categorical=np.array([True]), known_categories=known_categories, ).fit(X) assert bin_mapper.n_bins_non_missing_ == [6] assert_array_equal(bin_mapper.bin_thresholds_[0], [0, 1, 4, 7, 10, 13]) X = np.array([[0, 1, 4, np.nan, 7, 10, 13]], dtype=X_DTYPE).T expected_trans = np.array([[0, 1, 2, n_bins - 1, 3, 4, 5]]).T assert_array_equal(bin_mapper.transform(X), expected_trans) # For unknown categories, the mapping is incorrect / undefined. This never # happens in practice. This check is only for illustration purpose. X = np.array([[-1, 100]], dtype=X_DTYPE).T expected_trans = np.array([[0, 6]]).T assert_array_equal(bin_mapper.transform(X), expected_trans) @pytest.mark.parametrize("n_bins", (128, 256)) def test_categorical_with_numerical_features(n_bins): # basic check for binmapper with mixed data X1 = np.arange(10, 20).reshape(-1, 1) # numerical X2 = np.arange(10, 15).reshape(-1, 1) # categorical X2 = np.r_[X2, X2] X = np.c_[X1, X2] known_categories = [None, np.unique(X2).astype(X_DTYPE)] bin_mapper = _BinMapper( n_bins=n_bins, is_categorical=np.array([False, True]), known_categories=known_categories, ).fit(X) assert_array_equal(bin_mapper.n_bins_non_missing_, [10, 5]) bin_thresholds = bin_mapper.bin_thresholds_ assert len(bin_thresholds) == 2 assert_array_equal(bin_thresholds[1], np.arange(10, 15)) expected_X_trans = [ [0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 0], [6, 1], [7, 2], [8, 3], [9, 4], ] assert_array_equal(bin_mapper.transform(X), expected_X_trans) def test_make_known_categories_bitsets(): # Check the output of make_known_categories_bitsets X = np.array( [[14, 2, 30], [30, 4, 70], [40, 10, 180], [40, 240, 180]], dtype=X_DTYPE ) bin_mapper = _BinMapper( n_bins=256, is_categorical=np.array([False, True, True]), known_categories=[None, X[:, 1], X[:, 2]], ) bin_mapper.fit(X) known_cat_bitsets, f_idx_map = bin_mapper.make_known_categories_bitsets() # Note that for non-categorical features, values are left to 0 expected_f_idx_map = np.array([0, 0, 1], dtype=np.uint8) assert_allclose(expected_f_idx_map, f_idx_map) expected_cat_bitset = np.zeros((2, 8), dtype=np.uint32) # first categorical feature: [2, 4, 10, 240] f_idx = 1 mapped_f_idx = f_idx_map[f_idx] expected_cat_bitset[mapped_f_idx, 0] = 2 ** 2 + 2 ** 4 + 2 ** 10 # 240 = 32**7 + 16, therefore the 16th bit of the 7th array is 1. expected_cat_bitset[mapped_f_idx, 7] = 2 ** 16 # second categorical feature [30, 70, 180] f_idx = 2 mapped_f_idx = f_idx_map[f_idx] expected_cat_bitset[mapped_f_idx, 0] = 2 ** 30 expected_cat_bitset[mapped_f_idx, 2] = 2 ** 6 expected_cat_bitset[mapped_f_idx, 5] = 2 ** 20 assert_allclose(expected_cat_bitset, known_cat_bitsets) @pytest.mark.parametrize( "is_categorical, known_categories, match", [ (np.array([True]), [None], "Known categories for feature 0 must be provided"), ( np.array([False]), np.array([1, 2, 3]), "isn't marked as a categorical feature, but categories were passed", ), ], ) def test_categorical_parameters(is_categorical, known_categories, match): # test the validation of the is_categorical and known_categories parameters X = np.array([[1, 2, 3]], dtype=X_DTYPE) bin_mapper = _BinMapper( is_categorical=is_categorical, known_categories=known_categories ) with pytest.raises(ValueError, match=match): bin_mapper.fit(X)
{ "content_hash": "ef6ac476738017467bbff731d38b47ca", "timestamp": "", "source": "github", "line_count": 461, "max_line_length": 86, "avg_line_length": 33.24945770065076, "alnum_prop": 0.6143658663883089, "repo_name": "huzq/scikit-learn", "id": "7cbc6603ee01f37702ea139bc3ca3dbc401d0f10", "size": "15328", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "sklearn/ensemble/_hist_gradient_boosting/tests/test_binning.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3366" }, { "name": "C", "bytes": "394787" }, { "name": "C++", "bytes": "140225" }, { "name": "Makefile", "bytes": "1579" }, { "name": "PowerShell", "bytes": "17042" }, { "name": "Python", "bytes": "6394128" }, { "name": "Shell", "bytes": "9250" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using ServiceStack.Logging; using ServiceStack.ServiceHost; using ServiceStack.WebHost.Endpoints.Utils; namespace ServiceStack.WebHost.Endpoints.Metadata { public class XsdGenerator { private readonly ILog log = LogManager.GetLogger(typeof(XsdGenerator)); public bool OptimizeForFlash { get; set; } public ICollection<Type> OperationTypes { get; set; } public bool IncludeAllTypesInAssembly { get; set; } private string Filter(string xsd) { return !this.OptimizeForFlash ? xsd : xsd.Replace("ser:guid", "xs:string"); } public override string ToString() { if (OperationTypes == null || OperationTypes.Count == 0) return null; if (IncludeAllTypesInAssembly) { var uniqueTypes = new List<Type>(); var uniqueTypeNames = new List<string>(); foreach (var type in OperationTypes) { foreach (var assemblyType in type.Assembly.GetTypes()) { if (assemblyType.GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0) { var baseTypeWithSameName = ServiceOperations.GetBaseTypeWithTheSameName(assemblyType); if (uniqueTypeNames.Contains(baseTypeWithSameName.Name)) { log.WarnFormat("Skipping duplicate type with existing name '{0}'", baseTypeWithSameName.Name); } uniqueTypes.Add(baseTypeWithSameName); } } } this.OperationTypes = uniqueTypes; } var schemaSet = XsdUtils.GetXmlSchemaSet(OperationTypes); var xsd = XsdUtils.GetXsd(schemaSet); var filteredXsd = Filter(xsd); return filteredXsd; } } }
{ "content_hash": "c640e164fc2e3ad9e560469d022f9f6d", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 102, "avg_line_length": 30.163636363636364, "alnum_prop": 0.7166968053044003, "repo_name": "firstsee/ServiceStack", "id": "468e50e893186c79e35a9a861f8d3d722161b7e6", "size": "1659", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ServiceStack.WebHost.Endpoints/Metadata/XsdGenerator.cs", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using System.Collections.Generic; using Nancy.Bootstrapper; using StructureMap; namespace Nancy.Bootstrappers.StructureMap { using System; using Nancy.ViewEngines; public abstract class StructureMapNancyBootstrapper : NancyBootstrapperBase<IContainer>, INancyBootstrapperPerRequestRegistration<IContainer>, INancyModuleCatalog { /// <summary> /// Container instance /// </summary> protected IContainer _Container; /// <summary> /// Resolve INancyEngine /// </summary> /// <returns>INancyEngine implementation</returns> protected sealed override INancyEngine GetEngineInternal() { return _Container.GetInstance<INancyEngine>(); } /// <summary> /// Get the moduleKey generator /// </summary> /// <returns>IModuleKeyGenerator instance</returns> protected sealed override IModuleKeyGenerator GetModuleKeyGenerator() { return _Container.GetInstance<IModuleKeyGenerator>(); } /// <summary> /// Configures the container with defaults for application scope /// </summary> /// <param name="existingContainer"></param> protected override void ConfigureApplicationContainer(IContainer existingContainer) { base.ConfigureApplicationContainer(existingContainer); } protected override void RegisterViewSourceProviders(IContainer container, IEnumerable<Type> viewSourceProviderTypes) { _Container.Configure(registry => { foreach (var viewSourceProvider in viewSourceProviderTypes) { registry.For(typeof(IViewSourceProvider)).LifecycleIs(InstanceScope.Singleton).Use(viewSourceProvider); } }); } protected override void RegisterViewEngines(IContainer container, IEnumerable<Type> viewEngineTypes) { _Container.Configure(registry => { foreach (var viewEngineType in viewEngineTypes) { registry.For(typeof(IViewEngine)).LifecycleIs(InstanceScope.Singleton).Use(viewEngineType); } }); } public virtual void ConfigureRequestContainer(IContainer container) { } /// <summary> /// Creates a new container instance /// </summary> /// <returns>A new StructureMap container</returns> protected sealed override IContainer CreateContainer() { _Container = new Container(); return _Container; } /// <summary> /// Registers all modules in the container as multi-instance /// </summary> /// <param name="moduleRegistrations">NancyModule registration types</param> protected sealed override void RegisterModules(IEnumerable<ModuleRegistration> moduleRegistrations) { _Container.Configure(registry => { foreach (var registrationType in moduleRegistrations) { registry.For(typeof(NancyModule)) .LifecycleIs(InstanceScope.PerRequest) .Use(registrationType.ModuleType) .Named(registrationType.ModuleKey); } }); } /// <summary> /// Register the default implementations of internally used types into the container as singletons /// </summary> protected sealed override void RegisterDefaults(IContainer container, IEnumerable<TypeRegistration> typeRegistrations) { _Container.Configure(registry => { registry.For<INancyModuleCatalog>().Singleton().Use(this); foreach (var typeRegistration in typeRegistrations) { registry.For(typeRegistration.RegistrationType) .Singleton() .Use(typeRegistration.ImplementationType); } }); } /// <summary> /// Get all NancyModule implementation instances /// </summary> /// <returns>IEnumerable of NancyModule</returns> public IEnumerable<NancyModule> GetAllModules(NancyContext context) { var childContainer = _Container.GetNestedContainer(); ConfigureRequestContainer(childContainer); return childContainer.GetAllInstances<NancyModule>(); } /// <summary> /// Gets a specific, per-request, module instance by the modulekey /// </summary> /// <param name="moduleKey">ModuleKey</param> /// <returns>NancyModule instance</returns> public NancyModule GetModuleByKey(string moduleKey, NancyContext context) { // TODO - add child container to context so it's disposed? var childContainer = _Container.GetNestedContainer(); ConfigureRequestContainer(childContainer); return childContainer.TryGetInstance<NancyModule>(moduleKey); } } }
{ "content_hash": "eec5b4ac4c4e8691025d485d30adb5a7", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 166, "avg_line_length": 37.66197183098591, "alnum_prop": 0.5845175766641735, "repo_name": "ToJans/Nancy", "id": "5b42afce8f4b12acc19a4d2980405102498ca51f", "size": "5350", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Nancy.BootStrappers.StructureMap/StructureMapNancyBootStrapper.cs", "mode": "33261", "license": "mit", "language": [ { "name": "C#", "bytes": "895000" }, { "name": "JavaScript", "bytes": "44" }, { "name": "Ruby", "bytes": "2957" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using CsvHelper; using NUnit.Framework; namespace AtataSamples.CsvDataSource { public static class CsvSource { public static TestCaseData[] Get<T>(string filePath, Type expectedResultType = null, string expectedResultName = "ExpectedResult") { string completeFilePath = Path.IsPathRooted(filePath) ? filePath : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath); using var streamReader = new StreamReader(completeFilePath); using var csvReader = new CsvReader(streamReader, Thread.CurrentThread.CurrentCulture); TestCaseData[] dataItems = csvReader.GetRecords<T>() .Select(x => new TestCaseData(x)) .ToArray(); if (expectedResultType != null) { // Reset stream reader to beginning. streamReader.BaseStream.Position = 0; // Read the header line. csvReader.Read(); object[] expectedResults = GetExpectedResults(csvReader, expectedResultType, expectedResultName).ToArray(); for (int i = 0; i < dataItems.Length; i++) { dataItems[i].Returns(expectedResults[i]); } } return dataItems; } private static IEnumerable<object> GetExpectedResults(CsvReader csvReader, Type expectedResultType, string expectedResultName) { while (csvReader.Read()) { yield return csvReader.GetField(expectedResultType, expectedResultName); } } } }
{ "content_hash": "a2ed4021a6dc3a22463880c1197a5a6c", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 138, "avg_line_length": 33.98076923076923, "alnum_prop": 0.601018675721562, "repo_name": "atata-framework/atata-samples", "id": "3eb5d1f891ccd86148a9cb790ae8b4a016a05207", "size": "1769", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CsvDataSource/AtataSamples.CsvDataSource/CsvSource.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "133845" }, { "name": "Gherkin", "bytes": "1182" }, { "name": "PowerShell", "bytes": "255" } ], "symlink_target": "" }
/*************************************************************************************** * Modified part of the code (4D texture mechanism) from Eric Bruneton is used in the * following code. ****************************************************************************************/ /** * Precomputed Atmospheric Scattering * Copyright (c) 2008 INRIA * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <modules/atmosphere/rendering/atmospheredeferredcaster.h> #include <openspace/engine/globals.h> #include <openspace/query/query.h> #include <openspace/rendering/renderengine.h> #include <openspace/scene/scene.h> #include <openspace/util/spicemanager.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ghoul/opengl/openglstatecache.h> #include <cmath> #include <fstream> namespace { constexpr std::string_view _loggerCat = "AtmosphereDeferredcaster"; constexpr std::array<const char*, 27> UniformNames = { "cullAtmosphere", "Rg", "Rt", "groundRadianceEmission", "HR", "betaRayleigh", "HM", "betaMieExtinction", "mieG", "sunRadiance", "ozoneLayerEnabled", "HO", "betaOzoneExtinction", "SAMPLES_R", "SAMPLES_MU", "SAMPLES_MU_S", "SAMPLES_NU", "inverseModelTransformMatrix", "modelTransformMatrix", "projectionToModelTransformMatrix", "viewToWorldMatrix", "camPosObj", "sunDirectionObj", "hardShadows", "transmittanceTexture", "irradianceTexture", "inscatterTexture" }; constexpr float ATM_EPS = 2000.f; constexpr float KM_TO_M = 1000.f; template <GLenum colorBufferAttachment = GL_COLOR_ATTACHMENT0> void saveTextureFile(const std::filesystem::path& fileName, const glm::ivec2& size) { std::ofstream ppmFile(fileName); if (!ppmFile.is_open()) { return; } std::vector<unsigned char> px( size.x * size.y * 3, static_cast<unsigned char>(255) ); glReadBuffer(colorBufferAttachment); glReadPixels(0, 0, size.x, size.y, GL_RGB, GL_UNSIGNED_BYTE, px.data()); ppmFile << "P3" << '\n' << size.x << " " << size.y << '\n' << "255" << '\n'; int k = 0; for (int i = 0; i < size.x; i++) { for (int j = 0; j < size.y; j++) { ppmFile << static_cast<unsigned int>(px[k]) << ' ' << static_cast<unsigned int>(px[k + 1]) << ' ' << static_cast<unsigned int>(px[k + 2]) << ' '; k += 3; } ppmFile << '\n'; } } bool isAtmosphereInFrustum(const glm::dmat4& MVMatrix, const glm::dvec3& position, double radius) { // Frustum Planes glm::dvec3 col1 = glm::dvec3(MVMatrix[0][0], MVMatrix[1][0], MVMatrix[2][0]); glm::dvec3 col2 = glm::dvec3(MVMatrix[0][1], MVMatrix[1][1], MVMatrix[2][1]); glm::dvec3 col3 = glm::dvec3(MVMatrix[0][2], MVMatrix[1][2], MVMatrix[2][2]); glm::dvec3 col4 = glm::dvec3(MVMatrix[0][3], MVMatrix[1][3], MVMatrix[2][3]); glm::dvec3 leftNormal = col4 + col1; glm::dvec3 rightNormal = col4 - col1; glm::dvec3 bottomNormal = col4 + col2; glm::dvec3 topNormal = col4 - col2; glm::dvec3 nearNormal = col3 + col4; glm::dvec3 farNormal = col4 - col3; // Plane Distances double leftDistance = MVMatrix[3][3] + MVMatrix[3][0]; double rightDistance = MVMatrix[3][3] - MVMatrix[3][0]; double bottomDistance = MVMatrix[3][3] + MVMatrix[3][1]; double topDistance = MVMatrix[3][3] - MVMatrix[3][1]; double nearDistance = MVMatrix[3][3] + MVMatrix[3][2]; // Normalize Planes const double invLeftMag = 1.0 / glm::length(leftNormal); leftNormal *= invLeftMag; leftDistance *= invLeftMag; const double invRightMag = 1.0 / glm::length(rightNormal); rightNormal *= invRightMag; rightDistance *= invRightMag; const double invBottomMag = 1.0 / glm::length(bottomNormal); bottomNormal *= invBottomMag; bottomDistance *= invBottomMag; const double invTopMag = 1.0 / glm::length(topNormal); topNormal *= invTopMag; topDistance *= invTopMag; const double invNearMag = 1.0 / glm::length(nearNormal); nearNormal *= invNearMag; nearDistance *= invNearMag; const double invFarMag = 1.0 / glm::length(farNormal); farNormal *= invFarMag; if (((glm::dot(leftNormal, position) + leftDistance) < -radius) || ((glm::dot(rightNormal, position) + rightDistance) < -radius) || ((glm::dot(bottomNormal, position) + bottomDistance) < -radius) || ((glm::dot(topNormal, position) + topDistance) < -radius) || ((glm::dot(nearNormal, position) + nearDistance) < -radius)) // The far plane testing is disabled because the atm has no depth. { return false; } return true; } GLuint createTexture(const glm::ivec2& size, std::string_view name) { GLuint t; glGenTextures(1, &t); glBindTexture(GL_TEXTURE_2D, t); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB32F, size.x, size.y, 0, GL_RGB, GL_FLOAT, nullptr ); if (glbinding::Binding::ObjectLabel.isResolved()) { glObjectLabel(GL_TEXTURE, t, static_cast<GLsizei>(name.size()), name.data()); } return t; } GLuint createTexture(const glm::ivec3& size, std::string_view name, int components) { ghoul_assert(components == 3 || components == 4, "Only 3-4 components supported"); GLuint t; glGenTextures(1, &t); glBindTexture(GL_TEXTURE_3D, t); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); // Stopped using a buffer object for GL_PIXEL_UNPACK_BUFFER glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); glTexImage3D( GL_TEXTURE_3D, 0, (components == 3) ? GL_RGB32F : GL_RGBA32F, size.x, size.y, size.z, 0, GL_RGB, GL_FLOAT, nullptr ); if (glbinding::Binding::ObjectLabel.isResolved()) { glObjectLabel(GL_TEXTURE, t, static_cast<GLsizei>(name.size()), name.data()); } return t; } } // namespace namespace openspace { AtmosphereDeferredcaster::AtmosphereDeferredcaster(float textureScale, std::vector<ShadowConfiguration> shadowConfigArray, bool saveCalculatedTextures) : _transmittanceTableSize(glm::ivec2(256 * textureScale, 64 * textureScale)) , _irradianceTableSize(glm::ivec2(64 * textureScale, 16 * textureScale)) , _deltaETableSize(glm::ivec2(64 * textureScale, 16 * textureScale)) , _muSSamples(static_cast<int>(32 * textureScale)) , _nuSamples(static_cast<int>(8 * textureScale)) , _muSamples(static_cast<int>(128 * textureScale)) , _rSamples(static_cast<int>(32 * textureScale)) , _textureSize(_muSSamples * _nuSamples, _muSamples, _rSamples) , _shadowConfArray(std::move(shadowConfigArray)) , _saveCalculationTextures(saveCalculatedTextures) { std::memset(_uniformNameBuffer, '\0', sizeof(_uniformNameBuffer)); std::strcpy(_uniformNameBuffer, "shadowDataArray["); _shadowDataArrayCache.reserve(_shadowConfArray.size()); } void AtmosphereDeferredcaster::initialize() { ZoneScoped _transmittanceTableTexture = createTexture(_transmittanceTableSize, "Transmittance"); _irradianceTableTexture = createTexture(_irradianceTableSize, "Irradiance"); _inScatteringTableTexture = createTexture(_textureSize, "InScattering", 4); calculateAtmosphereParameters(); } void AtmosphereDeferredcaster::deinitialize() { ZoneScoped glDeleteTextures(1, &_transmittanceTableTexture); glDeleteTextures(1, &_irradianceTableTexture); glDeleteTextures(1, &_inScatteringTableTexture); } void AtmosphereDeferredcaster::update(const UpdateData&) {} void AtmosphereDeferredcaster::preRaycast(const RenderData& data, const DeferredcastData&, ghoul::opengl::ProgramObject& prg) { ZoneScoped // Atmosphere Frustum Culling glm::dvec3 tPlanetPos = glm::dvec3(_modelTransform * glm::dvec4(0.0, 0.0, 0.0, 1.0)); const double distance = glm::distance(tPlanetPos, data.camera.eyePositionVec3()); // Radius is in KM const double scaledRadius = glm::length( glm::dmat3(_modelTransform) * glm::dvec3(KM_TO_M * _atmosphereRadius, 0.0, 0.0) ); // Number of planet radii to use as distance threshold for culling prg.setUniform(_uniformCache.cullAtmosphere, 1); constexpr double DistanceCullingRadii = 5000; glm::dmat4 MV = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * data.camera.combinedViewMatrix(); if (distance <= scaledRadius * DistanceCullingRadii && isAtmosphereInFrustum(MV, tPlanetPos, scaledRadius + ATM_EPS)) { prg.setUniform(_uniformCache.cullAtmosphere, 0); prg.setUniform(_uniformCache.Rg, _atmospherePlanetRadius); prg.setUniform(_uniformCache.Rt, _atmosphereRadius); prg.setUniform(_uniformCache.groundRadianceEmission, _groundRadianceEmission); prg.setUniform(_uniformCache.HR, _rayleighHeightScale); prg.setUniform(_uniformCache.betaRayleigh, _rayleighScatteringCoeff); prg.setUniform(_uniformCache.HM, _mieHeightScale); prg.setUniform(_uniformCache.betaMieExtinction, _mieExtinctionCoeff); prg.setUniform(_uniformCache.mieG, _miePhaseConstant); prg.setUniform(_uniformCache.sunRadiance, _sunRadianceIntensity); prg.setUniform(_uniformCache.ozoneLayerEnabled, _ozoneEnabled); prg.setUniform(_uniformCache.HO, _ozoneHeightScale); prg.setUniform(_uniformCache.betaOzoneExtinction, _ozoneExtinctionCoeff); prg.setUniform(_uniformCache.SAMPLES_R, _rSamples); prg.setUniform(_uniformCache.SAMPLES_MU, _muSamples); prg.setUniform(_uniformCache.SAMPLES_MU_S, _muSSamples); prg.setUniform(_uniformCache.SAMPLES_NU, _nuSamples); // Object Space glm::dmat4 invModelMatrix = glm::inverse(_modelTransform); prg.setUniform(_uniformCache.inverseModelTransformMatrix, invModelMatrix); prg.setUniform(_uniformCache.modelTransformMatrix, _modelTransform); glm::dmat4 viewToWorldMatrix = glm::inverse(data.camera.combinedViewMatrix()); // Eye Space to World Space prg.setUniform(_uniformCache.viewToWorldMatrix, viewToWorldMatrix); // Projection to Eye Space glm::dmat4 dInvProj = glm::inverse(glm::dmat4(data.camera.projectionMatrix())); glm::dmat4 invWholePipeline = invModelMatrix * viewToWorldMatrix * dInvProj; prg.setUniform(_uniformCache.projectionToModelTransform, invWholePipeline); glm::dvec4 camPosObjCoords = invModelMatrix * glm::dvec4(data.camera.eyePositionVec3(), 1.0); prg.setUniform(_uniformCache.camPosObj, glm::dvec3(camPosObjCoords)); SceneGraphNode* node = sceneGraph()->sceneGraphNode("Sun"); glm::dvec3 sunPosWorld = node ? node->worldPosition() : glm::dvec3(0.0); glm::dvec3 sunPosObj; // Sun following camera position if (_sunFollowingCameraEnabled) { sunPosObj = invModelMatrix * glm::dvec4(data.camera.eyePositionVec3(), 1.0); } else { sunPosObj = invModelMatrix * glm::dvec4((sunPosWorld - data.modelTransform.translation) * 1000.0, 1.0); } // Sun Position in Object Space prg.setUniform(_uniformCache.sunDirectionObj, glm::normalize(sunPosObj)); // Shadow calculations.. _shadowDataArrayCache.clear(); for (ShadowConfiguration& shadowConf : _shadowConfArray) { // TO REMEMBER: all distances and lengths in world coordinates are in // meters!!! We need to move this to view space... double lt; glm::dvec3 sourcePos = SpiceManager::ref().targetPosition( shadowConf.source.first, "SSB", "GALACTIC", {}, data.time.j2000Seconds(), lt ); sourcePos *= KM_TO_M; // converting to meters glm::dvec3 casterPos = SpiceManager::ref().targetPosition( shadowConf.caster.first, "SSB", "GALACTIC", {}, data.time.j2000Seconds(), lt ); casterPos *= KM_TO_M; // converting to meters SceneGraphNode* sourceNode = sceneGraphNode(shadowConf.source.first); if (!sourceNode) { if (!shadowConf.printedSourceError) { LERROR("Invalid scenegraph node for the shadow's receiver"); shadowConf.printedSourceError = true; } return; } SceneGraphNode* casterNode = sceneGraphNode(shadowConf.caster.first); if (!casterNode) { if (!shadowConf.printedCasterError) { LERROR("Invalid scenegraph node for the shadow's caster"); shadowConf.printedCasterError = true; } return; } const double sourceScale = std::max(glm::compMax(sourceNode->scale()), 1.0); const double casterScale = std::max(glm::compMax(casterNode->scale()), 1.0); // First we determine if the caster is shadowing the current planet // (all calculations in World Coordinates): glm::dvec3 planetCasterVec = casterPos - data.modelTransform.translation; glm::dvec3 sourceCasterVec = casterPos - sourcePos; double scLength = glm::length(sourceCasterVec); glm::dvec3 planetCasterProj = (glm::dot(planetCasterVec, sourceCasterVec) / (scLength * scLength)) * sourceCasterVec; double dTest = glm::length(planetCasterVec - planetCasterProj); double xpTest = shadowConf.caster.second * casterScale * scLength / (shadowConf.source.second * sourceScale + shadowConf.caster.second * casterScale); double rpTest = shadowConf.caster.second * casterScale * (glm::length(planetCasterProj) + xpTest) / xpTest; double casterDistSun = glm::length(casterPos - sunPosWorld); double planetDistSun = glm::length( data.modelTransform.translation - sunPosWorld ); ShadowRenderingStruct shadow; shadow.isShadowing = false; if (((dTest - rpTest) < (_atmospherePlanetRadius * KM_TO_M)) && (casterDistSun < planetDistSun)) { // The current caster is shadowing the current planet shadow.isShadowing = true; shadow.rs = shadowConf.source.second * sourceScale; shadow.rc = shadowConf.caster.second * casterScale; shadow.sourceCasterVec = glm::normalize(sourceCasterVec); shadow.xp = xpTest; shadow.xu = shadow.rc * scLength / (shadow.rs - shadow.rc); shadow.casterPositionVec = casterPos; } _shadowDataArrayCache.push_back(shadow); } // _uniformNameBuffer[0..15] = "shadowDataArray[" unsigned int counter = 0; for (const ShadowRenderingStruct& sd : _shadowDataArrayCache) { // Add the counter char* bf = fmt::format_to(_uniformNameBuffer + 16, "{}", counter); std::strcpy(bf, "].isShadowing\0"); prg.setUniform(_uniformNameBuffer, sd.isShadowing); if (sd.isShadowing) { std::strcpy(bf, "].xp\0"); prg.setUniform(_uniformNameBuffer, sd.xp); std::strcpy(bf, "].xu\0"); prg.setUniform(_uniformNameBuffer, sd.xu); std::strcpy(bf, "].rc\0"); prg.setUniform(_uniformNameBuffer, sd.rc); std::strcpy(bf, "].sourceCasterVec\0"); prg.setUniform(_uniformNameBuffer, sd.sourceCasterVec); std::strcpy(bf, "].casterPositionVec\0"); prg.setUniform(_uniformNameBuffer, sd.casterPositionVec); } counter++; } prg.setUniform(_uniformCache.hardShadows, _hardShadowsEnabled); } _transmittanceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); prg.setUniform(_uniformCache.transmittanceTexture, _transmittanceTableTextureUnit); _irradianceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _irradianceTableTexture); prg.setUniform(_uniformCache.irradianceTexture, _irradianceTableTextureUnit); _inScatteringTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); prg.setUniform(_uniformCache.inscatterTexture, _inScatteringTableTextureUnit); } void AtmosphereDeferredcaster::postRaycast(const RenderData&, const DeferredcastData&, ghoul::opengl::ProgramObject&) { ZoneScoped // Deactivate the texture units _transmittanceTableTextureUnit.deactivate(); _irradianceTableTextureUnit.deactivate(); _inScatteringTableTextureUnit.deactivate(); } std::filesystem::path AtmosphereDeferredcaster::deferredcastFSPath() const { return absPath("${MODULE_ATMOSPHERE}/shaders/atmosphere_deferred_fs.glsl"); } std::filesystem::path AtmosphereDeferredcaster::deferredcastVSPath() const { return absPath("${MODULE_ATMOSPHERE}/shaders/atmosphere_deferred_vs.glsl"); } std::filesystem::path AtmosphereDeferredcaster::helperPath() const { return ""; // no helper file } void AtmosphereDeferredcaster::initializeCachedVariables( ghoul::opengl::ProgramObject& program) { ghoul::opengl::updateUniformLocations(program, _uniformCache, UniformNames); } void AtmosphereDeferredcaster::setModelTransform(glm::dmat4 transform) { _modelTransform = std::move(transform); } void AtmosphereDeferredcaster::setParameters(float atmosphereRadius, float planetRadius, float averageGroundReflectance, float groundRadianceEmission, float rayleighHeightScale, bool enableOzone, float ozoneHeightScale, float mieHeightScale, float miePhaseConstant, float sunRadiance, glm::vec3 rayScatteringCoefficients, glm::vec3 ozoneExtinctionCoefficients, glm::vec3 mieScatteringCoefficients, glm::vec3 mieExtinctionCoefficients, bool sunFollowing) { _atmosphereRadius = atmosphereRadius; _atmospherePlanetRadius = planetRadius; _averageGroundReflectance = averageGroundReflectance; _groundRadianceEmission = groundRadianceEmission; _rayleighHeightScale = rayleighHeightScale; _ozoneEnabled = enableOzone; _ozoneHeightScale = ozoneHeightScale; _mieHeightScale = mieHeightScale; _miePhaseConstant = miePhaseConstant; _sunRadianceIntensity = sunRadiance; _rayleighScatteringCoeff = std::move(rayScatteringCoefficients); _ozoneExtinctionCoeff = std::move(ozoneExtinctionCoefficients); _mieScatteringCoeff = std::move(mieScatteringCoefficients); _mieExtinctionCoeff = std::move(mieExtinctionCoefficients); _sunFollowingCameraEnabled = sunFollowing; } void AtmosphereDeferredcaster::setHardShadows(bool enabled) { _hardShadowsEnabled = enabled; } void AtmosphereDeferredcaster::calculateTransmittance() { ZoneScoped glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _transmittanceTableTexture, 0 ); glViewport(0, 0, _transmittanceTableSize.x, _transmittanceTableSize.y); using ProgramObject = ghoul::opengl::ProgramObject; std::unique_ptr<ProgramObject> program = ProgramObject::Build( "Transmittance Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/transmittance_calc_fs.glsl") ); program->activate(); program->setUniform("Rg", _atmospherePlanetRadius); program->setUniform("Rt", _atmosphereRadius); program->setUniform("HR", _rayleighHeightScale); program->setUniform("betaRayleigh", _rayleighScatteringCoeff); program->setUniform("HM", _mieHeightScale); program->setUniform("betaMieExtinction", _mieExtinctionCoeff); program->setUniform("TRANSMITTANCE", _transmittanceTableSize); program->setUniform("ozoneLayerEnabled", _ozoneEnabled); program->setUniform("HO", _ozoneHeightScale); program->setUniform("betaOzoneExtinction", _ozoneExtinctionCoeff); constexpr float Black[] = { 0.f, 0.f, 0.f, 0.f }; glClearBufferfv(GL_COLOR, 0, Black); glDrawArrays(GL_TRIANGLES, 0, 6); if (_saveCalculationTextures) { saveTextureFile("transmittance_texture.ppm", _transmittanceTableSize); } program->deactivate(); } GLuint AtmosphereDeferredcaster::calculateDeltaE() { ZoneScoped GLuint deltaE = createTexture(_deltaETableSize, "DeltaE"); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, deltaE, 0); glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); using ProgramObject = ghoul::opengl::ProgramObject; std::unique_ptr<ProgramObject> program = ProgramObject::Build( "Irradiance Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_calc_fs.glsl") ); program->activate(); ghoul::opengl::TextureUnit unit; unit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); program->setUniform("transmittanceTexture", unit); program->setUniform("Rg", _atmospherePlanetRadius); program->setUniform("Rt", _atmosphereRadius); program->setUniform("OTHER_TEXTURES", _deltaETableSize); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 6); if (_saveCalculationTextures) { saveTextureFile("deltaE_table_texture.ppm", _deltaETableSize); } program->deactivate(); return deltaE; } std::pair<GLuint, GLuint> AtmosphereDeferredcaster::calculateDeltaS() { ZoneScoped GLuint deltaSRayleigh = createTexture(_textureSize, "DeltaS Rayleigh", 3); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, deltaSRayleigh, 0); GLuint deltaSMie = createTexture(_textureSize, "DeltaS Mie", 3); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, deltaSMie, 0); GLenum colorBuffers[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glDrawBuffers(2, colorBuffers); glViewport(0, 0, _textureSize.x, _textureSize.y); using ProgramObject = ghoul::opengl::ProgramObject; std::unique_ptr<ProgramObject> program = ProgramObject::Build( "InScattering Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_calc_fs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") ); program->activate(); ghoul::opengl::TextureUnit unit; unit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); program->setUniform("transmittanceTexture", unit); program->setUniform("Rg", _atmospherePlanetRadius); program->setUniform("Rt", _atmosphereRadius); program->setUniform("HR", _rayleighHeightScale); program->setUniform("betaRayleigh", _rayleighScatteringCoeff); program->setUniform("HM", _mieHeightScale); program->setUniform("betaMieScattering", _mieScatteringCoeff); program->setUniform("SAMPLES_MU_S", _muSSamples); program->setUniform("SAMPLES_NU", _nuSamples); program->setUniform("SAMPLES_MU", _muSamples); program->setUniform("ozoneLayerEnabled", _ozoneEnabled); program->setUniform("HO", _ozoneHeightScale); glClear(GL_COLOR_BUFFER_BIT); for (int layer = 0; layer < _rSamples; ++layer) { program->setUniform("layer", layer); step3DTexture(*program, layer); glDrawArrays(GL_TRIANGLES, 0, 6); } if (_saveCalculationTextures) { saveTextureFile("deltaS_rayleigh_texture.ppm", glm::ivec2(_textureSize)); saveTextureFile<GL_COLOR_ATTACHMENT1>( "deltaS_mie_texture.ppm", glm::ivec2(_textureSize) ); } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0); GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, drawBuffers); program->deactivate(); return { deltaSRayleigh, deltaSMie }; } void AtmosphereDeferredcaster::calculateIrradiance() { ZoneScoped glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _irradianceTableTexture, 0 ); glDrawBuffer(GL_COLOR_ATTACHMENT0); glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); using ProgramObject = ghoul::opengl::ProgramObject; std::unique_ptr<ProgramObject> program = ProgramObject::Build( "DeltaE Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/deltaE_calc_fs.glsl") ); program->activate(); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLES, 0, 6); if (_saveCalculationTextures) { saveTextureFile("irradiance_texture.ppm", _deltaETableSize); } program->deactivate(); } void AtmosphereDeferredcaster::calculateInscattering(GLuint deltaSRayleigh, GLuint deltaSMie) { ZoneScoped glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _inScatteringTableTexture, 0 ); glViewport(0, 0, _textureSize.x, _textureSize.y); using ProgramObject = ghoul::opengl::ProgramObject; std::unique_ptr<ProgramObject> program = ProgramObject::Build( "deltaSCalcProgram", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_calc_fs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") ); program->activate(); ghoul::opengl::TextureUnit deltaSRayleighUnit; deltaSRayleighUnit.activate(); glBindTexture(GL_TEXTURE_3D, deltaSRayleigh); program->setUniform("deltaSRTexture", deltaSRayleighUnit); ghoul::opengl::TextureUnit deltaSMieUnit; deltaSMieUnit.activate(); glBindTexture(GL_TEXTURE_3D, deltaSMie); program->setUniform("deltaSMTexture", deltaSMieUnit); program->setUniform("SAMPLES_MU_S", _muSSamples); program->setUniform("SAMPLES_NU", _nuSamples); program->setUniform("SAMPLES_MU", _muSamples); program->setUniform("SAMPLES_R", _rSamples); glClear(GL_COLOR_BUFFER_BIT); for (int layer = 0; layer < _rSamples; ++layer) { program->setUniform("layer", layer); glDrawArrays(GL_TRIANGLES, 0, 6); } if (_saveCalculationTextures) { saveTextureFile("S_texture.ppm", glm::ivec2(_textureSize)); } program->deactivate(); } void AtmosphereDeferredcaster::calculateDeltaJ(int scatteringOrder, ghoul::opengl::ProgramObject& program, GLuint deltaJ, GLuint deltaE, GLuint deltaSRayleigh, GLuint deltaSMie) { ZoneScoped glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, deltaJ, 0); glViewport(0, 0, _textureSize.x, _textureSize.y); program.activate(); ghoul::opengl::TextureUnit transmittanceUnit; transmittanceUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); program.setUniform("transmittanceTexture", transmittanceUnit); ghoul::opengl::TextureUnit deltaEUnit; deltaEUnit.activate(); glBindTexture(GL_TEXTURE_2D, deltaE); program.setUniform("deltaETexture", deltaEUnit); ghoul::opengl::TextureUnit deltaSRayleighUnit; deltaSRayleighUnit.activate(); glBindTexture(GL_TEXTURE_3D, deltaSRayleigh); program.setUniform("deltaSRTexture", deltaSRayleighUnit); ghoul::opengl::TextureUnit deltaSMieUnit; deltaSMieUnit.activate(); glBindTexture(GL_TEXTURE_3D, deltaSMie); program.setUniform("deltaSMTexture", deltaSMieUnit); program.setUniform("firstIteration", (scatteringOrder == 2) ? 1 : 0); program.setUniform("Rg", _atmospherePlanetRadius); program.setUniform("Rt", _atmosphereRadius); program.setUniform("AverageGroundReflectance", _averageGroundReflectance); program.setUniform("HR", _rayleighHeightScale); program.setUniform("betaRayleigh", _rayleighScatteringCoeff); program.setUniform("HM", _mieHeightScale); program.setUniform("betaMieScattering", _mieScatteringCoeff); program.setUniform("mieG", _miePhaseConstant); program.setUniform("SAMPLES_MU_S", _muSSamples); program.setUniform("SAMPLES_NU", _nuSamples); program.setUniform("SAMPLES_MU", _muSamples); program.setUniform("SAMPLES_R", _rSamples); for (int layer = 0; layer < _rSamples; ++layer) { program.setUniform("layer", layer); step3DTexture(program, layer); glDrawArrays(GL_TRIANGLES, 0, 6); } if (_saveCalculationTextures) { saveTextureFile( fmt::format("deltaJ_texture-scattering_order-{}.ppm", scatteringOrder), glm::ivec2(_textureSize) ); } program.deactivate(); } void AtmosphereDeferredcaster::calculateDeltaE(int scatteringOrder, ghoul::opengl::ProgramObject& program, GLuint deltaE, GLuint deltaSRayleigh, GLuint deltaSMie) { ZoneScoped glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, deltaE, 0); glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); program.activate(); ghoul::opengl::TextureUnit deltaSRayleighUnit; deltaSRayleighUnit.activate(); glBindTexture(GL_TEXTURE_3D, deltaSRayleigh); program.setUniform("deltaSRTexture", deltaSRayleighUnit); ghoul::opengl::TextureUnit deltaSMieUnit; deltaSMieUnit.activate(); glBindTexture(GL_TEXTURE_3D, deltaSMie); program.setUniform("deltaSMTexture", deltaSMieUnit); program.setUniform("firstIteration", (scatteringOrder == 2) ? 1 : 0); program.setUniform("Rg", _atmospherePlanetRadius); program.setUniform("Rt", _atmosphereRadius); program.setUniform("mieG", _miePhaseConstant); program.setUniform("SKY", _irradianceTableSize); program.setUniform("SAMPLES_MU_S", _muSSamples); program.setUniform("SAMPLES_NU", _nuSamples); program.setUniform("SAMPLES_MU", _muSamples); program.setUniform("SAMPLES_R", _rSamples); glDrawArrays(GL_TRIANGLES, 0, 6); if (_saveCalculationTextures) { saveTextureFile( fmt::format("deltaE_texture-scattering_order-{}.ppm", scatteringOrder), _deltaETableSize ); } program.deactivate(); } void AtmosphereDeferredcaster::calculateDeltaS(int scatteringOrder, ghoul::opengl::ProgramObject& program, GLuint deltaSRayleigh, GLuint deltaJ) { ZoneScoped glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, deltaSRayleigh, 0); glViewport(0, 0, _textureSize.x, _textureSize.y); program.activate(); ghoul::opengl::TextureUnit transmittanceUnit; transmittanceUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); program.setUniform("transmittanceTexture", transmittanceUnit); ghoul::opengl::TextureUnit deltaJUnit; deltaJUnit.activate(); glBindTexture(GL_TEXTURE_3D, deltaJ); program.setUniform("deltaJTexture", deltaJUnit); program.setUniform("Rg", _atmospherePlanetRadius); program.setUniform("Rt", _atmosphereRadius); program.setUniform("SAMPLES_MU_S", _muSSamples); program.setUniform("SAMPLES_NU", _nuSamples); program.setUniform("SAMPLES_MU", _muSamples); program.setUniform("SAMPLES_R", _rSamples); for (int layer = 0; layer < _rSamples; ++layer) { program.setUniform("layer", layer); step3DTexture(program, layer); glDrawArrays(GL_TRIANGLES, 0, 6); } if (_saveCalculationTextures) { saveTextureFile( fmt::format("deltaS_texture-scattering_order-{}.ppm", scatteringOrder), glm::ivec2(_textureSize) ); } program.deactivate(); } void AtmosphereDeferredcaster::calculateIrradiance(int scatteringOrder, ghoul::opengl::ProgramObject& program, GLuint deltaE) { ZoneScoped glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _irradianceTableTexture, 0 ); glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); program.activate(); ghoul::opengl::TextureUnit unit; unit.activate(); glBindTexture(GL_TEXTURE_2D, deltaE); program.setUniform("deltaETexture", unit); program.setUniform("OTHER_TEXTURES", _deltaETableSize); glDrawArrays(GL_TRIANGLES, 0, 6); if (_saveCalculationTextures) { saveTextureFile( fmt::format("irradianceTable_order-{}.ppm", scatteringOrder), _deltaETableSize ); } program.deactivate(); } void AtmosphereDeferredcaster::calculateInscattering(int scatteringOrder, ghoul::opengl::ProgramObject& prg, GLuint deltaSRayleigh) { ZoneScoped glFramebufferTexture( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _inScatteringTableTexture, 0 ); glViewport(0, 0, _textureSize.x, _textureSize.y); prg.activate(); ghoul::opengl::TextureUnit unit; unit.activate(); glBindTexture(GL_TEXTURE_3D, deltaSRayleigh); prg.setUniform("deltaSTexture", unit); prg.setUniform("SAMPLES_MU_S", _muSSamples); prg.setUniform("SAMPLES_NU", _nuSamples); prg.setUniform("SAMPLES_MU", _muSamples); prg.setUniform("SAMPLES_R", _rSamples); for (int layer = 0; layer < _rSamples; ++layer) { prg.setUniform("layer", layer); glDrawArrays(GL_TRIANGLES, 0, 6); } if (_saveCalculationTextures) { saveTextureFile( fmt::format("inscatteringTable_order-{}.ppm", scatteringOrder), glm::ivec2(_textureSize) ); } prg.deactivate(); } void AtmosphereDeferredcaster::calculateAtmosphereParameters() { ZoneScoped using ProgramObject = ghoul::opengl::ProgramObject; std::unique_ptr<ProgramObject> deltaJProgram = ProgramObject::Build( "DeltaJ Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/deltaJ_calc_fs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") ); std::unique_ptr<ProgramObject> irradianceSupTermsProgram = ProgramObject::Build( "IrradianceSupTerms Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_sup_calc_fs.glsl") ); std::unique_ptr<ProgramObject> inScatteringSupTermsProgram = ProgramObject::Build( "InScatteringSupTerms Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/inScattering_sup_calc_fs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") ); std::unique_ptr<ProgramObject> irradianceFinalProgram = ProgramObject::Build( "IrradianceEFinal Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/irradiance_final_fs.glsl") ); std::unique_ptr<ProgramObject> deltaSSupTermsProgram = ProgramObject::Build( "DeltaSSUPTerms Program", absPath("${MODULE_ATMOSPHERE}/shaders/calculation_vs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/deltaS_sup_calc_fs.glsl"), absPath("${MODULE_ATMOSPHERE}/shaders/calculation_gs.glsl") ); // Saves current FBO first GLint defaultFBO; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); GLint viewport[4]; global::renderEngine->openglStateCache().viewport(viewport); // Creates the FBO for the calculations GLuint calcFBO; glGenFramebuffers(1, &calcFBO); glBindFramebuffer(GL_FRAMEBUFFER, calcFBO); GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, drawBuffers); // Prepare for rendering/calculations GLuint quadVao; glGenVertexArrays(1, &quadVao); glBindVertexArray(quadVao); GLuint quadVbo; glGenBuffers(1, &quadVbo); glBindBuffer(GL_ARRAY_BUFFER, quadVbo); const GLfloat VertexData[] = { // x y z -1.f, -1.f, 1.f, 1.f, -1.f, 1.f, -1.f, -1.f, 1.f, -1.f, 1.f, 1.f, }; glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); // Execute Calculations LDEBUG("Starting precalculations for scattering effects"); glDisable(GL_BLEND); // See Precomputed Atmosphere Scattering from Bruneton et al. paper, algorithm 4.1: calculateTransmittance(); // line 2 in algorithm 4.1 GLuint deltaETable = calculateDeltaE(); // line 3 in algorithm 4.1 auto [deltaSRayleighTable, deltaSMieTable] = calculateDeltaS(); // line 4 in algorithm 4.1 calculateIrradiance(); // line 5 in algorithm 4.1 calculateInscattering(deltaSRayleighTable, deltaSMieTable); GLuint deltaJTable = createTexture(_textureSize, "DeltaJ", 3); // loop in line 6 in algorithm 4.1 for (int scatteringOrder = 2; scatteringOrder <= 4; ++scatteringOrder) { // line 7 in algorithm 4.1 calculateDeltaJ( scatteringOrder, *deltaJProgram, deltaJTable, deltaETable, deltaSRayleighTable, deltaSMieTable ); // line 8 in algorithm 4.1 calculateDeltaE( scatteringOrder, *irradianceSupTermsProgram, deltaETable, deltaSRayleighTable, deltaSMieTable ); // line 9 in algorithm 4.1 calculateDeltaS( scatteringOrder, *inScatteringSupTermsProgram, deltaSRayleighTable, deltaJTable ); glEnable(GL_BLEND); glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE); // line 10 in algorithm 4.1 calculateIrradiance( scatteringOrder, *irradianceFinalProgram, deltaETable ); // line 11 in algorithm 4.1 calculateInscattering( scatteringOrder, *deltaSSupTermsProgram, deltaSRayleighTable ); glDisable(GL_BLEND); } // Restores OpenGL blending state global::renderEngine->openglStateCache().resetBlendState(); glDeleteTextures(1, &deltaETable); glDeleteTextures(1, &deltaSRayleighTable); glDeleteTextures(1, &deltaSMieTable); glDeleteTextures(1, &deltaJTable); // Restores system state glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); global::renderEngine->openglStateCache().setViewportState(viewport); glDeleteBuffers(1, &quadVbo); glDeleteVertexArrays(1, &quadVao); glDeleteFramebuffers(1, &calcFBO); glBindVertexArray(0); LDEBUG("Ended precalculations for Atmosphere effects"); } void AtmosphereDeferredcaster::step3DTexture(ghoul::opengl::ProgramObject& prg, int layer) { // See OpenGL redbook 8th Edition page 556 for Layered Rendering const float planet2 = _atmospherePlanetRadius * _atmospherePlanetRadius; const float diff = _atmosphereRadius * _atmosphereRadius - planet2; const float ri = static_cast<float>(layer) / static_cast<float>(_rSamples - 1); float eps = 0.01f; if (layer > 0) { if (layer == (_rSamples - 1)) { eps = -0.001f; } else { eps = 0.f; } } const float r = std::sqrt(planet2 + ri * ri * diff) + eps; const float dminG = r - _atmospherePlanetRadius; const float dminT = _atmosphereRadius - r; const float dh = std::sqrt(r * r - planet2); const float dH = dh + std::sqrt(diff); prg.setUniform("r", r); prg.setUniform("dhdH", dminT, dH, dminG, dh); } } // namespace openspace
{ "content_hash": "82bdb8a4eebabc6c157439ee3851abfb", "timestamp": "", "source": "github", "line_count": 1101, "max_line_length": 90, "avg_line_length": 39.97184377838329, "alnum_prop": 0.6413460883001204, "repo_name": "OpenSpace/OpenSpace", "id": "59fc78af5c5a545a49d96018e2b29f200a5774e9", "size": "46101", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/atmosphere/rendering/atmospheredeferredcaster.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "13497055" }, { "name": "CMake", "bytes": "287847" }, { "name": "CSS", "bytes": "17271" }, { "name": "GLSL", "bytes": "670237" }, { "name": "HTML", "bytes": "1846" }, { "name": "Handlebars", "bytes": "1722" }, { "name": "JavaScript", "bytes": "11617" }, { "name": "Lua", "bytes": "2541160" }, { "name": "Objective-C++", "bytes": "10866" }, { "name": "Python", "bytes": "25442" } ], "symlink_target": "" }
package org.dspace.app.xmlui.wing; /** * A class representing an error generated by the Wing framework. * * This particular variation indicates that the arguments passed to the Wing * framework were invalid for the context in which they were attempting to be * used. * * @author Scott Phillips */ public class WingInvalidArgument extends WingException { // Because exception is serializable. public static final long serialVersionUID = 1; public WingInvalidArgument(String message) { super(message, null); } public WingInvalidArgument(Throwable t) { super(t); } public WingInvalidArgument(String message, Throwable t) { super(message, t); } }
{ "content_hash": "52a2ae33bd7b031a895e8b52ec5f8b73", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 77, "avg_line_length": 22.03030303030303, "alnum_prop": 0.6905089408528198, "repo_name": "jamie-dryad/dryad-repo", "id": "919350eb752ac39dd6f81f5fd0f532013b9f9993", "size": "943", "binary": false, "copies": "12", "ref": "refs/heads/dryad-master", "path": "dspace-xmlui/dspace-xmlui-wing/src/main/java/org/dspace/app/xmlui/wing/WingInvalidArgument.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "482606" }, { "name": "Java", "bytes": "13333046" }, { "name": "JavaScript", "bytes": "1408949" }, { "name": "Perl", "bytes": "23479" }, { "name": "Python", "bytes": "5899" }, { "name": "Shell", "bytes": "42647" }, { "name": "XSLT", "bytes": "1927492" } ], "symlink_target": "" }
(function () { 'use strict'; var entitiesListModule = angular.module('app.directives.dependencies-graph', ['app.services' ]); entitiesListModule.controller('DependenciesGraphCtrl', ['$scope', 'Falcon', 'X2jsService', '$window', 'EncodeService', 'EntityModel', function($scope, Falcon, X2jsService, $window, encodeService, EntityModel) { }]); entitiesListModule.directive('dependenciesGraph', ["$timeout", 'Falcon', '$filter', '$state', 'X2jsService', 'EntityModel', function($timeout, Falcon, $filter, $state, X2jsService, EntityModel) { return { scope: { type: "=", name: "=" }, controller: 'DependenciesGraphCtrl', restrict: "EA", templateUrl: 'html/directives/dependenciesGraphDv.html', link: function (scope, element) { var loadDependencyGraph = function(entity_type, entity_name, done_callback) { var nodes = {}; var next_node_id = 0; var requests_in_fly = 0; function key(type, name) { return type + '/' + name; } function getOrCreateNode(type, name) { var k = key(type, name); if (nodes[k] !== undefined) return nodes[k]; var n = { "id": next_node_id++, "type": type, "name": name, "dependency": [] }; nodes[k] = n; return n; } function loadEntry(node) { var type = node.type, name = node.name, k = key(type, name); Falcon.logRequest(); Falcon.getEntityDependencies(type, name) .success(function (data) { Falcon.logResponse('success', data, false, true); if (data.entity == null) return; if (!($.isArray(data.entity))) data.entity = new Array(data.entity); var l = data.entity.length; for (var i = 0; i < l; ++i) { var e = data.entity[i]; var d = getOrCreateNode(e.type, e.name); var src = null, dst = null; if (d.type === "cluster") { src = node; dst = d; } else if (d.type === "process") { src = d; dst = node; } else { if (node.type === "cluster") { src = d; dst = node; } else { src = node; dst = d; } } //console.log(src.name + '->' + dst.name); src.dependency.push(dst.id); } done_callback(nodes); }) .error(function (err) { Falcon.logResponse('error', err, false, true); }); } function load() { var n = getOrCreateNode(entity_type, entity_name); loadEntry(n); } load(); }; var plotDependencyGraph = function(nodes, element) { var NODE_WIDTH = 150; var NODE_HEIGHT = 50; var RECT_ROUND = 10; var SEPARATION = 40; var UNIVERSAL_SEP = 80; var svg = d3.select(element).append("svg"); // Function to draw the lines of the edge var LINE_FUNCTION = d3.svg.line() .x(function(d) { return d.x; }) .y(function(d) { return d.y; }) .interpolate('basis'); // Mappining from id to a node var node_by_id = {}; var layout = null; /** * Calculate the intersection point between the point p and the edges of the rectangle rect **/ function intersectRect(rect, p) { var cx = rect.x, cy = rect.y, dx = p.x - cx, dy = p.y - cy, w = rect.width / 2, h = rect.height / 2; if (dx == 0) return { "x": p.x, "y": rect.y + (dy > 0 ? h : -h) }; var slope = dy / dx; var x0 = null, y0 = null; if (Math.abs(slope) < rect.height / rect.width) { // intersect with the left or right edges of the rect x0 = rect.x + (dx > 0 ? w : -w); y0 = cy + slope * (x0 - cx); } else { y0 = rect.y + (dy > 0 ? h : -h); x0 = cx + (y0 - cy) / slope; } return { "x": x0, "y": y0 }; } function drawNode(u, value) { var root = svg.append('g').classed('node', true) .attr('transform', 'translate(' + -value.width/2 + ',' + -value.height/2 + ')'); var node = node_by_id[u]; var fo = root.append('foreignObject') .attr('x', value.x) .attr('y', value.y) .attr('width', value.width) .attr('height', value.height) .attr('class', 'foreignObject'); var txt = fo.append('xhtml:div') .text(node.name) .classed('node-name', true) .classed('node-name-' + node.type, true); var rect = root.append('rect') .attr('width', value.width) .attr('height', value.height) .attr('x', value.x) .attr('y', value.y) .attr('rx', RECT_ROUND) .attr('ry', RECT_ROUND) .on('click', function () { Falcon.logRequest(); Falcon.getEntityDefinition(node.type.toLowerCase(), node.name) .success(function (data) { Falcon.logResponse('success', data, false, true); var entityModel = X2jsService.xml_str2json(data); EntityModel.type = node.type.toLowerCase(); EntityModel.name = node.name; EntityModel.model = entityModel; $state.go('entityDetails'); }) .error(function (err) { Falcon.logResponse('error', err, false, false); }); }); } function drawEdge(e, u, v, value) { var root = svg.append('g').classed('edge', true); root.append('path') .attr('marker-end', 'url(#arrowhead)') .attr('d', function() { var points = value.points; var source = layout.node(u); var target = layout.node(v); var p0 = points.length === 0 ? target : points[0]; var p1 = points.length === 0 ? source : points[points.length - 1]; points.unshift(intersectRect(source, p0)); points.push(intersectRect(target, p1)); return LINE_FUNCTION(points); }); } function postRender() { svg .append('svg:defs') .append('svg:marker') .attr('id', 'arrowhead') .attr('viewBox', '0 0 10 10') .attr('refX', 8) .attr('refY', 5) .attr('markerUnits', 'strokewidth') .attr('markerWidth', 8) .attr('markerHeight', 5) .attr('orient', 'auto') .attr('style', 'fill: #333') .append('svg:path') .attr('d', 'M 0 0 L 10 5 L 0 10 z'); } function plot() { var g = new dagre.Digraph(); for (var key in nodes) { var n = nodes[key]; node_by_id[n.id] = n; g.addNode(n.id, { "width": NODE_WIDTH, "height": NODE_HEIGHT }); } for (var key in nodes) { var n = nodes[key]; for (var i = 0, l = n.dependency.length; i < l; ++i) { var d = n.dependency[i]; g.addEdge(null, n.id, d); } } layout = dagre.layout() .universalSep(UNIVERSAL_SEP).rankSep(SEPARATION) .run(g); layout.eachEdge(drawEdge); layout.eachNode(drawNode); var graph = layout.graph(); svg.attr("width", graph.width+150); svg.attr("height", graph.height+10); postRender(); } plot(); }; var visualizeDependencyGraph = function(type, name) { loadDependencyGraph(type, name, function(nodes) { plotDependencyGraph(nodes, element[0]); }); }; //console.log(scope.type + " " + scope.name); visualizeDependencyGraph(scope.type, scope.name); } }; }]); })();
{ "content_hash": "59021d4134b6d6bc25e46f465ae60164", "timestamp": "", "source": "github", "line_count": 278, "max_line_length": 135, "avg_line_length": 32.2589928057554, "alnum_prop": 0.43766726137377343, "repo_name": "OpenPOWER-BigData/HDP-falcon", "id": "db090cd1e191d3b1b5e798cae0ccec64d0508122", "size": "9774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "falcon-ui/app/js/directives/dependencies-graph.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2838" }, { "name": "CSS", "bytes": "138663" }, { "name": "HTML", "bytes": "427863" }, { "name": "Java", "bytes": "5485993" }, { "name": "JavaScript", "bytes": "746250" }, { "name": "Perl", "bytes": "19690" }, { "name": "PigLatin", "bytes": "7131" }, { "name": "PowerShell", "bytes": "674896" }, { "name": "Python", "bytes": "19302" }, { "name": "Shell", "bytes": "25505" }, { "name": "XSLT", "bytes": "16792" } ], "symlink_target": "" }