text
stringlengths
2
1.04M
meta
dict
<?php session_start(); require("../../MySQLconnect/config.php"); if(!isset($_SESSION['user_id'])) { header('location:../../'); } else { $userid = mysql_real_escape_string($_SESSION['user_id']); } $riskid = mysql_real_escape_string($_GET['risk_id']); $projectid = mysql_real_escape_string($_GET['project_id']); $riskinfo = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['risk_info']))),ENT_QUOTES); $consequence = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['consequence']))),ENT_QUOTES); $chance = mysql_real_escape_string($_GET['chance']); $programme = mysql_real_escape_string($_GET['programme']); $budget = mysql_real_escape_string($_GET['budget']); $she = mysql_real_escape_string($_GET['she']); $timeimpact = mysql_real_escape_string($_GET['impact_t']); $cost = mysql_real_escape_string($_GET['cost']); $costtbd = mysql_real_escape_string($_GET['cost_tbd']); $owner = mysql_real_escape_string($_GET['owner']); $mitigation = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['mitigation']))),ENT_QUOTES); $time=time(); $riskrating = $chance*max($programme,$budget); $oldrecorddetails = mysql_fetch_array(mysql_query("SELECT * FROM risk_log WHERE risk_id='$riskid'")); //check for the ID of the new owner and add them to the system if they do not exist $results = mysql_query("SELECT * FROM users WHERE email='$owner'"); $countrows = mysql_num_rows($results); if($countrows==0) { mysql_query("INSERT INTO users SET email='$owner'"); $results = mysql_query("SELECT * FROM users WHERE email='$owner'"); $ownerid = mysql_fetch_array($results); $ownerid = $ownerid['user_id']; } else { $ownerid = mysql_fetch_array($results); $ownerid = $ownerid['user_id']; } mysql_query("UPDATE risk_log SET risk_info='$riskinfo', consequence='$consequence', chance='$chance', impact_p='$programme', impact_b='$budget', impact_she='$she', impact_t='$timeimpact', e_cost='$cost', e_cost_tbd='$costtbd', owner='$ownerid', mitigation='$mitigation', risk_rating='$riskrating' WHERE risk_id='$riskid'"); $updatecomment1 = ""; $updatecomment2 = ""; $updatecomment3 = ""; $updatecomment4 = ""; $updatecomment5 = ""; $updatecomment6 = ""; $updatecomment7 = ""; $updatecomment8 = ""; $updatecomment9 = ""; $updatecomment10 = ""; $updatecomment11 = ""; $updatecomment12 = ""; $changed = 0; if($oldrecorddetails['risk_info']<>$riskinfo) { $updatecomment1 = "<br />Risk info changed from: " . $oldrecorddetails['risk_info']; $changed = 1; } if($oldrecorddetails['owner']<>$owner) { $updatecomment2 = "<br />Owner changed from: " . $oldrecorddetails['owner']; $changed = 1; } if($oldrecorddetails['consequence']<>$consequence) { $updatecomment3 = "<br />Consequence changed from: " . $oldrecorddetails['consequence']; $changed = 1; } if($oldrecorddetails['impact_p']<>$programme) { $updatecomment4 = "<br />Programme impact changed from: " . $oldrecorddetails['impact_p']; $changed = 1; } if($oldrecorddetails['impact_b']<>$budget) { $updatecomment5 = "<br />Budget impact changed from: " . $oldrecorddetails['impact_b']; $changed = 1; } if($oldrecorddetails['impact_she']<>$she) { $updatecomment6 = "<br />SHE impact changed from: " . $oldrecorddetails['impact_she']; $changed = 1; } if($oldrecorddetails['chance']<>$chance) { $updatecomment7 = "<br />Likelihood changed from: " . $oldrecorddetails['chance']; $changed = 1; } if($oldrecorddetails['risk_rating']<>$riskrating) { $updatecomment8 = "<br />Risk rating changed from: " . $oldrecorddetails['risk_rating']; $changed = 1; } if($oldrecorddetails['impact_t']<>$timeimpact) { $updatecomment9 = "<br />Time impact changed from: " . $oldrecorddetails['impact_t']; $changed = 1; } if($oldrecorddetails['e_cost']<>$cost) { $updatecomment10 = "<br />Estimated cost changed from: " . $oldrecorddetails['e_cost']; $changed = 1; } if($oldrecorddetails['e_cost_tbd']<>$costtbd) { if($costtbd==1) { $updatecomment11 = "<br />Costs to be determined changed to: confirmation needed"; } else { $updatecomment11 = "<br />Costs to be determined changed to: costs confirmed"; } $changed = 1; } if($oldrecorddetails['mitigation']<>$mitigation) { $updatecomment12 = "<br />Mitigation measures changed from: " . $oldrecorddetails['mitigation']; $changed = 1; } if($changed>0) { $updatecomment = $updatecomment1.$updatecomment2.$updatecomment3.$updatecomment4.$updatecomment5.$updatecomment6.$updatecomment7.$updatecomment8.$updatecomment9.$updatecomment10.$updatecomment11.$updatecomment12; mysql_query("INSERT INTO audit_trail_risk_log (project_id, risk_id, comment, user_id) VALUES ('$projectid','$riskid','$updatecomment','$userid')"); } //display the list of daily records require("load_risk_records.php"); ?>
{ "content_hash": "043d57789b2864ef93ce78c7accb7a41", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 267, "avg_line_length": 31.649350649350648, "alnum_prop": 0.6721378744357817, "repo_name": "tomwinslow/Open-Project-Tracker", "id": "e53dabec918a440732a15fde41e4dac0904872c3", "size": "4874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ajax/risk_log/update_risk_details.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "28700" }, { "name": "HTML", "bytes": "13314" }, { "name": "JavaScript", "bytes": "214765" }, { "name": "PHP", "bytes": "341361" } ], "symlink_target": "" }
package cmdui import core._ import org.apache.commons.cli._ import java.io.File import com.github.nscala_time.time.Imports._ /** * Created by DiscipleOfShinku on 11/5/2016. */ //That is for testing class CmdUI { } //That is for running application object CmdUI extends CmdUI { def main(args: Array[String]): Unit = { val dbName = new String(System.getProperty("user.home") + "/.jpersonalstat/data.db") new File(dbName).getParentFile().mkdir() val db = SQLiteInitializer.init(dbName) val measurementInterface = new SQLiteMeasurementInterface(db) val options = new Options() var input = new Option("h", "help", false, "show this help") input.setRequired(false) options.addOption(input) input = new Option("s", "show", false, "[--show | -s] [--all | -A] [-m | -l] [<ID>]") input.setRequired(false) options.addOption(input) input = new Option("A", "all", false, "list all measurements or logs") input.setRequired(false) options.addOption(input) input = new Option("m", true, "show measurement; ID is required") input.setRequired(false) options.addOption(input) //problem: with argument and without argument are required input = new Option("l", true, "logs of measurement; ID is required") input.setRequired(false) options.addOption(input) input = new Option("a", "add", true, "create new measurement; name is required") input.setRequired(false) options.addOption(input) input = new Option("i", "inc", true, "increment measurement; ID is required") input.setRequired(false) options.addOption(input) /* does not implemented yet input = new Option("c", "change", false, "--change [default: --increment]") input.setRequired(false) options.addOption(input) */ val parser = new DefaultParser() val formatter = new HelpFormatter() try { val cmd: CommandLine = parser.parse(options, args) if (cmd.hasOption("h")){ formatter.printHelp("jpersonalstat", options) } else if (cmd.hasOption("s")){ if (cmd.hasOption("A")) { if (cmd.hasOption("l")) { val allLogs: String = measurementInterface.getAllLogs().toString() System.out.println(allLogs) } else { val allMeasurements: String = measurementInterface.getAll().toString() System.out.println(allMeasurements) } } else if (cmd.hasOption("m")) { val measurement: String = measurementInterface.getById(cmd.getOptionValue('m').toInt).toString() System.out.println(measurement) } else if (cmd.hasOption("l")) { val measurementLogs: String = measurementInterface.getLog(measurementInterface.getById(cmd.getOptionValue('l').toInt)).toString() System.out.println(measurementLogs) } else { val allMeasurements: String = measurementInterface.getAll().toString() System.out.println(allMeasurements) } } else if (cmd.hasOption("a")){ val ID = measurementInterface.add(cmd.getOptionValue('a')).id System.out.println("You have created measurement with ID: " + ID) } else if (cmd.hasOption("i")) { val dateTime = new DateTime() measurementInterface.inc(measurementInterface.getById(cmd.getOptionValue('i').toInt), "Incrementing measurement", DateTime.now) System.out.println("You have incremented measurement.") } else if (cmd.hasOption("c")) { //This command does not implemented yet. System.out.println("This command does not implemented yet.") } else formatter.printHelp("jpersonalstat", options) } catch { case e: ParseException => System.out.println(e.getMessage()) formatter.printHelp("jpersonalstat", options) System.exit(1) return } } }
{ "content_hash": "9b34b9e5fdc4dfdbc95ec0dd4011ec36", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 139, "avg_line_length": 35.27927927927928, "alnum_prop": 0.641726251276813, "repo_name": "DiscipleOfShinku/jpersonalstat", "id": "76a4941811870c35bacfcd4c726937d8fdd06f7d", "size": "3916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/cmdui/CmdUI.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "15136" } ], "symlink_target": "" }
<!doctype html> <html> <title>npm-folders</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../../static/style.css"> <link rel="canonical" href="https://www.npmjs.org/doc/files/npm-folders.html"> <script async=true src="../../static/toc.js"></script> <body> <div id="wrapper"> <h1><a href="../files/npm-folders.html">npm-folders</a></h1> <p>Folder Structures Used by npm</p> <h2 id="description">DESCRIPTION</h2> <p>npm puts various things on your computer. That&#39;s its job.</p> <p>This document will tell you what it puts where.</p> <h3 id="tl-dr">tl;dr</h3> <ul> <li>Local install (default): puts stuff in <code>./node_modules</code> of the current package root.</li> <li>Global install (with <code>-g</code>): puts stuff in /usr/local or wherever node is installed.</li> <li>Install it <strong>locally</strong> if you&#39;re going to <code>require()</code> it.</li> <li>Install it <strong>globally</strong> if you&#39;re going to run it on the command line.</li> <li>If you need both, then install it in both places, or use <code>npm link</code>.</li> </ul> <h3 id="prefix-configuration">prefix Configuration</h3> <p>The <code>prefix</code> config defaults to the location where node is installed. On most systems, this is <code>/usr/local</code>, and most of the time is the same as node&#39;s <code>process.installPrefix</code>.</p> <p>On windows, this is the exact location of the node.exe binary. On Unix systems, it&#39;s one level up, since node is typically installed at <code>{prefix}/bin/node</code> rather than <code>{prefix}/node.exe</code>.</p> <p>When the <code>global</code> flag is set, npm installs things into this prefix. When it is not set, it uses the root of the current package, or the current working directory if not in a package already.</p> <h3 id="node-modules">Node Modules</h3> <p>Packages are dropped into the <code>node_modules</code> folder under the <code>prefix</code>. When installing locally, this means that you can <code>require(&quot;packagename&quot;)</code> to load its main module, or <code>require(&quot;packagename/lib/path/to/sub/module&quot;)</code> to load other modules.</p> <p>Global installs on Unix systems go to <code>{prefix}/lib/node_modules</code>. Global installs on Windows go to <code>{prefix}/node_modules</code> (that is, no <code>lib</code> folder.)</p> <p>Scoped packages are installed the same way, except they are grouped together in a sub-folder of the relevant <code>node_modules</code> folder with the name of that scope prefix by the @ symbol, e.g. <code>npm install @myorg/package</code> would place the package in <code>{prefix}/node_modules/@myorg/package</code>. See <code><a href="../misc/scopes.html"><a href="../misc/scopes.html">scopes(7)</a></a></code> for more details.</p> <p>If you wish to <code>require()</code> a package, then install it locally.</p> <h3 id="executables">Executables</h3> <p>When in global mode, executables are linked into <code>{prefix}/bin</code> on Unix, or directly into <code>{prefix}</code> on Windows.</p> <p>When in local mode, executables are linked into <code>./node_modules/.bin</code> so that they can be made available to scripts run through npm. (For example, so that a test runner will be in the path when you run <code>npm test</code>.)</p> <h3 id="man-pages">Man Pages</h3> <p>When in global mode, man pages are linked into <code>{prefix}/share/man</code>.</p> <p>When in local mode, man pages are not installed.</p> <p>Man pages are not installed on Windows systems.</p> <h3 id="cache">Cache</h3> <p>See <code><a href="../cli/npm-cache.html"><a href="../cli/npm-cache.html">npm-cache(1)</a></a></code>. Cache files are stored in <code>~/.npm</code> on Posix, or <code>~/npm-cache</code> on Windows.</p> <p>This is controlled by the <code>cache</code> configuration param.</p> <h3 id="temp-files">Temp Files</h3> <p>Temporary files are stored by default in the folder specified by the <code>tmp</code> config, which defaults to the TMPDIR, TMP, or TEMP environment variables, or <code>/tmp</code> on Unix and <code>c:\windows\temp</code> on Windows.</p> <p>Temp files are given a unique folder under this root for each run of the program, and are deleted upon successful exit.</p> <h2 id="more-information">More Information</h2> <p>When installing locally, npm first tries to find an appropriate <code>prefix</code> folder. This is so that <code>npm install foo@1.2.3</code> will install to the sensible root of your package, even if you happen to have <code>cd</code>ed into some other folder.</p> <p>Starting at the $PWD, npm will walk up the folder tree checking for a folder that contains either a <code>package.json</code> file, or a <code>node_modules</code> folder. If such a thing is found, then that is treated as the effective &quot;current directory&quot; for the purpose of running npm commands. (This behavior is inspired by and similar to git&#39;s .git-folder seeking logic when running git commands in a working dir.)</p> <p>If no package root is found, then the current folder is used.</p> <p>When you run <code>npm install foo@1.2.3</code>, then the package is loaded into the cache, and then unpacked into <code>./node_modules/foo</code>. Then, any of foo&#39;s dependencies are similarly unpacked into <code>./node_modules/foo/node_modules/...</code>.</p> <p>Any bin files are symlinked to <code>./node_modules/.bin/</code>, so that they may be found by npm scripts when necessary.</p> <h3 id="global-installation">Global Installation</h3> <p>If the <code>global</code> configuration is set to true, then npm will install packages &quot;globally&quot;.</p> <p>For global installation, packages are installed roughly the same way, but using the folders described above.</p> <h3 id="cycles-conflicts-and-folder-parsimony">Cycles, Conflicts, and Folder Parsimony</h3> <p>Cycles are handled using the property of node&#39;s module system that it walks up the directories looking for <code>node_modules</code> folders. So, at every stage, if a package is already installed in an ancestor <code>node_modules</code> folder, then it is not installed at the current location.</p> <p>Consider the case above, where <code>foo -&gt; bar -&gt; baz</code>. Imagine if, in addition to that, baz depended on bar, so you&#39;d have: <code>foo -&gt; bar -&gt; baz -&gt; bar -&gt; baz ...</code>. However, since the folder structure is: <code>foo/node_modules/bar/node_modules/baz</code>, there&#39;s no need to put another copy of bar into <code>.../baz/node_modules</code>, since when it calls require(&quot;bar&quot;), it will get the copy that is installed in <code>foo/node_modules/bar</code>.</p> <p>This shortcut is only used if the exact same version would be installed in multiple nested <code>node_modules</code> folders. It is still possible to have <code>a/node_modules/b/node_modules/a</code> if the two &quot;a&quot; packages are different versions. However, without repeating the exact same package multiple times, an infinite regress will always be prevented.</p> <p>Another optimization can be made by installing dependencies at the highest level possible, below the localized &quot;target&quot; folder.</p> <h4 id="example">Example</h4> <p>Consider this dependency graph:</p> <pre><code>foo +-- blerg@1.2.5 +-- bar@1.2.3 | +-- blerg@1.x (latest=1.3.7) | +-- baz@2.x | | `-- quux@3.x | | `-- bar@1.2.3 (cycle) | `-- asdf@* `-- baz@1.2.3 `-- quux@3.x `-- bar </code></pre><p>In this case, we might expect a folder structure like this:</p> <pre><code>foo +-- node_modules +-- blerg (1.2.5) &lt;---[A] +-- bar (1.2.3) &lt;---[B] | `-- node_modules | +-- baz (2.0.2) &lt;---[C] | | `-- node_modules | | `-- quux (3.2.0) | `-- asdf (2.3.4) `-- baz (1.2.3) &lt;---[D] `-- node_modules `-- quux (3.2.0) &lt;---[E] </code></pre><p>Since foo depends directly on <code>bar@1.2.3</code> and <code>baz@1.2.3</code>, those are installed in foo&#39;s <code>node_modules</code> folder.</p> <p>Even though the latest copy of blerg is 1.3.7, foo has a specific dependency on version 1.2.5. So, that gets installed at [A]. Since the parent installation of blerg satisfies bar&#39;s dependency on <code>blerg@1.x</code>, it does not install another copy under [B].</p> <p>Bar [B] also has dependencies on baz and asdf, so those are installed in bar&#39;s <code>node_modules</code> folder. Because it depends on <code>baz@2.x</code>, it cannot re-use the <code>baz@1.2.3</code> installed in the parent <code>node_modules</code> folder [D], and must install its own copy [C].</p> <p>Underneath bar, the <code>baz -&gt; quux -&gt; bar</code> dependency creates a cycle. However, because bar is already in quux&#39;s ancestry [B], it does not unpack another copy of bar into that folder.</p> <p>Underneath <code>foo -&gt; baz</code> [D], quux&#39;s [E] folder tree is empty, because its dependency on bar is satisfied by the parent folder copy installed at [B].</p> <p>For a graphical breakdown of what is installed where, use <code>npm ls</code>.</p> <h3 id="publishing">Publishing</h3> <p>Upon publishing, npm will look in the <code>node_modules</code> folder. If any of the items there are not in the <code>bundledDependencies</code> array, then they will not be included in the package tarball.</p> <p>This allows a package maintainer to install all of their dependencies (and dev dependencies) locally, but only re-publish those items that cannot be found elsewhere. See <code><a href="../files/package.json.html"><a href="../files/package.json.html">package.json(5)</a></a></code> for more information.</p> <h2 id="see-also">SEE ALSO</h2> <ul> <li><a href="../misc/npm-faq.html"><a href="../misc/npm-faq.html">npm-faq(7)</a></a></li> <li><a href="../files/package.json.html"><a href="../files/package.json.html">package.json(5)</a></a></li> <li><a href="../cli/npm-install.html"><a href="../cli/npm-install.html">npm-install(1)</a></a></li> <li><a href="../cli/npm-pack.html"><a href="../cli/npm-pack.html">npm-pack(1)</a></a></li> <li><a href="../cli/npm-cache.html"><a href="../cli/npm-cache.html">npm-cache(1)</a></a></li> <li><a href="../cli/npm-config.html"><a href="../cli/npm-config.html">npm-config(1)</a></a></li> <li><a href="../files/npmrc.html"><a href="../files/npmrc.html">npmrc(5)</a></a></li> <li><a href="../misc/npm-config.html"><a href="../misc/npm-config.html">npm-config(7)</a></a></li> <li><a href="../cli/npm-publish.html"><a href="../cli/npm-publish.html">npm-publish(1)</a></a></li> </ul> </div> <table border=0 cellspacing=0 cellpadding=0 id=npmlogo> <tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18>&nbsp;</td></tr> <tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td colspan=6 style="width:60px;height:10px;background:#fff">&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td></tr> <tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2>&nbsp;</td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff" rowspan=2>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff">&nbsp;</td></tr> <tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6>&nbsp;</td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td></tr> <tr><td colspan=5 style="width:50px;height:10px;background:#fff">&nbsp;</td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4>&nbsp;</td><td style="width:90px;height:10px;background:#fff" colspan=9>&nbsp;</td></tr> </table> <p id="footer">npm-folders &mdash; npm@2.1.8</p>
{ "content_hash": "b93157bf565a239c2be2d7f666c7d5f0", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 807, "avg_line_length": 68.1436170212766, "alnum_prop": 0.7010381703223793, "repo_name": "grdmunoz/peopleplusplus", "id": "260d125d9ca4d3600547bd9654f88102030e8a7e", "size": "12811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/meanio/node_modules/mean-cli/node_modules/npm/html/doc/files/npm-folders.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "337406" }, { "name": "JavaScript", "bytes": "843669" }, { "name": "Perl", "bytes": "48" }, { "name": "Python", "bytes": "3523" }, { "name": "Shell", "bytes": "111" } ], "symlink_target": "" }
package de.is24.playground; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by CHeeren on 25.07.2014. */ // This class contains some successful tests // Although it has "Cat" in its name, it actually doesn't contain any categories public class GreenCatTest { @Before public void setUp() throws Exception { } @Test public void testGreen1() throws Exception { assertEquals("This test will succeed", true, true); } @Test public void testGreen2() throws Exception { assertEquals("This test will succeed", true, true); } @Test public void testGreen3() throws Exception { assertEquals("This test will succeed", true, true); } }
{ "content_hash": "6cf4fdbca5373012ed7651a27bed8e60", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 80, "avg_line_length": 21.82857142857143, "alnum_prop": 0.6740837696335078, "repo_name": "matey-jack/grouping-tests", "id": "8a04b16b2b71102f7663e0a2c19e0c463b06354f", "size": "764", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/de/is24/playground/GreenCatTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "7689" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SassyStudio.Compiler.Parsing { public class XmlAttribute : ComplexItem { public TokenItem Name { get; protected set; } public TokenItem EqualSign { get; protected set; } public StringValue Value { get; protected set; } public override bool Parse(IItemFactory itemFactory, ITextProvider text, ITokenStream stream) { if (stream.Current.Type == TokenType.Identifier) { Name = Children.AddCurrentAndAdvance(stream, SassClassifierType.XmlDocumentationTag); if (stream.Current.Type == TokenType.Equal) EqualSign = Children.AddCurrentAndAdvance(stream); if (stream.Current.Type == TokenType.String || stream.Current.Type == TokenType.BadString) Value = itemFactory.CreateSpecificParsed<StringValue>(this, text, stream); } return Children.Count > 0; } } }
{ "content_hash": "f75d4ffa3c8ec9adcd16b1e54e60147e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 106, "avg_line_length": 34.86666666666667, "alnum_prop": 0.6395793499043977, "repo_name": "darrenkopp/SassyStudio", "id": "5820022893417f351f488942c9e1723283507c54", "size": "1048", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SassyStudio.Compiler/Parsing/XmlAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "469079" }, { "name": "CSS", "bytes": "15" }, { "name": "Smalltalk", "bytes": "7242" } ], "symlink_target": "" }
import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('POSTGRES_DB', 'postgres'), 'USER': os.environ.get('POSTGRES_USER', 'postgres'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD', 'postgres'), 'HOST': os.environ.get('DATABASE_PGPOOL_SERVICE_SERVICE_HOST', 'postgres'), 'PORT': os.environ.get('DATABASE_PGPOOL_SERVICE_PORT_5432_TCP_PORT', '5123'), 'OPTIONS': { 'connect_timeout': 3, } } }
{ "content_hash": "d3e5f7709ccff590b0be411ff9c9fd84", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 85, "avg_line_length": 35.6, "alnum_prop": 0.5842696629213483, "repo_name": "ConnorMac/stokvel.io", "id": "2f3fbc69d5a0c93d98db83564867a26e0dd4a57c", "size": "534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/config/plugins/database.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1665" }, { "name": "Jupyter Notebook", "bytes": "656" }, { "name": "Python", "bytes": "76875" } ], "symlink_target": "" }
"use strict"; import "./../style/visual.less"; import powerbi from "powerbi-visuals-api"; import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions; import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions; import IVisual = powerbi.extensibility.visual.IVisual; import * as d3 from "d3"; export class Visual implements IVisual { private svgRoot: d3.Selection<SVGElement, {}, HTMLElement, any>; private ellipse: d3.Selection<SVGElement, {}, HTMLElement, any>; private text: d3.Selection<SVGElement, {}, HTMLElement, any>; private padding: number = 20; constructor(options: VisualConstructorOptions) { console.log('Visual constructor', options); this.svgRoot = d3.select(options.element).append("svg"); this.ellipse = this.svgRoot.append("ellipse") .attr("fill", "#FEBF0F"); this.text = this.svgRoot.append("text") .text("Hello D3") .attr("text-anchor", "middle") .attr("dominant-baseline", "central"); this.RenderVisual(options.element.clientWidth, options.element.clientHeight); } public update(options: VisualUpdateOptions) { console.log('Visual update', options); this.RenderVisual(options.viewport.width, options.viewport.height); } private RenderVisual(clientWidth: number, clientHeight: number) { this.svgRoot .attr("width", clientWidth) .attr("height", clientHeight); var plot = { xOffset: this.padding, yOffset: this.padding, width: clientWidth - (this.padding * 2), height: clientHeight - (this.padding * 2), }; this.ellipse .attr("cx", plot.xOffset + (plot.width * 0.5)) .attr("cy", plot.yOffset + (plot.height * 0.5)) .attr("rx", (plot.width * 0.5)) .attr("ry", (plot.height * 0.5)) var fontSizeForWidth: number = plot.width * .20; var fontSizeForHeight: number = plot.height * .35; var fontSize: number = d3.min([fontSizeForWidth, fontSizeForHeight]); this.text .attr("x", plot.xOffset + (plot.width / 2)) .attr("y", plot.yOffset + (plot.height / 2)) .attr("width", plot.width) .attr("height", plot.height) .attr("font-size", fontSize); } }
{ "content_hash": "16ef3351bc65184d173bdbe0b1b61791", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 88, "avg_line_length": 32.74324324324324, "alnum_prop": 0.610813041683863, "repo_name": "CriticalPathTraining/PBD365", "id": "0bef2373701601067ab67e3cd7b2f1e93455a2d3", "size": "2423", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Modules/08_CustomVisuals/Demo/DemosV3/helloWorld/src/visual.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "652" }, { "name": "C#", "bytes": "1002173" }, { "name": "CSS", "bytes": "949018" }, { "name": "HTML", "bytes": "9045876" }, { "name": "JavaScript", "bytes": "5909863" }, { "name": "Less", "bytes": "3570" }, { "name": "M", "bytes": "51" }, { "name": "MATLAB", "bytes": "1208" }, { "name": "Mathematica", "bytes": "181" }, { "name": "Mercury", "bytes": "191" }, { "name": "Objective-C", "bytes": "9539" }, { "name": "PowerShell", "bytes": "55367" }, { "name": "SCSS", "bytes": "5628" }, { "name": "TSQL", "bytes": "7695" }, { "name": "TypeScript", "bytes": "299137" } ], "symlink_target": "" }
require File.expand_path '../../../lib/catarse_full/engine', __FILE__ if Rails.env.production? Catarse::Application.initializer 'production' do |app| config = app.config # Settings specified here will take precedence over those in config/environment.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Specifies the header that your server uses for sending files config.action_dispatch.x_sendfile_header = "X-Sendfile" # For nginx: # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # If you have no front-end server that supports something like X-Sendfile, # just comment this out and Rails will serve the files # See everything in the log (default is :info) # config.log_level = :debug # Use a different logger for distributed setups # config.logger = SyslogLogger.new # https://github.com/ryanb/cancan/issues/511 config.logger = Logger.new(STDOUT) config.logger.level = Logger.const_get((ENV["LOG_LEVEL"] || "ERROR").upcase) # Use a different cache store in production #config.cache_store = :dalli_store # Disable Rails's static asset server # In production, Apache or nginx will already do this config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed #config.assets.compile = false config.assets.compile = true config.assets.precompile << 'catarse.css' # Generate digests for assets URLs config.assets.digest = true # Enable serving of images, stylesheets, and javascripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify config.active_record.schema_format = :sql end end
{ "content_hash": "a43386b5ddc71be68b325a973e08a4d4", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 86, "avg_line_length": 35.885714285714286, "alnum_prop": 0.7137738853503185, "repo_name": "marnen/catarse_full", "id": "d0f3f53cb6339f7d7155d1b16c69415c8872a4fc", "size": "2512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/environments/production.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "327592" }, { "name": "HTML", "bytes": "239553" }, { "name": "JavaScript", "bytes": "172760" }, { "name": "Ruby", "bytes": "460086" }, { "name": "SQLPL", "bytes": "68023" } ], "symlink_target": "" }
list="./icon.png\ ./index.html\ ./resources/Western-logo-CBE.jpg\ ./resources/treeHeader.jpg\ ./resources/help.svg\ ./manifest.json\ ./css/css-toggle-switch-master/dist/toggle-switch.css\ ./css/print.css\ ./css/Fonts/AvenirLTStd-Light.otf\ ./css/Fonts/AvenirLTStd-LightOblique.otf\ ./css/Fonts/AvenirLTStd-Oblique.otf\ ./css/Fonts/AvenirLTStd-Roman.otf\ ./css/xeditable.css\ ./css/style.css\ ./js/xeditable.js\ ./js/angularApp.js\ ./js/content.js\ ./js/menu.js\ ./js/popup.js\ ./js/calculator-backend.js" zip CBECalculator.zip $list
{ "content_hash": "c18e38628939e12155e9d8f94cdeac6e", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 58, "avg_line_length": 24.52, "alnum_prop": 0.6394779771615008, "repo_name": "WWUCBE/cbe-calc", "id": "65da1d4c1bff319426f14249329e4ef70ee69f7e", "size": "666", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CBE_Chrome_Extension/createZip.sh", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "44038" }, { "name": "HTML", "bytes": "320173" }, { "name": "JavaScript", "bytes": "118032" }, { "name": "Python", "bytes": "234" }, { "name": "Shell", "bytes": "785" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.yzq.zxinglibrary.android.CaptureActivity"> <!-- 整体透明画布 --> <SurfaceView android:id="@+id/preview_view" android:layout_width="match_parent" android:layout_height="match_parent" /> <androidx.appcompat.widget.LinearLayoutCompat android:id="@+id/statusbarutil_offset_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="48dp" android:layout_gravity="top" android:background="#99000000"> <androidx.appcompat.widget.AppCompatImageView android:id="@+id/backIv" android:layout_width="42dp" android:layout_height="match_parent" android:padding="6dp" app:srcCompat="@drawable/ic_back" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="扫一扫" android:textColor="#ffffff" android:textSize="20sp" /> </RelativeLayout> <!-- 扫描取景框 --> <com.yzq.zxinglibrary.view.ViewfinderView android:id="@+id/viewfinder_view" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <androidx.appcompat.widget.LinearLayoutCompat android:id="@+id/bottomLayout" android:layout_width="match_parent" android:layout_height="96dp" android:layout_gravity="bottom" android:background="#99000000" android:orientation="horizontal"> <androidx.appcompat.widget.LinearLayoutCompat android:id="@+id/flashLightLayout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <androidx.appcompat.widget.AppCompatImageView android:id="@+id/flashLightIv" android:layout_width="36dp" android:layout_height="36dp" app:srcCompat="@drawable/ic_close" /> <TextView android:id="@+id/flashLightTv" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:gravity="center" android:text="打开闪光灯" android:textColor="#ffffff" /> </androidx.appcompat.widget.LinearLayoutCompat> <androidx.appcompat.widget.LinearLayoutCompat android:id="@+id/albumLayout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <androidx.appcompat.widget.AppCompatImageView android:id="@+id/albumIv" android:layout_width="36dp" android:layout_height="36dp" android:tint="#ffffffff" app:srcCompat="@drawable/ic_photo" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:gravity="center" android:text="相册" android:textColor="#ffffff" /> </androidx.appcompat.widget.LinearLayoutCompat> </androidx.appcompat.widget.LinearLayoutCompat> </androidx.appcompat.widget.LinearLayoutCompat> </RelativeLayout>
{ "content_hash": "e35dc106780109119c5bd677a150e5ff", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 74, "avg_line_length": 37.18181818181818, "alnum_prop": 0.5643476328072905, "repo_name": "humorousz/Exercises", "id": "bd76ae0ddd7291262bdd654d63c21db61fafccc2", "size": "4541", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MyApplication/zq-3rd-part/zxinglibrary/src/main/res/layout/activity_capture.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "415" }, { "name": "Java", "bytes": "736835" }, { "name": "Kotlin", "bytes": "12935" } ], "symlink_target": "" }
package java.util.regex; /** * The result of applying a {@code Pattern} to a given input. See {@link Pattern} for * example uses. */ public final class Matcher implements MatchResult { /** * Holds the pattern, that is, the compiled regular expression. */ private Pattern pattern; /** * Holds the input text. */ private String input; /** * Holds the start of the region, or 0 if the matching should start at the * beginning of the text. */ private int regionStart; /** * Holds the end of the region, or input.length() if the matching should * go until the end of the input. */ private int regionEnd; /** * Holds the position where the next find operation will take place. */ private int findPos; /** * Holds the position where the next append operation will take place. */ private int appendPos; /** * Reflects whether a match has been found during the most recent find * operation. */ private boolean matchFound; /** * Holds the offsets for the most recent match. */ private int[] matchOffsets; /** * Reflects whether the bounds of the region are anchoring. */ private boolean anchoringBounds = true; /** * Reflects whether the bounds of the region are transparent. */ private boolean transparentBounds; /** * Progress state from last match. */ private int progressFlags; /** * Creates a matcher for a given combination of pattern and input. Both * elements can be changed later on. * * @param pattern * the pattern to use. * @param input * the input to use. */ Matcher(Pattern pattern, CharSequence input) { usePattern(pattern); reset(input); } /** * Appends a literal part of the input plus a replacement for the current * match to a given {@link StringBuffer}. The literal part is exactly the * part of the input between the previous match and the current match. The * method can be used in conjunction with {@link #find()} and * {@link #appendTail(StringBuffer)} to walk through the input and replace * all occurrences of the {@code Pattern} with something else. * * @param buffer * the {@code StringBuffer} to append to. * @param replacement * the replacement text. * @return the {@code Matcher} itself. * @throws IllegalStateException * if no successful match has been made. */ public Matcher appendReplacement(StringBuffer buffer, String replacement) { buffer.append(input.substring(appendPos, start())); appendEvaluated(buffer, replacement); appendPos = end(); return this; } /** * Internal helper method to append a given string to a given string buffer. * If the string contains any references to groups, these are replaced by * the corresponding group's contents. * * @param buffer * the string buffer. * @param s * the string to append. */ private void appendEvaluated(StringBuffer buffer, String s) { boolean escape = false; boolean dollar = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '\\' && !escape) { escape = true; } else if (c == '$' && !escape) { dollar = true; } else if (c >= '0' && c <= '9' && dollar) { buffer.append(group(c - '0')); dollar = false; } else { buffer.append(c); dollar = false; escape = false; } } // This seemingly stupid piece of code reproduces a JDK bug. if (escape) { throw new ArrayIndexOutOfBoundsException(s.length()); } } /** * Resets the {@code Matcher}. This results in the region being set to the * whole input. Results of a previous find get lost. The next attempt to * find an occurrence of the {@link Pattern} in the string will start at the * beginning of the input. * * @return the {@code Matcher} itself. */ public Matcher reset() { return reset(input, 0, input.length()); } /** * Provides a new input and resets the {@code Matcher}. This results in the * region being set to the whole input. Results of a previous find get lost. * The next attempt to find an occurrence of the {@link Pattern} in the * string will start at the beginning of the input. * * @param input * the new input sequence. * * @return the {@code Matcher} itself. */ public Matcher reset(CharSequence input) { return reset(input, 0, input.length()); } /** * Resets the Matcher. A new input sequence and a new region can be * specified. Results of a previous find get lost. The next attempt to find * an occurrence of the Pattern in the string will start at the beginning of * the region. This is the internal version of reset() to which the several * public versions delegate. * * @param input * the input sequence. * @param start * the start of the region. * @param end * the end of the region. * * @return the matcher itself. */ private Matcher reset(CharSequence input, int start, int end) { if (input == null) { throw new IllegalArgumentException(); } if (start < 0 || end < 0 || start > input.length() || end > input.length() || start > end) { throw new IndexOutOfBoundsException(); } this.input = input.toString(); this.regionStart = start; this.regionEnd = end; matchFound = false; findPos = regionStart; appendPos = 0; return this; } /** * Sets a new pattern for the {@code Matcher}. Results of a previous find * get lost. The next attempt to find an occurrence of the {@link Pattern} * in the string will start at the beginning of the input. * * @param pattern * the new {@code Pattern}. * * @return the {@code Matcher} itself. */ public Matcher usePattern(Pattern pattern) { if (pattern == null) { throw new IllegalArgumentException(); } this.pattern = pattern; matchOffsets = new int[(groupCount() + 1) * 2]; matchFound = false; // If the pattern matches multiple lines, turn off anchoring bounds. anchoringBounds = (pattern.flags() & Pattern.MULTILINE) == 0; return this; } /** * Resets this matcher and sets a region. Only characters inside the region * are considered for a match. * * @param start * the first character of the region. * @param end * the first character after the end of the region. * @return the {@code Matcher} itself. */ public Matcher region(int start, int end) { return reset(input, start, end); } /** * Appends the (unmatched) remainder of the input to the given * {@link StringBuffer}. The method can be used in conjunction with * {@link #find()} and {@link #appendReplacement(StringBuffer, String)} to * walk through the input and replace all matches of the {@code Pattern} * with something else. * * @param buffer * the {@code StringBuffer} to append to. * @return the {@code StringBuffer}. * @throws IllegalStateException * if no successful match has been made. */ public StringBuffer appendTail(StringBuffer buffer) { if (appendPos < regionEnd) { buffer.append(input.substring(appendPos, regionEnd)); } return buffer; } /** * Replaces the first occurrence of this matcher's pattern in the input with * a given string. * * @param replacement * the replacement text. * @return the modified input string. */ public String replaceFirst(String replacement) { reset(); StringBuffer buffer = new StringBuffer(input.length()); if (find()) { appendReplacement(buffer, replacement); } return appendTail(buffer).toString(); } /** * Replaces all occurrences of this matcher's pattern in the input with a * given string. * * @param replacement * the replacement text. * @return the modified input string. */ public String replaceAll(String replacement) { reset(); StringBuffer buffer = new StringBuffer(input.length()); while (find()) { appendReplacement(buffer, replacement); } return appendTail(buffer).toString(); } /** * Returns the {@link Pattern} instance used inside this matcher. * * @return the {@code Pattern} instance. */ public Pattern pattern() { return pattern; } /** * Returns the text that matched a given group of the regular expression. * Explicit capturing groups in the pattern are numbered left to right in order * of their <i>opening</i> parenthesis, starting at 1. * The special group 0 represents the entire match (as if the entire pattern is surrounded * by an implicit capturing group). * For example, "a((b)c)" matching "abc" would give the following groups: * <pre> * 0 "abc" * 1 "bc" * 2 "b" * </pre> * * <p>An optional capturing group that failed to match as part of an overall * successful match (for example, "a(b)?c" matching "ac") returns null. * A capturing group that matched the empty string (for example, "a(b?)c" matching "ac") * returns the empty string. * * @throws IllegalStateException * if no successful match has been made. */ public native String group(int group) /*-[ [self ensureMatch]; nil_chk(matchOffsets_); int from = IOSIntArray_Get(matchOffsets_, group * 2); int to = IOSIntArray_Get(matchOffsets_, (group * 2) + 1); // On 64-bit systems NSNotFound gets truncated to -1 when stored in IOSIntArray. static const NSInteger notFound = (sizeof(int) < sizeof(NSInteger)) ? -1 : NSNotFound; if (from == notFound || to == notFound) { return nil; } else { return [nil_chk(input_) substring:from endIndex:to]; } ]-*/; /** * Returns the text that matched the whole regular expression. * * @return the text. * @throws IllegalStateException * if no successful match has been made. */ public String group() { return group(0); } /** * Returns the next occurrence of the {@link Pattern} in the input. The * method starts the search from the given character in the input. * * @param start * The index in the input at which the find operation is to * begin. If this is less than the start of the region, it is * automatically adjusted to that value. If it is beyond the end * of the region, the method will fail. * @return true if (and only if) a match has been found. */ public boolean find(int start) { findPos = start; if (findPos < regionStart) { findPos = regionStart; } else if (findPos >= regionEnd) { matchFound = false; return false; } matchFound = findImpl(findPos, false); if (matchFound) { findPos = matchOffsets[1]; } return matchFound; } /** * Returns the next occurrence of the {@link Pattern} in the input. If a * previous match was successful, the method continues the search from the * first character following that match in the input. Otherwise it searches * either from the region start (if one has been set), or from position 0. * * @return true if (and only if) a match has been found. */ public boolean find() { matchFound = findImpl(findPos, true); if (matchFound) { findPos = matchOffsets[1]; } return matchFound; } /** * Tries to match the {@link Pattern}, starting from the beginning of the * region (or the beginning of the input, if no region has been set). * Doesn't require the {@code Pattern} to match against the whole region. * * @return true if (and only if) the {@code Pattern} matches. */ public boolean lookingAt() { matchFound = findImpl(0, false); if (matchFound) { findPos = matchOffsets[1]; } return matchFound; } /** * Tries to match the {@link Pattern} against the entire region (or the * entire input, if no region has been set). * * @return true if (and only if) the {@code Pattern} matches the entire * region. */ public boolean matches() { matchFound = matchesImpl(); if (matchFound) { findPos = matchOffsets[1]; } return matchFound; } /** * Returns the index of the first character of the text that matched a given * group. * * @param group * the group, ranging from 0 to groupCount() - 1, with 0 * representing the whole pattern. * @return the character index. * @throws IllegalStateException * if no successful match has been made. */ public int start(int group) throws IllegalStateException { ensureMatch(); return matchOffsets[group * 2]; } /** * Returns the index of the first character following the text that matched * a given group. * * @param group * the group, ranging from 0 to groupCount() - 1, with 0 * representing the whole pattern. * @return the character index. * @throws IllegalStateException * if no successful match has been made. */ public int end(int group) { ensureMatch(); return matchOffsets[(group * 2) + 1]; } /** * Returns a replacement string for the given one that has all backslashes * and dollar signs escaped. * * @param s * the input string. * @return the input string, with all backslashes and dollar signs having * been escaped. */ public static String quoteReplacement(String s) { StringBuilder result = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '\\' || c == '$') { result.append('\\'); } result.append(c); } return result.toString(); } /** * Returns the index of the first character of the text that matched the * whole regular expression. * * @return the character index. * @throws IllegalStateException * if no successful match has been made. */ public int start() { return start(0); } /** * Returns the number of groups in the results, which is always equal to * the number of groups in the original regular expression. * * @return the number of groups. */ public int groupCount() { return groupCountImpl(); } /** * Returns the index of the first character following the text that matched * the whole regular expression. * * @return the character index. * @throws IllegalStateException * if no successful match has been made. */ public int end() { return end(0); } /** * Converts the current match into a separate {@link MatchResult} instance * that is independent from this matcher. The new object is unaffected when * the state of this matcher changes. * * @return the new {@code MatchResult}. * @throws IllegalStateException * if no successful match has been made. */ public MatchResult toMatchResult() { ensureMatch(); return new MatchResultImpl(input, matchOffsets); } /** * Determines whether this matcher has anchoring bounds enabled or not. When * anchoring bounds are enabled, the start and end of the input match the * '^' and '$' meta-characters, otherwise not. Anchoring bounds are enabled * by default. * * @param value * the new value for anchoring bounds. * @return the {@code Matcher} itself. */ public Matcher useAnchoringBounds(boolean value) { anchoringBounds = value; return this; } /** * Indicates whether this matcher has anchoring bounds enabled. When * anchoring bounds are enabled, the start and end of the input match the * '^' and '$' meta-characters, otherwise not. Anchoring bounds are enabled * by default. * * @return true if (and only if) the {@code Matcher} uses anchoring bounds. */ public boolean hasAnchoringBounds() { return anchoringBounds; } /** * Determines whether this matcher has transparent bounds enabled or not. * When transparent bounds are enabled, the parts of the input outside the * region are subject to lookahead and lookbehind, otherwise they are not. * Transparent bounds are disabled by default. * * @param value * the new value for transparent bounds. * @return the {@code Matcher} itself. */ public Matcher useTransparentBounds(boolean value) { transparentBounds = value; return this; } /** * Makes sure that a successful match has been made. Is invoked internally * from various places in the class. * * @throws IllegalStateException * if no successful match has been made. */ private void ensureMatch() { if (!matchFound) { throw new IllegalStateException("No successful match so far"); } } /** * Indicates whether this matcher has transparent bounds enabled. When * transparent bounds are enabled, the parts of the input outside the region * are subject to lookahead and lookbehind, otherwise they are not. * Transparent bounds are disabled by default. * * @return true if (and only if) the {@code Matcher} uses anchoring bounds. */ public boolean hasTransparentBounds() { return transparentBounds; } /** * Returns this matcher's region start, that is, the first character that is * considered for a match. * * @return the start of the region. */ public int regionStart() { return regionStart; } /** * Returns this matcher's region end, that is, the first character that is * not considered for a match. * * @return the end of the region. */ public int regionEnd() { return regionEnd; } /** * Indicates whether more input might change a successful match into an * unsuccessful one. * * @return true if (and only if) more input might change a successful match * into an unsuccessful one. */ public boolean requireEnd() { return requireEndImpl(); } /** * Indicates whether the last match hit the end of the input. * * @return true if (and only if) the last match hit the end of the input. */ public boolean hitEnd() { return hitEndImpl(); } private native boolean findImpl(int start, boolean continuing) /*-[ NSRegularExpression *regex = (NSRegularExpression *) self->pattern__->nativePattern_; NSMatchingOptions options = 0; if (!self->anchoringBounds_) { options |= NSMatchingWithoutAnchoringBounds; } if (!continuing && self->transparentBounds_) { options |= NSMatchingWithTransparentBounds; } NSRange range = NSMakeRange(self->regionStart__, self->regionEnd__ - self->regionStart__); // Use enumerateMatchesInString to get progress state. __block BOOL matched = NO; [regex enumerateMatchesInString:self->input_ options:options range:range usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) { if (match.range.location < (NSUInteger) start) { *stop = NO; } else { self->progressFlags_ = flags; // Update offsets. NSUInteger nGroups = [match numberOfRanges]; for (NSUInteger i = 0; i < nGroups; i++) { NSRange matchRange = [match rangeAtIndex:i]; [self->matchOffsets_ replaceIntAtIndex:i * 2 withInt:(int) matchRange.location]; [self->matchOffsets_ replaceIntAtIndex:(i * 2) + 1 withInt:(int) (matchRange.location + matchRange.length)]; } matched = [match range].length > 0; // No match if length is zero. *stop = YES; } }]; return matched; ]-*/; private native int groupCountImpl() /*-[ NSRegularExpression *regex = (NSRegularExpression *) self->pattern__->nativePattern_; return (int) regex.numberOfCaptureGroups; ]-*/; private native boolean hitEndImpl() /*-[ return (self->progressFlags_ | NSMatchingHitEnd) > 0; ]-*/; private native boolean matchesImpl() /*-[ NSRegularExpression *regex = (NSRegularExpression *) self->pattern__->nativePattern_; NSUInteger patternFlags = [regex options]; NSMatchingOptions options = 0; if (!self->anchoringBounds_) { options |= NSMatchingWithoutAnchoringBounds; } if (self->transparentBounds_ || (patternFlags & NSRegularExpressionAnchorsMatchLines) > 0) { options |= NSMatchingWithTransparentBounds; } NSUInteger length = self->regionEnd__ - self->regionStart__; NSRange searchRange = NSMakeRange(self->regionStart__, length); NSTextCheckingResult *match = [regex firstMatchInString:self->input_ options:options range:searchRange]; if (match == nil) { return NO; } // Update offsets. NSUInteger nGroups = [match numberOfRanges]; for (NSUInteger i = 0; i < nGroups; i++) { NSRange matchRange = [match rangeAtIndex:i]; [self->matchOffsets_ replaceIntAtIndex:i * 2 withInt:(int) matchRange.location]; [self->matchOffsets_ replaceIntAtIndex:(i * 2) + 1 withInt:(int) (matchRange.location + matchRange.length)]; } NSRange range = [match range]; return range.location == (NSUInteger) self->regionStart__ && range.length == length; ]-*/; private native boolean requireEndImpl() /*-[ return (self->progressFlags_ | NSMatchingRequiredEnd) > 0; ]-*/; }
{ "content_hash": "522e0151e3adba6030bef7be26aadf4e", "timestamp": "", "source": "github", "line_count": 726, "max_line_length": 100, "avg_line_length": 32.49586776859504, "alnum_prop": 0.5854526958290946, "repo_name": "csripada/j2objc", "id": "a709e8c9aed7c5f84d10a16b10803b57435f5ae0", "size": "24211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jre_emul/android/libcore/luni/src/main/java/java/util/regex/Matcher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "73214" }, { "name": "Java", "bytes": "19605389" }, { "name": "Objective-C", "bytes": "490140" }, { "name": "Shell", "bytes": "6473" } ], "symlink_target": "" }
package com.android.angle; import java.io.IOException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; /** * Main Activity * * @author Ivan Pajuelo * */ public class AngleActivity extends Activity { public AngleSurfaceView mGLSurfaceView; // The main GL View public XmlPullParser xmlParser; protected AngleUI mCurrentUI = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { Thread.sleep(100); mGLSurfaceView = new AngleSurfaceView(this); mGLSurfaceView.setAwake(true); mGLSurfaceView.start(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Set the current user interface * * @param currentUI */ public void setUI(AngleUI currentUI) { if (mCurrentUI != currentUI) { if (mCurrentUI != null) { mCurrentUI.onDeactivate(); mGLSurfaceView.removeObject(mCurrentUI); } mCurrentUI = currentUI; if (mCurrentUI != null) { mCurrentUI.onActivate(); mGLSurfaceView.addObject(mCurrentUI); } } } @Override public boolean onTouchEvent(MotionEvent event) { if (mCurrentUI != null) if (mCurrentUI.onTouchEvent(event)) return true; return super.onTouchEvent(event); } @Override public boolean onTrackballEvent(MotionEvent event) { if (mCurrentUI != null) if (mCurrentUI.onTrackballEvent(event)) return true; return super.onTrackballEvent(event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mCurrentUI != null) if (mCurrentUI.onKeyDown(keyCode, event)) return true; return super.onKeyDown(keyCode, event); } @Override protected void onPause() { super.onPause(); mGLSurfaceView.onPause(); if (mCurrentUI != null) mCurrentUI.onPause(); } @Override protected void onResume() { super.onResume(); mGLSurfaceView.onResume(); if (mCurrentUI != null) mCurrentUI.onResume(); } @Override public void finish() { mGLSurfaceView.delete(); super.finish(); } public boolean executeXML(int resId) { xmlParser = getResources().getXml(resId); Log.d("XML", "executeXML " + resId); return nextXMLCommand(); } public boolean nextXMLCommand() { try { xmlParser.next(); while ( ((xmlParser.getEventType() != XmlPullParser.START_TAG)|| (xmlParser.getDepth() != 2)) && (xmlParser.getEventType() != XmlPullParser.END_DOCUMENT) ) xmlParser.next();// skip comments if (xmlParser.getEventType() != XmlPullParser.END_DOCUMENT) { Log.d("XML", "nextXMLCommand"); executeXMLCommand(xmlParser.getName().toLowerCase()); return true; } else executeXMLCommand(null); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } protected void executeXMLCommand(String command) { } }
{ "content_hash": "6d17d5784afb58bfe2bcd02feee54a1f", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 158, "avg_line_length": 19.401273885350317, "alnum_prop": 0.6946815495732108, "repo_name": "jsaun/DungeonBrawlers", "id": "5d9eb065bc23471f15e115d294b6f6b62d636600", "size": "3046", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/android/angle/AngleActivity.java", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/*! \file printer_core.c \brief USB printer device class core functions \version 2020-08-01, V3.0.0, firmware for GD32F30x */ /* Copyright (c) 2020, GigaDevice Semiconductor Inc. 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 holder 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 HOLDER 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 "usbd_transc.h" #include "printer_core.h" #define USBD_VID 0x28E9U #define USBD_PID 0x028DU /* printer port status: paper not empty/selected/no error */ static uint8_t g_port_status = 0x18U; uint8_t g_printer_data_buf[PRINTER_OUT_PACKET]; uint8_t Printer_DEVICE_ID[DEVICE_ID_LEN] = { 0x00, 0x67, 'M', 'A', 'N', 'U', 'F', 'A', 'C', 'T', 'U', 'R', 'E', 'R', ':', 'G', 'I', 'G', 'A', ' ', 'D', 'E', 'V', 'I', 'C', 'E', '-', ';', 'C', 'O', 'M', 'M', 'A', 'N', 'D', ' ', 'S', 'E', 'T', ':', 'P', 'C', 'L', ',', 'M', 'P', 'L', ';', 'M', 'O', 'D', 'E', 'L', ':', 'L', 'a', 's', 'e', 'r', 'B', 'e', 'a', 'm', '?', ';', 'C', 'O', 'M', 'M', 'E', 'N', 'T', ':', 'G', 'o', 'o', 'd', ' ', '!', ';', 'A', 'C', 'T', 'I', 'V', 'E', ' ', 'C', 'O', 'M', 'M', 'A', 'N', 'D', ' ', 'S', 'E', 'T', ':', 'P', 'C', 'L', ';' }; /* USB standard device descriptor */ usb_desc_dev printer_dev_desc = { .header = { .bLength = USB_DEV_DESC_LEN, .bDescriptorType = USB_DESCTYPE_DEV, }, .bcdUSB = 0x0200U, .bDeviceClass = 0x00U, .bDeviceSubClass = 0x00U, .bDeviceProtocol = 0x00U, .bMaxPacketSize0 = USBD_EP0_MAX_SIZE, .idVendor = USBD_VID, .idProduct = USBD_PID, .bcdDevice = 0x0100U, .iManufacturer = STR_IDX_MFC, .iProduct = STR_IDX_PRODUCT, .iSerialNumber = STR_IDX_SERIAL, .bNumberConfigurations = USBD_CFG_MAX_NUM, }; /* USB device configuration descriptor */ usb_printer_desc_config_set printer_config_desc = { .config = { .header = { .bLength = sizeof(usb_desc_config), .bDescriptorType = USB_DESCTYPE_CONFIG }, .wTotalLength = USB_PRINTER_CONFIG_DESC_LEN, .bNumInterfaces = 0x01U, .bConfigurationValue = 0x01U, .iConfiguration = 0x00U, .bmAttributes = 0xA0U, .bMaxPower = 0x32U }, .printer_itf = { .header = { .bLength = sizeof(usb_desc_itf), .bDescriptorType = USB_DESCTYPE_ITF }, .bInterfaceNumber = 0x00U, .bAlternateSetting = 0x00U, .bNumEndpoints = 0x02U, .bInterfaceClass = USB_CLASS_PRINTER, .bInterfaceSubClass = USB_SUBCLASS_PRINTER, .bInterfaceProtocol = PROTOCOL_BI_DIRECTIONAL_ITF, .iInterface = 0x00U }, .printer_epin = { .header = { .bLength = sizeof(usb_desc_ep), .bDescriptorType = USB_DESCTYPE_EP }, .bEndpointAddress = PRINTER_IN_EP, .bmAttributes = USB_EP_ATTR_BULK, .wMaxPacketSize = PRINTER_IN_PACKET, .bInterval = 0x00U }, .printer_epout = { .header = { .bLength = sizeof(usb_desc_ep), .bDescriptorType = USB_DESCTYPE_EP }, .bEndpointAddress = PRINTER_OUT_EP, .bmAttributes = USB_EP_ATTR_BULK, .wMaxPacketSize = PRINTER_OUT_PACKET, .bInterval = 0x00U }, }; /* USB language ID Descriptor */ static usb_desc_LANGID usbd_language_id_desc = { .header = { .bLength = sizeof(usb_desc_LANGID), .bDescriptorType = USB_DESCTYPE_STR, }, .wLANGID = ENG_LANGID }; /* USB manufacture string */ static usb_desc_str manufacturer_string = { .header = { .bLength = USB_STRING_LEN(10U), .bDescriptorType = USB_DESCTYPE_STR, }, .unicode_string = {'G', 'i', 'g', 'a', 'D', 'e', 'v', 'i', 'c', 'e'} }; /* USB product string */ static usb_desc_str product_string = { .header = { .bLength = USB_STRING_LEN(16U), .bDescriptorType = USB_DESCTYPE_STR, }, .unicode_string = {'G', 'D', '3', '2', '-', 'U', 'S', 'B', '_', 'P', 'r', 'i', 'n', 't', 'e', 'r'} }; /* USBD serial string */ static usb_desc_str serial_string = { .header = { .bLength = USB_STRING_LEN(12U), .bDescriptorType = USB_DESCTYPE_STR, } }; /* USB string descriptor */ static uint8_t* usbd_msc_strings[] = { [STR_IDX_LANGID] = (uint8_t *)&usbd_language_id_desc, [STR_IDX_MFC] = (uint8_t *)&manufacturer_string, [STR_IDX_PRODUCT] = (uint8_t *)&product_string, [STR_IDX_SERIAL] = (uint8_t *)&serial_string }; usb_desc printer_desc = { .dev_desc = (uint8_t *)&printer_dev_desc, .config_desc = (uint8_t *)&printer_config_desc, .strings = usbd_msc_strings }; /* local function prototypes ('static') */ static uint8_t printer_init (usb_dev *udev, uint8_t config_index); static uint8_t printer_deinit (usb_dev *udev, uint8_t config_index); static uint8_t printer_req_handler (usb_dev *udev, usb_req *req); static void printer_data_in (usb_dev *udev, uint8_t ep_num); static void printer_data_out (usb_dev *udev, uint8_t ep_num); usb_class printer_class = { .init = printer_init, .deinit = printer_deinit, .req_process = printer_req_handler, .data_in = printer_data_in, .data_out = printer_data_out }; /*! \brief initialize the printer device \param[in] udev: pointer to USB device instance \param[in] config_index: configuration index \param[out] none \retval USB device operation status */ static uint8_t printer_init (usb_dev *udev, uint8_t config_index) { /* initialize the data Tx/Rx endpoint */ usbd_ep_init(udev, EP_BUF_SNG, BULK_TX_ADDR, &(printer_config_desc.printer_epin)); usbd_ep_init(udev, EP_BUF_SNG, BULK_RX_ADDR, &(printer_config_desc.printer_epout)); udev->ep_transc[EP_ID(PRINTER_IN_EP)][TRANSC_IN] = printer_class.data_in; udev->ep_transc[PRINTER_OUT_EP][TRANSC_OUT] = printer_class.data_out; /* prepare to receive data */ usbd_ep_recev(udev, PRINTER_OUT_EP, g_printer_data_buf, PRINTER_OUT_PACKET); return USBD_OK; } /*! \brief de-initialize the printer device \param[in] udev: pointer to USB device instance \param[in] config_index: configuration index \param[out] none \retval USB device operation status */ static uint8_t printer_deinit (usb_dev *udev, uint8_t config_index) { /* deinitialize the data Tx/Rx endpoint */ usbd_ep_deinit(udev, PRINTER_IN_EP); usbd_ep_deinit(udev, PRINTER_OUT_EP); return USBD_OK; } /*! \brief handle the printer class-specific requests \param[in] udev: pointer to USB device instance \param[in] req: device class-specific request \param[out] none \retval USB device operation status */ static uint8_t printer_req_handler (usb_dev *udev, usb_req *req) { uint8_t status = REQ_NOTSUPP; switch (req->bRequest) { case GET_DEVICE_ID: usb_transc_config(&udev->transc_in[0], Printer_DEVICE_ID, DEVICE_ID_LEN, 0U); status = REQ_SUPP; break; case GET_PORT_STATUS: usb_transc_config(&udev->transc_in[0], (uint8_t *)&g_port_status, 1U, 0U); status = REQ_SUPP; break; case SOFT_RESET: usbd_ep_recev(udev, PRINTER_OUT_EP, g_printer_data_buf, PRINTER_OUT_PACKET); status = REQ_SUPP; break; default: break; } return status; } /*! \brief handle printer data \param[in] udev: pointer to USB device instance \param[in] ep_num: endpoint number \param[out] none \retval none */ static void printer_data_in (usb_dev *udev, uint8_t ep_num) { } /*! \brief handle printer data \param[in] udev: pointer to USB device instance \param[in] ep_num: endpoint number \param[out] none \retval none */ static void printer_data_out (usb_dev *udev, uint8_t ep_num) { }
{ "content_hash": "cdf7c8738307530ba19991df2b02b7d3", "timestamp": "", "source": "github", "line_count": 310, "max_line_length": 102, "avg_line_length": 31.40967741935484, "alnum_prop": 0.5804662627092534, "repo_name": "hezlog/rt-thread", "id": "720bda45cf266bb06c6e6383c241b41b5f0dc635", "size": "9737", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "bsp/gd32/libraries/GD32F30x_Firmware_Library/GD32F30x_usbd_library/class/device/printer/Source/printer_core.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "11397093" }, { "name": "Batchfile", "bytes": "179616" }, { "name": "C", "bytes": "542194322" }, { "name": "C++", "bytes": "6056498" }, { "name": "CMake", "bytes": "148026" }, { "name": "CSS", "bytes": "9978" }, { "name": "DIGITAL Command Language", "bytes": "13234" }, { "name": "GDB", "bytes": "11796" }, { "name": "HTML", "bytes": "4371848" }, { "name": "Lex", "bytes": "7026" }, { "name": "Logos", "bytes": "7078" }, { "name": "M4", "bytes": "17515" }, { "name": "Makefile", "bytes": "268009" }, { "name": "Module Management System", "bytes": "1548" }, { "name": "Objective-C", "bytes": "4093973" }, { "name": "Pawn", "bytes": "1427" }, { "name": "Perl", "bytes": "9520" }, { "name": "Python", "bytes": "1008227" }, { "name": "RPC", "bytes": "14162" }, { "name": "Roff", "bytes": "4486" }, { "name": "Ruby", "bytes": "869" }, { "name": "Shell", "bytes": "407723" }, { "name": "TeX", "bytes": "3113" }, { "name": "Yacc", "bytes": "16084" } ], "symlink_target": "" }
package org.fujion.plotly.layout; import org.fujion.annotation.Option; import org.fujion.plotly.common.CalendarTypeEnum; import org.fujion.plotly.common.PolarDirectionEnum; /** * Layout options for polar angular axis. */ public class RadialAxisOptions extends AxisOptions { /** * The angle (in degrees) from which the radial axis is drawn. Note that by default, radial axis * line on the theta=0 line corresponds to a line pointing right (like what mathematicians * prefer). * <p> * Default: the first "polar.sector" angle. */ @Option public Integer angle; /** * Determines on which side of radial axis line the tick and tick labels appear. * <p> * Default: CLOCKWISE */ @Option public PolarDirectionEnum side; /** * The hover text formatting rule using d3 formatting mini-languages which are very similar to * those in Python. For numbers, see: * https://github.com/d3/d3-format/blob/master/README.md#locale_format And for dates see: * https://github.com/d3/d3-time-format/blob/master/README.md#locale_format We add one item to * d3's date formatter: "%{n}f" for fractional seconds with n digits. For example, "2016-10-13 * 09:15:23.456" with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" */ @Option public String hoverformat; /** * Determines whether and where ticks are drawn. */ @Option public TicksEnum ticks; /** * The tick length (in px). * <p> * Constraints: &ge;0 * <p> * Length: 5 */ @Option public Integer ticklen; /** * The tick width (in px). * <p> * Constraints: &ge;0 * <p> * Default: 1 */ @Option public Integer tickwidth; /** * The tick color; * <p> * Default: "#444" */ @Option public String tickcolor; /** * The layer on which this axis is displayed. Useful when used together with scatter-like traces * with "cliponaxis" set to "false" to show markers and/or text nodes above this axis. */ @Option public LayerEnum layer; /** * The calendar system to use for "range" and "tick0" if this is a date axis. This does not set * the calendar for interpreting data on this axis, that's specified in the trace or via the * global "layout.calendar" */ @Option public CalendarTypeEnum calendar; /** * */ @Option public Boolean visible; }
{ "content_hash": "ff7fe7b92c898562ebbc97369110d370", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 100, "avg_line_length": 26.239583333333332, "alnum_prop": 0.6236601826121477, "repo_name": "fujion/fujion-framework", "id": "6b38cf28f84e239f149e8f0e716286d3d5f38cdc", "size": "3159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fujion-plotly/src/main/java/org/fujion/plotly/layout/RadialAxisOptions.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "22117" }, { "name": "Groovy", "bytes": "38" }, { "name": "HTML", "bytes": "1136" }, { "name": "Java", "bytes": "2838298" }, { "name": "JavaScript", "bytes": "246823" }, { "name": "Shell", "bytes": "520" }, { "name": "TypeScript", "bytes": "6153" } ], "symlink_target": "" }
package org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer; import com.google.common.cache.LoadingCache; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.yarn.api.records.ContainerId; import java.util.concurrent.Future; public class LocalizerContext { private final String user; private final ContainerId containerId; private final Credentials credentials; private final LoadingCache<Path, Future<FileStatus>> statCache; public LocalizerContext(String user, ContainerId containerId, Credentials credentials) { this(user, containerId, credentials, null); } public LocalizerContext(String user, ContainerId containerId, Credentials credentials, LoadingCache<Path, Future<FileStatus>> statCache) { this.user = user; this.containerId = containerId; this.credentials = credentials; this.statCache = statCache; } public String getUser() { return user; } public ContainerId getContainerId() { return containerId; } public Credentials getCredentials() { return credentials; } public LoadingCache<Path, Future<FileStatus>> getStatCache() { return statCache; } }
{ "content_hash": "c1f80a84339e1007f408f6a29ff9b33e", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 77, "avg_line_length": 25.836734693877553, "alnum_prop": 0.7543443917851501, "repo_name": "srijeyanthan/hops", "id": "70deeb014f0a9deb4b175f7b2cacbb6ef1728558", "size": "2072", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/LocalizerContext.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "31146" }, { "name": "Batchfile", "bytes": "49561" }, { "name": "C", "bytes": "1065087" }, { "name": "C++", "bytes": "81364" }, { "name": "CMake", "bytes": "32686" }, { "name": "CSS", "bytes": "42221" }, { "name": "HTML", "bytes": "2031435" }, { "name": "Java", "bytes": "36323051" }, { "name": "JavaScript", "bytes": "4688" }, { "name": "Perl", "bytes": "18992" }, { "name": "Protocol Buffer", "bytes": "147182" }, { "name": "Python", "bytes": "11309" }, { "name": "Shell", "bytes": "159501" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "36114" } ], "symlink_target": "" }
function getAllImages({ props, firebase, path }) { return firebase .value(`competitions/${props.data.competitionKey}/images`) .then(images => path.success({ images: Object.keys(images.value || {}).reduce( (acc, userkey) => acc.concat(Object.keys(images.value[userkey] || {})), [] ), }) ) .catch(path.error); } module.exports = getAllImages;
{ "content_hash": "9d63743fb888a21ab0d581fd89a7b986", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 65, "avg_line_length": 26.25, "alnum_prop": 0.5642857142857143, "repo_name": "JohannesAnd/SKWebsite", "id": "8903483ff178c6e151170034b3588f643b3f1b8e", "size": "420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "service/taskHandlers/remove_competition/actions/getAllImages.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "4731" }, { "name": "JavaScript", "bytes": "279510" } ], "symlink_target": "" }
/*! ColVis 1.1.2 * ©2010-2015 SpryMedia Ltd - datatables.net/license */ /** * @summary ColVis * @description Controls for column visibility in DataTables * @version 1.1.2 * @file dataTables.colReorder.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2010-2015 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license/mit * * This source file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. * * For details please refer to: http://www.datatables.net */ (function(window, document, undefined) { var factory = function( $, DataTable ) { "use strict"; /** * ColVis provides column visibility control for DataTables * * @class ColVis * @constructor * @param {object} DataTables settings object. With DataTables 1.10 this can * also be and API instance, table node, jQuery collection or jQuery selector. * @param {object} ColVis configuration options */ var ColVis = function( oDTSettings, oInit ) { /* Santiy check that we are a new instance */ if ( !this.CLASS || this.CLASS != "ColVis" ) { alert( "Warning: ColVis must be initialised with the keyword 'new'" ); } if ( typeof oInit == 'undefined' ) { oInit = {}; } var camelToHungarian = $.fn.dataTable.camelToHungarian; if ( camelToHungarian ) { camelToHungarian( ColVis.defaults, ColVis.defaults, true ); camelToHungarian( ColVis.defaults, oInit ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for * ColVis instance. Augmented by ColVis.defaults */ this.s = { /** * DataTables settings object * @property dt * @type Object * @default null */ "dt": null, /** * Customisation object * @property oInit * @type Object * @default passed in */ "oInit": oInit, /** * Flag to say if the collection is hidden * @property hidden * @type boolean * @default true */ "hidden": true, /** * Store the original visibility settings so they could be restored * @property abOriginal * @type Array * @default [] */ "abOriginal": [] }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * Wrapper for the button - given back to DataTables as the node to insert * @property wrapper * @type Node * @default null */ "wrapper": null, /** * Activation button * @property button * @type Node * @default null */ "button": null, /** * Collection list node * @property collection * @type Node * @default null */ "collection": null, /** * Background node used for shading the display and event capturing * @property background * @type Node * @default null */ "background": null, /** * Element to position over the activation button to catch mouse events when using mouseover * @property catcher * @type Node * @default null */ "catcher": null, /** * List of button elements * @property buttons * @type Array * @default [] */ "buttons": [], /** * List of group button elements * @property groupButtons * @type Array * @default [] */ "groupButtons": [], /** * Restore button * @property restore * @type Node * @default null */ "restore": null }; /* Store global reference */ ColVis.aInstances.push( this ); /* Constructor logic */ this.s.dt = $.fn.dataTable.Api ? new $.fn.dataTable.Api( oDTSettings ).settings()[0] : oDTSettings; this._fnConstruct( oInit ); return this; }; ColVis.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get the ColVis instance's control button so it can be injected into the * DOM * @method button * @returns {node} ColVis button */ button: function () { return this.dom.wrapper; }, /** * Alias of `rebuild` for backwards compatibility * @method fnRebuild */ "fnRebuild": function () { this.rebuild(); }, /** * Rebuild the list of buttons for this instance (i.e. if there is a column * header update) * @method fnRebuild */ rebuild: function () { /* Remove the old buttons */ for ( var i=this.dom.buttons.length-1 ; i>=0 ; i-- ) { this.dom.collection.removeChild( this.dom.buttons[i] ); } this.dom.buttons.splice( 0, this.dom.buttons.length ); this.dom.groupButtons.splice(0, this.dom.groupButtons.length); if ( this.dom.restore ) { this.dom.restore.parentNode( this.dom.restore ); } /* Re-add them (this is not the optimal way of doing this, it is fast and effective) */ this._fnAddGroups(); this._fnAddButtons(); /* Update the checkboxes */ this._fnDrawCallback(); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @returns void * @private */ "_fnConstruct": function ( init ) { this._fnApplyCustomisation( init ); var that = this; var i, iLen; this.dom.wrapper = document.createElement('div'); this.dom.wrapper.className = "ColVis"; this.dom.button = $( '<button />', { 'class': !this.s.dt.bJUI ? "ColVis_Button ColVis_MasterButton" : "ColVis_Button ColVis_MasterButton ui-button ui-state-default" } ) .append( '<span>'+this.s.buttonText+'</span>' ) .bind( this.s.activate=="mouseover" ? "mouseover" : "click", function (e) { e.preventDefault(); that._fnCollectionShow(); } ) .appendTo( this.dom.wrapper )[0]; this.dom.catcher = this._fnDomCatcher(); this.dom.collection = this._fnDomCollection(); this.dom.background = this._fnDomBackground(); this._fnAddGroups(); this._fnAddButtons(); /* Store the original visibility information */ for ( i=0, iLen=this.s.dt.aoColumns.length ; i<iLen ; i++ ) { this.s.abOriginal.push( this.s.dt.aoColumns[i].bVisible ); } /* Update on each draw */ this.s.dt.aoDrawCallback.push( { "fn": function () { that._fnDrawCallback.call( that ); }, "sName": "ColVis" } ); /* If columns are reordered, then we need to update our exclude list and * rebuild the displayed list */ $(this.s.dt.oInstance).bind( 'column-reorder.dt', function ( e, oSettings, oReorder ) { for ( i=0, iLen=that.s.aiExclude.length ; i<iLen ; i++ ) { that.s.aiExclude[i] = oReorder.aiInvertMapping[ that.s.aiExclude[i] ]; } var mStore = that.s.abOriginal.splice( oReorder.iFrom, 1 )[0]; that.s.abOriginal.splice( oReorder.iTo, 0, mStore ); that.fnRebuild(); } ); $(this.s.dt.oInstance).bind( 'destroy.dt', function () { $(that.dom.wrapper).remove(); } ); // Set the initial state this._fnDrawCallback(); }, /** * Apply any customisation to the settings from the DataTables initialisation * @method _fnApplyCustomisation * @returns void * @private */ "_fnApplyCustomisation": function ( init ) { $.extend( true, this.s, ColVis.defaults, init ); // Slightly messy overlap for the camelCase notation if ( ! this.s.showAll && this.s.bShowAll ) { this.s.showAll = this.s.sShowAll; } if ( ! this.s.restore && this.s.bRestore ) { this.s.restore = this.s.sRestore; } // CamelCase to Hungarian for the column groups var groups = this.s.groups; var hungarianGroups = this.s.aoGroups; if ( groups ) { for ( var i=0, ien=groups.length ; i<ien ; i++ ) { if ( groups[i].title ) { hungarianGroups[i].sTitle = groups[i].title; } if ( groups[i].columns ) { hungarianGroups[i].aiColumns = groups[i].columns; } } } }, /** * On each table draw, check the visibility checkboxes as needed. This allows any process to * update the table's column visibility and ColVis will still be accurate. * @method _fnDrawCallback * @returns void * @private */ "_fnDrawCallback": function () { var columns = this.s.dt.aoColumns; var buttons = this.dom.buttons; var groups = this.s.aoGroups; var button; for ( var i=0, ien=buttons.length ; i<ien ; i++ ) { button = buttons[i]; if ( button.__columnIdx !== undefined ) { $('input', button).prop( 'checked', columns[ button.__columnIdx ].bVisible ); } } var allVisible = function ( columnIndeces ) { for ( var k=0, kLen=columnIndeces.length ; k<kLen ; k++ ) { if ( columns[columnIndeces[k]].bVisible === false ) { return false; } } return true; }; var allHidden = function ( columnIndeces ) { for ( var m=0 , mLen=columnIndeces.length ; m<mLen ; m++ ) { if ( columns[columnIndeces[m]].bVisible === true ) { return false; } } return true; }; for ( var j=0, jLen=groups.length ; j<jLen ; j++ ) { if ( allVisible(groups[j].aiColumns) ) { $('input', this.dom.groupButtons[j]).prop('checked', true); $('input', this.dom.groupButtons[j]).prop('indeterminate', false); } else if ( allHidden(groups[j].aiColumns) ) { $('input', this.dom.groupButtons[j]).prop('checked', false); $('input', this.dom.groupButtons[j]).prop('indeterminate', false); } else { $('input', this.dom.groupButtons[j]).prop('indeterminate', true); } } }, /** * Loop through the groups (provided in the settings) and create a button for each. * @method _fnAddgroups * @returns void * @private */ "_fnAddGroups": function () { var nButton; if ( typeof this.s.aoGroups != 'undefined' ) { for ( var i=0, iLen=this.s.aoGroups.length ; i<iLen ; i++ ) { nButton = this._fnDomGroupButton( i ); this.dom.groupButtons.push( nButton ); this.dom.buttons.push( nButton ); this.dom.collection.appendChild( nButton ); } } }, /** * Loop through the columns in the table and as a new button for each one. * @method _fnAddButtons * @returns void * @private */ "_fnAddButtons": function () { var nButton, columns = this.s.dt.aoColumns; if ( $.inArray( 'all', this.s.aiExclude ) === -1 ) { for ( var i=0, iLen=columns.length ; i<iLen ; i++ ) { if ( $.inArray( i, this.s.aiExclude ) === -1 ) { nButton = this._fnDomColumnButton( i ); nButton.__columnIdx = i; this.dom.buttons.push( nButton ); } } } if ( this.s.order === 'alpha' ) { this.dom.buttons.sort( function ( a, b ) { var titleA = columns[ a.__columnIdx ].sTitle; var titleB = columns[ b.__columnIdx ].sTitle; return titleA === titleB ? 0 : titleA < titleB ? -1 : 1; } ); } if ( this.s.restore ) { nButton = this._fnDomRestoreButton(); nButton.className += " ColVis_Restore"; this.dom.buttons.push( nButton ); } if ( this.s.showAll ) { nButton = this._fnDomShowXButton( this.s.showAll, true ); nButton.className += " ColVis_ShowAll"; this.dom.buttons.push( nButton ); } if ( this.s.showNone ) { nButton = this._fnDomShowXButton( this.s.showNone, false ); nButton.className += " ColVis_ShowNone"; this.dom.buttons.push( nButton ); } $(this.dom.collection).append( this.dom.buttons ); }, /** * Create a button which allows a "restore" action * @method _fnDomRestoreButton * @returns {Node} Created button * @private */ "_fnDomRestoreButton": function () { var that = this, dt = this.s.dt; return $( '<li class="ColVis_Special '+(dt.bJUI ? 'ui-button ui-state-default' : '')+'">'+ this.s.restore+ '</li>' ) .click( function (e) { for ( var i=0, iLen=that.s.abOriginal.length ; i<iLen ; i++ ) { that.s.dt.oInstance.fnSetColumnVis( i, that.s.abOriginal[i], false ); } that._fnAdjustOpenRows(); that.s.dt.oInstance.fnAdjustColumnSizing( false ); that.s.dt.oInstance.fnDraw( false ); } )[0]; }, /** * Create a button which allows show all and show node actions * @method _fnDomShowXButton * @returns {Node} Created button * @private */ "_fnDomShowXButton": function ( str, action ) { var that = this, dt = this.s.dt; return $( '<li class="ColVis_Special '+(dt.bJUI ? 'ui-button ui-state-default' : '')+'">'+ str+ '</li>' ) .click( function (e) { for ( var i=0, iLen=that.s.abOriginal.length ; i<iLen ; i++ ) { if (that.s.aiExclude.indexOf(i) === -1) { that.s.dt.oInstance.fnSetColumnVis( i, action, false ); } } that._fnAdjustOpenRows(); that.s.dt.oInstance.fnAdjustColumnSizing( false ); that.s.dt.oInstance.fnDraw( false ); } )[0]; }, /** * Create the DOM for a show / hide group button * @method _fnDomGroupButton * @param {int} i Group in question, order based on that provided in settings * @returns {Node} Created button * @private */ "_fnDomGroupButton": function ( i ) { var that = this, dt = this.s.dt, oGroup = this.s.aoGroups[i]; return $( '<li class="ColVis_Special '+(dt.bJUI ? 'ui-button ui-state-default' : '')+'">'+ '<label>'+ '<input type="checkbox" />'+ '<span>'+oGroup.sTitle+'</span>'+ '</label>'+ '</li>' ) .click( function (e) { var showHide = !$('input', this).is(":checked"); if ( e.target.nodeName.toLowerCase() !== "li" ) { showHide = ! showHide; } for ( var j=0 ; j < oGroup.aiColumns.length ; j++ ) { that.s.dt.oInstance.fnSetColumnVis( oGroup.aiColumns[j], showHide ); } } )[0]; }, /** * Create the DOM for a show / hide button * @method _fnDomColumnButton * @param {int} i Column in question * @returns {Node} Created button * @private */ "_fnDomColumnButton": function ( i ) { var that = this, column = this.s.dt.aoColumns[i], dt = this.s.dt; var title = this.s.fnLabel===null ? column.sTitle : this.s.fnLabel( i, column.sTitle, column.nTh ); return $( '<li '+(dt.bJUI ? 'class="ui-button ui-state-default"' : '')+'>'+ '<label>'+ '<input type="checkbox" />'+ '<span>'+title+'</span>'+ '</label>'+ '</li>' ) .click( function (e) { var showHide = !$('input', this).is(":checked"); if ( e.target.nodeName.toLowerCase() !== "li" ) { if ( e.target.nodeName.toLowerCase() == "input" || that.s.fnStateChange === null ) { showHide = ! showHide; } } /* Need to consider the case where the initialiser created more than one table - change the * API index that DataTables is using */ var oldIndex = $.fn.dataTableExt.iApiIndex; $.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that); // Optimisation for server-side processing when scrolling - don't do a full redraw if ( dt.oFeatures.bServerSide ) { that.s.dt.oInstance.fnSetColumnVis( i, showHide, false ); that.s.dt.oInstance.fnAdjustColumnSizing( false ); if (dt.oScroll.sX !== "" || dt.oScroll.sY !== "" ) { that.s.dt.oInstance.oApi._fnScrollDraw( that.s.dt ); } that._fnDrawCallback(); } else { that.s.dt.oInstance.fnSetColumnVis( i, showHide ); } $.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */ if ( that.s.fnStateChange !== null ) { if ( e.target.nodeName.toLowerCase() == "span" ) { e.preventDefault(); } that.s.fnStateChange.call( that, i, showHide ); } } )[0]; }, /** * Get the position in the DataTables instance array of the table for this * instance of ColVis * @method _fnDataTablesApiIndex * @returns {int} Index * @private */ "_fnDataTablesApiIndex": function () { for ( var i=0, iLen=this.s.dt.oInstance.length ; i<iLen ; i++ ) { if ( this.s.dt.oInstance[i] == this.s.dt.nTable ) { return i; } } return 0; }, /** * Create the element used to contain list the columns (it is shown and * hidden as needed) * @method _fnDomCollection * @returns {Node} div container for the collection * @private */ "_fnDomCollection": function () { return $('<ul />', { 'class': !this.s.dt.bJUI ? "ColVis_collection" : "ColVis_collection ui-buttonset ui-buttonset-multi" } ) .css( { 'display': 'none', 'opacity': 0, 'position': ! this.s.bCssPosition ? 'absolute' : '' } )[0]; }, /** * An element to be placed on top of the activate button to catch events * @method _fnDomCatcher * @returns {Node} div container for the collection * @private */ "_fnDomCatcher": function () { var that = this, nCatcher = document.createElement('div'); nCatcher.className = "ColVis_catcher"; $(nCatcher).click( function () { that._fnCollectionHide.call( that, null, null ); } ); return nCatcher; }, /** * Create the element used to shade the background, and capture hide events (it is shown and * hidden as needed) * @method _fnDomBackground * @returns {Node} div container for the background * @private */ "_fnDomBackground": function () { var that = this; var background = $('<div></div>') .addClass( 'ColVis_collectionBackground' ) .css( 'opacity', 0 ) .click( function () { that._fnCollectionHide.call( that, null, null ); } ); /* When considering a mouse over action for the activation, we also consider a mouse out * which is the same as a mouse over the background - without all the messing around of * bubbling events. Use the catcher element to avoid messing around with bubbling */ if ( this.s.activate == "mouseover" ) { background.mouseover( function () { that.s.overcollection = false; that._fnCollectionHide.call( that, null, null ); } ); } return background[0]; }, /** * Show the show / hide list and the background * @method _fnCollectionShow * @returns void * @private */ "_fnCollectionShow": function () { var that = this, i, iLen, iLeft; var oPos = $(this.dom.button).offset(); var nHidden = this.dom.collection; var nBackground = this.dom.background; var iDivX = parseInt(oPos.left, 10); var iDivY = parseInt(oPos.top + $(this.dom.button).outerHeight(), 10); if ( ! this.s.bCssPosition ) { nHidden.style.top = iDivY+"px"; nHidden.style.left = iDivX+"px"; } $(nHidden).css( { 'display': 'block', 'opacity': 0 } ); nBackground.style.bottom ='0px'; nBackground.style.right = '0px'; var oStyle = this.dom.catcher.style; oStyle.height = $(this.dom.button).outerHeight()+"px"; oStyle.width = $(this.dom.button).outerWidth()+"px"; oStyle.top = oPos.top+"px"; oStyle.left = iDivX+"px"; document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); document.body.appendChild( this.dom.catcher ); /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ $(nHidden).animate({"opacity": 1}, that.s.iOverlayFade); $(nBackground).animate({"opacity": 0.1}, that.s.iOverlayFade, 'linear', function () { /* In IE6 if you set the checked attribute of a hidden checkbox, then this is not visually * reflected. As such, we need to do it here, once it is visible. Unbelievable. */ if ( $.browser && $.browser.msie && $.browser.version == "6.0" ) { that._fnDrawCallback(); } }); /* Visual corrections to try and keep the collection visible */ if ( !this.s.bCssPosition ) { iLeft = ( this.s.sAlign=="left" ) ? iDivX : iDivX - $(nHidden).outerWidth() + $(this.dom.button).outerWidth(); nHidden.style.left = iLeft+"px"; var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); var iDocWidth = $(document).width(); if ( iLeft + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } } this.s.hidden = false; }, /** * Hide the show / hide list and the background * @method _fnCollectionHide * @returns void * @private */ "_fnCollectionHide": function ( ) { var that = this; if ( !this.s.hidden && this.dom.collection !== null ) { this.s.hidden = true; $(this.dom.collection).animate({"opacity": 0}, that.s.iOverlayFade, function (e) { this.style.display = "none"; } ); $(this.dom.background).animate({"opacity": 0}, that.s.iOverlayFade, function (e) { document.body.removeChild( that.dom.background ); document.body.removeChild( that.dom.catcher ); } ); } }, /** * Alter the colspan on any fnOpen rows */ "_fnAdjustOpenRows": function () { var aoOpen = this.s.dt.aoOpenRows; var iVisible = this.s.dt.oApi._fnVisbleColumns( this.s.dt ); for ( var i=0, iLen=aoOpen.length ; i<iLen ; i++ ) { aoOpen[i].nTr.getElementsByTagName('td')[0].colSpan = iVisible; } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static object methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Rebuild the collection for a given table, or all tables if no parameter given * @method ColVis.fnRebuild * @static * @param object oTable DataTable instance to consider - optional * @returns void */ ColVis.fnRebuild = function ( oTable ) { var nTable = null; if ( typeof oTable != 'undefined' ) { nTable = $.fn.dataTable.Api ? new $.fn.dataTable.Api( oTable ).table().node() : oTable.fnSettings().nTable; } for ( var i=0, iLen=ColVis.aInstances.length ; i<iLen ; i++ ) { if ( typeof oTable == 'undefined' || nTable == ColVis.aInstances[i].s.dt.nTable ) { ColVis.aInstances[i].fnRebuild(); } } }; ColVis.defaults = { /** * Mode of activation. Can be 'click' or 'mouseover' * @property activate * @type string * @default click */ active: 'click', /** * Text used for the button * @property buttonText * @type string * @default Show / hide columns */ buttonText: 'Show / hide columns', /** * List of columns (integers) which should be excluded from the list * @property aiExclude * @type array * @default [] */ aiExclude: [], /** * Show restore button * @property bRestore * @type boolean * @default false */ bRestore: false, /** * Restore button text * @property sRestore * @type string * @default Restore original */ sRestore: 'Restore original', /** * Show Show-All button * @property bShowAll * @type boolean * @default false */ bShowAll: false, /** * Show All button text * @property sShowAll * @type string * @default Restore original */ sShowAll: 'Show All', /** * Position of the collection menu when shown - align "left" or "right" * @property sAlign * @type string * @default left */ sAlign: 'left', /** * Callback function to tell the user when the state has changed * @property fnStateChange * @type function * @default null */ fnStateChange: null, /** * Overlay animation duration in mS * @property iOverlayFade * @type integer|false * @default 500 */ iOverlayFade: 500, /** * Label callback for column names. Takes three parameters: 1. the * column index, 2. the column title detected by DataTables and 3. the * TH node for the column * @property fnLabel * @type function * @default null */ fnLabel: null, /** * Indicate if the column list should be positioned by Javascript, * visually below the button or allow CSS to do the positioning * @property bCssPosition * @type boolean * @default false */ bCssPosition: false, /** * Group buttons * @property aoGroups * @type array * @default [] */ aoGroups: [], /** * Button ordering - 'alpha' (alphabetical) or 'column' (table column * order) * @property order * @type string * @default column */ order: 'column' }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static object properties * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Collection of all ColVis instances * @property ColVis.aInstances * @static * @type Array * @default [] */ ColVis.aInstances = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Name of this class * @constant CLASS * @type String * @default ColVis */ ColVis.prototype.CLASS = "ColVis"; /** * ColVis version * @constant VERSION * @type String * @default See code */ ColVis.VERSION = "1.1.2"; ColVis.prototype.VERSION = ColVis.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.7.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var init = oDTSettings.oInit; var colvis = new ColVis( oDTSettings, init.colVis || init.oColVis || {} ); return colvis.button(); }, "cFeature": "C", "sFeature": "ColVis" } ); } else { alert( "Warning: ColVis requires DataTables 1.7 or greater - www.datatables.net/download"); } // Make ColVis accessible from the DataTables instance $.fn.dataTable.ColVis = ColVis; $.fn.DataTable.ColVis = ColVis; return ColVis; }; // /factory // Define as an AMD module if possible if ( typeof xxdefine === 'function' && define.amd ) { define( ['jquery', 'datatables'], factory ); } else if ( typeof xxexports === 'object' ) { // Node/CommonJS factory( require('jquery'), require('datatables') ); } else if ( jQuery && !jQuery.fn.dataTable.ColVis ) { // Otherwise simply initialise as normal, stopping multiple evaluation factory( jQuery, jQuery.fn.dataTable ); } })(window, document);
{ "content_hash": "2392b2f8295b157a7db354c941ca50f3", "timestamp": "", "source": "github", "line_count": 1122, "max_line_length": 97, "avg_line_length": 24.092691622103388, "alnum_prop": 0.5857872151524119, "repo_name": "bugodelnya/scn-sdk-package", "id": "616dd5988ab760f0eb79660ff6a500220e416ee8", "size": "27034", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org.scn.community.databound/os/jquery-datatables/plugins/dataTables.colVis.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23519" }, { "name": "CSS", "bytes": "772428" }, { "name": "HTML", "bytes": "560792" }, { "name": "JavaScript", "bytes": "12677574" }, { "name": "Shell", "bytes": "297" }, { "name": "XSLT", "bytes": "552" } ], "symlink_target": "" }
package com.eduworks.cruncher.string; import java.io.InputStream; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.eduworks.lang.util.EwUri; import com.eduworks.resolver.Context; import com.eduworks.resolver.Cruncher; public class CruncherUrlEncode extends Cruncher { @Override public Object resolve(Context c, Map<String, String[]> parameters, Map<String, InputStream> dataStreams) throws JSONException { final String obj = getAsString("obj", c, parameters, dataStreams); if (obj == null) return null; return EwUri.encodeValue(obj); } @Override public String getDescription() { return "Performs URI encoding on a string."; } @Override public String getReturn() { return "String"; } @Override public String getAttribution() { return ATTRIB_NONE; } @Override public JSONObject getParameters() throws JSONException { return jo("obj", "String"); } }
{ "content_hash": "f97eb42fdaa00f94515d482b0a168e14", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 126, "avg_line_length": 20.708333333333332, "alnum_prop": 0.6991951710261569, "repo_name": "Eduworks/ew", "id": "75c3b554401c57b0263e1b8fe506c5b9269d0cb0", "size": "994", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ew.levr.base/src/main/java/com/eduworks/cruncher/string/CruncherUrlEncode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "8674" }, { "name": "Groovy", "bytes": "85" }, { "name": "Java", "bytes": "1614713" }, { "name": "JavaScript", "bytes": "18500" }, { "name": "Shell", "bytes": "127" } ], "symlink_target": "" }
""" * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. """ """ Django settings for udon project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ from djangae.settings_base import * # set up some AppEngine specific stuff from djangae.utils import find_project_root from django.core.urlresolvers import reverse_lazy from google.appengine.api.app_identity.app_identity import get_default_gcs_bucket_name # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os PROJECT_DIR = find_project_root() SITE_URL = "https://virtualart.chromeexperiments.com" SHORT_URL = "g.co/VirtualArtSessions" # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ from ..boot import get_app_config # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = get_app_config().secret_key # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = ( 'djangae', # Djangae needs to come before django apps in django 1.7 and above 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'djangosecure', 'csp', 'cspreports', 'djangae.contrib.security', 'udon' ) MIDDLEWARE_CLASSES = ( 'djangae.contrib.security.middleware.AppEngineSecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'csp.middleware.CSPMiddleware', 'djangosecure.middleware.SecurityMiddleware', ) DJANGO_TEMPLATE_LOADERS = [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader' ] TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(PROJECT_DIR, 'static', 'dist')], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ ('django.template.loaders.cached.Loader', DJANGO_TEMPLATE_LOADERS), ], 'context_processors': ( "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.core.context_processors.request", "udon.context_processor.context_processor" ) }, }] SECURE_CHECKS = [ "djangosecure.check.sessions.check_session_cookie_secure", "djangosecure.check.sessions.check_session_cookie_httponly", "djangosecure.check.djangosecure.check_security_middleware", "djangosecure.check.djangosecure.check_sts", "djangosecure.check.djangosecure.check_frame_deny", "djangosecure.check.djangosecure.check_ssl_redirect", "udon.checks.check_csp_is_not_report_only" ] CSP_REPORT_URI = reverse_lazy('report_csp') CSP_REPORTS_LOG = True CSP_REPORTS_LOG_LEVEL = 'warning' CSP_REPORTS_SAVE = True CSP_REPORTS_EMAIL_ADMINS = False ROOT_URLCONF = 'udon.urls' WSGI_APPLICATION = 'udon.wsgi.application' # Internationalization # https://docs.djangoproject.com/en/1.6/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/1.6/howto/static-files/ STATIC_URL = '/static/' # sensible default CPS settings, feel free to modify them CSP_DEFAULT_SRC = ( "'self'", "*.gstatic.com", "https://project-udon.appspot.com", "storage.googleapis.com", "http://virtualartsessions.chromeexperiments.com.global.prod.fastly.net", "https://virtualartsessions.global.ssl.fastly.net", ) CSP_STYLE_SRC = ( "'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://*.gstatic.com", "use.typekit.net", "https://use.typekit.net", ) CSP_FONT_SRC = ( "'self'", "themes.googleusercontent.com", "https://*.gstatic.com", "data:", ) CSP_FRAME_SRC = ( "'self'", "https://www.youtube.com", "www.google.com", "accounts.google.com", "apis.google.com", "plus.google.com", ) CSP_SCRIPT_SRC = ( "'self'", "'unsafe-inline'", "https://www.youtube.com", "https://s.ytimg.com", "*.googleanalytics.com", "*.google-analytics.com", "ajax.googleapis.com", "*.gstatic.com", "use.typekit.net", "https://use.typekit.net", ) CSP_IMG_SRC = ( "'self'", "data:", "s.ytimg.com", "*.google-analytics.com", "*.googleusercontent.com", "*.gstatic.com", "p.typekit.net", "https://p.typekit.net", ) CSP_CONNECT_SRC = ( "'self'", "plus.google.com", "www.google-analytics.com", ) BUCKET_KEY = get_default_gcs_bucket_name() DEFAULT_FILE_STORAGE = 'google.appengine.api.blobstore.blobstore_stub.BlobStorage' DJANGAE_RUNSERVER_IGNORED_FILES_REGEXES = [ '^.+$(?<!\.py)(?<!\.yaml)(?<!\.html)', ] # Note that these should match a directory name, not directory path: DJANGAE_RUNSERVER_IGNORED_DIR_REGEXES = [ r"^google_appengine$", r"^bower_components$", r"^node_modules$", r"^sitepackages$", ]
{ "content_hash": "7de42d3770f90b9c83ab1ded8930fcf9", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 86, "avg_line_length": 28.151219512195123, "alnum_prop": 0.6809911627101022, "repo_name": "dataarts/virtual-art-sessions", "id": "66913d57cf7996484081493e6b0924e1b18245ba", "size": "5771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "udon/conf/base.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "47466" }, { "name": "HTML", "bytes": "20496" }, { "name": "JavaScript", "bytes": "180874" }, { "name": "Python", "bytes": "32051" }, { "name": "Shell", "bytes": "1394" } ], "symlink_target": "" }
package ml.shifu.shifu.udf; import java.io.IOException; import java.util.List; import java.util.Random; import ml.shifu.shifu.container.obj.ColumnConfig; import ml.shifu.shifu.exception.ShifuErrorCode; import ml.shifu.shifu.exception.ShifuException; import org.apache.commons.lang.StringUtils; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; /** * <pre> * AddColumnNumUDF class is to convert tuple of row data into bag of column data * Its structure is like * { * (column-id, column-value, column-tag, column-score) * (column-id, column-value, column-tag, column-score) * ... * } */ public class AddColumnNumUDF extends AbstractTrainerUDF<DataBag> { private List<String> negTags; private Random random = new Random(System.currentTimeMillis()); private int weightedColumnNum = -1; public AddColumnNumUDF(String source, String pathModelConfig, String pathColumnConfig, String withScoreStr) throws Exception { super(source, pathModelConfig, pathColumnConfig); if(!StringUtils.isEmpty(this.modelConfig.getDataSet().getWeightColumnName())) { String weightColumnName = this.modelConfig.getDataSet().getWeightColumnName(); for(int i = 0; i < this.columnConfigList.size(); i++) { ColumnConfig config = this.columnConfigList.get(i); if(config.getColumnName().equals(weightColumnName)) { this.weightedColumnNum = i; break; } } } negTags = modelConfig.getNegTags(); } public DataBag exec(Tuple input) throws IOException { DataBag bag = BagFactory.getInstance().newDefaultBag(); TupleFactory tupleFactory = TupleFactory.getInstance(); if(input == null) { return null; } int size = input.size(); if(size == 0 || input.size() < this.columnConfigList.size()) { log.info("the input size - " + input.size() + ", while column size - " + columnConfigList.size()); throw new ShifuException(ShifuErrorCode.ERROR_NO_EQUAL_COLCONFIG); } if(input.get(tagColumnNum) == null) { throw new ShifuException(ShifuErrorCode.ERROR_NO_TARGET_COLUMN); } String tag = input.get(tagColumnNum).toString(); Double rate = modelConfig.getBinningSampleRate(); if(modelConfig.isBinningSampleNegOnly()) { if(negTags.contains(tag) && random.nextDouble() > rate) { return null; } } else { if(random.nextDouble() > rate) { return null; } } for(int i = 0; i < size; i++) { if(modelConfig.isCategoricalDisabled()) { try { Double.valueOf(input.get(i).toString()); } catch (Exception e) { continue; } } ColumnConfig config = columnConfigList.get(i); if(config.isCandidate()) { Tuple tuple = tupleFactory.newTuple(5); tuple.set(0, i); // Set Data tuple.set(1, input.get(i) == null ? null : input.get(i).toString()); // Set Tag tuple.set(2, tag); // set weights if(weightedColumnNum != -1) { try { tuple.set(3, Double.valueOf(input.get(weightedColumnNum).toString())); } catch (NumberFormatException e) { tuple.set(3, 1.0); } if(i == weightedColumnNum) { // weight and its column, set to 1 tuple.set(3, 1.0); } } else { tuple.set(3, 1.0); } // add random seed for distribution tuple.set(4, Math.abs(random.nextInt() % 300)); bag.add(tuple); } } return bag; } @Override public Schema outputSchema(Schema input) { try { Schema tupleSchema = new Schema(); tupleSchema.add(new FieldSchema("columnId", DataType.INTEGER)); tupleSchema.add(new FieldSchema("value", DataType.CHARARRAY)); tupleSchema.add(new FieldSchema("tag", DataType.CHARARRAY)); tupleSchema.add(new FieldSchema("weight", DataType.DOUBLE)); tupleSchema.add(new FieldSchema("rand", DataType.INTEGER)); return new Schema(new Schema.FieldSchema("columnInfos", new Schema(new Schema.FieldSchema("columnInfo", tupleSchema, DataType.TUPLE)), DataType.BAG)); } catch (IOException e) { log.error("Error in outputSchema", e); return null; } } }
{ "content_hash": "49bdf7be78d9e07d569c86a2e4849f28", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 115, "avg_line_length": 33.65359477124183, "alnum_prop": 0.5684598951252671, "repo_name": "aglne/shifu", "id": "3b43d48a8338bc12c306cb1bd31c2b2e942fbf92", "size": "5765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ml/shifu/shifu/udf/AddColumnNumUDF.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1551627" }, { "name": "PigLatin", "bytes": "19736" }, { "name": "Shell", "bytes": "9029" } ], "symlink_target": "" }
var IS_TEST_MODE = global.IS_TEST_MODE || false; var Emitter = require("events").EventEmitter; var util = require("util"); var os = require("os"); var fs = require("fs"); var colors = require("colors"); var _ = require("lodash"); var __ = require("../lib/fn.js"); var Repl = require("../lib/repl.js"); var Options = require("../lib/board.options.js"); var Pins = require("../lib/board.pins.js"); // var temporal = require("temporal"), var IO; // Environment Setup var boards = []; var rport = /usb|acm|^com/i; var port = ""; // TODO: // // At some point we should figure out a way to // make execution-on-board environments uniformally // detected and reported. // var isGalileo = (function() { var release = os.release(); return release.contains("yocto") || release.contains("edison"); })(); var isOnBoard = isGalileo; if (isOnBoard) { if (isGalileo) { IO = require("galileo-io"); } } /** * Process Codes * SIGHUP 1 Term Hangup detected on controlling terminal or death of controlling process * SIGINT 2 Term Interrupt from keyboard * SIGQUIT 3 Core Quit from keyboard * SIGILL 4 Core Illegal Instruction * SIGABRT 6 Core Abort signal from abort(3) * SIGFPE 8 Core Floating point exception * SIGKILL 9 Term Kill signal * SIGSEGV 11 Core Invalid memory reference * SIGPIPE 13 Term Broken pipe: write to pipe with no readers * SIGALRM 14 Term Timer signal from alarm(2) * SIGTERM 15 Term Termination signal * * * * http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Batch/exitcode.html * */ var Serial = { used: [], attempts: [], detect: function(callback) { var serialport = IS_TEST_MODE ? require("../test/mock-serial") : require("serialport"); // Request a list of available ports, from // the result set, filter for valid paths // via known path pattern match. serialport.list(function(err, result) { var ports, length; ports = result.filter(function(val) { var available = true; // Match only ports that Arduino cares about // ttyUSB#, cu.usbmodem#, COM# if (!rport.test(val.comName)) { available = false; } // Don't allow already used/encountered usb device paths if (Serial.used.indexOf(val.comName) > -1) { available = false; } return available; }).map(function(val) { return val.comName; }); length = ports.length; // If no ports are detected... if (!length) { // Create an attempt counter if (!Serial.attempts[Serial.used.length]) { Serial.attempts[Serial.used.length] = 0; // Log notification... this.info("Looking for connected device", ""); } // Set the attempt number Serial.attempts[Serial.used.length]++; // Retry Serial connection Serial.detect.call(this, callback); return; } this.info( "Device(s)", ports.toString().grey ); // Get the first available device path from the list of // detected ports callback.call(this, ports[0]); }.bind(this)); }, connect: function(portOrPath, callback) { var IO = require("firmata").Board; var err, io, isConnected, path, type; if (typeof portOrPath === "object" && portOrPath.path) { // // Board({ port: SerialPort Object }) // path = portOrPath.path; this.info( "SerialPort", path.grey ); } else { // // Board({ port: path String }) // // Board() // ie. auto-detected // path = portOrPath; } // Add the usb device path to the list of device paths that // are currently in use - this is used by the filter function // above to remove any device paths that we've already encountered // or used to avoid blindly attempting to reconnect on them. Serial.used.push(path); try { io = new IO(portOrPath, function(error) { if (error !== undefined) { err = error; } callback.call(this, err, "ready", io); }.bind(this)); // Extend io instance with special expandos used // by Johny-Five for the IO Plugin system. io.name = "Firmata"; io.transport = "Serialport"; io.defaultLed = 13; io.port = path; // Made this far, safely connected isConnected = true; } catch (error) { err = error; } if (err) { err = err.message || err; } // Determine the type of event that will be passed on to // the board emitter in the callback passed to Serial.detect(...) type = isConnected ? "connect" : "error"; // Execute "connect" callback callback.call(this, err, type, io); } }; /** * Board * @constructor * * @param {Object} opts */ function Board(opts) { if (!(this instanceof Board)) { return new Board(opts); } // Ensure opts is an object opts = opts || {}; var inject, isPostponed; inject = {}; // Initialize this Board instance with // param specified properties. _.assign(this, opts); this.timer = null; this.isConnected = false; // Easily track state of hardware this.isReady = false; // Initialize instance property to reference io board this.io = this.io || null; // Registry of devices by pin address this.register = []; // Identify for connect hardware cache if (!this.id) { this.id = __.uid(); } // If no debug flag, default to true if (!("debug" in this)) { this.debug = true; } if (!("repl" in this)) { this.repl = true; } // Specially processed pin capabilities object // assigned when board is initialized and ready this.pins = null; // Human readable name (if one can be detected) this.type = ""; // Create a Repl instance and store as // instance property of this io/board. // This will reduce the amount of boilerplate // code required to _always_ have a Repl // session available. // // If a sesssion exists, use it // (instead of creating a new session) // if (this.repl) { if (Repl.ref) { inject[this.id] = this; Repl.ref.on("ready", function() { Repl.ref.inject(inject); }); this.repl = Repl.ref; } else { inject[this.id] = inject.board = this; this.repl = new Repl(inject); } } if (opts.io) { // If you already have a connected io instance this.io = opts.io; this.isReady = opts.io.isReady; this.transport = this.io.transport || "unknown transport"; this.port = this.io.name; this.pins = Board.Pins(this); } else { if (isOnBoard) { this.io = new IO(); this.port = this.io.name; } else { if (this.port && opts.port) { Serial.connect.call(this, this.port, broadcast); } else { // TODO: refactor to do the path lookups // as soon as this file is required. Serial.detect.call(this, function(path) { Serial.connect.call(this, path, broadcast); }); } } } // Either an IO instance was provided or isOnBoard is true if (!opts.port && this.io !== null) { this.info( "Device(s)", (this.io.name || "unknown").grey ); isPostponed = false; ["connect", "ready"].forEach(function(type) { if (this.io.isReady) { broadcast.call(this, null, type, this.io); } else { this.io.once(type, function() { // Since connection and readiness happen asynchronously, // it's actually possible for Johnny-Five to receive the // events out of order and that should be ok. if (type === "ready" && !this.isConnected) { isPostponed = true; } else { broadcast.call(this, null, type, this.io); } if (type === "connect" && isPostponed) { broadcast.call(this, null, "ready", this.io); } }.bind(this)); } }, this); } // Cache instance to allow access from module constructors boards.push(this); } function broadcast(err, type, io) { if (err) { this.error("Board", err); } else { // Assign found io to instance if (!this.io) { this.io = io; } } if (type === "connect") { this.isConnected = true; // 10 Second timeout... // // If "ready" hasn't fired and cleared the timer within // 10 seconds of the connect event, then it's likely // there is an issue with the device or firmware. this.timer = setTimeout(function() { this.error( "Device or Firmware Error", "A timeout occurred while connecting to the Board. \n" + "Please check that you've properly flashed the board with the correct firmware." ); process.exit(15); }.bind(this), 1e5); } if (type === "ready") { clearTimeout(this.timer); // Update instance `ready` flag this.isReady = true; this.port = io.port || io.name; this.pins = Board.Pins(this); this.info( "Connected", this.port.grey ); // In multi-board mode, block the REPL from // activation. This will be started directly // by the Board.Array constructor. if (!Repl.isBlocked) { process.stdin.emit("data", "1"); } if (io.name !== "Mock") { process.on("SIGINT", function() { this.warn("Board", "Closing."); process.exit(0); }.bind(this)); } // Bubble "string" events from IO layer io.on("string", function(data) { this.emit("string", data); }.bind(this)); } // process.on("SIGINT", function() { // console.log( "exit...." ); // // On ^c, make sure we close the process after the // // io and serialport are closed. Approx 100ms // // TODO: this sucks, need better solution // setTimeout(function() { // process.exit(); // }, 100); // }.bind(this)); // emit connect|ready event this.emit(type, err); } // Inherit event api util.inherits(Board, Emitter); /** * pinMode, analogWrite, analogRead, digitalWrite, digitalRead * * Pass through methods */ [ "pinMode", "analogWrite", "analogRead", "digitalWrite", "digitalRead" ].forEach(function(method) { Board.prototype[method] = function(pin, arg) { this.io[method](pin, arg); return this; }; }); Board.prototype.serialize = function(filter) { var blacklist, special; blacklist = this.serialize.blacklist; special = this.serialize.special; return JSON.stringify( this.register.map(function(device) { return Object.getOwnPropertyNames(device).reduce(function(data, prop) { var value = device[prop]; if (blacklist.indexOf(prop) === -1 && typeof value !== "function") { data[prop] = special[prop] ? special[prop](value) : value; if (filter) { data[prop] = filter(prop, data[prop], device); } } return data; }, {}); }, this) ); }; Board.prototype.serialize.blacklist = [ "board", "io", "_events" ]; Board.prototype.samplingInterval = function(ms) { if (this.io.setSamplingInterval) { this.io.setSamplingInterval(ms); } else { console.log("This IO plugin does not implement an interval adjustment method"); } return this; }; Board.prototype.serialize.special = { mode: function(value) { return ["INPUT", "OUTPUT", "ANALOG", "PWM", "SERVO"][value] || "unknown"; } }; /** * shiftOut * */ Board.prototype.shiftOut = function(dataPin, clockPin, isBigEndian, value) { var mask, write; write = function(value, mask) { this.digitalWrite(clockPin, this.io.LOW); this.digitalWrite( dataPin, this.io[value & mask ? "HIGH" : "LOW"] ); this.digitalWrite(clockPin, this.io.HIGH); }.bind(this); if (arguments.length === 3) { value = arguments[2]; isBigEndian = true; } if (isBigEndian) { for (mask = 128; mask > 0; mask = mask >> 1) { write(value, mask); } } else { for (mask = 0; mask < 128; mask = mask << 1) { write(value, mask); } } }; Board.prototype.log = function( /* type, module, message [, long description] */ ) { var args = [].slice.call(arguments), type = args.shift(), module = args.shift(), message = args.shift(), color = Board.prototype.log.types[type]; if (this.debug) { console.log([ // Timestamp String(+new Date()).grey, // Module, color matches type of log module.magenta, // Message message[color], // Miscellaneous args args.join(", ") ].join(" ")); } }; Board.prototype.log.types = { error: "red", fail: "orange", warn: "yellow", info: "cyan" }; // Make shortcuts to all logging methods Object.keys(Board.prototype.log.types).forEach(function(type) { Board.prototype[type] = function() { var args = [].slice.call(arguments); args.unshift(type); this.log.apply(this, args); }; }); /** * delay, loop, queue * * Pass through methods to temporal */ /* [ "delay", "loop", "queue" ].forEach(function( method ) { Board.prototype[ method ] = function( time, callback ) { temporal[ method ]( time, callback ); return this; }; }); // Alias wait to delay to match existing Johnny-five API Board.prototype.wait = Board.prototype.delay; */ // -----THIS IS A TEMPORARY FIX UNTIL THE ISSUES WITH TEMPORAL ARE RESOLVED----- // Aliasing. // (temporary, while ironing out API details) // The idea is to match existing hardware programming apis // or simply find the words that are most intuitive. // Eventually, there should be a queuing process // for all new callbacks added // // TODO: Repalce with temporal or compulsive API Board.prototype.wait = function(time, callback) { setTimeout(callback.bind(this), time); return this; }; Board.prototype.loop = function(time, callback) { setInterval(callback.bind(this), time); return this; }; // ---------- // Static API // ---------- // Board.map( val, fromLow, fromHigh, toLow, toHigh ) // // Re-maps a number from one range to another. // Based on arduino map() Board.map = __.map; Board.fmap = __.fmap; // Board.constrain( val, lower, upper ) // // Constrains a number to be within a range. // Based on arduino constrain() Board.constrain = __.constrain; // Board.range( upper ) // Board.range( lower, upper ) // Board.range( lower, upper, tick ) // // Returns a new array range // Board.range = __.range; // Board.range.prefixed( prefix, upper ) // Board.range.prefixed( prefix, lower, upper ) // Board.range.prefixed( prefix, lower, upper, tick ) // // Returns a new array range, each value prefixed // Board.range.prefixed = __.range.prefixed; // Board.uid() // // Returns a reasonably unique id string // Board.uid = __.uid; // Board.mount() // Board.mount( index ) // Board.mount( object ) // // Return hardware instance, based on type of param: // @param {arg} // object, user specified // number/index, specified in cache // none, defaults to first in cache // // Notes: // Used to reduce the amount of boilerplate // code required in any given module or program, by // giving the developer the option of omitting an // explicit Board reference in a module // constructor's options Board.mount = function(arg) { var index = typeof arg === "number" && arg, hardware; // board was explicitly provided if (arg && arg.board) { return arg.board; } // index specified, attempt to return // hardware instance. Return null if not // found or not available if (index) { hardware = boards[index]; return hardware && hardware || null; } // If no arg specified and hardware instances // exist in the cache if (boards.length) { return boards[0]; } // No mountable hardware return null; }; /** * Board.Device * * Initialize a new device instance * * Board.Device is a |this| senstive constructor, * and must be called as: * * Board.Device.call( this, opts ); * * * * TODO: Migrate all constructors to use this * to avoid boilerplate */ Board.Device = function(opts) { // Board specific properties this.board = Board.mount(opts); this.io = this.board.io; // Device/Module instance properties this.id = opts.id || null; // Pin or Pins address(es) opts = Board.Pins.normalize(opts, this.board); if (typeof opts.pins !== "undefined") { this.pins = opts.pins || []; } if (typeof opts.pin !== "undefined") { this.pin = opts.pin || 0; } this.board.register.push(this); }; /** * Pin Capability Signature Mapping */ Board.Pins = Pins; Board.Options = Options; // Define a user-safe, unwritable hardware cache access Object.defineProperty(Board, "cache", { get: function() { return boards; } }); /** * Board event constructor. * opts: * type - event type. eg: "read", "change", "up" etc. * target - the instance for which the event fired. * 0..* other properties */ Board.Event = function(opts) { if (!(this instanceof Board.Event)) { return new Board.Event(opts); } opts = opts || {}; // default event is read this.type = opts.type || "read"; // actual target instance this.target = opts.target || null; // Initialize this Board instance with // param specified properties. _.assign(this, opts); }; /** * Boards or Board.Array; Used when the program must connect to * more then one board. * * @memberof Board * * @param {Array} ports List of port objects { id: ..., port: ... } * List of id strings (initialized in order) * * @return {Boards} board object references */ Board.Array = function(ports) { if (!(this instanceof Board.Array)) { return new Board.Array(ports); } if (!Array.isArray(ports)) { throw new Error("Expected ports to be an array"); } Array.call(this, ports.length); this.length = 0; var initialized, count; initialized = {}; count = ports.length; // Block initialization of the program's // REPL until all boards are ready. Repl.isBlocked = true; ports.forEach(function(port, k) { var opts; if (typeof port === "string") { opts = { id: port }; } else { opts = port; } this[k] = initialized[opts.id] = new Board(opts); this[k].on("ready", function() { this[k].info("Board ID: ", opts.id.green); if (!--count) { Repl.isBlocked = false; process.stdin.emit("data", "1"); this.emit("ready", initialized); } }.bind(this)); this.length++; }, this); }; util.inherits(Board.Array, Emitter); Board.Array.prototype.each = Array.prototype.forEach; if (IS_TEST_MODE) { Board.__spy = { Serial: Serial }; } module.exports = Board; // References: // http://arduino.cc/en/Main/arduinoBoardUno
{ "content_hash": "f91b18404da1b2c076f7a3c7c71e1c26", "timestamp": "", "source": "github", "line_count": 835, "max_line_length": 90, "avg_line_length": 22.851497005988023, "alnum_prop": 0.5983963104659085, "repo_name": "joelunmsm2003/arduino", "id": "23d27b43793c822aa8402b814fd31399d9636750", "size": "19081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/board.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "661188" } ], "symlink_target": "" }
module Hbc class CLI class Edit def self.exec_editor(*command) editor_commands << command end def self.reset! @editor_commands = [] end def self.editor_commands @editor_commands ||= [] end end end end describe Hbc::CLI::Edit, :cask do before(:each) do Hbc::CLI::Edit.reset! end it "opens the editor for the specified Cask" do Hbc::CLI::Edit.run("local-caffeine") expect(Hbc::CLI::Edit.editor_commands).to eq [ [Hbc::CaskLoader.path("local-caffeine")], ] end it "throws away additional arguments and uses the first" do Hbc::CLI::Edit.run("local-caffeine", "local-transmission") expect(Hbc::CLI::Edit.editor_commands).to eq [ [Hbc::CaskLoader.path("local-caffeine")], ] end it "raises an exception when the Cask doesnt exist" do expect { Hbc::CLI::Edit.run("notacask") }.to raise_error(Hbc::CaskUnavailableError) end describe "when no Cask is specified" do it "raises an exception" do expect { Hbc::CLI::Edit.run }.to raise_error(Hbc::CaskUnspecifiedError) end end describe "when no Cask is specified, but an invalid option" do it "raises an exception" do expect { Hbc::CLI::Edit.run("--notavalidoption") }.to raise_error(Hbc::CaskUnspecifiedError) end end end
{ "content_hash": "88d10cba6fab585297f881a723e980cb", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 64, "avg_line_length": 23.271186440677965, "alnum_prop": 0.6263656227239621, "repo_name": "rwhogg/brew", "id": "f5f98afc8738908013e404842c7f26af2c55e1e5", "size": "1399", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Library/Homebrew/test/cask/cli/edit_spec.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "HTML", "bytes": "9583" }, { "name": "PostScript", "bytes": "485" }, { "name": "Roff", "bytes": "60517" }, { "name": "Ruby", "bytes": "1816180" }, { "name": "Shell", "bytes": "69081" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "716f7f836ded3bd7f85597607989fc9a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "ef87912ffadbe938be5b9a1afe682c76afd56841", "size": "179", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex banksii/ Syn. Carex promaucana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
'use babel'; import SubAtom from 'sub-atom'; // css classes on the status items that we don't want // to be serialized const ignoredCSSClasses = /(^|\s)\S*(inline-block)\S*/g; var disposables; export function activate() { disposables = new SubAtom(); atom.packages.onDidActivateInitialPackages(() => { process.nextTick(() => { handleEvents(); setInitialOrder(); }); }); } export function deactivate() { disposables.dispose(); disposables = null; } function handleEvents() { disposables.add('status-bar', 'mousedown', '.status-bar-left > *, .status-bar-right > *', dragStart); } var dragDisposable; function dragStart(event) { if (event.which != 1) return; event.preventDefault(); var currentItem = event.currentTarget; dragDisposable = new SubAtom(); dragDisposable.add(document.body, 'mousemove', mousemoveEvent => drag(currentItem, mousemoveEvent)); dragDisposable.add(document.body, 'mouseup mouseleave', () => dragEnd(currentItem)); currentItem.classList.add('dragging'); document.querySelector('status-bar').classList.add('dragging'); } function drag(currentItem, event) { var {pageX} = event; var previousItem = getNextItem(currentItem, true); var nextItem = getNextItem(currentItem); if (previousItem && pageX < Math.round(previousItem.offsetLeft / 10) * 10 + previousItem.clientWidth) { var previousOffset = Math.round(previousItem.offsetLeft / 10) * 10; var previousWidth = previousItem.clientWidth; if (pageX > previousOffset + previousWidth / 2) { previousItem.parentNode.insertBefore(currentItem, previousItem.nextSibling); } else { previousItem.parentNode.insertBefore(currentItem, previousItem); } } else if (nextItem && pageX > Math.round(nextItem.offsetLeft / 10 * 10)) { var nextOffset = Math.round(nextItem.offsetLeft / 10) * 10; var nextWidth = nextItem.clientWidth; if (pageX < nextOffset + nextWidth / 2) { nextItem.parentNode.insertBefore(currentItem, nextItem); } else { nextItem.parentNode.insertBefore(currentItem, nextItem.nextSibling); } } } function dragEnd(currentItem) { if (dragDisposable) dragDisposable.dispose(); dragDisposable = null; currentItem.classList.remove('dragging'); document.querySelector('status-bar').classList.remove('dragging'); saveOrder(); } function getNextItem(currentItem, reverse = false) { var statusItems = document.querySelectorAll('.status-bar-left > *, .status-bar-right > *'); var currentIndex = Array.prototype.indexOf.call(statusItems, currentItem); while (currentIndex >= 0 && currentIndex < statusItems.length) { currentIndex += Math.pow(-1, reverse); // -1 if reverse == true, 1 otherwise let item = statusItems[currentIndex]; if (isVisible(item)) return item; } } function isVisible(el) { if (!isHTMLElement(el)) return false; var {display, visibility, width} = window.getComputedStyle(el); width = parseInt(width) || el.clientWidth; return display != 'none' && visibility != 'hidden' && width > 0; } function saveOrder() { for (let side of ['left', 'right']) { let statusItems = document.querySelectorAll(`status-bar .status-bar-${side} > *`); atom.config.set(`move-status-items.${side}`, serializeStatusItems(statusItems)); } } function serializeStatusItems(statusItems) { return Array.prototype.map.call(statusItems, statusItem => { if (!isHTMLElement(statusItem)) return ''; return serializeStatusItem(statusItem); }); } function serializeStatusItem(statusItem) { return statusItem.tagName + serializeClassName(statusItem) + serializeAttribute(statusItem, 'is'); } function serializeClassName(el) { if (!el || !el.className) return ''; var className = el.className.replace(ignoredCSSClasses, '').trim(); if (!className) return ''; return className.replace(/(^|\s+)/g, '.'); } function serializeAttribute(el, attr) { var value = el.getAttribute(attr); if (!value) return ''; return `[${attr}="${value}"]`; } function setInitialOrder() { var statusBar = document.querySelector('status-bar'); var config = atom.config.get('move-status-items'); for (let side in config) { if (!config.hasOwnProperty(side)) continue; let statusItemContainer = statusBar.querySelector(`.status-bar-${side}`); for (let serializedStatusItem of config[side]) { let statusItem = statusBar.querySelector(serializedStatusItem); if (!isHTMLElement(statusItem)) continue; if (statusItemContainer.contains(statusItem)) continue; if (statusItem.contains(statusItemContainer)) continue; statusItemContainer.appendChild(statusItem); } } } function isHTMLElement(el) { return el instanceof HTMLElement; }
{ "content_hash": "398c654f19794bd2c028ce5001311979", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 105, "avg_line_length": 33.935251798561154, "alnum_prop": 0.7048971804112784, "repo_name": "olmokramer/atom-move-status-items", "id": "2a5f849e314e11139a239d4d0441cc97e6c464ce", "size": "4717", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/move-status-items.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "40" }, { "name": "JavaScript", "bytes": "4429" } ], "symlink_target": "" }
<html> <head> <meta charset="UTF-8"> <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="//code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script> <script src="../js/formEnterprise.js"></script> <link href="../dist/css/sb-admin-2.css" rel="stylesheet"> </head> <body> <script> $(document).ready(function() { $("#includeNavigation").load("navigation.html"); }); </script> <form> <div class="form-group"> <label>Nombre test</label> <input class="form-control" placeholder="Enter text" name="name"> </div> <div class="form-group"> <label>Descripción :</label> <textarea class="form-control" rows="3" name="description"></textarea> </div> <div class="form-group"> <label>Problema a valorar :</label> <textarea class="form-control" rows="3" name="problem"></textarea> </div> <br> <input id="add-restriction-button" type="button" value="Añade restricción"> <div id = "rectrictions"> </div> </form> </body> </html>
{ "content_hash": "03ebfb717fb69211452579f067420f63", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 89, "avg_line_length": 21.433962264150942, "alnum_prop": 0.590669014084507, "repo_name": "jester-euborn/h4g", "id": "4b1817e10be6f6203465751c092a9cec4459060c", "size": "1140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pages/enterprisetest_quique.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "22614" }, { "name": "HTML", "bytes": "522814" }, { "name": "JavaScript", "bytes": "56126" } ], "symlink_target": "" }
package org.omg.PortableInterceptor; /** * org/omg/PortableInterceptor/NON_EXISTENT.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u112/7884/corba/src/share/classes/org/omg/PortableInterceptor/Interceptors.idl * Thursday, September 22, 2016 9:33:09 PM PDT */ public interface NON_EXISTENT { /** Object adapter state indicating that the adapter has been destroyed. */ public static final short value = (short)(4); }
{ "content_hash": "fa705850c69d3748e7439f57e422bfe9", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 136, "avg_line_length": 30, "alnum_prop": 0.7509803921568627, "repo_name": "wapalxj/Java", "id": "399dd6981f7a61f1ec74e8a9cb2e4caefcc76717", "size": "510", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javaworkplace/source/src/org/omg/PortableInterceptor/NON_EXISTENT.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1" }, { "name": "C++", "bytes": "1" }, { "name": "HTML", "bytes": "200117" }, { "name": "Java", "bytes": "687071" }, { "name": "JavaScript", "bytes": "238567" }, { "name": "PHP", "bytes": "2789730" } ], "symlink_target": "" }
using System; using System.Collections; using Android.Content; using Android.Content.Res; using Plugin.Contacts.Abstractions; namespace Plugin.Contacts { internal class ContactQueryProvider : ContentQueryProvider { internal ContactQueryProvider(ContentResolver content, Resources resources) : base(content, resources, new ContactTableFinder()) { } public bool UseRawContacts { get { return ((ContactTableFinder)TableFinder).UseRawContacts; } set { ((ContactTableFinder)TableFinder).UseRawContacts = value; } } protected override IEnumerable GetObjectReader(ContentQueryTranslator translator) { if (translator == null || translator.ReturnType == null || translator.ReturnType == typeof(Contact)) return new ContactReader(UseRawContacts, translator, content, resources); else if (translator.ReturnType == typeof(Phone)) return new GenericQueryReader<Phone>(translator, content, resources, ContactHelper.GetPhone); else if (translator.ReturnType == typeof(Email)) return new GenericQueryReader<Email>(translator, content, resources, ContactHelper.GetEmail); else if (translator.ReturnType == typeof(Address)) return new GenericQueryReader<Address>(translator, content, resources, ContactHelper.GetAddress); else if (translator.ReturnType == typeof(Relationship)) return new GenericQueryReader<Relationship>(translator, content, resources, ContactHelper.GetRelationship); else if (translator.ReturnType == typeof(InstantMessagingAccount)) return new GenericQueryReader<InstantMessagingAccount>(translator, content, resources, ContactHelper.GetImAccount); else if (translator.ReturnType == typeof(Website)) return new GenericQueryReader<Website>(translator, content, resources, ContactHelper.GetWebsite); else if (translator.ReturnType == typeof(Organization)) return new GenericQueryReader<Organization>(translator, content, resources, ContactHelper.GetOrganization); else if (translator.ReturnType == typeof(Note)) return new GenericQueryReader<Note>(translator, content, resources, ContactHelper.GetNote); else if (translator.ReturnType == typeof(string)) return new ProjectionReader<string>(content, translator, (cur, col) => cur.GetString(col)); else if (translator.ReturnType == typeof(int)) return new ProjectionReader<int>(content, translator, (cur, col) => cur.GetInt(col)); throw new ArgumentException(); } } }
{ "content_hash": "bc11430148d570c030e3c57498ea8366", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 123, "avg_line_length": 49.86274509803921, "alnum_prop": 0.7377113645300826, "repo_name": "predictive-technology-laboratory/Xamarin.Plugins", "id": "c97fb8041ac589b335fbd224177151c802135aaf", "size": "3173", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Contacts/Contacts/Contacts.Plugin.Android/ContactQueryProvider.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1237533" }, { "name": "Pascal", "bytes": "3645" }, { "name": "PowerShell", "bytes": "3697" } ], "symlink_target": "" }
@extends('admin/layout') @section('content') <!-- akan merujuk @yield('content') --> <h1>Dashboard Admin</h1> @endsection
{ "content_hash": "71d2046fab913801403eab18a9acab97", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 39, "avg_line_length": 20.5, "alnum_prop": 0.6747967479674797, "repo_name": "jomphp/helpdesk", "id": "d9f106fff78984cb062a1e54c03b35e00020b411", "size": "123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/views/admin/dashboard.blade.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "HTML", "bytes": "22798" }, { "name": "JavaScript", "bytes": "987" }, { "name": "PHP", "bytes": "70258" } ], "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.Gui.GraphWindows.BottomPanel.viewReferences; import com.google.security.zynamics.binnavi.ZyGraph.CHighlightLayers; import com.google.security.zynamics.binnavi.disassembly.INaviCodeNode; import com.google.security.zynamics.binnavi.disassembly.INaviFunctionNode; import com.google.security.zynamics.binnavi.disassembly.INaviGroupNode; import com.google.security.zynamics.binnavi.disassembly.INaviInstruction; import com.google.security.zynamics.binnavi.disassembly.INaviTextNode; import com.google.security.zynamics.binnavi.disassembly.algorithms.CNodeTypeSwitcher; import com.google.security.zynamics.binnavi.disassembly.algorithms.INodeTypeCallback; import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode; import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph; import com.google.security.zynamics.zylib.gui.zygraph.helpers.INodeCallback; import com.google.security.zynamics.zylib.types.common.IterationMode; import java.awt.Color; import java.util.Collection; /** * Helper class used to highlight instructions that use a given variable. */ public final class CVariableHighlighter { /** * You are not supposed to instantiate this class. */ private CVariableHighlighter() {} /** * Highlights the given instructions. * * @param graph The graph where the instructions are highlighted. * @param toHighlight The instructions to highlight. */ public static void highlightInstructions( final ZyGraph graph, final Collection<INaviInstruction> toHighlight) { graph.iterate(new INodeCallback<NaviNode>() { @Override public IterationMode next(final NaviNode node) { CNodeTypeSwitcher.switchNode(node.getRawNode(), new INodeTypeCallback<Void>() { @Override public Void handle(final INaviCodeNode node) { for (final INaviInstruction instruction : node.getInstructions()) { if (toHighlight.contains(instruction)) { node.setInstructionColor( instruction, CHighlightLayers.VARIABLE_LAYER, new Color(100, 160, 200)); } else { node.setInstructionColor(instruction, CHighlightLayers.VARIABLE_LAYER, null); } } return null; } @Override public Void handle(final INaviFunctionNode node) { return null; } @Override public Void handle(final INaviGroupNode node) { return null; } @Override public Void handle(final INaviTextNode node) { return null; } }); return IterationMode.CONTINUE; } }); } }
{ "content_hash": "66f94386243bc754e277bff673bbed4b", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 93, "avg_line_length": 37.76136363636363, "alnum_prop": 0.7126090881733373, "repo_name": "mayl8822/binnavi", "id": "947e456f492a3e5a7c455888ba40945579b259e3", "size": "3323", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/google/security/zynamics/binnavi/Gui/GraphWindows/BottomPanel/viewReferences/CVariableHighlighter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1479" }, { "name": "C++", "bytes": "1876" }, { "name": "CSS", "bytes": "12843" }, { "name": "GAP", "bytes": "3637" }, { "name": "HTML", "bytes": "437420" }, { "name": "Java", "bytes": "21677942" }, { "name": "PLSQL", "bytes": "1866504" }, { "name": "PLpgSQL", "bytes": "638395" }, { "name": "Python", "bytes": "23981" }, { "name": "SQLPL", "bytes": "330046" }, { "name": "Shell", "bytes": "708" } ], "symlink_target": "" }
package org.jflowlight.model; import java.io.Serializable; /** * @author Giovanni Cammarata <cammarata.giovanni@gmail.com> */ public class LinkModel implements Serializable{ private static final long serialVersionUID = 6914468584987148627L; public enum LinkType{ SWITCH_LEAF, SWITCH_SWITCH } private final String dstID; private final Integer dstPort; private final Integer srcPort; private final LinkType linkType; public LinkModel(final String dstID, final Integer dstPort, final Integer srcPort, final LinkType linkType) { this.dstID = dstID; this.dstPort = dstPort; this.srcPort = srcPort; this.linkType = linkType; } public String getDstID() { return dstID; } public Integer getDstPort() { return dstPort; } public Integer getSrcPort() { return srcPort; } public LinkType getLinkType() { return linkType; } @Override public String toString() { return "Link{" + "dstID='" + dstID + '\'' + ", dstPort=" + dstPort + ", srcPort=" + srcPort + ", linkType=" + linkType + '}'; } @Override public boolean equals(final Object o) { if (this == o) return true; if (!(o instanceof LinkModel)) return false; final LinkModel linkModel = (LinkModel) o; if (dstID != null ? !dstID.equals(linkModel.dstID) : linkModel.dstID != null) return false; if (dstPort != null ? !dstPort.equals(linkModel.dstPort) : linkModel.dstPort != null) return false; if (srcPort != null ? !srcPort.equals(linkModel.srcPort) : linkModel.srcPort != null) return false; if (linkType != null ? !linkType.equals(linkModel.linkType) : linkModel.linkType != null) return false; return true; } @Override public int hashCode() { int result = dstID != null ? dstID.hashCode() : 0; result = 31 * result + (dstPort != null ? dstPort.hashCode() : 0); result = 31 * result + (srcPort != null ? srcPort.hashCode() : 0); result = 31 * result + (linkType != null ? linkType.hashCode() : 0); return result; } @Override protected LinkModel clone(){ return new LinkModel(dstID,dstPort,srcPort,linkType); } }
{ "content_hash": "18969460219dfad2923b51f62d3a4f2e", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 113, "avg_line_length": 28.226190476190474, "alnum_prop": 0.6005904681568959, "repo_name": "giovannicammarata/jflowlight", "id": "e9302def7ed9f74c58b21bd317264c61076eb80e", "size": "2371", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/src/main/java/org/jflowlight/model/LinkModel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "250034" } ], "symlink_target": "" }
import {set} from 'ember-metal/property_set'; import {get} from 'ember-metal/property_get'; import {Mixin} from 'ember-metal/mixin'; import { Binding } from 'ember-metal/binding'; import run from 'ember-metal/run_loop'; QUnit.module('system/mixin/binding_test'); QUnit.test('Defining a property ending in Binding should setup binding when applied', function() { let MyMixin = Mixin.create({ fooBinding: 'bar.baz' }); let obj = { bar: { baz: 'BIFF' } }; run(() => { let deprecationMessage = /`Ember.Binding` is deprecated/; expectDeprecation(() => { MyMixin.apply(obj); }, deprecationMessage); }); ok(get(obj, 'fooBinding') instanceof Binding, 'should be a binding object'); equal(get(obj, 'foo'), 'BIFF', 'binding should be created and synced'); }); QUnit.test('Defining a property ending in Binding should apply to prototype children', function() { let MyMixin = run(() => { return Mixin.create({ fooBinding: 'bar.baz' }); }); let obj = { bar: { baz: 'BIFF' } }; run(function() { let deprecationMessage = /`Ember.Binding` is deprecated/; expectDeprecation(() => { MyMixin.apply(obj); }, deprecationMessage); }); let obj2 = Object.create(obj); run(() => set(get(obj2, 'bar'), 'baz', 'BARG')); ok(get(obj2, 'fooBinding') instanceof Binding, 'should be a binding object'); equal(get(obj2, 'foo'), 'BARG', 'binding should be created and synced'); });
{ "content_hash": "4e5a3678420962b4e8ea128c707098b8", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 99, "avg_line_length": 28.392156862745097, "alnum_prop": 0.6422651933701657, "repo_name": "lan0/ember.js", "id": "f925bedc99742c1471e3dfa80bbc542896a43e02", "size": "1448", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/ember-runtime/tests/ext/mixin_test.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7457" }, { "name": "JavaScript", "bytes": "3298970" }, { "name": "Ruby", "bytes": "1925" }, { "name": "Shell", "bytes": "2529" } ], "symlink_target": "" }
define([ 'comindware/core', 'demoPage/views/CanvasView', 'demoPage/views/DemoDropdownPanelView', 'demoPage/views/DemoInputView', 'demoPage/demoDataProvider' ], function (core, CanvasView, DemoDropdownPanelView, DemoInputView, demoDataProvider) { 'use strict'; return function () { var collection = demoDataProvider.createIdFullNameCollection(); /* Possible panelPosition values: 'down', 'down-over', 'up', 'up-over' */ var dropdown = core.dropdown.factory.createDropdown({ buttonView: DemoInputView, panelView: DemoDropdownPanelView, panelViewOptions: { collection: collection }, panelPosition: 'down-over' }); return new CanvasView({ view: dropdown, canvas: { width: '300px' } }); }; });
{ "content_hash": "b53c9f71eb11bcf68d568d64e1ea1067", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 88, "avg_line_length": 26.944444444444443, "alnum_prop": 0.5412371134020618, "repo_name": "ConstYavorskiy/HeractJS", "id": "66df465fb559e5bd8a8233df09c64b52a95ca3fe", "size": "970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/HeractJS/Scripts/project/demo/cases/dropdown/dropdownPanelPosition.js", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3173" }, { "name": "CSS", "bytes": "1211841" }, { "name": "HTML", "bytes": "76939" }, { "name": "Handlebars", "bytes": "11275" }, { "name": "JavaScript", "bytes": "7003641" }, { "name": "TypeScript", "bytes": "126260" } ], "symlink_target": "" }
<!--- This file is automatically generated by make gen-cli-docs; changes should be made in the go CLI command code (under cmd/kops) --> ## kops upgrade cluster Upgrade a kubernetes cluster. ### Synopsis Automates checking for and applying Kubernetes updates. This upgrades a cluster to the latest recommended production ready k8s version. After this command is run, use kops update cluster and kops rolling-update cluster to finish a cluster upgrade. ``` kops upgrade cluster [flags] ``` ### Examples ``` # Upgrade a cluster's Kubernetes version. kops upgrade cluster kubernetes-cluster.example.com --yes --state=s3://kops-state-1234 ``` ### Options ``` --channel string Channel to use for upgrade -h, --help help for cluster -y, --yes Apply update ``` ### Options inherited from parent commands ``` --alsologtostderr log to standard error as well as files --config string yaml config file (default is $HOME/.kops.yaml) --log_backtrace_at traceLocation when logging hits line file:N, emit a stack trace (default :0) --log_dir string If non-empty, write log files in this directory --log_file string If non-empty, use this log file --log_file_max_size uint Defines the maximum size a log file can grow to. Unit is megabytes. If the value is 0, the maximum file size is unlimited. (default 1800) --logtostderr log to standard error instead of files (default true) --name string Name of cluster. Overrides KOPS_CLUSTER_NAME environment variable --skip_headers If true, avoid header prefixes in the log messages --skip_log_headers If true, avoid headers when opening log files --state string Location of state storage (kops 'config' file). Overrides KOPS_STATE_STORE environment variable --stderrthreshold severity logs at or above this threshold go to stderr (default 2) -v, --v Level number for the log level verbosity --vmodule moduleSpec comma-separated list of pattern=N settings for file-filtered logging ``` ### SEE ALSO * [kops upgrade](kops_upgrade.md) - Upgrade a kubernetes cluster.
{ "content_hash": "880cd394ee14615cfac6d2f0d8fd7824", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 247, "avg_line_length": 45.26923076923077, "alnum_prop": 0.6469838572642311, "repo_name": "aledbf/kops", "id": "9fef64f0e4891b796276719f5ae381f8d493d38e", "size": "2355", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/cli/kops_upgrade_cluster.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "6113586" }, { "name": "HCL", "bytes": "435861" }, { "name": "Makefile", "bytes": "32776" }, { "name": "Python", "bytes": "182981" }, { "name": "Ruby", "bytes": "1027" }, { "name": "Shell", "bytes": "87027" } ], "symlink_target": "" }
require 'rubygems' require 'test/unit' $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'simple_app_config' class Test::Unit::TestCase end
{ "content_hash": "f775937bb79c643cae196ff644f6dc5d", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 66, "avg_line_length": 23.333333333333332, "alnum_prop": 0.7, "repo_name": "phuesler/simple_app_config", "id": "40c55747ec1bd6cae5494ffaa1386838ec9a21dd", "size": "210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3620" } ], "symlink_target": "" }
// Copyright (c) 1997 // Utrecht University (The Netherlands), // ETH Zurich (Switzerland), // INRIA Sophia-Antipolis (France), // Max-Planck-Institute Saarbruecken (Germany), // and Tel-Aviv University (Israel). All rights reserved. // // This file is part of CGAL (www.cgal.org); you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 3 of the License, // or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Michael Hoffmann <hoffmann@inf.ethz.ch> // : Michael Hemmer <hemmer@mpi-inf.mpg.de> // to be included by number_utils.h #ifndef CGAL_NUMBER_UTILS_CLASSES_H #define CGAL_NUMBER_UTILS_CLASSES_H 1 #include <CGAL/Real_embeddable_traits.h> #include <CGAL/Algebraic_structure_traits.h> #include <algorithm> #include <utility> namespace CGAL { /* Defines functors: - Is_zero - Is_one - Is_negative - Is_positive - Sgn - Abs - Compare - Square - Sqrt - Div - Gcd - To_double - To_interval */ template < class NT > struct Is_negative : Real_embeddable_traits<NT>::Is_negative {}; template < class NT > struct Is_positive : Real_embeddable_traits<NT>::Is_positive {}; template < class NT > struct Abs : Real_embeddable_traits<NT>::Abs{}; template < class NT > struct To_double : Real_embeddable_traits<NT>::To_double{}; template < class NT > struct To_interval : Real_embeddable_traits<NT>::To_interval{}; // Sign would result in a name clash with enum.h template < class NT > struct Sgn : Real_embeddable_traits<NT>::Sgn {}; template < class NT > struct Square : Algebraic_structure_traits<NT>::Square{}; template < class NT > struct Sqrt : Algebraic_structure_traits<NT>::Sqrt {}; template < class NT > struct Div : Algebraic_structure_traits<NT>::Div{}; template < class NT > struct Gcd : Algebraic_structure_traits<NT>::Gcd{}; template < class NT > struct Is_one : Algebraic_structure_traits<NT>::Is_one {}; // This is due to the fact that Is_zero may be provided by // Algebraic_structure_traits as well as Real_embeddable_traits // Of course it is not possible to derive from both since this // would cause an ambiguity. namespace internal{ template <class AST_Is_zero, class RET_Is_zero> struct Is_zero_base : AST_Is_zero {} ; template <class RET_Is_zero> struct Is_zero_base <CGAL::Null_functor, RET_Is_zero >: RET_Is_zero {} ; } // namespace internal template < class NT > struct Is_zero : internal::Is_zero_base <typename Algebraic_structure_traits<NT>::Is_zero, typename Real_embeddable_traits<NT>::Is_zero>{}; // This is due to the fact that CGAL::Compare is used for other // non-realembeddable types as well. // In this case we try to provide a default implementation namespace internal { template <class NT, class Compare> struct Compare_base: public Compare {}; template <class NT> struct Compare_base<NT,Null_functor> :public std::binary_function< NT, NT, Comparison_result > { Comparison_result operator()( const NT& x, const NT& y) const { if (x < y) return SMALLER; if (x > y) return LARGER; CGAL_postcondition(x == y); return EQUAL; } }; } // namespace internal template < class NT > struct Compare :public internal::Compare_base <NT,typename Real_embeddable_traits<NT>::Compare>{}; } //namespace CGAL #endif // CGAL_NUMBER_UTILS_CLASSES_H
{ "content_hash": "babf9963bef90f585891dd594dfd53ec", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 79, "avg_line_length": 30.072580645161292, "alnum_prop": 0.7047465808527755, "repo_name": "hlzz/dotfiles", "id": "005e01a76433862bd0f20f540fb0201d525d996b", "size": "3729", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "graphics/cgal/Algebraic_foundations/include/CGAL/number_utils_classes.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "1240" }, { "name": "Arc", "bytes": "38" }, { "name": "Assembly", "bytes": "449468" }, { "name": "Batchfile", "bytes": "16152" }, { "name": "C", "bytes": "102303195" }, { "name": "C++", "bytes": "155056606" }, { "name": "CMake", "bytes": "7200627" }, { "name": "CSS", "bytes": "179330" }, { "name": "Cuda", "bytes": "30026" }, { "name": "D", "bytes": "2152" }, { "name": "Emacs Lisp", "bytes": "14892" }, { "name": "FORTRAN", "bytes": "5276" }, { "name": "Forth", "bytes": "3637" }, { "name": "GAP", "bytes": "14495" }, { "name": "GLSL", "bytes": "438205" }, { "name": "Gnuplot", "bytes": "327" }, { "name": "Groff", "bytes": "518260" }, { "name": "HLSL", "bytes": "965" }, { "name": "HTML", "bytes": "2003175" }, { "name": "Haskell", "bytes": "10370" }, { "name": "IDL", "bytes": "2466" }, { "name": "Java", "bytes": "219109" }, { "name": "JavaScript", "bytes": "1618007" }, { "name": "Lex", "bytes": "119058" }, { "name": "Lua", "bytes": "23167" }, { "name": "M", "bytes": "1080" }, { "name": "M4", "bytes": "292475" }, { "name": "Makefile", "bytes": "7112810" }, { "name": "Matlab", "bytes": "1582" }, { "name": "NSIS", "bytes": "34176" }, { "name": "Objective-C", "bytes": "65312" }, { "name": "Objective-C++", "bytes": "269995" }, { "name": "PAWN", "bytes": "4107117" }, { "name": "PHP", "bytes": "2690" }, { "name": "Pascal", "bytes": "5054" }, { "name": "Perl", "bytes": "485508" }, { "name": "Pike", "bytes": "1338" }, { "name": "Prolog", "bytes": "5284" }, { "name": "Python", "bytes": "16799659" }, { "name": "QMake", "bytes": "89858" }, { "name": "Rebol", "bytes": "291" }, { "name": "Ruby", "bytes": "21590" }, { "name": "Scilab", "bytes": "120244" }, { "name": "Shell", "bytes": "2266191" }, { "name": "Slash", "bytes": "1536" }, { "name": "Smarty", "bytes": "1368" }, { "name": "Swift", "bytes": "331" }, { "name": "Tcl", "bytes": "1911873" }, { "name": "TeX", "bytes": "11981" }, { "name": "Verilog", "bytes": "3893" }, { "name": "VimL", "bytes": "595114" }, { "name": "XSLT", "bytes": "62675" }, { "name": "Yacc", "bytes": "307000" }, { "name": "eC", "bytes": "366863" } ], "symlink_target": "" }
<instance description="50 cal mounted on the m8 greyhound" template="weapon"> <group name="weapon_bag"> <group name="accuracy"> <float name="near" value="0.75" /> <float name="far" value="0.2" /> <float name="mid" value="0.45" /> </group> <group name="aim"> <group name="fire_aim_time"> <float name="max" value="0.75" /> <float name="min" value="0.125" /> </group> <float name="post_firing_aim_time" value="1" /> <float name="post_firing_cooldown_interval" value="0" /> <group name="ready_aim_time"> <float name="max" value="0.125" /> <float name="min" value="0.125" /> </group> <group name="aim_time_multiplier"> <float name="near" value="0.5" /> <float name="far" value="1" /> <float name="mid" value="0.75" /> </group> </group> <group name="anim_table"> <string name="cooldown_time_name" value="" /> <string name="state_name" value="pintle_m2hb50cal_state" /> <string name="track_horizontal" value="turret_gunner_horiz" /> <string name="track_horizontal_speed" value="" /> <string name="track_vertical" value="pintle_m2hb50cal_vertical" /> <string name="track_vertical_speed" value="" /> <string name="variety_name" value="vehicle" /> <string name="visibility_name" value="pintle_m2hb50cal_visibility" /> <string name="target_range_name" value="" /> </group> <group name="area_effect"> <group name="accuracy"> <float name="far" value="0.6" /> <float name="near" value="5" /> <float name="mid" value="2.8" /> </group> <group name="area_info"> <float name="angle_left" value="0" /> <float name="angle_right" value="0" /> <enum name="area_type" value="circle" /> <float name="radius" value="0" /> </group> <group name="damage"> <float name="far" value="0.25" /> <float name="near" value="1" /> <float name="mid" value="0.625" /> </group> <group name="damage_friendly"> <float name="far" value="0.25" /> <float name="near" value="1" /> <float name="mid" value="0.625" /> </group> <group name="distance"> <float name="far" value="0" /> <float name="near" value="0" /> <float name="mid" value="0" /> </group> <bool name="has_friendly_fire" value="False" /> <bool name="can_harm_shooter" value="False" /> <group name="suppression"> <float name="far" value="0" /> <float name="near" value="0" /> <float name="mid" value="0" /> </group> <group name="suppression_friendly"> <float name="far" value="0" /> <float name="near" value="0" /> <float name="mid" value="0" /> </group> <bool name="damage_all_in_hold" value="False" /> <template_reference name="aoe_penetration" value="tables\range_table"> <float name="far" value="1" /> <float name="mid" value="1" /> <float name="near" value="1" /> </template_reference> <group name="building_damage"> <float name="near" value="1" /> <float name="mid" value="1" /> <float name="far" value="1" /> </group> <instance_reference name="weapon_building_damage" value="weapon_building_damage\aoe_profile_no_change" /> <enum name="aoe_origin_and_direction" value="hit_position_and_direction" /> </group> <group name="behaviour"> <bool name="aa_weapon" value="True" /> <bool name="aa_weapon_shoot_through" value="True" /> <bool name="artillery_force_obey_los" value="False" /> <bool name="attack_team_weapon_user" value="False" /> <bool name="can_be_offhanded" value="False" /> <bool name="can_be_substituted" value="False" /> <float name="combat_slot_offset" value="0" /> <bool name="enable_auto_target_search" value="True" /> <bool name="fire_at_building_combat_slot" value="False" /> <float name="ground_hit_rate" value="0.75" /> <bool name="ignore_shot_blocking" value="False" /> <bool name="non_moving_setup" value="False" /> <bool name="point_blank" value="True" /> <bool name="prevents_prone" value="False" /> <bool name="reset_rotation_on_teardown" value="False" /> <bool name="share_parent_anim" value="False" /> <bool name="single_handed_weapon" value="False" /> <bool name="substitute_weapon" value="False" /> <bool name="support_weapon" value="False" /> <bool name="surprises_idle" value="False" /> <bool name="piercing" value="False" /> <float name="reaction_radius" value="0" /> <bool name="can_be_pilfered" value="True" /> <bool name="causes_combat" value="True" /> <bool name="can_abort_winddown" value="False" /> <enum name="reaction_type" value="normal" /> <bool name="ignore_relations" value="False" /> <template_reference name="wants_prone_firing_option" value="options\none"> </template_reference> <enum name="attack_ground_type" value="not_allowed" /> </group> <group name="burst"> <bool name="can_burst" value="True" /> <group name="duration"> <float name="max" value="2.78" /> <float name="min" value="2.78" /> </group> <group name="incremental_target_table"> <float name="accuracy_multiplier" value="1.12" /> <group name="search_radius"> <float name="far" value="10" /> <float name="near" value="6" /> <float name="mid" value="8" /> </group> </group> <group name="rate_of_fire"> <float name="max" value="9" /> <float name="min" value="9" /> </group> <group name="duration_multiplier"> <float name="near" value="1.5" /> <float name="far" value="1" /> <float name="mid" value="1.25" /> </group> <group name="rate_of_fire_multiplier"> <float name="near" value="1" /> <float name="far" value="1" /> <float name="mid" value="1" /> </group> <bool name="focus_fire" value="True" /> </group> <group name="cooldown"> <group name="duration"> <float name="max" value="4" /> <float name="min" value="2" /> </group> <group name="duration_multiplier"> <float name="near" value="0.5" /> <float name="far" value="1" /> <float name="mid" value="0.75" /> </group> </group> <group name="cover_table"> <group name="tp_defcover"> <float name="accuracy_multiplier" value="1" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1" /> </group> <group name="tp_defcover_narrow"> <float name="accuracy_multiplier" value="1" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1" /> </group> <group name="tp_garrison_cover"> <float name="accuracy_multiplier" value="0.55" /> <float name="damage_multiplier" value="0.5" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0" /> </group> <group name="tp_garrison_halftrack"> <float name="accuracy_multiplier" value="0.5" /> <float name="damage_multiplier" value="0.5" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0" /> </group> <group name="tp_heavy"> <float name="accuracy_multiplier" value="0.5" /> <float name="damage_multiplier" value="0.5" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0.1" /> </group> <group name="tp_light"> <float name="accuracy_multiplier" value="0.5" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0.5" /> </group> <group name="tp_negative"> <float name="accuracy_multiplier" value="1.25" /> <float name="damage_multiplier" value="1.25" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1.5" /> </group> <group name="tp_open"> <float name="accuracy_multiplier" value="1.25" /> <float name="damage_multiplier" value="1.25" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1" /> </group> <group name="tp_smoke"> <float name="accuracy_multiplier" value="0.25" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0.05" /> </group> <group name="tp_trench"> <float name="accuracy_multiplier" value="0.2" /> <float name="damage_multiplier" value="0.3" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0" /> </group> <group name="tp_water"> <float name="accuracy_multiplier" value="1" /> <float name="damage_multiplier" value="1.5" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1" /> </group> <group name="tp_z_bunker"> <float name="accuracy_multiplier" value="0.35" /> <float name="damage_multiplier" value="0.35" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0" /> </group> <group name="tp_z_emplacement"> <float name="accuracy_multiplier" value="0.5" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0.75" /> </group> <group name="tp_z_ice"> <float name="accuracy_multiplier" value="1" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1" /> </group> <group name="tp_z_snow"> <float name="accuracy_multiplier" value="1" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1" /> </group> <group name="tp_zz_deep_snow"> <float name="accuracy_multiplier" value="1" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1" /> </group> <group name="tp_zz_mud"> <float name="accuracy_multiplier" value="1" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="1" /> </group> <group name="tp_zz_team_weapon_heavy"> <float name="accuracy_multiplier" value="0.5" /> <float name="damage_multiplier" value="0.5" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0.1" /> </group> </group> <group name="damage"> <float name="max" value="8" /> <float name="min" value="8" /> <list name="on_penetrated_actions"> </list> </group> <group name="damage_over_time"> <template_reference name="damage_over_time" value="dot_type\none"> </template_reference> </group> <group name="deflection"> <float name="deflection_damage_multiplier" value="0" /> <bool name="has_deflection_damage" value="False" /> <list name="on_deflected_actions"> <template_reference name="action" value="action\requirement_action"> <bool name="check_self" value="False" /> <bool name="global_fire_and_forget_on_success" value="False" /> <bool name="instant_requirement_check" value="False" /> <bool name="kill_action_on_failed_requirements" value="False" /> <bool name="no_retrigger" value="False" /> <bool name="validate_all_sub_actions" value="True" /> <list name="requirement_table"> <template_reference name="required" value="requirements\required_unit_type"> <enum name="reason" value="usage" /> <locstring name="ui_name" value="0" /> <enum name="unit_type" value="aircraft" /> <template_reference name="qualify_option" value="options\none"> </template_reference> <bool name="search_load_out" value="False" /> <bool name="owned_by_player_only" value="True" /> </template_reference> </list> <list name="action_table"> <template_reference name="action" value="action\random_action"> <bool name="instant" value="True" /> <list name="random_actions"> <group name="action_choice"> <list name="actions"> <template_reference name="action" value="action\trigger_critical_action"> <float name="remove_at_health" value="1" /> <instance_reference name="critical" value="critical\vehicle_destroy" /> <uniqueid name="id" value="1073741837" /> </template_reference> </list> <int name="weight" value="197" /> </group> <group name="action_choice"> <list name="actions"> <template_reference name="action" value="action\no_action"> <uniqueid name="id" value="1073741838" /> <template_reference name="ui_help_text" value="options\none"> </template_reference> </template_reference> </list> <int name="weight" value="9803" /> </group> </list> <uniqueid name="id" value="1073741839" /> </template_reference> </list> <uniqueid name="id" value="1073741840" /> <bool name="fire_and_forget_non_global" value="False" /> <template_reference name="ui_help_text" value="tables\help_text_phrase"> <int name="phrase_order" value="0" /> <locstring name="phrase" value="0" /> </template_reference> </template_reference> </list> </group> <group name="fire"> <float name="wind_down" value="0" /> <float name="wind_up" value="0" /> <list name="on_fire_actions"> </list> </group> <float name="flinch_radius" value="0" /> <string name="fx_action_target_name" value="50cal_target" /> <bool name="fx_always_visible" value="False" /> <float name="fx_building_hit_delay" value="0" /> <float name="fx_delay_in_building" value="0" /> <string name="fx_munition_name" value="hmg_large" /> <string name="fx_tracer_name" value="m2hb50cal_tracer" /> <float name="fx_tracer_speed" value="120" /> <bool name="fx_use_building_panel_normal" value="True" /> <locstring name="help_text" value="0" /> <icon name="icon_name" value="" /> <group name="moving"> <float name="accuracy_multiplier" value="0.5" /> <float name="burst_multiplier" value="1" /> <float name="cooldown_multiplier" value="1" /> <bool name="disable_moving_firing" value="False" /> <float name="moving_end_time" value="0" /> <float name="moving_start_time" value="0" /> </group> <string name="name" value="50 cal mounted on the top (M8 Greyhound)" /> <group name="offhand"> <float name="offhand_end_time" value="0" /> <float name="offhand_start_time" value="0" /> </group> <group name="priority"> <float name="current_target" value="8" /> <group name="distance"> <float name="far" value="-10" /> <float name="near" value="60" /> <float name="mid" value="25" /> </group> <float name="rotation" value="-0.035" /> <float name="window_bonus" value="0" /> <float name="threat" value="20" /> <float name="penetration" value="2" /> <float name="suggested_target" value="1000" /> <bool name="over_penetration_priority_penalty" value="True" /> </group> <group name="projectile"> <bool name="delete_previous_on_hit" value="False" /> <instance_reference name="projectile" value="" /> </group> <group name="range"> <float name="max" value="40" /> <float name="min" value="0" /> <group name="distance"> <float name="near" value="10" /> <float name="far" value="40" /> <float name="mid" value="25" /> </group> </group> <group name="reload"> <group name="duration"> <float name="max" value="6" /> <float name="min" value="5" /> </group> <group name="duration_multiplier"> <float name="far" value="1" /> <float name="near" value="1" /> <float name="mid" value="1" /> </group> <group name="frequency"> <float name="max" value="3" /> <float name="min" value="3" /> </group> <list name="on_reload_actions"> </list> </group> <group name="scatter"> <float name="angle_scatter" value="3" /> <bool name="burst_pattern_enable" value="True" /> <float name="delay_bracket_change_chance" value="0.3" /> <float name="distance_bracket_count_air" value="5" /> <float name="distance_bracket_count_ground" value="18" /> <float name="distance_scatter_max" value="15" /> <float name="distance_scatter_obj_hit_min" value="0" /> <float name="distance_scatter_offset" value="0.8" /> <float name="distance_scatter_ratio" value="0.8" /> <float name="fow_angle_multiplier" value="1" /> <float name="fow_distance_multiplier" value="1" /> <float name="max_tilt_angle" value="5" /> <float name="min_tilt_angle" value="2" /> <float name="tilt_max_distance" value="20" /> <float name="tilt_scatter_chance" value="0.5" /> </group> <group name="setup"> <float name="duration" value="0" /> <bool name="has_instant_setup" value="False" /> <bool name="can_interrupt_setup" value="False" /> <float name="attach_duration" value="0" /> </group> <group name="suppressed"> <float name="pinned_burst_multiplier" value="1" /> <float name="pinned_cooldown_multiplier" value="1" /> <float name="pinned_reload_multiplier" value="1" /> <float name="suppressed_burst_multiplier" value="1" /> <float name="suppressed_cooldown_multiplier" value="1" /> <float name="suppressed_reload_multiplier" value="1" /> </group> <group name="suppression"> <float name="nearby_suppression_multiplier" value="0" /> <float name="nearby_suppression_radius" value="0" /> <group name="target_pinned_multipliers"> <float name="accuracy_multiplier" value="0.25" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0.1" /> </group> <group name="target_suppressed_multipliers"> <float name="accuracy_multiplier" value="0.5" /> <float name="damage_multiplier" value="1" /> <float name="penetration_multiplier" value="1" /> <float name="suppression_multiplier" value="0.5" /> </group> <float name="amount" value="0" /> </group> <group name="teardown"> <float name="duration" value="0" /> </group> <group name="tracking"> <float name="fire_cone_angle" value="5" /> <group name="normal"> <float name="max_down" value="-90" /> <float name="max_left" value="-180" /> <float name="max_right" value="180" /> <float name="max_up" value="45" /> <float name="speed_horizontal" value="110" /> <float name="speed_vertical" value="60" /> </group> <float name="pivot_end_time" value="0" /> <bool name="pivot_only" value="False" /> <float name="pivot_start_time" value="0" /> </group> <locstring name="ui_name" value="0" /> <enum name="weapon_type" value="small_arms" /> <instance_reference name="ui_range" value="" /> <instance_reference name="ui_setfacing" value="" /> <group name="penetration"> <float name="mid" value="0.5" /> <float name="far" value="0.5" /> <float name="near" value="0.5" /> </group> <group name="ui_map_colour"> <int name="red" value="0" /> <int name="green" value="0" /> <int name="blue" value="0" /> <int name="alpha" value="0" /> </group> </group> <uniqueid name="pbgid" value="2828" /> </instance>
{ "content_hash": "706352e9058b72ddfce5a13c2841fb78", "timestamp": "", "source": "github", "line_count": 497, "max_line_length": 108, "avg_line_length": 39.27967806841046, "alnum_prop": 0.6188915070177236, "repo_name": "Ruhrpottpatriot/LastCrusade", "id": "282ec3bfb7d43bb6c7f42a927608846a4e994dbe", "size": "19522", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/instances/weapon/aef/small_arms/machine_gun/heavy_machine_gun/m8_greyhound_m2hb_50cal_mounted_mp.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "5218" }, { "name": "CSS", "bytes": "2640" }, { "name": "HTML", "bytes": "117223" }, { "name": "Lua", "bytes": "87140" } ], "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"/> <title>Core Plot (Mac OS): Source/NSDecimalNumberExtensions.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="customdoxygen.css" rel="stylesheet" type="text/css" /> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="core-plot-logo.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">Core Plot (Mac OS) </div> <div id="projectbrief">Cocoa plotting framework for Mac OS X and iOS</div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.8.1.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="modules.html"><span>Animation&#160;&&#160;Constants</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&#160;List</span></a></li> <li><a href="globals.html"><span>File&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('_n_s_decimal_number_extensions_8h.html','');}); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">NSDecimalNumberExtensions.h</div> </div> </div><!--header--> <div class="contents"> <a href="_n_s_decimal_number_extensions_8h.html">Go to the documentation of this file.</a><div class="fragment"><div class="line"><a name="l00001"></a><span class="lineno"> 1</span>&#160;<span class="preprocessor">#import &lt;Foundation/Foundation.h&gt;</span></div> <div class="line"><a name="l00002"></a><span class="lineno"> 2</span>&#160;<span class="preprocessor">#import &lt;QuartzCore/QuartzCore.h&gt;</span></div> <div class="line"><a name="l00003"></a><span class="lineno"> 3</span>&#160;</div> <div class="line"><a name="l00007"></a><span class="lineno"> 7</span>&#160;<span class="keyword">@interface </span><a class="codeRef" href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDecimalNumber_Class/Reference/Reference.html">NSDecimalNumber</a>(CPTExtensions)</div> <div class="line"><a name="l00008"></a><span class="lineno"> 8</span>&#160;</div> <div class="line"><a name="l00009"></a><span class="lineno"> 9</span>&#160;<span class="keyword">@end</span></div> </div><!-- fragment --></div><!-- contents --> </div><!-- doc-content --> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a></li> </ul> </div> </body> </html>
{ "content_hash": "a658e5be792f1216054a914dffec522c", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 307, "avg_line_length": 45.8875, "alnum_prop": 0.6472350858076819, "repo_name": "aufflick/core-plot", "id": "2413896b385970c5bc4f62f9772838fceacdaa49", "size": "3671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documentation/html/MacOS/_n_s_decimal_number_extensions_8h_source.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "17035" }, { "name": "D", "bytes": "343" }, { "name": "JavaScript", "bytes": "602937" }, { "name": "Objective-C", "bytes": "1899495" }, { "name": "Perl", "bytes": "5096" }, { "name": "Python", "bytes": "10576" }, { "name": "Shell", "bytes": "631" } ], "symlink_target": "" }
package org.apache.beam.fn.harness.state; import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument; import java.io.IOException; import org.apache.beam.fn.harness.Cache; import org.apache.beam.fn.harness.Caches; import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey; import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateRequest; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.transforms.Materializations.MultimapView; import org.apache.beam.vendor.grpc.v1p43p2.com.google.protobuf.ByteString; /** * An implementation of a multimap side input that utilizes the Beam Fn State API to fetch values. */ @SuppressWarnings({ "rawtypes", // TODO(https://issues.apache.org/jira/browse/BEAM-10556) "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402) }) public class MultimapSideInput<K, V> implements MultimapView<K, V> { private final Cache<?, ?> cache; private final BeamFnStateClient beamFnStateClient; private final StateRequest keysRequest; private final Coder<K> keyCoder; private final Coder<V> valueCoder; public MultimapSideInput( Cache<?, ?> cache, BeamFnStateClient beamFnStateClient, String instructionId, StateKey stateKey, Coder<K> keyCoder, Coder<V> valueCoder) { checkArgument( stateKey.hasMultimapKeysSideInput(), "Expected MultimapKeysSideInput StateKey but received %s.", stateKey); this.cache = cache; this.beamFnStateClient = beamFnStateClient; this.keysRequest = StateRequest.newBuilder().setInstructionId(instructionId).setStateKey(stateKey).build(); this.keyCoder = keyCoder; this.valueCoder = valueCoder; } @Override public Iterable<K> get() { return StateFetchingIterators.readAllAndDecodeStartingFrom( cache, beamFnStateClient, keysRequest, keyCoder); } @Override public Iterable<V> get(K k) { ByteString.Output output = ByteString.newOutput(); try { keyCoder.encode(k, output); } catch (IOException e) { throw new IllegalStateException( String.format( "Failed to encode key %s for side input id %s.", k, keysRequest.getStateKey().getMultimapKeysSideInput().getSideInputId()), e); } ByteString encodedKey = output.toByteString(); StateKey stateKey = StateKey.newBuilder() .setMultimapSideInput( StateKey.MultimapSideInput.newBuilder() .setTransformId( keysRequest.getStateKey().getMultimapKeysSideInput().getTransformId()) .setSideInputId( keysRequest.getStateKey().getMultimapKeysSideInput().getSideInputId()) .setWindow(keysRequest.getStateKey().getMultimapKeysSideInput().getWindow()) .setKey(encodedKey)) .build(); StateRequest request = keysRequest.toBuilder().setStateKey(stateKey).build(); return StateFetchingIterators.readAllAndDecodeStartingFrom( Caches.subCache(cache, "ValuesForKey", encodedKey), beamFnStateClient, request, valueCoder); } }
{ "content_hash": "e62d97cad13da4366088976f339eaf77", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 104, "avg_line_length": 37.98809523809524, "alnum_prop": 0.6988404888749609, "repo_name": "robertwb/incubator-beam", "id": "36228fbb984f9a8e9aa9867e0c2eac2b9bde30cb", "size": "3996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1598" }, { "name": "C", "bytes": "3869" }, { "name": "CSS", "bytes": "4957" }, { "name": "Cython", "bytes": "59582" }, { "name": "Dart", "bytes": "541526" }, { "name": "Dockerfile", "bytes": "48191" }, { "name": "FreeMarker", "bytes": "7933" }, { "name": "Go", "bytes": "4688736" }, { "name": "Groovy", "bytes": "888171" }, { "name": "HCL", "bytes": "101646" }, { "name": "HTML", "bytes": "164685" }, { "name": "Java", "bytes": "38649211" }, { "name": "JavaScript", "bytes": "105966" }, { "name": "Jupyter Notebook", "bytes": "55818" }, { "name": "Kotlin", "bytes": "209531" }, { "name": "Lua", "bytes": "3620" }, { "name": "Python", "bytes": "9785295" }, { "name": "SCSS", "bytes": "312814" }, { "name": "Sass", "bytes": "19336" }, { "name": "Scala", "bytes": "1429" }, { "name": "Shell", "bytes": "336583" }, { "name": "Smarty", "bytes": "2618" }, { "name": "Thrift", "bytes": "3260" }, { "name": "TypeScript", "bytes": "181369" } ], "symlink_target": "" }
require 'spec_helper' require File.expand_path('../fixtures/classes', __FILE__) describe Function::Predicate::LessThan::Methods, '#lt' do subject { object.lt(other) } let(:object) { described_class.new.freeze } let(:described_class) { LessThanMethodsSpecs::Object } let(:other) { 1 } it { should be_instance_of(Function::Predicate::LessThan) } its(:left) { should be(object) } its(:right) { should be(other) } end
{ "content_hash": "55e89ab916d4726b46b9913a551816f7", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 61, "avg_line_length": 30.0625, "alnum_prop": 0.6133056133056133, "repo_name": "dkubb/axiom", "id": "613ef0e0c0a90a0666321731b886d0b656436fda", "size": "500", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/unit/axiom/function/predicate/less_than/methods/lt_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "627873" } ], "symlink_target": "" }
import React, { Component } from 'react' import { Grid, Container, Segment, Icon } from 'semantic-ui-react' import Link from 'gatsby-link' export default class MenuExampleBasic extends Component { state = {} handleItemClick = (e, { name }) => this.setState({ activeItem: name }) render() { const { activeItem } = this.state return ( <div className={"footer"}> <Container> <Segment padded={"very"} basic className={"site-logo"}> <Link to="/"> MVMNT </Link> </Segment> <Segment padded={"very"} basic className={"fluid-grid"}> <Grid columns={3} className="phone"> <Grid.Column> <p>STRATEGY</p> <Link to="/services/#strategy"> UX Design</Link> <Link to="/services/#strategy"> Product Management</Link> <Link to="/services/#strategy"> Project Management</Link> </Grid.Column> <Grid.Column> <p>DESIGN</p> <Link to="/services/#design"> Interface Design</Link> <Link to="/services/#design"> Brand Identity</Link> <Link to="/services/#design"> Web Design</Link> <Link to="/services/#design"> Graphic Design</Link> <Link to="/services/#design"> Advertising</Link> </Grid.Column> <Grid.Column> <p>DEVELOPMENT</p> <Link to="/services/#development">Custom Solutions</Link> <Link to="/services/#development"> Native Apps</Link> <Link to="/services/#development"> E-Commerce</Link> <Link to="/services/#development">Content Management</Link> </Grid.Column> </Grid> </Segment> <Grid columns={2} className="phone"> <Grid.Column> <Segment padded={'very'} basic className={"social"}> <a title={"MVMNT Linkedin profile"} href="https://www.linkedin.com/company/thought-code/"> <Icon link name='linkedin' size={'large'} /> </a> <a title={"MVMNT facebook profile"} href="https://www.facebook.com/thoughtcodetech/"> <Icon link name='facebook f' size={'large'} /> </a> <a title={"MVMNT twitter profile"} href="https://twitter.com/thoughtcode1"> <Icon link name='twitter' size={'large'} /> </a> </Segment> </Grid.Column> <Grid.Column> <Segment padded={'very'} basic> Copyright MVMNT LLC 2018 </Segment> </Grid.Column> </Grid> </Container> </div> ) } }
{ "content_hash": "658ce5d4742668c1b4d8898dcd400dc2", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 106, "avg_line_length": 39.52857142857143, "alnum_prop": 0.5117455728225515, "repo_name": "Centrico/centrico", "id": "fdb46ceefa64917afe4b1854088b6761683054bb", "size": "2767", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/footer.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "619982" }, { "name": "JavaScript", "bytes": "947081" } ], "symlink_target": "" }
sap.ui.define([ "sap/ui/documentation/sdk/controller/BaseController" ], function (BaseController) { "use strict"; return BaseController.extend("sap.ui.documentation.sdk.controller.Downloads", { /** * Called when the controller is instantiated. * @public */ onInit : function () { this.getRouter().getRoute("downloads").attachPatternMatched(this._onMatched, this); }, /** * Handles "downloads" routing * @function * @private */ _onMatched: function () { this.hideMasterSide(); } }); } );
{ "content_hash": "92c3e1ff82516f37e47ec7566721cbd8", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 87, "avg_line_length": 19.821428571428573, "alnum_prop": 0.6306306306306306, "repo_name": "SAP/openui5", "id": "5bae057aabaf7b21fcf630b283048ca82a3fbcf0", "size": "578", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sap.ui.documentation/src/sap/ui/documentation/sdk/controller/Downloads.controller.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "294216" }, { "name": "Gherkin", "bytes": "17201" }, { "name": "HTML", "bytes": "6443688" }, { "name": "Java", "bytes": "83398" }, { "name": "JavaScript", "bytes": "109546491" }, { "name": "Less", "bytes": "8741757" }, { "name": "TypeScript", "bytes": "20918" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Configuration; using System.IdentityModel.Claims; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using Owin; using _2016MT45.Models; namespace _2016MT45 { public partial class Startup { private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"]; private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; private string authority = aadInstance + "common"; private ApplicationDbContext db = new ApplicationDbContext(); public string ResponseType { get; private set; } public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions { }); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, Authority = authority, ResponseType = "code id_token", TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { // instead of using the default validation (validating against a single issuer value, as we do in line of business apps), // we inject our own multitenant validation logic ValidateIssuer = false, }, Notifications = new OpenIdConnectAuthenticationNotifications() { RedirectToIdentityProvider = (context) => { //string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase; //context.ProtocolMessage.RedirectUri = appBaseUrl; //context.ProtocolMessage.PostLogoutRedirectUri= appBaseUrl; context.ProtocolMessage.Prompt = "admin_consent"; return Task.FromResult(0); }, SecurityTokenValidated = (context) => { return Task.FromResult(0); }, AuthorizationCodeReceived = (context) => { var code = context.Code; ClientCredential credential = new ClientCredential(clientId, appKey); string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID)); var redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)); //Graph AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode( code, redirectUri, credential, "https://graph.windows.net"); //Microsoft Graph result = authContext.AcquireTokenByAuthorizationCode( code, redirectUri, credential, "https://graph.microsoft.com"); //Our WebAPI: //https://localhost:44308/ //But ID: https://tkopaczmsE3.onmicrosoft.com/eef85c5a-61d4-46c0-b27e-e354c57ca071 result = authContext.AcquireTokenByAuthorizationCode( code, redirectUri, credential, "https://tkopaczmsE3.onmicrosoft.com/eef85c5a-61d4-46c0-b27e-e354c57ca071"); return Task.FromResult(0); }, AuthenticationFailed = (context) => { context.OwinContext.Response.Redirect("/Home/Error"); context.HandleResponse(); // Suppress the exception return Task.FromResult(0); } } }); } } }
{ "content_hash": "fecbc5c67da3e1e946e74ceeb4e2a3b7", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 157, "avg_line_length": 49.642857142857146, "alnum_prop": 0.5570400822199383, "repo_name": "tkopacz/2016NetCoreWebApiOneDriveBusiness", "id": "8875190025e74b42131adeb415a629cd251d38f3", "size": "4867", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2016MT45/2016MT45/App_Start/Startup.Auth.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "690" }, { "name": "Batchfile", "bytes": "52" }, { "name": "C#", "bytes": "530087" }, { "name": "CSS", "bytes": "8831" }, { "name": "HTML", "bytes": "108499" }, { "name": "JavaScript", "bytes": "43423" } ], "symlink_target": "" }
 #pragma once #include <aws/connect/Connect_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/connect/model/PhoneNumberType.h> #include <aws/connect/model/PhoneNumberCountryCode.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Connect { namespace Model { /** * <p>Contains summary information about a phone number for a contact * center.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/connect-2017-08-08/PhoneNumberSummary">AWS * API Reference</a></p> */ class AWS_CONNECT_API PhoneNumberSummary { public: PhoneNumberSummary(); PhoneNumberSummary(Aws::Utils::Json::JsonView jsonValue); PhoneNumberSummary& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The identifier of the phone number.</p> */ inline const Aws::String& GetId() const{ return m_id; } /** * <p>The identifier of the phone number.</p> */ inline bool IdHasBeenSet() const { return m_idHasBeenSet; } /** * <p>The identifier of the phone number.</p> */ inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; } /** * <p>The identifier of the phone number.</p> */ inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); } /** * <p>The identifier of the phone number.</p> */ inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); } /** * <p>The identifier of the phone number.</p> */ inline PhoneNumberSummary& WithId(const Aws::String& value) { SetId(value); return *this;} /** * <p>The identifier of the phone number.</p> */ inline PhoneNumberSummary& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;} /** * <p>The identifier of the phone number.</p> */ inline PhoneNumberSummary& WithId(const char* value) { SetId(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the phone number.</p> */ inline const Aws::String& GetArn() const{ return m_arn; } /** * <p>The Amazon Resource Name (ARN) of the phone number.</p> */ inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the phone number.</p> */ inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; } /** * <p>The Amazon Resource Name (ARN) of the phone number.</p> */ inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the phone number.</p> */ inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the phone number.</p> */ inline PhoneNumberSummary& WithArn(const Aws::String& value) { SetArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the phone number.</p> */ inline PhoneNumberSummary& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the phone number.</p> */ inline PhoneNumberSummary& WithArn(const char* value) { SetArn(value); return *this;} /** * <p>The phone number.</p> */ inline const Aws::String& GetPhoneNumber() const{ return m_phoneNumber; } /** * <p>The phone number.</p> */ inline bool PhoneNumberHasBeenSet() const { return m_phoneNumberHasBeenSet; } /** * <p>The phone number.</p> */ inline void SetPhoneNumber(const Aws::String& value) { m_phoneNumberHasBeenSet = true; m_phoneNumber = value; } /** * <p>The phone number.</p> */ inline void SetPhoneNumber(Aws::String&& value) { m_phoneNumberHasBeenSet = true; m_phoneNumber = std::move(value); } /** * <p>The phone number.</p> */ inline void SetPhoneNumber(const char* value) { m_phoneNumberHasBeenSet = true; m_phoneNumber.assign(value); } /** * <p>The phone number.</p> */ inline PhoneNumberSummary& WithPhoneNumber(const Aws::String& value) { SetPhoneNumber(value); return *this;} /** * <p>The phone number.</p> */ inline PhoneNumberSummary& WithPhoneNumber(Aws::String&& value) { SetPhoneNumber(std::move(value)); return *this;} /** * <p>The phone number.</p> */ inline PhoneNumberSummary& WithPhoneNumber(const char* value) { SetPhoneNumber(value); return *this;} /** * <p>The type of phone number.</p> */ inline const PhoneNumberType& GetPhoneNumberType() const{ return m_phoneNumberType; } /** * <p>The type of phone number.</p> */ inline bool PhoneNumberTypeHasBeenSet() const { return m_phoneNumberTypeHasBeenSet; } /** * <p>The type of phone number.</p> */ inline void SetPhoneNumberType(const PhoneNumberType& value) { m_phoneNumberTypeHasBeenSet = true; m_phoneNumberType = value; } /** * <p>The type of phone number.</p> */ inline void SetPhoneNumberType(PhoneNumberType&& value) { m_phoneNumberTypeHasBeenSet = true; m_phoneNumberType = std::move(value); } /** * <p>The type of phone number.</p> */ inline PhoneNumberSummary& WithPhoneNumberType(const PhoneNumberType& value) { SetPhoneNumberType(value); return *this;} /** * <p>The type of phone number.</p> */ inline PhoneNumberSummary& WithPhoneNumberType(PhoneNumberType&& value) { SetPhoneNumberType(std::move(value)); return *this;} /** * <p>The ISO country code.</p> */ inline const PhoneNumberCountryCode& GetPhoneNumberCountryCode() const{ return m_phoneNumberCountryCode; } /** * <p>The ISO country code.</p> */ inline bool PhoneNumberCountryCodeHasBeenSet() const { return m_phoneNumberCountryCodeHasBeenSet; } /** * <p>The ISO country code.</p> */ inline void SetPhoneNumberCountryCode(const PhoneNumberCountryCode& value) { m_phoneNumberCountryCodeHasBeenSet = true; m_phoneNumberCountryCode = value; } /** * <p>The ISO country code.</p> */ inline void SetPhoneNumberCountryCode(PhoneNumberCountryCode&& value) { m_phoneNumberCountryCodeHasBeenSet = true; m_phoneNumberCountryCode = std::move(value); } /** * <p>The ISO country code.</p> */ inline PhoneNumberSummary& WithPhoneNumberCountryCode(const PhoneNumberCountryCode& value) { SetPhoneNumberCountryCode(value); return *this;} /** * <p>The ISO country code.</p> */ inline PhoneNumberSummary& WithPhoneNumberCountryCode(PhoneNumberCountryCode&& value) { SetPhoneNumberCountryCode(std::move(value)); return *this;} private: Aws::String m_id; bool m_idHasBeenSet = false; Aws::String m_arn; bool m_arnHasBeenSet = false; Aws::String m_phoneNumber; bool m_phoneNumberHasBeenSet = false; PhoneNumberType m_phoneNumberType; bool m_phoneNumberTypeHasBeenSet = false; PhoneNumberCountryCode m_phoneNumberCountryCode; bool m_phoneNumberCountryCodeHasBeenSet = false; }; } // namespace Model } // namespace Connect } // namespace Aws
{ "content_hash": "03caecb76c2ac402e2435ac69e597e22", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 165, "avg_line_length": 30.34016393442623, "alnum_prop": 0.6456841820883426, "repo_name": "aws/aws-sdk-cpp", "id": "f53e211917edae1b17219074cf69f0e85e9b96a5", "size": "7522", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "aws-cpp-sdk-connect/include/aws/connect/model/PhoneNumberSummary.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
+++ title = "Rule Definition" weight = 2 chapter = true +++ This chapter describes the syntax of rule definition.
{ "content_hash": "89668c6534e8538225cb01dd47edc846", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 53, "avg_line_length": 16.428571428571427, "alnum_prop": 0.7130434782608696, "repo_name": "apache/incubator-shardingsphere", "id": "94d0a9949493cb4c45e4f12c20da3126fd2ade71", "size": "115", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "docs/document/content/user-manual/shardingsphere-proxy/distsql/syntax/rdl/rule-definition/_index.en.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "269258" }, { "name": "Batchfile", "bytes": "3280" }, { "name": "CSS", "bytes": "2842" }, { "name": "Dockerfile", "bytes": "1485" }, { "name": "HTML", "bytes": "2146" }, { "name": "Java", "bytes": "7542761" }, { "name": "JavaScript", "bytes": "92884" }, { "name": "Shell", "bytes": "9837" }, { "name": "TSQL", "bytes": "68705" }, { "name": "Vue", "bytes": "81855" } ], "symlink_target": "" }
using namespace seqan; using namespace std; template<typename TPath> int readCommandlineParameters(TPath & clusteredDatabase, TPath & clusterRepresentanten, TPath & queries, TPath & outFile, string & scoreMode, int & argc, char const ** & argv) { // Setup ArgumentParser. seqan::ArgumentParser parser("GSearch"); addUsageLine(parser, "[\\fIOPTIONS\\fP] \"Database\" \"ClusterMaster\" \"Queries\" \"outPathMatches\""); addArgument( parser, seqan::ArgParseArgument(seqan::ArgParseArgument::STRING, "Path to input cluster FASTA")); addArgument( parser, seqan::ArgParseArgument(seqan::ArgParseArgument::STRING, "Path to input Master FASTA")); addArgument( parser, seqan::ArgParseArgument(seqan::ArgParseArgument::STRING, "Path to input queries FASTA")); addArgument( parser, seqan::ArgParseArgument(seqan::ArgParseArgument::STRING, "Path to output file FASTA")); addSection(parser, "Modification Options"); addOption( parser, seqan::ArgParseOption("m", "scoringMode", "mode of scoring function.\n\tLOCAL_ALIGNMENT_MODE\n\tCOMMON_QGRAM_MODE", seqan::ArgParseArgument::STRING, "STRING")); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return 1;//res == seqan::ArgumentParser::PARSE_ERROR; getArgumentValue(clusteredDatabase, parser, 0); getArgumentValue(clusterRepresentanten, parser, 1); getArgumentValue(queries, parser, 2); getArgumentValue(outFile, parser, 3); getOptionValue(scoreMode, parser, "scoringMode"); return 0; } int checkStreams(SequenceStream &myCluster, SequenceStream &myMaster, SequenceStream &myQueries, fstream &myOutput) { if (!isGood(myCluster)) { std::cerr << "ERROR: Could not open the clustered database file in function GSearch.\n"; return 1; } if (!isGood(myMaster)) { std::cerr << "ERROR: Could not open the master sequences file in function GSearch.\n"; return 1; } if (!isGood(myQueries)) { std::cerr << "ERROR: Could not open the queries file in function GSearch.\n"; return 1; } if (!myOutput.good()) { std::cerr << "ERROR: Could not open the output file in function GSearch.\n"; return 1; } return 0; } int GSearch(String<PerformanceSample> & performance, int argc, char const ** argv) { PerformanceSample perfSearchFunc("GSearch Funktion"); typedef Score<int> TScoringScheme; typedef int TScore; typedef Rna5String TSequence; String<char> queries; String<char> outFile; String<char> clusterRepresentanten; String<char> clusteredDatabase; string scoreMode; if (readCommandlineParameters(clusteredDatabase, clusterRepresentanten, queries, outFile, scoreMode, argc, argv)) return 1; SequenceStream myCluster(toCString(clusteredDatabase)); SequenceStream myMaster(toCString(clusterRepresentanten)); SequenceStream myQueries(toCString(queries)); std::fstream myOutput(toCString(outFile), std::ios::binary | std::ios::out); if (checkStreams(myCluster, myMaster, myQueries, myOutput)) return 1; TScoringScheme scoringScheme(1, -2, -1); GFastaRecord<TSequence> queryRecord; GFastaRecord<TSequence> referenceRecord; GFastaRecord<TSequence> clusterRecord; TScore score; String<GMatch<TScore> > matches; String<PerformanceSample> perfQueryAvgContainer; while (!readRecord(queryRecord.id, queryRecord.seq, myQueries)) { PerformanceSample perfQueryAvg(""); open(myMaster, toCString(clusterRepresentanten)); GScoreStorage<TScore> scoreStorage; while(!readRecord(referenceRecord.id, referenceRecord.seq, myMaster)) { GScore(score, queryRecord, referenceRecord, scoringScheme, scoreMode); GEvaluateScore(scoreStorage, score, referenceRecord); } open(myCluster, toCString(clusteredDatabase)); while(!readRecord(clusterRecord.id, clusterRecord.seq, myCluster)) { if (GCheckClusterMaster(scoreStorage, clusterRecord)) { GComputeMatch(matches, queryRecord, clusterRecord, scoringScheme, scoreMode); } } GPostProcessMatches(matches); GWriteMatches(myOutput, matches, queryRecord); perfQueryAvg.end(); appendValue(perfQueryAvgContainer, perfQueryAvg); } PerformanceSample perfQueryAvg("Handle one query in GSearch average"); perfQueryAvg.takeAverageValues(perfQueryAvgContainer); appendValue(performance, perfQueryAvg); perfSearchFunc.end(); appendValue(performance, perfSearchFunc); return 0; } #endif // GINGER_GSEARCH_GSEARCH_BASE_H_
{ "content_hash": "27c4cfa874988f70392e47c4192b9eed", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 177, "avg_line_length": 35.285714285714285, "alnum_prop": 0.6955465587044535, "repo_name": "bkahlert/seqan-research", "id": "0a21a25ad796fa147a56e20156562e3bffd10e2f", "size": "5641", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "raw/pmsb13/pmsb13-data-20130530/sources/qhuulr654q26tohr/2013-05-14T10-48-50.127+0200/sandbox/PMSB_group6/include/seqan/GSearch/GSearch_base.h", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "39014" }, { "name": "Awk", "bytes": "44044" }, { "name": "Batchfile", "bytes": "37736" }, { "name": "C", "bytes": "1261223" }, { "name": "C++", "bytes": "277576131" }, { "name": "CMake", "bytes": "5546616" }, { "name": "CSS", "bytes": "271972" }, { "name": "GLSL", "bytes": "2280" }, { "name": "Groff", "bytes": "2694006" }, { "name": "HTML", "bytes": "15207297" }, { "name": "JavaScript", "bytes": "362928" }, { "name": "LSL", "bytes": "22561" }, { "name": "Makefile", "bytes": "6418610" }, { "name": "Objective-C", "bytes": "3730085" }, { "name": "PHP", "bytes": "3302" }, { "name": "Perl", "bytes": "10468" }, { "name": "PostScript", "bytes": "22762" }, { "name": "Python", "bytes": "9267035" }, { "name": "R", "bytes": "230698" }, { "name": "Rebol", "bytes": "283" }, { "name": "Shell", "bytes": "437340" }, { "name": "Tcl", "bytes": "15439" }, { "name": "TeX", "bytes": "738415" }, { "name": "VimL", "bytes": "12685" } ], "symlink_target": "" }
package com.microsoft.azure.management.apimanagement.v2019_12_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.apimanagement.v2019_12_01.UserGroups; import rx.Observable; import rx.functions.Func1; import com.microsoft.azure.Page; import com.microsoft.azure.management.apimanagement.v2019_12_01.UserGroupContract; class UserGroupsImpl extends WrapperImpl<UserGroupsInner> implements UserGroups { private final ApiManagementManager manager; UserGroupsImpl(ApiManagementManager manager) { super(manager.inner().userGroups()); this.manager = manager; } public ApiManagementManager manager() { return this.manager; } private UserGroupContractImpl wrapModel(GroupContractInner inner) { return new UserGroupContractImpl(inner, manager()); } @Override public Observable<UserGroupContract> listAsync(final String resourceGroupName, final String serviceName, final String userId) { UserGroupsInner client = this.inner(); return client.listAsync(resourceGroupName, serviceName, userId) .flatMapIterable(new Func1<Page<GroupContractInner>, Iterable<GroupContractInner>>() { @Override public Iterable<GroupContractInner> call(Page<GroupContractInner> page) { return page.items(); } }) .map(new Func1<GroupContractInner, UserGroupContract>() { @Override public UserGroupContract call(GroupContractInner inner) { return wrapModel(inner); } }); } }
{ "content_hash": "e221629e1e88b23786c625ea591ef746", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 131, "avg_line_length": 35.67391304347826, "alnum_prop": 0.7074954296160878, "repo_name": "selvasingh/azure-sdk-for-java", "id": "7f521783632d0d5edd282f7aa449e19c857e2679", "size": "1874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/implementation/UserGroupsImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29891970" }, { "name": "JavaScript", "bytes": "6198" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/pepper/content_renderer_pepper_host_factory.h" #include "base/logging.h" #include "content/renderer/pepper/pepper_audio_input_host.h" #include "content/renderer/pepper/pepper_directory_reader_host.h" #include "content/renderer/pepper/pepper_file_chooser_host.h" #include "content/renderer/pepper/pepper_file_io_host.h" #include "content/renderer/pepper/pepper_graphics_2d_host.h" #include "content/renderer/pepper/pepper_video_capture_host.h" #include "content/renderer/pepper/pepper_websocket_host.h" #include "content/renderer/pepper/renderer_ppapi_host_impl.h" #include "ppapi/host/resource_host.h" #include "ppapi/proxy/ppapi_messages.h" using ppapi::host::ResourceHost; namespace content { ContentRendererPepperHostFactory::ContentRendererPepperHostFactory( RendererPpapiHostImpl* host) : host_(host) { } ContentRendererPepperHostFactory::~ContentRendererPepperHostFactory() { } scoped_ptr<ResourceHost> ContentRendererPepperHostFactory::CreateResourceHost( ppapi::host::PpapiHost* host, const ppapi::proxy::ResourceMessageCallParams& params, PP_Instance instance, const IPC::Message& message) { DCHECK(host == host_->GetPpapiHost()); // Make sure the plugin is giving us a valid instance for this resource. if (!host_->IsValidInstance(instance)) return scoped_ptr<ResourceHost>(); // Public interfaces. switch (message.type()) { case PpapiHostMsg_Graphics2D_Create::ID: { PpapiHostMsg_Graphics2D_Create::Schema::Param msg_params; if (!PpapiHostMsg_Graphics2D_Create::Read(&message, &msg_params)) { NOTREACHED(); return scoped_ptr<ResourceHost>(); } return scoped_ptr<ResourceHost>( PepperGraphics2DHost::Create(host_, instance, params.pp_resource(), msg_params.a /* PP_Size */, msg_params.b /* PP_Bool */)); } case PpapiHostMsg_WebSocket_Create::ID: return scoped_ptr<ResourceHost>(new PepperWebSocketHost( host_, instance, params.pp_resource())); case PpapiHostMsg_FileIO_Create::ID: return scoped_ptr<ResourceHost>(new PepperFileIOHost( host_, instance, params.pp_resource())); } // Dev interfaces. if (GetPermissions().HasPermission(ppapi::PERMISSION_DEV)) { switch (message.type()) { case PpapiHostMsg_AudioInput_Create::ID: return scoped_ptr<ResourceHost>(new PepperAudioInputHost( host_, instance, params.pp_resource())); case PpapiHostMsg_DirectoryReader_Create::ID: return scoped_ptr<ResourceHost>(new PepperDirectoryReaderHost( host_, instance, params.pp_resource())); case PpapiHostMsg_FileChooser_Create::ID: return scoped_ptr<ResourceHost>(new PepperFileChooserHost( host_, instance, params.pp_resource())); case PpapiHostMsg_VideoCapture_Create::ID: { PepperVideoCaptureHost* host = new PepperVideoCaptureHost( host_, instance, params.pp_resource()); if (!host->Init()) { delete host; return scoped_ptr<ResourceHost>(); } return scoped_ptr<ResourceHost>(host); } } } return scoped_ptr<ResourceHost>(); } const ppapi::PpapiPermissions& ContentRendererPepperHostFactory::GetPermissions() const { return host_->GetPpapiHost()->permissions(); } } // namespace content
{ "content_hash": "abbd0dbf0fc0bbc50ba4613ff3e27f1c", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 78, "avg_line_length": 37.694736842105264, "alnum_prop": 0.6931024853392908, "repo_name": "zcbenz/cefode-chromium", "id": "bb42068d1b6a65f8461bd7ff8ca6319cf8b87878", "size": "3581", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "content/renderer/pepper/content_renderer_pepper_host_factory.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "853" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "1174304" }, { "name": "Awk", "bytes": "9519" }, { "name": "C", "bytes": "76026099" }, { "name": "C#", "bytes": "1132" }, { "name": "C++", "bytes": "157904700" }, { "name": "DOT", "bytes": "1559" }, { "name": "F#", "bytes": "381" }, { "name": "Java", "bytes": "3225038" }, { "name": "JavaScript", "bytes": "18180217" }, { "name": "Logos", "bytes": "4517" }, { "name": "Matlab", "bytes": "5234" }, { "name": "Objective-C", "bytes": "7139426" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "932901" }, { "name": "Python", "bytes": "8654916" }, { "name": "R", "bytes": "262" }, { "name": "Ragel in Ruby Host", "bytes": "3621" }, { "name": "Shell", "bytes": "1533012" }, { "name": "Tcl", "bytes": "277077" }, { "name": "XML", "bytes": "13493" } ], "symlink_target": "" }
Hi! Thanks for reporting this feature/bug/question! Please keep / fill in the relevant info from this template so that we can help you as best as possible. QUESTIONS are preferred on StackOverflow. You could expect a faster response there (but do include all the info below). Use the tag "nlog" https://stackoverflow.com/questions/ask Please only post issues here related to NLog.Web. If unsure, please post on https://github.com/NLog/NLog/issues/new **Type** (choose one): - Bug - Feature request - Question **NLog version**: (e.g. 4.5.6) **NLog.Web / NLog.Web.AspNetCore version**: **NLog.Extensions.Logging version**: **Platform**: .Net 3.5 / .Net 4.6 / .NET Core 3.1 / .NET 6.0 **Current NLog config** (xml or C#, if relevant) ```xml <nlog> <targets> </targets> <rules> </rules> </nlog> ``` In case of a BUG: - What is the current result? - What is the expected result? - Did you checked the [Internal log](https://github.com/NLog/NLog/wiki/Internal-Logging)? - Please post full exception details (message, stacktrace, inner exceptions) - Are there any workarounds? yes/no - Is there a version in which it did work? - Can you help us by writing an unit test? In case of a FEATURE REQUEST: - Why do we need it? - An example of the XML config, if relevant.
{ "content_hash": "93040645a9a33c2c9833f454770b9276", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 178, "avg_line_length": 25.86, "alnum_prop": 0.7076566125290024, "repo_name": "NLog/NLog.Web", "id": "61af1fd57d43f6c3ba06c85760abc71960a9b39f", "size": "1293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".github/ISSUE_TEMPLATE.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "608369" }, { "name": "PowerShell", "bytes": "1500" } ], "symlink_target": "" }
set -e if [ "$(uname)" == "Darwin" ]; then SEDINPLACE='sed -i ""' else SEDINPLACE='sed -i' fi if [[ "$(pwd)" != "$(git rev-parse --show-toplevel)" ]]; then printf '#### WARNING: This should be run in the git top level directory! ####\n' > /dev/stderr fi export BACH_ENVIRONMENT=${BACH_ENVIRONMENT:-'Test-Laptop'} export BACH_CLUSTER_PREFIX=${BACH_CLUSTER_PREFIX:-''} export CLUSTER_TYPE=${CLUSTER_TYPE:-Hadoop} export PATH=/opt/chefdk/embedded/bin:$PATH # normalize capitaliztion of CLUSTER_TYPE to lower case typeset -l CLUSTER_TYPE="${CLUSTER_TYPE}" printf "#### Setup configuration files\n" # setup vagrant $SEDINPLACE 's/vb.gui = true/vb.gui = false/' Vagrantfile # Prepare the test environment file and inject local settings. #if hash ruby; then #ruby ./tests/edit_environment.rb #else printf "#### WARNING: no ruby found -- proceeding without editing environment!\n" > /dev/stderr mkdir -p ../cluster cp -rv stub-environment/* ../cluster #fi if [ "${CLUSTER_TYPE,,}" == "kafka" ]; then printf "Using kafka_cluster.txt\n" cp stub-environment/kafka_cluster.txt ../cluster/cluster.txt else printf "Using hadoop_cluster.txt\n" cp stub-environment/hadoop_cluster.txt ../cluster/cluster.txt fi # Remove unused files. rm -f ../cluster/kafka_cluster.txt rm -f ../cluster/hadoop_cluster.txt printf "#### Setup VB's and Bootstrap\n" source ./vbox_create.sh # VM Snapshot Statemachine: # After cluster-assign-roles Bootstrap Step: SNAP_POST_BASIC='Post-Basic' # After cluster-assign-roles <cluster> Step: SNAP_POST_BOOTSTRAP='Post-Bootstrap' # After cluster-assign-roles <cluster> Step: SNAP_POST_INSTALL='Post-Install' download_VM_files || ( echo "############## VBOX CREATE DOWNLOAD VM FILES RETURNED $? ##############" && exit 1 ) create_bootstrap_VM || ( echo "############## VBOX CREATE BOOTSTRAP VM RETURNED $? ##############" && exit 1 ) python_to_find_bootstrap_ip="import json; j = json.load(file('${environments[0]}')); print j['override_attributes']['bcpc']['bootstrap']['server']" BOOTSTRAP_IP=$(python -c "$python_to_find_bootstrap_ip") create_cluster_VMs || ( echo "############## VBOX CREATE CLUSTER VMs RETURNED $? ##############" && exit 1 ) install_cluster $BACH_ENVIRONMENT $BOOTSTRAP_IP || ( echo "############## VBOX CREATE INSTALL CLUSTER RETURNED $? ##############" && exit 1 ) printf "#### Chef the nodes with Basic role\n" vagrant ssh -c "cd chef-bcpc; ./cluster-assign-roles.sh $BACH_ENVIRONMENT Basic" snapshotVMs "${SNAP_POST_BASIC}" printf "#### Chef the nodes with complete roles\n" printf "Cluster type: $CLUSTER_TYPE\n" # Kafka does not run Bootstrap step if [ "${CLUSTER_TYPE,,}" == "hadoop" ]; then printf "Running C-A-R 'bootstrap' before final C-A-R" # https://github.com/bloomberg/chef-bach/issues/847 # We know the first run might fail set +e set +e vagrant ssh -c "cd chef-bcpc; ./cluster-assign-roles.sh $BACH_ENVIRONMENT Bootstrap" set -e # if we still fail here we have some other issue vagrant ssh -c "cd chef-bcpc; ./cluster-assign-roles.sh $BACH_ENVIRONMENT Bootstrap" snapshotVMs "${SNAP_POST_BOOTSTRAP}" printf "Running final C-A-R(s)" fi printf "#### Chef machine bcpc-vms with $CLUSTER_TYPE\n" vagrant ssh -c "cd chef-bcpc; ./cluster-assign-roles.sh $BACH_ENVIRONMENT $CLUSTER_TYPE" # for Hadoop installs we need to re-run the headnodes once HDFS is up to ensure # we deploy various JARs. Run a second time once a datanode is up. if [[ "${CLUSTER_TYPE,,}" == "hadoop" ]]; then vagrant ssh -c "cd chef-bcpc; ./cluster-assign-roles.sh $BACH_ENVIRONMENT $CLUSTER_TYPE BCPC-Hadoop-Head" fi snapshotVMs "${SNAP_POST_INSTALL}" printf '#### Install Completed!\n'
{ "content_hash": "9d6f4ca707fcbb4acd6369fa674a4e96", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 147, "avg_line_length": 37.76288659793814, "alnum_prop": 0.6827736827736828, "repo_name": "kiiranh/chef-bach", "id": "7e82b611b465a9eae0f71167280fcbc151a940f6", "size": "4048", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/automated_install.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "912" }, { "name": "HTML", "bytes": "317513" }, { "name": "Python", "bytes": "12012" }, { "name": "Ruby", "bytes": "907292" }, { "name": "Shell", "bytes": "118230" } ], "symlink_target": "" }
package org.apache.hms.common.util; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.GridLayout; import java.io.IOException; import java.util.Enumeration; import java.util.Vector; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; import javax.jmdns.ServiceTypeListener; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; /** * User Interface for browsing JmDNS services. * * @author Arthur van Hoff, Werner Randelshofer * @version %I%, %G% */ public class ServiceDiscovery extends JFrame implements ServiceListener, ServiceTypeListener, ListSelectionListener { JmDNS jmdns; Vector headers; String type; DefaultListModel types; JList typeList; DefaultListModel services; JList serviceList; JTextArea info; ServiceDiscovery(JmDNS jmdns) throws IOException { super("JmDNS Browser"); this.jmdns = jmdns; Color bg = new Color(230, 230, 230); EmptyBorder border = new EmptyBorder(5, 5, 5, 5); Container content = getContentPane(); content.setLayout(new GridLayout(1, 3)); types = new DefaultListModel(); typeList = new JList(types); typeList.setBorder(border); typeList.setBackground(bg); typeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); typeList.addListSelectionListener(this); JPanel typePanel = new JPanel(); typePanel.setLayout(new BorderLayout()); typePanel.add("North", new JLabel("Types")); typePanel.add("Center", new JScrollPane(typeList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); content.add(typePanel); services = new DefaultListModel(); serviceList = new JList(services); serviceList.setBorder(border); serviceList.setBackground(bg); serviceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); serviceList.addListSelectionListener(this); JPanel servicePanel = new JPanel(); servicePanel.setLayout(new BorderLayout()); servicePanel.add("North", new JLabel("Services")); servicePanel.add("Center", new JScrollPane(serviceList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); content.add(servicePanel); info = new JTextArea(); info.setBorder(border); info.setBackground(bg); info.setEditable(false); info.setLineWrap(true); JPanel infoPanel = new JPanel(); infoPanel.setLayout(new BorderLayout()); infoPanel.add("North", new JLabel("Details")); infoPanel.add("Center", new JScrollPane(info, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); content.add(infoPanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocation(100, 100); setSize(600, 400); jmdns.addServiceTypeListener(this); // register some well known types String list[] = new String[] { "_http._tcp.local.", "_ftp._tcp.local.", "_tftp._tcp.local.", "_ssh._tcp.local.", "_smb._tcp.local.", "_printer._tcp.local.", "_airport._tcp.local.", "_afpovertcp._tcp.local.", "_ichat._tcp.local.", "_eppc._tcp.local.", "_presence._tcp.local.", "_zookeeper._tcp.local.", "_test._tcp.local." }; for (int i = 0 ; i < list.length ; i++) { jmdns.registerServiceType(list[i]); } show(); } /** * Add a service. */ public void serviceAdded(ServiceEvent event) { final String name = event.getName(); System.out.println("ADD: " + name); SwingUtilities.invokeLater(new Runnable() { public void run() { insertSorted(services, name); } }); } /** * Remove a service. */ public void serviceRemoved(ServiceEvent event) { final String name = event.getName(); System.out.println("REMOVE: " + name); SwingUtilities.invokeLater(new Runnable() { public void run() { services.removeElement(name); } }); } /** * A new service type was <discovered. */ public void serviceTypeAdded(ServiceEvent event) { final String type = event.getType(); System.out.println("TYPE: " + type); SwingUtilities.invokeLater(new Runnable() { public void run() { insertSorted(types, type); } }); } void insertSorted(DefaultListModel model, String value) { for (int i = 0, n = model.getSize() ; i < n ; i++) { if (value.compareToIgnoreCase((String)model.elementAt(i)) < 0) { model.insertElementAt(value, i); return; } } model.addElement(value); } /** * Resolve a service. */ public void serviceResolved(ServiceEvent event) { String name = event.getName(); String type = event.getType(); ServiceInfo info = event.getInfo(); if (name.equals(serviceList.getSelectedValue())) { if (info == null) { this.info.setText("service not found"); } else { StringBuffer buf = new StringBuffer(); buf.append(name); buf.append('.'); buf.append(type); buf.append('\n'); buf.append(info.getServer()); buf.append(':'); buf.append(info.getPort()); buf.append('\n'); buf.append(info.getAddress()); buf.append(':'); buf.append(info.getPort()); buf.append('\n'); for (Enumeration names = info.getPropertyNames() ; names.hasMoreElements() ; ) { String prop = (String)names.nextElement(); buf.append(prop); buf.append('='); buf.append(info.getPropertyString(prop)); buf.append('\n'); } this.info.setText(buf.toString()); } } } /** * List selection changed. */ public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { if (e.getSource() == typeList) { type = (String)typeList.getSelectedValue(); jmdns.removeServiceListener(type, this); services.setSize(0); info.setText(""); if (type != null) { jmdns.addServiceListener(type, this); } } else if (e.getSource() == serviceList) { String name = (String)serviceList.getSelectedValue(); if (name == null) { info.setText(""); } else { System.out.println(this+" valueChanged() type:"+type+" name:"+name); System.out.flush(); ServiceInfo service = jmdns.getServiceInfo(type, name); if (service == null) { info.setText("service not found"); } else { jmdns.requestServiceInfo(type, name); } } } } } /** * Table data. */ class ServiceTableModel extends AbstractTableModel { public String getColumnName(int column) { switch (column) { case 0: return "service"; case 1: return "address"; case 2: return "port"; case 3: return "text"; } return null; } public int getColumnCount() { return 1; } public int getRowCount() { return services.size(); } public Object getValueAt(int row, int col) { return services.elementAt(row); } } public String toString() { return "RVBROWSER"; } /** * Main program. */ public static void main(String argv[]) throws IOException { new ServiceDiscovery(JmDNS.create()); } @Override public void subTypeForServiceTypeAdded(ServiceEvent arg0) { // TODO Auto-generated method stub } }
{ "content_hash": "b53458b1d7bddc04241dc4045f42bc90", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 153, "avg_line_length": 33.4468085106383, "alnum_prop": 0.5405004240882103, "repo_name": "macroadster/HMS", "id": "72e277ec3c228636e8a647c129c485e762036f23", "size": "10237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/java/org/apache/hms/common/util/ServiceDiscovery.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "281850" }, { "name": "JavaScript", "bytes": "112597" }, { "name": "Python", "bytes": "48753" }, { "name": "Shell", "bytes": "51250" } ], "symlink_target": "" }
/* * Category.cpp * * Created on: 25 March 2015 * Author: cyosp */ #include <com/cyosp/mpa/core/Category.hpp> namespace mpapo { // Check if a category exists with the same name before to set the category name void Category::setName(int accountId, string name) { int categoryId = mpa::Category::getCategoryId(accountId, name); //MPA_LOG_TRIVIAL(trace,"setName1"); //usleep( 10000000 ); //MPA_LOG_TRIVIAL(trace,"setName2"); if( categoryId == 0 ) { this->name = name; setUpdated(); } else throw mpa_exception::MsgNotTranslated(CATEGORY_SAME_NAME_ALREADY_EXIST); } void Category::setAmount(float amount) { this->amount = amount; setUpdated(); } void Category::addToAmount(float amount) { this->amount = this->amount + amount; setUpdated(); } }
{ "content_hash": "e5b9c8d82b3bd9b84c9fae2b6d414fb3", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 84, "avg_line_length": 21.181818181818183, "alnum_prop": 0.5761802575107297, "repo_name": "cyosp/MPA", "id": "e8f043319228bca483ea918e5dfd17a31e73c32d", "size": "932", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/cyosp/mpa/po/Category.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* RecordComparer.cs -- * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System.Collections.Generic; using JetBrains.Annotations; using MoonSharp.Interpreter; #endregion // ReSharper disable PossibleNullReferenceException namespace ManagedIrbis { /// <summary> /// /// </summary> [PublicAPI] [MoonSharpUserData] public static class RecordComparer { #region Nested classes sealed class ByMfnComparer : IComparer<MarcRecord> { /// <inheritdoc cref="IComparer{T}.Compare" /> public int Compare ( MarcRecord x, MarcRecord y ) { return x.Mfn - y.Mfn; } } sealed class ByIndexComparer : IComparer<MarcRecord> { /// <inheritdoc cref="IComparer{T}.Compare" /> public int Compare ( MarcRecord x, MarcRecord y ) { return string.CompareOrdinal ( x.Index, y.Index ); } } sealed class ByDescriptionComparer : IComparer<MarcRecord> { /// <inheritdoc cref="IComparer{T}.Compare" /> public int Compare ( MarcRecord x, MarcRecord y ) { return string.CompareOrdinal ( x.Description, y.Description ); } } sealed class BySortKeyComparer : IComparer<MarcRecord> { /// <inheritdoc cref="IComparer{T}.Compare" /> public int Compare(MarcRecord x, MarcRecord y) { return string.CompareOrdinal ( x.SortKey, y.SortKey ); } } #endregion #region Public methods /// <summary> /// Compare <see cref="MarcRecord"/> by MFN. /// </summary> [NotNull] public static IComparer<MarcRecord> ByMfn() { return new ByMfnComparer(); } /// <summary> /// Compare <see cref="MarcRecord"/> by index. /// </summary> [NotNull] public static IComparer<MarcRecord> ByIndex() { return new ByIndexComparer(); } /// <summary> /// Compare <see cref="MarcRecord"/> by descrption. /// </summary> [NotNull] public static IComparer<MarcRecord> ByDescription() { return new ByDescriptionComparer(); } /// <summary> /// Compare <see cref="MarcRecord"/> by sort key. /// </summary> [NotNull] public static IComparer<MarcRecord> BySortKey() { return new BySortKeyComparer(); } #endregion } }
{ "content_hash": "0510e950f4cb531f1958d01f83117279", "timestamp": "", "source": "github", "line_count": 139, "max_line_length": 84, "avg_line_length": 24.66906474820144, "alnum_prop": 0.45290172061825607, "repo_name": "amironov73/ManagedIrbis", "id": "12785c853d3e020303f377af5683f348bdf45320", "size": "3431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Classic/Libs/ManagedIrbis/Source/RecordComparer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "92910" }, { "name": "ASP.NET", "bytes": "413" }, { "name": "Batchfile", "bytes": "33021" }, { "name": "C", "bytes": "24669" }, { "name": "C#", "bytes": "19567730" }, { "name": "CSS", "bytes": "170" }, { "name": "F*", "bytes": "362819" }, { "name": "HTML", "bytes": "5592" }, { "name": "JavaScript", "bytes": "5342" }, { "name": "Pascal", "bytes": "152697" }, { "name": "Shell", "bytes": "524" }, { "name": "Smalltalk", "bytes": "29356" }, { "name": "TeX", "bytes": "44337" }, { "name": "VBA", "bytes": "46543" }, { "name": "Witcher Script", "bytes": "40165" } ], "symlink_target": "" }
namespace sp = syncer::prefs; namespace csp = chromeos::settings::prefs; class OsSyncUtilTest : public testing::Test { public: OsSyncUtilTest() { feature_list_.InitAndEnableFeature( chromeos::features::kSyncSettingsCategorization); syncer::SyncPrefs::RegisterProfilePrefs(prefs_.registry()); chromeos::settings::OSSettingsUI::RegisterProfilePrefs(prefs_.registry()); } base::test::ScopedFeatureList feature_list_; sync_preferences::TestingPrefServiceSyncable prefs_; }; TEST_F(OsSyncUtilTest, SimpleMigration) { os_sync_util::MigrateOsSyncPreferences(&prefs_); EXPECT_TRUE(prefs_.GetBoolean(sp::kOsSyncPrefsMigrated)); EXPECT_TRUE(prefs_.GetBoolean(sp::kSyncAllOsTypes)); } TEST_F(OsSyncUtilTest, MigrationWithIndividualBrowserTypes) { // Customize the browser data types. prefs_.SetBoolean(sp::kSyncKeepEverythingSynced, false); prefs_.SetBoolean(sp::kSyncApps, true); prefs_.SetBoolean(sp::kSyncPreferences, true); prefs_.SetBoolean(sp::kSyncThemes, true); os_sync_util::MigrateOsSyncPreferences(&prefs_); // Equivalent OS types are enabled. EXPECT_FALSE(prefs_.GetBoolean(sp::kSyncAllOsTypes)); EXPECT_TRUE(prefs_.GetBoolean(sp::kSyncOsApps)); EXPECT_TRUE(prefs_.GetBoolean(sp::kSyncOsPreferences)); EXPECT_TRUE(prefs_.GetBoolean(csp::kSyncOsWallpaper)); } TEST_F(OsSyncUtilTest, MigrationForWallpaperRequiresApps) { prefs_.SetBoolean(sp::kSyncKeepEverythingSynced, false); ASSERT_FALSE(prefs_.GetBoolean(sp::kSyncApps)); prefs_.SetBoolean(sp::kSyncThemes, true); os_sync_util::MigrateOsSyncPreferences(&prefs_); EXPECT_FALSE(prefs_.GetBoolean(csp::kSyncOsWallpaper)); } TEST_F(OsSyncUtilTest, MigrationOnlyHappensOnce) { // Do initial migration. os_sync_util::MigrateOsSyncPreferences(&prefs_); // Customize some browser prefs. prefs_.SetBoolean(sp::kSyncKeepEverythingSynced, false); prefs_.SetBoolean(sp::kSyncApps, true); prefs_.SetBoolean(sp::kSyncPreferences, true); // Customize some OS prefs. prefs_.SetBoolean(sp::kSyncAllOsTypes, false); prefs_.SetBoolean(sp::kSyncOsApps, false); prefs_.SetBoolean(sp::kSyncOsPreferences, false); // Try to migrate again. os_sync_util::MigrateOsSyncPreferences(&prefs_); // OS prefs didn't change. EXPECT_FALSE(prefs_.GetBoolean(sp::kSyncAllOsTypes)); EXPECT_FALSE(prefs_.GetBoolean(sp::kSyncOsApps)); EXPECT_FALSE(prefs_.GetBoolean(sp::kSyncOsPreferences)); } TEST_F(OsSyncUtilTest, Rollback) { // Do initial migration. os_sync_util::MigrateOsSyncPreferences(&prefs_); EXPECT_TRUE(prefs_.GetBoolean(sp::kOsSyncPrefsMigrated)); { // Simulate disabling the feature (e.g. disabling via Finch). base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature( chromeos::features::kSyncSettingsCategorization); os_sync_util::MigrateOsSyncPreferences(&prefs_); // OS sync is marked as not migrated. EXPECT_FALSE(prefs_.GetBoolean(sp::kOsSyncPrefsMigrated)); } // Simulate re-enabling the feature. { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( chromeos::features::kSyncSettingsCategorization); os_sync_util::MigrateOsSyncPreferences(&prefs_); // OS sync is marked as migrated. EXPECT_TRUE(prefs_.GetBoolean(sp::kOsSyncPrefsMigrated)); } } TEST_F(OsSyncUtilTest, MigrationMetrics) { base::HistogramTester histograms; // Initial migration. os_sync_util::MigrateOsSyncPreferences(&prefs_); // Migration recorded. histograms.ExpectBucketCount("ChromeOS.Sync.PreferencesMigrated", true, 1); // Try to migrate again. This is a no-op. os_sync_util::MigrateOsSyncPreferences(&prefs_); // Non-migration recorded. histograms.ExpectBucketCount("ChromeOS.Sync.PreferencesMigrated", false, 1); }
{ "content_hash": "c1b2b239d58237fae2d4fe39b600ff35", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 78, "avg_line_length": 33.830357142857146, "alnum_prop": 0.7455793085246767, "repo_name": "scheib/chromium", "id": "cf147652cae2f5fb0d3255d876f3f62f281b7c2f", "size": "4482", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "chrome/browser/ash/sync/os_sync_util_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
var Observable = require("FuseJS/Observable"); var Backend = require("Backend.js"); module.exports = { pet: this.CurrentPet.map(function(name) { return Backend.getPet(name); }) };
{ "content_hash": "4dd5c40bda5ab382566606b19540c5d3", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 46, "avg_line_length": 23, "alnum_prop": 0.7065217391304348, "repo_name": "fusetools/fuse-samples", "id": "3328ffc2db96975a788ca9f9d7a937b316dd17a1", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Samples/cattr/Pages/Home/Pics/PicsPage.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "183" }, { "name": "Shell", "bytes": "3957" } ], "symlink_target": "" }
<div class="zoom-buttons-container mat-elevation-z2"> <button md-button class="btn-zoom-in" (click)="zoomIn.emit()" md-tooltip="Zoom In" [mdTooltipPosition]="'left'"> <md-icon>add</md-icon> </button> <button md-button class="btn-zoom-out" (click)="zoomOut.emit()" md-tooltip="Zoom Out" [mdTooltipPosition]="'left'"> <md-icon>remove</md-icon> </button> </div>
{ "content_hash": "902931dcb561929032cc2cf2dd9b34a7", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 87, "avg_line_length": 39.5, "alnum_prop": 0.6354430379746835, "repo_name": "lukaszkostrzewa/graphy", "id": "d9b64f4eb409f70168fef25f16d6c85f5dfd5112", "size": "395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/zoom-buttons/zoom-buttons.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8116" }, { "name": "HTML", "bytes": "13515" }, { "name": "JavaScript", "bytes": "2050" }, { "name": "TeX", "bytes": "123492" }, { "name": "TypeScript", "bytes": "104725" } ], "symlink_target": "" }
namespace TestCases.HSSF.UserModel { using System; using NPOI.HSSF.UserModel; using NUnit.Framework; using TestCases.HSSF; using NPOI.SS.UserModel; using TestCases.SS.UserModel; using NPOI.SS; using NPOI.HSSF.Record; /** * Test Row is okay. * * @author Glen Stampoultzis (glens at apache.org) */ [TestFixture] public class TestHSSFRow : BaseTestRow { public TestHSSFRow(): base(HSSFITestDataProvider.Instance) { } [Test] public void TestMoveCell() { HSSFWorkbook workbook = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet(); IRow row = sheet.CreateRow(0); IRow rowB = sheet.CreateRow(1); ICell cellA2 = rowB.CreateCell(0); Assert.AreEqual(0, rowB.FirstCellNum); Assert.AreEqual(0, rowB.FirstCellNum); Assert.AreEqual(-1, row.LastCellNum); Assert.AreEqual(-1, row.FirstCellNum); ICell cellB2 = row.CreateCell(1); ICell cellB3 = row.CreateCell(2); ICell cellB4 = row.CreateCell(3); Assert.AreEqual(1, row.FirstCellNum); Assert.AreEqual(4, row.LastCellNum); // Try to move to somewhere else that's used try { row.MoveCell(cellB2, (short)3); Assert.Fail("ArgumentException should have been thrown"); } catch (ArgumentException) { // expected during successful Test } // Try to move one off a different row try { row.MoveCell(cellA2, (short)3); Assert.Fail("ArgumentException should have been thrown"); } catch (ArgumentException) { // expected during successful Test } // Move somewhere spare Assert.IsNotNull(row.GetCell(1)); row.MoveCell(cellB2, (short)5); Assert.IsNull(row.GetCell(1)); Assert.IsNotNull(row.GetCell(5)); Assert.AreEqual(5, cellB2.ColumnIndex); Assert.AreEqual(2, row.FirstCellNum); Assert.AreEqual(6, row.LastCellNum); } [Test] public void TestRowBounds() { BaseTestRowBounds(SpreadsheetVersion.EXCEL97.LastRowIndex); } [Test] public void TestCellBounds() { BaseTestCellBounds(SpreadsheetVersion.EXCEL97.LastColumnIndex); } /** * Prior to patch 43901, POI was producing files with the wrong last-column * number on the row */ [Test] public new void TestLastCellNumIsCorrectAfterAddCell_bug43901() { HSSFWorkbook book = new HSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Test"); IRow row = sheet.CreateRow(0); // New row has last col -1 Assert.AreEqual(-1, row.LastCellNum); if (row.LastCellNum == 0) { Assert.Fail("Identified bug 43901"); } // Create two cells, will return one higher // than that for the last number row.CreateCell(0); Assert.AreEqual(1, row.LastCellNum); row.CreateCell(255); Assert.AreEqual(256, row.LastCellNum); } [Test] public void TestLastAndFirstColumns_bug46654() { int ROW_IX = 10; int COL_IX = 3; HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); RowRecord rowRec = new RowRecord(ROW_IX); rowRec.FirstCol=((short)2); rowRec.LastCol=((short)5); BlankRecord br = new BlankRecord(); br.Row=(ROW_IX); br.Column=((short)COL_IX); sheet.Sheet.AddValueRecord(ROW_IX, br); HSSFRow row = new HSSFRow(workbook,sheet, rowRec); ICell cell = row.CreateCellFromRecord(br); if (row.FirstCellNum == 2 && row.LastCellNum == 5) { throw new AssertionException("Identified bug 46654a"); } Assert.AreEqual(COL_IX, row.FirstCellNum); Assert.AreEqual(COL_IX + 1, row.LastCellNum); row.RemoveCell(cell); Assert.AreEqual(-1, row.FirstCellNum); Assert.AreEqual(-1, row.LastCellNum); } [Test] public void TestRowHeight() { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; HSSFRow row = sheet.CreateRow(0) as HSSFRow; Assert.AreEqual(row.Height, sheet.DefaultRowHeight); Assert.AreEqual(row.RowRecord.BadFontHeight, false); row.Height=((short)123); Assert.AreEqual(row.Height, 123); Assert.AreEqual(row.RowRecord.BadFontHeight, true); row.Height = ((short)-1); Assert.AreEqual(row.Height, sheet.DefaultRowHeight); Assert.AreEqual(row.RowRecord.BadFontHeight, false); } } }
{ "content_hash": "ee889999a0cc98d530d781a03c40f870", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 83, "avg_line_length": 32.303030303030305, "alnum_prop": 0.5478424015009381, "repo_name": "akrisiun/npoi", "id": "5f459f495da2c55eea6e36f001f0f51b4d866a4f", "size": "6264", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "testcases/main/HSSF/UserModel/TestHSSFRow.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1305" }, { "name": "C#", "bytes": "13726402" }, { "name": "Smalltalk", "bytes": "62554" } ], "symlink_target": "" }
package CPANPLUS::Dist::Build::Constants; use if $] > 5.017, 'deprecate'; use strict; use warnings; use File::Spec; BEGIN { require Exporter; use vars qw[$VERSION @ISA @EXPORT]; $VERSION = '0.70'; @ISA = qw[Exporter]; @EXPORT = qw[ BUILD_DIR BUILD CPDB_PERL_WRAPPER]; } use constant BUILD_DIR => sub { return @_ ? File::Spec->catdir($_[0], '_build') : '_build'; }; use constant BUILD => sub { my $file = @_ ? File::Spec->catfile($_[0], 'Build') : 'Build'; ### on VMS, '.com' is appended when ### creating the Build file $file .= '.com' if $^O eq 'VMS'; return $file; }; use constant CPDB_PERL_WRAPPER => 'use strict; BEGIN { my $old = select STDERR; $|++; select $old; $|++; $0 = shift(@ARGV); my $rv = do($0); die $@ if $@; }'; 1; =head1 NAME CPANPLUS::Dist::Build::Constants - Constants for CPANPLUS::Dist::Build =head1 SYNOPSIS use CPANPLUS::Dist::Build::Constants; =head1 DESCRIPTION CPANPLUS::Dist::Build::Constants provides some constants required by L<CPANPLUS::Dist::Build>. =head1 AUTHOR Originally by Jos Boumans E<lt>kane@cpan.orgE<gt>. Brought to working condition and currently maintained by Ken Williams E<lt>kwilliams@cpan.orgE<gt>. =head1 LICENSE The CPAN++ interface (of which this module is a part of) is copyright (c) 2001, 2002, 2003, 2004, 2005 Jos Boumans E<lt>kane@cpan.orgE<gt>. All rights reserved. This library is free software; you may redistribute and/or modify it under the same terms as Perl itself. =cut # Local variables: # c-indentation-style: bsd # c-basic-offset: 4 # indent-tabs-mode: nil # End: # vim: expandtab shiftwidth=4:
{ "content_hash": "e4b481fe4dd2a42fbc91b7951334936d", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 160, "avg_line_length": 27.135135135135137, "alnum_prop": 0.5393426294820717, "repo_name": "Bjay1435/capstone", "id": "f020093c9c79cc6a1fb4dbf6299ba7075aa7a4af", "size": "2008", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "rootfs/usr/share/perl/5.18.2/CPANPLUS/Dist/Build/Constants.pm", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "841" }, { "name": "Awk", "bytes": "10779" }, { "name": "Batchfile", "bytes": "35708" }, { "name": "C", "bytes": "12874998" }, { "name": "C++", "bytes": "8412918" }, { "name": "CMake", "bytes": "2014897" }, { "name": "CSS", "bytes": "17738" }, { "name": "Coq", "bytes": "29047" }, { "name": "Emacs Lisp", "bytes": "28540" }, { "name": "FORTRAN", "bytes": "1781" }, { "name": "Forth", "bytes": "2078" }, { "name": "Go", "bytes": "15064" }, { "name": "Groff", "bytes": "325029" }, { "name": "HTML", "bytes": "3226229" }, { "name": "JavaScript", "bytes": "83945" }, { "name": "Logos", "bytes": "116581" }, { "name": "M4", "bytes": "1138587" }, { "name": "Makefile", "bytes": "60298" }, { "name": "Matlab", "bytes": "2038" }, { "name": "Objective-C", "bytes": "11673" }, { "name": "Pascal", "bytes": "37459" }, { "name": "Perl", "bytes": "18475849" }, { "name": "Perl6", "bytes": "1084056" }, { "name": "Prolog", "bytes": "1416519" }, { "name": "Python", "bytes": "13249253" }, { "name": "Shell", "bytes": "5189424" }, { "name": "Smalltalk", "bytes": "21514" }, { "name": "Stata", "bytes": "13166" }, { "name": "SystemVerilog", "bytes": "213462" }, { "name": "Tcl", "bytes": "134338" }, { "name": "TeX", "bytes": "323102" }, { "name": "VHDL", "bytes": "57795938" }, { "name": "Verilog", "bytes": "8965533" }, { "name": "VimL", "bytes": "12589" }, { "name": "XC", "bytes": "17727" }, { "name": "XS", "bytes": "17577" }, { "name": "Yacc", "bytes": "7489" } ], "symlink_target": "" }
<?php namespace Twig\TokenParser; use Twig\Node\Expression\AssignNameExpression; use Twig\Node\ImportNode; use Twig\Node\Node; use Twig\Token; /** * Imports macros. * * {% from 'forms.html' import forms %} */ final class FromTokenParser extends AbstractTokenParser { public function parse(Token $token): Node { $macro = $this->parser->getExpressionParser()->parseExpression(); $stream = $this->parser->getStream(); $stream->expect(/* Token::NAME_TYPE */ 5, 'import'); $targets = []; do { $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); $alias = $name; if ($stream->nextIf('as')) { $alias = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); } $targets[$name] = $alias; if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { break; } } while (true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $var = new AssignNameExpression($this->parser->getVarName(), $token->getLine()); $node = new ImportNode($macro, $var, $token->getLine(), $this->getTag(), $this->parser->isMainScope()); foreach ($targets as $name => $alias) { $this->parser->addImportedSymbol('function', $alias, 'macro_'.$name, $var); } return $node; } public function getTag(): string { return 'from'; } }
{ "content_hash": "649b2ff52ed0ebe04de7418c230457ff", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 111, "avg_line_length": 25.82456140350877, "alnum_prop": 0.5421195652173914, "repo_name": "cloudfoundry/php-buildpack", "id": "c1d1f4cbab53c4f7b7af1b5e0fd55c6874ff6047", "size": "1665", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "fixtures/symfony_5_local_deps/vendor/twig/twig/src/TokenParser/FromTokenParser.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1724" }, { "name": "CSS", "bytes": "27696" }, { "name": "Go", "bytes": "73324" }, { "name": "HTML", "bytes": "24121" }, { "name": "JavaScript", "bytes": "20500" }, { "name": "Makefile", "bytes": "295" }, { "name": "PHP", "bytes": "541348" }, { "name": "Python", "bytes": "584757" }, { "name": "Ruby", "bytes": "1102" }, { "name": "SCSS", "bytes": "15480" }, { "name": "Shell", "bytes": "20264" }, { "name": "Smalltalk", "bytes": "8" }, { "name": "Twig", "bytes": "86464" } ], "symlink_target": "" }
"""Test suite for the TG app's models""" from nose.tools import eq_ from helloworld import model from helloworld.tests.models import ModelTest
{ "content_hash": "d14edfe8c82fea7eb776207e066e02f6", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 45, "avg_line_length": 24.166666666666668, "alnum_prop": 0.7793103448275862, "repo_name": "fadado/shed", "id": "78fcdc4e835af86a634e26dbb1a6e59aac430fee", "size": "169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/turbogears/helloworld/helloworld/tests/models/test_auth.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1675" }, { "name": "HTML", "bytes": "496" }, { "name": "Makefile", "bytes": "7055" }, { "name": "Python", "bytes": "24120" }, { "name": "Shell", "bytes": "93747" } ], "symlink_target": "" }
**Learning Objective**: To gain a fuller understanding of process scheduling algorithms by implementing them. **Development**: Use C, C++, C# or Java. Create a console-mode application that does not use a windowing environment. Document your code adequately, including your name and the course name at the top of every file. **Assignment**: Implement the First-Come First-Served, preemptive Shortest Job First, and Round-Robin algorithms as for single processors. **Input**: Your program will read a file from the current directory called **processes.in**, which will be formatted as follows. Your program should ignore everything on a line after a **#** mark and ignore additional spaces in input. ``` processcount 2 # Read 2 processes runfor 15 # Run for 15 time units use rr # Can be fcfs, sjf, or rr quantum 2 # Time quantum – only if using rr process name P1 arrival 3 burst 5 process name P2 arrival 0 burst 9 end ``` *Note that the processes do not need to be specified in order of arrival, and do not need to have similar names.* **Output**: Generate a file called **processes.out**, formatted as follows. ``` 2 processes Using Round-Robin Quantum 2 Time 0: P2 arrived Time 0: P2 selected (burst 9) Time 2: P2 selected (burst 7) Time 3: P1 arrived Time 4: P1 selected (burst 5) Time 6: P2 selected (burst 5) Time 8: P1 selected (burst 3) Time 10: P2 selected (burst 3) Time 12: P1 selected (burst 1) Time 13: P1 finished Time 13: P2 selected (burst 1) Time 14: P2 finished Time 14: Idle Finished at time 15 P1 wait 5 turnaround 10 P2 wait 5 turnaround 14 ``` **Clarifications** This version of Round-Robin should not run the scheduler immediately upon the arrival of a new process, unless the CPU is currently idle. Your program will not be given an input that results in an ambiguous decision, such as identical arrival times for Round-Robin or identical burst lengths for SJF; you should avoid generating an error in that case on general principles but it will not appear in either the example inputs or the grading inputs.
{ "content_hash": "357535af858c809fec4f955ed6bcdd15", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 309, "avg_line_length": 41.07692307692308, "alnum_prop": 0.7298689138576779, "repo_name": "lrosa007/COP4600", "id": "09316f39af6e5954a9a523a21c35db6bc7f9b671", "size": "2154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assignments/002/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "8932" } ], "symlink_target": "" }
import {setStyle} from '#core/dom/style'; import {validateData, writeScript} from '#3p/3p'; /** * @param {!Window} global * @param {!Object} data */ export function adverticum(global, data) { validateData(data, ['goa3zone'], ['costumetargetstring']); const zoneid = 'zone' + data['goa3zone']; const d = global.document.createElement('div'); d.id = zoneid; d.classList.add('goAdverticum'); document.getElementById('c').appendChild(d); if (data['costumetargetstring']) { const s = global.document.createTextNode(data['costumetargetstring']); const v = global.document.createElement('var'); v.setAttribute('id', 'cT'); v.setAttribute('class', 'customtarget'); setStyle(v, 'display', 'none'); v.appendChild(s); document.getElementById(zoneid).appendChild(v); } writeScript(global, '//ad.adverticum.net/g3.js'); }
{ "content_hash": "27cfb480b2421c852cd79a9c475e6911", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 74, "avg_line_length": 30.785714285714285, "alnum_prop": 0.6751740139211136, "repo_name": "rsimha-amp/amphtml", "id": "c3333045420510d635957b884f22d119d7356a33", "size": "1489", "binary": false, "copies": "1", "ref": "refs/heads/2021-06-29-CrossBrowserTests", "path": "ads/vendors/adverticum.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "195514" }, { "name": "Go", "bytes": "15254" }, { "name": "HTML", "bytes": "1018438" }, { "name": "Java", "bytes": "36670" }, { "name": "JavaScript", "bytes": "9464137" }, { "name": "Python", "bytes": "80044" }, { "name": "Ruby", "bytes": "14445" }, { "name": "Shell", "bytes": "12162" }, { "name": "Yacc", "bytes": "22292" } ], "symlink_target": "" }
require 'rubygems' require 'sinatra' require 'open-uri' require 'hpricot' require 'pp' require 'date' require 'active_support/all' require 'net/http' require 'rexml/document' require 'digest/md5' #require 'sinatra/reloader' require 'geonames' def cloudinesspredictions( latitude, longitude ) url = "http://api.yr.no/weatherapi/locationforecastlts/1.1/?lat=#{latitude};lon=#{longitude}" xml_data = Net::HTTP.get_response(URI.parse(url)).body doc = REXML::Document.new(xml_data) predictions = {} REXML::XPath.each(doc, "//time") do |e| location = REXML::XPath.first( e, "location") if location clouds = REXML::XPath.first( location, "cloudiness") if clouds predictions[ DateTime.parse( e.attributes[ "from" ] ).strftime( '%s' ).to_i ] = clouds.attributes["percent"].to_f end end end return predictions end def predictcloudiness( predictions, time ) time = time.strftime( '%s' ).to_i beforeprediction = nil beforetime = ( DateTime.now - (30*24/24.0) ).strftime( '%s' ).to_i afterprediction = nil aftertime = ( DateTime.now + (30*24/24.0) ).strftime( '%s' ).to_i predictions.each do | t, p | if t < time if t > beforetime beforetime = t beforeprediction = p end elsif t > time if t < aftertime aftertime = t afterprediction = p end end end if( afterprediction && beforeprediction ) befored = ( time - beforetime ) afterd = ( aftertime - time ) prediction = ( ( afterprediction * befored ) + ( beforeprediction * afterd ) ) / ( befored + afterd ) return prediction.round else return -1 end end class Flyby attr_accessor :date, :starttime, :startdatetime, :endtime, :enddatetime, :magnitude, :location, :url, :description, :duration end def fetchxml( url, cache ) if !File.exists?( cache ) || ( File.mtime( cache ) < Time.now - 24 * 60 * 60 ) # we do not have a cache, or the cache has elapsed $stderr.puts "downloading and caching " + url require 'uri' url = URI.parse( url ) require 'net/http' resp = 0 Net::HTTP.start( url.host, url.port ) { |http| resp = http.post( url.path, url.query ) open( cache, "wb") { |file| file.write(resp.body) } } doc = Hpricot( resp.body ) return doc else # we have the result in cache $stderr.puts "loading "+url+" from cache" require 'rexml/document' doc = Hpricot( File.new( cache, 'r' ) ) return doc end end def getFromCache( latitude, longitude ) latitude = latitude.to_f.round 1 longitude = longitude.to_f.round 1 hash = Digest::MD5.hexdigest "#{latitude}#{longitude}" cachename = "cache/#{hash[0..0]}/#{hash}" doc = fetchxml "http://www.heavens-above.com/PassSummary.aspx?lat=#{latitude}&lng=#{longitude}&satid=25544", cachename end def getFlybys( latitude, longitude ) months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] flybys = [] doc = getFromCache( latitude, longitude ) counter = 0 # select the table that contains the flybys require 'pp' table = (doc/".standardTable") rows = table/"tr" if (table/"tr").at("td")['class'] != 'address' rows.each do |row| # each row contains a prediction ... if row.attributes[ "class" ] != "tablehead" # unless the row contains header information fields = [] (row/"td").each do |field| if (field/"a").size > 0 element = field.at "a" fields << element.inner_html.strip # fields[ 0 ] = date of flyby fields << "http://www.heavens-above.com/" + element['href'].strip # link to more info on heavens-above.com else fields << field.inner_html.strip end end flyby = Flyby.new # extract all the information that is hidden in the table row year = Date.today.year if fields[ 0 ] != "Chris Peat" month = months.index( fields[ 0 ].split( " " )[ 1 ] ) + 1 if month == 1 && Date.today.month == 12 # if the predicted year is in the beginning of january, but we're still december ... year = year + 1 end if month < 10 month = "0" + month.to_s end day = fields[ 0 ].split( " " )[ 0 ].to_i if day < 10 day = "0" + day.to_s end flyby.date = "#{year}#{month}#{day}" flyby.starttime = fields[ 3 ].gsub(/:/, "") hour = fields[ 3 ].split(":")[ 0 ] minute = fields[ 3 ].split(":")[ 1 ] second = fields[ 3 ].split(":")[ 2 ] flyby.startdatetime = DateTime.new(year,month.to_i,day.to_i,hour.to_i,minute.to_i,second.to_i) flyby.endtime = fields[ 9 ].gsub(/:/, "") hour = fields[ 9 ].split(":")[ 0 ] minute = fields[ 9 ].split(":")[ 1 ] second = fields[ 9 ].split(":")[ 2 ] flyby.enddatetime = DateTime.new(year,month.to_i,day.to_i,hour.to_i,minute.to_i,second.to_i) flyby.duration = ( ( flyby.enddatetime - flyby.startdatetime ) * 24 * 60 ).to_i flyby.magnitude = fields[ 2 ] flyby.url = fields[ 1 ].gsub( /\&[Tt][Zz]=[^\&]*/, "" ) flyby.description = flyby.url flyby.location = "#{fields[4]}#{fields[5]} - #{fields[7]}#{fields[8]} - #{fields[10]}#{fields[11]}" flybys << flyby end end end end return flybys end get '/' do erb :index end helpers do def cloudiness( cloudpredictions, datetime ) return predictcloudiness( cloudpredictions, datetime ) end end get '/flybys' do @latitude = params[ 'lat' ] @latitude = 51.2 if !@latitude @longitude = params[ 'lng' ] @longitude = 4.4830 if !@longitude @timezone = Geonames::WebService.timezone @latitude, @longitude @nearby = ( Geonames::WebService.find_nearby_place_name @latitude, @longitude ).first @flybys = getFlybys( @latitude, @longitude ) @cloudpredictions = cloudinesspredictions( @latitude, @longitude ) erb :flybys end get '/iss.ics' do @latitude = params[ 'lat' ] @latitude = 51.2 if !@latitude @longitude = params[ 'lng' ] @longitude = 4.4830 if !@longitude flybys = getFlybys( @latitude, @longitude ) if params['alarm'] && params['alarmtime'] @alarm = ( params[ 'alarm' ] == "on" ) @alarmtime = params[ 'alarmtime' ] end @maximumMagnitude = 0 if params[ 'mag'] @maximumMagnitude = params[ 'mag' ].to_f end @results = getFlybys( @latitude, @longitude ) headers 'Content-Type' => 'text/calendar' erb :calendar, :layout => false end
{ "content_hash": "b4c7b060db1970d8aa960b40d66fad45", "timestamp": "", "source": "github", "line_count": 233, "max_line_length": 134, "avg_line_length": 28.918454935622318, "alnum_prop": 0.5853368952211339, "repo_name": "aliekens/lookup", "id": "1322a0f017f327b2d54d3fe85a5801e85787f194", "size": "6738", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "7811" } ], "symlink_target": "" }
@class OS_dispatch_queue; @protocol SimDeviceNotifier - (unsigned long long)registerNotificationHandlerOnQueue:(OS_dispatch_queue *)arg1 handler:(void (^)(NSDictionary *))arg2; - (BOOL)unregisterNotificationHandler:(unsigned long long)arg1 error:(id *)arg2; @end
{ "content_hash": "603650d5672a121b7c9db53cec846af7", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 122, "avg_line_length": 33.25, "alnum_prop": 0.7819548872180451, "repo_name": "plu/FBSimulatorControl", "id": "b8557e5f373057ddabfd8506daff7d018c8f7931", "size": "574", "binary": false, "copies": "3", "ref": "refs/heads/pxctest", "path": "PrivateHeaders/SimulatorKit/SimDeviceNotifier-Protocol.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1043" }, { "name": "Objective-C", "bytes": "2180393" }, { "name": "Python", "bytes": "27477" }, { "name": "Shell", "bytes": "9821" }, { "name": "Swift", "bytes": "221667" } ], "symlink_target": "" }
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Data.Objects.DataClasses; namespace Cats.Models.Hubs.MetaModels { public sealed class TransactionMetaModel { [Required(ErrorMessage="Transaction is required")] public Guid TransactionID { get; set; } ////[Required(ErrorMessage="Partition is required")] //public Int32? PartitionId { get; set; } public Guid? TransactionGroupID { get; set; } [Required(ErrorMessage="Ledger is required")] public Int32 LedgerID { get; set; } //[Required(ErrorMessage="Hub Owner is required")] public Int32? HubOwnerID { get; set; } //[Required(ErrorMessage="Account is required")] public Int32? AccountID { get; set; } //[Required(ErrorMessage="Hub is required")] public Int32? HubID { get; set; } //[Required(ErrorMessage="Store is required")] public Int32? StoreID { get; set; } public Int32? Stack { get; set; } //[Required(ErrorMessage="Project Code is required")] public Int32? ProjectCodeID { get; set; } //[Required(ErrorMessage="Shipping Instruction is required")] public Int32? ShippingInstructionID { get; set; } [Required(ErrorMessage="Program is required")] public Int32 ProgramID { get; set; } //[Required(ErrorMessage="Parent Commodity is required")] public Int32? ParentCommodityID { get; set; } //[Required(ErrorMessage="Commodity is required")] public Int32? CommodityID { get; set; } public Int32? CommodityGradeID { get; set; } [Required(ErrorMessage="Quantity In M T is required")] public Decimal QuantityInMT { get; set; } [Required(ErrorMessage="Quantity In Unit is required")] public Decimal QuantityInUnit { get; set; } [Required(ErrorMessage="Unit is required")] public Int32 UnitID { get; set; } [Required(ErrorMessage="Transaction Date is required")] [DataType(DataType.DateTime)] public DateTime TransactionDate { get; set; } public EntityCollection<Account> Account { get; set; } public EntityCollection<Commodity> Commodity { get; set; } public EntityCollection<Commodity> Commodity1 { get; set; } public EntityCollection<CommodityGrade> CommodityGrade { get; set; } public EntityCollection<Hub> Hub { get; set; } public EntityCollection<HubOwner> HubOwner { get; set; } public EntityCollection<Ledger> Ledger { get; set; } public EntityCollection<Program> Program { get; set; } public EntityCollection<ProjectCode> ProjectCode { get; set; } public EntityCollection<ShippingInstruction> ShippingInstruction { get; set; } public EntityCollection<Store> Store { get; set; } public EntityCollection<TransactionGroup> TransactionGroup { get; set; } public EntityCollection<Unit> Unit { get; set; } } }
{ "content_hash": "6f94ee1afb8bf80ce20b1069e500733d", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 84, "avg_line_length": 30.673684210526314, "alnum_prop": 0.6818805765271105, "repo_name": "ndrmc/cats", "id": "821610e60676804a83aa02fbb2d66d64d4f7ad0d", "size": "2914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Models/Cats.Models.Hub/MetaModels/TransactionMetaModel.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "23179" }, { "name": "Batchfile", "bytes": "220" }, { "name": "C#", "bytes": "17077194" }, { "name": "CSS", "bytes": "1272649" }, { "name": "HTML", "bytes": "1205906" }, { "name": "JavaScript", "bytes": "4300261" }, { "name": "PLpgSQL", "bytes": "10605" }, { "name": "SQLPL", "bytes": "11550" }, { "name": "Smalltalk", "bytes": "10" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- Splash.java --> <string name="key_first_launch">APP_FIRST_LAUNCH</string> <string name="key_install_stamp">APP_INSTALL_STAMP</string> <string name="key_use_count">APP_USE_COUNT</string> <!-- LoginFragment.java --> <string name="key_login_user">APP_LOGIN_USER</string> <string name="admob_unit_id">pub-9439716523405765</string> <string name="admob_test_device">F409968388311AB2806E8E280CE38D47</string> <string name="youmi_pub_id">48ca1f69992df596</string> <string name="youmi_ads_key">f8ae9444a6e560a7</string> </resources>
{ "content_hash": "bade269e7019accc4a9888804d11f6a0", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 78, "avg_line_length": 37.411764705882355, "alnum_prop": 0.6776729559748428, "repo_name": "zxfhacker/LetsChat", "id": "aba9884bcd14d83d593f0acbb951fc2c9fa9cb39", "size": "636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/donottranslate.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "37474" } ], "symlink_target": "" }
package is.hail.utils.richUtils import is.hail.annotations.{JoinedRegionValue, RegionValue} import is.hail.types.physical.PType class RichJoinedRegionValue(jrv: JoinedRegionValue) { def pretty(lTyp: PType, rTyp: PType): String = jrv._1.pretty(lTyp) + "," + jrv._2.pretty(rTyp) def rvLeft: RegionValue = jrv._1 def rvRight: RegionValue = jrv._2 }
{ "content_hash": "8a7cd00097b08fdd1533b2e6f7b2be63", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 96, "avg_line_length": 35.4, "alnum_prop": 0.7457627118644068, "repo_name": "cseed/hail", "id": "bd07f29b0491b4795f56f0770177157262a2efeb", "size": "354", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "hail/src/main/scala/is/hail/utils/richUtils/RichJoinedRegionValue.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "7729" }, { "name": "C", "bytes": "289" }, { "name": "C++", "bytes": "170210" }, { "name": "CSS", "bytes": "20423" }, { "name": "Dockerfile", "bytes": "7426" }, { "name": "HTML", "bytes": "43106" }, { "name": "Java", "bytes": "22564" }, { "name": "JavaScript", "bytes": "730" }, { "name": "Jupyter Notebook", "bytes": "162397" }, { "name": "Makefile", "bytes": "58348" }, { "name": "PLpgSQL", "bytes": "23163" }, { "name": "Python", "bytes": "3477764" }, { "name": "R", "bytes": "3038" }, { "name": "Scala", "bytes": "3496240" }, { "name": "Shell", "bytes": "41254" }, { "name": "TSQL", "bytes": "10385" }, { "name": "TeX", "bytes": "7125" }, { "name": "XSLT", "bytes": "9787" } ], "symlink_target": "" }
package cn.edu.cdu.structural.facade; /** * a simple interface is required to access a complex system; * 打开电脑流程 */ class You { public static void main(String[] args) { ComputerFacade computer = new ComputerFacade(); computer.start(); } }
{ "content_hash": "7f58847fe4d24e9e888653bcaf725944", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 61, "avg_line_length": 22.083333333333332, "alnum_prop": 0.660377358490566, "repo_name": "ylfeiu/DesignPattern", "id": "bbb84fce350bfc69017c5f06c8d41660c5073577", "size": "277", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample/src/cn/edu/cdu/structural/facade/You.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "17852" } ], "symlink_target": "" }
set -e set -x # Update package for ubuntu sudo apt-get -qq update sudo apt-get install -y --force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" docker-engine # Start service sudo service docker stop sudo service docker start # Setup/update docker compose curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose chmod +x docker-compose sudo mv docker-compose /usr/local/bin
{ "content_hash": "2fc2cb3e06e985ecc9b03a28f85d902e", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 139, "avg_line_length": 32.8, "alnum_prop": 0.7479674796747967, "repo_name": "Arttii/malefico", "id": "184ae575eb0bdcdcd877d809aa9026907aec8cc7", "size": "513", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ci/scripts/travis_docker_setup.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "57358" } ], "symlink_target": "" }
package com.manning.hsia.dvdstore; import com.manning.hsia.test.ch13.SearchTestCase; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.spell.LuceneDictionary; import org.apache.lucene.search.spell.SpellChecker; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.search.FullTextSession; import org.hibernate.search.Search; import org.hibernate.search.SearchFactory; import org.hibernate.search.store.DirectoryProvider; import org.hibernate.search.store.FSDirectoryProvider; import org.testng.annotations.Test; import java.io.File; import java.util.List; public class TestSpellChecker extends SearchTestCase { public List<String> results; private String baseDir; private Directory spellDir; String texts[] = { "Keanu Reeves is completely wooden in this romantic misfired flick", "Reeves plays a traveling salesman and agrees to help a woman", "Jamie Lee Curtis finds out that he's not really a salesman" }; @Test(groups="ch13") public void testSpellCheck() throws Exception { FullTextSession session = Search.getFullTextSession( openSession() ); Transaction tx = session.beginTransaction(); try { buildIndex( session, tx ); tx = session.beginTransaction(); SpellChecker spellChecker = buildSpellCheckIndex( "description", session ); String misspelledUserInput = "kenu"; assert !spellChecker.exist( misspelledUserInput ) : "misspelled word found"; String[] suggestions = spellChecker.suggestSimilar( misspelledUserInput, 5 ); assert suggestions.length == 1 : "incorrect suggestion count"; for (String suggestion : suggestions) { System.out.println( suggestion ); assert suggestion.equals( "keanu" ); } tx.commit(); } finally { session.close(); } } private SpellChecker buildSpellCheckIndex( String fieldName, FullTextSession session ) throws Exception { SearchFactory searchFactory = session.getSearchFactory(); DirectoryProvider[] providers = searchFactory.getDirectoryProviders( Dvd.class ); org.apache.lucene.store.Directory DvdDirectory = providers[0].getDirectory(); IndexReader spellReader = null; SpellChecker spellchecker = null; try { // read from the DVD directory spellReader = IndexReader.open( DvdDirectory ); LuceneDictionary dict = new LuceneDictionary( IndexReader.open( DvdDirectory ), fieldName ); // build the spellcheck index in the base directory spellDir = FSDirectory.getDirectory( baseDir ); spellchecker = new SpellChecker( spellDir ); // build the directory spellchecker.indexDictionary( dict ); } finally { if ( spellReader != null ) spellReader.close(); } return spellchecker; } private void buildIndex( FullTextSession session, Transaction tx ) { for (int x = 0; x < texts.length; x++) { Dvd dvd = new Dvd(); dvd.setId( x + 1 ); dvd.setDescription( texts[x] ); session.save( dvd ); } tx.commit(); session.clear(); } @Override protected void configure( Configuration cfg ) { super.configure( cfg ); cfg.setProperty( "hibernate.search.default.directory_provider", FSDirectoryProvider.class.getName() ); File sub = locateBaseDir(); baseDir = sub.getAbsolutePath(); cfg.setProperty( "hibernate.search.default.indexBase", baseDir ); } protected Class[] getMappings() { return new Class[]{ Dvd.class }; } }
{ "content_hash": "814fe95e515d95985889cbbbe0069e2f", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 106, "avg_line_length": 31.672566371681416, "alnum_prop": 0.7194747136071529, "repo_name": "ashraf-revo/hibernatesearchinaction", "id": "f2ba05350f1c5a9b825c59efa1eeba2cfb2a01d9", "size": "3579", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ch13/src/com/manning/hsia/dvdstore/TestSpellChecker.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "435324" }, { "name": "SQLPL", "bytes": "3387761" } ], "symlink_target": "" }
package com.asksunny.kmip; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import com.asksunny.tls.AliasSpecificSSLSocketFactory; public class SimpleKmipClient { public static final String KEYSTORE_PASS = "changeit"; public static final String TRUSTSTORE_PASS = "changeit"; public static final String CLIENT_KEY_ALIAS = "socketclient"; public SimpleKmipClient() { } public static void main(String[] args) throws Exception { SSLSocketFactory socketFactory = AliasSpecificSSLSocketFactory.getSSLSocketFactory( SimpleKmipClient.class.getResourceAsStream("/client_keystore.jks"), KEYSTORE_PASS, CLIENT_KEY_ALIAS, SimpleKmipClient.class.getResourceAsStream("/server_keystore.jks"), TRUSTSTORE_PASS); SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", 8889); InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); PrintWriter writer = new PrintWriter(out); String line = null; writer.println("Hello Server"); writer.flush(); line = br.readLine(); System.out.printf("From server:%s\n", line); writer.println("who am I"); writer.flush(); line = br.readLine(); System.out.printf("From server:%s\n", line); writer.println("shutdown"); writer.flush(); socket.close(); } }
{ "content_hash": "d06fc70610b050094257acd45ee1a361", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 104, "avg_line_length": 30.80392156862745, "alnum_prop": 0.7313812858052197, "repo_name": "devsunny/app-galleries", "id": "c7e01ae4594794a0ea3b2d9ae4b7eff1bb836ab5", "size": "1571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tls-authentication/src/main/java/com/asksunny/kmip/SimpleKmipClient.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "146" }, { "name": "CSS", "bytes": "10476" }, { "name": "HTML", "bytes": "201054" }, { "name": "Java", "bytes": "5840363" }, { "name": "JavaScript", "bytes": "14341" }, { "name": "RPC", "bytes": "85142" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package greedyalgos; /** * * @author rex */ public class Knapsack { }
{ "content_hash": "591a6383f505890b0418a631a8c79866", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 79, "avg_line_length": 18.857142857142858, "alnum_prop": 0.6931818181818182, "repo_name": "rnijhara/AlgoPractice", "id": "31e3b10f36610d9a39670bd438f39d34649a0d6b", "size": "264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AlgoPractice/src/greedyalgos/Knapsack.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "49752" } ], "symlink_target": "" }
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. <a name="1.9.0"></a> # [1.9.0](https://github.com/tleunen/react-mdl/compare/v1.8.0...v1.9.0) (2016-11-23) ### Bug Fixes * Don't die if function::name is not configurable. (#437) ([929534f](https://github.com/tleunen/react-mdl/commit/929534f)) * **Menu:** Restore menu DOM after downgrade in order to allow react to cleanly unmount the component. (#435) ([0069600](https://github.com/tleunen/react-mdl/commit/0069600)), closes [#426](https://github.com/tleunen/react-mdl/issues/426) ### Features * exports from palette (#433) ([5563865](https://github.com/tleunen/react-mdl/commit/5563865)), closes [#399](https://github.com/tleunen/react-mdl/issues/399) <a name="1.8.0"></a> # [1.8.0](https://github.com/tleunen/react-mdl/compare/v1.7.2...v1.8.0) (2016-11-17) ### Bug Fixes * pass the values of `mdlRowProps` on the row (#398) ([a405631](https://github.com/tleunen/react-mdl/commit/a405631)) ### Features * **Badge:** Allow other props on Badge (#422) ([af8c4eb](https://github.com/tleunen/react-mdl/commit/af8c4eb)) <a name="1.7.2"></a> ## [1.7.2](https://github.com/tleunen/react-mdl/compare/v1.7.1...v1.7.2) (2016-09-12) ### Bug Fixes * **MDL:** Update to MDL 1.2.1 ([df7a3c1](https://github.com/tleunen/react-mdl/commit/df7a3c1)) <a name="1.7.1"></a> ## [1.7.1](https://github.com/tleunen/react-mdl/compare/v1.7.0...v1.7.1) (2016-08-30) ### Bug Fixes * **Chip:** Allow Chip to have more than 1 child (#385) ([7616167](https://github.com/tleunen/react-mdl/commit/7616167)), closes [#384](https://github.com/tleunen/react-mdl/issues/384) * **HeaderTabs:** Fix ripple effect ([6034345](https://github.com/tleunen/react-mdl/commit/6034345)), closes [#380](https://github.com/tleunen/react-mdl/issues/380) * **Tabs:** Remove the hack href "react-mdl-tabs-hack" ([967be52](https://github.com/tleunen/react-mdl/commit/967be52)), closes [#381](https://github.com/tleunen/react-mdl/issues/381) <a name="1.7.0"></a> # [1.7.0](https://github.com/tleunen/react-mdl/compare/v1.6.1...v1.7.0) (2016-08-21) ### Bug Fixes * **Cell:** Remove required col prop ([3ed1749](https://github.com/tleunen/react-mdl/commit/3ed1749)) * **Dialog:** Using window height instead of body.clientHeight (#373) ([b6c1a71](https://github.com/tleunen/react-mdl/commit/b6c1a71)), closes [#370](https://github.com/tleunen/react-mdl/issues/370) * **ProgressBar:** Fix unknown props ([4547085](https://github.com/tleunen/react-mdl/commit/4547085)) * **Tabs:** Fix js error when clicking on a tab (#376) ([ca9309e](https://github.com/tleunen/react-mdl/commit/ca9309e)), closes [#376](https://github.com/tleunen/react-mdl/issues/376) [#347](https://github.com/tleunen/react-mdl/issues/347) ### Features * Update MDL lib to version 1.2.0 (#375) ([9ab92f9](https://github.com/tleunen/react-mdl/commit/9ab92f9)) * **Chip:** Add Chip component (#378) ([c4ddfe7](https://github.com/tleunen/react-mdl/commit/c4ddfe7)), closes [#377](https://github.com/tleunen/react-mdl/issues/377) <a name="1.6.1"></a> ## [1.6.1](https://github.com/tleunen/react-mdl/compare/v1.6.0...v1.6.1) (2016-07-07) ### Bug Fixes * **DataTable:** Fix infinite loop with onSelectionChanged ([4d6b95d](https://github.com/tleunen/react-mdl/commit/4d6b95d)), closes [#339](https://github.com/tleunen/react-mdl/issues/339) * **DataTable:** Fix react unknown property warning ([c7d7a7a](https://github.com/tleunen/react-mdl/commit/c7d7a7a)) * **List:** Fix children proptype ([7b1a5ee](https://github.com/tleunen/react-mdl/commit/7b1a5ee)), closes [#329](https://github.com/tleunen/react-mdl/issues/329) * **Shadows:** Fix incorrect shadow level ([7d3bdce](https://github.com/tleunen/react-mdl/commit/7d3bdce)), closes [#314](https://github.com/tleunen/react-mdl/issues/314) * **Snackbar:** Prevent unknown prop warning (#343) ([a9b2a70](https://github.com/tleunen/react-mdl/commit/a9b2a70)) ## [1.5.4] ### New - Adds `hideSpacer` prop on the `Header` and `HeaderRow` ([#282]) ### Fixes - Fixes the generated bundled React-MDL files ([#301]) - Fixes/Removes the default upgrade elements by MDL since it's done by our components ([#302]) [1.5.4]: https://github.com/tleunen/react-mdl/compare/v1.5.3...v1.5.4 [#282]: https://github.com/tleunen/react-mdl/issues/282 [#301]: https://github.com/tleunen/react-mdl/issues/301 [#302]: https://github.com/tleunen/react-mdl/issues/302 ## [1.5.3] ### New - New documentation using [gatsby] ### Fixes - Fixes `Slider` documentation ([#268]) - Fixes react export names in the bundle files ([#267]) - Fixes multiple `is-invalid` clasname on `Textfield` ([#277]) - Fixes `Navigation` not working with null/false children ([#278]) - Fixes `Badge` not retaining classnames from its child ([#279]) - Fixes `Layout` invariant violation error ([#280]) [1.5.3]: https://github.com/tleunen/react-mdl/compare/v1.5.2...v1.5.3 [gatsby]: https://github.com/gatsbyjs/gatsby [#267]: https://github.com/tleunen/react-mdl/issues/267 [#268]: https://github.com/tleunen/react-mdl/issues/268 [#277]: https://github.com/tleunen/react-mdl/issues/277 [#278]: https://github.com/tleunen/react-mdl/issues/278 [#279]: https://github.com/tleunen/react-mdl/issues/279 [#280]: https://github.com/tleunen/react-mdl/issues/280 ## [1.5.2] ### Fixes - Fixes layout `Header` in small screens ([#264]) - Fixes uncontrolled `Slider` ([#263]) [1.5.2]: https://github.com/tleunen/react-mdl/compare/v1.5.1...v1.5.2 [#264]: https://github.com/tleunen/react-mdl/issues/264 [#263]: https://github.com/tleunen/react-mdl/issues/263 ## [1.5.1] ### Fixes - Fixes `Slider` UI background when it receives a new value ([#261]) - Fixes javascript error when using tabs ([#255]) ### New - Adds `jsnext:main` field in `package.json` for ES6 build tools ([#259]) - Adds support for all version of React 15 rc. - Updates to MDL 1.1.3 [1.5.1]: https://github.com/tleunen/react-mdl/compare/v1.5.0...v1.5.1 [#261]: https://github.com/tleunen/react-mdl/issues/261 [#259]: https://github.com/tleunen/react-mdl/issues/259 [#255]: https://github.com/tleunen/react-mdl/issues/255 ## [1.5.0] ### New - Adds `selectable` and `sortable` props on the `DataTable` component. ([#246]) - Adds `rowKeyColumn` on the `DataTable` component. This allows users to specify the data from the specific column to use as `key` for each rows (usually `id` or `uid`). ([#246]) - Adds support of React 15 rc1. [1.5.0]: https://github.com/tleunen/react-mdl/compare/v1.4.4...v1.5.0 [#246]: https://github.com/tleunen/react-mdl/issues/246 ## [1.4.4] ### Changes/Fixes - Updates to MDL 1.1.2 [1.4.4]: https://github.com/tleunen/react-mdl/compare/v1.4.3...v1.4.4 ## [1.4.3] ### Fixes - Fixes documentation on IE by including the babel polyfill ([#236]) - Fixes `Textfield` initial invalid state ([#241]) - Tried to resolve memory issue while running tests ([#230]) [1.4.3]: https://github.com/tleunen/react-mdl/compare/v1.4.2...v1.4.3 [#236]: https://github.com/tleunen/react-mdl/issues/236 [#241]: https://github.com/tleunen/react-mdl/issues/241 [#230]: https://github.com/tleunen/react-mdl/issues/230 ## [1.4.2] ### Fixes - Fixes `Snackbar` clear timeer on unmount. ([#227] by [@carpie]). - Fixes `Dialog` onCancel event. ([#237] by [@Permagate]) [1.4.2]: https://github.com/tleunen/react-mdl/compare/v1.4.1...v1.4.2 [#227]: https://github.com/tleunen/react-mdl/issues/227 [#237]: https://github.com/tleunen/react-mdl/issues/237 [@Permagate]: https://github.com/Permagate [@carpie]: https://github.com/carpie ## [1.4.1] ### Fixes - Do not close the `Dialog` with the escape key, by default. Can be customized with the `onCancel` prop. ([#221]). [1.4.1]: https://github.com/tleunen/react-mdl/compare/v1.4.0...v1.4.1 [#221]: https://github.com/tleunen/react-mdl/issues/221 ## [1.4.0] ### New - New `Dialog` component ([#207] by [@Permagate]). - New `Snackbar` component ([#208]). - New `List` component. ([#201] with [@darenju]'s help) - Adds `overlap` and `noBackground` prop in `Badge`. - Adds `hideTop` prop in `Layout`. - Adds position specific props in `Tooltip` ([#214] by [@Permagate]). - Adds `component` prop in `Tab` in order to fix custom links ([#116]) ### Fixes - Fixes `layout.scss` import paths ([#138]). - Fixes an issue in `Textfield` when a field replaces another one ([#197]) ### Changes - Changes `for` attribute with `data-mdl-for` in `Menu`. [1.4.0]: https://github.com/tleunen/react-mdl/compare/v1.3.0...v1.4.0 [#138]: https://github.com/tleunen/react-mdl/issues/138 [#207]: https://github.com/tleunen/react-mdl/issues/207 [#208]: https://github.com/tleunen/react-mdl/issues/208 [#197]: https://github.com/tleunen/react-mdl/issues/197 [#214]: https://github.com/tleunen/react-mdl/issues/214 [#116]: https://github.com/tleunen/react-mdl/issues/116 [#201]: https://github.com/tleunen/react-mdl/issues/201 [@Permagate]: https://github.com/Permagate [@darenju]: https://github.com/darenju ## [1.3.0] - Adds the Text and Article templates on the documentation website - Adds `hideDesktop`, `hidePhone`, `hideTablet` props in `Cell` - Adds `shadow` prop in `Grid` and `Cell` - Adds `component` prop in `Grid`, `Cell` and `Content` - Changes `HeaderRow` to only render a `Spacer` if a title is present [1.3.0]: https://github.com/tleunen/react-mdl/compare/v1.2.0...v1.3.0 ## [1.2.0] - Adds `shadow` prop on `DataTable` - Changes `RadioGroup` to be controlled or uncontrolled ([#180]) - Changes the propTypes of `DataTable` to be less strict - Adds `tooltip` and `className` in the column description of `DataTable` - Deprecates `data` in favor of `rows` in `DataTable` - Deprecates `selectable` in `DataTable` [1.2.0]: https://github.com/tleunen/react-mdl/compare/v1.1.0...v1.2.0 [#180]: https://github.com/tleunen/react-mdl/issues/180 ## [1.1.0] - Adds new `tabBarProps` to `Tabs` ([#160]) - Fixes the propTypes of Tabs ([#160]) - Fixes the `error` propType of `Textfield` ([#179]) [1.1.0]: https://github.com/tleunen/react-mdl/compare/v1.0.4...v1.1.0 [#160]: https://github.com/tleunen/react-mdl/issues/160 [#179]: https://github.com/tleunen/react-mdl/issues/179 ## [1.0.4] - Fixes the validity of a `TextField` when specifying an `error` ([#156]) [1.0.4]: https://github.com/tleunen/react-mdl/compare/v1.0.3...v1.0.4 [#156]: https://github.com/tleunen/react-mdl/issues/156 ## [1.0.3] - Adds `noSpacing` prop to `Grid` component - Changes some propTypes in `Layout` to accept more renderables ([#147]) - Fixes the updates of `disabled`and `checked` on `Checkbox` ([#136]) - Fixes the updates of `disabled`and `checked` on `Radio` and `IconToggle` [1.0.3]: https://github.com/tleunen/react-mdl/compare/v1.0.2...v1.0.3 [#136]: https://github.com/tleunen/react-mdl/issues/136 [#147]: https://github.com/tleunen/react-mdl/issues/147 ## [1.0.2] - Adds `CardMedia` component ([#114]) - New documentation website [1.0.2]: https://github.com/tleunen/react-mdl/compare/v1.0.1...v1.0.2 [#114]: https://github.com/tleunen/react-mdl/issues/114 ## [1.0.1] - Fixes imports module ([#109]) [1.0.1]: https://github.com/tleunen/react-mdl/compare/v1.0.0...v1.0.1 [#109]: https://github.com/tleunen/react-mdl/issues/109 ## [1.0.0] - Adds `mdlUpgrade` and `MDLComponent` are now exported. ([#77]) - Updates the internal Material Design Lite to 1.0.6 ([#106]) - Changes the path to some components ([#85]) - Changes `ripple` is now false by default ([#90]) - Fixes all components: the `change` function now provides the event object. ([#83]) - Fixes `Textfield` not being updated when receiving a value programmatically ([#79]) - Fixes `Switch` not being updated when receiving new `checked`/`disabled` value programmatically. - Fixes `Badge` won't be rendered if the child is empty/null. ([#78]) - Fixes `Badge` won't be rendered when the prop `text` is null or undefined. ([#84]) - Fixes `HeaderTabs` to work the same way as `Tabs` ([#66]) [1.0.0]: https://github.com/tleunen/react-mdl/compare/v0.15.0...v1.0.0 [#77]: https://github.com/tleunen/react-mdl/issues/77 [#106]: https://github.com/tleunen/react-mdl/issues/106 [#85]: https://github.com/tleunen/react-mdl/issues/85 [#90]: https://github.com/tleunen/react-mdl/issues/90 [#83]: https://github.com/tleunen/react-mdl/issues/83 [#79]: https://github.com/tleunen/react-mdl/issues/79 [#78]: https://github.com/tleunen/react-mdl/issues/78 [#84]: https://github.com/tleunen/react-mdl/issues/84 [#66]: https://github.com/tleunen/react-mdl/issues/66
{ "content_hash": "88134e8ba0089f8cfa9d6a88b93ed68e", "timestamp": "", "source": "github", "line_count": 317, "max_line_length": 239, "avg_line_length": 39.59305993690852, "alnum_prop": 0.6932515337423313, "repo_name": "andeemarks/conf-gen-div-react", "id": "5ce805315ccde81342eb4082ab78067f21863d34", "size": "12565", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/react-mdl/CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5432" }, { "name": "HTML", "bytes": "2433" }, { "name": "JavaScript", "bytes": "40219" } ], "symlink_target": "" }
package org.olat.presentation.course.nodes.tu; import java.net.MalformedURLException; import java.net.URL; import org.olat.lms.commons.ModuleConfiguration; import org.olat.presentation.framework.core.UserRequest; import org.olat.presentation.framework.core.components.form.flexible.FormItem; import org.olat.presentation.framework.core.components.form.flexible.FormItemContainer; import org.olat.presentation.framework.core.components.form.flexible.elements.MultipleSelectionElement; import org.olat.presentation.framework.core.components.form.flexible.elements.SingleSelection; import org.olat.presentation.framework.core.components.form.flexible.elements.TextElement; import org.olat.presentation.framework.core.components.form.flexible.impl.FormBasicController; import org.olat.presentation.framework.core.components.form.flexible.impl.FormEvent; import org.olat.presentation.framework.core.control.Controller; import org.olat.presentation.framework.core.control.WindowControl; import org.olat.system.commons.StringHelper; import org.olat.system.event.Event; import org.olat.system.exception.OLATRuntimeException; /** * Description:<BR/> * TODO: Class Description for TUConfigForm * <P/> * Initial Date: Oct 12, 2004 * * @author Felix Jost * @author Lars Eberle (<a href="http://www.bps-system.de/">BPS Bildungsportal Sachsen GmbH</a>) */ public class TUConfigForm extends FormBasicController { /** config option: password */ public static final String CONFIGKEY_PASS = "pass"; /** config option: username */ public static final String CONFIGKEY_USER = "user"; /** config option: port */ public static final String CONFIGKEY_PORT = "port"; /** config option: uri */ public static final String CONFIGKEY_URI = "uri"; /** config option: query */ public static final String CONFIGKEY_QUERY = "query"; /** config option: hostname */ public static final String CONFIGKEY_HOST = "host"; /** config option: protocol */ public static final String CONFIGKEY_PROTO = "proto"; /** supported protocols */ public static final String[] PROTOCOLS = new String[] { "http", "https" }; /** Configuration key: use tunnel for iframe or display directly ("<iframe src='www.ethz.ch'></iframe>"). Values: true, false **/ public static final String CONFIG_TUNNEL = "useframetunnel"; // don't change value, used in config /** Configuration key: display content in iframe: Values: true, false **/ public static final String CONFIG_IFRAME = "iniframe"; /** Configuration key: display content in new browser window: Values: true, false **/ public static final String CONFIG_EXTERN = "extern"; /* * They are only used inside this form and will not be saved anywhere, so feel free to change them... */ private static final String OPTION_TUNNEL_THROUGH_OLAT_INLINE = "tunnelInline"; private static final String OPTION_TUNNEL_THROUGH_OLAT_IFRAME = "tunnelIFrame"; private static final String OPTION_SHOW_IN_OLAT_IN_AN_IFRAME = "directIFrame"; private static final String OPTION_SHOW_IN_NEW_BROWSER_WINDOW = "extern"; /* * NLS support: */ private static final String NLS_OPTION_TUNNEL_INLINE_LABEL = "option.tunnel.inline.label"; private static final String NLS_OPTION_TUNNEL_IFRAME_LABEL = "option.tunnel.iframe.label"; private static final String NLS_OPTION_OLAT_IFRAME_LABEL = "option.olat.iframe.label"; private static final String NLS_OPTION_EXTERN_PAGE_LABEL = "option.extern.page.label"; private static final String NLS_DESCRIPTION_LABEL = "description.label"; private static final String NLS_DESCRIPTION_PREAMBLE = "description.preamble"; private static final String NLS_DISPLAY_CONFIG_EXTERN = "display.config.extern"; private final ModuleConfiguration config; private TextElement thost; private TextElement tuser; private TextElement tpass; private SingleSelection selectables; private final String[] selectableValues, selectableLabels; String user, pass; String fullURI; private MultipleSelectionElement checkboxPagePasswordProtected; /** * Constructor for the tunneling configuration form * * @param name * @param config * @param withCancel */ public TUConfigForm(final UserRequest ureq, final WindowControl wControl, final ModuleConfiguration config, final boolean withCancel) { super(ureq, wControl); this.config = config; final int configVersion = config.getConfigurationVersion(); final String proto = (String) config.get(CONFIGKEY_PROTO); final String host = (String) config.get(CONFIGKEY_HOST); String uri = (String) config.get(CONFIGKEY_URI); if (uri != null && uri.length() > 0 && uri.charAt(0) == '/') { uri = uri.substring(1); } String query = null; if (configVersion == 2) { // query string is available since config version 2 query = (String) config.get(TUConfigForm.CONFIGKEY_QUERY); } final Integer port = (Integer) config.get(CONFIGKEY_PORT); user = (String) config.get(CONFIGKEY_USER); pass = (String) config.get(CONFIGKEY_PASS); fullURI = getFullURL(proto, host, port, uri, query).toString(); selectableValues = new String[] { OPTION_SHOW_IN_NEW_BROWSER_WINDOW, OPTION_TUNNEL_THROUGH_OLAT_IFRAME, OPTION_SHOW_IN_OLAT_IN_AN_IFRAME, OPTION_TUNNEL_THROUGH_OLAT_INLINE }; selectableLabels = new String[] { translate(NLS_OPTION_EXTERN_PAGE_LABEL), translate(NLS_OPTION_TUNNEL_IFRAME_LABEL), translate(NLS_OPTION_OLAT_IFRAME_LABEL), translate(NLS_OPTION_TUNNEL_INLINE_LABEL) }; initForm(ureq); } public static StringBuilder getFullURL(final String proto, final String host, final Integer port, final String uri, final String query) { final StringBuilder fullURL = new StringBuilder(); if (proto != null && host != null) { fullURL.append(proto).append("://"); fullURL.append(host); if (port != null) { if (proto.equals("http") || proto.equals("https")) { if (proto.equals("http") && port.intValue() != 80) { fullURL.append(":" + port); } else if (proto.equals("https") && port.intValue() != 443) { fullURL.append(":" + port); } } else { fullURL.append(":" + port); } } if (uri == null) { fullURL.append("/"); } else { // append "/" if not already there, old configurations might have no "/" if (uri.indexOf("/") != 0) { fullURL.append("/"); } fullURL.append(uri); } if (query != null) { fullURL.append("?").append(query); } } return fullURL; } @Override protected boolean validateFormLogic(final UserRequest ureq) { try { new URL(thost.getValue()); } catch (final MalformedURLException e) { thost.setErrorKey("TUConfigForm.invalidurl"); return false; } return true; } private String convertConfigToNewStyle(final ModuleConfiguration cfg) { final Boolean tunnel = cfg.getBooleanEntry(CONFIG_TUNNEL); final Boolean iframe = cfg.getBooleanEntry(CONFIG_IFRAME); final Boolean extern = cfg.getBooleanEntry(CONFIG_EXTERN); if (tunnel == null && iframe == null && extern == null) { // nothing saved yet return OPTION_SHOW_IN_NEW_BROWSER_WINDOW; } else { // something is saved ... if (extern != null && extern.booleanValue()) { // ... it was extern... return OPTION_SHOW_IN_NEW_BROWSER_WINDOW; } else if (tunnel != null && tunnel.booleanValue()) { // ... it was tunneled if (iframe != null && iframe.booleanValue()) { // ... and in a iframe return OPTION_TUNNEL_THROUGH_OLAT_IFRAME; } else { // ... no iframe return OPTION_TUNNEL_THROUGH_OLAT_INLINE; } } else { // ... no tunnel means inline return OPTION_SHOW_IN_OLAT_IN_AN_IFRAME; } } } /** * @return the updated module configuration using the form data */ public ModuleConfiguration getUpdatedConfig() { URL url = null; try { url = new URL(thost.getValue()); } catch (final MalformedURLException e) { throw new OLATRuntimeException("MalformedURL in TUConfigForm which should not happen, since we've validated before. URL: " + thost.getValue(), e); } config.setConfigurationVersion(2); config.set(CONFIGKEY_PROTO, url.getProtocol()); config.set(CONFIGKEY_HOST, url.getHost()); config.set(CONFIGKEY_URI, url.getPath()); config.set(CONFIGKEY_QUERY, url.getQuery()); final int portHere = url.getPort(); config.set(CONFIGKEY_PORT, new Integer(portHere != -1 ? portHere : url.getDefaultPort())); config.set(CONFIGKEY_USER, getFormUser()); config.set(CONFIGKEY_PASS, getFormPass()); // now save new mapped config: final String selected = selectables.getSelectedKey(); // if content should be show in extern window config.setBooleanEntry(CONFIG_EXTERN, selected.equals(OPTION_SHOW_IN_NEW_BROWSER_WINDOW)); // if content should be tunneled config.setBooleanEntry(CONFIG_TUNNEL, (selected.equals(OPTION_TUNNEL_THROUGH_OLAT_INLINE) || selected.equals(OPTION_TUNNEL_THROUGH_OLAT_IFRAME))); // if content should be displayed in iframe config.setBooleanEntry(CONFIG_IFRAME, (selected.equals(OPTION_TUNNEL_THROUGH_OLAT_IFRAME) || selected.equals(OPTION_SHOW_IN_OLAT_IN_AN_IFRAME))); return config; } private String getFormUser() { if (StringHelper.containsNonWhitespace(tuser.getValue())) { return tuser.getValue(); } else { return null; } } private String getFormPass() { return tpass.getValue(); } @Override protected void formOK(final UserRequest ureq) { fireEvent(ureq, Event.DONE_EVENT); } @Override protected void initForm(final FormItemContainer formLayout, final Controller listener, final UserRequest ureq) { thost = uifactory.addTextElement("st", "TUConfigForm.url", 255, fullURI, formLayout); thost.setExampleKey("form.url.example", null); thost.setMandatory(true); uifactory.addStaticTextElement("expl", NLS_DESCRIPTION_LABEL, translate(NLS_DESCRIPTION_PREAMBLE), formLayout); final String loadedConfig = convertConfigToNewStyle(config); selectables = uifactory.addRadiosVertical("selectables", NLS_DISPLAY_CONFIG_EXTERN, formLayout, selectableValues, selectableLabels); selectables.select(loadedConfig, true); selectables.addActionListener(this, FormEvent.ONCLICK); checkboxPagePasswordProtected = uifactory.addCheckboxesVertical("checkbox", "TUConfigForm.protected", formLayout, new String[] { "ison" }, new String[] { "" }, null, 1); checkboxPagePasswordProtected.select("ison", (user != null) && !user.equals("")); // register for on click event to hide/disable other elements checkboxPagePasswordProtected.addActionListener(listener, FormEvent.ONCLICK); tuser = uifactory.addTextElement("user", "TUConfigForm.user", 255, user == null ? "" : user, formLayout); tpass = uifactory.addPasswordElement("pass", "TUConfigForm.pass", 255, pass == null ? "" : pass, formLayout); uifactory.addFormSubmitButton("submit", formLayout); update(); } @Override protected void formInnerEvent(final UserRequest ureq, final FormItem source, final FormEvent event) { update(); } private void update() { // Checkbox 'page password protected' only visible when OPTION_TUNNEL_THROUGH_OLAT_INLINE or OPTION_TUNNEL_THROUGH_OLAT_IFRAME checkboxPagePasswordProtected.setVisible(selectables.isSelected(0) || selectables.isSelected(3)); if (checkboxPagePasswordProtected.isSelected(0) && checkboxPagePasswordProtected.isVisible()) { tuser.setVisible(true); tpass.setVisible(true); } else { tuser.setValue(""); tuser.setVisible(false); tpass.setValue(""); tpass.setVisible(false); } } @Override protected void doDispose() { // } }
{ "content_hash": "2ed876e7735c3fbfbfa26c4639cf5613", "timestamp": "", "source": "github", "line_count": 298, "max_line_length": 167, "avg_line_length": 43.057046979865774, "alnum_prop": 0.6497545008183306, "repo_name": "huihoo/olat", "id": "901faa5a13dbdeb72f43026617e8f039ac187f3e", "size": "13627", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "olat7.8/src/main/java/org/olat/presentation/course/nodes/tu/TUConfigForm.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "24445" }, { "name": "AspectJ", "bytes": "36132" }, { "name": "CSS", "bytes": "2135670" }, { "name": "HTML", "bytes": "2950677" }, { "name": "Java", "bytes": "50804277" }, { "name": "JavaScript", "bytes": "31237972" }, { "name": "PLSQL", "bytes": "64492" }, { "name": "Perl", "bytes": "10717" }, { "name": "Shell", "bytes": "79994" }, { "name": "XSLT", "bytes": "186520" } ], "symlink_target": "" }
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ namespace Amqp { using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Amqp.Framing; using Amqp.Sasl; /// <summary> /// The factory to create connections asynchronously. /// </summary> public class ConnectionFactory : ConnectionFactoryBase { SslSettings sslSettings; SaslSettings saslSettings; /// <summary> /// Constructor to create a connection factory. /// </summary> public ConnectionFactory() : base() { } /// <summary> /// Gets the TLS/SSL settings on the factory. /// </summary> public SslSettings SSL { get { return this.sslSettings ?? (this.sslSettings = new SslSettings()); } } /// <summary> /// Gets the SASL settings on the factory. /// </summary> public SaslSettings SASL { get { return this.saslSettings ?? (this.saslSettings = new SaslSettings()); } } internal SslSettings SslInternal { get { return this.sslSettings; } } /// <summary> /// Creates a new connection. /// </summary> /// <param name="address">The address of remote endpoint to connect to.</param> /// <returns></returns> public Task<Connection> CreateAsync(Address address) { return this.CreateAsync(address, null, null); } /// <summary> /// Creates a new connection with a custom open frame and a callback to handle remote open frame. /// </summary> /// <param name="address">The address of remote endpoint to connect to.</param> /// <param name="open">If specified, it is sent to open the connection, otherwise an open frame created from the AMQP settings property is sent.</param> /// <param name="onOpened">If specified, it is invoked when an open frame is received from the remote peer.</param> /// <returns></returns> public async Task<Connection> CreateAsync(Address address, Open open, OnOpened onOpened) { IAsyncTransport transport; if (WebSocketTransport.MatchScheme(address.Scheme)) { WebSocketTransport wsTransport = new WebSocketTransport(); await wsTransport.ConnectAsync(address); transport = wsTransport; } else { TcpTransport tcpTransport = new TcpTransport(); await tcpTransport.ConnectAsync(address, this); transport = tcpTransport; } if (address.User != null) { SaslPlainProfile profile = new SaslPlainProfile(address.User, address.Password); transport = await profile.OpenAsync(address.Host, transport); } else if (this.saslSettings != null && this.saslSettings.Profile != null) { transport = await this.saslSettings.Profile.OpenAsync(address.Host, transport); } AsyncPump pump = new AsyncPump(transport); Connection connection = new Connection(this.AMQP, address, transport, open, onOpened); pump.Start(connection); return connection; } /// <summary> /// Contains the TLS/SSL settings for a connection. /// </summary> public class SslSettings { internal SslSettings() { this.Protocols = SslProtocols.Default; this.ClientCertificates = new X509CertificateCollection(); } /// <summary> /// Client certificates to use for mutual authentication. /// </summary> public X509CertificateCollection ClientCertificates { get; set; } /// <summary> /// Supported protocols to use. /// </summary> public SslProtocols Protocols { get; set; } /// <summary> /// Specifies whether certificate revocation should be performed during handshake. /// </summary> public bool CheckCertificateRevocation { get; set; } /// <summary> /// Gets or sets a certificate validation callback to validate remote certificate. /// </summary> public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; } } /// <summary> /// Contains the SASL settings for a connection. /// </summary> public class SaslSettings { /// <summary> /// The SASL profile to use for SASL negotiation. /// </summary> public SaslProfile Profile { get; set; } } } }
{ "content_hash": "417ac728a80acfe462b150110efaacab", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 160, "avg_line_length": 33.80327868852459, "alnum_prop": 0.5355641771742645, "repo_name": "timhermann/amqpnetlite", "id": "a5a6061b3bbc8cd8f00c69d02e8bd2786b038417", "size": "6188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Net/ConnectionFactory.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "898" }, { "name": "C#", "bytes": "795374" } ], "symlink_target": "" }
#include "examples/peerconnection/client/peer_connection_client.h" #include "examples/peerconnection/client/defaults.h" #include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h" #include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h" #include BOSS_WEBRTC_U_rtc_base__nethelpers_h //original-code:"rtc_base/nethelpers.h" #include BOSS_WEBRTC_U_rtc_base__stringutils_h //original-code:"rtc_base/stringutils.h" #ifdef WIN32 #include BOSS_WEBRTC_U_rtc_base__win32socketserver_h //original-code:"rtc_base/win32socketserver.h" #endif using rtc::sprintfn; namespace { // This is our magical hangup signal. const char kByeMessage[] = "BYE"; // Delay between server connection retries, in milliseconds const int kReconnectDelay = 2000; rtc::AsyncSocket* CreateClientSocket(int family) { #ifdef WIN32 rtc::Win32Socket* sock = new rtc::Win32Socket(); sock->CreateT(family, SOCK_STREAM); return sock; #elif defined(WEBRTC_POSIX) rtc::Thread* thread = rtc::Thread::Current(); RTC_DCHECK(thread != NULL); return thread->socketserver()->CreateAsyncSocket(family, SOCK_STREAM); #else #error Platform not supported. #endif } } // namespace PeerConnectionClient::PeerConnectionClient() : callback_(NULL), resolver_(NULL), state_(NOT_CONNECTED), my_id_(-1) { } PeerConnectionClient::~PeerConnectionClient() { } void PeerConnectionClient::InitSocketSignals() { RTC_DCHECK(control_socket_.get() != NULL); RTC_DCHECK(hanging_get_.get() != NULL); control_socket_->SignalCloseEvent.connect(this, &PeerConnectionClient::OnClose); hanging_get_->SignalCloseEvent.connect(this, &PeerConnectionClient::OnClose); control_socket_->SignalConnectEvent.connect(this, &PeerConnectionClient::OnConnect); hanging_get_->SignalConnectEvent.connect(this, &PeerConnectionClient::OnHangingGetConnect); control_socket_->SignalReadEvent.connect(this, &PeerConnectionClient::OnRead); hanging_get_->SignalReadEvent.connect(this, &PeerConnectionClient::OnHangingGetRead); } int PeerConnectionClient::id() const { return my_id_; } bool PeerConnectionClient::is_connected() const { return my_id_ != -1; } const Peers& PeerConnectionClient::peers() const { return peers_; } void PeerConnectionClient::RegisterObserver( PeerConnectionClientObserver* callback) { RTC_DCHECK(!callback_); callback_ = callback; } void PeerConnectionClient::Connect(const std::string& server, int port, const std::string& client_name) { RTC_DCHECK(!server.empty()); RTC_DCHECK(!client_name.empty()); if (state_ != NOT_CONNECTED) { RTC_LOG(WARNING) << "The client must not be connected before you can call Connect()"; callback_->OnServerConnectionFailure(); return; } if (server.empty() || client_name.empty()) { callback_->OnServerConnectionFailure(); return; } if (port <= 0) port = kDefaultServerPort; server_address_.SetIP(server); server_address_.SetPort(port); client_name_ = client_name; if (server_address_.IsUnresolvedIP()) { state_ = RESOLVING; resolver_ = new rtc::AsyncResolver(); resolver_->SignalDone.connect(this, &PeerConnectionClient::OnResolveResult); resolver_->Start(server_address_); } else { DoConnect(); } } void PeerConnectionClient::OnResolveResult( rtc::AsyncResolverInterface* resolver) { if (resolver_->GetError() != 0) { callback_->OnServerConnectionFailure(); resolver_->Destroy(false); resolver_ = NULL; state_ = NOT_CONNECTED; } else { server_address_ = resolver_->address(); DoConnect(); } } void PeerConnectionClient::DoConnect() { control_socket_.reset(CreateClientSocket(server_address_.ipaddr().family())); hanging_get_.reset(CreateClientSocket(server_address_.ipaddr().family())); InitSocketSignals(); char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /sign_in?%s HTTP/1.0\r\n\r\n", client_name_.c_str()); onconnect_data_ = buffer; bool ret = ConnectControlSocket(); if (ret) state_ = SIGNING_IN; if (!ret) { callback_->OnServerConnectionFailure(); } } bool PeerConnectionClient::SendToPeer(int peer_id, const std::string& message) { if (state_ != CONNECTED) return false; RTC_DCHECK(is_connected()); RTC_DCHECK(control_socket_->GetState() == rtc::Socket::CS_CLOSED); if (!is_connected() || peer_id == -1) return false; char headers[1024]; sprintfn(headers, sizeof(headers), "POST /message?peer_id=%i&to=%i HTTP/1.0\r\n" "Content-Length: %i\r\n" "Content-Type: text/plain\r\n" "\r\n", my_id_, peer_id, message.length()); onconnect_data_ = headers; onconnect_data_ += message; return ConnectControlSocket(); } bool PeerConnectionClient::SendHangUp(int peer_id) { return SendToPeer(peer_id, kByeMessage); } bool PeerConnectionClient::IsSendingMessage() { return state_ == CONNECTED && control_socket_->GetState() != rtc::Socket::CS_CLOSED; } bool PeerConnectionClient::SignOut() { if (state_ == NOT_CONNECTED || state_ == SIGNING_OUT) return true; if (hanging_get_->GetState() != rtc::Socket::CS_CLOSED) hanging_get_->Close(); if (control_socket_->GetState() == rtc::Socket::CS_CLOSED) { state_ = SIGNING_OUT; if (my_id_ != -1) { char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /sign_out?peer_id=%i HTTP/1.0\r\n\r\n", my_id_); onconnect_data_ = buffer; return ConnectControlSocket(); } else { // Can occur if the app is closed before we finish connecting. return true; } } else { state_ = SIGNING_OUT_WAITING; } return true; } void PeerConnectionClient::Close() { control_socket_->Close(); hanging_get_->Close(); onconnect_data_.clear(); peers_.clear(); if (resolver_ != NULL) { resolver_->Destroy(false); resolver_ = NULL; } my_id_ = -1; state_ = NOT_CONNECTED; } bool PeerConnectionClient::ConnectControlSocket() { RTC_DCHECK(control_socket_->GetState() == rtc::Socket::CS_CLOSED); int err = control_socket_->Connect(server_address_); if (err == SOCKET_ERROR) { Close(); return false; } return true; } void PeerConnectionClient::OnConnect(rtc::AsyncSocket* socket) { RTC_DCHECK(!onconnect_data_.empty()); size_t sent = socket->Send(onconnect_data_.c_str(), onconnect_data_.length()); RTC_DCHECK(sent == onconnect_data_.length()); onconnect_data_.clear(); } void PeerConnectionClient::OnHangingGetConnect(rtc::AsyncSocket* socket) { char buffer[1024]; sprintfn(buffer, sizeof(buffer), "GET /wait?peer_id=%i HTTP/1.0\r\n\r\n", my_id_); int len = static_cast<int>(strlen(buffer)); int sent = socket->Send(buffer, len); RTC_DCHECK(sent == len); } void PeerConnectionClient::OnMessageFromPeer(int peer_id, const std::string& message) { if (message.length() == (sizeof(kByeMessage) - 1) && message.compare(kByeMessage) == 0) { callback_->OnPeerDisconnected(peer_id); } else { callback_->OnMessageFromPeer(peer_id, message); } } bool PeerConnectionClient::GetHeaderValue(const std::string& data, size_t eoh, const char* header_pattern, size_t* value) { RTC_DCHECK(value != NULL); size_t found = data.find(header_pattern); if (found != std::string::npos && found < eoh) { *value = atoi(&data[found + strlen(header_pattern)]); return true; } return false; } bool PeerConnectionClient::GetHeaderValue(const std::string& data, size_t eoh, const char* header_pattern, std::string* value) { RTC_DCHECK(value != NULL); size_t found = data.find(header_pattern); if (found != std::string::npos && found < eoh) { size_t begin = found + strlen(header_pattern); size_t end = data.find("\r\n", begin); if (end == std::string::npos) end = eoh; value->assign(data.substr(begin, end - begin)); return true; } return false; } bool PeerConnectionClient::ReadIntoBuffer(rtc::AsyncSocket* socket, std::string* data, size_t* content_length) { char buffer[0xffff]; do { int bytes = socket->Recv(buffer, sizeof(buffer), nullptr); if (bytes <= 0) break; data->append(buffer, bytes); } while (true); bool ret = false; size_t i = data->find("\r\n\r\n"); if (i != std::string::npos) { RTC_LOG(INFO) << "Headers received"; if (GetHeaderValue(*data, i, "\r\nContent-Length: ", content_length)) { size_t total_response_size = (i + 4) + *content_length; if (data->length() >= total_response_size) { ret = true; std::string should_close; const char kConnection[] = "\r\nConnection: "; if (GetHeaderValue(*data, i, kConnection, &should_close) && should_close.compare("close") == 0) { socket->Close(); // Since we closed the socket, there was no notification delivered // to us. Compensate by letting ourselves know. OnClose(socket, 0); } } else { // We haven't received everything. Just continue to accept data. } } else { RTC_LOG(LS_ERROR) << "No content length field specified by the server."; } } return ret; } void PeerConnectionClient::OnRead(rtc::AsyncSocket* socket) { size_t content_length = 0; if (ReadIntoBuffer(socket, &control_data_, &content_length)) { size_t peer_id = 0, eoh = 0; bool ok = ParseServerResponse(control_data_, content_length, &peer_id, &eoh); if (ok) { if (my_id_ == -1) { // First response. Let's store our server assigned ID. RTC_DCHECK(state_ == SIGNING_IN); my_id_ = static_cast<int>(peer_id); RTC_DCHECK(my_id_ != -1); // The body of the response will be a list of already connected peers. if (content_length) { size_t pos = eoh + 4; while (pos < control_data_.size()) { size_t eol = control_data_.find('\n', pos); if (eol == std::string::npos) break; int id = 0; std::string name; bool connected; if (ParseEntry(control_data_.substr(pos, eol - pos), &name, &id, &connected) && id != my_id_) { peers_[id] = name; callback_->OnPeerConnected(id, name); } pos = eol + 1; } } RTC_DCHECK(is_connected()); callback_->OnSignedIn(); } else if (state_ == SIGNING_OUT) { Close(); callback_->OnDisconnected(); } else if (state_ == SIGNING_OUT_WAITING) { SignOut(); } } control_data_.clear(); if (state_ == SIGNING_IN) { RTC_DCHECK(hanging_get_->GetState() == rtc::Socket::CS_CLOSED); state_ = CONNECTED; hanging_get_->Connect(server_address_); } } } void PeerConnectionClient::OnHangingGetRead(rtc::AsyncSocket* socket) { RTC_LOG(INFO) << __FUNCTION__; size_t content_length = 0; if (ReadIntoBuffer(socket, &notification_data_, &content_length)) { size_t peer_id = 0, eoh = 0; bool ok = ParseServerResponse(notification_data_, content_length, &peer_id, &eoh); if (ok) { // Store the position where the body begins. size_t pos = eoh + 4; if (my_id_ == static_cast<int>(peer_id)) { // A notification about a new member or a member that just // disconnected. int id = 0; std::string name; bool connected = false; if (ParseEntry(notification_data_.substr(pos), &name, &id, &connected)) { if (connected) { peers_[id] = name; callback_->OnPeerConnected(id, name); } else { peers_.erase(id); callback_->OnPeerDisconnected(id); } } } else { OnMessageFromPeer(static_cast<int>(peer_id), notification_data_.substr(pos)); } } notification_data_.clear(); } if (hanging_get_->GetState() == rtc::Socket::CS_CLOSED && state_ == CONNECTED) { hanging_get_->Connect(server_address_); } } bool PeerConnectionClient::ParseEntry(const std::string& entry, std::string* name, int* id, bool* connected) { RTC_DCHECK(name != NULL); RTC_DCHECK(id != NULL); RTC_DCHECK(connected != NULL); RTC_DCHECK(!entry.empty()); *connected = false; size_t separator = entry.find(','); if (separator != std::string::npos) { *id = atoi(&entry[separator + 1]); name->assign(entry.substr(0, separator)); separator = entry.find(',', separator + 1); if (separator != std::string::npos) { *connected = atoi(&entry[separator + 1]) ? true : false; } } return !name->empty(); } int PeerConnectionClient::GetResponseStatus(const std::string& response) { int status = -1; size_t pos = response.find(' '); if (pos != std::string::npos) status = atoi(&response[pos + 1]); return status; } bool PeerConnectionClient::ParseServerResponse(const std::string& response, size_t content_length, size_t* peer_id, size_t* eoh) { int status = GetResponseStatus(response.c_str()); if (status != 200) { RTC_LOG(LS_ERROR) << "Received error from server"; Close(); callback_->OnDisconnected(); return false; } *eoh = response.find("\r\n\r\n"); RTC_DCHECK(*eoh != std::string::npos); if (*eoh == std::string::npos) return false; *peer_id = -1; // See comment in peer_channel.cc for why we use the Pragma header and // not e.g. "X-Peer-Id". GetHeaderValue(response, *eoh, "\r\nPragma: ", peer_id); return true; } void PeerConnectionClient::OnClose(rtc::AsyncSocket* socket, int err) { RTC_LOG(INFO) << __FUNCTION__; socket->Close(); #ifdef WIN32 if (err != WSAECONNREFUSED) { #else if (err != ECONNREFUSED) { #endif if (socket == hanging_get_.get()) { if (state_ == CONNECTED) { hanging_get_->Close(); hanging_get_->Connect(server_address_); } } else { callback_->OnMessageSent(err); } } else { if (socket == control_socket_.get()) { RTC_LOG(WARNING) << "Connection refused; retrying in 2 seconds"; rtc::Thread::Current()->PostDelayed(RTC_FROM_HERE, kReconnectDelay, this, 0); } else { Close(); callback_->OnDisconnected(); } } } void PeerConnectionClient::OnMessage(rtc::Message* msg) { // ignore msg; there is currently only one supported message ("retry") DoConnect(); }
{ "content_hash": "1fc09f86d059c9b49e0addf7bafb037c", "timestamp": "", "source": "github", "line_count": 505, "max_line_length": 99, "avg_line_length": 30.04158415841584, "alnum_prop": 0.6003559422582558, "repo_name": "koobonil/Boss2D", "id": "efda5f28494fa867706b3fca56c9e9c187b058e9", "size": "15579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Boss2D/addon/_old/webrtc-qt5.11.2_for_boss/examples/peerconnection/client/peer_connection_client.cc", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "4820445" }, { "name": "Awk", "bytes": "4272" }, { "name": "Batchfile", "bytes": "89930" }, { "name": "C", "bytes": "119747922" }, { "name": "C#", "bytes": "87505" }, { "name": "C++", "bytes": "272329620" }, { "name": "CMake", "bytes": "1199656" }, { "name": "CSS", "bytes": "42679" }, { "name": "Clojure", "bytes": "1487" }, { "name": "Cuda", "bytes": "1651996" }, { "name": "DIGITAL Command Language", "bytes": "239527" }, { "name": "Dockerfile", "bytes": "9638" }, { "name": "Emacs Lisp", "bytes": "15570" }, { "name": "Go", "bytes": "858185" }, { "name": "HLSL", "bytes": "3314" }, { "name": "HTML", "bytes": "2958385" }, { "name": "Java", "bytes": "2921052" }, { "name": "JavaScript", "bytes": "178190" }, { "name": "Jupyter Notebook", "bytes": "1833654" }, { "name": "LLVM", "bytes": "6536" }, { "name": "M4", "bytes": "775724" }, { "name": "MATLAB", "bytes": "74606" }, { "name": "Makefile", "bytes": "3941551" }, { "name": "Meson", "bytes": "2847" }, { "name": "Module Management System", "bytes": "2626" }, { "name": "NSIS", "bytes": "4505" }, { "name": "Objective-C", "bytes": "4090702" }, { "name": "Objective-C++", "bytes": "1702390" }, { "name": "PHP", "bytes": "3530" }, { "name": "Perl", "bytes": "11096338" }, { "name": "Perl 6", "bytes": "11802" }, { "name": "PowerShell", "bytes": "38571" }, { "name": "Python", "bytes": "24123805" }, { "name": "QMake", "bytes": "18188" }, { "name": "Roff", "bytes": "1261269" }, { "name": "Ruby", "bytes": "5890" }, { "name": "Scala", "bytes": "5683" }, { "name": "Shell", "bytes": "2879948" }, { "name": "TeX", "bytes": "243507" }, { "name": "TypeScript", "bytes": "1593696" }, { "name": "Verilog", "bytes": "1215" }, { "name": "Vim Script", "bytes": "3759" }, { "name": "Visual Basic", "bytes": "16186" }, { "name": "eC", "bytes": "9705" } ], "symlink_target": "" }
<!-- Copyright 2008 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- ================================================================== --> <!-- Route Setup --> <!-- ================================================================== --> <bean id="routeBuilder" class="org.openehealth.ipf.platform.camel.core.camel.exception.ExceptionHandlingRouteBuilder"> </bean> </beans>
{ "content_hash": "edd9917ac8d8f577822cfdbf6d5f5c99", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 100, "avg_line_length": 41.83870967741935, "alnum_prop": 0.5905936777178104, "repo_name": "krasserm/ipf", "id": "cc4de76026f39ed333b3b03763c73933323b10e7", "size": "1297", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform-camel/core/src/test/resources/context-camel-exception.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1891019" }, { "name": "Java", "bytes": "4710701" }, { "name": "Shell", "bytes": "12378" }, { "name": "XML", "bytes": "554629" }, { "name": "XQuery", "bytes": "15044" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using ThirtyNineEighty.BinarySerializer.Types; namespace ThirtyNineEighty.BinarySerializer { enum TypeExtensionKind { Write, Read } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] class BinTypeExtensionAttribute : Attribute { public string Name { get; private set; } public Type Type { get; private set; } public TypeExtensionKind Kind { get; private set; } public BinTypeExtensionAttribute(string name, Type type, TypeExtensionKind kind) { Name = name; Type = type; Kind = kind; } } static class BinTypeExtensions { [BinTypeExtension(SerializerTypes.DictionaryToken, typeof(Dictionary<,>), TypeExtensionKind.Write)] public static void WriteDictionary<TKey, TValue>(Stream stream, Dictionary<TKey, TValue> value) { stream.Write(value.Count); foreach (var current in value) { BinSerializer.Serialize(stream, current.Key); BinSerializer.Serialize(stream, current.Value); } } [BinTypeExtension(SerializerTypes.DictionaryToken, typeof(Dictionary<,>), TypeExtensionKind.Read)] public static Dictionary<TKey, TValue> ReadDictionary<TKey, TValue>(Stream stream, Dictionary<TKey, TValue> instance, int version) { var count = stream.ReadInt32(); for (int i = 0; i < count; i++) { var key = BinSerializer.Deserialize<TKey>(stream); var value = BinSerializer.Deserialize<TValue>(stream); instance.Add(key, value); } return instance; } [BinTypeExtension(SerializerTypes.ListToken, typeof(List<>), TypeExtensionKind.Write)] public static void WriteList<T>(Stream stream, List<T> value) { stream.Write(value.Count); foreach (var current in value) BinSerializer.Serialize(stream, current); } [BinTypeExtension(SerializerTypes.ListToken, typeof(List<>), TypeExtensionKind.Read)] public static List<T> ReadList<T>(Stream stream, List<T> instance, int version) { var count = stream.ReadInt32(); instance.Capacity = count; for (int i = 0; i < count; i++) { var value = BinSerializer.Deserialize<T>(stream); instance.Add(value); } return instance; } } }
{ "content_hash": "6929fca9f4c2a33edcb9a7612b00e6c4", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 134, "avg_line_length": 30.57894736842105, "alnum_prop": 0.6738382099827883, "repo_name": "Nirklav/BinSerializer", "id": "9580399cac569c74e5b9bef3318d0bb3b6f1c9a2", "size": "2326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BinSerializer/BinTypeExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "130663" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>vst: 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.8.0 / vst - 2.7</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> vst <small> 2.7 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-28 13:50:54 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-28 13:50:54 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.0 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; synopsis: &quot;Verified Software Toolchain&quot; description: &quot;The software toolchain includes static analyzers to check assertions about your program; optimizing compilers to translate your program to machine language; operating systems and libraries to supply context for your program. The Verified Software Toolchain project assures with machine-checked proofs that the assertions claimed at the top of the toolchain really hold in the machine-language program, running in the operating-system context.&quot; authors: [ &quot;Andrew W. Appel&quot; &quot;Lennart Beringer&quot; &quot;Sandrine Blazy&quot; &quot;Qinxiang Cao&quot; &quot;Santiago Cuellar&quot; &quot;Robert Dockins&quot; &quot;Josiah Dodds&quot; &quot;Nick Giannarakis&quot; &quot;Samuel Gruetter&quot; &quot;Aquinas Hobor&quot; &quot;Jean-Marie Madiot&quot; &quot;William Mansky&quot; ] maintainer: &quot;VST team&quot; homepage: &quot;http://vst.cs.princeton.edu/&quot; dev-repo: &quot;git+https://github.com/PrincetonUniversity/VST.git&quot; bug-reports: &quot;https://github.com/PrincetonUniversity/VST/issues&quot; license: &quot;https://raw.githubusercontent.com/PrincetonUniversity/VST/master/LICENSE&quot; build: [ [make &quot;-j%{jobs}%&quot; &quot;BITSIZE=64&quot; &quot;IGNORECOQVERSION=true&quot;] ] install: [ [&quot;mkdir&quot; &quot;-p&quot; &quot;%{lib}%/coq/user-contrib/VST&quot;] [&quot;cp&quot; &quot;-r&quot; &quot;msl&quot; &quot;%{lib}%/coq/user-contrib/VST/&quot;] [&quot;cp&quot; &quot;-r&quot; &quot;veric&quot; &quot;%{lib}%/coq/user-contrib/VST/&quot;] [&quot;cp&quot; &quot;-r&quot; &quot;floyd&quot; &quot;%{lib}%/coq/user-contrib/VST/&quot;] [&quot;cp&quot; &quot;-r&quot; &quot;sepcomp&quot; &quot;%{lib}%/coq/user-contrib/VST/&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.12&quot; &amp; &lt; &quot;8.14&quot;} &quot;coq-compcert&quot; {(= &quot;3.8&quot;) | (= &quot;3.8~open-source&quot;)} &quot;coq-flocq&quot; {&gt;= &quot;3.2.1&quot;} ] tags: [ &quot;category:Computer Science/Semantics and Compilation/Semantics&quot; &quot;keyword:C&quot; &quot;logpath:VST&quot; &quot;date:2020-12-20&quot; ] patches: [&quot;makefile.patch&quot;] url { src: &quot;https://github.com/PrincetonUniversity/VST/archive/v2.7.tar.gz&quot; checksum: &quot;sha256=970be13e71bdb013e2b9de64aecf1dda08228dd8ef3a1f6e4bb23ccd3a0896d3&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-vst.2.7 coq.8.8.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.0). The following dependencies couldn&#39;t be met: - coq-vst -&gt; coq &gt;= 8.12 -&gt; ocaml &gt;= 4.09.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-vst.2.7</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": "38f35980f07117d5e8b63461331f816b", "timestamp": "", "source": "github", "line_count": 192, "max_line_length": 467, "avg_line_length": 42.848958333333336, "alnum_prop": 0.568858636197885, "repo_name": "coq-bench/coq-bench.github.io", "id": "897fa1d1fe86faa349399328237a336e4340529f", "size": "8252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.8.0/vst/2.7.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
'use strict'; /** * Main sving module. * Usage: * * var opt = { * input: 'graphics.svg', * output: 'graphics.png', * 'output-path': 'build', // output directory * config: 'path/to/file.json' // json or yaml * id: 'asset_id_3', // element string id * filter: 'rect.*', // regex based id filter * all: false, // all elements in SVG input file * width: 48, * height: 48, * size: 48, // size sets width and height * dpi: 90, // 90 is Inkscape default * scale: 1.0, // alternative to dpi * background: '#ff00ff', * }; * * function callback(err, log) { * } * * var svink = require('svg-inkscape-rasterizer').svink; * * // with callback * svink(options, callback); * * // or without callback * svink(options); * * @module svink * @class svink */ var path = require('path'), fs = require('fs'), glob = require('glob'), debug = require('debug')('svink'), colors = require('colors'), _ = require('underscore'), async = require('async'), yaml = require('js-yaml'), ink = require('./inkscape'); var defaultConfig = 'graphics.json', defaults = { input: 'graphics.svg', output: 'graphics.png', 'output-path': 'build' }; colors.setTheme({ command: 'white', warn: 'yellow', error: 'red' }); function completed(err) { if (!err) { debug('finished'); } else { debug('finished with error %s', err.error); } } function expand(opt, cb) { glob(opt.input, function (err, files) { opt.inputs = files; cb(); }); } function run(opt, log, cb) { function iterator(item, cb) { var tmp = _.clone(opt); tmp.input = item; ink.render(tmp, log, cb); } expand(opt, function () { if (opt.inputs.length === 0) { cb("missing input files"); } else { async.eachSeries(opt.inputs, iterator, cb); } }); } function batch(opt, log, finale, depth) { function iterator(item, cb) { _.defaults(item, _.omit(opt, 'batch')); if (!item.batch) { run(item, log, cb); } else { batch(item, log, finale, cb); } } function finish(err) { debug('batch end'); if (!depth) { finale(err); } else { depth(err); } } debug('batch start'); async.eachSeries(opt.batch, iterator, finish); } /** * @method svink Main method * @param opt {Object} Options * @param cb {Function} Optional callback */ exports.svink = function (opt, cb) { var cfg, basedir = process.cwd(), cp, log = []; function finale(err) { debug('log %s', JSON.stringify(log)); completed(err); if (cb) { cb(err, log); } } debug('started'); debug('options: %s', JSON.stringify(opt)); if(opt.probe) { ink.probe(opt, log, function(err, stderr, stdout){ console.log(stdout); finale(err); }); return; } opt.config = opt.config || defaultConfig; try { cp = path.join(basedir, opt.config); if (fs.existsSync(cp)) { debug('using config: %s', cp); if (path.extname(cp) === '.yaml' || path.extname(cp) === '.yml') { cfg = yaml.safeLoad(fs.readFileSync(cp, 'utf8')); } else { cfg = JSON.parse(fs.readFileSync(cp, 'utf8')); } } } catch (ex) { debug('config error: %s', ex); finale(ex); return; } _.defaults(opt, defaults); if (cfg) { _.defaults(opt, cfg); } if (opt.help || opt.version || opt.probe) { finale(); return; } if (!opt.batch) { run(opt, log, finale); } else { batch(opt, log, finale); } };
{ "content_hash": "47babb07049f9373be7f311aee4e6bb7", "timestamp": "", "source": "github", "line_count": 186, "max_line_length": 78, "avg_line_length": 23.13978494623656, "alnum_prop": 0.4570167286245353, "repo_name": "darosh/node-svink", "id": "501664fdf6c59c55c80acd2c1a86aac0ebaa8709", "size": "4435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/svink.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "27745" }, { "name": "Shell", "bytes": "1137" } ], "symlink_target": "" }
package com.example.tutorial.ejemplo2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class Dos extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dos); } }
{ "content_hash": "a4b6e23781faf5e38fde1a5a9b1f4547", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 56, "avg_line_length": 22.266666666666666, "alnum_prop": 0.7485029940119761, "repo_name": "alfespa17/tutorialmobile", "id": "29bfeab8a3df0cdc836893ef87c146c05434d2da", "size": "334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ejemplo2LanzarActividadImplicita/app/src/main/java/com/example/tutorial/ejemplo2/Dos.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "50883" } ], "symlink_target": "" }
'use strict'; const BaseClient = require('./BaseClient'); const Permissions = require('../util/Permissions'); const ClientVoiceManager = require('./voice/ClientVoiceManager'); const WebSocketManager = require('./websocket/WebSocketManager'); const ActionsManager = require('./actions/ActionsManager'); const Collection = require('../util/Collection'); const VoiceRegion = require('../structures/VoiceRegion'); const Webhook = require('../structures/Webhook'); const Invite = require('../structures/Invite'); const ClientApplication = require('../structures/ClientApplication'); const ShardClientUtil = require('../sharding/ShardClientUtil'); const UserStore = require('../stores/UserStore'); const ChannelStore = require('../stores/ChannelStore'); const GuildStore = require('../stores/GuildStore'); const GuildEmojiStore = require('../stores/GuildEmojiStore'); const { Events, browser, DefaultOptions } = require('../util/Constants'); const DataResolver = require('../util/DataResolver'); const Structures = require('../util/Structures'); const { Error, TypeError, RangeError } = require('../errors'); /** * The main hub for interacting with the Discord API, and the starting point for any bot. * @extends {BaseClient} */ class Client extends BaseClient { /** * @param {ClientOptions} [options] Options for the client */ constructor(options = {}) { super(Object.assign({ _tokenType: 'Bot' }, options)); // Obtain shard details from environment or if present, worker threads let data = process.env; try { // Test if worker threads module is present and used data = require('worker_threads').workerData || data; } catch (_) { // Do nothing } if (this.options.shards === DefaultOptions.shards) { if ('SHARDS' in data) { this.options.shards = JSON.parse(data.SHARDS); } } if (this.options.totalShardCount === DefaultOptions.totalShardCount) { if ('TOTAL_SHARD_COUNT' in data) { this.options.totalShardCount = Number(data.TOTAL_SHARD_COUNT); } else if (Array.isArray(this.options.shards)) { this.options.totalShardCount = this.options.shards.length; } else { this.options.totalShardCount = this.options.shardCount; } } if (typeof this.options.shards === 'undefined' && typeof this.options.shardCount === 'number') { this.options.shards = Array.from({ length: this.options.shardCount }, (_, i) => i); } if (typeof this.options.shards === 'number') this.options.shards = [this.options.shards]; if (typeof this.options.shards !== 'undefined') { this.options.shards = [...new Set( this.options.shards.filter(item => !isNaN(item) && item >= 0 && item < Infinity) )]; } this._validateOptions(); /** * The WebSocket manager of the client * @type {WebSocketManager} */ this.ws = new WebSocketManager(this); /** * The action manager of the client * @type {ActionsManager} * @private */ this.actions = new ActionsManager(this); /** * The voice manager of the client (`null` in browsers) * @type {?ClientVoiceManager} */ this.voice = !browser ? new ClientVoiceManager(this) : null; /** * Shard helpers for the client (only if the process was spawned from a {@link ShardingManager}) * @type {?ShardClientUtil} */ this.shard = !browser && process.env.SHARDING_MANAGER ? ShardClientUtil.singleton(this, process.env.SHARDING_MANAGER_MODE) : null; /** * All of the {@link User} objects that have been cached at any point, mapped by their IDs * @type {UserStore<Snowflake, User>} */ this.users = new UserStore(this); /** * All of the guilds the client is currently handling, mapped by their IDs - * as long as sharding isn't being used, this will be *every* guild the bot is a member of * @type {GuildStore<Snowflake, Guild>} */ this.guilds = new GuildStore(this); /** * All of the {@link Channel}s that the client is currently handling, mapped by their IDs - * as long as sharding isn't being used, this will be *every* channel in *every* guild the bot * is a member of. Note that DM channels will not be initially cached, and thus not be present * in the store without their explicit fetching or use. * @type {ChannelStore<Snowflake, Channel>} */ this.channels = new ChannelStore(this); const ClientPresence = Structures.get('ClientPresence'); /** * The presence of the Client * @private * @type {ClientPresence} */ this.presence = new ClientPresence(this); Object.defineProperty(this, 'token', { writable: true }); if (!browser && !this.token && 'DISCORD_TOKEN' in process.env) { /** * Authorization token for the logged in bot * <warn>This should be kept private at all times.</warn> * @type {?string} */ this.token = process.env.DISCORD_TOKEN; } else { this.token = null; } /** * User that the client is logged in as * @type {?ClientUser} */ this.user = null; /** * Time at which the client was last regarded as being in the `READY` state * (each time the client disconnects and successfully reconnects, this will be overwritten) * @type {?Date} */ this.readyAt = null; if (this.options.messageSweepInterval > 0) { this.setInterval(this.sweepMessages.bind(this), this.options.messageSweepInterval * 1000); } } /** * All custom emojis that the client has access to, mapped by their IDs * @type {GuildEmojiStore<Snowflake, GuildEmoji>} * @readonly */ get emojis() { const emojis = new GuildEmojiStore({ client: this }); for (const guild of this.guilds.values()) { if (guild.available) for (const emoji of guild.emojis.values()) emojis.set(emoji.id, emoji); } return emojis; } /** * Timestamp of the time the client was last `READY` at * @type {?number} * @readonly */ get readyTimestamp() { return this.readyAt ? this.readyAt.getTime() : null; } /** * How long it has been since the client last entered the `READY` state in milliseconds * @type {?number} * @readonly */ get uptime() { return this.readyAt ? Date.now() - this.readyAt : null; } /** * Logs the client in, establishing a websocket connection to Discord. * @param {string} token Token of the account to log in with * @returns {Promise<string>} Token of the account used * @example * client.login('my token'); */ async login(token = this.token) { if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID'); this.token = token = token.replace(/^(Bot|Bearer)\s*/i, ''); this.emit(Events.DEBUG, `Provided token: ${token}`); if (this.options.presence) { this.options.ws.presence = await this.presence._parse(this.options.presence); } this.emit(Events.DEBUG, 'Preparing to connect to the gateway...'); try { await this.ws.connect(); return this.token; } catch (error) { this.destroy(); throw error; } } /** * Logs out, terminates the connection to Discord, and destroys the client. * @returns {void} */ destroy() { super.destroy(); this.ws.destroy(); this.token = null; } /** * Obtains an invite from Discord. * @param {InviteResolvable} invite Invite code or URL * @returns {Promise<Invite>} * @example * client.fetchInvite('https://discord.gg/bRCvFy9') * .then(invite => console.log(`Obtained invite with code: ${invite.code}`)) * .catch(console.error); */ fetchInvite(invite) { const code = DataResolver.resolveInviteCode(invite); return this.api.invites(code).get({ query: { with_counts: true } }) .then(data => new Invite(this, data)); } /** * Obtains a webhook from Discord. * @param {Snowflake} id ID of the webhook * @param {string} [token] Token for the webhook * @returns {Promise<Webhook>} * @example * client.fetchWebhook('id', 'token') * .then(webhook => console.log(`Obtained webhook with name: ${webhook.name}`)) * .catch(console.error); */ fetchWebhook(id, token) { return this.api.webhooks(id, token).get().then(data => new Webhook(this, data)); } /** * Obtains the available voice regions from Discord. * @returns {Collection<string, VoiceRegion>} * @example * client.fetchVoiceRegions() * .then(regions => console.log(`Available regions are: ${regions.map(region => region.name).join(', ')}`)) * .catch(console.error); */ fetchVoiceRegions() { return this.api.voice.regions.get().then(res => { const regions = new Collection(); for (const region of res) regions.set(region.id, new VoiceRegion(region)); return regions; }); } /** * Sweeps all text-based channels' messages and removes the ones older than the max message lifetime. * If the message has been edited, the time of the edit is used rather than the time of the original message. * @param {number} [lifetime=this.options.messageCacheLifetime] Messages that are older than this (in seconds) * will be removed from the caches. The default is based on {@link ClientOptions#messageCacheLifetime} * @returns {number} Amount of messages that were removed from the caches, * or -1 if the message cache lifetime is unlimited * @example * // Remove all messages older than 1800 seconds from the messages cache * const amount = client.sweepMessages(1800); * console.log(`Successfully removed ${amount} messages from the cache.`); */ sweepMessages(lifetime = this.options.messageCacheLifetime) { if (typeof lifetime !== 'number' || isNaN(lifetime)) { throw new TypeError('CLIENT_INVALID_OPTION', 'Lifetime', 'a number'); } if (lifetime <= 0) { this.emit(Events.DEBUG, 'Didn\'t sweep messages - lifetime is unlimited'); return -1; } const lifetimeMs = lifetime * 1000; const now = Date.now(); let channels = 0; let messages = 0; for (const channel of this.channels.values()) { if (!channel.messages) continue; channels++; messages += channel.messages.sweep( message => now - (message.editedTimestamp || message.createdTimestamp) > lifetimeMs ); } this.emit(Events.DEBUG, `Swept ${messages} messages older than ${lifetime} seconds in ${channels} text-based channels`); return messages; } /** * Obtains the OAuth Application of this bot from Discord. * @returns {Promise<ClientApplication>} */ fetchApplication() { return this.api.oauth2.applications('@me').get() .then(app => new ClientApplication(this, app)); } /** * Generates a link that can be used to invite the bot to a guild. * @param {PermissionResolvable} [permissions] Permissions to request * @returns {Promise<string>} * @example * client.generateInvite(['SEND_MESSAGES', 'MANAGE_GUILD', 'MENTION_EVERYONE']) * .then(link => console.log(`Generated bot invite link: ${link}`)) * .catch(console.error); */ async generateInvite(permissions) { permissions = Permissions.resolve(permissions); const application = await this.fetchApplication(); const query = new URLSearchParams({ client_id: application.id, permissions: permissions, scope: 'bot', }); return `${this.options.http.api}${this.api.oauth2.authorize}?${query}`; } toJSON() { return super.toJSON({ readyAt: false, presences: false, }); } /** * Calls {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval} on a script * with the client as `this`. * @param {string} script Script to eval * @returns {*} * @private */ _eval(script) { return eval(script); } /** * Validates the client options. * @param {ClientOptions} [options=this.options] Options to validate * @private */ _validateOptions(options = this.options) { // eslint-disable-line complexity if (options.shardCount !== 'auto' && (typeof options.shardCount !== 'number' || isNaN(options.shardCount))) { throw new TypeError('CLIENT_INVALID_OPTION', 'shardCount', 'a number or "auto"'); } if (options.shards && !Array.isArray(options.shards)) { throw new TypeError('CLIENT_INVALID_OPTION', 'shards', 'a number or array'); } if (options.shards && !options.shards.length) throw new RangeError('CLIENT_INVALID_PROVIDED_SHARDS'); if (options.shardCount < 1) throw new RangeError('CLIENT_INVALID_OPTION', 'shardCount', 'at least 1'); if (typeof options.messageCacheMaxSize !== 'number' || isNaN(options.messageCacheMaxSize)) { throw new TypeError('CLIENT_INVALID_OPTION', 'messageCacheMaxSize', 'a number'); } if (typeof options.messageCacheLifetime !== 'number' || isNaN(options.messageCacheLifetime)) { throw new TypeError('CLIENT_INVALID_OPTION', 'The messageCacheLifetime', 'a number'); } if (typeof options.messageSweepInterval !== 'number' || isNaN(options.messageSweepInterval)) { throw new TypeError('CLIENT_INVALID_OPTION', 'messageSweepInterval', 'a number'); } if (typeof options.fetchAllMembers !== 'boolean') { throw new TypeError('CLIENT_INVALID_OPTION', 'fetchAllMembers', 'a boolean'); } if (typeof options.disableEveryone !== 'boolean') { throw new TypeError('CLIENT_INVALID_OPTION', 'disableEveryone', 'a boolean'); } if (!Array.isArray(options.partials)) { throw new TypeError('CLIENT_INVALID_OPTION', 'partials', 'an Array'); } if (typeof options.restWsBridgeTimeout !== 'number' || isNaN(options.restWsBridgeTimeout)) { throw new TypeError('CLIENT_INVALID_OPTION', 'restWsBridgeTimeout', 'a number'); } if (typeof options.restSweepInterval !== 'number' || isNaN(options.restSweepInterval)) { throw new TypeError('CLIENT_INVALID_OPTION', 'restSweepInterval', 'a number'); } if (!Array.isArray(options.disabledEvents)) { throw new TypeError('CLIENT_INVALID_OPTION', 'disabledEvents', 'an Array'); } if (typeof options.retryLimit !== 'number' || isNaN(options.retryLimit)) { throw new TypeError('CLIENT_INVALID_OPTION', 'retryLimit', 'a number'); } } } module.exports = Client; /** * Emitted for general warnings. * @event Client#warn * @param {string} info The warning */ /** * Emitted for general debugging information. * @event Client#debug * @param {string} info The debug information */
{ "content_hash": "1622352a2b480d32499acf847eac4ebd", "timestamp": "", "source": "github", "line_count": 419, "max_line_length": 116, "avg_line_length": 35.004773269689736, "alnum_prop": 0.6518033681052703, "repo_name": "appellation/discord.js", "id": "257a5cd8109ecf1f3b113bef8c42f2d113565d1c", "size": "14667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/Client.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "874" }, { "name": "JavaScript", "bytes": "586067" }, { "name": "Shell", "bytes": "3020" } ], "symlink_target": "" }
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* Primitive-type-only definitions (values) */ /* * Copyright (C) 2002-2013 Sebastiano Vigna * * 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 it.unimi.dsi.fastutil.bytes; import it.unimi.dsi.fastutil.objects.AbstractObjectSortedSet; import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; import it.unimi.dsi.fastutil.objects.ObjectListIterator; import it.unimi.dsi.fastutil.objects.ObjectSortedSet; import it.unimi.dsi.fastutil.chars.CharCollection; import it.unimi.dsi.fastutil.chars.AbstractCharCollection; import it.unimi.dsi.fastutil.chars.CharIterator; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.SortedMap; import java.util.NoSuchElementException; import it.unimi.dsi.fastutil.chars.CharListIterator; /** A type-specific red-black tree map with a fast, small-footprint implementation. * * <P>The iterators provided by the views of this class are type-specific {@linkplain * it.unimi.dsi.fastutil.BidirectionalIterator bidirectional iterators}. * Moreover, the iterator returned by <code>iterator()</code> can be safely cast * to a type-specific {@linkplain java.util.ListIterator list iterator}. * */ public class Byte2CharRBTreeMap extends AbstractByte2CharSortedMap implements java.io.Serializable, Cloneable { /** A reference to the root entry. */ protected transient Entry tree; /** Number of entries in this map. */ protected int count; /** The first key in this map. */ protected transient Entry firstEntry; /** The last key in this map. */ protected transient Entry lastEntry; /** Cached set of entries. */ protected transient volatile ObjectSortedSet<Byte2CharMap.Entry > entries; /** Cached set of keys. */ protected transient volatile ByteSortedSet keys; /** Cached collection of values. */ protected transient volatile CharCollection values; /** The value of this variable remembers, after a <code>put()</code> * or a <code>remove()</code>, whether the <em>domain</em> of the map * has been modified. */ protected transient boolean modified; /** This map's comparator, as provided in the constructor. */ protected Comparator<? super Byte> storedComparator; /** This map's actual comparator; it may differ from {@link #storedComparator} because it is always a type-specific comparator, so it could be derived from the former by wrapping. */ protected transient ByteComparator actualComparator; private static final long serialVersionUID = -7046029254386353129L; private static final boolean ASSERTS = false; { allocatePaths(); } /** Creates a new empty tree map. */ public Byte2CharRBTreeMap() { tree = null; count = 0; } /** Generates the comparator that will be actually used. * * <P>When a specific {@link Comparator} is specified and stored in {@link * #storedComparator}, we must check whether it is type-specific. If it is * so, we can used directly, and we store it in {@link #actualComparator}. Otherwise, * we generate on-the-fly an anonymous class that wraps the non-specific {@link Comparator} * and makes it into a type-specific one. */ @SuppressWarnings("unchecked") private void setActualComparator() { /* If the provided comparator is already type-specific, we use it. Otherwise, we use a wrapper anonymous class to fake that it is type-specific. */ if ( storedComparator == null || storedComparator instanceof ByteComparator ) actualComparator = (ByteComparator)storedComparator; else actualComparator = new ByteComparator () { public int compare( byte k1, byte k2 ) { return storedComparator.compare( (Byte.valueOf(k1)), (Byte.valueOf(k2)) ); } public int compare( Byte ok1, Byte ok2 ) { return storedComparator.compare( ok1, ok2 ); } }; } /** Creates a new empty tree map with the given comparator. * * @param c a (possibly type-specific) comparator. */ public Byte2CharRBTreeMap( final Comparator<? super Byte> c ) { this(); storedComparator = c; setActualComparator(); } /** Creates a new tree map copying a given map. * * @param m a {@link Map} to be copied into the new tree map. */ public Byte2CharRBTreeMap( final Map<? extends Byte, ? extends Character> m ) { this(); putAll( m ); } /** Creates a new tree map copying a given sorted map (and its {@link Comparator}). * * @param m a {@link SortedMap} to be copied into the new tree map. */ public Byte2CharRBTreeMap( final SortedMap<Byte,Character> m ) { this( m.comparator() ); putAll( m ); } /** Creates a new tree map copying a given map. * * @param m a type-specific map to be copied into the new tree map. */ public Byte2CharRBTreeMap( final Byte2CharMap m ) { this(); putAll( m ); } /** Creates a new tree map copying a given sorted map (and its {@link Comparator}). * * @param m a type-specific sorted map to be copied into the new tree map. */ public Byte2CharRBTreeMap( final Byte2CharSortedMap m ) { this( m.comparator() ); putAll( m ); } /** Creates a new tree map using the elements of two parallel arrays and the given comparator. * * @param k the array of keys of the new tree map. * @param v the array of corresponding values in the new tree map. * @param c a (possibly type-specific) comparator. * @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths. */ public Byte2CharRBTreeMap( final byte[] k, final char v[], final Comparator<? super Byte> c ) { this( c ); if ( k.length != v.length ) throw new IllegalArgumentException( "The key array and the value array have different lengths (" + k.length + " and " + v.length + ")" ); for( int i = 0; i < k.length; i++ ) this.put( k[ i ], v[ i ] ); } /** Creates a new tree map using the elements of two parallel arrays. * * @param k the array of keys of the new tree map. * @param v the array of corresponding values in the new tree map. * @throws IllegalArgumentException if <code>k</code> and <code>v</code> have different lengths. */ public Byte2CharRBTreeMap( final byte[] k, final char v[] ) { this( k, v, null ); } /* * The following methods implements some basic building blocks used by * all accessors. They are (and should be maintained) identical to those used in RBTreeSet.drv. * * The put()/remove() code is derived from Ben Pfaff's GNU libavl * (http://www.msu.edu/~pfaffben/avl/). If you want to understand what's * going on, you should have a look at the literate code contained therein * first. */ /** Compares two keys in the right way. * * <P>This method uses the {@link #actualComparator} if it is non-<code>null</code>. * Otherwise, it resorts to primitive type comparisons or to {@link Comparable#compareTo(Object) compareTo()}. * * @param k1 the first key. * @param k2 the second key. * @return a number smaller than, equal to or greater than 0, as usual * (i.e., when k1 &lt; k2, k1 = k2 or k1 &gt; k2, respectively). */ @SuppressWarnings("unchecked") final int compare( final byte k1, final byte k2 ) { return actualComparator == null ? ( (k1) < (k2) ? -1 : ( (k1) == (k2) ? 0 : 1 ) ) : actualComparator.compare( k1, k2 ); } /** Returns the entry corresponding to the given key, if it is in the tree; <code>null</code>, otherwise. * * @param k the key to search for. * @return the corresponding entry, or <code>null</code> if no entry with the given key exists. */ final Entry findKey( final byte k ) { Entry e = tree; int cmp; while ( e != null && ( cmp = compare( k, e.key ) ) != 0 ) e = cmp < 0 ? e.left() : e.right(); return e; } /** Locates a key. * * @param k a key. * @return the last entry on a search for the given key; this will be * the given key, if it present; otherwise, it will be either the smallest greater key or the greatest smaller key. */ final Entry locateKey( final byte k ) { Entry e = tree, last = tree; int cmp = 0; while ( e != null && ( cmp = compare( k, e.key ) ) != 0 ) { last = e; e = cmp < 0 ? e.left() : e.right(); } return cmp == 0 ? e : last; } /** This vector remembers the path and the direction followed during the * current insertion. It suffices for about 2<sup>32</sup> entries. */ private transient boolean dirPath[]; private transient Entry nodePath[]; @SuppressWarnings("unchecked") private void allocatePaths() { dirPath = new boolean[ 64 ]; nodePath = new Entry[ 64 ]; } /* After execution of this method, modified is true iff a new entry has been inserted. */ public char put( final byte k, final char v ) { modified = false; int maxDepth = 0; if ( tree == null ) { // The case of the empty tree is treated separately. count++; tree = lastEntry = firstEntry = new Entry ( k, v ); } else { Entry p = tree, e; int cmp, i = 0; while( true ) { if ( ( cmp = compare( k, p.key ) ) == 0 ) { final char oldValue = p.value; p.value = v; // We clean up the node path, or we could have stale references later. while( i-- != 0 ) nodePath[ i ] = null; return oldValue; } nodePath[ i ] = p; if ( dirPath[ i++ ] = cmp > 0 ) { if ( p.succ() ) { count++; e = new Entry ( k, v ); if ( p.right == null ) lastEntry = e; e.left = p; e.right = p.right; p.right( e ); break; } p = p.right; } else { if ( p.pred() ) { count++; e = new Entry ( k, v ); if ( p.left == null ) firstEntry = e; e.right = p; e.left = p.left; p.left( e ); break; } p = p.left; } } modified = true; maxDepth = i--; while( i > 0 && ! nodePath[ i ].black() ) { if ( ! dirPath[ i - 1 ] ) { Entry y = nodePath[ i - 1 ].right; if ( ! nodePath[ i - 1 ].succ() && ! y.black() ) { nodePath[ i ].black( true ); y.black( true ); nodePath[ i - 1 ].black( false ); i -= 2; } else { Entry x; if ( ! dirPath[ i ] ) y = nodePath[ i ]; else { x = nodePath[ i ]; y = x.right; x.right = y.left; y.left = x; nodePath[ i - 1 ].left = y; if ( y.pred() ) { y.pred( false ); x.succ( y ); } } x = nodePath[ i - 1 ]; x.black( false ); y.black( true ); x.left = y.right; y.right = x; if ( i < 2 ) tree = y; else { if ( dirPath[ i - 2 ] ) nodePath[ i - 2 ].right = y; else nodePath[ i - 2 ].left = y; } if ( y.succ() ) { y.succ( false ); x.pred( y ); } break; } } else { Entry y = nodePath[ i - 1 ].left; if ( ! nodePath[ i - 1 ].pred() && ! y.black() ) { nodePath[ i ].black( true ); y.black( true ); nodePath[ i - 1 ].black( false ); i -= 2; } else { Entry x; if ( dirPath[ i ] ) y = nodePath[ i ]; else { x = nodePath[ i ]; y = x.left; x.left = y.right; y.right = x; nodePath[ i - 1 ].right = y; if ( y.succ() ) { y.succ( false ); x.pred( y ); } } x = nodePath[ i - 1 ]; x.black( false ); y.black( true ); x.right = y.left; y.left = x; if ( i < 2 ) tree = y; else { if ( dirPath[ i - 2 ] ) nodePath[ i - 2 ].right = y; else nodePath[ i - 2 ].left = y; } if ( y.pred() ){ y.pred( false ); x.succ( y ); } break; } } } } tree.black( true ); // We clean up the node path, or we could have stale references later. while( maxDepth-- != 0 ) nodePath[ maxDepth ] = null; if ( ASSERTS ) { checkNodePath(); checkTree( tree, 0, -1 ); } return defRetValue; } /* After execution of this method, {@link #modified} is true iff an entry has been deleted. */ @SuppressWarnings("unchecked") public char remove( final byte k ) { modified = false; if ( tree == null ) return defRetValue; Entry p = tree; int cmp; int i = 0; final byte kk = k; while( true ) { if ( ( cmp = compare( kk, p.key ) ) == 0 ) break; dirPath[ i ] = cmp > 0; nodePath[ i ] = p; if ( dirPath[ i++ ] ) { if ( ( p = p.right() ) == null ) { // We clean up the node path, or we could have stale references later. while( i-- != 0 ) nodePath[ i ] = null; return defRetValue; } } else { if ( ( p = p.left() ) == null ) { // We clean up the node path, or we could have stale references later. while( i-- != 0 ) nodePath[ i ] = null; return defRetValue; } } } if ( p.left == null ) firstEntry = p.next(); if ( p.right == null ) lastEntry = p.prev(); if ( p.succ() ) { if ( p.pred() ) { if ( i == 0 ) tree = p.left; else { if ( dirPath[ i - 1 ] ) nodePath[ i - 1 ].succ( p.right ); else nodePath[ i - 1 ].pred( p.left ); } } else { p.prev().right = p.right; if ( i == 0 ) tree = p.left; else { if ( dirPath[ i - 1 ] ) nodePath[ i - 1 ].right = p.left; else nodePath[ i - 1 ].left = p.left; } } } else { boolean color; Entry r = p.right; if ( r.pred() ) { r.left = p.left; r.pred( p.pred() ); if ( ! r.pred() ) r.prev().right = r; if ( i == 0 ) tree = r; else { if ( dirPath[ i - 1 ] ) nodePath[ i - 1 ].right = r; else nodePath[ i - 1 ].left = r; } color = r.black(); r.black( p.black() ); p.black( color ); dirPath[ i ] = true; nodePath[ i++ ] = r; } else { Entry s; int j = i++; while( true ) { dirPath[ i ] = false; nodePath[ i++ ] = r; s = r.left; if ( s.pred() ) break; r = s; } dirPath[ j ] = true; nodePath[ j ] = s; if ( s.succ() ) r.pred( s ); else r.left = s.right; s.left = p.left; if ( ! p.pred() ) { p.prev().right = s; s.pred( false ); } s.right( p.right ); color = s.black(); s.black( p.black() ); p.black( color ); if ( j == 0 ) tree = s; else { if ( dirPath[ j - 1 ] ) nodePath[ j - 1 ].right = s; else nodePath[ j - 1 ].left = s; } } } int maxDepth = i; if ( p.black() ) { for( ; i > 0; i-- ) { if ( dirPath[ i - 1 ] && ! nodePath[ i - 1 ].succ() || ! dirPath[ i - 1 ] && ! nodePath[ i - 1 ].pred() ) { Entry x = dirPath[ i - 1 ] ? nodePath[ i - 1 ].right : nodePath[ i - 1 ].left; if ( ! x.black() ) { x.black( true ); break; } } if ( ! dirPath[ i - 1 ] ) { Entry w = nodePath[ i - 1 ].right; if ( ! w.black() ) { w.black( true ); nodePath[ i - 1 ].black( false ); nodePath[ i - 1 ].right = w.left; w.left = nodePath[ i - 1 ]; if ( i < 2 ) tree = w; else { if ( dirPath[ i - 2 ] ) nodePath[ i - 2 ].right = w; else nodePath[ i - 2 ].left = w; } nodePath[ i ] = nodePath[ i - 1 ]; dirPath[ i ] = false; nodePath[ i - 1 ] = w; if ( maxDepth == i++ ) maxDepth++; w = nodePath[ i - 1 ].right; } if ( ( w.pred() || w.left.black() ) && ( w.succ() || w.right.black() ) ) { w.black( false ); } else { if ( w.succ() || w.right.black() ) { Entry y = w.left; y.black ( true ); w.black( false ); w.left = y.right; y.right = w; w = nodePath[ i - 1 ].right = y; if ( w.succ() ) { w.succ( false ); w.right.pred( w ); } } w.black( nodePath[ i - 1 ].black() ); nodePath[ i - 1 ].black( true ); w.right.black( true ); nodePath[ i - 1 ].right = w.left; w.left = nodePath[ i - 1 ]; if ( i < 2 ) tree = w; else { if ( dirPath[ i - 2 ] ) nodePath[ i - 2 ].right = w; else nodePath[ i - 2 ].left = w; } if ( w.pred() ) { w.pred( false ); nodePath[ i - 1 ].succ( w ); } break; } } else { Entry w = nodePath[ i - 1 ].left; if ( ! w.black() ) { w.black ( true ); nodePath[ i - 1 ].black( false ); nodePath[ i - 1 ].left = w.right; w.right = nodePath[ i - 1 ]; if ( i < 2 ) tree = w; else { if ( dirPath[ i - 2 ] ) nodePath[ i - 2 ].right = w; else nodePath[ i - 2 ].left = w; } nodePath[ i ] = nodePath[ i - 1 ]; dirPath[ i ] = true; nodePath[ i - 1 ] = w; if ( maxDepth == i++ ) maxDepth++; w = nodePath[ i - 1 ].left; } if ( ( w.pred() || w.left.black() ) && ( w.succ() || w.right.black() ) ) { w.black( false ); } else { if ( w.pred() || w.left.black() ) { Entry y = w.right; y.black( true ); w.black ( false ); w.right = y.left; y.left = w; w = nodePath[ i - 1 ].left = y; if ( w.pred() ) { w.pred( false ); w.left.succ( w ); } } w.black( nodePath[ i - 1 ].black() ); nodePath[ i - 1 ].black( true ); w.left.black( true ); nodePath[ i - 1 ].left = w.right; w.right = nodePath[ i - 1 ]; if ( i < 2 ) tree = w; else { if ( dirPath[ i - 2 ] ) nodePath[ i - 2 ].right = w; else nodePath[ i - 2 ].left = w; } if ( w.succ() ) { w.succ( false ); nodePath[ i - 1 ].pred( w ); } break; } } } if ( tree != null ) tree.black( true ); } modified = true; count--; // We clean up the node path, or we could have stale references later. while( maxDepth-- != 0 ) nodePath[ maxDepth ] = null; if ( ASSERTS ) { checkNodePath(); checkTree( tree, 0, -1 ); } return p.value; } public Character put( final Byte ok, final Character ov ) { final char oldValue = put( ((ok).byteValue()), ((ov).charValue()) ); return modified ? (null) : (Character.valueOf(oldValue)); } public Character remove( final Object ok ) { final char oldValue = remove( ((((Byte)(ok)).byteValue())) ); return modified ? (Character.valueOf(oldValue)) : (null); } public boolean containsValue( final char v ) { final ValueIterator i = new ValueIterator(); char ev; int j = count; while( j-- != 0 ) { ev = i.nextChar(); if ( ( (ev) == (v) ) ) return true; } return false; } public void clear() { count = 0; tree = null; entries = null; values = null; keys = null; firstEntry = lastEntry = null; } /** This class represent an entry in a tree map. * * <P>We use the only "metadata", i.e., {@link Entry#info}, to store * information about color, predecessor status and successor status. * * <P>Note that since the class is recursive, it can be * considered equivalently a tree. */ private static final class Entry implements Cloneable, Byte2CharMap.Entry { /** The the bit in this mask is true, the node is black. */ private final static int BLACK_MASK = 1; /** If the bit in this mask is true, {@link #right} points to a successor. */ private final static int SUCC_MASK = 1 << 31; /** If the bit in this mask is true, {@link #left} points to a predecessor. */ private final static int PRED_MASK = 1 << 30; /** The key of this entry. */ byte key; /** The value of this entry. */ char value; /** The pointers to the left and right subtrees. */ Entry left, right; /** This integers holds different information in different bits (see {@link #SUCC_MASK} and {@link #PRED_MASK}. */ int info; Entry() {} /** Creates a new entry with the given key and value. * * @param k a key. * @param v a value. */ Entry( final byte k, final char v ) { this.key = k; this.value = v; info = SUCC_MASK | PRED_MASK; } /** Returns the left subtree. * * @return the left subtree (<code>null</code> if the left * subtree is empty). */ Entry left() { return ( info & PRED_MASK ) != 0 ? null : left; } /** Returns the right subtree. * * @return the right subtree (<code>null</code> if the right * subtree is empty). */ Entry right() { return ( info & SUCC_MASK ) != 0 ? null : right; } /** Checks whether the left pointer is really a predecessor. * @return true if the left pointer is a predecessor. */ boolean pred() { return ( info & PRED_MASK ) != 0; } /** Checks whether the right pointer is really a successor. * @return true if the right pointer is a successor. */ boolean succ() { return ( info & SUCC_MASK ) != 0; } /** Sets whether the left pointer is really a predecessor. * @param pred if true then the left pointer will be considered a predecessor. */ void pred( final boolean pred ) { if ( pred ) info |= PRED_MASK; else info &= ~PRED_MASK; } /** Sets whether the right pointer is really a successor. * @param succ if true then the right pointer will be considered a successor. */ void succ( final boolean succ ) { if ( succ ) info |= SUCC_MASK; else info &= ~SUCC_MASK; } /** Sets the left pointer to a predecessor. * @param pred the predecessr. */ void pred( final Entry pred ) { info |= PRED_MASK; left = pred; } /** Sets the right pointer to a successor. * @param succ the successor. */ void succ( final Entry succ ) { info |= SUCC_MASK; right = succ; } /** Sets the left pointer to the given subtree. * @param left the new left subtree. */ void left( final Entry left ) { info &= ~PRED_MASK; this.left = left; } /** Sets the right pointer to the given subtree. * @param right the new right subtree. */ void right( final Entry right ) { info &= ~SUCC_MASK; this.right = right; } /** Returns whether this node is black. * @return true iff this node is black. */ boolean black() { return ( info & BLACK_MASK ) != 0; } /** Sets whether this node is black. * @param black if true, then this node becomes black; otherwise, it becomes red.. */ void black( final boolean black ) { if ( black ) info |= BLACK_MASK; else info &= ~BLACK_MASK; } /** Computes the next entry in the set order. * * @return the next entry (<code>null</code>) if this is the last entry). */ Entry next() { Entry next = this.right; if ( ( info & SUCC_MASK ) == 0 ) while ( ( next.info & PRED_MASK ) == 0 ) next = next.left; return next; } /** Computes the previous entry in the set order. * * @return the previous entry (<code>null</code>) if this is the first entry). */ Entry prev() { Entry prev = this.left; if ( ( info & PRED_MASK ) == 0 ) while ( ( prev.info & SUCC_MASK ) == 0 ) prev = prev.right; return prev; } public Byte getKey() { return (Byte.valueOf(key)); } public byte getByteKey() { return key; } public Character getValue() { return (Character.valueOf(value)); } public char getCharValue() { return value; } public char setValue(final char value) { final char oldValue = this.value; this.value = value; return oldValue; } public Character setValue(final Character value) { return (Character.valueOf(setValue(((value).charValue())))); } @SuppressWarnings("unchecked") public Entry clone() { Entry c; try { c = (Entry )super.clone(); } catch(CloneNotSupportedException cantHappen) { throw new InternalError(); } c.key = key; c.value = value; c.info = info; return c; } @SuppressWarnings("unchecked") public boolean equals( final Object o ) { if (!(o instanceof Map.Entry)) return false; Map.Entry <Byte, Character> e = (Map.Entry <Byte, Character>)o; return ( (key) == (((e.getKey()).byteValue())) ) && ( (value) == (((e.getValue()).charValue())) ); } public int hashCode() { return (key) ^ (value); } public String toString() { return key + "=>" + value; } /* public void prettyPrint() { prettyPrint(0); } public void prettyPrint(int level) { if ( pred() ) { for (int i = 0; i < level; i++) System.err.print(" "); System.err.println("pred: " + left ); } else if (left != null) left.prettyPrint(level +1 ); for (int i = 0; i < level; i++) System.err.print(" "); System.err.println(key + "=" + value + " (" + balance() + ")"); if ( succ() ) { for (int i = 0; i < level; i++) System.err.print(" "); System.err.println("succ: " + right ); } else if (right != null) right.prettyPrint(level + 1); }*/ } /* public void prettyPrint() { System.err.println("size: " + count); if (tree != null) tree.prettyPrint(); }*/ @SuppressWarnings("unchecked") public boolean containsKey( final byte k ) { return findKey( k ) != null; } public int size() { return count; } public boolean isEmpty() { return count == 0; } @SuppressWarnings("unchecked") public char get( final byte k ) { final Entry e = findKey( k ); return e == null ? defRetValue : e.value; } public byte firstByteKey() { if ( tree == null ) throw new NoSuchElementException(); return firstEntry.key; } public byte lastByteKey() { if ( tree == null ) throw new NoSuchElementException(); return lastEntry.key; } /** An abstract iterator on the whole range. * * <P>This class can iterate in both directions on a threaded tree. */ private class TreeIterator { /** The entry that will be returned by the next call to {@link java.util.ListIterator#previous()} (or <code>null</code> if no previous entry exists). */ Entry prev; /** The entry that will be returned by the next call to {@link java.util.ListIterator#next()} (or <code>null</code> if no next entry exists). */ Entry next; /** The last entry that was returned (or <code>null</code> if we did not iterate or used {@link #remove()}). */ Entry curr; /** The current index (in the sense of a {@link java.util.ListIterator}). Note that this value is not meaningful when this {@link TreeIterator} has been created using the nonempty constructor.*/ int index = 0; TreeIterator() { next = firstEntry; } TreeIterator( final byte k ) { if ( ( next = locateKey( k ) ) != null ) { if ( compare( next.key, k ) <= 0 ) { prev = next; next = next.next(); } else prev = next.prev(); } } public boolean hasNext() { return next != null; } public boolean hasPrevious() { return prev != null; } void updateNext() { next = next.next(); } Entry nextEntry() { if ( ! hasNext() ) throw new NoSuchElementException(); curr = prev = next; index++; updateNext(); return curr; } void updatePrevious() { prev = prev.prev(); } Entry previousEntry() { if ( ! hasPrevious() ) throw new NoSuchElementException(); curr = next = prev; index--; updatePrevious(); return curr; } public int nextIndex() { return index; } public int previousIndex() { return index - 1; } public void remove() { if ( curr == null ) throw new IllegalStateException(); /* If the last operation was a next(), we are removing an entry that preceeds the current index, and thus we must decrement it. */ if ( curr == prev ) index--; next = prev = curr; updatePrevious(); updateNext(); Byte2CharRBTreeMap.this.remove( curr.key ); curr = null; } public int skip( final int n ) { int i = n; while( i-- != 0 && hasNext() ) nextEntry(); return n - i - 1; } public int back( final int n ) { int i = n; while( i-- != 0 && hasPrevious() ) previousEntry(); return n - i - 1; } } /** An iterator on the whole range. * * <P>This class can iterate in both directions on a threaded tree. */ private class EntryIterator extends TreeIterator implements ObjectListIterator<Byte2CharMap.Entry > { EntryIterator() {} EntryIterator( final byte k ) { super( k ); } public Byte2CharMap.Entry next() { return nextEntry(); } public Byte2CharMap.Entry previous() { return previousEntry(); } public void set( Byte2CharMap.Entry ok ) { throw new UnsupportedOperationException(); } public void add( Byte2CharMap.Entry ok ) { throw new UnsupportedOperationException(); } } public ObjectSortedSet<Byte2CharMap.Entry > byte2CharEntrySet() { if ( entries == null ) entries = new AbstractObjectSortedSet<Byte2CharMap.Entry >() { final Comparator<? super Byte2CharMap.Entry > comparator = new Comparator<Byte2CharMap.Entry > () { public int compare( final Byte2CharMap.Entry x, Byte2CharMap.Entry y ) { return Byte2CharRBTreeMap.this.storedComparator.compare( x.getKey(), y.getKey() ); } }; public Comparator<? super Byte2CharMap.Entry > comparator() { return comparator; } public ObjectBidirectionalIterator<Byte2CharMap.Entry > iterator() { return new EntryIterator(); } public ObjectBidirectionalIterator<Byte2CharMap.Entry > iterator( final Byte2CharMap.Entry from ) { return new EntryIterator( ((from.getKey()).byteValue()) ); } @SuppressWarnings("unchecked") public boolean contains( final Object o ) { if (!(o instanceof Map.Entry)) return false; final Map.Entry<Byte, Character> e = (Map.Entry<Byte, Character>)o; final Entry f = findKey( ((e.getKey()).byteValue()) ); return e.equals( f ); } @SuppressWarnings("unchecked") public boolean remove( final Object o ) { if (!(o instanceof Map.Entry)) return false; final Map.Entry<Byte, Character> e = (Map.Entry<Byte, Character>)o; final Entry f = findKey( ((e.getKey()).byteValue()) ); if ( f != null ) Byte2CharRBTreeMap.this.remove( f.key ); return f != null; } public int size() { return count; } public void clear() { Byte2CharRBTreeMap.this.clear(); } public Byte2CharMap.Entry first() { return firstEntry; } public Byte2CharMap.Entry last() { return lastEntry; } public ObjectSortedSet<Byte2CharMap.Entry > subSet( Byte2CharMap.Entry from, Byte2CharMap.Entry to ) { return subMap( from.getKey(), to.getKey() ).byte2CharEntrySet(); } public ObjectSortedSet<Byte2CharMap.Entry > headSet( Byte2CharMap.Entry to ) { return headMap( to.getKey() ).byte2CharEntrySet(); } public ObjectSortedSet<Byte2CharMap.Entry > tailSet( Byte2CharMap.Entry from ) { return tailMap( from.getKey() ).byte2CharEntrySet(); } }; return entries; } /** An iterator on the whole range of keys. * * <P>This class can iterate in both directions on the keys of a threaded tree. We * simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods (and possibly * their type-specific counterparts) so that they return keys instead of entries. */ private final class KeyIterator extends TreeIterator implements ByteListIterator { public KeyIterator() {} public KeyIterator( final byte k ) { super( k ); } public byte nextByte() { return nextEntry().key; } public byte previousByte() { return previousEntry().key; } public void set( byte k ) { throw new UnsupportedOperationException(); } public void add( byte k ) { throw new UnsupportedOperationException(); } public Byte next() { return (Byte.valueOf(nextEntry().key)); } public Byte previous() { return (Byte.valueOf(previousEntry().key)); } public void set( Byte ok ) { throw new UnsupportedOperationException(); } public void add( Byte ok ) { throw new UnsupportedOperationException(); } }; /** A keyset implementation using a more direct implementation for iterators. */ private class KeySet extends AbstractByte2CharSortedMap .KeySet { public ByteBidirectionalIterator iterator() { return new KeyIterator(); } public ByteBidirectionalIterator iterator( final byte from ) { return new KeyIterator( from ); } } /** Returns a type-specific sorted set view of the keys contained in this map. * * <P>In addition to the semantics of {@link java.util.Map#keySet()}, you can * safely cast the set returned by this call to a type-specific sorted * set interface. * * @return a type-specific sorted set view of the keys contained in this map. */ public ByteSortedSet keySet() { if ( keys == null ) keys = new KeySet(); return keys; } /** An iterator on the whole range of values. * * <P>This class can iterate in both directions on the values of a threaded tree. We * simply override the {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods (and possibly * their type-specific counterparts) so that they return values instead of entries. */ private final class ValueIterator extends TreeIterator implements CharListIterator { public char nextChar() { return nextEntry().value; } public char previousChar() { return previousEntry().value; } public void set( char v ) { throw new UnsupportedOperationException(); } public void add( char v ) { throw new UnsupportedOperationException(); } public Character next() { return (Character.valueOf(nextEntry().value)); } public Character previous() { return (Character.valueOf(previousEntry().value)); } public void set( Character ok ) { throw new UnsupportedOperationException(); } public void add( Character ok ) { throw new UnsupportedOperationException(); } }; /** Returns a type-specific collection view of the values contained in this map. * * <P>In addition to the semantics of {@link java.util.Map#values()}, you can * safely cast the collection returned by this call to a type-specific collection * interface. * * @return a type-specific collection view of the values contained in this map. */ public CharCollection values() { if ( values == null ) values = new AbstractCharCollection () { public CharIterator iterator() { return new ValueIterator(); } public boolean contains( final char k ) { return containsValue( k ); } public int size() { return count; } public void clear() { Byte2CharRBTreeMap.this.clear(); } }; return values; } public ByteComparator comparator() { return actualComparator; } public Byte2CharSortedMap headMap( byte to ) { return new Submap( ((byte)0), true, to, false ); } public Byte2CharSortedMap tailMap( byte from ) { return new Submap( from, false, ((byte)0), true ); } public Byte2CharSortedMap subMap( byte from, byte to ) { return new Submap( from, false, to, false ); } /** A submap with given range. * * <P>This class represents a submap. One has to specify the left/right * limits (which can be set to -&infin; or &infin;). Since the submap is a * view on the map, at a given moment it could happen that the limits of * the range are not any longer in the main map. Thus, things such as * {@link java.util.SortedMap#firstKey()} or {@link java.util.Collection#size()} must be always computed * on-the-fly. */ private final class Submap extends AbstractByte2CharSortedMap implements java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; /** The start of the submap range, unless {@link #bottom} is true. */ byte from; /** The end of the submap range, unless {@link #top} is true. */ byte to; /** If true, the submap range starts from -&infin;. */ boolean bottom; /** If true, the submap range goes to &infin;. */ boolean top; /** Cached set of entries. */ @SuppressWarnings("hiding") protected transient volatile ObjectSortedSet<Byte2CharMap.Entry > entries; /** Cached set of keys. */ @SuppressWarnings("hiding") protected transient volatile ByteSortedSet keys; /** Cached collection of values. */ @SuppressWarnings("hiding") protected transient volatile CharCollection values; /** Creates a new submap with given key range. * * @param from the start of the submap range. * @param bottom if true, the first parameter is ignored and the range starts from -&infin;. * @param to the end of the submap range. * @param top if true, the third parameter is ignored and the range goes to &infin;. */ public Submap( final byte from, final boolean bottom, final byte to, final boolean top ) { if ( ! bottom && ! top && Byte2CharRBTreeMap.this.compare( from, to ) > 0 ) throw new IllegalArgumentException( "Start key (" + from + ") is larger than end key (" + to + ")" ); this.from = from; this.bottom = bottom; this.to = to; this.top = top; this.defRetValue = Byte2CharRBTreeMap.this.defRetValue; } public void clear() { final SubmapIterator i = new SubmapIterator(); while( i.hasNext() ) { i.nextEntry(); i.remove(); } } /** Checks whether a key is in the submap range. * @param k a key. * @return true if is the key is in the submap range. */ final boolean in( final byte k ) { return ( bottom || Byte2CharRBTreeMap.this.compare( k, from ) >= 0 ) && ( top || Byte2CharRBTreeMap.this.compare( k, to ) < 0 ); } public ObjectSortedSet<Byte2CharMap.Entry > byte2CharEntrySet() { if ( entries == null ) entries = new AbstractObjectSortedSet<Byte2CharMap.Entry >() { public ObjectBidirectionalIterator<Byte2CharMap.Entry > iterator() { return new SubmapEntryIterator(); } public ObjectBidirectionalIterator<Byte2CharMap.Entry > iterator( final Byte2CharMap.Entry from ) { return new SubmapEntryIterator( ((from.getKey()).byteValue()) ); } public Comparator<? super Byte2CharMap.Entry > comparator() { return Byte2CharRBTreeMap.this.byte2CharEntrySet().comparator(); } @SuppressWarnings("unchecked") public boolean contains( final Object o ) { if (!(o instanceof Map.Entry)) return false; final Map.Entry<Byte, Character> e = (Map.Entry<Byte, Character>)o; final Byte2CharRBTreeMap.Entry f = findKey( ((e.getKey()).byteValue()) ); return f != null && in( f.key ) && e.equals( f ); } @SuppressWarnings("unchecked") public boolean remove( final Object o ) { if (!(o instanceof Map.Entry)) return false; final Map.Entry<Byte, Character> e = (Map.Entry<Byte, Character>)o; final Byte2CharRBTreeMap.Entry f = findKey( ((e.getKey()).byteValue()) ); if ( f != null && in( f.key ) ) Submap.this.remove( f.key ); return f != null; } public int size() { int c = 0; for( Iterator<?> i = iterator(); i.hasNext(); i.next() ) c++; return c; } public boolean isEmpty() { return ! new SubmapIterator().hasNext(); } public void clear() { Submap.this.clear(); } public Byte2CharMap.Entry first() { return firstEntry(); } public Byte2CharMap.Entry last() { return lastEntry(); } public ObjectSortedSet<Byte2CharMap.Entry > subSet( Byte2CharMap.Entry from, Byte2CharMap.Entry to ) { return subMap( from.getKey(), to.getKey() ).byte2CharEntrySet(); } public ObjectSortedSet<Byte2CharMap.Entry > headSet( Byte2CharMap.Entry to ) { return headMap( to.getKey() ).byte2CharEntrySet(); } public ObjectSortedSet<Byte2CharMap.Entry > tailSet( Byte2CharMap.Entry from ) { return tailMap( from.getKey() ).byte2CharEntrySet(); } }; return entries; } private class KeySet extends AbstractByte2CharSortedMap .KeySet { public ByteBidirectionalIterator iterator() { return new SubmapKeyIterator(); } public ByteBidirectionalIterator iterator( final byte from ) { return new SubmapKeyIterator( from ); } } public ByteSortedSet keySet() { if ( keys == null ) keys = new KeySet(); return keys; } public CharCollection values() { if ( values == null ) values = new AbstractCharCollection () { public CharIterator iterator() { return new SubmapValueIterator(); } public boolean contains( final char k ) { return containsValue( k ); } public int size() { return Submap.this.size(); } public void clear() { Submap.this.clear(); } }; return values; } @SuppressWarnings("unchecked") public boolean containsKey( final byte k ) { return in( k ) && Byte2CharRBTreeMap.this.containsKey( k ); } public boolean containsValue( final char v ) { final SubmapIterator i = new SubmapIterator(); char ev; while( i.hasNext() ) { ev = i.nextEntry().value; if ( ( (ev) == (v) ) ) return true; } return false; } @SuppressWarnings("unchecked") public char get(final byte k) { final Byte2CharRBTreeMap.Entry e; final byte kk = k; return in( kk ) && ( e = findKey( kk ) ) != null ? e.value : this.defRetValue; } public char put(final byte k, final char v) { modified = false; if ( ! in( k ) ) throw new IllegalArgumentException( "Key (" + k + ") out of range [" + ( bottom ? "-" : String.valueOf( from ) ) + ", " + ( top ? "-" : String.valueOf( to ) ) + ")" ); final char oldValue = Byte2CharRBTreeMap.this.put( k, v ); return modified ? this.defRetValue : oldValue; } public Character put( final Byte ok, final Character ov ) { final char oldValue = put( ((ok).byteValue()), ((ov).charValue()) ); return modified ? (null) : (Character.valueOf(oldValue)); } @SuppressWarnings("unchecked") public char remove( final byte k ) { modified = false; if ( ! in( k ) ) return this.defRetValue; final char oldValue = Byte2CharRBTreeMap.this.remove( k ); return modified ? oldValue : this.defRetValue; } public Character remove( final Object ok ) { final char oldValue = remove( ((((Byte)(ok)).byteValue())) ); return modified ? (Character.valueOf(oldValue)) : (null); } public int size() { final SubmapIterator i = new SubmapIterator(); int n = 0; while( i.hasNext() ) { n++; i.nextEntry(); } return n; } public boolean isEmpty() { return ! new SubmapIterator().hasNext(); } public ByteComparator comparator() { return actualComparator; } public Byte2CharSortedMap headMap( final byte to ) { if ( top ) return new Submap( from, bottom, to, false ); return compare( to, this.to ) < 0 ? new Submap( from, bottom, to, false ) : this; } public Byte2CharSortedMap tailMap( final byte from ) { if ( bottom ) return new Submap( from, false, to, top ); return compare( from, this.from ) > 0 ? new Submap( from, false, to, top ) : this; } public Byte2CharSortedMap subMap( byte from, byte to ) { if ( top && bottom ) return new Submap( from, false, to, false ); if ( ! top ) to = compare( to, this.to ) < 0 ? to : this.to; if ( ! bottom ) from = compare( from, this.from ) > 0 ? from : this.from; if ( ! top && ! bottom && from == this.from && to == this.to ) return this; return new Submap( from, false, to, false ); } /** Locates the first entry. * * @return the first entry of this submap, or <code>null</code> if the submap is empty. */ public Byte2CharRBTreeMap.Entry firstEntry() { if ( tree == null ) return null; // If this submap goes to -infinity, we return the main map first entry; otherwise, we locate the start of the map. Byte2CharRBTreeMap.Entry e; if ( bottom ) e = firstEntry; else { e = locateKey( from ); // If we find either the start or something greater we're OK. if ( compare( e.key, from ) < 0 ) e = e.next(); } // Finally, if this submap doesn't go to infinity, we check that the resulting key isn't greater than the end. if ( e == null || ! top && compare( e.key, to ) >= 0 ) return null; return e; } /** Locates the last entry. * * @return the last entry of this submap, or <code>null</code> if the submap is empty. */ public Byte2CharRBTreeMap.Entry lastEntry() { if ( tree == null ) return null; // If this submap goes to infinity, we return the main map last entry; otherwise, we locate the end of the map. Byte2CharRBTreeMap.Entry e; if ( top ) e = lastEntry; else { e = locateKey( to ); // If we find something smaller than the end we're OK. if ( compare( e.key, to ) >= 0 ) e = e.prev(); } // Finally, if this submap doesn't go to -infinity, we check that the resulting key isn't smaller than the start. if ( e == null || ! bottom && compare( e.key, from ) < 0 ) return null; return e; } public byte firstByteKey() { Byte2CharRBTreeMap.Entry e = firstEntry(); if ( e == null ) throw new NoSuchElementException(); return e.key; } public byte lastByteKey() { Byte2CharRBTreeMap.Entry e = lastEntry(); if ( e == null ) throw new NoSuchElementException(); return e.key; } public Byte firstKey() { Byte2CharRBTreeMap.Entry e = firstEntry(); if ( e == null ) throw new NoSuchElementException(); return e.getKey(); } public Byte lastKey() { Byte2CharRBTreeMap.Entry e = lastEntry(); if ( e == null ) throw new NoSuchElementException(); return e.getKey(); } /** An iterator for subranges. * * <P>This class inherits from {@link TreeIterator}, but overrides the methods that * update the pointer after a {@link java.util.ListIterator#next()} or {@link java.util.ListIterator#previous()}. If we would * move out of the range of the submap we just overwrite the next or previous * entry with <code>null</code>. */ private class SubmapIterator extends TreeIterator { SubmapIterator() { next = firstEntry(); } SubmapIterator( final byte k ) { this(); if ( next != null ) { if ( ! bottom && compare( k, next.key ) < 0 ) prev = null; else if ( ! top && compare( k, ( prev = lastEntry() ).key ) >= 0 ) next = null; else { next = locateKey( k ); if ( compare( next.key, k ) <= 0 ) { prev = next; next = next.next(); } else prev = next.prev(); } } } void updatePrevious() { prev = prev.prev(); if ( ! bottom && prev != null && Byte2CharRBTreeMap.this.compare( prev.key, from ) < 0 ) prev = null; } void updateNext() { next = next.next(); if ( ! top && next != null && Byte2CharRBTreeMap.this.compare( next.key, to ) >= 0 ) next = null; } } private class SubmapEntryIterator extends SubmapIterator implements ObjectListIterator<Byte2CharMap.Entry > { SubmapEntryIterator() {} SubmapEntryIterator( final byte k ) { super( k ); } public Byte2CharMap.Entry next() { return nextEntry(); } public Byte2CharMap.Entry previous() { return previousEntry(); } public void set( Byte2CharMap.Entry ok ) { throw new UnsupportedOperationException(); } public void add( Byte2CharMap.Entry ok ) { throw new UnsupportedOperationException(); } } /** An iterator on a subrange of keys. * * <P>This class can iterate in both directions on a subrange of the * keys of a threaded tree. We simply override the {@link * java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods (and possibly their * type-specific counterparts) so that they return keys instead of * entries. */ private final class SubmapKeyIterator extends SubmapIterator implements ByteListIterator { public SubmapKeyIterator() { super(); } public SubmapKeyIterator( byte from ) { super( from ); } public byte nextByte() { return nextEntry().key; } public byte previousByte() { return previousEntry().key; } public void set( byte k ) { throw new UnsupportedOperationException(); } public void add( byte k ) { throw new UnsupportedOperationException(); } public Byte next() { return (Byte.valueOf(nextEntry().key)); } public Byte previous() { return (Byte.valueOf(previousEntry().key)); } public void set( Byte ok ) { throw new UnsupportedOperationException(); } public void add( Byte ok ) { throw new UnsupportedOperationException(); } }; /** An iterator on a subrange of values. * * <P>This class can iterate in both directions on the values of a * subrange of the keys of a threaded tree. We simply override the * {@link java.util.ListIterator#next()}/{@link java.util.ListIterator#previous()} methods (and possibly their * type-specific counterparts) so that they return values instead of * entries. */ private final class SubmapValueIterator extends SubmapIterator implements CharListIterator { public char nextChar() { return nextEntry().value; } public char previousChar() { return previousEntry().value; } public void set( char v ) { throw new UnsupportedOperationException(); } public void add( char v ) { throw new UnsupportedOperationException(); } public Character next() { return (Character.valueOf(nextEntry().value)); } public Character previous() { return (Character.valueOf(previousEntry().value)); } public void set( Character ok ) { throw new UnsupportedOperationException(); } public void add( Character ok ) { throw new UnsupportedOperationException(); } }; } /** Returns a deep copy of this tree map. * * <P>This method performs a deep copy of this tree map; the data stored in the * set, however, is not cloned. Note that this makes a difference only for object keys. * * @return a deep copy of this tree map. */ @SuppressWarnings("unchecked") public Byte2CharRBTreeMap clone() { Byte2CharRBTreeMap c; try { c = (Byte2CharRBTreeMap )super.clone(); } catch(CloneNotSupportedException cantHappen) { throw new InternalError(); } c.keys = null; c.values = null; c.entries = null; c.allocatePaths(); if ( count != 0 ) { // Also this apparently unfathomable code is derived from GNU libavl. Entry e, p, q, rp = new Entry (), rq = new Entry (); p = rp; rp.left( tree ); q = rq; rq.pred( null ); while( true ) { if ( ! p.pred() ) { e = p.left.clone(); e.pred( q.left ); e.succ( q ); q.left( e ); p = p.left; q = q.left; } else { while( p.succ() ) { p = p.right; if ( p == null ) { q.right = null; c.tree = rq.left; c.firstEntry = c.tree; while( c.firstEntry.left != null ) c.firstEntry = c.firstEntry.left; c.lastEntry = c.tree; while( c.lastEntry.right != null ) c.lastEntry = c.lastEntry.right; return c; } q = q.right; } p = p.right; q = q.right; } if ( ! p.succ() ) { e = p.right.clone(); e.succ( q.right ); e.pred( q ); q.right( e ); } } } return c; } private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { int n = count; EntryIterator i = new EntryIterator(); Entry e; s.defaultWriteObject(); while(n-- != 0) { e = i.nextEntry(); s.writeByte( e.key ); s.writeChar( e.value ); } } /** Reads the given number of entries from the input stream, returning the corresponding tree. * * @param s the input stream. * @param n the (positive) number of entries to read. * @param pred the entry containing the key that preceeds the first key in the tree. * @param succ the entry containing the key that follows the last key in the tree. */ @SuppressWarnings("unchecked") private Entry readTree( final java.io.ObjectInputStream s, final int n, final Entry pred, final Entry succ ) throws java.io.IOException, ClassNotFoundException { if ( n == 1 ) { final Entry top = new Entry ( s.readByte(), s.readChar() ); top.pred( pred ); top.succ( succ ); top.black( true ); return top; } if ( n == 2 ) { /* We handle separately this case so that recursion will *always* be on nonempty subtrees. */ final Entry top = new Entry ( s.readByte(), s.readChar() ); top.black( true ); top.right( new Entry ( s.readByte(), s.readChar() ) ); top.right.pred( top ); top.pred( pred ); top.right.succ( succ ); return top; } // The right subtree is the largest one. final int rightN = n / 2, leftN = n - rightN - 1; final Entry top = new Entry (); top.left( readTree( s, leftN, pred, top ) ); top.key = s.readByte(); top.value = s.readChar(); top.black( true ); top.right( readTree( s, rightN, top, succ ) ); if ( n + 2 == ( ( n + 2 ) & -( n + 2 ) ) ) top.right.black( false ); // Quick test for determining whether n + 2 is a power of 2. return top; } private void readObject( java.io.ObjectInputStream s ) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); /* The storedComparator is now correctly set, but we must restore on-the-fly the actualComparator. */ setActualComparator(); allocatePaths(); if ( count != 0 ) { tree = readTree( s, count, null, null ); Entry e; e = tree; while( e.left() != null ) e = e.left(); firstEntry = e; e = tree; while( e.right() != null ) e = e.right(); lastEntry = e; } if ( ASSERTS ) checkTree( tree, 0, -1 ); } private void checkNodePath() {} @SuppressWarnings("unused") private int checkTree( Entry e, int d, int D ) { return 0; } }
{ "content_hash": "05efab5e9ee70fc5fb9d01a6fff4e6a4", "timestamp": "", "source": "github", "line_count": 1731, "max_line_length": 196, "avg_line_length": 31.21894858463316, "alnum_prop": 0.6203737971872687, "repo_name": "karussell/fastutil", "id": "fc0be64e518019eb839d481ffabe15744ce6b8a5", "size": "54040", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/it/unimi/dsi/fastutil/bytes/Byte2CharRBTreeMap.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "554418" }, { "name": "Shell", "bytes": "23387" } ], "symlink_target": "" }
module Admin module ContactLists class CsvView def initialize(contact_list) @contact_list = contact_list end def coordinator_name coordinator.name end def coordinator_email coordinator.email end def contacts contact_list.customers.map { |customer| Admin::ContactLists::ContactView.new(customer) } end def filename contact_list.filename end private attr_reader :contact_list def territorial_authority contact_list.territorial_authority end def coordinator territorial_authority.coordinator end end end end
{ "content_hash": "3c86dec5d987285d30b893f5e9b823fc", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 96, "avg_line_length": 17.842105263157894, "alnum_prop": 0.6238938053097345, "repo_name": "hdfelix/bfnz", "id": "6ab5b0812413af8d245310101bf910a2ca36a038", "size": "678", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/view_models/admin/contact_lists/csv_view.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "355338" }, { "name": "CoffeeScript", "bytes": "1663" }, { "name": "HTML", "bytes": "95855" }, { "name": "JavaScript", "bytes": "6497" }, { "name": "Ruby", "bytes": "127278" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="#FFFFFFFF" android:layout_height="100dp"> </LinearLayout>
{ "content_hash": "cf4f9fd11d03da1d31ac1f6e5cb2359d", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 72, "avg_line_length": 39.125, "alnum_prop": 0.6325878594249201, "repo_name": "AlphaBetaPeter/android-lockscreenview", "id": "b9a91a99a5548a16bfbc395924a97622a34d0b7d", "size": "313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/lock_screen_view.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "997" }, { "name": "Java", "bytes": "5696" } ], "symlink_target": "" }
import Vue from 'vue'; import vuetifyIcons from 'vuetify/lib/components/Vuetify/mixins/icons'; import CollapseAllIcon from '../views/icons/CollapseAllIcon'; import IndicatorIcon from '../views/icons/IndicatorIcon'; import LightBulbIcon from '../views/icons/LightBulbIcon'; import ViewOnlyIcon from '../views/icons/ViewOnlyIcon'; import Icon from 'shared/views/Icon'; import { ContentKindsNames } from 'shared/leUtils/ContentKinds'; Vue.component(Icon.name, Icon); const EMPTY = '_empty'; export const CONTENT_KIND_ICONS = { [ContentKindsNames.TOPIC]: 'folder', [ContentKindsNames.TOPIC + EMPTY]: 'folder_open', [ContentKindsNames.VIDEO]: 'ondemand_video', [ContentKindsNames.AUDIO]: 'music_note', [ContentKindsNames.SLIDESHOW]: 'image', [ContentKindsNames.EXERCISE]: 'assignment', [ContentKindsNames.DOCUMENT]: 'class', [ContentKindsNames.HTML5]: 'widgets', }; export function getContentKindIcon(kind, isEmpty = false) { const icon = (isEmpty ? [kind + EMPTY] : []).concat([kind]).find(k => k in CONTENT_KIND_ICONS); return icon ? CONTENT_KIND_ICONS[icon] : 'error_outline'; } // Can use $vuetify.icons.iconName in <Icon> tags const customIcons = { collapse_all: { component: CollapseAllIcon, props: { iconName: 'collapse_all', }, }, light_bulb: { component: LightBulbIcon, props: { iconsName: 'light_bulb', }, }, view_only: { component: ViewOnlyIcon, props: { iconName: 'view_only', }, }, indicator: { component: IndicatorIcon, props: { iconName: 'indicator', }, }, }; export default function icons(additional = {}) { // Grab icon name mapping from Vuetify. `md` is default icon font set const iconMap = vuetifyIcons('md', additional); // Update icons to use our custom `Icon` component which adds a layer between implementation // within Vuetify and our code, and the underlying `VIcon` component let vuetifyUpdatedIcons = Object.entries(iconMap) .map(([name, mdName]) => { return { [name]: { component: Icon.name, props: { iconName: mdName, }, }, }; }) .reduce((icons, icon) => Object.assign(icons, icon), {}); return { ...vuetifyUpdatedIcons, ...customIcons, }; }
{ "content_hash": "1414f5c48d536843494685f777ec5a24", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 97, "avg_line_length": 28.936708860759495, "alnum_prop": 0.6587926509186351, "repo_name": "DXCanas/content-curation", "id": "b069c4a8effa5ab324490c800f27d49fdeb07e37", "size": "2286", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "contentcuration/contentcuration/frontend/shared/vuetify/icons.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "173955" }, { "name": "Dockerfile", "bytes": "2215" }, { "name": "HTML", "bytes": "503467" }, { "name": "JavaScript", "bytes": "601189" }, { "name": "Makefile", "bytes": "3409" }, { "name": "Python", "bytes": "813881" }, { "name": "Shell", "bytes": "6970" }, { "name": "Smarty", "bytes": "6584" }, { "name": "Vue", "bytes": "21539" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>multiplier: 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.14.0 / multiplier - 8.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> multiplier <small> 8.5.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-06-03 05:49:13 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-03 05:49:13 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.14.0 Formal proof management system dune 3.2.0 Fast, portable, and opinionated build system ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matej.kosik@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/multiplier&quot; license: &quot;LGPL 2&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Multiplier&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;keyword:hardware verification&quot; &quot;keyword:circuit&quot; &quot;category:Computer Science/Architecture&quot; &quot;category:Miscellaneous/Extracted Programs/Hardware&quot; ] authors: [ &quot;Christine Paulin &lt;&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/multiplier/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/multiplier.git&quot; synopsis: &quot;Proof of a multiplier circuit&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/multiplier/archive/v8.5.0.tar.gz&quot; checksum: &quot;md5=5dff8fca270a7aaf1752a9fa26efbb30&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-multiplier.8.5.0 coq.8.14.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.0). The following dependencies couldn&#39;t be met: - coq-multiplier -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) 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-multiplier.8.5.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": "87689787815051d440cf247cf50d801e", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 193, "avg_line_length": 42.9079754601227, "alnum_prop": 0.5384615384615384, "repo_name": "coq-bench/coq-bench.github.io", "id": "6da5a16585554d0059254dfb77fe815c9a29f044", "size": "7019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.14.0/multiplier/8.5.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package main import ( "context" "flag" "fmt" "go/build" "io/ioutil" "os" "path/filepath" "github.com/google/gapid/core/app" "github.com/google/gapid/core/app/flags" "github.com/google/gapid/core/log" "github.com/google/gapid/core/os/file" "github.com/google/gapid/gapil" "github.com/google/gapid/gapil/template" ) var ( dir string tracer string deps string cmake string gopath string globalList flags.Strings searchPath file.PathList ) func init() { verb := &app.Verb{ Name: "template", ShortHelp: "Passes the ast to a template for code generation", } verb.Flags.Raw.Var(&globalList, "G", "A global value setting for the template") verb.Flags.Raw.Var(&searchPath, "search", "The set of paths to search for includes") verb.Flags.Raw.StringVar(&dir, "dir", cwd(), "The output directory") verb.Flags.Raw.StringVar(&tracer, "t", "", "The template function trace expression") verb.Flags.Raw.StringVar(&deps, "deps", "", "The dependancies file to generate") verb.Flags.Raw.StringVar(&cmake, "cmake", "", "The cmake dependancies file to generate") verb.Flags.Raw.StringVar(&gopath, "gopath", "", "the go path to use when looking up packages") verb.Run = doTemplate app.AddVerb(verb) } func doTemplate(ctx context.Context, flags flag.FlagSet) error { args := flags.Args() if len(args) < 1 { app.Usage(ctx, "Missing api file") return nil } apiName := args[0] if len(args) < 2 { app.Usage(ctx, "Missing template file") return nil } if gopath != "" { build.Default.GOPATH = filepath.FromSlash(gopath) } mainTemplate := args[1] log.I(ctx, "Reading %v", apiName) processor := gapil.NewProcessor() if len(searchPath) > 0 { processor.Loader = gapil.NewSearchLoader(searchPath) } compiled, errs := processor.Resolve(apiName) for path := range processor.Parsed { template.InputDep(path) } if err := gapil.CheckErrors(apiName, errs, maxErrors); err != nil { return err } options := template.Options{ Dir: dir, APIFile: apiName, Loader: ioutil.ReadFile, Globals: globalList.Strings(), Tracer: tracer, } f, err := template.NewFunctions(ctx, compiled, processor.Mappings, options) if err != nil { return err } if err := f.Include(mainTemplate); err != nil { return fmt.Errorf("%s: %s\n", mainTemplate, err) } writeDeps(ctx) writeCMake(ctx) return nil } func cwd() string { p, _ := os.Getwd() return p } func writeDeps(ctx context.Context) error { if len(deps) == 0 { return nil } log.I(ctx, "Writing deps %v", deps) file, err := os.Create(deps) if err != nil { return err } defer file.Close() template.WriteDeps(ctx, file) return file.Close() } func writeCMake(ctx context.Context) error { if len(cmake) == 0 { return nil } log.I(ctx, "Writing cmake %v", cmake) file, err := os.Create(cmake) if err != nil { return err } defer file.Close() template.WriteCMake(ctx, file) return file.Close() }
{ "content_hash": "ec535bd8761cebaa04b377d29ba0addf", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 95, "avg_line_length": 23.88617886178862, "alnum_prop": 0.6773315180394827, "repo_name": "ianthehat/gapid", "id": "b39056ff7ccf2899a4da80d01a0efd4e6214e4e4", "size": "3532", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cmd/apic/template.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "763" }, { "name": "C", "bytes": "223243" }, { "name": "C++", "bytes": "1081024" }, { "name": "CMake", "bytes": "390556" }, { "name": "GLSL", "bytes": "22280" }, { "name": "Go", "bytes": "4280527" }, { "name": "HTML", "bytes": "99377" }, { "name": "Java", "bytes": "1106214" }, { "name": "JavaScript", "bytes": "13177" }, { "name": "Objective-C++", "bytes": "11819" }, { "name": "Protocol Buffer", "bytes": "104558" }, { "name": "Shell", "bytes": "4910" } ], "symlink_target": "" }
<div #arrayAlbumContent > <div *ngIf="currentUser" class="row username">Welcome, {{fullName}}.</div> <div class="list-group"> <button *ngFor="let album of arrayAlbums" class="list-group-item d-flex justify-content-start" (click)="getSelectedAlbumContent(album)"> <div class="thumb" *ngIf="album.thumbPhoto" [style.background-image]="'url(' + album.thumbPhoto.src_big + ')'"></div> <div class="p-2 album_info"> <p class="album_title">{{album.title}}</p> <p><i class="fa fa-folder-open" aria-hidden="true"></i>{{album.size}} files</p> <p><i class="fa fa-clock-o" aria-hidden="true"></i>{{ (album.updated | amFromUnix) | amTimeAgo}}</p> </div> <i class="fa fa-angle-double-right ml-auto fa-3x hidden-xs-down" aria-hidden="true"></i> </button> </div> </div> <list-photo #listPhotoContent (backwardFromAlbum)="onBackwardFromAlbumContent($event)"></list-photo> <alert [errorMessage]="alertMessage"></alert>
{ "content_hash": "dabb9538d8d18b240de9d5aed0297adb", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 140, "avg_line_length": 61.1875, "alnum_prop": 0.6435137895812053, "repo_name": "zm1994/gallery", "id": "dc48c085aa59ab7358b1cbd7bf1a50bbd0cdecc0", "size": "979", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/album/list_albums.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6041" }, { "name": "HTML", "bytes": "12038" }, { "name": "JavaScript", "bytes": "52945" }, { "name": "TypeScript", "bytes": "52753" } ], "symlink_target": "" }
import copy import numbers TNAME = 0 TVALUE = 1 TLIST = 2 TSEQ = 3 COPY_NS = -99 def _seq(self, seq=None, inc=1): # decide on a starting point (result) if seq: result = str(seq) else: result = str(self.NS[0]) self.NS[0] += inc # now account for duplicates ext = 2 if _seq_find_dup(self.ancestor, result): try_result = result+" ("+str(ext)+")" while _seq_find_dup(self.ancestor, try_result) and ext<100000: ext += 1 try_result = result+" ("+str(ext)+")" result = try_result return result def _seq_find_dup(data, seq): for item in data: if item[TSEQ]==seq: return True if item[TLIST]: if _seq_find_dup(item[TLIST], seq): return True return False def mards(self, detail=False): # this is NOT, of course, a _real_ MARDS representation. # for example, it is possible for a 'rolne' name to be a string with spaces. # but that is not possible in MARDS. Here, we simply put quotes around the name. # Plus, MARDS only does strings. A rolne can do anything. # Here, we add a equals sign to non-None scenarios. return _mards(self.data, detail) def _mards(data, detail): result = u"" # return repr(self.data) if data: for entry in data: if detail==True: result += u"[{}] ".format(unicode(entry[TSEQ])) result += poss_quotes(entry[TNAME]) if entry[TVALUE] is None: result += u" is None" else: result += u" = "+poss_quotes(entry[TVALUE]) result += u"\n" if entry[TLIST]: temp = _mards(entry[TLIST], detail) for line in temp.split(u"\n"): if line: result += u" "+line result += u"\n" else: result = u"%empty\n" return result def poss_quotes(value): printable = unicode(value) quote_flag = False if len(printable)==0: quote_flag = True if '"' in printable: quote_flag = True if ' ' in printable: quote_flag = True if '=' in printable: quote_flag = True if len(printable) != len(printable.strip()): quote_flag = True if quote_flag: return u'"'+printable+u'"' return printable def _extend(self, sublist, prefix, retain_seq): new_list = [] for entry in sublist: (en, ev, el, es) = entry if retain_seq: seq = _seq(self, seq=prefix+es) else: seq = prefix+_seq(self) sub_list = _extend(self, el, prefix, retain_seq) tup = (en, ev, sub_list, seq) new_list.append(tup) return new_list def _flattened_list(self, data, args, name, value, index, seq, grep=False): arg_count = len(args) result = [] ctr = {} for entry in data: # the counter function if (entry[TNAME], entry[TVALUE]) in ctr: ctr[(entry[TNAME], entry[TVALUE])] += 1 else: ctr[(entry[TNAME], entry[TVALUE])] = 0 # make the tuple items = [] if name: items.append(entry[TNAME]) if value: items.append(entry[TVALUE]) if index: items.append(ctr[(entry[TNAME], entry[TVALUE])]) if seq: items.append(entry[TSEQ]) tup = tuple(items) # insert as dictated by args given append_flag = False if arg_count==0: result.append(tup) append_flag = True if arg_count==1: if entry[TNAME]==args[0]: result.append(tup) append_flag = True if arg_count==2: if entry[TNAME]==args[0] and entry[TVALUE]==args[1]: result.append(tup) append_flag = True if arg_count==3: if entry[TNAME]==args[0] and entry[TVALUE]==args[1]: if ctr[(entry[TNAME], entry[TVALUE])]==args[2]: result.append(tup) append_flag = True if entry[TLIST]: # notice that the 'args' parameter does not get passed on recursion. That # is because the search only happen at layer one. (unless 'grep'=True) if grep: result.extend(_flattened_list(self, entry[TLIST], args, name, value, index, seq, grep=True) ) else: if append_flag: result.extend(_flattened_list(self, entry[TLIST], (), name, value, index, seq) ) return result def _serialize(self, data, name_prefix, value_prefix, index_prefix, explicit, path=None): result = [] ctr = {} if path is None: path = name_prefix else: path += name_prefix for entry in data: # the counter function if (entry[TNAME], entry[TVALUE]) in ctr: ctr[(entry[TNAME], entry[TVALUE])] += 1 else: ctr[(entry[TNAME], entry[TVALUE])] = 0 # make the tuple idx = ctr[(entry[TNAME], entry[TVALUE])] if explicit: full_path = path+unicode(entry[TNAME]) if entry[TVALUE] is None: full_path += value_prefix else: full_path += value_prefix+unicode(entry[TVALUE]) full_path += index_prefix+str(idx) else: full_path = path+unicode(entry[TNAME]) if idx>0 or entry[TVALUE] is not None: full_path += value_prefix+unicode(entry[TVALUE]) if idx>0: full_path += index_prefix+str(idx) sub = [] if entry[TLIST]: # notice that the 'args' parameter does not get passed on recursion. That # is because the search only happen at layer one. sub = _serialize(self, entry[TLIST], name_prefix, value_prefix, index_prefix, explicit, path=full_path) tup = (full_path, entry[TVALUE], [], entry[TSEQ]) result.append(tup) result.extend(sub) return result def _serialize_names(self, data, name_prefix, value_prefix, index_prefix, explicit, path=None): result = [] ctr = {} if path is None: path = name_prefix else: path += name_prefix for entry in data: # the counter function if entry[TNAME] in ctr: ctr[entry[TNAME]] += 1 else: ctr[entry[TNAME]] = 0 # make the tuple idx = ctr[entry[TNAME]] if explicit: full_path = path+unicode(entry[TNAME]) full_path += index_prefix+str(idx) else: full_path = path+unicode(entry[TNAME]) if idx>0: full_path += index_prefix+str(idx) sub = [] if entry[TLIST]: # notice that the 'args' parameter does not get passed on recursion. That # is because the search only happen at layer one. sub = _serialize_names(self, entry[TLIST], name_prefix, value_prefix, index_prefix, explicit, path=full_path) tup = (full_path, entry[TVALUE], [], entry[TSEQ]) result.append(tup) result.extend(sub) return result def _deserialize_names(self, data, name_prefix, value_prefix, index_prefix, level=0): result = [] next_ptr = result while data: entry = data[0] chunks = entry[TNAME].split(name_prefix) if chunks: if not chunks[0]: del chunks[0] # the first entry is always/often empty if chunks: if len(chunks)==(level+1): parts = chunks[-1].split(index_prefix) if len(parts)==0: continue elif len(parts)==1: name = parts[0] index = 0 else: name = parts[0] index = parts[1] result.append((name, entry[TVALUE], entry[TLIST], entry[TSEQ])) del data[0] elif len(chunks)==(level+2): (en, ev, el, es) = result[-1] el += _deserialize_names(self, data, name_prefix, value_prefix, index_prefix, level+1) result[-1] = (en, ev, el, es) elif len(chunks)>(level+2): raise ValueError("deserialize indexing jumped ahead by more than one level: "+repr(entry)) del data[0] else: return result return result def _flatten(data, args): arg_count = len(args) result = [] ctr = {} for entry in data: # the counter function if (entry[TNAME], entry[TVALUE]) in ctr: ctr[(entry[TNAME], entry[TVALUE])] += 1 else: ctr[(entry[TNAME], entry[TVALUE])] = 0 # make the tuple idx = ctr[(entry[TNAME], entry[TVALUE])] sub = [] if entry[TLIST]: # notice that the 'args' parameter does not get passed on recursion. That # is because the search only happen at layer one. sub = _flatten(entry[TLIST], args) # insert as dictated by args given append_flag = False if arg_count==0: append_flag = True if arg_count==1: if entry[TNAME]==args[0]: append_flag = True if arg_count==2: if entry[TNAME]==args[0] and entry[TVALUE]==args[1]: append_flag = True if arg_count==3: if entry[TNAME]==args[0] and entry[TVALUE]==args[1]: if ctr[(entry[TNAME], entry[TVALUE])]==args[2]: append_flag = True if append_flag: tup = (entry[TNAME], entry[TVALUE], [], entry[TSEQ]) result.append(tup) result.extend(sub) return result def _renumber(self, data, increment, prefix, suffix): result = [] for entry in data: seq = str(self.NS[0]) if prefix: seq = prefix+seq if suffix: seq = seq+suffix self.NS[0] += increment # now account for duplicates if self.ref_seq is not None: #am i a child (not the root)? ext = 2 if _seq_find_dup(self.ancestor, seq): try_result = seq+" ("+str(ext)+")" while _seq_find_dup(self.ancestor, try_result) and ext<100000: ext += 1 try_result = seq+" ("+str(ext)+")" seq = try_result if entry[TLIST]: sub = _renumber(self, entry[TLIST], increment, prefix, suffix) else: sub = [] tup = (entry[TNAME], entry[TVALUE], sub, seq) result.append(tup) return result def _dump(self, data): result = [] for entry in data: tup = (entry[TNAME], entry[TVALUE], _dump(self, entry[TLIST])) result.append(tup) return result # an internal routine to get self or an element based on flexible args # returns (name, value, index, seq, list) def ref_super_tuple(self, *args): arglen = len(args) (name, value, index) = (None, None, 0) if arglen>0: name = args[0] if arglen>1: value = args[1] if arglen>2: index = args[2] ctr = 0 if arglen==0: super_tup = super_tuple_search_seq(self.ref_seq, self.ancestor) return super_tup else: for entry in self.data: (en, ev, el, es) = entry if en==name: if arglen==1: return (en, ev, ctr, es, el) elif ev==value: if ctr==index: return (en, ev, ctr, es, el) ctr += 1 return (None, None, None, None, None) def super_tuple_search_seq(seq, data): ctr = 0 for entry in data: (en, ev, el, es) = entry if es==seq: target_name = en target_value = ev for (tn, tv, _, ts) in data: if target_name==tn and target_value==tv: if ts==seq: break ctr += 1 return (en, ev, ctr, es, el) if el: result = super_tuple_search_seq(seq, el) if result: return result return None # an internal routine to get data index based on flexible args # -1 = self # None = not found # else returns index number def _ref_index(self, *args): arglen = len(args) (name, value, index) = (None, None, 0) if arglen>0: name = args[0] if arglen>1: value = args[1] if arglen>2: index = args[2] ctr = 0 if arglen==0: return -1 else: for i, entry in enumerate(self.data): (en, ev, el, es) = entry if en==name: if arglen==1 or ev==value: if ctr==index: return i ctr += 1 return None # this routine creates a 'temporary' rolne that points to the # 'top-level' rolne list. # Any changes to self.ref_seq, ref_name, or ref_value are bogus # and are lost when the rolne is garbage collected. But changes # to children in TLIST survive. # TODO: delete this function; I strongly suspect that it is an unneeded later def _point_ancestry(self): return rolne(in_tuple=(None, None, self.ancestor, None)) def ptr_to_seq(self, seq): # this is an interesting one: return a reference to # the direct tuple with this sequence. Use with care. (target_list, target_index) = list_ref_to_seq(self.ancestor, seq) if target_list is None: return None return target_list[target_index] def _seq_lineage(data, seq): for index, entry in enumerate(data): (en, ev, el, es) = entry if es==seq: return [es] if el: result = _seq_lineage(el, seq) if result: return [es]+result return [] def list_ref_to_seq(orig_data, seq): # this one REALLY jumps down the rabbit hole. # # returns a tuple containing the original list containing the # sequence and the index pointing to the entry that # has the sequence. # # (list, index) # # this is useful for for routines that, in turn, modify # an entry. One cannot "change" a tuple. So a pointer # to a tuple has no value. This combo allows true change # because lists are mutable. # return _list_ref_to_seq(orig_data, seq) def _list_ref_to_seq(data, seq): result = (None, None) for index, entry in enumerate(data): (en, ev, el, es) = entry if es==seq: return (data, index) if el: result = _list_ref_to_seq(el, seq) if result[0] is not None: return result return (None, None) def _copy_sublist_with_new_seq(self, source, prefix): dest = [] for (ev, en, el, es) in source: new_seq = prefix+_seq(self) # called before next to make seq look logical new_list = _copy_sublist_with_new_seq(self, el, prefix) new_tup = (copy.copy(ev), copy.copy(en), new_list, new_seq) dest.append(new_tup) return dest def _copy(self, seq_prefix, seq_suffix, data, renumber): global COPY_NS new_list = [] for (ev, en, el, es) in data: if renumber: mid = str(COPY_NS) else: mid = es COPY_NS += 1 sub = _copy(self, seq_prefix, seq_suffix, el, renumber) new_list.append((copy.copy(ev), copy.copy(en), sub, seq_prefix+mid+seq_suffix)) return new_list def dump_list(self, args, name=False, value=False, index=False, seq=False): if not isinstance(args, tuple): args = tuple([args]) arg_count = len(args) result = [] ctr = {} for entry in self.data: # the counter function if (entry[TNAME], entry[TVALUE]) in ctr: ctr[(entry[TNAME], entry[TVALUE])] += 1 else: ctr[(entry[TNAME], entry[TVALUE])] = 0 # make the tuple items = [] if name: items.append(entry[TNAME]) if value: items.append(entry[TVALUE]) if index: items.append(ctr[(entry[TNAME], entry[TVALUE])]) if seq: items.append(entry[TSEQ]) tup = tuple(items) # insert as dictated by args given if arg_count==0: result.append(tup) if arg_count==1: if entry[TNAME]==args[0]: result.append(tup) if arg_count==2: if entry[TNAME]==args[0] and entry[TVALUE]==args[1]: result.append(tup) if arg_count==3: if entry[TNAME]==args[0] and entry[TVALUE]==args[1]: if ctr[(entry[TNAME], entry[TVALUE])]==args[2]: result.append(tup) return result # the 'key_list' is very flexible: # exist_pull(item, "name") # exist_pull(item, ("name", "val")) # exist_pull(item, ["name1", "name2"]) # exist_pull(item, [("name", "val"), ("name2", "val2")]) def exist_and_pull(tup, root_index, key_list): if isinstance(key_list, list): pass else: key_list = [key_list] ptr = [tup] for level, key in enumerate(key_list): en = ev = None ei = 0 if isinstance(key, list) or isinstance(key, tuple): cl = len(key) if cl>0: en = key[0] if cl>1: ev = key[1] if cl>2: ei = key[2] if cl>3: cl=3 if cl==1 and en is None: cl=0 # (None) and [] and [None] is the same as None: match everything else: en = key cl = 1 if key is None: cl=0 # None means match everything. It is the same thing as () and [] ctr = 0 for i, item in enumerate(ptr): if cl==0: value = item[TVALUE] break elif cl==1: if en==item[TNAME]: value = item[TVALUE] break elif cl==2: if en==item[TNAME] and ev==item[TVALUE]: value = item[TVALUE] break elif cl==3: if en==item[TNAME] and ev==item[TVALUE]: if level==0: if ei==root_index: value = item[TVALUE] break else: if ei==ctr: value = item[TVALUE] break ctr += 1 else: return False, None ptr = ptr[i][TLIST] return True, value
{ "content_hash": "2b62d0fc9f474f0c3553f6704e19abfd", "timestamp": "", "source": "github", "line_count": 569, "max_line_length": 121, "avg_line_length": 33.09666080843585, "alnum_prop": 0.5153462192013594, "repo_name": "MakerReduxCorp/rolne", "id": "392a21e95bbf8a20fe23340aaf8fc67066dd8a60", "size": "18891", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rolne/support_library.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "78638" }, { "name": "Shell", "bytes": "6483" } ], "symlink_target": "" }
// Copyright (c) 2008-2022, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using Hazelcast.Configuration; using Hazelcast.Core; using Hazelcast.Partitioning.Strategies; using Hazelcast.Serialization.Compact; using Microsoft.Extensions.Logging; namespace Hazelcast.Serialization { internal sealed class SerializationServiceBuilder { private const int DefaultOutBufferSize = 4 * 1024; private readonly SerializationOptions _options; private readonly SerializerHooks _hooks = new SerializerHooks(); private readonly List<ISerializerDefinitions> _definitions = new List<ISerializerDefinitions>(); private readonly ILoggerFactory _loggerFactory; private int _initialOutputBufferSize = DefaultOutBufferSize; private Endianness _endianness; private bool _validatePortableClassDefinitions; private int _portableVersion; private readonly IDictionary<int, IDataSerializableFactory> _dataSerializableFactories = new Dictionary<int, IDataSerializableFactory>(); private readonly IDictionary<int, IPortableFactory> _portableFactories = new Dictionary<int, IPortableFactory>(); private ICollection<IClassDefinition> _portableClassDefinitions = new HashSet<IClassDefinition>(); private IPartitioningStrategy _partitioningStrategy; private ISchemas _compactSchemas; public SerializationServiceBuilder(ILoggerFactory loggerFactory) : this(new SerializationOptions(), loggerFactory) { } public SerializationServiceBuilder(SerializationOptions options, ILoggerFactory loggerFactory) { _options = options ?? throw new ArgumentNullException(nameof(options)); _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); if (options.PortableVersion < 0) throw new ConfigurationException("PortableVersion must be >= 0."); _portableVersion = options.PortableVersion; _validatePortableClassDefinitions = options.ValidateClassDefinitions; _endianness = options.Endianness; } public SerializationServiceBuilder AddHook<T>() => AddHook(typeof (T)); public SerializationServiceBuilder AddHook(Type type) { _hooks.Add(type); return this; } public SerializationServiceBuilder AddDefinitions(ISerializerDefinitions definition) { _definitions.Add(definition); return this; } public SerializationServiceBuilder SetPortableVersion(int version) { if (version < 0) throw new ArgumentOutOfRangeException(nameof(version), "Value must be greater than, or equal to, zero."); _portableVersion = version; return this; } public SerializationServiceBuilder AddDataSerializableFactory(int id, IDataSerializableFactory factory) { _dataSerializableFactories.Add(id, factory); return this; } public SerializationServiceBuilder AddPortableFactory(int id, IPortableFactory factory) { _portableFactories.Add(id, factory); return this; } public SerializationServiceBuilder AddClassDefinition(IClassDefinition cd) { _portableClassDefinitions.Add(cd); return this; } public SerializationServiceBuilder SetValidatePortableClassDefinitions(bool validatePortableClassDefinitions) { _validatePortableClassDefinitions = validatePortableClassDefinitions; return this; } public SerializationServiceBuilder SetEndianness(Endianness endianness) { _endianness = endianness; return this; } public SerializationServiceBuilder SetPartitioningStrategy(IPartitioningStrategy partitionStrategy) { _partitioningStrategy = partitionStrategy; return this; } public SerializationServiceBuilder SetInitialOutputBufferSize(int initialOutputBufferSize) { if (initialOutputBufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(initialOutputBufferSize), "Value must be greater than zero."); } _initialOutputBufferSize = initialOutputBufferSize; return this; } public SerializationServiceBuilder SetCompactSchemas(ISchemas schemas) { _compactSchemas = schemas; return this; } public SerializationService Build() { // merge lists AddDataSerializableFactoriesFromOptions(_dataSerializableFactories, _options); AddPortableFactoriesFromOptions(_portableFactories, _options); _portableClassDefinitions = _portableClassDefinitions.Union(_options.ClassDefinitions).ToList(); var service = new SerializationService( _options, _endianness, _portableVersion, _dataSerializableFactories, _portableFactories, _portableClassDefinitions, _hooks, _definitions, _validatePortableClassDefinitions, _partitioningStrategy, _initialOutputBufferSize, _compactSchemas, _loggerFactory); return service; } private static void AddDataSerializableFactoriesFromOptions(IDictionary<int, IDataSerializableFactory> dataSerializableFactories, SerializationOptions options) { foreach (var factoryOptions in options.DataSerializableFactories) { if (factoryOptions.Id <= 0) throw new ArgumentException("IDataSerializableFactory factoryId must be positive."); if (dataSerializableFactories.ContainsKey(factoryOptions.Id)) throw new InvalidOperationException($"IDataSerializableFactory with factoryId {factoryOptions.Id} is already registered."); dataSerializableFactories.Add(factoryOptions.Id, factoryOptions.Service); } } private static void AddPortableFactoriesFromOptions(IDictionary<int, IPortableFactory> portableFactories, SerializationOptions options) { foreach (var factoryOptions in options.PortableFactories) { if (factoryOptions.Id <= 0) throw new ArgumentException("IPortableFactory factoryId must be positive."); if (portableFactories.ContainsKey(factoryOptions.Id)) throw new InvalidOperationException($"IPortableFactory with factoryId {factoryOptions.Id} is already registered."); portableFactories.Add(factoryOptions.Id, factoryOptions.Service); } } } }
{ "content_hash": "f84795b36b817fd5f556a3499e7092ad", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 167, "avg_line_length": 39.80104712041885, "alnum_prop": 0.6690344646145752, "repo_name": "asimarslan/hazelcast-csharp-client", "id": "aeb4e848e8976c169a47749575510089710d2fea", "size": "7604", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Hazelcast.Net/Serialization/SerializationServiceBuilder.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "7109601" }, { "name": "PowerShell", "bytes": "115235" }, { "name": "Shell", "bytes": "484" } ], "symlink_target": "" }
package module import ( "github.com/watermint/toolbox/essentials/go/go_module" "github.com/watermint/toolbox/essentials/log/esl" "github.com/watermint/toolbox/infra/control/app_control" "github.com/watermint/toolbox/infra/recipe/rc_exec" "github.com/watermint/toolbox/infra/recipe/rc_recipe" ) type List struct { rc_recipe.RemarkSecret } func (z *List) Preset() { } func (z *List) Exec(c app_control.Control) error { b, err := go_module.ScanBuild() if err != nil { return err } l := c.Log() l.Info("Go Version", esl.String("version", b.GoVersion())) for _, m := range b.Modules() { lic, err := go_module.SelectLicenses(m, []go_module.LicenseType{ go_module.LicenseTypeApache20, go_module.LicenseTypeBSD2Clause, go_module.LicenseTypeBSD3Clause, go_module.LicenseTypeMIT, }, []go_module.LicenseType{ go_module.LicenseTypeAGPL, go_module.LicenseTypeGPL, go_module.LicenseTypeLGPL, }, ) if err != nil { l.Error("No license", esl.String("Path", m.Path()), esl.String("Version", m.Version())) continue } l.Info("Module", esl.String("Path", m.Path()), esl.String("Version", m.Version()), esl.String("License", string(lic.Type()))) } return nil } func (z *List) Test(c app_control.Control) error { return rc_exec.Exec(c, &List{}, rc_recipe.NoCustomValues) }
{ "content_hash": "fc7ebf7e14dc3ab9d51228cfd2c98007", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 127, "avg_line_length": 26.058823529411764, "alnum_prop": 0.6832204665161776, "repo_name": "watermint/toolbox", "id": "cc9b38566a38a4fc6bedddf9d9e007c679f9d79a", "size": "1329", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "recipe/dev/module/list.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "215" }, { "name": "Go", "bytes": "3090492" }, { "name": "HTML", "bytes": "14475" }, { "name": "Shell", "bytes": "1731" } ], "symlink_target": "" }
import os import six from twisted.trial import unittest from twisted.protocols.policies import WrappingFactory from twisted.python.filepath import FilePath from twisted.internet import reactor, defer, error from twisted.web import server, static, util, resource from twisted.web.test.test_webclient import ForeverTakingResource, \ NoLengthResource, HostHeaderResource, \ PayloadResource, BrokenDownloadResource from twisted.cred import portal, checkers, credentials from w3lib.url import path_to_file_uri from scrapy import twisted_version from scrapy.core.downloader.handlers import DownloadHandlers from scrapy.core.downloader.handlers.file import FileDownloadHandler from scrapy.core.downloader.handlers.http import HTTPDownloadHandler, HttpDownloadHandler from scrapy.core.downloader.handlers.http10 import HTTP10DownloadHandler from scrapy.core.downloader.handlers.http11 import HTTP11DownloadHandler from scrapy.core.downloader.handlers.s3 import S3DownloadHandler from scrapy.spiders import Spider from scrapy.http import Request from scrapy.settings import Settings from scrapy.utils.test import get_crawler from scrapy.utils.python import to_bytes from scrapy.exceptions import NotConfigured from tests.mockserver import MockServer, ssl_context_factory from tests.spiders import SingleRequestSpider class DummyDH(object): def __init__(self, crawler): pass class OffDH(object): def __init__(self, crawler): raise NotConfigured class LoadTestCase(unittest.TestCase): def test_enabled_handler(self): handlers = {'scheme': 'tests.test_downloader_handlers.DummyDH'} crawler = get_crawler(settings_dict={'DOWNLOAD_HANDLERS': handlers}) dh = DownloadHandlers(crawler) self.assertIn('scheme', dh._schemes) for scheme in handlers: # force load handlers dh._get_handler(scheme) self.assertIn('scheme', dh._handlers) self.assertNotIn('scheme', dh._notconfigured) def test_not_configured_handler(self): handlers = {'scheme': 'tests.test_downloader_handlers.OffDH'} crawler = get_crawler(settings_dict={'DOWNLOAD_HANDLERS': handlers}) dh = DownloadHandlers(crawler) self.assertIn('scheme', dh._schemes) for scheme in handlers: # force load handlers dh._get_handler(scheme) self.assertNotIn('scheme', dh._handlers) self.assertIn('scheme', dh._notconfigured) def test_disabled_handler(self): handlers = {'scheme': None} crawler = get_crawler(settings_dict={'DOWNLOAD_HANDLERS': handlers}) dh = DownloadHandlers(crawler) self.assertNotIn('scheme', dh._schemes) for scheme in handlers: # force load handlers dh._get_handler(scheme) self.assertNotIn('scheme', dh._handlers) self.assertIn('scheme', dh._notconfigured) class FileTestCase(unittest.TestCase): def setUp(self): self.tmpname = self.mktemp() fd = open(self.tmpname + '^', 'w') fd.write('0123456789') fd.close() self.download_request = FileDownloadHandler(Settings()).download_request def test_download(self): def _test(response): self.assertEquals(response.url, request.url) self.assertEquals(response.status, 200) self.assertEquals(response.body, b'0123456789') request = Request(path_to_file_uri(self.tmpname + '^')) assert request.url.upper().endswith('%5E') return self.download_request(request, Spider('foo')).addCallback(_test) def test_non_existent(self): request = Request('file://%s' % self.mktemp()) d = self.download_request(request, Spider('foo')) return self.assertFailure(d, IOError) class HttpTestCase(unittest.TestCase): scheme = 'http' download_handler_cls = HTTPDownloadHandler def setUp(self): name = self.mktemp() os.mkdir(name) FilePath(name).child("file").setContent(b"0123456789") r = static.File(name) r.putChild(b"redirect", util.Redirect(b"/file")) r.putChild(b"wait", ForeverTakingResource()) r.putChild(b"hang-after-headers", ForeverTakingResource(write=True)) r.putChild(b"nolength", NoLengthResource()) r.putChild(b"host", HostHeaderResource()) r.putChild(b"payload", PayloadResource()) r.putChild(b"broken", BrokenDownloadResource()) self.site = server.Site(r, timeout=None) self.wrapper = WrappingFactory(self.site) self.host = 'localhost' if self.scheme == 'https': self.port = reactor.listenSSL( 0, self.wrapper, ssl_context_factory(), interface=self.host) else: self.port = reactor.listenTCP(0, self.wrapper, interface=self.host) self.portno = self.port.getHost().port self.download_handler = self.download_handler_cls(Settings()) self.download_request = self.download_handler.download_request @defer.inlineCallbacks def tearDown(self): yield self.port.stopListening() if hasattr(self.download_handler, 'close'): yield self.download_handler.close() def getURL(self, path): return "%s://%s:%d/%s" % (self.scheme, self.host, self.portno, path) def test_download(self): request = Request(self.getURL('file')) d = self.download_request(request, Spider('foo')) d.addCallback(lambda r: r.body) d.addCallback(self.assertEquals, b"0123456789") return d def test_download_head(self): request = Request(self.getURL('file'), method='HEAD') d = self.download_request(request, Spider('foo')) d.addCallback(lambda r: r.body) d.addCallback(self.assertEquals, b'') return d def test_redirect_status(self): request = Request(self.getURL('redirect')) d = self.download_request(request, Spider('foo')) d.addCallback(lambda r: r.status) d.addCallback(self.assertEquals, 302) return d def test_redirect_status_head(self): request = Request(self.getURL('redirect'), method='HEAD') d = self.download_request(request, Spider('foo')) d.addCallback(lambda r: r.status) d.addCallback(self.assertEquals, 302) return d @defer.inlineCallbacks def test_timeout_download_from_spider(self): if self.scheme == 'https': raise unittest.SkipTest( 'test_timeout_download_from_spider skipped under https') spider = Spider('foo') meta = {'download_timeout': 0.2} # client connects but no data is received request = Request(self.getURL('wait'), meta=meta) d = self.download_request(request, spider) yield self.assertFailure(d, defer.TimeoutError, error.TimeoutError) # client connects, server send headers and some body bytes but hangs request = Request(self.getURL('hang-after-headers'), meta=meta) d = self.download_request(request, spider) yield self.assertFailure(d, defer.TimeoutError, error.TimeoutError) def test_host_header_not_in_request_headers(self): def _test(response): self.assertEquals( response.body, to_bytes('%s:%d' % (self.host, self.portno))) self.assertEquals(request.headers, {}) request = Request(self.getURL('host')) return self.download_request(request, Spider('foo')).addCallback(_test) def test_host_header_seted_in_request_headers(self): def _test(response): self.assertEquals(response.body, b'example.com') self.assertEquals(request.headers.get('Host'), b'example.com') request = Request(self.getURL('host'), headers={'Host': 'example.com'}) return self.download_request(request, Spider('foo')).addCallback(_test) d = self.download_request(request, Spider('foo')) d.addCallback(lambda r: r.body) d.addCallback(self.assertEquals, b'example.com') return d def test_payload(self): body = b'1'*100 # PayloadResource requires body length to be 100 request = Request(self.getURL('payload'), method='POST', body=body) d = self.download_request(request, Spider('foo')) d.addCallback(lambda r: r.body) d.addCallback(self.assertEquals, body) return d class DeprecatedHttpTestCase(HttpTestCase): """HTTP 1.0 test case""" download_handler_cls = HttpDownloadHandler class Http10TestCase(HttpTestCase): """HTTP 1.0 test case""" download_handler_cls = HTTP10DownloadHandler class Https10TestCase(Http10TestCase): scheme = 'https' class Http11TestCase(HttpTestCase): """HTTP 1.1 test case""" download_handler_cls = HTTP11DownloadHandler if twisted_version < (11, 1, 0): skip = 'HTTP1.1 not supported in twisted < 11.1.0' def test_download_without_maxsize_limit(self): request = Request(self.getURL('file')) d = self.download_request(request, Spider('foo')) d.addCallback(lambda r: r.body) d.addCallback(self.assertEquals, b"0123456789") return d @defer.inlineCallbacks def test_download_with_maxsize(self): request = Request(self.getURL('file')) # 10 is minimal size for this request and the limit is only counted on # response body. (regardless of headers) d = self.download_request(request, Spider('foo', download_maxsize=10)) d.addCallback(lambda r: r.body) d.addCallback(self.assertEquals, b"0123456789") yield d d = self.download_request(request, Spider('foo', download_maxsize=9)) yield self.assertFailure(d, defer.CancelledError, error.ConnectionAborted) @defer.inlineCallbacks def test_download_with_maxsize_per_req(self): meta = {'download_maxsize': 2} request = Request(self.getURL('file'), meta=meta) d = self.download_request(request, Spider('foo')) yield self.assertFailure(d, defer.CancelledError, error.ConnectionAborted) @defer.inlineCallbacks def test_download_with_small_maxsize_per_spider(self): request = Request(self.getURL('file')) d = self.download_request(request, Spider('foo', download_maxsize=2)) yield self.assertFailure(d, defer.CancelledError, error.ConnectionAborted) def test_download_with_large_maxsize_per_spider(self): request = Request(self.getURL('file')) d = self.download_request(request, Spider('foo', download_maxsize=100)) d.addCallback(lambda r: r.body) d.addCallback(self.assertEquals, b"0123456789") return d class Https11TestCase(Http11TestCase): scheme = 'https' class Http11MockServerTestCase(unittest.TestCase): """HTTP 1.1 test case with MockServer""" if twisted_version < (11, 1, 0): skip = 'HTTP1.1 not supported in twisted < 11.1.0' def setUp(self): self.mockserver = MockServer() self.mockserver.__enter__() def tearDown(self): self.mockserver.__exit__(None, None, None) @defer.inlineCallbacks def test_download_with_content_length(self): crawler = get_crawler(SingleRequestSpider) # http://localhost:8998/partial set Content-Length to 1024, use download_maxsize= 1000 to avoid # download it yield crawler.crawl(seed=Request(url='http://localhost:8998/partial', meta={'download_maxsize': 1000})) failure = crawler.spider.meta['failure'] self.assertIsInstance(failure.value, defer.CancelledError) @defer.inlineCallbacks def test_download(self): crawler = get_crawler(SingleRequestSpider) yield crawler.crawl(seed=Request(url='http://localhost:8998')) failure = crawler.spider.meta.get('failure') self.assertTrue(failure == None) reason = crawler.spider.meta['close_reason'] self.assertTrue(reason, 'finished') @defer.inlineCallbacks def test_download_gzip_response(self): if twisted_version > (12, 3, 0): crawler = get_crawler(SingleRequestSpider) body = b'1'*100 # PayloadResource requires body length to be 100 request = Request('http://localhost:8998/payload', method='POST', body=body, meta={'download_maxsize': 50}) yield crawler.crawl(seed=request) failure = crawler.spider.meta['failure'] # download_maxsize < 100, hence the CancelledError self.assertIsInstance(failure.value, defer.CancelledError) if six.PY2: request.headers.setdefault(b'Accept-Encoding', b'gzip,deflate') request = request.replace(url='http://localhost:8998/xpayload') yield crawler.crawl(seed=request) # download_maxsize = 50 is enough for the gzipped response failure = crawler.spider.meta.get('failure') self.assertTrue(failure == None) reason = crawler.spider.meta['close_reason'] self.assertTrue(reason, 'finished') else: # See issue https://twistedmatrix.com/trac/ticket/8175 raise unittest.SkipTest("xpayload only enabled for PY2") else: raise unittest.SkipTest("xpayload and payload endpoint only enabled for twisted > 12.3.0") class UriResource(resource.Resource): """Return the full uri that was requested""" def getChild(self, path, request): return self def render(self, request): return request.uri class HttpProxyTestCase(unittest.TestCase): download_handler_cls = HTTPDownloadHandler def setUp(self): site = server.Site(UriResource(), timeout=None) wrapper = WrappingFactory(site) self.port = reactor.listenTCP(0, wrapper, interface='127.0.0.1') self.portno = self.port.getHost().port self.download_handler = self.download_handler_cls(Settings()) self.download_request = self.download_handler.download_request @defer.inlineCallbacks def tearDown(self): yield self.port.stopListening() if hasattr(self.download_handler, 'close'): yield self.download_handler.close() def getURL(self, path): return "http://127.0.0.1:%d/%s" % (self.portno, path) def test_download_with_proxy(self): def _test(response): self.assertEquals(response.status, 200) self.assertEquals(response.url, request.url) self.assertEquals(response.body, b'http://example.com') http_proxy = self.getURL('') request = Request('http://example.com', meta={'proxy': http_proxy}) return self.download_request(request, Spider('foo')).addCallback(_test) def test_download_with_proxy_https_noconnect(self): def _test(response): self.assertEquals(response.status, 200) self.assertEquals(response.url, request.url) self.assertEquals(response.body, b'https://example.com') http_proxy = '%s?noconnect' % self.getURL('') request = Request('https://example.com', meta={'proxy': http_proxy}) return self.download_request(request, Spider('foo')).addCallback(_test) def test_download_without_proxy(self): def _test(response): self.assertEquals(response.status, 200) self.assertEquals(response.url, request.url) self.assertEquals(response.body, b'/path/to/resource') request = Request(self.getURL('path/to/resource')) return self.download_request(request, Spider('foo')).addCallback(_test) class DeprecatedHttpProxyTestCase(unittest.TestCase): """Old deprecated reference to http10 downloader handler""" download_handler_cls = HttpDownloadHandler class Http10ProxyTestCase(HttpProxyTestCase): download_handler_cls = HTTP10DownloadHandler class Http11ProxyTestCase(HttpProxyTestCase): download_handler_cls = HTTP11DownloadHandler if twisted_version < (11, 1, 0): skip = 'HTTP1.1 not supported in twisted < 11.1.0' @defer.inlineCallbacks def test_download_with_proxy_https_timeout(self): """ Test TunnelingTCP4ClientEndpoint """ http_proxy = self.getURL('') domain = 'https://no-such-domain.nosuch' request = Request( domain, meta={'proxy': http_proxy, 'download_timeout': 0.2}) d = self.download_request(request, Spider('foo')) timeout = yield self.assertFailure(d, error.TimeoutError) self.assertIn(domain, timeout.osError) class HttpDownloadHandlerMock(object): def __init__(self, settings): pass def download_request(self, request, spider): return request class S3AnonTestCase(unittest.TestCase): try: import boto except ImportError: skip = 'missing boto library' if six.PY3: skip = 'S3 not supported on Py3' def setUp(self): self.s3reqh = S3DownloadHandler(Settings(), httpdownloadhandler=HttpDownloadHandlerMock, #anon=True, # is implicit ) self.download_request = self.s3reqh.download_request self.spider = Spider('foo') def test_anon_request(self): req = Request('s3://aws-publicdatasets/') httpreq = self.download_request(req, self.spider) self.assertEqual(hasattr(self.s3reqh.conn, 'anon'), True) self.assertEqual(self.s3reqh.conn.anon, True) class S3TestCase(unittest.TestCase): download_handler_cls = S3DownloadHandler try: import boto except ImportError: skip = 'missing boto library' if six.PY3: skip = 'S3 not supported on Py3' # test use same example keys than amazon developer guide # http://s3.amazonaws.com/awsdocs/S3/20060301/s3-dg-20060301.pdf # and the tests described here are the examples from that manual AWS_ACCESS_KEY_ID = '0PN5J17HBGZHT7JJ3X82' AWS_SECRET_ACCESS_KEY = 'uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o' def setUp(self): s3reqh = S3DownloadHandler(Settings(), self.AWS_ACCESS_KEY_ID, self.AWS_SECRET_ACCESS_KEY, httpdownloadhandler=HttpDownloadHandlerMock) self.download_request = s3reqh.download_request self.spider = Spider('foo') def test_request_signing1(self): # gets an object from the johnsmith bucket. req = Request('s3://johnsmith/photos/puppy.jpg', headers={'Date': 'Tue, 27 Mar 2007 19:36:42 +0000'}) httpreq = self.download_request(req, self.spider) self.assertEqual(httpreq.headers['Authorization'], \ 'AWS 0PN5J17HBGZHT7JJ3X82:xXjDGYUmKxnwqr5KXNPGldn5LbA=') def test_request_signing2(self): # puts an object into the johnsmith bucket. req = Request('s3://johnsmith/photos/puppy.jpg', method='PUT', headers={ 'Content-Type': 'image/jpeg', 'Date': 'Tue, 27 Mar 2007 21:15:45 +0000', 'Content-Length': '94328', }) httpreq = self.download_request(req, self.spider) self.assertEqual(httpreq.headers['Authorization'], \ 'AWS 0PN5J17HBGZHT7JJ3X82:hcicpDDvL9SsO6AkvxqmIWkmOuQ=') def test_request_signing3(self): # lists the content of the johnsmith bucket. req = Request('s3://johnsmith/?prefix=photos&max-keys=50&marker=puppy', \ method='GET', headers={ 'User-Agent': 'Mozilla/5.0', 'Date': 'Tue, 27 Mar 2007 19:42:41 +0000', }) httpreq = self.download_request(req, self.spider) self.assertEqual(httpreq.headers['Authorization'], \ 'AWS 0PN5J17HBGZHT7JJ3X82:jsRt/rhG+Vtp88HrYL706QhE4w4=') def test_request_signing4(self): # fetches the access control policy sub-resource for the 'johnsmith' bucket. req = Request('s3://johnsmith/?acl', \ method='GET', headers={'Date': 'Tue, 27 Mar 2007 19:44:46 +0000'}) httpreq = self.download_request(req, self.spider) self.assertEqual(httpreq.headers['Authorization'], \ 'AWS 0PN5J17HBGZHT7JJ3X82:thdUi9VAkzhkniLj96JIrOPGi0g=') def test_request_signing5(self): # deletes an object from the 'johnsmith' bucket using the # path-style and Date alternative. req = Request('s3://johnsmith/photos/puppy.jpg', \ method='DELETE', headers={ 'Date': 'Tue, 27 Mar 2007 21:20:27 +0000', 'x-amz-date': 'Tue, 27 Mar 2007 21:20:26 +0000', }) httpreq = self.download_request(req, self.spider) self.assertEqual(httpreq.headers['Authorization'], \ 'AWS 0PN5J17HBGZHT7JJ3X82:k3nL7gH3+PadhTEVn5Ip83xlYzk=') def test_request_signing6(self): # uploads an object to a CNAME style virtual hosted bucket with metadata. req = Request('s3://static.johnsmith.net:8080/db-backup.dat.gz', \ method='PUT', headers={ 'User-Agent': 'curl/7.15.5', 'Host': 'static.johnsmith.net:8080', 'Date': 'Tue, 27 Mar 2007 21:06:08 +0000', 'x-amz-acl': 'public-read', 'content-type': 'application/x-download', 'Content-MD5': '4gJE4saaMU4BqNR0kLY+lw==', 'X-Amz-Meta-ReviewedBy': 'joe@johnsmith.net,jane@johnsmith.net', 'X-Amz-Meta-FileChecksum': '0x02661779', 'X-Amz-Meta-ChecksumAlgorithm': 'crc32', 'Content-Disposition': 'attachment; filename=database.dat', 'Content-Encoding': 'gzip', 'Content-Length': '5913339', }) httpreq = self.download_request(req, self.spider) self.assertEqual(httpreq.headers['Authorization'], \ 'AWS 0PN5J17HBGZHT7JJ3X82:C0FlOtU8Ylb9KDTpZqYkZPX91iI=') def test_request_signing7(self): # ensure that spaces are quoted properly before signing req = Request( ("s3://johnsmith/photos/my puppy.jpg" "?response-content-disposition=my puppy.jpg"), method='GET', headers={ 'Date': 'Tue, 27 Mar 2007 19:42:41 +0000', }) httpreq = self.download_request(req, self.spider) self.assertEqual( httpreq.headers['Authorization'], 'AWS 0PN5J17HBGZHT7JJ3X82:+CfvG8EZ3YccOrRVMXNaK2eKZmM=') class FTPTestCase(unittest.TestCase): username = "scrapy" password = "passwd" if twisted_version < (10, 2, 0): skip = "Twisted pre 10.2.0 doesn't allow to set home path other than /home" if six.PY3: skip = "Twisted missing ftp support for PY3" def setUp(self): from twisted.protocols.ftp import FTPRealm, FTPFactory from scrapy.core.downloader.handlers.ftp import FTPDownloadHandler # setup dirs and test file self.directory = self.mktemp() os.mkdir(self.directory) userdir = os.path.join(self.directory, self.username) os.mkdir(userdir) fp = FilePath(userdir) fp.child('file.txt').setContent("I have the power!") fp.child('file with spaces.txt').setContent("Moooooooooo power!") # setup server realm = FTPRealm(anonymousRoot=self.directory, userHome=self.directory) p = portal.Portal(realm) users_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() users_checker.addUser(self.username, self.password) p.registerChecker(users_checker, credentials.IUsernamePassword) self.factory = FTPFactory(portal=p) self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1") self.portNum = self.port.getHost().port self.download_handler = FTPDownloadHandler(Settings()) self.addCleanup(self.port.stopListening) def _add_test_callbacks(self, deferred, callback=None, errback=None): def _clean(data): self.download_handler.client.transport.loseConnection() return data deferred.addCallback(_clean) if callback: deferred.addCallback(callback) if errback: deferred.addErrback(errback) return deferred def test_ftp_download_success(self): request = Request(url="ftp://127.0.0.1:%s/file.txt" % self.portNum, meta={"ftp_user": self.username, "ftp_password": self.password}) d = self.download_handler.download_request(request, None) def _test(r): self.assertEqual(r.status, 200) self.assertEqual(r.body, 'I have the power!') self.assertEqual(r.headers, {'Local Filename': [''], 'Size': ['17']}) return self._add_test_callbacks(d, _test) def test_ftp_download_path_with_spaces(self): request = Request( url="ftp://127.0.0.1:%s/file with spaces.txt" % self.portNum, meta={"ftp_user": self.username, "ftp_password": self.password} ) d = self.download_handler.download_request(request, None) def _test(r): self.assertEqual(r.status, 200) self.assertEqual(r.body, 'Moooooooooo power!') self.assertEqual(r.headers, {'Local Filename': [''], 'Size': ['18']}) return self._add_test_callbacks(d, _test) def test_ftp_download_notexist(self): request = Request(url="ftp://127.0.0.1:%s/notexist.txt" % self.portNum, meta={"ftp_user": self.username, "ftp_password": self.password}) d = self.download_handler.download_request(request, None) def _test(r): self.assertEqual(r.status, 404) return self._add_test_callbacks(d, _test) def test_ftp_local_filename(self): local_fname = "/tmp/file.txt" request = Request(url="ftp://127.0.0.1:%s/file.txt" % self.portNum, meta={"ftp_user": self.username, "ftp_password": self.password, "ftp_local_filename": local_fname}) d = self.download_handler.download_request(request, None) def _test(r): self.assertEqual(r.body, local_fname) self.assertEqual(r.headers, {'Local Filename': ['/tmp/file.txt'], 'Size': ['17']}) self.assertTrue(os.path.exists(local_fname)) with open(local_fname) as f: self.assertEqual(f.read(), "I have the power!") os.remove(local_fname) return self._add_test_callbacks(d, _test) def test_invalid_credentials(self): from twisted.protocols.ftp import ConnectionLost request = Request(url="ftp://127.0.0.1:%s/file.txt" % self.portNum, meta={"ftp_user": self.username, "ftp_password": 'invalid'}) d = self.download_handler.download_request(request, None) def _test(r): self.assertEqual(r.type, ConnectionLost) return self._add_test_callbacks(d, errback=_test)
{ "content_hash": "ebf4baa99238b20588799545e2d25671", "timestamp": "", "source": "github", "line_count": 670, "max_line_length": 119, "avg_line_length": 40.38955223880597, "alnum_prop": 0.6403680573519086, "repo_name": "rklabs/scrapy", "id": "56608bfc670211aa052bcfe1a5d24db2c253ecf5", "size": "27061", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/test_downloader_handlers.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Groff", "bytes": "2008" }, { "name": "HTML", "bytes": "1809" }, { "name": "Python", "bytes": "1335036" }, { "name": "Shell", "bytes": "258" } ], "symlink_target": "" }
#include "pch.h" #include "TomKitten30.xaml.h" using namespace PrintableTomKitten; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 TomKitten30::TomKitten30() { InitializeComponent(); }
{ "content_hash": "bc37b10e742c0a27411466944ac8b582", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 96, "avg_line_length": 29.91304347826087, "alnum_prop": 0.751453488372093, "repo_name": "nnaabbcc/exercise", "id": "f1c32645e168f06df0e2a154cf2df83fd0b7389a", "size": "765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "windows/pw6e.official/CPlusPlus/Chapter17/PrintableTomKitten/PrintableTomKitten/TomKitten30.xaml.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "6872" }, { "name": "C", "bytes": "1764627" }, { "name": "C#", "bytes": "1976292" }, { "name": "C++", "bytes": "2643235" }, { "name": "CMake", "bytes": "6371" }, { "name": "CSS", "bytes": "5461" }, { "name": "Cuda", "bytes": "400" }, { "name": "HTML", "bytes": "683692" }, { "name": "Java", "bytes": "863101" }, { "name": "JavaScript", "bytes": "65541" }, { "name": "Makefile", "bytes": "650457" }, { "name": "PHP", "bytes": "1501" }, { "name": "Python", "bytes": "61596" }, { "name": "Shell", "bytes": "2340" }, { "name": "Vim script", "bytes": "220" }, { "name": "Visual Basic .NET", "bytes": "257344" }, { "name": "XSLT", "bytes": "2038" } ], "symlink_target": "" }
.. _track-types: =========== Track Types =========== Linking value scales ==================== The scaling of values in quantitative tracks is done from lowest to highest values. Two tracks displaying different data will likely have different axis scales based on the extent of the data visible in each. To enable comparison between the two tracks, HiGlass supports locking value scales such that they both display the same axes. This can be done using the track configuration menu: .. image:: img/lock-value-scales.png :align: center Bed-like ================= .. image:: img/bedlike-track-thumb.png :align: right track-type: ``bedlike`` datatype: ``bedlike`` The bedlike track is intended to display generic interval data. It is used to render tracks with a `bedlike` datatype. This usually comes from the `beddb` filetype. Regular bed-like files can be converted to beddb using the instructions in the `data preparation section <data_preparation.html#bed-files>`__. This track has two modes: stranded and unstranded (value-based). In stranded mode, which is activated when the underlying data has information about which strand entries are on, items on the + and - strand are drawn above each other. Overlapping items are further stacked. In unstranded (value-based) mode, items can be be ordered vertically or colored based on the values of a column (chosen in the config -> "Value column" section). **Color Encoding:** Intervals can visually encode information using the following three ``options``: - **colorEncoding**: int, null or "itemRgb" If set to a bed column number (1-based), use the values in that column to color the annotations. If set to `itemRgb`, then check if the underlying BED file has a 9th column and use the r,g,b value there to color the annotations. (default: "itemRgb") - **colorRange**: array of color values A list of colors that make up the continuous color map. Defaults to the same colormap used by the heatmap track. - **colorEncodingRange**: [Number, Number] A tuple defining the minimum and maximum range value for color encoding. Defaults to the min and max values. - **fillColor:** Fill color if annotations aren't stranded (default "blue") - **fillOpacity:** The opacity of the annotations. - **fontColor:** The color of the label text's font - **fontSize:** The font size for annotation labels (default 10) - **maxAnnotationHeight:** int or null The maximum annotation height when using 'scaled' annotation heights. Useful to avoid huge annotations. (default 'none') - **maxTexts** Limit the maximum number of texts that can be shown (default: 50) - **minusStrandColor** For stranded mode, the color of the minus strand entries. Ignored if ``colorEncoding`` is set. (default "purple") - **plusStrandColor** For stranded mode, the color of the plus strand entries. Ignored if ``colorEncoding`` is set. (default "blue") - **separatePlusMinusStrands** Draw + and - strand annotations at different y values if true. Draw them at the same vertical position if false. (default: true). This option only takes effect if the `valueColumn` is set to null. Otherwise annotations are placed along the y-axis according to the values in their valueColumn. - **showTexts**: 'yes' or 'no' Show annotation labels? (default: no) - **valueColumn**: int or null Use one of the bed columns (1-based) to scale the annotations along the y axis. (default `null`) Here is an example snippet. Used if the other options aren't set. .. code-block:: javascript { ..., colorEncoding: true, // Turn on color encoding colorRange: [ // Define the color map '#000000', '#652537', '#bf5458', '#fba273', '#ffffe0' ], colorEncodingRange: [0, 0.5119949], // Limit the encoding range ... } **Other Options*** .. image:: img/box-style.png :align: right .. image:: img/segment-style.png :align: right - **annotationStyle**: [box|segment] Two different ways of displaying annotations. Box style as pictured on the right top and segment style as shown on the right bottom. Box style is the default. Empty ===== track-type: ``empty`` The empty track can be used to create blank space between other tracks. It can be placed in either the left, right, top or bottom positions. Gene Annotations ================ .. image:: img/gene-annotations-track-thumb.png :align: right track-type: ``gene-annotations`` datatype: ``gene-annotation`` Gene annotations display the locations of genes and their exons and introns. The tracks displayed on HiGlass show a transcript consisting of the union of all annotated exons in refseq. There are separate tracks for the different available species. Details on how gene annotation tracks are created is available in the `gene annotations section <data_preparation.html#gene-annotation-tracks>`_. Event Handlers -------------- - **click**: Called when a gene annotaion is clicked on. The parameter to the callback is a single object whose format is described below. Genome coordinates are offsets from position 0 as if the chromosomes were laid out end-to-end. .. code-block:: javascript { type: "gene-annotation", event: [PIXI.js event object], payload: { xStart: [int: genome coordinate ], xStart: [int: genome coordinate ], offset: [int: start of this annotations chromosome (genome coordinate)], uid: [string: unique identifier for this annotation], fields: [array: genePred formatted array of values], ... other fields } } Heatmap ======= .. image:: img/heatmap-track-thumb.png :align: right track-type: ``heatmap`` datatype: ``matrix`` Heatmaps in HiGlass are usually used to display HiC data. They log-scale input values and map them to a user-selectable color scale (color map configuration option). Because HiGlass displays data at varying zoom levels, heatmaps are displayed at different resolutions depending on the current zoom level. To limit the resolution of the displayed data, users can set the `Zoom Limit` configuration option. You can limit the extent of the heatmap to the upper right and lower left triangle via the track context menu or by setting ``extent`` option to ``upper-right`` or ``lower-left`` respectively. Options -------- - **colorRange**: This is an array of colors used to create a segmented color scale for the heatmap. The contents of this array are passed in to `d3's scaleLinear function <https://github.com/d3/d3-scale>`_ to create the color scale. The domain of the color scale spans the lowest visible value to the highest visible value except when modified by the colorbar. Acceptable color values are ones that can be used with CSS (see, for example, `Color Names <https://htmlcolorcodes.com/color-names/>`_ ). Example: .. code-block:: javascript "colorRange": [ "white", "rgba(245,166,35,1.0)", "rgba(208,2,27,1.0)", "black" ] - **valueScaleMin/valueScaleMax**: Absolute values limiting the value to color scale. The scale can be further adjusted within this range using the colorbar. - **zeroValueColor**: The color to use for zero data values. By default, null, which uses the current color scale. (``NaN`` values are not assigned any color) Rotated 2D Heatmap ================== .. image:: img/horizontal-heatmap-thumb.png :align: right track-type: ``linear-heatmap`` datatype: ``matrix`` Rotated 2D heatmaps are regular 2D heatmaps sliced across the diagonal and rotated 45 degrees. The base of the heatmap is always the diagonal of the 2D heatmap. This is useful for displaying data, such as HiC, which has prominent features along the diagonal. .. _2d-rectangle-domain: 2D Rectangle Domain ============================== .. image:: img/2d-rectangles-track-thumb.png :align: right track-type: ``2d-rectangle-domains`` The rectangle domains track shows rectangular regions on the heatmap. These are commonly aggregated using clodius based on some importance using the ``clodius bedpe`` command. See the `data preparation section <data_preparation.html#bedpe-like-files>`__ for an example of the aggregation command. **Options** ``flipDiagonal: [yes|no|copy]`` If yes, flip domains across the diagonal. If no, plot as usual. If copy, plot regular and mirrored. **Importing** .. code-block:: bash higlass-manage ingest --filetype bed2ddb --datatype 2d-rectangle-domains annotations.bed2ddb .. _horizontal-2d-rectangle-domain: Linear 2D Rectangle Domain ========================== .. image:: img/horizontal-2d-rectangle-domains-thumb.png :align: right track-type: ``linear-2d-rectangle-domains`` datatype: ``2d-rectangle-domains`` Horizontal rectangle domains show a 45 degree rotation of rectangular domains on a 1D track. This track is most commonly used with domains that are close to the diagonal of the heatmap. Because the track is oriented so that the diagonal of the 2D view is situated along its base, rectangles far from the diagonal may be outside of the bounds of the track. .. _line-track: Line ==== .. image:: img/line-track-thumb.png :align: right track-type: ``line`` datatype: ``vector`` Line tracks display 1D vector data. Because each line segment requires two adjacent points to be present, data with lots of NaNs may lead to a fragmented plot. For such data, the :ref:`bar track <bar-track>` or :ref:`point track <point-track>` may be more appropriate. Options -------- - **axisLabelFormatting**: ['normal', 'scientific'] - Display the vertical axis labels as regular numbers or using scientific notation. - **lineStrokeColor**: - A valid color (e.g. ``black``) or to track the color of the line use ``[glyph-color]``. - **constIndicators**: Array of constant value indicators - A constant value indicator display a line for a constant value, e.g., a minimum or maximum value. This property is also available on other 1D tracks like ``Bar`` and ``Point`` tracks. See the following for an example: .. code-block:: javascript { type: 'line', ... options: { constIndicators: [ { color: '#000000', opacity: 0.33, label: 'Max', labelPosition: 'leftBottom', labelColor: '#000000', labelOpacity: 0.25, value: 60000 }, ], ... } } - **valueScaleMin/valueScaleMax**: Absolute values limiting the the value scale, which is used to determine y-position (in 1D tracks) or color (heatmap) tracks. .. _bar-track: Bar ==== .. image:: img/bar-track-thumb.png :align: right track-type: ``bar`` datatype: ``vector`` Bar tracks display 1D vector data as bars. Options -------- - **axisLabelFormatting**: ['normal', 'scientific'] - Display the vertical axis labels as regular numbers or using scientific notation. - **barFillColor**: A valid color (e.g. ``black``) or to track the color of the bars use ``[glyph-color]``. - **valueScaleMin/valueScaleMax**: Absolute values limiting the value to y-position scale. - **zeroLineVisible**: If ``true`` draws a demarcation line at the bottom of a bar track, i.e., at the zero value. - **zeroLineColor**: The color of the zero line. If ``undefined`` the bar fill color (``barFillColor``) will be used. - **zeroLineOpacity**: The opacity of the zero line. If ``undefined`` the bar opacity (``barOpacity``) will be used. **Demos:** - `Diverging bars with color map and gradient <examples/bar-track-color-range.html>` .. _point-track: Point ===== .. image:: img/point-track-thumb.png :align: right track-type: ``point`` datatype: ``vector`` Point tracks display 1D vector data. Unlike :ref:`line tracks <line-track>`, they are well suited to data with NaNs because they do not require two points to draw something. Options -------- - **axisLabelFormatting**: ['normal', 'scientific'] - Display the vertical axis labels as regular numbers or using scientific notation. - **valueScaleMin/valueScaleMax**: Absolute values limiting the value to y-position scale. .. _1d-heatmap: 1D Heatmap ========== .. image:: img/1d-heatmap-track.png :align: right track-type: ``1d-heatmap`` datatype: ``vector`` 1D heatmap tracks display 1D vector data. Unlike the other 1D tracks, they are well suited for getting an overview of distribution and less suited for identifying precise properties of individual data points. E.g., finding regions that are on average highly expressed is much easier than finding the highest peak with this track. **Example:** .. code-block:: javascript { server: 'http://higlass.io/api/v1', tilesetUid: 'e0DYtZBSTqiMLHoaimsSpg', uid: '1d-heatmap', type: '1d-heatmap', options: { labelPosition: 'hidden', colorRange: ['#FFFFFF', '#ccc6ff', '#4f3de5', '#120489', '#000000'], }, height: 12, } **Demo**: `Full example <1d-heatmap-track.html>`_. `Genome browser-like view from HiGlass.io <1d-heatmap-track-2.html>`_. Options ------- - **valueScaleMin/valueScaleMax**: Absolute values limiting the value to color scale. The scale can be further adjusted within this range using the colorbar. .. _chromosome-labels: Chromosome Labels ================= .. image:: img/chromosome-labels-thumb.png :align: right track-type: ``chromosome-labes`` datatype: ``chromsizes`` or ``cooler`` filetypes: ``chromsizes-tsv`` The chromosome labels track shows the names of the chromosomes. Its data is sourced from a standard chromSizes file containing chromosome names and chromosome files. The file can be ingested by the higlass server like any other tileset. As long as the `datatype` is set to `chromsizes` this track should be selectable from the "Add Track Dialog". Options ------- - **tickPositions**: [even|ends] Space tick marks evenly across the track or only show them at the start and end. - **tickFormat**: [plain|si] The format for the ticks. If set to plain, ticks are formatted as regular numbers with commas delimiting blocks of zeros (e.g. 1,100,000). If set to SI, then SI prefixes along with precision limiting is used (e.g. 1.1M). If not specified, the default is *plain* for ``tickPosition == 'even'`` and *si* for ``tickPosition == 'ends'`` - **reverseOrientation**: [false|true] Alignment of ticks. If set to true, ticks stick to the top in the horizontal label tracks and to the left in the vertical label tracks. **Demos:** - `demonstrate adjustability <examples/chromosome-labels.html>`_. Chromosome Grid =============== .. image:: img/chromosome-grid-thumb.png :align: right track-type: ``2d-chromosome-grid`` datatype: ``chromsizes`` or ``cooler`` filetypes: ``chromsizes-tsv`` A chromosome grid displays the boundaries of chromosomes on the 2D area. Its data is sourced from a standard chromSizes file containing chromosome names and chromosome files. The file can be ingested by the higlass server like any other tileset. As long as the `datatype` is set to `chromsizes` this track should be selectable from the "Add Track Dialog". To find the chromosome grid in the list of tracks, search for "chromosomes" when adding a track to the *center* view. Horizontal Chromosome Grid ========================== .. image:: img/horizontal-chromosome-labels-thumb.png :align: right track-type: ``chromosome-lables`` datatype: ``chromsizes`` or ``cooler`` filetypes: ``chromsizes-tsv`` The horizontal chromosome grid shows the locations of chromosome boundaries on a 1D track. Stacked Bars ============ .. image:: img/horizontal-stacked-bar-scaled-thumb.png :align: right track-type: ``stacked-bar`` datatype: ``multivec`` Stacked bar tracks display multivec data. They show multiple values at every location in the data by using a set of vertically stacked bars. There is an option to pick 'unscaled' and 'scaled' representations, which scale the height of the bars to the maximum and minimum value in all visible tiles or to fit the height of the track, respectively. Multiple Lines ============== .. image:: img/basic-multiple-line-chart-thumb.png :align: right track-type: ``basic-multiple-line-chart`` datatype: ``multivec`` Displays multivec data by showing multiple values at every location using a number of line graphs. Multiple Bar Charts =================== .. image:: img/basic-multiple-bar-chart-thumb.png :align: right track-type: ``basic-multiple-bar-chart`` datatype: ``multivec`` Displays multivec data by showing multiple values at every location using a number of bar graphs. .. _1d-annotations: 1D Annotations ============== .. image:: img/1d-annotations.png :align: right track-type: ``1d-annotations`` and ``1d-annotations`` datatype: none Displays absolute positioned 1D annotations on horizontal and vertical 1D tracks as well as 2D tracks. This track can be used to permanently highlight 1D regions in any kind of dataset. The data is directly passed in via the ``regions`` parameter of the ``options``. **Example:** .. code-block:: javascript { uid: 'selection-a', type: '1d-annotations', options: { regions: [ [230000000, 561000000], ], minRectWidth: 3, fillOpacity: 0.1, stroke: 'blue', strokePos: ['left', 'right'], strokeWidth: 2, strokeOpacity: 0.6, } } Multivec ======== .. image:: img/horizontal-multivec.png :align: right track-type: ``multivec`` datatype: multivec Multivec tracks show multiple values at every location in the data by using a set of rows. Options -------- - **colorbarPosition**: ['hidden', 'topLeft', 'topRight', 'bottomLeft', 'bottomRight'] - The position of the colorbar element. - **colorbarBackgroundColor**: The background color for the colorbar element. - **zeroValueColor**: The color to use for zero data values. By default, null, which uses the current color scale. - **selectRows**: Array of row indices (of the original multivec dataset) to include in the visualization. This enables filtering, sorting, and aggregation. By default, null, to show all rows and use the default ordering. - **selectRowsAggregationMode**: If the ``selectRows`` array contains subarrays, these will be treated as aggregation groups. This option can be used to define the aggregation function to use ("mean", "sum", "variance", "deviation"). By default, "mean". - **selectRowsAggregationWithRelativeHeight**: If the ``selectRows`` array contains subarrays, this option will determine whether the visual heights for the aggregated row groups will be scaled by the group size or always a single unit. By default, true. - **selectRowsAggregationMethod**: Where should the aggregation be done? By default, "client". **Example:** .. code-block:: javascript { type: 'multivec', uid: 'K_0GxgCvQfCHM56neOnHKg', tilesetUid: 'abohuD-sTbiyAPqh2y5OpA', server: 'https://resgen.io/api/v1', options: { labelPosition: 'topLeft', labelColor: 'black', labelTextOpacity: 0.4, valueScaling: 'linear', trackBorderWidth: 0, trackBorderColor: 'black', heatmapValueScaling: 'log', name: 'my_file_genome_wide_20180228.multires.mv5', labelLeftMargin: 0, labelRightMargin: 0, labelTopMargin: 0, labelBottomMargin: 0, labelShowResolution: true, minHeight: 100, colorbarPosition: 'topRight', colorbarBackgroundColor: '#ffffff' }, width: 1500, height: 700 } Viewport Projection =================== track-type: ``viewport-projection-horizontal``, ``viewport-projection-vertical``, ``viewport-projection-center`` Viewport projection tracks allow brushing interactions for an interval or area, which is optionally linked to the domain of another view. Properties -------- - **fromViewUid**: The ``uid`` of the linked view, from which this track will obtain its domain. If null, then the ``projectionXDomain`` and/or ``projectionYDomain`` properties must be used instead. - **projectionXDomain**: ``[x0, x1]`` The x domain coordinates that define the selected interval. Only used if ``fromViewUid`` is null. - **projectionYDomain**: ``[y0, y1]`` The y domain coordinates that define the selected interval. Only used if ``fromViewUid`` is null. Options -------- - **projectionFillColor**: The fill color for the brush selection rect element. - **projectionStrokeColor**: The stroke color for the brush selection rect element. - **projectionFillOpacity**: The opacity for the fill of the brush selection rect element. - **projectionStrokeOpacity**: The opacity for the stroke of the brush selection rect element. - **strokeWidth**: The stroke width for the brush selection rect element. **Example:** .. code-block:: javascript { "type": "viewport-projection-horizontal", "uid": "my-track-id", "fromViewUid": null, "projectionXDomain": [225681609.97037065, 226375261.90599522], "options": { "projectionFillColor": "#F00", "projectionStrokeColor": "#777", "projectionFillOpacity": 0.3, "projectionStrokeOpacity": 0.7, "strokeWidth": 1 } }
{ "content_hash": "75ead80a54989a622e3fa0b111d03b82", "timestamp": "", "source": "github", "line_count": 637, "max_line_length": 361, "avg_line_length": 33.06750392464678, "alnum_prop": 0.7096942650968477, "repo_name": "hms-dbmi/4DN_matrix-viewer", "id": "96f75da49fa554d56187dc5cbee8343dcf4ded3a", "size": "21064", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "docs/track_types.rst", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4314" }, { "name": "HTML", "bytes": "19879" }, { "name": "JavaScript", "bytes": "154056" }, { "name": "Python", "bytes": "18239" } ], "symlink_target": "" }
'------------------------------------------------------------------------------ ' <auto-generated> ' Il codice è stato generato da uno strumento. ' Versione runtime:4.0.30319.42000 ' ' Le modifiche apportate a questo file possono provocare un comportamento non corretto e andranno perse se ' il codice viene rigenerato. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'Questa classe è stata generata automaticamente dalla classe StronglyTypedResourceBuilder. 'tramite uno strumento quale ResGen o Visual Studio. 'Per aggiungere o rimuovere un membro, modificare il file con estensione ResX ed eseguire nuovamente ResGen 'con l'opzione /str oppure ricompilare il progetto VS. '''<summary> ''' Classe di risorse fortemente tipizzata per la ricerca di stringhe localizzate e così via. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Restituisce l'istanza di ResourceManager nella cache utilizzata da questa classe. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("ACS.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Esegue l'override della proprietà CurrentUICulture del thread corrente per tutte le ''' ricerche di risorse eseguite utilizzando questa classe di risorse fortemente tipizzata. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property cross() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("cross", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Empty_Quest_Log() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Empty_Quest_Log", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property money_copper_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("money-copper[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property money_gold_2_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("money-gold[2]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property money_silver_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("money-silver[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Pvecurrency_valor_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Pvecurrency-valor[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Pvpcurrency_honor_alliance_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Pvpcurrency-honor-alliance[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Pvpcurrency_honor_horde_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Pvpcurrency-honor-horde[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_deathknight_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_deathknight[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_druid_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_druid[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_hunter_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_hunter[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_mage_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_mage[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_paladin_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_paladin[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_priest_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_priest[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_rogue_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_rogue[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_shaman_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_shaman[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_warlock_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_warlock[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_classes_warrior_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-classes_warrior[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_bloodelf_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_bloodelf-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_draenei_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_draenei-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_dwarf_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_dwarf-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_gnome_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_gnome-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_human_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_human-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_nightelf_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_nightelf-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_orc_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_orc-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_tauren_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_tauren-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_troll_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_troll-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property '''<summary> ''' Cerca una risorsa localizzata di tipo System.Drawing.Bitmap. '''</summary> Friend ReadOnly Property Ui_charactercreate_races_undead_male_1_() As System.Drawing.Bitmap Get Dim obj As Object = ResourceManager.GetObject("Ui-charactercreate-races_undead-male[1]", resourceCulture) Return CType(obj,System.Drawing.Bitmap) End Get End Property End Module End Namespace
{ "content_hash": "1ded792ee9f66b0924f32d2bd6e21ff4", "timestamp": "", "source": "github", "line_count": 343, "max_line_length": 163, "avg_line_length": 44.95043731778426, "alnum_prop": 0.6107796082500973, "repo_name": "Gargarensis/ACS", "id": "fd7469055d9abe3e753e9d2e30175902b62a7ade", "size": "15424", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "My Project/Resources.Designer.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Visual Basic", "bytes": "440277" } ], "symlink_target": "" }
function change_track(sourceUrl) { var audio = $("#player"); if(sourceUrl==""){ return 0; } $("#mp3-src").attr("src", sourceUrl); /****************/ audio[0].pause(); audio[0].load(); audio[0].play(); $('.spinner-wrap').addClass('playing').addClass('pulse'); /****************/ } $( document ).ready(function() { $('.spinner-wrap').click(function() { var $this = $(this), audio = $this.siblings('audio')[0], bpm = Number($('.track').attr('data-bpm')); pulse = (60/bpm)*1000; console.log(bpm); if (audio.paused === false) { audio.pause(); audio.currentTime = 0; $this.removeClass('playing').removeClass('pulse'); clearInterval(intervals); } else { audio.play(); $this.addClass('playing').addClass('pulse'); pulsing(); intervals = setInterval(function() {pulsing()}, pulse); } function pulsing() { $this.addClass('pulse'); setTimeout(function() { $this.removeClass('pulse'); }, pulse-100); } }); });
{ "content_hash": "aa0e5fdd83cd7616082106ecad2c48a6", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 67, "avg_line_length": 21.31578947368421, "alnum_prop": 0.45925925925925926, "repo_name": "maunilswadas/musicapp", "id": "995f5e81de64c04f75a5e1ed749525c249cefdd2", "size": "1215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/js/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7638" }, { "name": "HTML", "bytes": "14201" }, { "name": "JavaScript", "bytes": "13530" } ], "symlink_target": "" }
set -ex # Run the unit tests vendor/bin/phpunit eval $(./ci/set-behat-tags.sh) # Run the functional tests vendor/bin/behat --format progress $behat_tags # Run CodeSniffer ./codesniffer/scripts/phpcs --standard=./ci/ php/
{ "content_hash": "66b528c38b98834a459e094cf9bc7310", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 49, "avg_line_length": 18.75, "alnum_prop": 0.7288888888888889, "repo_name": "heiglandreas/wp-cli", "id": "0972b3a341e6db5db47b2ff41a4f7999b928730c", "size": "238", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "ci/test.sh", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "543879" }, { "name": "Shell", "bytes": "13718" } ], "symlink_target": "" }
<div ng-include="contentUrl" ng-init="init()"></div>
{ "content_hash": "22ecc4f1230e305628b2ff49027299b7", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 52, "avg_line_length": 52, "alnum_prop": 0.6730769230769231, "repo_name": "pritok/konga", "id": "1fc4e5eddab525eb08ac44a762a93969f66fb5db", "size": "52", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/result-table.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "24295" }, { "name": "CSS", "bytes": "240867" }, { "name": "HTML", "bytes": "96302" }, { "name": "JavaScript", "bytes": "770399" }, { "name": "Shell", "bytes": "4012" } ], "symlink_target": "" }
package com.sksamuel.scapegoat.inspections.collections import com.sksamuel.scapegoat._ /** @author Stephen Samuel */ class FilterOptionAndGet extends Inspection { def inspector(context: InspectionContext): Inspector = new Inspector(context) { override def postTyperTraverser = Some apply new context.Traverser { import context.global._ override def inspect(tree: Tree): Unit = { tree match { case Apply(TypeApply( Select(Apply(Select(_, TermName("filter")), List(Function(_, Select(_, TermName("isDefined"))))), TermName("map")), args), List(Function(_, Select(_, TermName("get"))))) => context.warn("filter(_.isDefined).map(_.get)", tree.pos, Levels.Info, ".filter(_.isDefined).map(_.get) can be replaced with flatten: " + tree.toString().take(500), FilterOptionAndGet.this) case _ => continue(tree) } } } } }
{ "content_hash": "e09f22843912d237ff37f585feec0bdf", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 132, "avg_line_length": 37.32, "alnum_prop": 0.6345123258306538, "repo_name": "jasonchaffee/scalac-scapegoat-plugin", "id": "6b964a47370ff9c722889e51113e098eef7ab26b", "size": "933", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/main/scala/com/sksamuel/scapegoat/inspections/collections/FilterOptionAndGet.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "665" }, { "name": "Scala", "bytes": "366763" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Thelidium plumbeum f. plumbeum (Ach.) Servít ### Remarks null
{ "content_hash": "d298b793499ef886ad83631e2f74071f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 44, "avg_line_length": 11.461538461538462, "alnum_prop": 0.7046979865771812, "repo_name": "mdoering/backbone", "id": "5bb822ae990a1a8fa753dbbbe6af7fe1b9957f96", "size": "216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Eurotiomycetes/Verrucariales/Verrucariaceae/Thelidium/Thelidium plumbeum/Thelidium plumbeum plumbeum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }