text
stringlengths
2
1.04M
meta
dict
namespace RiakClient.Models.MapReduce.Phases { using Models.MapReduce.Languages; using Newtonsoft.Json; internal abstract class RiakActionPhase<TLanguage> : RiakPhase where TLanguage : IRiakPhaseLanguage, new() { private readonly TLanguage language; private object argument; protected RiakActionPhase() { this.language = new TLanguage(); } /// <summary> /// The language type of the phase. /// (<see cref="RiakPhaseLanguageErlang"/> or <see cref="RiakPhaseLanguageJavascript"/>). /// </summary> public TLanguage Language { get { return language; } } /// <summary> /// The optional arguments to pass onto the phase function. /// </summary> /// <typeparam name="T">The type of the <paramref name="argument"/> parameter.</typeparam> /// <param name="argument">The argument to pass on.</param> public void Argument<T>(T argument) { this.argument = argument; } protected override void WriteJson(JsonWriter writer) { Language.WriteJson(writer); if (argument != null) { var json = JsonConvert.SerializeObject(argument); writer.WritePropertyName("arg"); writer.WriteRawValue(json); } } } }
{ "content_hash": "bdca158618e906719d008c1a1ecffeb8", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 98, "avg_line_length": 29.833333333333332, "alnum_prop": 0.5649441340782123, "repo_name": "basho/riak-dotnet-client", "id": "86044183a38f58cb44288efd439db68144ed5d92", "size": "2203", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/RiakClient/Models/MapReduce/Phases/RiakActionPhase.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "183" }, { "name": "C#", "bytes": "1832967" }, { "name": "Makefile", "bytes": "2094" }, { "name": "PowerShell", "bytes": "10101" }, { "name": "Shell", "bytes": "1586" } ], "symlink_target": "" }
// Copyright (c) André N. Klingsheim. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using NWebsec.Core; namespace NWebsec.Middleware.Middleware { public class RedirectValidationMiddleware : MiddlewareBase { private readonly RedirectValidationOptions _config; private readonly RedirectValidator _redirectValidator; public RedirectValidationMiddleware(RequestDelegate next, RedirectValidationOptions options) : base(next) { _config = options; _redirectValidator = new RedirectValidator(); } internal override void PostInvokeNext(HttpContext context) { var statusCode = context.Response.StatusCode; if (!_redirectValidator.IsRedirectStatusCode(statusCode)) { return; } var scheme = context.Request.Scheme; var hostandport = context.Request.Host; var requestUri = new Uri(scheme + "://" + hostandport); _redirectValidator.ValidateRedirect(statusCode, context.Response.Headers["Location"], requestUri, _config); } } }
{ "content_hash": "00d63cd06358bda2e9e2246e788960ed", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 119, "avg_line_length": 31.974358974358974, "alnum_prop": 0.6511627906976745, "repo_name": "nklap/core", "id": "0cfa5571c3c3b094380ef4904f1902a23d338223", "size": "1250", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "external/NWebsec/Middleware/RedirectValidationMiddleware.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1526" }, { "name": "C#", "bytes": "84005" }, { "name": "CSS", "bytes": "1413" }, { "name": "Shell", "bytes": "1198" } ], "symlink_target": "" }
<html> <title> Light Crafts on Linux </title> <body> <center> Welcome to Light Crafts, Inc. </center> </body> </html>
{ "content_hash": "d23855a8e8ef4cd65dcc55425e66ce1f", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 29, "avg_line_length": 11.8, "alnum_prop": 0.6694915254237288, "repo_name": "AntonKast/LightZone", "id": "5cd8779082ea322d9f05ea57ac2379c84888829f", "size": "118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "linux/web/linux.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "151670" }, { "name": "C", "bytes": "5865855" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "1169604" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "Delphi", "bytes": "40318" }, { "name": "Haskell", "bytes": "1896" }, { "name": "Java", "bytes": "16309002" }, { "name": "JavaScript", "bytes": "1994" }, { "name": "Objective-C", "bytes": "366933" }, { "name": "Perl", "bytes": "12957" }, { "name": "Shell", "bytes": "489287" }, { "name": "Smalltalk", "bytes": "10530" } ], "symlink_target": "" }
'use strict'; // Configuring the Articles module angular.module('users.admin').run(['Menus', function (Menus) { Menus.addSubMenuItem('topbar', 'admin', { title: ' Người dùng', state: 'admin.users' }); } ]);
{ "content_hash": "6afa699ccbdf3cfccf6ce174d4d87c2c", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 45, "avg_line_length": 21.181818181818183, "alnum_prop": 0.6008583690987125, "repo_name": "dewn49/farmpro", "id": "7614ffb0c94ca94939060d1719fed5e52b823893", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/users/client/config/users-admin.client.menus.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "155817" }, { "name": "HTML", "bytes": "68052" }, { "name": "JavaScript", "bytes": "392351" }, { "name": "Shell", "bytes": "685" } ], "symlink_target": "" }
extern NSURL *ASFURLByAppendingParameters(NSURL *URL, NSDictionary *parameters); extern NSString *ASFQueryFromParameters(NSDictionary *parameters); extern NSString *ASFURLEncodedString(NSString *string); extern NSString *ASFURLDecodedString(NSString *string); extern NSDictionary *ASFParametersFromQuery(NSString *query); @interface ASFRequestBuilder : NSObject - (NSURLRequest *)request:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters token:(NSString *)token error:(NSError *__autoreleasing *)error; @end
{ "content_hash": "4c4c1e2a662ea2cbb9cfd823a5d09333", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 80, "avg_line_length": 41.06666666666667, "alnum_prop": 0.7126623376623377, "repo_name": "anton-simakov/ASFeedly", "id": "883e711266dfd4ffee9982f1b23848745c68758e", "size": "800", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ASFFeedly/ASFRequestBuilder.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "350" }, { "name": "Objective-C", "bytes": "44581" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Lonchocarpus gillyi Lundell ### Remarks null
{ "content_hash": "42697f25cfbd971b8f1cee26636c4641", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 11.461538461538462, "alnum_prop": 0.738255033557047, "repo_name": "mdoering/backbone", "id": "7835e22e8acfc1385c1f1f8221b462954e138ec0", "size": "228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Lonchocarpus/Lonchocarpus rugosus/Lonchocarpus rugosus gillyi/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <title>GitHubRelease</title> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="GitHubRelease"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/GitHubRelease.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/myrobotlab/framework/repo/GitHubContent.html" title="class in org.myrobotlab.framework.repo"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/myrobotlab/framework/repo/Repo.html" title="class in org.myrobotlab.framework.repo"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/myrobotlab/framework/repo/GitHubRelease.html" target="_top">Frames</a></li> <li><a href="GitHubRelease.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods.inherited.from.class.java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.myrobotlab.framework.repo</div> <h2 title="Class GitHubRelease" class="title">Class GitHubRelease</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.myrobotlab.framework.repo.GitHubRelease</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">GitHubRelease</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/myrobotlab/framework/repo/GitHubRelease.html#draft">draft</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.Integer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/myrobotlab/framework/repo/GitHubRelease.html#id">id</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/myrobotlab/framework/repo/GitHubRelease.html#name">name</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/myrobotlab/framework/repo/GitHubRelease.html#tag_name">tag_name</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/myrobotlab/framework/repo/GitHubRelease.html#upload_url">upload_url</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/myrobotlab/framework/repo/GitHubRelease.html#url">url</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/myrobotlab/framework/repo/GitHubRelease.html#GitHubRelease--">GitHubRelease</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="url"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>url</h4> <pre>public&nbsp;java.lang.String url</pre> </li> </ul> <a name="upload_url"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>upload_url</h4> <pre>public&nbsp;java.lang.String upload_url</pre> </li> </ul> <a name="id"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>id</h4> <pre>public&nbsp;java.lang.Integer id</pre> </li> </ul> <a name="tag_name"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>tag_name</h4> <pre>public&nbsp;java.lang.String tag_name</pre> </li> </ul> <a name="name"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>name</h4> <pre>public&nbsp;java.lang.String name</pre> </li> </ul> <a name="draft"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>draft</h4> <pre>public&nbsp;java.lang.String draft</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="GitHubRelease--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>GitHubRelease</h4> <pre>public&nbsp;GitHubRelease()</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/GitHubRelease.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../org/myrobotlab/framework/repo/GitHubContent.html" title="class in org.myrobotlab.framework.repo"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/myrobotlab/framework/repo/Repo.html" title="class in org.myrobotlab.framework.repo"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/myrobotlab/framework/repo/GitHubRelease.html" target="_top">Frames</a></li> <li><a href="GitHubRelease.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods.inherited.from.class.java.lang.Object">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "1ea08acf265d393c13cf1a918f6666f3", "timestamp": "", "source": "github", "line_count": 337, "max_line_length": 185, "avg_line_length": 33.0919881305638, "alnum_prop": 0.6119081779053085, "repo_name": "robojukie/myrobotlab", "id": "108bf73e31e999763fa9a13c13dcc8b677b04a83", "size": "11152", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "javadoc/org/myrobotlab/framework/repo/GitHubRelease.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Arduino", "bytes": "88249" }, { "name": "Groff", "bytes": "7733" }, { "name": "HTML", "bytes": "9173" }, { "name": "Java", "bytes": "3744167" }, { "name": "Processing", "bytes": "9582" }, { "name": "Propeller Spin", "bytes": "14185" }, { "name": "Python", "bytes": "4187" } ], "symlink_target": "" }
package net.opengis.gml; /** * A document containing one _Object(@http://www.opengis.net/gml) element. * * This is a complex type. */ public interface ObjectDocument extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(ObjectDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s6E28D279B6C224D74769DB8B98AF1665").resolveHandle("objectdcbfdoctype"); /** * Gets the "_Object" element */ org.apache.xmlbeans.XmlObject getObject(); /** * Sets the "_Object" element */ void setObject(org.apache.xmlbeans.XmlObject object); /** * Appends and returns a new empty "_Object" element */ org.apache.xmlbeans.XmlObject addNewObject(); /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static net.opengis.gml.ObjectDocument newInstance() { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static net.opengis.gml.ObjectDocument newInstance(org.apache.xmlbeans.XmlOptions options) { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } /** @param xmlAsString the string value to parse */ public static net.opengis.gml.ObjectDocument parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); } public static net.opengis.gml.ObjectDocument parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); } /** @param file the file from which to load an xml document */ public static net.opengis.gml.ObjectDocument parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); } public static net.opengis.gml.ObjectDocument parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); } public static net.opengis.gml.ObjectDocument parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); } public static net.opengis.gml.ObjectDocument parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); } public static net.opengis.gml.ObjectDocument parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); } public static net.opengis.gml.ObjectDocument parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); } public static net.opengis.gml.ObjectDocument parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); } public static net.opengis.gml.ObjectDocument parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); } public static net.opengis.gml.ObjectDocument parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); } public static net.opengis.gml.ObjectDocument parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); } public static net.opengis.gml.ObjectDocument parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); } public static net.opengis.gml.ObjectDocument parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static net.opengis.gml.ObjectDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static net.opengis.gml.ObjectDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (net.opengis.gml.ObjectDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ @Deprecated public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } private Factory() { } // No instance of this class allowed } }
{ "content_hash": "531b1b23b5d21ffe9a00f15f4c521529", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 279, "avg_line_length": 71.21100917431193, "alnum_prop": 0.7290646740530791, "repo_name": "moosbusch/xbLIDO", "id": "c15661186716449c0f5f1cc1d578385e3f9099bc", "size": "8375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/net/opengis/gml/ObjectDocument.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18814207" } ], "symlink_target": "" }
package local import ( "archive/tar" "encoding/json" "fmt" "io/ioutil" "os" "path" "path/filepath" "strings" "github.com/chengtiesheng/ContainerAnalyzer/attr" ) type FileBackend struct { file *os.File } func NewFileBackend(file *os.File) *FileBackend { return &FileBackend{ file: file, } } func (lb *FileBackend) GetImageInfo(dockerURL string) ([]string, *attr.ParsedDockerURL, error) { parsedDockerURL := attr.ParseDockerURL(dockerURL) appImageID, parsedDockerURL, err := getImageID(lb.file, parsedDockerURL) if err != nil { return nil, nil, fmt.Errorf("error getting ImageID: %v", err) } ancestry, err := getAncestry(lb.file, appImageID) if err != nil { return nil, nil, fmt.Errorf("error getting ancestry: %v", err) } return ancestry, parsedDockerURL, nil } func (lb *FileBackend) GetLayerInfo(layerID string, dockerURL *attr.ParsedDockerURL) (*attr.DockerImageData, error) { j, err := getJson(lb.file, layerID) if err != nil { return nil, err } layerData := attr.DockerImageData{} if err := json.Unmarshal(j, &layerData); err != nil { return nil, err } return &layerData, nil } func getImageID(file *os.File, dockerURL *attr.ParsedDockerURL) (string, *attr.ParsedDockerURL, error) { type tags map[string]string type apps map[string]tags _, err := file.Seek(0, 0) if err != nil { return "", nil, fmt.Errorf("error seeking file: %v", err) } var imageID string var appName string reposWalker := func(t *TarFile) error { if filepath.Clean(t.Name()) == "repositories" { repob, err := ioutil.ReadAll(t.TarStream) if err != nil { return fmt.Errorf("error reading repositories file: %v", err) } var repositories apps if err := json.Unmarshal(repob, &repositories); err != nil { return fmt.Errorf("error unmarshaling repositories file") } if dockerURL == nil { n := len(repositories) switch { case n == 1: for key, _ := range repositories { appName = key } case n > 1: var appNames []string for key, _ := range repositories { appNames = append(appNames, key) } return fmt.Errorf("several images found, use option --image with one of:\n\n%s", strings.Join(appNames, "\n")) default: return fmt.Errorf("no images found") } } else { appName = dockerURL.ImageName } tag := "latest" if dockerURL != nil { tag = dockerURL.Tag } app, ok := repositories[appName] if !ok { return fmt.Errorf("app %q not found", appName) } _, ok = app[tag] if !ok { if len(app) == 1 { for key, _ := range app { tag = key } } else { return fmt.Errorf("tag %q not found", tag) } } if dockerURL == nil { dockerURL = &attr.ParsedDockerURL{ IndexURL: "", Tag: tag, ImageName: appName, } } imageID = string(app[tag]) } return nil } tr := tar.NewReader(file) if err := Walk(*tr, reposWalker); err != nil { return "", nil, err } if imageID == "" { return "", nil, fmt.Errorf("repositories file not found") } return imageID, dockerURL, nil } func getJson(file *os.File, layerID string) ([]byte, error) { jsonPath := path.Join(layerID, "json") return getTarFileBytes(file, jsonPath) } func getTarFileBytes(file *os.File, path string) ([]byte, error) { _, err := file.Seek(0, 0) if err != nil { fmt.Errorf("error seeking file: %v", err) } var fileBytes []byte fileWalker := func(t *TarFile) error { if filepath.Clean(t.Name()) == path { fileBytes, err = ioutil.ReadAll(t.TarStream) if err != nil { return err } } return nil } tr := tar.NewReader(file) if err := Walk(*tr, fileWalker); err != nil { return nil, err } if fileBytes == nil { return nil, fmt.Errorf("file %q not found", path) } return fileBytes, nil } func getAncestry(file *os.File, imgID string) ([]string, error) { var ancestry []string curImgID := imgID var err error for curImgID != "" { ancestry = append(ancestry, curImgID) curImgID, err = getParent(file, curImgID) if err != nil { return nil, err } } return ancestry, nil } func getParent(file *os.File, imgID string) (string, error) { var parent string _, err := file.Seek(0, 0) if err != nil { return "", fmt.Errorf("error seeking file: %v", err) } jsonPath := filepath.Join(imgID, "json") parentWalker := func(t *TarFile) error { if filepath.Clean(t.Name()) == jsonPath { jsonb, err := ioutil.ReadAll(t.TarStream) if err != nil { return fmt.Errorf("error reading layer json: %v", err) } var dockerData attr.DockerImageData if err := json.Unmarshal(jsonb, &dockerData); err != nil { return fmt.Errorf("error unmarshaling layer data: %v", err) } parent = dockerData.Parent } return nil } tr := tar.NewReader(file) if err := Walk(*tr, parentWalker); err != nil { return "", err } return parent, nil }
{ "content_hash": "b006ab2809f3f87c1702b8b63f673f12", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 117, "avg_line_length": 21.15948275862069, "alnum_prop": 0.6341413729883887, "repo_name": "ChengTiesheng/ContainerAnalyzer", "id": "f08c6f70188e728d3d5212d801c5d108ef65ce68", "size": "4909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "attr/local/local.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "38635" } ], "symlink_target": "" }
const _ = require('lodash'); const Service = require('../../service'); const { ParameterNotAllowNullException, NotFoundException, } = require('../../error'); module.exports = async function getAvailableProductsByUserId({ userId }) { if (!userId) { throw new ParameterNotAllowNullException(); } const products = await Service.Product.getAll(); const placeRewards = await Service.RelationPlaceProductReward.getAll(); const associateProducts = products.map((product) => { const supplyPlaces = placeRewards.filter(place => place.productId === product.id); return Object.assign(product.get(), { supplyPlaces, }); }); const user = await Service.User.getById(+userId); if (!user) { throw new NotFoundException(); } const userConquest = await Service.RelationUserPlaceConquest.getRelationByUserId(user.id); const userConquestPlaceIds = userConquest.map(relation => relation.placeId); // return { associateUser, associateProducts }; return associateProducts.map((product) => { if (product.supplyPlaces.length > 0) { const productSupplyPlaceIds = product.supplyPlaces.map(relation => relation.placeId); const userPurchaseAvailable = _.intersection( productSupplyPlaceIds, userConquestPlaceIds, ).length > 0; if (userPurchaseAvailable) { return Object.assign(product, { available: true, }); } return Object.assign(product, { available: false, name: 'BLOCK', imageUrl: 'BLOCK', description: 'BLOCK', price: 0, sale: 0, }); } return Object.assign(product, { available: true, }); }); };
{ "content_hash": "109709aad1d072ffc60c8c98588caafd", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 92, "avg_line_length": 30.70909090909091, "alnum_prop": 0.6560094730609828, "repo_name": "uyu423/9xd-Go-Server", "id": "56b69bf6e37228d35af88bc7be50f2109d2c8478", "size": "1689", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "controller/Product/getAvailableProductsByUserId.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "17296" } ], "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" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>IoServiceListener xref</title> <link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" /> </head> <body> <div id="overview"><a href="../../../../../../apidocs/org/apache/mina/core/service/IoServiceListener.html">View Javadoc</a></div><pre> <a name="1" href="#1">1</a> <em class="jxr_comment"></em> <a name="20" href="#20">20</a> <strong class="jxr_keyword">package</strong> org.apache.mina.core.service; <a name="21" href="#21">21</a> <a name="22" href="#22">22</a> <strong class="jxr_keyword">import</strong> java.util.EventListener; <a name="23" href="#23">23</a> <a name="24" href="#24">24</a> <strong class="jxr_keyword">import</strong> org.apache.mina.core.session.IdleStatus; <a name="25" href="#25">25</a> <strong class="jxr_keyword">import</strong> org.apache.mina.core.session.IoSession; <a name="26" href="#26">26</a> <a name="27" href="#27">27</a> <em class="jxr_javadoccomment">/**</em> <a name="28" href="#28">28</a> <em class="jxr_javadoccomment"> * Listens to events related to an {@link IoService}.</em> <a name="29" href="#29">29</a> <em class="jxr_javadoccomment"> *</em> <a name="30" href="#30">30</a> <em class="jxr_javadoccomment"> * @author &lt;a href="<a href="http://mina.apache.org" target="alexandria_uri">http://mina.apache.org</a>"&gt;Apache MINA Project&lt;/a&gt;</em> <a name="31" href="#31">31</a> <em class="jxr_javadoccomment"> */</em> <a name="32" href="#32">32</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">interface</strong> <a href="../../../../../org/apache/mina/core/service/IoServiceListener.html">IoServiceListener</a> <strong class="jxr_keyword">extends</strong> EventListener { <a name="33" href="#33">33</a> <em class="jxr_javadoccomment">/**</em> <a name="34" href="#34">34</a> <em class="jxr_javadoccomment"> * Invoked when a new service is activated by an {@link IoService}.</em> <a name="35" href="#35">35</a> <em class="jxr_javadoccomment"> *</em> <a name="36" href="#36">36</a> <em class="jxr_javadoccomment"> * @param service the {@link IoService}</em> <a name="37" href="#37">37</a> <em class="jxr_javadoccomment"> */</em> <a name="38" href="#38">38</a> <strong class="jxr_keyword">void</strong> serviceActivated(<a href="../../../../../org/apache/mina/core/service/IoService.html">IoService</a> service) <strong class="jxr_keyword">throws</strong> Exception; <a name="39" href="#39">39</a> <a name="40" href="#40">40</a> <em class="jxr_javadoccomment">/**</em> <a name="41" href="#41">41</a> <em class="jxr_javadoccomment"> * Invoked when a service is idle.</em> <a name="42" href="#42">42</a> <em class="jxr_javadoccomment"> */</em> <a name="43" href="#43">43</a> <strong class="jxr_keyword">void</strong> serviceIdle(<a href="../../../../../org/apache/mina/core/service/IoService.html">IoService</a> service, <a href="../../../../../org/apache/mina/core/session/IdleStatus.html">IdleStatus</a> idleStatus) <strong class="jxr_keyword">throws</strong> Exception; <a name="44" href="#44">44</a> <a name="45" href="#45">45</a> <em class="jxr_javadoccomment">/**</em> <a name="46" href="#46">46</a> <em class="jxr_javadoccomment"> * Invoked when a service is deactivated by an {@link IoService}.</em> <a name="47" href="#47">47</a> <em class="jxr_javadoccomment"> *</em> <a name="48" href="#48">48</a> <em class="jxr_javadoccomment"> * @param service the {@link IoService}</em> <a name="49" href="#49">49</a> <em class="jxr_javadoccomment"> */</em> <a name="50" href="#50">50</a> <strong class="jxr_keyword">void</strong> serviceDeactivated(<a href="../../../../../org/apache/mina/core/service/IoService.html">IoService</a> service) <strong class="jxr_keyword">throws</strong> Exception; <a name="51" href="#51">51</a> <a name="52" href="#52">52</a> <em class="jxr_javadoccomment">/**</em> <a name="53" href="#53">53</a> <em class="jxr_javadoccomment"> * Invoked when a new session is created by an {@link IoService}.</em> <a name="54" href="#54">54</a> <em class="jxr_javadoccomment"> *</em> <a name="55" href="#55">55</a> <em class="jxr_javadoccomment"> * @param session the new session</em> <a name="56" href="#56">56</a> <em class="jxr_javadoccomment"> */</em> <a name="57" href="#57">57</a> <strong class="jxr_keyword">void</strong> sessionCreated(<a href="../../../../../org/apache/mina/core/session/IoSession.html">IoSession</a> session) <strong class="jxr_keyword">throws</strong> Exception; <a name="58" href="#58">58</a> <a name="59" href="#59">59</a> <em class="jxr_javadoccomment">/**</em> <a name="60" href="#60">60</a> <em class="jxr_javadoccomment"> * Invoked when a session is being destroyed by an {@link IoService}.</em> <a name="61" href="#61">61</a> <em class="jxr_javadoccomment"> *</em> <a name="62" href="#62">62</a> <em class="jxr_javadoccomment"> * @param session the session to be destroyed</em> <a name="63" href="#63">63</a> <em class="jxr_javadoccomment"> */</em> <a name="64" href="#64">64</a> <strong class="jxr_keyword">void</strong> sessionDestroyed(<a href="../../../../../org/apache/mina/core/session/IoSession.html">IoSession</a> session) <strong class="jxr_keyword">throws</strong> Exception; <a name="65" href="#65">65</a> } </pre> <hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body> </html>
{ "content_hash": "fad1202f505416817e8520c8e44a20fc", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 333, "avg_line_length": 94.19672131147541, "alnum_prop": 0.6350504698920989, "repo_name": "sardine/mina-ja", "id": "6ea9155dea6a2bc9916de5639f15ff36b9b561c4", "size": "7733", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/xref/org/apache/mina/core/service/IoServiceListener.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2917667" } ], "symlink_target": "" }
<div align="center"> <h1>⚠️ Archived</h1> <p>This repository is archived and is no longer maintained.</p> <p>For the latest Keystone release please visit <a href="https://keystonejs.com">the Keystone website.</a></p> <hr> </div> <br> # generator-keystone-react > [Yeoman](http://yeoman.io) generator Builds a simple scaffold for a KeystoneJS + React project, using browserify to pull it all together. ## Getting Started ```bash npm install -g yo ``` ### Yeoman Generators To install generator-keystone-react from npm, run: ```bash npm install -g generator-keystone-react ``` Finally, initiate the generator: ```bash yo keystone-react ``` ## License [MIT License](http://en.wikipedia.org/wiki/MIT_License). Copyright (c) 2016 Jed Watson.
{ "content_hash": "119126fb339e03803accc9f74304055f", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 112, "avg_line_length": 19.46153846153846, "alnum_prop": 0.7075098814229249, "repo_name": "keystonejs/generator-keystone-react", "id": "e076f247e0f242c81fb6cfbb14e75b00328724dd", "size": "763", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20" }, { "name": "HTML", "bytes": "572" }, { "name": "JavaScript", "bytes": "5188" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_60) on Sun Sep 27 09:02:05 EDT 2015 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>net.ljcomputing.people Class Hierarchy (LJ Computing - Contacts 1.0.0-SNAPSHOT API)</title> <meta name="date" content="2015-09-27"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="net.ljcomputing.people Class Hierarchy (LJ Computing - Contacts 1.0.0-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div style='background:#eeeeef;font-size:8pt;font-family:'DejaVu Sans',Arial,Helvetica,sans-serif;text-align:left;margin-left:25px;margin-right:25px;padding:8px 3px 3px 7px;'> <p>Copyright 2014-2015, James G. Willmore, <a href="http://ljcomputing.net">LJ Computing</a></p> <p>Licensed under the Apache License, Version 2.0 (the "License");</br> you may not use this file except in compliance with the License. You may obtain a copy of the License at <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> <p>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.</p> </div> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li><a href="../../../net/ljcomputing/people/domain/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?net/ljcomputing/people/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package net.ljcomputing.people</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">net.ljcomputing.people.<a href="../../../net/ljcomputing/people/PeopleApplication.html" title="class in net.ljcomputing.people"><span class="typeNameLink">PeopleApplication</span></a> (implements org.springframework.boot.CommandLineRunner)</li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li><a href="../../../net/ljcomputing/people/domain/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?net/ljcomputing/people/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2015 <a href="http://ljcomputing.net/">LJ Computing</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "7fa910105ac1aafae53db559a8fd7f20", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 971, "avg_line_length": 42.27142857142857, "alnum_prop": 0.644136532612369, "repo_name": "willmorejg/net.ljcomputing.ecsr", "id": "8e7e85439cbf2ec054ae570683c381ba44f2a763", "size": "5918", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "net.ljcomputing.people/docs/javadoc/apidocs/net/ljcomputing/people/package-tree.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "319856" }, { "name": "HTML", "bytes": "27620" }, { "name": "Java", "bytes": "334147" }, { "name": "JavaScript", "bytes": "71102" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; namespace Samurai.Graphics.Sprites { public sealed partial class TextureFont : DisposableObject { public const string DefaultFontName = "Unknown"; public const int DefaultFontSize = 12; public const int DefaultCharacterSpacing = 2; public const int DefaultLineSpacing = 0; private static readonly char[] CharsToExclude = new char[] { '\r' }; IDictionary<char, Rectangle> rectangles; public Texture2D Texture { get; private set; } public int LineHeight { get; private set; } public string FontName { get; private set; } public int FontSize { get; private set; } /// <summary> /// The amount of space to use between each character when rendering a string. /// </summary> public int CharacterSpacing { get; set; } /// <summary> /// The amount of space to use between each line when rendering a string. /// </summary> public int LineSpacing { get; set; } public Rectangle this[char ch] { get { return this.rectangles[ch]; } } /// <summary> /// Constructor. /// </summary> /// <param name="texture">The texture used by the font.</param> /// <param name="rectangles">Dictionary of characters to rectangles.</param> public TextureFont(Texture2D texture, IDictionary<char, Rectangle> rectangles) { if (texture == null) throw new ArgumentNullException("texture"); if (rectangles == null) throw new ArgumentNullException("rectangles"); this.Texture = texture; this.rectangles = rectangles; this.CharacterSpacing = DefaultCharacterSpacing; this.LineSpacing = DefaultLineSpacing; foreach (Rectangle rectangle in this.rectangles.Values) if (rectangle.Height > this.LineHeight) this.LineHeight = rectangle.Height; } protected override void DisposeManagedResources() { this.Texture.Dispose(); } /// <summary> /// Returns true if the TextureFont can render the given character. /// </summary> /// <param name="ch"></param> /// <returns></returns> public bool ContainsCharacter(char ch) { return this.rectangles.ContainsKey(ch); } /// <summary> /// Measures the given string. /// </summary> /// <param name="s"></param> /// <returns></returns> public Size MeasureString(string s) { return this.MeasureString(s, 0, s.Length); } /// <summary> /// Measures the size of the string. /// </summary> /// <param name="s"></param> /// <param name="start">The index of the string at which to start measuring.</param> /// <param name="length">How many characters to measure from the start.</param> /// <returns></returns> public Size MeasureString(string s, int start, int length) { if (start < 0 || start > s.Length) throw new ArgumentOutOfRangeException("start", "Start is not an index within the string."); if (length < 0) throw new ArgumentOutOfRangeException("length", "Length must me >= 0."); if (start + length > s.Length) throw new ArgumentOutOfRangeException("length", "Start + length is greater than the string's length."); Size size = Size.Zero; size.Height = this.LineHeight; int lineWidth = 0; for (int i = start; i < length; i++) { if (s[i] == '\n') { if (lineWidth > size.Width) size.Width = lineWidth; lineWidth = 0; size.Height += this.LineHeight + this.LineSpacing; } else if (!CharsToExclude.Contains(s[i])) { lineWidth += this.rectangles[s[i]].Width + this.CharacterSpacing; } } if (lineWidth > size.Width) size.Width = lineWidth; return size; } } }
{ "content_hash": "26eeab9c9844d2ffb443f12cb7738b43", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 107, "avg_line_length": 22.641975308641975, "alnum_prop": 0.6543075245365322, "repo_name": "smack0007/Samurai", "id": "9c417756d92484e4cb20978345f517ccbbc8dfd4", "size": "3670", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Samurai.Graphics/Sprites/TextureFont.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "378" }, { "name": "C#", "bytes": "350379" }, { "name": "GLSL", "bytes": "5186" } ], "symlink_target": "" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdlib.h> #ifdef _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #if __linux__ #include <glib.h> #endif #include <string.h> #include "azure_c_shared_utility/constmap.h" #include "azure_c_shared_utility/gballoc.h" #include "azure_c_shared_utility/gb_time.h" #include "azure_c_shared_utility/buffer_.h" #include "azure_c_shared_utility/strings.h" #include "azure_c_shared_utility/base64.h" #include "azure_c_shared_utility/vector.h" #include "azure_c_shared_utility/map.h" #include "azure_c_shared_utility/xlogging.h" #include "azure_c_shared_utility/threadapi.h" #include "module.h" #include "message.h" #include "broker.h" #include "ble_gatt_io.h" #include "bleio_seq.h" #include "messageproperties.h" #include "ble_instr_utils.h" #include "ble_utils.h" #include "ble.h" #include <parson.h> DEFINE_ENUM_STRINGS(BLEIO_SEQ_INSTRUCTION_TYPE, BLEIO_SEQ_INSTRUCTION_TYPE_VALUES); typedef struct BLE_HANDLE_DATA_TAG { BROKER_HANDLE broker; BLE_DEVICE_CONFIG device_config; BLEIO_GATT_HANDLE bleio_gatt; BLEIO_SEQ_HANDLE bleio_seq; bool is_connected; bool is_destroy_complete; #if __linux__ GMainLoop* main_loop; THREAD_HANDLE event_thread; #endif }BLE_HANDLE_DATA; // how long to wait for a destroy complete callback to be invoked // in microseconds #define DESTROY_COMPLETE_TIMEOUT (1000000 * 5) static void on_connect_complete( BLEIO_GATT_HANDLE bleio_gatt_handle, void* context, BLEIO_GATT_CONNECT_RESULT connect_result ); static void on_disconnect_complete( BLEIO_GATT_HANDLE bleio_gatt_handle, void* context ); static void on_read_complete( BLEIO_SEQ_HANDLE bleio_seq_handle, void* context, const char* characteristic_uuid, BLEIO_SEQ_INSTRUCTION_TYPE type, BLEIO_SEQ_RESULT result, BUFFER_HANDLE data ); static void on_write_complete( BLEIO_SEQ_HANDLE bleio_seq_handle, void* context, const char* characteristic_uuid, BLEIO_SEQ_INSTRUCTION_TYPE type, BLEIO_SEQ_RESULT result ); static VECTOR_HANDLE ble_instr_to_bleioseq_instr( BLE_HANDLE_DATA* module, VECTOR_HANDLE source_instructions ); #if __linux__ // how long to wait for a event dispatcher thread to start up #define EVENT_DISPATCHER_START_TIMEOUT (G_USEC_PER_SEC * 5) static bool init_glib_loop( BLE_HANDLE_DATA* handle_data ); static int event_dispatcher( void * user_data ); static bool terminate_event_dispatcher( BLE_HANDLE_DATA* handle_data ); #endif static void free_bleioseq_instr(VECTOR_HANDLE instructions) { size_t len = VECTOR_size(instructions); for (size_t i = 0; i < len; ++i) { BLEIO_SEQ_INSTRUCTION* instr = (BLEIO_SEQ_INSTRUCTION*)VECTOR_element(instructions, i); // free string handle for the characteristic uuid if (instr->characteristic_uuid != NULL) { STRING_delete(instr->characteristic_uuid); } if((instr->instruction_type == WRITE_AT_INIT || instr->instruction_type == WRITE_AT_EXIT || instr->instruction_type == WRITE_ONCE) && instr->data.buffer != NULL) { BUFFER_delete(instr->data.buffer); } } } static MODULE_HANDLE BLE_Create(BROKER_HANDLE broker, const void* configuration) { BLE_HANDLE_DATA* result; BLE_CONFIG* config = (BLE_CONFIG*)configuration; /*Codes_SRS_BLE_13_001: [BLE_Create shall return NULL if broker is NULL.]*/ /*Codes_SRS_BLE_13_002: [BLE_Create shall return NULL if configuration is NULL.]*/ /*Codes_SRS_BLE_13_003: [BLE_Create shall return NULL if configuration->instructions is NULL.]*/ /*Codes_SRS_BLE_13_004: [BLE_Create shall return NULL if the configuration->instructions vector is empty(size is zero).]*/ if ( broker == NULL || configuration == NULL || config->instructions == NULL || VECTOR_size(config->instructions) == 0 ) { LogError("Invalid input"); result = NULL; } else { /*Codes_SRS_BLE_13_009: [ BLE_Create shall allocate memory for an instance of the BLE_HANDLE_DATA structure and use that as the backing structure for the module handle. ]*/ result = (BLE_HANDLE_DATA*)malloc(sizeof(BLE_HANDLE_DATA)); if (result == NULL) { /*Codes_SRS_BLE_13_005: [ BLE_Create shall return NULL if an underlying API call fails. ]*/ LogError("malloc failed"); /* result is already NULL */ } else { /*Codes_SRS_BLE_13_008: [ BLE_Create shall create and initialize the bleio_gatt field in the BLE_HANDLE_DATA object by calling BLEIO_gatt_create . ]*/ result->bleio_gatt = BLEIO_gatt_create(&(config->device_config)); if (result->bleio_gatt == NULL) { /*Codes_SRS_BLE_13_005: [ BLE_Create shall return NULL if an underlying API call fails. ]*/ LogError("BLEIO_gatt_create failed"); free(result); result = NULL; } else { // transform BLE_INSTRUCTION objects into BLEIO_SEQ_INSTRUCTION objects VECTOR_HANDLE instructions = ble_instr_to_bleioseq_instr(result, config->instructions); if (instructions == NULL) { /*Codes_SRS_BLE_13_005: [ BLE_Create shall return NULL if an underlying API call fails. ]*/ LogError("Converting BLE_INSTRUCTION objects into BLEIO_SEQ_INSTRUCTION objects failed"); BLEIO_gatt_destroy(result->bleio_gatt); free(result); result = NULL; } else { /*Codes_SRS_BLE_13_010: [ BLE_Create shall create and initialize the bleio_seq field in the BLE_HANDLE_DATA object by calling BLEIO_Seq_Create . ]*/ result->bleio_seq = BLEIO_Seq_Create( result->bleio_gatt, instructions, on_read_complete, on_write_complete ); if (result->bleio_seq == NULL) { /*Codes_SRS_BLE_13_005: [ BLE_Create shall return NULL if an underlying API call fails. ]*/ LogError("BLEIO_Seq_Create failed"); BLEIO_gatt_destroy(result->bleio_gatt); free_bleioseq_instr(instructions); VECTOR_destroy(instructions); free(result); result = NULL; } else { result->broker = broker; memcpy(&(result->device_config), &(config->device_config), sizeof(result->device_config)); result->is_destroy_complete = false; #if __linux__ if (init_glib_loop(result) == false) { LogError("init_glib_loop returned false"); BLEIO_Seq_Destroy(result->bleio_seq, NULL, NULL); free(result); result = NULL; } else { #endif /*Codes_SRS_BLE_13_011: [ BLE_Create shall asynchronously open a connection to the BLE device by calling BLEIO_gatt_connect . ]*/ result->is_connected = false; if (BLEIO_gatt_connect(result->bleio_gatt, on_connect_complete, (void*)result) != 0) { /*Codes_SRS_BLE_13_012: [ BLE_Create shall return NULL if BLEIO_gatt_connect returns a non-zero value. ]*/ LogError("BLEIO_gatt_connect failed"); #if __linux__ if (terminate_event_dispatcher(result) == false) { LogError("terminate_event_dispatcher returned false"); } #endif BLEIO_Seq_Destroy(result->bleio_seq, NULL, NULL); free(result); result = NULL; /** * We don't destroy handle_data->bleio_gatt because the handle is * 'owned' by the BLEIO sequence object and that will destroy the * GATT I/O object. */ } #if __linux__ } #endif } } } } } /*Codes_SRS_BLE_13_006: [ BLE_Create shall return a non- NULL MODULE_HANDLE when successful. ]*/ return (MODULE_HANDLE)result; } static MODULE_HANDLE BLE_CreateFromJson(BROKER_HANDLE broker, const char* configuration) { MODULE_HANDLE result; /*Codes_SRS_BLE_05_001: [ BLE_CreateFromJson shall return NULL if the broker or configuration parameters are NULL. ]*/ if( (broker == NULL) || (configuration == NULL) ) { LogError("NULL parameter detected broker=%p configuration=%p", broker, configuration); result = NULL; } else { JSON_Value* json = json_parse_string((const char*)configuration); if (json == NULL) { /*Codes_SRS_BLE_05_002: [ BLE_CreateFromJson shall return NULL if any of the underlying platform calls fail. ]*/ LogError("unable to json_parse_string"); result = NULL; } else { JSON_Object* root = json_value_get_object(json); if (root == NULL) { /*Codes_SRS_BLE_05_003: [ BLE_CreateFromJson shall return NULL if the JSON does not start with an object. ]*/ LogError("unable to json_value_get_object"); result = NULL; } else { // get controller index int controller_index = (int)json_object_get_number(root, "controller_index"); if (controller_index < 0) { /*Codes_SRS_BLE_05_005: [ BLE_CreateFromJson shall return NULL if the controller_index value in the JSON is less than zero. ]*/ LogError("Invalid BLE controller index specified"); result = NULL; } else { const char* mac_address = json_object_get_string(root, "device_mac_address"); if (mac_address == NULL) { /*Codes_SRS_BLE_05_004: [ BLE_CreateFromJson shall return NULL if there is no device_mac_address property in the JSON. ]*/ LogError("json_object_get_string failed for property 'device_mac_address'"); result = NULL; } else { JSON_Array* instructions = json_object_get_array(root, "instructions"); if (instructions == NULL) { /*Codes_SRS_BLE_05_006: [ BLE_CreateFromJson shall return NULL if the instructions array does not exist in the JSON. ]*/ LogError("json_object_get_array failed for property 'instructions'"); result = NULL; } else { VECTOR_HANDLE ble_instructions = parse_instructions(instructions); if (ble_instructions == NULL) { LogError("parse_instructions returned NULL"); result = NULL; } else { BLE_CONFIG ble_config; if (parse_mac_address( mac_address, &(ble_config.device_config.device_addr) ) == false) { /*Codes_SRS_BLE_05_013: [ BLE_CreateFromJson shall return NULL if the device_mac_address property's value is not a well-formed MAC address. ]*/ LogError("parse_mac_address returned false"); result = NULL; } else { ble_config.device_config.ble_controller_index = controller_index; ble_config.instructions = ble_instructions; /*Codes_SRS_BLE_05_014: [ BLE_CreateFromJson shall call the underlying module's 'create' function. ]*/ result = BLE_Create( broker, (const void*)&ble_config ); if (result == NULL) { /*Codes_SRS_BLE_05_022: [ BLE_CreateFromJson shall return NULL if calling the underlying module's create function fails. ]*/ LogError("Unable to create BLE low level module"); } } } free_instructions(ble_instructions); VECTOR_destroy(ble_instructions); } } } } json_value_free(json); } } /*Codes_SRS_BLE_05_023: [ BLE_CreateFromJson shall return a non-NULL handle if calling the underlying module's create function succeeds. ]*/ return result; } #if __linux__ static bool init_glib_loop(BLE_HANDLE_DATA* handle_data) { bool result; handle_data->main_loop = g_main_loop_new(NULL, FALSE); if (handle_data->main_loop == NULL) { LogError("g_main_loop_new returned NULL"); result = false; } else { // start a thread to pump the message loop if (ThreadAPI_Create( &(handle_data->event_thread), event_dispatcher, (void*)handle_data ) != THREADAPI_OK) { LogError("ThreadAPI_Create failed"); g_main_loop_unref(handle_data->main_loop); result = false; } else { result = true; } } return result; } static int event_dispatcher(void * user_data) { BLE_HANDLE_DATA* handle_data = (BLE_HANDLE_DATA*)user_data; g_main_loop_run(handle_data->main_loop); g_main_loop_unref(handle_data->main_loop); return 0; } static bool terminate_event_dispatcher(BLE_HANDLE_DATA* handle_data) { bool result; gint64 start_time = g_get_monotonic_time(); if (handle_data->main_loop != NULL) { GMainContext* loop_context = g_main_loop_get_context(handle_data->main_loop); if (loop_context != NULL) { while ( (g_get_monotonic_time() - start_time) < EVENT_DISPATCHER_START_TIMEOUT && g_main_loop_is_running(handle_data->main_loop) == FALSE ) { // wait for quarter of a second g_usleep(G_USEC_PER_SEC / 4); } if (g_main_loop_is_running(handle_data->main_loop) == TRUE) { g_main_loop_quit(handle_data->main_loop); result = true; } else { LogError("Timed out waiting for event dispatcher thread to initialize."); result = false; } } else { LogError("g_main_loop_get_context returned NULL"); result = false; } } else { LogError("No GLIB loop to terminate."); result = false; } return result; } #endif static VECTOR_HANDLE ble_instr_to_bleioseq_instr(BLE_HANDLE_DATA* module, VECTOR_HANDLE source_instructions) { VECTOR_HANDLE result = VECTOR_create(sizeof(BLEIO_SEQ_INSTRUCTION)); if (result != NULL) { size_t i, len = VECTOR_size(source_instructions); for (i = 0; i < len; ++i) { BLE_INSTRUCTION* src_instr = (BLE_INSTRUCTION*)VECTOR_element(source_instructions, i); // copy the data BLEIO_SEQ_INSTRUCTION instr; instr.instruction_type = src_instr->instruction_type; instr.characteristic_uuid = STRING_clone(src_instr->characteristic_uuid); memcpy(&(instr.data), &(src_instr->data), sizeof(instr.data)); instr.context = (void*)module; if (VECTOR_push_back(result, &instr, 1) != 0) { LogError("VECTOR_push_back failed"); STRING_delete(instr.characteristic_uuid); break; } } // if the loop terminated before all elements were processed, // then something went wrong if (i < len) { VECTOR_destroy(result); result = NULL; } } else { LogError("VECTOR_create failed"); } return result; } static void on_connect_complete( BLEIO_GATT_HANDLE bleio_gatt_handle, void* context, BLEIO_GATT_CONNECT_RESULT connect_result ) { // this MUST NOT be NULL BLE_HANDLE_DATA* handle_data = (BLE_HANDLE_DATA*)context; if (connect_result != BLEIO_GATT_CONNECT_OK) { LogError("BLEIO_gatt_connect asynchronously failed"); } else { handle_data->is_connected = true; /*Codes_SRS_BLE_13_014: [ If the asynchronous call to BLEIO_gatt_connect is successful then the BLEIO_Seq_Run function shall be called on the bleio_seq field from BLE_HANDLE_DATA . ]*/ if (BLEIO_Seq_Run(handle_data->bleio_seq) != BLEIO_SEQ_OK) { LogError("BLEIO_Seq_Run failed"); } } } static int format_timestamp(char* dest, size_t dest_size) { int result; time_t t1 = time(NULL); if (t1 == (time_t)-1) { LogError("time() failed"); result = __LINE__; } else { struct tm* t2 = localtime(&t1); if (t2 == NULL) { LogError("localtime() failed"); result = __LINE__; } else { /** * Note: We record the time only with a granularity of seconds. We * may want to increase this to include milliseconds. */ if (strftime(dest, dest_size, "%Y:%m:%dT%H:%M:%S", t2) == 0) { LogError("strftime() failed"); result = __LINE__; } else { result = 0; } } } return result; } static void on_read_complete( BLEIO_SEQ_HANDLE bleio_seq_handle, void* context, const char* characteristic_uuid, BLEIO_SEQ_INSTRUCTION_TYPE type, BLEIO_SEQ_RESULT result, BUFFER_HANDLE data ) { // this MUST NOT be NULL BLE_HANDLE_DATA* handle_data = (BLE_HANDLE_DATA*)context; if (result != BLEIO_SEQ_OK) { LogError("A read instruction for characteristic %s of type %s failed.", characteristic_uuid, ENUM_TO_STRING(BLEIO_SEQ_INSTRUCTION_TYPE, type)); } else { MAP_HANDLE message_properties = Map_Create(NULL); if (message_properties == NULL) { LogError("Map_Create() failed"); } else { // format BLE controller index char ble_controller_index[80]; int ret = snprintf(ble_controller_index, sizeof(ble_controller_index) / sizeof(ble_controller_index[0]), "%d", handle_data->device_config.ble_controller_index ); if(ret < 0 || ret >= (sizeof(ble_controller_index) / sizeof(ble_controller_index[0]))) { LogError("snprintf() failed"); } else { // format MAC address char mac_address[18] = ""; ret = snprintf( mac_address, sizeof(mac_address) / sizeof(mac_address[0]), "%02X:%02X:%02X:%02X:%02X:%02X", handle_data->device_config.device_addr.address[0], handle_data->device_config.device_addr.address[1], handle_data->device_config.device_addr.address[2], handle_data->device_config.device_addr.address[3], handle_data->device_config.device_addr.address[4], handle_data->device_config.device_addr.address[5] ); if (ret < 0 || ret >= (sizeof(mac_address) / sizeof(mac_address[0]))) { LogError("snprintf() failed"); } else { // format timestamp char timestamp[25] = ""; if (format_timestamp(timestamp, sizeof(timestamp) / sizeof(timestamp[0])) != 0) { LogError("format_timestamp() failed"); } else if (Map_Add(message_properties, GW_BLE_CONTROLLER_INDEX_PROPERTY, ble_controller_index) != MAP_OK) { LogError("Map_Add() failed for property %s", GW_BLE_CONTROLLER_INDEX_PROPERTY); } else if (Map_Add(message_properties, GW_MAC_ADDRESS_PROPERTY, mac_address) != MAP_OK) { LogError("Map_Add() failed for property %s", GW_MAC_ADDRESS_PROPERTY); } else if (Map_Add(message_properties, GW_TIMESTAMP_PROPERTY, timestamp) != MAP_OK) { LogError("Map_Add() failed for property %s", GW_TIMESTAMP_PROPERTY); } else if (Map_Add(message_properties, GW_CHARACTERISTIC_UUID_PROPERTY, characteristic_uuid) != MAP_OK) { LogError("Map_Add() failed for property %s", GW_CHARACTERISTIC_UUID_PROPERTY); } else if (Map_Add(message_properties, GW_SOURCE_PROPERTY, GW_SOURCE_BLE_TELEMETRY) != MAP_OK) { LogError("Map_Add() failed for property %s", GW_SOURCE_PROPERTY); } else { MESSAGE_CONFIG message_config; message_config.sourceProperties = message_properties; message_config.size = BUFFER_length(data); // "data" MUST NOT be NULL here message_config.source = (const unsigned char*)BUFFER_u_char(data); MESSAGE_HANDLE message = Message_Create(&message_config); if (message == NULL) { LogError("Message_Create() failed"); } else { /*Codes_SRS_BLE_13_019: [BLE_Create shall handle the ON_BLEIO_SEQ_READ_COMPLETE callback on the BLE I/O sequence. If the call is successful then a new message shall be published on the message broker with the buffer that was read as the content of the message along with the following properties: | Property Name | Description | |-------------------------|---------------------------------------------------------------| | ble_controller_index | The index of the bluetooth radio hardware on the device. | | mac_address | MAC address of the BLE device from which the data was read. | | timestamp | Timestamp indicating when the data was read. | | source | This property will always have the value `bleTelemetry`. | ]*/ if (Broker_Publish(handle_data->broker, (MODULE_HANDLE)handle_data, message) != BROKER_OK) { LogError("Broker_Publish() failed"); } Message_Destroy(message); } } Map_Destroy(message_properties); } } } } BUFFER_delete(data); } void on_write_complete( BLEIO_SEQ_HANDLE bleio_seq_handle, void * context, const char * characteristic_uuid, BLEIO_SEQ_INSTRUCTION_TYPE type, BLEIO_SEQ_RESULT result ) { // this MUST NOT be NULL BLE_HANDLE_DATA* handle_data = (BLE_HANDLE_DATA*)context; if (result != BLEIO_SEQ_OK) { // format MAC address char mac_address[18]; snprintf( mac_address, sizeof(mac_address) / sizeof(mac_address[0]), "%02X:%02X:%02X:%02X:%02X:%02X", handle_data->device_config.device_addr.address[0], handle_data->device_config.device_addr.address[1], handle_data->device_config.device_addr.address[2], handle_data->device_config.device_addr.address[3], handle_data->device_config.device_addr.address[4], handle_data->device_config.device_addr.address[5] ); LogError( "Write instruction of type %s for device %s on BLE controller %d for characteristic %s failed", ENUM_TO_STRING(BLEIO_SEQ_INSTRUCTION_TYPE, type), mac_address, handle_data->device_config.ble_controller_index, characteristic_uuid ); } } static bool is_message_for_module(const char* mac_address_str, BLE_HANDLE_DATA* handle_data) { bool result; BLE_MAC_ADDRESS mac_address; result = parse_mac_address(mac_address_str, &mac_address); if (result == true) { /*Codes_SRS_BLE_13_022: [ BLE_Receive shall ignore the message unless the 'macAddress' property matches the MAC address that was passed to this module when it was created. ]*/ // check if the mac address matches this module's mac address if (memcmp(&handle_data->device_config.device_addr, &mac_address, sizeof(BLE_MAC_ADDRESS)) == 0) { result = true; } else { result = false; } } else { LogError("Invalid mac address"); } return result; } static void BLE_Receive(MODULE_HANDLE module, MESSAGE_HANDLE message) { /*Codes_SRS_BLE_13_018: [ BLE_Receive shall do nothing if module is NULL or if message is NULL. ]*/ if (module != NULL && message != NULL) { BLE_HANDLE_DATA* handle_data = (BLE_HANDLE_DATA*)module; CONSTMAP_HANDLE properties = Message_GetProperties(message); /*Codes_SRS_BLE_13_020: [ BLE_Receive shall ignore all messages except those that have the following properties: >| Property Name | Description | >|-------------------------|-------------------------------------------------------------------------| >| source | This property should have the value "BLE". | >| macAddress | MAC address of the BLE device to which the data to should be written. | ]*/ // fetch the 'source' property const char* source = ConstMap_GetValue(properties, GW_SOURCE_PROPERTY); if (source != NULL && strcmp(source, GW_SOURCE_BLE_COMMAND) == 0) { // fetch the 'macAddress' property const char* mac_address = ConstMap_GetValue(properties, GW_MAC_ADDRESS_PROPERTY); if (mac_address != NULL && is_message_for_module(mac_address, handle_data) == true) { const CONSTBUFFER* content = Message_GetContent(message); if (content != NULL && content->buffer != NULL && content->size > 0) { BLE_INSTRUCTION* ble_instruction = (BLE_INSTRUCTION*)content->buffer; // transform BLE_INSTRUCTION into BLEIO_SEQ_INSTRUCTION BLEIO_SEQ_INSTRUCTION ble_seq_instruction; ble_seq_instruction.instruction_type = ble_instruction->instruction_type; ble_seq_instruction.characteristic_uuid = ble_instruction->characteristic_uuid; memcpy(&(ble_seq_instruction.data), &(ble_instruction->data), sizeof(ble_instruction->data)); // MUST set this as the context so on_read_complete and on_write_complete get // access to BLE_HANDLE_DATA ble_seq_instruction.context = (void*)module; /*Codes_SRS_BLE_13_021: [ BLE_Receive shall treat the content of the message as a BLE_INSTRUCTION and schedule it for execution by calling BLEIO_Seq_AddInstruction. ]*/ if (BLEIO_Seq_AddInstruction(handle_data->bleio_seq, &ble_seq_instruction) != BLEIO_SEQ_OK) { LogError("BLEIO_Seq_AddInstruction failed"); } } } } ConstMap_Destroy(properties); } else { LogError("module and/or message is NULL"); } } static void on_destroy_complete(BLEIO_SEQ_HANDLE bleio_seq_handle, void* context) { BLE_HANDLE_DATA* handle_data = (BLE_HANDLE_DATA*)context; if (handle_data != NULL) { handle_data->is_destroy_complete = true; if (handle_data->bleio_gatt != NULL) { // if the device is connected then first disconnect if (handle_data->is_connected) { BLEIO_gatt_disconnect(handle_data->bleio_gatt, NULL, NULL); } /** * We don't destroy handle_data->bleio_gatt because the handle is * 'owned' by the BLEIO sequence object and that will destroy the * GATT I/O object. */ } } else { LogError("bleio_seq_handle is NULL"); } } static void BLE_Destroy(MODULE_HANDLE module) { /*Codes_SRS_BLE_13_016: [If module is NULL BLE_Destroy shall do nothing.]*/ if (module != NULL) { /*Codes_SRS_BLE_13_017: BLE_Destroy shall free all resources. ]*/ BLE_HANDLE_DATA* handle_data = (BLE_HANDLE_DATA*)module; if (handle_data->bleio_seq != NULL) { BLEIO_Seq_Destroy ( handle_data->bleio_seq, on_destroy_complete, (void*)handle_data ); #if __linux__ // wait for on_destroy_complete to be called; bail after 5 seconds gint64 start_time = g_get_monotonic_time(); if (handle_data->main_loop != NULL) { GMainContext* loop_context = g_main_loop_get_context(handle_data->main_loop); if (loop_context != NULL) { LogInfo("Waiting for sequence to be destroyed..."); while (handle_data->is_destroy_complete == false) { g_main_context_iteration(loop_context, FALSE); if ((g_get_monotonic_time() - start_time) >= DESTROY_COMPLETE_TIMEOUT) { LogError("on_destroy_complete did not get called in time"); break; } } LogInfo("Done waiting for sequence to be destroyed."); } else { LogError("g_main_loop_get_context returned NULL"); } // terminate glib loop g_main_loop_quit(handle_data->main_loop); // wait for thread to exit int thread_result; if (ThreadAPI_Join(handle_data->event_thread, &thread_result) != THREADAPI_OK) { LogError("ThreadAPI_Join() returned an error"); } } #endif } free(handle_data); } else { LogError("module handle is NULL"); } } static const MODULE_API_1 Module_GetApi_Impl = { {MODULE_API_VERSION_1}, BLE_CreateFromJson, BLE_Create, BLE_Destroy, BLE_Receive, NULL }; /*Codes_SRS_BLE_26_001: [ `Module_GetApi` return a pointer to a `MODULE_API` structure. ]*/ #ifdef BUILD_MODULE_TYPE_STATIC MODULE_EXPORT const MODULE_API* MODULE_STATIC_GETAPI(BLE_MODULE)(const MODULE_API_VERSION gateway_api_version) #else MODULE_EXPORT const MODULE_API* Module_GetApi(const MODULE_API_VERSION gateway_api_version) #endif { (void)gateway_api_version; return (const MODULE_API*)&Module_GetApi_Impl; }
{ "content_hash": "17a18b6c717cd7b87400a095c05b7c9f", "timestamp": "", "source": "github", "line_count": 905, "max_line_length": 324, "avg_line_length": 37.702762430939224, "alnum_prop": 0.5121186366167463, "repo_name": "yaweiw/azure-iot-gateway-sdk", "id": "74860cafaed2393fcccf7d7defe5534a51f0be86", "size": "34121", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/ble/src/ble.c", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1483" }, { "name": "C", "bytes": "1435321" }, { "name": "C#", "bytes": "118865" }, { "name": "C++", "bytes": "1874229" }, { "name": "CMake", "bytes": "58382" }, { "name": "Java", "bytes": "29470" }, { "name": "Objective-C", "bytes": "1121" }, { "name": "Shell", "bytes": "1248" } ], "symlink_target": "" }
daeElementRef domAxis::create(DAE& dae) { domAxisRef ref = new domAxis(dae); return ref; } daeMetaElement * domAxis::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "axis" ); meta->registerClass(domAxis::create); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaArrayAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("Float3")); ma->setOffset( daeOffsetOf( domAxis , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } // Add attribute: sid { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "sid" ); ma->setType( dae.getAtomicTypes().get("Sid")); ma->setOffset( daeOffsetOf( domAxis , attrSid )); ma->setContainer( meta ); meta->appendAttribute(ma); } // Add attribute: name { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "name" ); ma->setType( dae.getAtomicTypes().get("xsToken")); ma->setOffset( daeOffsetOf( domAxis , attrName )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domAxis)); meta->validate(); return meta; }
{ "content_hash": "3348098f72bc1dc58a0598af0c4a5835", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 52, "avg_line_length": 21.596491228070175, "alnum_prop": 0.6718115353371243, "repo_name": "veter-team/daeview", "id": "a7f074cd630835d7b09e2419a2ee7d258a4d2538", "size": "1494", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/collada-dom/1.5/dom/domAxis.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2402158" }, { "name": "C++", "bytes": "8792611" }, { "name": "Objective-C", "bytes": "100424" }, { "name": "Python", "bytes": "949" } ], "symlink_target": "" }
<?php /* Unsafe sample input : reads the field UserData from the variable $_GET sanitize : none construction : use of sprintf via a %s with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_GET['UserData']; //no_sanitizing $query = sprintf("(&(objectCategory=person)(objectClass=user)(cn='%s'))", $tainted); //flaw $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
{ "content_hash": "fc117a3815750d7eb95b8d537e8b9c64", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 84, "avg_line_length": 23.385964912280702, "alnum_prop": 0.7569392348087022, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "ae9e31ea46d0980c1d41a714e446e13687ae4f7f", "size": "1333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_90/unsafe/CWE_90__GET__no_sanitizing__userByCN-sprintf_%s_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
// // JSONKit.m // http://github.com/johnezang/JSONKit // Dual licensed under either the terms of the BSD License, or alternatively // under the terms of the Apache License, Version 2.0, as specified below. // /* Copyright 2011 John Engelhart 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. */ /* Acknowledgments: The bulk of the UTF8 / UTF32 conversion and verification comes from ConvertUTF.[hc]. It has been modified from the original sources. The original sources were obtained from http://www.unicode.org/. However, the web site no longer seems to host the files. Instead, the Unicode FAQ http://www.unicode.org/faq//utf_bom.html#gen4 points to International Components for Unicode (ICU) http://site.icu-project.org/ as an example of how to write a UTF converter. The decision to use the ConvertUTF.[ch] code was made to leverage "proven" code. Hopefully the local modifications are bug free. The code in isValidCodePoint() is derived from the ICU code in utf.h for the macros U_IS_UNICODE_NONCHAR and U_IS_UNICODE_CHAR. From the original ConvertUTF.[ch]: * Copyright 2001-2004 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <sys/errno.h> #include <math.h> #include <limits.h> #include <objc/runtime.h> #import "JSONKit.h" //#include <CoreFoundation/CoreFoundation.h> #include <CoreFoundation/CFString.h> #include <CoreFoundation/CFArray.h> #include <CoreFoundation/CFDictionary.h> #include <CoreFoundation/CFNumber.h> //#import <Foundation/Foundation.h> #import <Foundation/NSArray.h> #import <Foundation/NSAutoreleasePool.h> #import <Foundation/NSData.h> #import <Foundation/NSDictionary.h> #import <Foundation/NSException.h> #import <Foundation/NSNull.h> #import <Foundation/NSObjCRuntime.h> #ifndef __has_feature #define __has_feature(x) 0 #endif #ifdef JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS #warning As of JSONKit v1.4, JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS is no longer required. It is no longer a valid option. #endif #ifdef __OBJC_GC__ #error JSONKit does not support Objective-C Garbage Collection #endif #if __has_feature(objc_arc) #error JSONKit does not support Objective-C Automatic Reference Counting (ARC) #endif // The following checks are really nothing more than sanity checks. // JSONKit technically has a few problems from a "strictly C99 conforming" standpoint, though they are of the pedantic nitpicking variety. // In practice, though, for the compilers and architectures we can reasonably expect this code to be compiled for, these pedantic nitpicks aren't really a problem. // Since we're limited as to what we can do with pre-processor #if checks, these checks are not nearly as through as they should be. #if (UINT_MAX != 0xffffffffU) || (INT_MIN != (-0x7fffffff-1)) || (ULLONG_MAX != 0xffffffffffffffffULL) || (LLONG_MIN != (-0x7fffffffffffffffLL-1LL)) #error JSONKit requires the C 'int' and 'long long' types to be 32 and 64 bits respectively. #endif #if !defined(__LP64__) && ((UINT_MAX != ULONG_MAX) || (INT_MAX != LONG_MAX) || (INT_MIN != LONG_MIN) || (WORD_BIT != LONG_BIT)) #error JSONKit requires the C 'int' and 'long' types to be the same on 32-bit architectures. #endif // Cocoa / Foundation uses NS*Integer as the type for a lot of arguments. We make sure that NS*Integer is something we are expecting and is reasonably compatible with size_t / ssize_t #if (NSUIntegerMax != ULONG_MAX) || (NSIntegerMax != LONG_MAX) || (NSIntegerMin != LONG_MIN) #error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'long' type. #endif #if (NSUIntegerMax != SIZE_MAX) || (NSIntegerMax != SSIZE_MAX) #error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'size_t' type. #endif // For DJB hash. #define JK_HASH_INIT (1402737925UL) // Use __builtin_clz() instead of trailingBytesForUTF8[] table lookup. #define JK_FAST_TRAILING_BYTES // JK_CACHE_SLOTS must be a power of 2. Default size is 1024 slots. #define JK_CACHE_SLOTS_BITS (10) #define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS) // JK_CACHE_PROBES is the number of probe attempts. #define JK_CACHE_PROBES (4UL) // JK_INIT_CACHE_AGE must be < (1 << AGE) - 1, where AGE is sizeof(typeof(AGE)) * 8. #define JK_INIT_CACHE_AGE (0) // JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes) #define JK_TOKENBUFFER_SIZE (1024UL * 2UL) // JK_STACK_OBJS is the default number of spaces reserved on the stack for temporarily storing pointers to Obj-C objects before they can be transferred to a NSArray / NSDictionary. #define JK_STACK_OBJS (1024UL * 1UL) #define JK_JSONBUFFER_SIZE (1024UL * 4UL) #define JK_UTF8BUFFER_SIZE (1024UL * 16UL) #define JK_ENCODE_CACHE_SLOTS (1024UL) #if defined (__GNUC__) && (__GNUC__ >= 4) #define JK_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__)) #define JK_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect)) #define JK_EXPECT_T(cond) JK_EXPECTED(cond, 1U) #define JK_EXPECT_F(cond) JK_EXPECTED(cond, 0U) #define JK_PREFETCH(ptr) __builtin_prefetch(ptr) #else // defined (__GNUC__) && (__GNUC__ >= 4) #define JK_ATTRIBUTES(attr, ...) #define JK_EXPECTED(cond, expect) (cond) #define JK_EXPECT_T(cond) (cond) #define JK_EXPECT_F(cond) (cond) #define JK_PREFETCH(ptr) #endif // defined (__GNUC__) && (__GNUC__ >= 4) #define JK_STATIC_INLINE static __inline__ JK_ATTRIBUTES(always_inline) #define JK_ALIGNED(arg) JK_ATTRIBUTES(aligned(arg)) #define JK_UNUSED_ARG JK_ATTRIBUTES(unused) #define JK_WARN_UNUSED JK_ATTRIBUTES(warn_unused_result) #define JK_WARN_UNUSED_CONST JK_ATTRIBUTES(warn_unused_result, const) #define JK_WARN_UNUSED_PURE JK_ATTRIBUTES(warn_unused_result, pure) #define JK_WARN_UNUSED_SENTINEL JK_ATTRIBUTES(warn_unused_result, sentinel) #define JK_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__)) #define JK_WARN_UNUSED_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__)) #define JK_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__)) #define JK_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__)) #if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) #define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as)) #else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) #define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__)) #endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3) @class JKArray, JKDictionaryEnumerator, JKDictionary; enum { JSONNumberStateStart = 0, JSONNumberStateFinished = 1, JSONNumberStateError = 2, JSONNumberStateWholeNumberStart = 3, JSONNumberStateWholeNumberMinus = 4, JSONNumberStateWholeNumberZero = 5, JSONNumberStateWholeNumber = 6, JSONNumberStatePeriod = 7, JSONNumberStateFractionalNumberStart = 8, JSONNumberStateFractionalNumber = 9, JSONNumberStateExponentStart = 10, JSONNumberStateExponentPlusMinus = 11, JSONNumberStateExponent = 12, }; enum { JSONStringStateStart = 0, JSONStringStateParsing = 1, JSONStringStateFinished = 2, JSONStringStateError = 3, JSONStringStateEscape = 4, JSONStringStateEscapedUnicode1 = 5, JSONStringStateEscapedUnicode2 = 6, JSONStringStateEscapedUnicode3 = 7, JSONStringStateEscapedUnicode4 = 8, JSONStringStateEscapedUnicodeSurrogate1 = 9, JSONStringStateEscapedUnicodeSurrogate2 = 10, JSONStringStateEscapedUnicodeSurrogate3 = 11, JSONStringStateEscapedUnicodeSurrogate4 = 12, JSONStringStateEscapedNeedEscapeForSurrogate = 13, JSONStringStateEscapedNeedEscapedUForSurrogate = 14, }; enum { JKParseAcceptValue = (1 << 0), JKParseAcceptComma = (1 << 1), JKParseAcceptEnd = (1 << 2), JKParseAcceptValueOrEnd = (JKParseAcceptValue | JKParseAcceptEnd), JKParseAcceptCommaOrEnd = (JKParseAcceptComma | JKParseAcceptEnd), }; enum { JKClassUnknown = 0, JKClassString = 1, JKClassNumber = 2, JKClassArray = 3, JKClassDictionary = 4, JKClassNull = 5, }; enum { JKManagedBufferOnStack = 1, JKManagedBufferOnHeap = 2, JKManagedBufferLocationMask = (0x3), JKManagedBufferLocationShift = (0), JKManagedBufferMustFree = (1 << 2), }; typedef JKFlags JKManagedBufferFlags; enum { JKObjectStackOnStack = 1, JKObjectStackOnHeap = 2, JKObjectStackLocationMask = (0x3), JKObjectStackLocationShift = (0), JKObjectStackMustFree = (1 << 2), }; typedef JKFlags JKObjectStackFlags; enum { JKTokenTypeInvalid = 0, JKTokenTypeNumber = 1, JKTokenTypeString = 2, JKTokenTypeObjectBegin = 3, JKTokenTypeObjectEnd = 4, JKTokenTypeArrayBegin = 5, JKTokenTypeArrayEnd = 6, JKTokenTypeSeparator = 7, JKTokenTypeComma = 8, JKTokenTypeTrue = 9, JKTokenTypeFalse = 10, JKTokenTypeNull = 11, JKTokenTypeWhiteSpace = 12, }; typedef NSUInteger JKTokenType; // These are prime numbers to assist with hash slot probing. enum { JKValueTypeNone = 0, JKValueTypeString = 5, JKValueTypeLongLong = 7, JKValueTypeUnsignedLongLong = 11, JKValueTypeDouble = 13, }; typedef NSUInteger JKValueType; enum { JKEncodeOptionAsData = 1, JKEncodeOptionAsString = 2, JKEncodeOptionAsTypeMask = 0x7, JKEncodeOptionCollectionObj = (1 << 3), JKEncodeOptionStringObj = (1 << 4), JKEncodeOptionStringObjTrimQuotes = (1 << 5), }; typedef NSUInteger JKEncodeOptionType; typedef NSUInteger JKHash; typedef struct JKTokenCacheItem JKTokenCacheItem; typedef struct JKTokenCache JKTokenCache; typedef struct JKTokenValue JKTokenValue; typedef struct JKParseToken JKParseToken; typedef struct JKPtrRange JKPtrRange; typedef struct JKObjectStack JKObjectStack; typedef struct JKBuffer JKBuffer; typedef struct JKConstBuffer JKConstBuffer; typedef struct JKConstPtrRange JKConstPtrRange; typedef struct JKRange JKRange; typedef struct JKManagedBuffer JKManagedBuffer; typedef struct JKFastClassLookup JKFastClassLookup; typedef struct JKEncodeCache JKEncodeCache; typedef struct JKEncodeState JKEncodeState; typedef struct JKObjCImpCache JKObjCImpCache; typedef struct JKHashTableEntry JKHashTableEntry; typedef id (*NSNumberAllocImp)(id receiver, SEL selector); typedef id (*NSNumberInitWithUnsignedLongLongImp)(id receiver, SEL selector, unsigned long long value); typedef id (*JKClassFormatterIMP)(id receiver, SEL selector, id object); #ifdef __BLOCKS__ typedef id (^JKClassFormatterBlock)(id formatObject); #endif struct JKPtrRange { unsigned char *ptr; size_t length; }; struct JKConstPtrRange { const unsigned char *ptr; size_t length; }; struct JKRange { size_t location, length; }; struct JKManagedBuffer { JKPtrRange bytes; JKManagedBufferFlags flags; size_t roundSizeUpToMultipleOf; }; struct JKObjectStack { void **objects, **keys; CFHashCode *cfHashes; size_t count, index, roundSizeUpToMultipleOf; JKObjectStackFlags flags; }; struct JKBuffer { JKPtrRange bytes; }; struct JKConstBuffer { JKConstPtrRange bytes; }; struct JKTokenValue { JKConstPtrRange ptrRange; JKValueType type; JKHash hash; union { long long longLongValue; unsigned long long unsignedLongLongValue; double doubleValue; } number; JKTokenCacheItem *cacheItem; }; struct JKParseToken { JKConstPtrRange tokenPtrRange; JKTokenType type; JKTokenValue value; JKManagedBuffer tokenBuffer; }; struct JKTokenCacheItem { void *object; JKHash hash; CFHashCode cfHash; size_t size; unsigned char *bytes; JKValueType type; }; struct JKTokenCache { JKTokenCacheItem *items; size_t count; unsigned int prng_lfsr; unsigned char age[JK_CACHE_SLOTS]; }; struct JKObjCImpCache { Class NSNumberClass; NSNumberAllocImp NSNumberAlloc; NSNumberInitWithUnsignedLongLongImp NSNumberInitWithUnsignedLongLong; }; struct JKParseState { JKParseOptionFlags parseOptionFlags; JKConstBuffer stringBuffer; size_t atIndex, lineNumber, lineStartIndex; size_t prev_atIndex, prev_lineNumber, prev_lineStartIndex; JKParseToken token; JKObjectStack objectStack; JKTokenCache cache; JKObjCImpCache objCImpCache; NSError *error; int errorIsPrev; BOOL mutableCollections; }; struct JKFastClassLookup { void *stringClass; void *numberClass; void *arrayClass; void *dictionaryClass; void *nullClass; }; struct JKEncodeCache { id object; size_t offset; size_t length; }; struct JKEncodeState { JKManagedBuffer utf8ConversionBuffer; JKManagedBuffer stringBuffer; size_t atIndex; JKFastClassLookup fastClassLookup; JKEncodeCache cache[JK_ENCODE_CACHE_SLOTS]; JKSerializeOptionFlags serializeOptionFlags; JKEncodeOptionType encodeOption; size_t depth; NSError *error; id classFormatterDelegate; SEL classFormatterSelector; JKClassFormatterIMP classFormatterIMP; #ifdef __BLOCKS__ JKClassFormatterBlock classFormatterBlock; #endif }; // This is a JSONKit private class. @interface JKSerializer : NSObject { JKEncodeState *encodeState; } #ifdef __BLOCKS__ #define JKSERIALIZER_BLOCKS_PROTO id(^)(id object) #else #define JKSERIALIZER_BLOCKS_PROTO id #endif + (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error; - (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error; - (void)releaseState; @end struct JKHashTableEntry { NSUInteger keyHash; id key, object; }; typedef uint32_t UTF32; /* at least 32 bits */ typedef uint16_t UTF16; /* at least 16 bits */ typedef uint8_t UTF8; /* typically 8 bits */ typedef enum { conversionOK, /* conversion successful */ sourceExhausted, /* partial character in source, but hit end */ targetExhausted, /* insuff. room in target for conversion */ sourceIllegal /* source sequence is illegal/malformed */ } ConversionResult; #define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD #define UNI_MAX_BMP (UTF32)0x0000FFFF #define UNI_MAX_UTF16 (UTF32)0x0010FFFF #define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF #define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF #define UNI_SUR_HIGH_START (UTF32)0xD800 #define UNI_SUR_HIGH_END (UTF32)0xDBFF #define UNI_SUR_LOW_START (UTF32)0xDC00 #define UNI_SUR_LOW_END (UTF32)0xDFFF #if !defined(JK_FAST_TRAILING_BYTES) static const char trailingBytesForUTF8[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; #endif static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; #define JK_AT_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->atIndex])) #define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length])) static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection); static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex); static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject); static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex); static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count); static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection); static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary); static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary); static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary); static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry); static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object); static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey); static void _JSONDecoderCleanup(JSONDecoder *decoder); static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection); static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer); static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length); static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize); static void jk_objectStack_release(JKObjectStack *objectStack); static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count); static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount); static void jk_error(JKParseState *parseState, NSString *format, ...); static int jk_parse_string(JKParseState *parseState); static int jk_parse_number(JKParseState *parseState); static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr); JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState); JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState); static int jk_parse_next_token(JKParseState *parseState); static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String); static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex); static void *jk_parse_dictionary(JKParseState *parseState); static void *jk_parse_array(JKParseState *parseState); static void *jk_object_for_token(JKParseState *parseState); static void *jk_cachedObjects(JKParseState *parseState); JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState); JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy); static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...); static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...); static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format); static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState); static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format); static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format); static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length); JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr); JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object); static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr); #define jk_encode_write1(es, dc, f) (JK_EXPECT_F(_jk_encode_prettyPrint) ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f)) JK_STATIC_INLINE size_t jk_min(size_t a, size_t b); JK_STATIC_INLINE size_t jk_max(size_t a, size_t b); JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c); // JSONKit v1.4 used both a JKArray : NSArray and JKMutableArray : NSMutableArray, and the same for the dictionary collection type. // However, Louis Gerbarg (via cocoa-dev) pointed out that Cocoa / Core Foundation actually implements only a single class that inherits from the // mutable version, and keeps an ivar bit for whether or not that instance is mutable. This means that the immutable versions of the collection // classes receive the mutating methods, but this is handled by having those methods throw an exception when the ivar bit is set to immutable. // We adopt the same strategy here. It's both cleaner and gets rid of the method swizzling hackery used in JSONKit v1.4. // This is a workaround for issue #23 https://github.com/johnezang/JSONKit/pull/23 // Basically, there seem to be a problem with using +load in static libraries on iOS. However, __attribute__ ((constructor)) does work correctly. // Since we do not require anything "special" that +load provides, and we can accomplish the same thing using __attribute__ ((constructor)), the +load logic was moved here. static Class _JKArrayClass = NULL; static size_t _JKArrayInstanceSize = 0UL; static Class _JKDictionaryClass = NULL; static size_t _JKDictionaryInstanceSize = 0UL; // For JSONDecoder... static Class _jk_NSNumberClass = NULL; static NSNumberAllocImp _jk_NSNumberAllocImp = NULL; static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp = NULL; extern void jk_collectionClassLoadTimeInitialization(void) __attribute__ ((constructor)); void jk_collectionClassLoadTimeInitialization(void) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at load time initialization may be less than ideal. _JKArrayClass = objc_getClass("JKArray"); _JKArrayInstanceSize = jk_max(16UL, class_getInstanceSize(_JKArrayClass)); _JKDictionaryClass = objc_getClass("JKDictionary"); _JKDictionaryInstanceSize = jk_max(16UL, class_getInstanceSize(_JKDictionaryClass)); // For JSONDecoder... _jk_NSNumberClass = [NSNumber class]; _jk_NSNumberAllocImp = (NSNumberAllocImp)[NSNumber methodForSelector:@selector(alloc)]; // Hacktacular. Need to do it this way due to the nature of class clusters. id temp_NSNumber = [NSNumber alloc]; _jk_NSNumberInitWithUnsignedLongLongImp = (NSNumberInitWithUnsignedLongLongImp)[temp_NSNumber methodForSelector:@selector(initWithUnsignedLongLong:)]; [[temp_NSNumber init] release]; temp_NSNumber = NULL; [pool release]; pool = NULL; } #pragma mark - @interface JKArray : NSMutableArray <NSCopying, NSMutableCopying, NSFastEnumeration> { id *objects; NSUInteger count, capacity, mutations; } @end @implementation JKArray + (id)allocWithZone:(NSZone *)zone { #pragma unused(zone) [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])]; return(NULL); } static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection) { NSCParameterAssert((objects != NULL) && (_JKArrayClass != NULL) && (_JKArrayInstanceSize > 0UL)); JKArray *array = NULL; if(JK_EXPECT_T((array = (JKArray *)calloc(1UL, _JKArrayInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc. object_setClass(array, _JKArrayClass); if((array = [array init]) == NULL) { return(NULL); } array->capacity = count; array->count = count; if(JK_EXPECT_F((array->objects = (id *)malloc(sizeof(id) * array->capacity)) == NULL)) { [array autorelease]; return(NULL); } memcpy(array->objects, objects, array->capacity * sizeof(id)); array->mutations = (mutableCollection == NO) ? 0UL : 1UL; } return(array); } // Note: The caller is responsible for -retaining the object that is to be added. static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex) { NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex <= array->count) && (newObject != NULL)); if(!((array != NULL) && (array->objects != NULL) && (objectIndex <= array->count) && (newObject != NULL))) { [newObject autorelease]; return; } if((array->count + 1UL) >= array->capacity) { id *newObjects = NULL; if((newObjects = (id *)realloc(array->objects, sizeof(id) * (array->capacity + 16UL))) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; } array->objects = newObjects; array->capacity += 16UL; memset(&array->objects[array->count], 0, sizeof(id) * (array->capacity - array->count)); } array->count++; if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex + 1UL], &array->objects[objectIndex], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[objectIndex] = NULL; } array->objects[objectIndex] = newObject; } // Note: The caller is responsible for -retaining the object that is to be added. static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject) { NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL)); if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL))) { [newObject autorelease]; return; } CFRelease(array->objects[objectIndex]); array->objects[objectIndex] = NULL; array->objects[objectIndex] = newObject; } static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex) { NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count > 0UL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL)); if(!((array != NULL) && (array->objects != NULL) && (array->count > 0UL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; } CFRelease(array->objects[objectIndex]); array->objects[objectIndex] = NULL; if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex], &array->objects[objectIndex + 1UL], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[array->count - 1UL] = NULL; } array->count--; } - (void)dealloc { if(JK_EXPECT_T(objects != NULL)) { NSUInteger atObject = 0UL; for(atObject = 0UL; atObject < count; atObject++) { if(JK_EXPECT_T(objects[atObject] != NULL)) { CFRelease(objects[atObject]); objects[atObject] = NULL; } } free(objects); objects = NULL; } [super dealloc]; } - (NSUInteger)count { NSParameterAssert((objects != NULL) && (count <= capacity)); return(count); } - (void)getObjects:(id *)objectsPtr range:(NSRange)range { NSParameterAssert((objects != NULL) && (count <= capacity)); if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range)]; } if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range), (unsigned long)count]; } #ifndef __clang_analyzer__ memcpy(objectsPtr, objects + range.location, range.length * sizeof(id)); #endif } - (id)objectAtIndex:(NSUInteger)objectIndex { if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL)); return(objects[objectIndex]); } - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len { NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (objects != NULL) && (count <= capacity)); if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; } if(JK_EXPECT_F(state->state >= count)) { return(0UL); } NSUInteger enumeratedCount = 0UL; while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < count)) { NSParameterAssert(objects[state->state] != NULL); stackbuf[enumeratedCount++] = objects[state->state++]; } return(enumeratedCount); } - (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex { if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)(count + 1UL)]; } #ifdef __clang_analyzer__ [anObject retain]; // Stupid clang analyzer... Issue #19. #else anObject = [anObject retain]; #endif _JKArrayInsertObjectAtIndex(self, anObject, objectIndex); mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; } - (void)removeObjectAtIndex:(NSUInteger)objectIndex { if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } _JKArrayRemoveObjectAtIndex(self, objectIndex); mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; } - (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject { if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; } #ifdef __clang_analyzer__ [anObject retain]; // Stupid clang analyzer... Issue #19. #else anObject = [anObject retain]; #endif _JKArrayReplaceObjectAtIndexWithObject(self, objectIndex, anObject); mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; } - (id)copyWithZone:(NSZone *)zone { NSParameterAssert((objects != NULL) && (count <= capacity)); return((mutations == 0UL) ? [self retain] : [(NSArray *)[NSArray allocWithZone:zone] initWithObjects:objects count:count]); } - (id)mutableCopyWithZone:(NSZone *)zone { NSParameterAssert((objects != NULL) && (count <= capacity)); return([(NSMutableArray *)[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]); } @end #pragma mark - @interface JKDictionaryEnumerator : NSEnumerator { id collection; NSUInteger nextObject; } - (id)initWithJKDictionary:(JKDictionary *)initDictionary; - (NSArray *)allObjects; - (id)nextObject; @end @implementation JKDictionaryEnumerator - (id)initWithJKDictionary:(JKDictionary *)initDictionary { NSParameterAssert(initDictionary != NULL); if((self = [super init]) == NULL) { return(NULL); } if((collection = (id)CFRetain(initDictionary)) == NULL) { [self autorelease]; return(NULL); } return(self); } - (void)dealloc { if(collection != NULL) { CFRelease(collection); collection = NULL; } [super dealloc]; } - (NSArray *)allObjects { NSParameterAssert(collection != NULL); NSUInteger count = [(NSDictionary *)collection count], atObject = 0UL; id objects[count]; while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; } return([NSArray arrayWithObjects:objects count:atObject]); } - (id)nextObject { NSParameterAssert((collection != NULL) && (_JKDictionaryHashEntry(collection) != NULL)); JKHashTableEntry *entry = _JKDictionaryHashEntry(collection); NSUInteger capacity = _JKDictionaryCapacity(collection); id returnObject = NULL; if(entry != NULL) { while((nextObject < capacity) && ((returnObject = entry[nextObject++].key) == NULL)) { /* ... */ } } return(returnObject); } @end #pragma mark - @interface JKDictionary : NSMutableDictionary <NSCopying, NSMutableCopying, NSFastEnumeration> { NSUInteger count, capacity, mutations; JKHashTableEntry *entry; } @end @implementation JKDictionary + (id)allocWithZone:(NSZone *)zone { #pragma unused(zone) [NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])]; return(NULL); } // These values are taken from Core Foundation CF-550 CFBasicHash.m. As a bonus, they align very well with our JKHashTableEntry struct too. static const NSUInteger jk_dictionaryCapacities[] = { 0UL, 3UL, 7UL, 13UL, 23UL, 41UL, 71UL, 127UL, 191UL, 251UL, 383UL, 631UL, 1087UL, 1723UL, 2803UL, 4523UL, 7351UL, 11959UL, 19447UL, 31231UL, 50683UL, 81919UL, 132607UL, 214519UL, 346607UL, 561109UL, 907759UL, 1468927UL, 2376191UL, 3845119UL, 6221311UL, 10066421UL, 16287743UL, 26354171UL, 42641881UL, 68996069UL, 111638519UL, 180634607UL, 292272623UL, 472907251UL }; static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) { NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = (NSUInteger)lround(floor(((double)count) * 1.33)); while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } } return(jk_dictionaryCapacities[bottom]); } static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) { NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity)); NSUInteger capacityForCount = 0UL; if(dictionary->capacity < (capacityForCount = _JKDictionaryCapacityForCount(dictionary->count + 1UL))) { // resize NSUInteger oldCapacity = dictionary->capacity; #ifndef NS_BLOCK_ASSERTIONS NSUInteger oldCount = dictionary->count; #endif JKHashTableEntry *oldEntry = dictionary->entry; if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * capacityForCount)) == NULL)) { [NSException raise:NSMallocException format:@"Unable to allocate memory for hash table."]; } dictionary->capacity = capacityForCount; dictionary->count = 0UL; NSUInteger idx = 0UL; for(idx = 0UL; idx < oldCapacity; idx++) { if(oldEntry[idx].key != NULL) { _JKDictionaryAddObject(dictionary, oldEntry[idx].keyHash, oldEntry[idx].key, oldEntry[idx].object); oldEntry[idx].keyHash = 0UL; oldEntry[idx].key = NULL; oldEntry[idx].object = NULL; } } NSCParameterAssert((oldCount == dictionary->count)); free(oldEntry); oldEntry = NULL; } } static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection) { NSCParameterAssert((keys != NULL) && (keyHashes != NULL) && (objects != NULL) && (_JKDictionaryClass != NULL) && (_JKDictionaryInstanceSize > 0UL)); JKDictionary *dictionary = NULL; if(JK_EXPECT_T((dictionary = (JKDictionary *)calloc(1UL, _JKDictionaryInstanceSize)) != NULL)) { // Directly allocate the JKDictionary instance via calloc. object_setClass(dictionary, _JKDictionaryClass); if((dictionary = [dictionary init]) == NULL) { return(NULL); } dictionary->capacity = _JKDictionaryCapacityForCount(count); dictionary->count = 0UL; if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * dictionary->capacity)) == NULL)) { [dictionary autorelease]; return(NULL); } NSUInteger idx = 0UL; for(idx = 0UL; idx < count; idx++) { _JKDictionaryAddObject(dictionary, keyHashes[idx], keys[idx], objects[idx]); } dictionary->mutations = (mutableCollection == NO) ? 0UL : 1UL; } return(dictionary); } - (void)dealloc { if(JK_EXPECT_T(entry != NULL)) { NSUInteger atEntry = 0UL; for(atEntry = 0UL; atEntry < capacity; atEntry++) { if(JK_EXPECT_T(entry[atEntry].key != NULL)) { CFRelease(entry[atEntry].key); entry[atEntry].key = NULL; } if(JK_EXPECT_T(entry[atEntry].object != NULL)) { CFRelease(entry[atEntry].object); entry[atEntry].object = NULL; } } free(entry); entry = NULL; } [super dealloc]; } static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary) { NSCParameterAssert(dictionary != NULL); return(dictionary->entry); } static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) { NSCParameterAssert(dictionary != NULL); return(dictionary->capacity); } static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) { NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL) && (dictionary->count <= dictionary->capacity)); CFRelease(entry->key); entry->key = NULL; CFRelease(entry->object); entry->object = NULL; entry->keyHash = 0UL; dictionary->count--; // In order for certain invariants that are used to speed up the search for a particular key, we need to "re-add" all the entries in the hash table following this entry until we hit a NULL entry. NSUInteger removeIdx = entry - dictionary->entry, idx = 0UL; NSCParameterAssert((removeIdx < dictionary->capacity)); for(idx = 0UL; idx < dictionary->capacity; idx++) { NSUInteger entryIdx = (removeIdx + idx + 1UL) % dictionary->capacity; JKHashTableEntry *atEntry = &dictionary->entry[entryIdx]; if(atEntry->key == NULL) { break; } NSUInteger keyHash = atEntry->keyHash; id key = atEntry->key, object = atEntry->object; NSCParameterAssert(object != NULL); atEntry->keyHash = 0UL; atEntry->key = NULL; atEntry->object = NULL; NSUInteger addKeyEntry = keyHash % dictionary->capacity, addIdx = 0UL; for(addIdx = 0UL; addIdx < dictionary->capacity; addIdx++) { JKHashTableEntry *atAddEntry = &dictionary->entry[((addKeyEntry + addIdx) % dictionary->capacity)]; if(JK_EXPECT_T(atAddEntry->key == NULL)) { NSCParameterAssert((atAddEntry->keyHash == 0UL) && (atAddEntry->object == NULL)); atAddEntry->key = key; atAddEntry->object = object; atAddEntry->keyHash = keyHash; break; } } } } static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object) { NSCParameterAssert((dictionary != NULL) && (key != NULL) && (object != NULL) && (dictionary->count < dictionary->capacity) && (dictionary->entry != NULL)); NSUInteger keyEntry = keyHash % dictionary->capacity, idx = 0UL; for(idx = 0UL; idx < dictionary->capacity; idx++) { NSUInteger entryIdx = (keyEntry + idx) % dictionary->capacity; JKHashTableEntry *atEntry = &dictionary->entry[entryIdx]; if(JK_EXPECT_F(atEntry->keyHash == keyHash) && JK_EXPECT_T(atEntry->key != NULL) && (JK_EXPECT_F(key == atEntry->key) || JK_EXPECT_F(CFEqual(atEntry->key, key)))) { _JKDictionaryRemoveObjectWithEntry(dictionary, atEntry); } if(JK_EXPECT_T(atEntry->key == NULL)) { NSCParameterAssert((atEntry->keyHash == 0UL) && (atEntry->object == NULL)); atEntry->key = key; atEntry->object = object; atEntry->keyHash = keyHash; dictionary->count++; return; } } // We should never get here. If we do, we -release the key / object because it's our responsibility. CFRelease(key); CFRelease(object); } - (NSUInteger)count { return(count); } static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey) { NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity)); if((aKey == NULL) || (dictionary->capacity == 0UL)) { return(NULL); } NSUInteger keyHash = CFHash(aKey), keyEntry = (keyHash % dictionary->capacity), idx = 0UL; JKHashTableEntry *atEntry = NULL; for(idx = 0UL; idx < dictionary->capacity; idx++) { atEntry = &dictionary->entry[(keyEntry + idx) % dictionary->capacity]; if(JK_EXPECT_T(atEntry->keyHash == keyHash) && JK_EXPECT_T(atEntry->key != NULL) && ((atEntry->key == aKey) || CFEqual(atEntry->key, aKey))) { NSCParameterAssert(atEntry->object != NULL); return(atEntry); break; } if(JK_EXPECT_F(atEntry->key == NULL)) { NSCParameterAssert(atEntry->object == NULL); return(NULL); break; } // If the key was in the table, we would have found it by now. } return(NULL); } - (id)objectForKey:(id)aKey { NSParameterAssert((entry != NULL) && (count <= capacity)); JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey); return((entryForKey != NULL) ? entryForKey->object : NULL); } - (void)getObjects:(id *)objects andKeys:(id *)keys { NSParameterAssert((entry != NULL) && (count <= capacity)); NSUInteger atEntry = 0UL; NSUInteger arrayIdx = 0UL; for(atEntry = 0UL; atEntry < capacity; atEntry++) { if(JK_EXPECT_T(entry[atEntry].key != NULL)) { NSCParameterAssert((entry[atEntry].object != NULL) && (arrayIdx < count)); if(JK_EXPECT_T(keys != NULL)) { keys[arrayIdx] = entry[atEntry].key; } if(JK_EXPECT_T(objects != NULL)) { objects[arrayIdx] = entry[atEntry].object; } arrayIdx++; } } } - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len { NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (entry != NULL) && (count <= capacity)); if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; } if(JK_EXPECT_F(state->state >= capacity)) { return(0UL); } NSUInteger enumeratedCount = 0UL; while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < capacity)) { if(JK_EXPECT_T(entry[state->state].key != NULL)) { stackbuf[enumeratedCount++] = entry[state->state].key; } state->state++; } return(enumeratedCount); } - (NSEnumerator *)keyEnumerator { return([[[JKDictionaryEnumerator alloc] initWithJKDictionary:self] autorelease]); } - (void)setObject:(id)anObject forKey:(id)aKey { if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil value (key: %@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), aKey]; } _JKDictionaryResizeIfNeccessary(self); #ifndef __clang_analyzer__ aKey = [aKey copy]; // Why on earth would clang complain that this -copy "might leak", anObject = [anObject retain]; // but this -retain doesn't!? #endif // __clang_analyzer__ _JKDictionaryAddObject(self, CFHash(aKey), aKey, anObject); mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; } - (void)removeObjectForKey:(id)aKey { if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to remove nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; } JKHashTableEntry *entryForKey = _JKDictionaryHashTableEntryForKey(self, aKey); if(entryForKey != NULL) { _JKDictionaryRemoveObjectWithEntry(self, entryForKey); mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL; } } - (id)copyWithZone:(NSZone *)zone { NSParameterAssert((entry != NULL) && (count <= capacity)); return((mutations == 0UL) ? [self retain] : [[NSDictionary allocWithZone:zone] initWithDictionary:self]); } - (id)mutableCopyWithZone:(NSZone *)zone { NSParameterAssert((entry != NULL) && (count <= capacity)); return([[NSMutableDictionary allocWithZone:zone] initWithDictionary:self]); } @end #pragma mark - JK_STATIC_INLINE size_t jk_min(size_t a, size_t b) { return((a < b) ? a : b); } JK_STATIC_INLINE size_t jk_max(size_t a, size_t b) { return((a > b) ? a : b); } JK_STATIC_INLINE JKHash jk_calculateHash(JKHash currentHash, unsigned char c) { return((((currentHash << 5) + currentHash) + (c - 29)) ^ (currentHash >> 19)); } static void jk_error(JKParseState *parseState, NSString *format, ...) { NSCParameterAssert((parseState != NULL) && (format != NULL)); va_list varArgsList; va_start(varArgsList, format); NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; va_end(varArgsList); #if 0 const unsigned char *lineStart = parseState->stringBuffer.bytes.ptr + parseState->lineStartIndex; const unsigned char *lineEnd = lineStart; const unsigned char *atCharacterPtr = NULL; for(atCharacterPtr = lineStart; atCharacterPtr < JK_END_STRING_PTR(parseState); atCharacterPtr++) { lineEnd = atCharacterPtr; if(jk_parse_is_newline(parseState, atCharacterPtr)) { break; } } NSString *lineString = @"", *carretString = @""; if(lineStart < JK_END_STRING_PTR(parseState)) { lineString = [[[NSString alloc] initWithBytes:lineStart length:(lineEnd - lineStart) encoding:NSUTF8StringEncoding] autorelease]; carretString = [NSString stringWithFormat:@"%*.*s^", (int)(parseState->atIndex - parseState->lineStartIndex), (int)(parseState->atIndex - parseState->lineStartIndex), " "]; } #endif if(parseState->error == NULL) { parseState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo: [NSDictionary dictionaryWithObjectsAndKeys: formatString, NSLocalizedDescriptionKey, [NSNumber numberWithUnsignedLong:parseState->atIndex], @"JKAtIndexKey", [NSNumber numberWithUnsignedLong:parseState->lineNumber], @"JKLineNumberKey", //lineString, @"JKErrorLine0Key", //carretString, @"JKErrorLine1Key", NULL]]; } } #pragma mark - #pragma mark Buffer and Object Stack management functions static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer) { if((managedBuffer->flags & JKManagedBufferMustFree)) { if(managedBuffer->bytes.ptr != NULL) { free(managedBuffer->bytes.ptr); managedBuffer->bytes.ptr = NULL; } managedBuffer->flags &= ~JKManagedBufferMustFree; } managedBuffer->bytes.ptr = NULL; managedBuffer->bytes.length = 0UL; managedBuffer->flags &= ~JKManagedBufferLocationMask; } static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length) { jk_managedBuffer_release(managedBuffer); managedBuffer->bytes.ptr = ptr; managedBuffer->bytes.length = length; managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | JKManagedBufferOnStack; } static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize) { size_t roundedUpNewSize = newSize; if(managedBuffer->roundSizeUpToMultipleOf > 0UL) { roundedUpNewSize = newSize + ((managedBuffer->roundSizeUpToMultipleOf - (newSize % managedBuffer->roundSizeUpToMultipleOf)) % managedBuffer->roundSizeUpToMultipleOf); } if((roundedUpNewSize != managedBuffer->bytes.length) && (roundedUpNewSize > managedBuffer->bytes.length)) { if((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnStack) { NSCParameterAssert((managedBuffer->flags & JKManagedBufferMustFree) == 0); unsigned char *newBuffer = NULL, *oldBuffer = managedBuffer->bytes.ptr; if((newBuffer = (unsigned char *)malloc(roundedUpNewSize)) == NULL) { return(NULL); } memcpy(newBuffer, oldBuffer, jk_min(managedBuffer->bytes.length, roundedUpNewSize)); managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | (JKManagedBufferOnHeap | JKManagedBufferMustFree); managedBuffer->bytes.ptr = newBuffer; managedBuffer->bytes.length = roundedUpNewSize; } else { NSCParameterAssert(((managedBuffer->flags & JKManagedBufferMustFree) != 0) && ((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnHeap)); if((managedBuffer->bytes.ptr = (unsigned char *)reallocf(managedBuffer->bytes.ptr, roundedUpNewSize)) == NULL) { return(NULL); } managedBuffer->bytes.length = roundedUpNewSize; } } return(managedBuffer->bytes.ptr); } static void jk_objectStack_release(JKObjectStack *objectStack) { NSCParameterAssert(objectStack != NULL); NSCParameterAssert(objectStack->index <= objectStack->count); size_t atIndex = 0UL; for(atIndex = 0UL; atIndex < objectStack->index; atIndex++) { if(objectStack->objects[atIndex] != NULL) { CFRelease(objectStack->objects[atIndex]); objectStack->objects[atIndex] = NULL; } if(objectStack->keys[atIndex] != NULL) { CFRelease(objectStack->keys[atIndex]); objectStack->keys[atIndex] = NULL; } } objectStack->index = 0UL; if(objectStack->flags & JKObjectStackMustFree) { NSCParameterAssert((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap); if(objectStack->objects != NULL) { free(objectStack->objects); objectStack->objects = NULL; } if(objectStack->keys != NULL) { free(objectStack->keys); objectStack->keys = NULL; } if(objectStack->cfHashes != NULL) { free(objectStack->cfHashes); objectStack->cfHashes = NULL; } objectStack->flags &= ~JKObjectStackMustFree; } objectStack->objects = NULL; objectStack->keys = NULL; objectStack->cfHashes = NULL; objectStack->count = 0UL; objectStack->flags &= ~JKObjectStackLocationMask; } static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count) { NSCParameterAssert((objectStack != NULL) && (objects != NULL) && (keys != NULL) && (cfHashes != NULL) && (count > 0UL)); jk_objectStack_release(objectStack); objectStack->objects = objects; objectStack->keys = keys; objectStack->cfHashes = cfHashes; objectStack->count = count; objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | JKObjectStackOnStack; #ifndef NS_BLOCK_ASSERTIONS size_t idx; for(idx = 0UL; idx < objectStack->count; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; } #endif } static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount) { size_t roundedUpNewCount = newCount; int returnCode = 0; void **newObjects = NULL, **newKeys = NULL; CFHashCode *newCFHashes = NULL; if(objectStack->roundSizeUpToMultipleOf > 0UL) { roundedUpNewCount = newCount + ((objectStack->roundSizeUpToMultipleOf - (newCount % objectStack->roundSizeUpToMultipleOf)) % objectStack->roundSizeUpToMultipleOf); } if((roundedUpNewCount != objectStack->count) && (roundedUpNewCount > objectStack->count)) { if((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnStack) { NSCParameterAssert((objectStack->flags & JKObjectStackMustFree) == 0); if((newObjects = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; } memcpy(newObjects, objectStack->objects, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *)); if((newKeys = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; } memcpy(newKeys, objectStack->keys, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *)); if((newCFHashes = (CFHashCode *)calloc(1UL, roundedUpNewCount * sizeof(CFHashCode))) == NULL) { returnCode = 1; goto errorExit; } memcpy(newCFHashes, objectStack->cfHashes, jk_min(objectStack->count, roundedUpNewCount) * sizeof(CFHashCode)); objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | (JKObjectStackOnHeap | JKObjectStackMustFree); objectStack->objects = newObjects; newObjects = NULL; objectStack->keys = newKeys; newKeys = NULL; objectStack->cfHashes = newCFHashes; newCFHashes = NULL; objectStack->count = roundedUpNewCount; } else { NSCParameterAssert(((objectStack->flags & JKObjectStackMustFree) != 0) && ((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap)); if((newObjects = (void ** )realloc(objectStack->objects, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->objects = newObjects; newObjects = NULL; } else { returnCode = 1; goto errorExit; } if((newKeys = (void ** )realloc(objectStack->keys, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->keys = newKeys; newKeys = NULL; } else { returnCode = 1; goto errorExit; } if((newCFHashes = (CFHashCode *)realloc(objectStack->cfHashes, roundedUpNewCount * sizeof(CFHashCode))) != NULL) { objectStack->cfHashes = newCFHashes; newCFHashes = NULL; } else { returnCode = 1; goto errorExit; } #ifndef NS_BLOCK_ASSERTIONS size_t idx; for(idx = objectStack->count; idx < roundedUpNewCount; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; } #endif objectStack->count = roundedUpNewCount; } } errorExit: if(newObjects != NULL) { free(newObjects); newObjects = NULL; } if(newKeys != NULL) { free(newKeys); newKeys = NULL; } if(newCFHashes != NULL) { free(newCFHashes); newCFHashes = NULL; } return(returnCode); } //////////// #pragma mark - #pragma mark Unicode related functions JK_STATIC_INLINE ConversionResult isValidCodePoint(UTF32 *u32CodePoint) { ConversionResult result = conversionOK; UTF32 ch = *u32CodePoint; if(JK_EXPECT_F(ch >= UNI_SUR_HIGH_START) && (JK_EXPECT_T(ch <= UNI_SUR_LOW_END))) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } if(JK_EXPECT_F(ch >= 0xFDD0U) && (JK_EXPECT_F(ch <= 0xFDEFU) || JK_EXPECT_F((ch & 0xFFFEU) == 0xFFFEU)) && JK_EXPECT_T(ch <= 0x10FFFFU)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } if(JK_EXPECT_F(ch == 0U)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } finished: *u32CodePoint = ch; return(result); } static int isLegalUTF8(const UTF8 *source, size_t length) { const UTF8 *srcptr = source + length; UTF8 a; switch(length) { default: return(0); // Everything else falls through when "true"... case 4: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); } case 3: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); } case 2: if(JK_EXPECT_F( (a = (*--srcptr)) > 0xBF )) { return(0); } switch(*source) { // no fall-through in this inner switch case 0xE0: if(JK_EXPECT_F(a < 0xA0)) { return(0); } break; case 0xED: if(JK_EXPECT_F(a > 0x9F)) { return(0); } break; case 0xF0: if(JK_EXPECT_F(a < 0x90)) { return(0); } break; case 0xF4: if(JK_EXPECT_F(a > 0x8F)) { return(0); } break; default: if(JK_EXPECT_F(a < 0x80)) { return(0); } } case 1: if(JK_EXPECT_F((JK_EXPECT_T(*source < 0xC2)) && JK_EXPECT_F(*source >= 0x80))) { return(0); } } if(JK_EXPECT_F(*source > 0xF4)) { return(0); } return(1); } static ConversionResult ConvertSingleCodePointInUTF8(const UTF8 *sourceStart, const UTF8 *sourceEnd, UTF8 const **nextUTF8, UTF32 *convertedUTF32) { ConversionResult result = conversionOK; const UTF8 *source = sourceStart; UTF32 ch = 0UL; #if !defined(JK_FAST_TRAILING_BYTES) unsigned short extraBytesToRead = trailingBytesForUTF8[*source]; #else unsigned short extraBytesToRead = __builtin_clz(((*source)^0xff) << 25); #endif if(JK_EXPECT_F((source + extraBytesToRead + 1) > sourceEnd) || JK_EXPECT_F(!isLegalUTF8(source, extraBytesToRead + 1))) { source++; while((source < sourceEnd) && (((*source) & 0xc0) == 0x80) && ((source - sourceStart) < (extraBytesToRead + 1))) { source++; } NSCParameterAssert(source <= sourceEnd); result = ((source < sourceEnd) && (((*source) & 0xc0) != 0x80)) ? sourceIllegal : ((sourceStart + extraBytesToRead + 1) > sourceEnd) ? sourceExhausted : sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; } switch(extraBytesToRead) { // The cases all fall through. case 5: ch += *source++; ch <<= 6; case 4: ch += *source++; ch <<= 6; case 3: ch += *source++; ch <<= 6; case 2: ch += *source++; ch <<= 6; case 1: ch += *source++; ch <<= 6; case 0: ch += *source++; } ch -= offsetsFromUTF8[extraBytesToRead]; result = isValidCodePoint(&ch); finished: *nextUTF8 = source; *convertedUTF32 = ch; return(result); } static ConversionResult ConvertUTF32toUTF8 (UTF32 u32CodePoint, UTF8 **targetStart, UTF8 *targetEnd) { const UTF32 byteMask = 0xBF, byteMark = 0x80; ConversionResult result = conversionOK; UTF8 *target = *targetStart; UTF32 ch = u32CodePoint; unsigned short bytesToWrite = 0; result = isValidCodePoint(&ch); // Figure out how many bytes the result will require. Turn any illegally large UTF32 things (> Plane 17) into replacement chars. if(ch < (UTF32)0x80) { bytesToWrite = 1; } else if(ch < (UTF32)0x800) { bytesToWrite = 2; } else if(ch < (UTF32)0x10000) { bytesToWrite = 3; } else if(ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; } else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; } target += bytesToWrite; if (target > targetEnd) { target -= bytesToWrite; result = targetExhausted; goto finished; } switch (bytesToWrite) { // note: everything falls through. case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6; case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]); } target += bytesToWrite; finished: *targetStart = target; return(result); } JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, uint32_t unicodeCodePoint, size_t *tokenBufferIdx, JKHash *stringHash) { UTF8 *u8s = &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx]; ConversionResult result; if((result = ConvertUTF32toUTF8(unicodeCodePoint, &u8s, (parseState->token.tokenBuffer.bytes.ptr + parseState->token.tokenBuffer.bytes.length))) != conversionOK) { if(result == targetExhausted) { return(1); } } size_t utf8len = u8s - &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx], nextIdx = (*tokenBufferIdx) + utf8len; while(*tokenBufferIdx < nextIdx) { *stringHash = jk_calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); } return(0); } //////////// #pragma mark - #pragma mark Decoding / parsing / deserializing functions static int jk_parse_string(JKParseState *parseState) { NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); const unsigned char *stringStart = JK_AT_STRING_PTR(parseState) + 1; const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState); const unsigned char *atStringCharacter = stringStart; unsigned char *tokenBuffer = parseState->token.tokenBuffer.bytes.ptr; size_t tokenStartIndex = parseState->atIndex; size_t tokenBufferIdx = 0UL; int onlySimpleString = 1, stringState = JSONStringStateStart; uint16_t escapedUnicode1 = 0U, escapedUnicode2 = 0U; uint32_t escapedUnicodeCodePoint = 0U; JKHash stringHash = JK_HASH_INIT; while(1) { unsigned long currentChar; if(JK_EXPECT_F(atStringCharacter == endOfBuffer)) { /* XXX Add error message */ stringState = JSONStringStateError; goto finishedParsing; } if(JK_EXPECT_F((currentChar = *atStringCharacter++) >= 0x80UL)) { const unsigned char *nextValidCharacter = NULL; UTF32 u32ch = 0U; ConversionResult result; if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; } stringHash = jk_calculateHash(stringHash, currentChar); while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = jk_calculateHash(stringHash, *atStringCharacter++); } continue; } else { if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; goto finishedParsing; } if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { switchToSlowPath: onlySimpleString = 0; stringState = JSONStringStateParsing; tokenBufferIdx = (atStringCharacter - stringStart) - 1L; if(JK_EXPECT_F((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length)) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } memcpy(tokenBuffer, stringStart, tokenBufferIdx); goto slowMatch; } if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; } stringHash = jk_calculateHash(stringHash, currentChar); } } slowMatch: for(atStringCharacter = (stringStart + ((atStringCharacter - stringStart) - 1L)); (atStringCharacter < endOfBuffer) && (tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); atStringCharacter++) { if((tokenBufferIdx + 16UL) > parseState->token.tokenBuffer.bytes.length) { if((tokenBuffer = jk_managedBuffer_resize(&parseState->token.tokenBuffer, tokenBufferIdx + 1024UL)) == NULL) { jk_error(parseState, @"Internal error: Unable to resize temporary buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } NSCParameterAssert(tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); unsigned long currentChar = (*atStringCharacter), escapedChar; if(JK_EXPECT_T(stringState == JSONStringStateParsing)) { if(JK_EXPECT_T(currentChar >= 0x20UL)) { if(JK_EXPECT_T(currentChar < (unsigned long)0x80)) { // Not a UTF8 sequence if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; } if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; } stringHash = jk_calculateHash(stringHash, currentChar); tokenBuffer[tokenBufferIdx++] = currentChar; continue; } else { // UTF8 sequence const unsigned char *nextValidCharacter = NULL; UTF32 u32ch = 0U; ConversionResult result; if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { if((result == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal UTF8 sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; } if(result == sourceExhausted) { jk_error(parseState, @"End of buffer reached while parsing UTF8 in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; } if(jk_string_add_unicodeCodePoint(parseState, u32ch, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } atStringCharacter = nextValidCharacter - 1; continue; } else { while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = jk_calculateHash(stringHash, *atStringCharacter++); } atStringCharacter--; continue; } } } else { // currentChar < 0x20 jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; } } else { // stringState != JSONStringStateParsing int isSurrogate = 1; switch(stringState) { case JSONStringStateEscape: switch(currentChar) { case 'u': escapedUnicode1 = 0U; escapedUnicode2 = 0U; escapedUnicodeCodePoint = 0U; stringState = JSONStringStateEscapedUnicode1; break; case 'b': escapedChar = '\b'; goto parsedEscapedChar; case 'f': escapedChar = '\f'; goto parsedEscapedChar; case 'n': escapedChar = '\n'; goto parsedEscapedChar; case 'r': escapedChar = '\r'; goto parsedEscapedChar; case 't': escapedChar = '\t'; goto parsedEscapedChar; case '\\': escapedChar = '\\'; goto parsedEscapedChar; case '/': escapedChar = '/'; goto parsedEscapedChar; case '"': escapedChar = '"'; goto parsedEscapedChar; parsedEscapedChar: stringState = JSONStringStateParsing; stringHash = jk_calculateHash(stringHash, escapedChar); tokenBuffer[tokenBufferIdx++] = escapedChar; break; default: jk_error(parseState, @"Invalid escape sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; break; } break; case JSONStringStateEscapedUnicode1: case JSONStringStateEscapedUnicode2: case JSONStringStateEscapedUnicode3: case JSONStringStateEscapedUnicode4: isSurrogate = 0; case JSONStringStateEscapedUnicodeSurrogate1: case JSONStringStateEscapedUnicodeSurrogate2: case JSONStringStateEscapedUnicodeSurrogate3: case JSONStringStateEscapedUnicodeSurrogate4: { uint16_t hexValue = 0U; switch(currentChar) { case '0' ... '9': hexValue = currentChar - '0'; goto parsedHex; case 'a' ... 'f': hexValue = (currentChar - 'a') + 10U; goto parsedHex; case 'A' ... 'F': hexValue = (currentChar - 'A') + 10U; goto parsedHex; parsedHex: if(!isSurrogate) { escapedUnicode1 = (escapedUnicode1 << 4) | hexValue; } else { escapedUnicode2 = (escapedUnicode2 << 4) | hexValue; } if(stringState == JSONStringStateEscapedUnicode4) { if(((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xE000U))) { if((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xDC00U)) { stringState = JSONStringStateEscapedNeedEscapeForSurrogate; } else if((escapedUnicode1 >= 0xDC00U) && (escapedUnicode1 < 0xE000U)) { if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; } else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } } } else { escapedUnicodeCodePoint = escapedUnicode1; } } if(stringState == JSONStringStateEscapedUnicodeSurrogate4) { if((escapedUnicode2 < 0xdc00) || (escapedUnicode2 > 0xdfff)) { if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; } else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } } else { escapedUnicodeCodePoint = ((escapedUnicode1 - 0xd800) * 0x400) + (escapedUnicode2 - 0xdc00) + 0x10000; } } if((stringState == JSONStringStateEscapedUnicode4) || (stringState == JSONStringStateEscapedUnicodeSurrogate4)) { if((isValidCodePoint(&escapedUnicodeCodePoint) == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } stringState = JSONStringStateParsing; if(jk_string_add_unicodeCodePoint(parseState, escapedUnicodeCodePoint, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } else if((stringState >= JSONStringStateEscapedUnicode1) && (stringState <= JSONStringStateEscapedUnicodeSurrogate4)) { stringState++; } break; default: jk_error(parseState, @"Unexpected character found in \\u Unicode escape sequence. Found '%c', expected [0-9a-fA-F].", currentChar); stringState = JSONStringStateError; goto finishedParsing; break; } } break; case JSONStringStateEscapedNeedEscapeForSurrogate: if(currentChar == '\\') { stringState = JSONStringStateEscapedNeedEscapedUForSurrogate; } else { if((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0) { jk_error(parseState, @"Required a second \\u Unicode escape sequence following a surrogate \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } else { stringState = JSONStringStateParsing; atStringCharacter--; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } } break; case JSONStringStateEscapedNeedEscapedUForSurrogate: if(currentChar == 'u') { stringState = JSONStringStateEscapedUnicodeSurrogate1; } else { if((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0) { jk_error(parseState, @"Required a second \\u Unicode escape sequence following a surrogate \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; } else { stringState = JSONStringStateParsing; atStringCharacter -= 2; if(jk_string_add_unicodeCodePoint(parseState, UNI_REPLACEMENT_CHAR, &tokenBufferIdx, &stringHash)) { jk_error(parseState, @"Internal error: Unable to add UTF8 sequence to internal string buffer. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; } } } break; default: jk_error(parseState, @"Internal error: Unknown stringState. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; break; } } } finishedParsing: if(JK_EXPECT_T(stringState == JSONStringStateFinished)) { NSCParameterAssert((parseState->stringBuffer.bytes.ptr + tokenStartIndex) < atStringCharacter); parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + tokenStartIndex; parseState->token.tokenPtrRange.length = (atStringCharacter - parseState->token.tokenPtrRange.ptr); if(JK_EXPECT_T(onlySimpleString)) { NSCParameterAssert(((parseState->token.tokenPtrRange.ptr + 1) < endOfBuffer) && (parseState->token.tokenPtrRange.length >= 2UL) && (((parseState->token.tokenPtrRange.ptr + 1) + (parseState->token.tokenPtrRange.length - 2)) < endOfBuffer)); parseState->token.value.ptrRange.ptr = parseState->token.tokenPtrRange.ptr + 1; parseState->token.value.ptrRange.length = parseState->token.tokenPtrRange.length - 2UL; } else { parseState->token.value.ptrRange.ptr = parseState->token.tokenBuffer.bytes.ptr; parseState->token.value.ptrRange.length = tokenBufferIdx; } parseState->token.value.hash = stringHash; parseState->token.value.type = JKValueTypeString; parseState->atIndex = (atStringCharacter - parseState->stringBuffer.bytes.ptr); } if(JK_EXPECT_F(stringState != JSONStringStateFinished)) { jk_error(parseState, @"Invalid string."); } return(JK_EXPECT_T(stringState == JSONStringStateFinished) ? 0 : 1); } static int jk_parse_number(JKParseState *parseState) { NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); const unsigned char *numberStart = JK_AT_STRING_PTR(parseState); const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState); const unsigned char *atNumberCharacter = NULL; int numberState = JSONNumberStateWholeNumberStart, isFloatingPoint = 0, isNegative = 0, backup = 0; size_t startingIndex = parseState->atIndex; for(atNumberCharacter = numberStart; (JK_EXPECT_T(atNumberCharacter < endOfBuffer)) && (JK_EXPECT_T(!(JK_EXPECT_F(numberState == JSONNumberStateFinished) || JK_EXPECT_F(numberState == JSONNumberStateError)))); atNumberCharacter++) { unsigned long currentChar = (unsigned long)(*atNumberCharacter), lowerCaseCC = currentChar | 0x20UL; switch(numberState) { case JSONNumberStateWholeNumberStart: if (currentChar == '-') { numberState = JSONNumberStateWholeNumberMinus; isNegative = 1; break; } case JSONNumberStateWholeNumberMinus: if (currentChar == '0') { numberState = JSONNumberStateWholeNumberZero; break; } else if( (currentChar >= '1') && (currentChar <= '9')) { numberState = JSONNumberStateWholeNumber; break; } else { /* XXX Add error message */ numberState = JSONNumberStateError; break; } case JSONNumberStateExponentStart: if( (currentChar == '+') || (currentChar == '-')) { numberState = JSONNumberStateExponentPlusMinus; break; } case JSONNumberStateFractionalNumberStart: case JSONNumberStateExponentPlusMinus:if(!((currentChar >= '0') && (currentChar <= '9'))) { /* XXX Add error message */ numberState = JSONNumberStateError; break; } else { if(numberState == JSONNumberStateFractionalNumberStart) { numberState = JSONNumberStateFractionalNumber; } else { numberState = JSONNumberStateExponent; } break; } case JSONNumberStateWholeNumberZero: case JSONNumberStateWholeNumber: if (currentChar == '.') { numberState = JSONNumberStateFractionalNumberStart; isFloatingPoint = 1; break; } case JSONNumberStateFractionalNumber: if (lowerCaseCC == 'e') { numberState = JSONNumberStateExponentStart; isFloatingPoint = 1; break; } case JSONNumberStateExponent: if(!((currentChar >= '0') && (currentChar <= '9')) || (numberState == JSONNumberStateWholeNumberZero)) { numberState = JSONNumberStateFinished; backup = 1; break; } break; default: /* XXX Add error message */ numberState = JSONNumberStateError; break; } } parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + startingIndex; parseState->token.tokenPtrRange.length = (atNumberCharacter - parseState->token.tokenPtrRange.ptr) - backup; parseState->atIndex = (parseState->token.tokenPtrRange.ptr + parseState->token.tokenPtrRange.length) - parseState->stringBuffer.bytes.ptr; if(JK_EXPECT_T(numberState == JSONNumberStateFinished)) { unsigned char numberTempBuf[parseState->token.tokenPtrRange.length + 4UL]; unsigned char *endOfNumber = NULL; memcpy(numberTempBuf, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length); numberTempBuf[parseState->token.tokenPtrRange.length] = 0; errno = 0; // Treat "-0" as a floating point number, which is capable of representing negative zeros. if(JK_EXPECT_F(parseState->token.tokenPtrRange.length == 2UL) && JK_EXPECT_F(numberTempBuf[1] == '0') && JK_EXPECT_F(isNegative)) { isFloatingPoint = 1; } if(isFloatingPoint) { parseState->token.value.number.doubleValue = strtod((const char *)numberTempBuf, (char **)&endOfNumber); // strtod is documented to return U+2261 (identical to) 0.0 on an underflow error (along with setting errno to ERANGE). parseState->token.value.type = JKValueTypeDouble; parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.doubleValue; parseState->token.value.ptrRange.length = sizeof(double); parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type); } else { if(isNegative) { parseState->token.value.number.longLongValue = strtoll((const char *)numberTempBuf, (char **)&endOfNumber, 10); parseState->token.value.type = JKValueTypeLongLong; parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.longLongValue; parseState->token.value.ptrRange.length = sizeof(long long); parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.longLongValue; } else { parseState->token.value.number.unsignedLongLongValue = strtoull((const char *)numberTempBuf, (char **)&endOfNumber, 10); parseState->token.value.type = JKValueTypeUnsignedLongLong; parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.unsignedLongLongValue; parseState->token.value.ptrRange.length = sizeof(unsigned long long); parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.unsignedLongLongValue; } } if(JK_EXPECT_F(errno != 0)) { numberState = JSONNumberStateError; if(errno == ERANGE) { switch(parseState->token.value.type) { case JKValueTypeDouble: jk_error(parseState, @"The value '%s' could not be represented as a 'double' due to %s.", numberTempBuf, (parseState->token.value.number.doubleValue == 0.0) ? "underflow" : "overflow"); break; // see above for == 0.0. case JKValueTypeLongLong: jk_error(parseState, @"The value '%s' exceeded the minimum value that could be represented: %lld.", numberTempBuf, parseState->token.value.number.longLongValue); break; case JKValueTypeUnsignedLongLong: jk_error(parseState, @"The value '%s' exceeded the maximum value that could be represented: %llu.", numberTempBuf, parseState->token.value.number.unsignedLongLongValue); break; default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } } if(JK_EXPECT_F(endOfNumber != &numberTempBuf[parseState->token.tokenPtrRange.length]) && JK_EXPECT_F(numberState != JSONNumberStateError)) { numberState = JSONNumberStateError; jk_error(parseState, @"The conversion function did not consume all of the number tokens characters."); } size_t hashIndex = 0UL; for(hashIndex = 0UL; hashIndex < parseState->token.value.ptrRange.length; hashIndex++) { parseState->token.value.hash = jk_calculateHash(parseState->token.value.hash, parseState->token.value.ptrRange.ptr[hashIndex]); } } if(JK_EXPECT_F(numberState != JSONNumberStateFinished)) { jk_error(parseState, @"Invalid number."); } return(JK_EXPECT_T((numberState == JSONNumberStateFinished)) ? 0 : 1); } JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy) { parseState->token.tokenPtrRange.ptr = ptr; parseState->token.tokenPtrRange.length = length; parseState->token.type = type; parseState->atIndex += advanceBy; } static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr) { NSCParameterAssert((parseState != NULL) && (atCharacterPtr != NULL) && (atCharacterPtr >= parseState->stringBuffer.bytes.ptr) && (atCharacterPtr < JK_END_STRING_PTR(parseState))); const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); if(JK_EXPECT_F(atCharacterPtr >= endOfStringPtr)) { return(0UL); } if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\n')) { return(1UL); } if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\r')) { if((JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr)) && ((*(atCharacterPtr + 1)) == '\n')) { return(2UL); } return(1UL); } if(parseState->parseOptionFlags & JKParseOptionUnicodeNewlines) { if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xc2)) && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x85))) { return(2UL); } if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xe2)) && (((atCharacterPtr + 2) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x80) && (((*(atCharacterPtr + 2)) == 0xa8) || ((*(atCharacterPtr + 2)) == 0xa9)))) { return(3UL); } } return(0UL); } JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState) { size_t newlineAdvanceAtIndex = 0UL; if(JK_EXPECT_F((newlineAdvanceAtIndex = jk_parse_is_newline(parseState, JK_AT_STRING_PTR(parseState))) > 0UL)) { parseState->lineNumber++; parseState->atIndex += (newlineAdvanceAtIndex - 1UL); parseState->lineStartIndex = parseState->atIndex + 1UL; return(1); } return(0); } JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState) { #ifndef __clang_analyzer__ NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); const unsigned char *atCharacterPtr = NULL; const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { if(((*(atCharacterPtr + 0)) == ' ') || ((*(atCharacterPtr + 0)) == '\t')) { continue; } if(jk_parse_skip_newline(parseState)) { continue; } if(parseState->parseOptionFlags & JKParseOptionComments) { if((JK_EXPECT_F((*(atCharacterPtr + 0)) == '/')) && (JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr))) { if((*(atCharacterPtr + 1)) == '/') { parseState->atIndex++; for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { if(jk_parse_skip_newline(parseState)) { break; } } continue; } if((*(atCharacterPtr + 1)) == '*') { parseState->atIndex++; for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) { if(jk_parse_skip_newline(parseState)) { continue; } if(((*(atCharacterPtr + 0)) == '*') && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == '/'))) { parseState->atIndex++; break; } } continue; } } } break; } #endif } static int jk_parse_next_token(JKParseState *parseState) { NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); const unsigned char *atCharacterPtr = NULL; const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState); unsigned char currentCharacter = 0U; int stopParsing = 0; parseState->prev_atIndex = parseState->atIndex; parseState->prev_lineNumber = parseState->lineNumber; parseState->prev_lineStartIndex = parseState->lineStartIndex; jk_parse_skip_whitespace(parseState); if((JK_AT_STRING_PTR(parseState) == endOfStringPtr)) { stopParsing = 1; } if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr))) { currentCharacter = *atCharacterPtr; if(JK_EXPECT_T(currentCharacter == '"')) { if(JK_EXPECT_T((stopParsing = jk_parse_string(parseState)) == 0)) { jk_set_parsed_token(parseState, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length, JKTokenTypeString, 0UL); } } else if(JK_EXPECT_T(currentCharacter == ':')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeSeparator, 1UL); } else if(JK_EXPECT_T(currentCharacter == ',')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeComma, 1UL); } else if((JK_EXPECT_T(currentCharacter >= '0') && JK_EXPECT_T(currentCharacter <= '9')) || JK_EXPECT_T(currentCharacter == '-')) { if(JK_EXPECT_T((stopParsing = jk_parse_number(parseState)) == 0)) { jk_set_parsed_token(parseState, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length, JKTokenTypeNumber, 0UL); } } else if(JK_EXPECT_T(currentCharacter == '{')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectBegin, 1UL); } else if(JK_EXPECT_T(currentCharacter == '}')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectEnd, 1UL); } else if(JK_EXPECT_T(currentCharacter == '[')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayBegin, 1UL); } else if(JK_EXPECT_T(currentCharacter == ']')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayEnd, 1UL); } else if(JK_EXPECT_T(currentCharacter == 't')) { if(!((JK_EXPECT_T((atCharacterPtr + 4UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'r')) && (JK_EXPECT_T(atCharacterPtr[2] == 'u')) && (JK_EXPECT_T(atCharacterPtr[3] == 'e')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 4UL, JKTokenTypeTrue, 4UL); } } else if(JK_EXPECT_T(currentCharacter == 'f')) { if(!((JK_EXPECT_T((atCharacterPtr + 5UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'a')) && (JK_EXPECT_T(atCharacterPtr[2] == 'l')) && (JK_EXPECT_T(atCharacterPtr[3] == 's')) && (JK_EXPECT_T(atCharacterPtr[4] == 'e')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 5UL, JKTokenTypeFalse, 5UL); } } else if(JK_EXPECT_T(currentCharacter == 'n')) { if(!((JK_EXPECT_T((atCharacterPtr + 4UL) < endOfStringPtr)) && (JK_EXPECT_T(atCharacterPtr[1] == 'u')) && (JK_EXPECT_T(atCharacterPtr[2] == 'l')) && (JK_EXPECT_T(atCharacterPtr[3] == 'l')))) { stopParsing = 1; /* XXX Add error message */ } else { jk_set_parsed_token(parseState, atCharacterPtr, 4UL, JKTokenTypeNull, 4UL); } } else { stopParsing = 1; /* XXX Add error message */ } } if(JK_EXPECT_F(stopParsing)) { jk_error(parseState, @"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."); } return(stopParsing); } static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String) { NSString *acceptStrings[16]; int acceptIdx = 0; if(state & JKParseAcceptValue) { acceptStrings[acceptIdx++] = or1String; } if(state & JKParseAcceptComma) { acceptStrings[acceptIdx++] = or2String; } if(state & JKParseAcceptEnd) { acceptStrings[acceptIdx++] = or3String; } if(acceptIdx == 1) { jk_error(parseState, @"Expected %@, not '%*.*s'", acceptStrings[0], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } else if(acceptIdx == 2) { jk_error(parseState, @"Expected %@ or %@, not '%*.*s'", acceptStrings[0], acceptStrings[1], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } else if(acceptIdx == 3) { jk_error(parseState, @"Expected %@, %@, or %@, not '%*.*s", acceptStrings[0], acceptStrings[1], acceptStrings[2], (int)parseState->token.tokenPtrRange.length, (int)parseState->token.tokenPtrRange.length, parseState->token.tokenPtrRange.ptr); } } static void *jk_parse_array(JKParseState *parseState) { size_t startingObjectIndex = parseState->objectStack.index; int arrayState = JKParseAcceptValueOrEnd, stopParsing = 0; void *parsedArray = NULL; while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) { if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [array] objectsIndex > %zu, resize failed? %@ line %#ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { void *object = NULL; #ifndef NS_BLOCK_ASSERTIONS parseState->objectStack.objects[parseState->objectStack.index] = NULL; parseState->objectStack.keys [parseState->objectStack.index] = NULL; #endif switch(parseState->token.type) { case JKTokenTypeNumber: case JKTokenTypeString: case JKTokenTypeTrue: case JKTokenTypeFalse: case JKTokenTypeNull: case JKTokenTypeArrayBegin: case JKTokenTypeObjectBegin: if(JK_EXPECT_F((arrayState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; } if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL"); stopParsing = 1; break; } else { parseState->objectStack.objects[parseState->objectStack.index++] = object; arrayState = JKParseAcceptCommaOrEnd; } break; case JKTokenTypeArrayEnd: if(JK_EXPECT_T(arrayState & JKParseAcceptEnd)) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedArray = (void *)_JKArrayCreate((id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ']'."); } stopParsing = 1; break; case JKTokenTypeComma: if(JK_EXPECT_T(arrayState & JKParseAcceptComma)) { arrayState = JKParseAcceptValue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break; default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, arrayState, @"a value", @"a comma", @"a ']'"); stopParsing = 1; break; } } } if(JK_EXPECT_F(parsedArray == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } } #if !defined(NS_BLOCK_ASSERTIONS) else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } } #endif parseState->objectStack.index = startingObjectIndex; return(parsedArray); } static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex) { void *parsedDictionary = NULL; parseState->objectStack.index--; parsedDictionary = _JKDictionaryCreate((id *)&parseState->objectStack.keys[startingObjectIndex], (NSUInteger *)&parseState->objectStack.cfHashes[startingObjectIndex], (id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections); return(parsedDictionary); } static void *jk_parse_dictionary(JKParseState *parseState) { size_t startingObjectIndex = parseState->objectStack.index; int dictState = JKParseAcceptValueOrEnd, stopParsing = 0; void *parsedDictionary = NULL; while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) { if(JK_EXPECT_F(parseState->objectStack.index > (parseState->objectStack.count - 4UL))) { if(jk_objectStack_resize(&parseState->objectStack, parseState->objectStack.count + 128UL)) { jk_error(parseState, @"Internal error: [dictionary] objectsIndex > %zu, resize failed? %@ line #%ld", (parseState->objectStack.count - 4UL), [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } } size_t objectStackIndex = parseState->objectStack.index++; parseState->objectStack.keys[objectStackIndex] = NULL; parseState->objectStack.objects[objectStackIndex] = NULL; void *key = NULL, *object = NULL; if(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)))) { switch(parseState->token.type) { case JKTokenTypeString: if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected string."); stopParsing = 1; break; } if(JK_EXPECT_F((key = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Key == NULL."); stopParsing = 1; break; } else { parseState->objectStack.keys[objectStackIndex] = key; if(JK_EXPECT_T(parseState->token.value.cacheItem != NULL)) { if(JK_EXPECT_F(parseState->token.value.cacheItem->cfHash == 0UL)) { parseState->token.value.cacheItem->cfHash = CFHash(key); } parseState->objectStack.cfHashes[objectStackIndex] = parseState->token.value.cacheItem->cfHash; } else { parseState->objectStack.cfHashes[objectStackIndex] = CFHash(key); } } break; case JKTokenTypeObjectEnd: if((JK_EXPECT_T(dictState & JKParseAcceptEnd))) { NSCParameterAssert(parseState->objectStack.index >= startingObjectIndex); parsedDictionary = jk_create_dictionary(parseState, startingObjectIndex); } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected '}'."); } stopParsing = 1; break; case JKTokenTypeComma: if((JK_EXPECT_T(dictState & JKParseAcceptComma))) { dictState = JKParseAcceptValue; parseState->objectStack.index--; continue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break; default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a \"STRING\"", @"a comma", @"a '}'"); stopParsing = 1; break; } } if(JK_EXPECT_T(stopParsing == 0)) { if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) { if(JK_EXPECT_F(parseState->token.type != JKTokenTypeSeparator)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Expected ':'."); stopParsing = 1; } } } if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) { switch(parseState->token.type) { case JKTokenTypeNumber: case JKTokenTypeString: case JKTokenTypeTrue: case JKTokenTypeFalse: case JKTokenTypeNull: case JKTokenTypeArrayBegin: case JKTokenTypeObjectBegin: if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; } if(JK_EXPECT_F((object = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Object == NULL."); stopParsing = 1; break; } else { parseState->objectStack.objects[objectStackIndex] = object; dictState = JKParseAcceptCommaOrEnd; } break; default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a value", @"a comma", @"a '}'"); stopParsing = 1; break; } } } if(JK_EXPECT_F(parsedDictionary == NULL)) { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { if(parseState->objectStack.keys[idx] != NULL) { CFRelease(parseState->objectStack.keys[idx]); parseState->objectStack.keys[idx] = NULL; } if(parseState->objectStack.objects[idx] != NULL) { CFRelease(parseState->objectStack.objects[idx]); parseState->objectStack.objects[idx] = NULL; } } } #if !defined(NS_BLOCK_ASSERTIONS) else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } } #endif parseState->objectStack.index = startingObjectIndex; return(parsedDictionary); } static id json_parse_it(JKParseState *parseState) { id parsedObject = NULL; int stopParsing = 0; while((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length))) { if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) { switch(parseState->token.type) { case JKTokenTypeArrayBegin: case JKTokenTypeObjectBegin: parsedObject = [(id)jk_object_for_token(parseState) autorelease]; stopParsing = 1; break; default: jk_error(parseState, @"Expected either '[' or '{'."); stopParsing = 1; break; } } } NSCParameterAssert((parseState->objectStack.index == 0) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState))); if((parsedObject == NULL) && (JK_AT_STRING_PTR(parseState) == JK_END_STRING_PTR(parseState))) { jk_error(parseState, @"Reached the end of the buffer."); } if(parsedObject == NULL) { jk_error(parseState, @"Unable to parse JSON."); } if((parsedObject != NULL) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) { jk_parse_skip_whitespace(parseState); if((parsedObject != NULL) && ((parseState->parseOptionFlags & JKParseOptionPermitTextAfterValidJSON) == 0) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) { jk_error(parseState, @"A valid JSON object was parsed but there were additional non-white-space characters remaining."); parsedObject = NULL; } } return(parsedObject); } //////////// #pragma mark - #pragma mark Object cache // This uses a Galois Linear Feedback Shift Register (LFSR) PRNG to pick which item in the cache to age. It has a period of (2^32)-1. // NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value. The LFSR is initalized to 1 in -initWithParseOptions: JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) { NSCParameterAssert((parseState != NULL) && (parseState->cache.prng_lfsr != 0U)); parseState->cache.prng_lfsr = (parseState->cache.prng_lfsr >> 1) ^ ((0U - (parseState->cache.prng_lfsr & 1U)) & 0x80200003U); parseState->cache.age[parseState->cache.prng_lfsr & (parseState->cache.count - 1UL)] >>= 1; } // The object cache is nothing more than a hash table with open addressing collision resolution that is bounded by JK_CACHE_PROBES attempts. // // The hash table is a linear C array of JKTokenCacheItem. The terms "item" and "bucket" are synonymous with the index in to the cache array, i.e. cache.items[bucket]. // // Items in the cache have an age associated with them. An items age is incremented using saturating unsigned arithmetic and decremeted using unsigned right shifts. // Thus, an items age is managed using an AIMD policy- additive increase, multiplicative decrease. All age calculations and manipulations are branchless. // The primitive C type MUST be unsigned. It is currently a "char", which allows (at a minimum and in practice) 8 bits. // // A "useable bucket" is a bucket that is not in use (never populated), or has an age == 0. // // When an item is found in the cache, it's age is incremented. // If a useable bucket hasn't been found, the current item (bucket) is aged along with two random items. // // If a value is not found in the cache, and no useable bucket has been found, that value is not added to the cache. static void *jk_cachedObjects(JKParseState *parseState) { unsigned long bucket = parseState->token.value.hash & (parseState->cache.count - 1UL), setBucket = 0UL, useableBucket = 0UL, x = 0UL; void *parsedAtom = NULL; if(JK_EXPECT_F(parseState->token.value.ptrRange.length == 0UL) && JK_EXPECT_T(parseState->token.value.type == JKValueTypeString)) { return(@""); } for(x = 0UL; x < JK_CACHE_PROBES; x++) { if(JK_EXPECT_F(parseState->cache.items[bucket].object == NULL)) { setBucket = 1UL; useableBucket = bucket; break; } if((JK_EXPECT_T(parseState->cache.items[bucket].hash == parseState->token.value.hash)) && (JK_EXPECT_T(parseState->cache.items[bucket].size == parseState->token.value.ptrRange.length)) && (JK_EXPECT_T(parseState->cache.items[bucket].type == parseState->token.value.type)) && (JK_EXPECT_T(parseState->cache.items[bucket].bytes != NULL)) && (JK_EXPECT_T(memcmp(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length) == 0U))) { parseState->cache.age[bucket] = (((uint32_t)parseState->cache.age[bucket]) + 1U) - (((((uint32_t)parseState->cache.age[bucket]) + 1U) >> 31) ^ 1U); parseState->token.value.cacheItem = &parseState->cache.items[bucket]; NSCParameterAssert(parseState->cache.items[bucket].object != NULL); return((void *)CFRetain(parseState->cache.items[bucket].object)); } else { if(JK_EXPECT_F(setBucket == 0UL) && JK_EXPECT_F(parseState->cache.age[bucket] == 0U)) { setBucket = 1UL; useableBucket = bucket; } if(JK_EXPECT_F(setBucket == 0UL)) { parseState->cache.age[bucket] >>= 1; jk_cache_age(parseState); jk_cache_age(parseState); } // This is the open addressing function. The values length and type are used as a form of "double hashing" to distribute values with the same effective value hash across different object cache buckets. // The values type is a prime number that is relatively coprime to the other primes in the set of value types and the number of hash table buckets. bucket = (parseState->token.value.hash + (parseState->token.value.ptrRange.length * (x + 1UL)) + (parseState->token.value.type * (x + 1UL)) + (3UL * (x + 1UL))) & (parseState->cache.count - 1UL); } } switch(parseState->token.value.type) { case JKValueTypeString: parsedAtom = (void *)CFStringCreateWithBytes(NULL, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length, kCFStringEncodingUTF8, 0); break; case JKValueTypeLongLong: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.longLongValue); break; case JKValueTypeUnsignedLongLong: if(parseState->token.value.number.unsignedLongLongValue <= LLONG_MAX) { parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.unsignedLongLongValue); } else { parsedAtom = (void *)parseState->objCImpCache.NSNumberInitWithUnsignedLongLong(parseState->objCImpCache.NSNumberAlloc(parseState->objCImpCache.NSNumberClass, @selector(alloc)), @selector(initWithUnsignedLongLong:), parseState->token.value.number.unsignedLongLongValue); } break; case JKValueTypeDouble: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberDoubleType, &parseState->token.value.number.doubleValue); break; default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } if(JK_EXPECT_T(setBucket) && (JK_EXPECT_T(parsedAtom != NULL))) { bucket = useableBucket; if(JK_EXPECT_T((parseState->cache.items[bucket].object != NULL))) { CFRelease(parseState->cache.items[bucket].object); parseState->cache.items[bucket].object = NULL; } if(JK_EXPECT_T((parseState->cache.items[bucket].bytes = (unsigned char *)reallocf(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.length)) != NULL)) { memcpy(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length); parseState->cache.items[bucket].object = (void *)CFRetain(parsedAtom); parseState->cache.items[bucket].hash = parseState->token.value.hash; parseState->cache.items[bucket].cfHash = 0UL; parseState->cache.items[bucket].size = parseState->token.value.ptrRange.length; parseState->cache.items[bucket].type = parseState->token.value.type; parseState->token.value.cacheItem = &parseState->cache.items[bucket]; parseState->cache.age[bucket] = JK_INIT_CACHE_AGE; } else { // The realloc failed, so clear the appropriate fields. parseState->cache.items[bucket].hash = 0UL; parseState->cache.items[bucket].cfHash = 0UL; parseState->cache.items[bucket].size = 0UL; parseState->cache.items[bucket].type = 0UL; } } return(parsedAtom); } static void *jk_object_for_token(JKParseState *parseState) { void *parsedAtom = NULL; parseState->token.value.cacheItem = NULL; switch(parseState->token.type) { case JKTokenTypeString: parsedAtom = jk_cachedObjects(parseState); break; case JKTokenTypeNumber: parsedAtom = jk_cachedObjects(parseState); break; case JKTokenTypeObjectBegin: parsedAtom = jk_parse_dictionary(parseState); break; case JKTokenTypeArrayBegin: parsedAtom = jk_parse_array(parseState); break; case JKTokenTypeTrue: parsedAtom = (void *)kCFBooleanTrue; break; case JKTokenTypeFalse: parsedAtom = (void *)kCFBooleanFalse; break; case JKTokenTypeNull: parsedAtom = (void *)kCFNull; break; default: jk_error(parseState, @"Internal error: Unknown token type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break; } return(parsedAtom); } #pragma mark - @implementation JSONDecoder + (id)decoder { return([self decoderWithParseOptions:JKParseOptionStrict]); } + (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags { return([[[self alloc] initWithParseOptions:parseOptionFlags] autorelease]); } - (id)init { return([self initWithParseOptions:JKParseOptionStrict]); } - (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags { if((self = [super init]) == NULL) { return(NULL); } if(parseOptionFlags & ~JKParseOptionValidFlags) { [self autorelease]; [NSException raise:NSInvalidArgumentException format:@"Invalid parse options."]; } if((parseState = (JKParseState *)calloc(1UL, sizeof(JKParseState))) == NULL) { goto errorExit; } parseState->parseOptionFlags = parseOptionFlags; parseState->token.tokenBuffer.roundSizeUpToMultipleOf = 4096UL; parseState->objectStack.roundSizeUpToMultipleOf = 2048UL; parseState->objCImpCache.NSNumberClass = _jk_NSNumberClass; parseState->objCImpCache.NSNumberAlloc = _jk_NSNumberAllocImp; parseState->objCImpCache.NSNumberInitWithUnsignedLongLong = _jk_NSNumberInitWithUnsignedLongLongImp; parseState->cache.prng_lfsr = 1U; parseState->cache.count = JK_CACHE_SLOTS; if((parseState->cache.items = (JKTokenCacheItem *)calloc(1UL, sizeof(JKTokenCacheItem) * parseState->cache.count)) == NULL) { goto errorExit; } return(self); errorExit: if(self) { [self autorelease]; self = NULL; } return(NULL); } // This is here primarily to support the NSString and NSData convenience functions so the autoreleased JSONDecoder can release most of its resources before the pool pops. static void _JSONDecoderCleanup(JSONDecoder *decoder) { if((decoder != NULL) && (decoder->parseState != NULL)) { jk_managedBuffer_release(&decoder->parseState->token.tokenBuffer); jk_objectStack_release(&decoder->parseState->objectStack); [decoder clearCache]; if(decoder->parseState->cache.items != NULL) { free(decoder->parseState->cache.items); decoder->parseState->cache.items = NULL; } free(decoder->parseState); decoder->parseState = NULL; } } - (void)dealloc { _JSONDecoderCleanup(self); [super dealloc]; } - (void)clearCache { if(JK_EXPECT_T(parseState != NULL)) { if(JK_EXPECT_T(parseState->cache.items != NULL)) { size_t idx = 0UL; for(idx = 0UL; idx < parseState->cache.count; idx++) { if(JK_EXPECT_T(parseState->cache.items[idx].object != NULL)) { CFRelease(parseState->cache.items[idx].object); parseState->cache.items[idx].object = NULL; } if(JK_EXPECT_T(parseState->cache.items[idx].bytes != NULL)) { free(parseState->cache.items[idx].bytes); parseState->cache.items[idx].bytes = NULL; } memset(&parseState->cache.items[idx], 0, sizeof(JKTokenCacheItem)); parseState->cache.age[idx] = 0U; } } } } // This needs to be completely rewritten. static id _JKParseUTF8String(JKParseState *parseState, BOOL mutableCollections, const unsigned char *string, size_t length, NSError **error) { NSCParameterAssert((parseState != NULL) && (string != NULL) && (parseState->cache.prng_lfsr != 0U)); parseState->stringBuffer.bytes.ptr = string; parseState->stringBuffer.bytes.length = length; parseState->atIndex = 0UL; parseState->lineNumber = 1UL; parseState->lineStartIndex = 0UL; parseState->prev_atIndex = 0UL; parseState->prev_lineNumber = 1UL; parseState->prev_lineStartIndex = 0UL; parseState->error = NULL; parseState->errorIsPrev = 0; parseState->mutableCollections = (mutableCollections == NO) ? NO : YES; unsigned char stackTokenBuffer[JK_TOKENBUFFER_SIZE] JK_ALIGNED(64); jk_managedBuffer_setToStackBuffer(&parseState->token.tokenBuffer, stackTokenBuffer, sizeof(stackTokenBuffer)); void *stackObjects [JK_STACK_OBJS] JK_ALIGNED(64); void *stackKeys [JK_STACK_OBJS] JK_ALIGNED(64); CFHashCode stackCFHashes[JK_STACK_OBJS] JK_ALIGNED(64); jk_objectStack_setToStackBuffer(&parseState->objectStack, stackObjects, stackKeys, stackCFHashes, JK_STACK_OBJS); id parsedJSON = json_parse_it(parseState); if((error != NULL) && (parseState->error != NULL)) { *error = parseState->error; } jk_managedBuffer_release(&parseState->token.tokenBuffer); jk_objectStack_release(&parseState->objectStack); parseState->stringBuffer.bytes.ptr = NULL; parseState->stringBuffer.bytes.length = 0UL; parseState->atIndex = 0UL; parseState->lineNumber = 1UL; parseState->lineStartIndex = 0UL; parseState->prev_atIndex = 0UL; parseState->prev_lineNumber = 1UL; parseState->prev_lineStartIndex = 0UL; parseState->error = NULL; parseState->errorIsPrev = 0; parseState->mutableCollections = NO; return(parsedJSON); } //////////// #pragma mark Deprecated as of v1.4 //////////// // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead. - (id)parseUTF8String:(const unsigned char *)string length:(size_t)length { return([self objectWithUTF8String:string length:length error:NULL]); } // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead. - (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error { return([self objectWithUTF8String:string length:length error:error]); } // Deprecated in JSONKit v1.4. Use objectWithData: instead. - (id)parseJSONData:(NSData *)jsonData { return([self objectWithData:jsonData error:NULL]); } // Deprecated in JSONKit v1.4. Use objectWithData:error: instead. - (id)parseJSONData:(NSData *)jsonData error:(NSError **)error { return([self objectWithData:jsonData error:error]); } //////////// #pragma mark Methods that return immutable collection objects //////////// - (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length { return([self objectWithUTF8String:string length:length error:NULL]); } - (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error { if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; } if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; } return(_JKParseUTF8String(parseState, NO, string, (size_t)length, error)); } - (id)objectWithData:(NSData *)jsonData { return([self objectWithData:jsonData error:NULL]); } - (id)objectWithData:(NSData *)jsonData error:(NSError **)error { if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; } return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]); } //////////// #pragma mark Methods that return mutable collection objects //////////// - (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length { return([self mutableObjectWithUTF8String:string length:length error:NULL]); } - (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error { if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; } if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; } return(_JKParseUTF8String(parseState, YES, string, (size_t)length, error)); } - (id)mutableObjectWithData:(NSData *)jsonData { return([self mutableObjectWithData:jsonData error:NULL]); } - (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error { if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; } return([self mutableObjectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]); } @end /* The NSString and NSData convenience methods need a little bit of explanation. Prior to JSONKit v1.4, the NSString -objectFromJSONStringWithParseOptions:error: method looked like const unsigned char *utf8String = (const unsigned char *)[self UTF8String]; if(utf8String == NULL) { return(NULL); } size_t utf8Length = strlen((const char *)utf8String); return([[JSONDecoder decoderWithParseOptions:parseOptionFlags] parseUTF8String:utf8String length:utf8Length error:error]); This changed with v1.4 to a more complicated method. The reason for this is to keep the amount of memory that is allocated, but not yet freed because it is dependent on the autorelease pool to pop before it can be reclaimed. In the simpler v1.3 code, this included all the bytes used to store the -UTF8String along with the JSONDecoder and all its overhead. Now we use an autoreleased CFMutableData that is sized to the UTF8 length of the NSString in question and is used to hold the UTF8 conversion of said string. Once parsed, the CFMutableData has its length set to 0. This should, hopefully, allow the CFMutableData to realloc and/or free the buffer. Another change made was a slight modification to JSONDecoder so that most of the cleanup work that was done in -dealloc was moved to a private, internal function. These convenience routines keep the pointer to the autoreleased JSONDecoder and calls _JSONDecoderCleanup() to early release the decoders resources since we already know that particular decoder is not going to be used again. If everything goes smoothly, this will most likely result in perhaps a few hundred bytes that are allocated but waiting for the autorelease pool to pop. This is compared to the thousands and easily hundreds of thousands of bytes that would have been in autorelease limbo. It's more complicated for us, but a win for the user. Autorelease objects are used in case things don't go smoothly. By having them autoreleased, we effectively guarantee that our requirement to -release the object is always met, not matter what goes wrong. The downside is having a an object or two in autorelease limbo, but we've done our best to minimize that impact, so it all balances out. */ @implementation NSString (JSONKitDeserializing) static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection) { id returnObject = NULL; CFMutableDataRef mutableData = NULL; JSONDecoder *decoder = NULL; CFIndex stringLength = CFStringGetLength((CFStringRef)jsonString); NSUInteger stringUTF8Length = [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; if((mutableData = (CFMutableDataRef)[(id)CFDataCreateMutable(NULL, (NSUInteger)stringUTF8Length) autorelease]) != NULL) { UInt8 *utf8String = CFDataGetMutableBytePtr(mutableData); CFIndex usedBytes = 0L, convertedCount = 0L; convertedCount = CFStringGetBytes((CFStringRef)jsonString, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, utf8String, (NSUInteger)stringUTF8Length, &usedBytes); if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { if(error != NULL) { *error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:[NSDictionary dictionaryWithObject:@"An error occurred converting the contents of a NSString to UTF8." forKey:NSLocalizedDescriptionKey]]; } goto exitNow; } if(mutableCollection == NO) { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; } else { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; } } exitNow: if(mutableData != NULL) { CFDataSetLength(mutableData, 0L); } if(decoder != NULL) { _JSONDecoderCleanup(decoder); } return(returnObject); } - (id)objectFromJSONString { return([self objectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]); } - (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags { return([self objectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]); } - (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error { return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, NO)); } - (id)mutableObjectFromJSONString { return([self mutableObjectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]); } - (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags { return([self mutableObjectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]); } - (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error { return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, YES)); } @end @implementation NSData (JSONKitDeserializing) - (id)objectFromJSONData { return([self objectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]); } - (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags { return([self objectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]); } - (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error { JSONDecoder *decoder = NULL; id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithData:self error:error]; if(decoder != NULL) { _JSONDecoderCleanup(decoder); } return(returnObject); } - (id)mutableObjectFromJSONData { return([self mutableObjectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]); } - (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags { return([self mutableObjectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]); } - (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error { JSONDecoder *decoder = NULL; id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithData:self error:error]; if(decoder != NULL) { _JSONDecoderCleanup(decoder); } return(returnObject); } @end //////////// #pragma mark - #pragma mark Encoding / deserializing functions static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...) { NSCParameterAssert((encodeState != NULL) && (format != NULL)); va_list varArgsList; va_start(varArgsList, format); NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease]; va_end(varArgsList); if(encodeState->error == NULL) { encodeState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo: [NSDictionary dictionaryWithObjectsAndKeys: formatString, NSLocalizedDescriptionKey, NULL]]; } } JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object) { NSCParameterAssert(encodeState != NULL); if(JK_EXPECT_T(cacheSlot != NULL)) { NSCParameterAssert((object != NULL) && (startingAtIndex <= encodeState->atIndex)); cacheSlot->object = object; cacheSlot->offset = startingAtIndex; cacheSlot->length = (size_t)(encodeState->atIndex - startingAtIndex); } } static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...) { va_list varArgsList, varArgsListCopy; va_start(varArgsList, format); va_copy(varArgsListCopy, varArgsList); NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL)); ssize_t formattedStringLength = 0L; int returnValue = 0; if(JK_EXPECT_T((formattedStringLength = vsnprintf((char *)&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex], (encodeState->stringBuffer.bytes.length - encodeState->atIndex), format, varArgsList)) >= (ssize_t)(encodeState->stringBuffer.bytes.length - encodeState->atIndex))) { NSCParameterAssert(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)); if(JK_EXPECT_F(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (formattedStringLength * 2UL)+ 4096UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); returnValue = 1; goto exitNow; } if(JK_EXPECT_F((formattedStringLength = vsnprintf((char *)&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex], (encodeState->stringBuffer.bytes.length - encodeState->atIndex), format, varArgsListCopy)) >= (ssize_t)(encodeState->stringBuffer.bytes.length - encodeState->atIndex))) { jk_encode_error(encodeState, @"vsnprintf failed unexpectedly."); returnValue = 1; goto exitNow; } } exitNow: va_end(varArgsList); va_end(varArgsListCopy); if(JK_EXPECT_T(returnValue == 0)) { encodeState->atIndex += formattedStringLength; jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); } return(returnValue); } static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format) { NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL)); if(JK_EXPECT_F(((encodeState->atIndex + strlen(format) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + strlen(format) + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } size_t formatIdx = 0UL; for(formatIdx = 0UL; format[formatIdx] != 0; formatIdx++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[formatIdx]; } jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); return(0); } static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState) { NSCParameterAssert((encodeState != NULL) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL)); if(JK_EXPECT_F((encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 16UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_T(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 4096UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\n'; size_t depthWhiteSpace = 0UL; for(depthWhiteSpace = 0UL; depthWhiteSpace < (encodeState->depth * 2UL); depthWhiteSpace++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; } return(0); } static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format) { NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (format != NULL) && ((depthChange >= -1L) && (depthChange <= 1L)) && ((encodeState->depth == 0UL) ? (depthChange >= 0L) : 1) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL)); if(JK_EXPECT_F((encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 16UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + ((encodeState->depth + 1UL) * 2UL) + 4096UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } encodeState->depth += depthChange; if(JK_EXPECT_T(format[0] == ':')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; } else { if(JK_EXPECT_F(depthChange == -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } } encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; if(JK_EXPECT_T(depthChange != -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } } } NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); return(0); } static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format) { NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0UL)); if(JK_EXPECT_T((encodeState->atIndex + 4UL) < encodeState->stringBuffer.bytes.length)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; } else { return(jk_encode_write(encodeState, NULL, 0UL, NULL, format)); } return(0); } static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length) { NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex)); if(JK_EXPECT_F((encodeState->stringBuffer.bytes.length - encodeState->atIndex) < (length + 4UL))) { if(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + 4096UL + length) == NULL) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } } memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, format, length); encodeState->atIndex += length; jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); return(0); } JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr) { return( ( (((JKHash)objectPtr) >> 21) ^ (((JKHash)objectPtr) >> 9) ) + (((JKHash)objectPtr) >> 4) ); } static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr) { NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (objectPtr != NULL)); id object = (id)objectPtr, encodeCacheObject = object; int isClass = JKClassUnknown; size_t startingAtIndex = encodeState->atIndex; JKHash objectHash = jk_encode_object_hash(objectPtr); JKEncodeCache *cacheSlot = &encodeState->cache[objectHash % JK_ENCODE_CACHE_SLOTS]; if(JK_EXPECT_T(cacheSlot->object == object)) { NSCParameterAssert((cacheSlot->object != NULL) && (cacheSlot->offset < encodeState->atIndex) && ((cacheSlot->offset + cacheSlot->length) < encodeState->atIndex) && (cacheSlot->offset < encodeState->stringBuffer.bytes.length) && ((cacheSlot->offset + cacheSlot->length) < encodeState->stringBuffer.bytes.length) && ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length))); if(JK_EXPECT_F(((encodeState->atIndex + cacheSlot->length + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + cacheSlot->length + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } NSCParameterAssert(((encodeState->atIndex + cacheSlot->length) < encodeState->stringBuffer.bytes.length) && ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) && ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->atIndex))); memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, encodeState->stringBuffer.bytes.ptr + cacheSlot->offset, cacheSlot->length); encodeState->atIndex += cacheSlot->length; return(0); } // When we encounter a class that we do not handle, and we have either a delegate or block that the user supplied to format unsupported classes, // we "re-run" the object check. However, we re-run the object check exactly ONCE. If the user supplies an object that isn't one of the // supported classes, we fail the second time (i.e., double fault error). BOOL rerunningAfterClassFormatter = NO; rerunAfterClassFormatter:; // XXX XXX XXX XXX // // We need to work around a bug in 10.7, which breaks ABI compatibility with Objective-C going back not just to 10.0, but OpenStep and even NextStep. // // It has long been documented that "the very first thing that a pointer to an Objective-C object "points to" is a pointer to that objects class". // // This is euphemistically called "tagged pointers". There are a number of highly technical problems with this, most involving long passages from // the C standard(s). In short, one can make a strong case, couched from the perspective of the C standard(s), that that 10.7 "tagged pointers" are // fundamentally Wrong and Broken, and should have never been implemented. Assuming those points are glossed over, because the change is very clearly // breaking ABI compatibility, this should have resulted in a minimum of a "minimum version required" bump in various shared libraries to prevent // causes code that used to work just fine to suddenly break without warning. // // In fact, the C standard says that the hack below is "undefined behavior"- there is no requirement that the 10.7 tagged pointer hack of setting the // "lower, unused bits" must be preserved when casting the result to an integer type, but this "works" because for most architectures // `sizeof(long) == sizeof(void *)` and the compiler uses the same representation for both. (note: this is informal, not meant to be // normative or pedantically correct). // // In other words, while this "works" for now, technically the compiler is not obligated to do "what we want", and a later version of the compiler // is not required in any way to produce the same results or behavior that earlier versions of the compiler did for the statement below. // // Fan-fucking-tastic. // // Why not just use `object_getClass()`? Because `object->isa` reduces to (typically) a *single* instruction. Calling `object_getClass()` requires // that the compiler potentially spill registers, establish a function call frame / environment, and finally execute a "jump subroutine" instruction. // Then, the called subroutine must spend half a dozen instructions in its prolog, however many instructions doing whatever it does, then half a dozen // instructions in its prolog. One instruction compared to dozens, maybe a hundred instructions. // // Yes, that's one to two orders of magnitude difference. Which is compelling in its own right. When going for performance, you're often happy with // gains in the two to three percent range. // // XXX XXX XXX XXX #pragma clang diagnostic push #pragma clang diagnostic ignored"-Wdeprecated-objc-pointer-introspection" BOOL workAroundMacOSXABIBreakingBug = (JK_EXPECT_F(((NSUInteger)object) &0x1)) ? YES : NO; #pragma clang diagnostic pop // BOOL workAroundMacOSXABIBreakingBug = (JK_EXPECT_F(((NSUInteger)object) & 0x1)) ? YES : NO; void *objectISA = (JK_EXPECT_F(workAroundMacOSXABIBreakingBug)) ? NULL : *((void **)objectPtr); if(JK_EXPECT_F(workAroundMacOSXABIBreakingBug)) { goto slowClassLookup; } if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; } else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; } else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; } else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; } else if(JK_EXPECT_T(objectISA == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; } else { slowClassLookup: if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.stringClass = objectISA; } isClass = JKClassString; } else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.numberClass = objectISA; } isClass = JKClassNumber; } else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.dictionaryClass = objectISA; } isClass = JKClassDictionary; } else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.arrayClass = objectISA; } isClass = JKClassArray; } else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { if(workAroundMacOSXABIBreakingBug == NO) { encodeState->fastClassLookup.nullClass = objectISA; } isClass = JKClassNull; } else { if((rerunningAfterClassFormatter == NO) && ( #ifdef __BLOCKS__ ((encodeState->classFormatterBlock) && ((object = encodeState->classFormatterBlock(object)) != NULL)) || #endif ((encodeState->classFormatterIMP) && ((object = encodeState->classFormatterIMP(encodeState->classFormatterDelegate, encodeState->classFormatterSelector, object)) != NULL)) )) { rerunningAfterClassFormatter = YES; goto rerunAfterClassFormatter; } if(rerunningAfterClassFormatter == NO) { jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([encodeCacheObject class])); return(1); } else { jk_encode_error(encodeState, @"Unable to serialize object class %@ that was returned by the unsupported class formatter. Original object class was %@.", (object == NULL) ? @"NULL" : NSStringFromClass([object class]), NSStringFromClass([encodeCacheObject class])); return(1); } } } // This is here for the benefit of the optimizer. It allows the optimizer to do loop invariant code motion for the JKClassArray // and JKClassDictionary cases when printing simple, single characters via jk_encode_write(), which is actually a macro: // #define jk_encode_write1(es, dc, f) (_jk_encode_prettyPrint ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f)) int _jk_encode_prettyPrint = JK_EXPECT_T((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0) ? 0 : 1; switch(isClass) { case JKClassString: { { const unsigned char *cStringPtr = (const unsigned char *)CFStringGetCStringPtr((CFStringRef)object, kCFStringEncodingMacRoman); if(cStringPtr != NULL) { const unsigned char *utf8String = cStringPtr; size_t utf8Idx = 0UL; CFIndex stringLength = CFStringGetLength((CFStringRef)object); if(JK_EXPECT_F(((encodeState->atIndex + (stringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length)) && JK_EXPECT_F((jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (stringLength * 2UL) + 1024UL) == NULL))) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } for(utf8Idx = 0UL; utf8String[utf8Idx] != 0U; utf8Idx++) { NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length); NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U)) { encodeState->atIndex = startingAtIndex; goto slowUTF8Path; } if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) { switch(utf8String[utf8Idx]) { case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break; case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break; case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break; case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break; case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break; default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break; } } else { if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\') || (JK_EXPECT_F(encodeState->serializeOptionFlags & JKSerializeOptionEscapeForwardSlashes) && JK_EXPECT_F(utf8String[utf8Idx] == '/'))) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; } encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx]; } } NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length); if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject); return(0); } } slowUTF8Path: { CFIndex stringLength = CFStringGetLength((CFStringRef)object); CFIndex maxStringUTF8Length = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 32L; if(JK_EXPECT_F((size_t)maxStringUTF8Length > encodeState->utf8ConversionBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->utf8ConversionBuffer, maxStringUTF8Length + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } CFIndex usedBytes = 0L, convertedCount = 0L; convertedCount = CFStringGetBytes((CFStringRef)object, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, encodeState->utf8ConversionBuffer.bytes.ptr, encodeState->utf8ConversionBuffer.bytes.length - 16L, &usedBytes); if(JK_EXPECT_F(convertedCount != stringLength) || JK_EXPECT_F(usedBytes < 0L)) { jk_encode_error(encodeState, @"An error occurred converting the contents of a NSString to UTF8."); return(1); } if(JK_EXPECT_F((encodeState->atIndex + (maxStringUTF8Length * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length) && JK_EXPECT_F(jk_managedBuffer_resize(&encodeState->stringBuffer, encodeState->atIndex + (maxStringUTF8Length * 2UL) + 1024UL) == NULL)) { jk_encode_error(encodeState, @"Unable to resize temporary buffer."); return(1); } const unsigned char *utf8String = encodeState->utf8ConversionBuffer.bytes.ptr; size_t utf8Idx = 0UL; if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } for(utf8Idx = 0UL; utf8Idx < (size_t)usedBytes; utf8Idx++) { NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length); NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); NSCParameterAssert((CFIndex)utf8Idx < usedBytes); if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) { switch(utf8String[utf8Idx]) { case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break; case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break; case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break; case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break; case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break; default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break; } } else { if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U) && (encodeState->serializeOptionFlags & JKSerializeOptionEscapeUnicode)) { const unsigned char *nextValidCharacter = NULL; UTF32 u32ch = 0U; ConversionResult result; if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(&utf8String[utf8Idx], &utf8String[usedBytes], (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { jk_encode_error(encodeState, @"Error converting UTF8."); return(1); } else { utf8Idx = (nextValidCharacter - utf8String) - 1UL; if(JK_EXPECT_T(u32ch <= 0xffffU)) { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", u32ch))) { return(1); } } else { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x\\u%4.4x", (0xd7c0U + (u32ch >> 10)), (0xdc00U + (u32ch & 0x3ffU))))) { return(1); } } } } else { if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\') || (JK_EXPECT_F(encodeState->serializeOptionFlags & JKSerializeOptionEscapeForwardSlashes) && JK_EXPECT_F(utf8String[utf8Idx] == '/'))) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; } encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx]; } } } NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length); if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; } jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, encodeCacheObject); return(0); } } break; case JKClassNumber: { if(object == (id)kCFBooleanTrue) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "true", 4UL)); } else if(object == (id)kCFBooleanFalse) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "false", 5UL)); } const char *objCType = [object objCType]; char anum[256], *aptr = &anum[255]; int isNegative = 0; unsigned long long ullv; long long llv; if(JK_EXPECT_F(objCType == NULL) || JK_EXPECT_F(objCType[0] == 0) || JK_EXPECT_F(objCType[1] != 0)) { jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%s'", (objCType == NULL) ? "<NULL>" : objCType); return(1); } switch(objCType[0]) { case 'c': case 'i': case 's': case 'l': case 'q': if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &llv))) { if(llv < 0LL) { ullv = -llv; isNegative = 1; } else { ullv = llv; isNegative = 0; } goto convertNumber; } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); } break; case 'C': case 'I': case 'S': case 'L': case 'Q': case 'B': if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &ullv))) { convertNumber: if(JK_EXPECT_F(ullv < 10ULL)) { *--aptr = ullv + '0'; } else { while(JK_EXPECT_T(ullv > 0ULL)) { *--aptr = (ullv % 10ULL) + '0'; ullv /= 10ULL; NSCParameterAssert(aptr > anum); } } if(isNegative) { *--aptr = '-'; } NSCParameterAssert(aptr > anum); return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, aptr, &anum[255] - aptr)); } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); } break; case 'f': case 'd': { double dv; if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberDoubleType, &dv))) { if(JK_EXPECT_F(!isfinite(dv))) { jk_encode_error(encodeState, @"Floating point values must be finite. JSON does not support NaN or Infinity."); return(1); } return(jk_encode_printf(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "%.17g", dv)); } else { jk_encode_error(encodeState, @"Unable to get floating point value from number object."); return(1); } } break; default: jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%c' / 0x%2.2x", objCType[0], objCType[0]); return(1); break; } } break; case JKClassArray: { int printComma = 0; CFIndex arrayCount = CFArrayGetCount((CFArrayRef)object), idx = 0L; if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "["))) { return(1); } if(JK_EXPECT_F(arrayCount > 1020L)) { for(id arrayObject in object) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, arrayObject))) { return(1); } } } else { void *objects[1024]; CFArrayGetValues((CFArrayRef)object, CFRangeMake(0L, arrayCount), (const void **)objects); for(idx = 0L; idx < arrayCount; idx++) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } } } return(jk_encode_write1(encodeState, -1L, "]")); } break; case JKClassDictionary: { int printComma = 0; CFIndex dictionaryCount = CFDictionaryGetCount((CFDictionaryRef)object), idx = 0L; id enumerateObject = JK_EXPECT_F(_jk_encode_prettyPrint) ? [[object allKeys] sortedArrayUsingSelector:@selector(compare:)] : object; if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "{"))) { return(1); } if(JK_EXPECT_F(_jk_encode_prettyPrint) || JK_EXPECT_F(dictionaryCount > 1020L)) { for(id keyObject in enumerateObject) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; void *keyObjectISA = *((void **)keyObject); if(JK_EXPECT_F((keyObjectISA != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keyObject))) { return(1); } if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, (void *)CFDictionaryGetValue((CFDictionaryRef)object, keyObject)))) { return(1); } } } else { void *keys[1024], *objects[1024]; CFDictionaryGetKeysAndValues((CFDictionaryRef)object, (const void **)keys, (const void **)objects); for(idx = 0L; idx < dictionaryCount; idx++) { if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } } printComma = 1; void *keyObjectISA = *((void **)keys[idx]); if(JK_EXPECT_F(keyObjectISA != encodeState->fastClassLookup.stringClass) && JK_EXPECT_F([(id)keys[idx] isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); } if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keys[idx]))) { return(1); } if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); } if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); } } } return(jk_encode_write1(encodeState, -1L, "}")); } break; case JKClassNull: return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, encodeCacheObject, "null", 4UL)); break; default: jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); break; } return(0); } @implementation JKSerializer + (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error { return([[[[self alloc] init] autorelease] serializeObject:object options:optionFlags encodeOption:encodeOption block:block delegate:delegate selector:selector error:error]); } - (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error { #ifndef __BLOCKS__ #pragma unused(block) #endif NSParameterAssert((object != NULL) && (encodeState == NULL) && ((delegate != NULL) ? (block == NULL) : 1) && ((block != NULL) ? (delegate == NULL) : 1) && (((encodeOption & JKEncodeOptionCollectionObj) != 0UL) ? (((encodeOption & JKEncodeOptionStringObj) == 0UL) && ((encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) : 1) && (((encodeOption & JKEncodeOptionStringObj) != 0UL) ? ((encodeOption & JKEncodeOptionCollectionObj) == 0UL) : 1)); id returnObject = NULL; if(encodeState != NULL) { [self releaseState]; } if((encodeState = (struct JKEncodeState *)calloc(1UL, sizeof(JKEncodeState))) == NULL) { [NSException raise:NSMallocException format:@"Unable to allocate state structure."]; return(NULL); } if((error != NULL) && (*error != NULL)) { *error = NULL; } if(delegate != NULL) { if(selector == NULL) { [NSException raise:NSInvalidArgumentException format:@"The delegate argument is not NULL, but the selector argument is NULL."]; } if([delegate respondsToSelector:selector] == NO) { [NSException raise:NSInvalidArgumentException format:@"The serializeUnsupportedClassesUsingDelegate: delegate does not respond to the selector argument."]; } encodeState->classFormatterDelegate = delegate; encodeState->classFormatterSelector = selector; encodeState->classFormatterIMP = (JKClassFormatterIMP)[delegate methodForSelector:selector]; NSCParameterAssert(encodeState->classFormatterIMP != NULL); } #ifdef __BLOCKS__ encodeState->classFormatterBlock = block; #endif encodeState->serializeOptionFlags = optionFlags; encodeState->encodeOption = encodeOption; encodeState->stringBuffer.roundSizeUpToMultipleOf = (1024UL * 32UL); encodeState->utf8ConversionBuffer.roundSizeUpToMultipleOf = 4096UL; unsigned char stackJSONBuffer[JK_JSONBUFFER_SIZE] JK_ALIGNED(64); jk_managedBuffer_setToStackBuffer(&encodeState->stringBuffer, stackJSONBuffer, sizeof(stackJSONBuffer)); unsigned char stackUTF8Buffer[JK_UTF8BUFFER_SIZE] JK_ALIGNED(64); jk_managedBuffer_setToStackBuffer(&encodeState->utf8ConversionBuffer, stackUTF8Buffer, sizeof(stackUTF8Buffer)); if(((encodeOption & JKEncodeOptionCollectionObj) != 0UL) && (([object isKindOfClass:[NSArray class]] == NO) && ([object isKindOfClass:[NSDictionary class]] == NO))) { jk_encode_error(encodeState, @"Unable to serialize object class %@, expected a NSArray or NSDictionary.", NSStringFromClass([object class])); goto errorExit; } if(((encodeOption & JKEncodeOptionStringObj) != 0UL) && ([object isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Unable to serialize object class %@, expected a NSString.", NSStringFromClass([object class])); goto errorExit; } if(jk_encode_add_atom_to_buffer(encodeState, object) == 0) { BOOL stackBuffer = ((encodeState->stringBuffer.flags & JKManagedBufferMustFree) == 0UL) ? YES : NO; if((encodeState->atIndex < 2UL)) if((stackBuffer == NO) && ((encodeState->stringBuffer.bytes.ptr = (unsigned char *)reallocf(encodeState->stringBuffer.bytes.ptr, encodeState->atIndex + 16UL)) == NULL)) { jk_encode_error(encodeState, @"Unable to realloc buffer"); goto errorExit; } switch((encodeOption & JKEncodeOptionAsTypeMask)) { case JKEncodeOptionAsData: if(stackBuffer == YES) { if((returnObject = [(id)CFDataCreate( NULL, encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSData object"); } } else { if((returnObject = [(id)CFDataCreateWithBytesNoCopy( NULL, encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, NULL) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSData object"); } } break; case JKEncodeOptionAsString: if(stackBuffer == YES) { if((returnObject = [(id)CFStringCreateWithBytes( NULL, (const UInt8 *)encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, kCFStringEncodingUTF8, NO) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSString object"); } } else { if((returnObject = [(id)CFStringCreateWithBytesNoCopy(NULL, (const UInt8 *)encodeState->stringBuffer.bytes.ptr, (CFIndex)encodeState->atIndex, kCFStringEncodingUTF8, NO, NULL) autorelease]) == NULL) { jk_encode_error(encodeState, @"Unable to create NSString object"); } } break; default: jk_encode_error(encodeState, @"Unknown encode as type."); break; } if((returnObject != NULL) && (stackBuffer == NO)) { encodeState->stringBuffer.flags &= ~JKManagedBufferMustFree; encodeState->stringBuffer.bytes.ptr = NULL; encodeState->stringBuffer.bytes.length = 0UL; } } errorExit: if((encodeState != NULL) && (error != NULL) && (encodeState->error != NULL)) { *error = encodeState->error; encodeState->error = NULL; } [self releaseState]; return(returnObject); } - (void)releaseState { if(encodeState != NULL) { jk_managedBuffer_release(&encodeState->stringBuffer); jk_managedBuffer_release(&encodeState->utf8ConversionBuffer); free(encodeState); encodeState = NULL; } } - (void)dealloc { [self releaseState]; [super dealloc]; } @end @implementation NSString (JSONKitSerializing) //////////// #pragma mark Methods for serializing a single NSString. //////////// // Useful for those who need to serialize just a NSString. Otherwise you would have to do something like [NSArray arrayWithObject:stringToBeJSONSerialized], serializing the array, and then chopping of the extra ^\[.*\]$ square brackets. // NSData returning methods... - (NSData *)JSONData { return([self JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]); } - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]); } // NSString returning methods... - (NSString *)JSONString { return([self JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]); } - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) block:NULL delegate:NULL selector:NULL error:error]); } @end @implementation NSArray (JSONKitSerializing) // NSData returning methods... - (NSData *)JSONData { return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); } - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); } - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); } // NSString returning methods... - (NSString *)JSONString { return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); } - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); } - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); } @end @implementation NSDictionary (JSONKitSerializing) // NSData returning methods... - (NSData *)JSONData { return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); } - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); } - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); } // NSString returning methods... - (NSString *)JSONString { return([JKSerializer serializeObject:self options:JKSerializeOptionNone encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:NULL]); } - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:NULL selector:NULL error:error]); } - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingDelegate:(id)delegate selector:(SEL)selector error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:NULL delegate:delegate selector:selector error:error]); } @end #ifdef __BLOCKS__ @implementation NSArray (JSONKitSerializingBlockAdditions) - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); } - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); } @end @implementation NSDictionary (JSONKitSerializingBlockAdditions) - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); } - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions serializeUnsupportedClassesUsingBlock:(id(^)(id object))block error:(NSError **)error { return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) block:block delegate:NULL selector:NULL error:error]); } @end #endif // __BLOCKS__
{ "content_hash": "f7ea278021dcd2217ca12e9fc3665018", "timestamp": "", "source": "github", "line_count": 3039, "max_line_length": 491, "avg_line_length": 57.9104968739717, "alnum_prop": 0.6796749815330416, "repo_name": "hfqf/AutoRepair-iOS", "id": "d1b7187d2a2338df56a07d996b586158b4e7fcf9", "size": "177505", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "autoRepairForiOS/GCP/JSONKit.m", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7794" }, { "name": "C++", "bytes": "2345" }, { "name": "HTML", "bytes": "4556" }, { "name": "Objective-C", "bytes": "3534742" }, { "name": "Objective-C++", "bytes": "44268" } ], "symlink_target": "" }
#!/usr/bin/env node /** * Adapted from AngularJS's contribution guidelines validation script * Source: https://github.com/angular/angular.js/blob/master/validate-commit-msg.js * * github/erikras contribution guidelines * Source: https://github.com/erikras/react-redux-universal-hot-example/blob/master/CONTRIBUTING.md */ /** * Git COMMIT-MSG hook for validating commit message * See https://docs.google.com/document/d/1rk04jEuGfk9kYzfqCuOlPTSJw3hEDZJTBN5E5f1SALo/edit * * Installation: * >> cd <angular-repo> * >> ln -s ../../validate-commit-msg.js .git/hooks/commit-msg */ 'use strict' const fs = require('fs') const util = require('util') const MAX_LENGTH = 100 const PATTERN = /^(?:fixup!\s*)?(?:(:\w*:)|(\w*)) ([\w\$\.\*/-]*)\: (.*)$/ const IGNORED = /^WIP\:/ const TYPES = { feat : true, fix : true, docs : true, style : true, refactor: true, test : true, chore : true, } const EMOJIS = [ ':seedling:', ':wrench:', ':books:', ':lipstick:', ':scissors:', ':vertical_traffic_light:', ':unamused:', ] const EMOJIMAP = [ [ /^feat/ , EMOJIS[ 0 ] ], [ /^fix/ , EMOJIS[ 1 ] ], [ /^docs/ , EMOJIS[ 2 ] ], [ /^style/ , EMOJIS[ 3 ] ], [ /^refactor/, EMOJIS[ 4 ] ], [ /^test/ , EMOJIS[ 5 ] ], [ /^chore/ , EMOJIS[ 6 ] ] ] const error = function() { // gitx does not display it // http://gitx.lighthouseapp.com/projects/17830/tickets/294-feature-display-hook-error-message-when-hook-fails // https://groups.google.com/group/gitx/browse_thread/thread/a03bcab60844b812 throw new Error( 'INVALID COMMIT MSG: ' + util.format.apply( null, arguments ) ) } const validateMessage = function( message ) { if ( IGNORED.test( message ) ) { console.info( 'Commit message validation ignored.' ) return true } if ( message.length > MAX_LENGTH ) { error( 'is longer than %d characters !', MAX_LENGTH ) return false } const match = PATTERN.exec( message ) if ( ! match ) { error( 'does not match "<type> <scope>: <subject>" ! was: ' + message ) return false } const emoji = match[ 1 ] const type = match[ 2 ] const scope = match[ 3 ] const subject = match[ 4 ] if ( ! TYPES.hasOwnProperty( type ) && EMOJIS.indexOf( emoji ) === -1 ) { error( '"%s" is not allowed type !', type || emoji ) return false } // TODO: // - auto correct the type to lower case // - auto correct first letter of the subject to lower case // - allow emojis so rebasing doesn't require rewriting // Some more ideas: // - allow only specific scopes (eg. fix(docs) should not be allowed ? // - auto add empty line after subject ? // - auto remove empty () ? // - auto correct typos in type ? return true } const firstLineFromBuffer = function( buffer ) { return buffer.toString().split( '\n' ).shift() } const giveEmojiToMsg = function( msg ) { for ( const replacement of EMOJIMAP ) { const r = replacement[ 0 ] if ( r.test( msg ) ) { return { msg: msg.replace( r, replacement[ 1 ] ), replaced: true, } } } return { msg, replaced: false, } } // publish for testing exports.validateMessage = validateMessage const commitMsgFile = '.git/COMMIT_EDITMSG' const incorrectLogFile = commitMsgFile.replace( 'COMMIT_EDITMSG', 'logs/incorrect-commit-msgs' ) fs.readFile( commitMsgFile, ( err, buffer ) => { const msg = firstLineFromBuffer( buffer ) if ( ! validateMessage( msg ) ) { fs.appendFile( incorrectLogFile, msg + '\n', () => { process.exit( 1 ) }) } else { const emojified = giveEmojiToMsg( buffer.toString() ) if ( emojified.replaced ) fs.writeFileSync( commitMsgFile, emojified.msg ) process.exit( 0 ) } })
{ "content_hash": "8e3b8f653f943f57e4dff89a99187f22", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 114, "avg_line_length": 27.846153846153847, "alnum_prop": 0.585635359116022, "repo_name": "LikeJasper/mantra-plus", "id": "a3a658aecbf58b9c457cdaaa1b25ebc3fdedddb5", "size": "3982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".scripts/validate-commit-msg.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "236" }, { "name": "JavaScript", "bytes": "53664" } ], "symlink_target": "" }
from collections import OrderedDict from django.core.urlresolvers import reverse from django.db.models.loading import get_model from django.test import TestCase from django.test.client import Client from django.test.utils import override_settings from django.utils.six.moves.urllib.parse import urlparse, parse_qs, \ parse_qsl, urlencode from django.http import HttpRequest from django.utils import six import mock import getpaid from getpaid_test_project.orders.models import Order if six.PY3: unicode = str class EpaydkBackendTestCase(TestCase): maxDiff = None def setUp(self): self.client = Client() Payment = get_model('getpaid', 'Payment') order = Order(name='Test DKK order', total='123.45', currency='DKK') order.save() payment = Payment(order=order, amount=order.total, currency=order.currency, backend='getpaid.backends.epaydk') payment.save() self.test_payment = Payment.objects.get(pk=payment.id) def test_format_ammount(self): payproc = getpaid.backends.epaydk.PaymentProcessor(self.test_payment) self.assertEqual(payproc.format_amount(123), "12300") self.assertEqual(payproc.format_amount("123.0"), "12300") self.assertEqual(payproc.format_amount(123.321), "12333") def test_get_gateway_url(self): payproc = getpaid.backends.epaydk.PaymentProcessor(self.test_payment) fake_req = mock.MagicMock(spec=HttpRequest) fake_req.scheme = 'https' fake_req.COOKIES = {} fake_req.META = {} actual = payproc.get_gateway_url(fake_req) self.assertEqual(actual[1], "GET") self.assertEqual(actual[2], {}) actual = list(urlparse(actual[0])) self.assertEqual(actual[0], 'https') self.assertEqual(actual[1], 'ssl.ditonlinebetalingssystem.dk') self.assertEqual(actual[2], '/integration/ewindow/Default.aspx') self.assertEqual(actual[3], '') domain = getpaid.utils.get_domain() accepturl = u'https://'+ domain +'/getpaid.backends.epaydk/success/' callbackurl = u'https://'+ domain +'/getpaid.backends.epaydk/online/' cancelurl = u'https://'+ domain +'/getpaid.backends.epaydk/failure/' expected = [ (u'merchantnumber', u'xxxxxxxx'), (u'orderid', u'1'), (u'currency', u'208'), (u'amount', u'12345'), (u'windowstate', u'3'), (u'mobile', u'1'), (u'timeout', u'3'), (u'instantcallback', u'0'), (u'language', u'2'), (u'accepturl', accepturl), (u'callbackurl', callbackurl), (u'cancelurl', cancelurl), ] md5hash = payproc.compute_hash(OrderedDict(expected)) expected.append(('hash', md5hash)) self.assertListEqual(expected, parse_qsl(actual[4])) self.assertEqual(actual[5], '') def test_online_invalid(self): response = self.client.get(reverse('getpaid-epaydk-online')) self.assertEqual(response.content, b'400 Bad Request') self.assertEqual(response.status_code, 400) @override_settings(GETPAID_SUCCESS_URL_NAME=None) def test_accept_ok(self): self.test_payment.status = 'in_progress' self.test_payment.save() payproc = getpaid.backends.epaydk.PaymentProcessor(self.test_payment) params = [ (u'txnid', u'48384464'), (u'orderid', unicode(self.test_payment.id)), (u'amount', payproc.format_amount(self.test_payment.amount)), (u'currency', u'208'), (u'date', u'20150716'), (u'time', u'1638'), (u'txnfee', u'0'), (u'paymenttype', u'1'), (u'cardno', u'444444XXXXXX4000'), ] md5hash = payproc.compute_hash(OrderedDict(params)) params.append(('hash', md5hash)) query = urlencode(params) url = reverse('getpaid-epaydk-success') + '?' + query response = self.client.get(url, data=params) expected_url = reverse('getpaid-success-fallback', kwargs=dict(pk=self.test_payment.pk)) self.assertRedirects(response, expected_url, 302, 302) Payment = get_model('getpaid', 'Payment') actual = Payment.objects.get(id=self.test_payment.id) self.assertEqual(actual.status, 'accepted_for_proc') def test_online_ok(self): self.test_payment.status = 'accepted_for_proc' self.test_payment.save() payproc = getpaid.backends.epaydk.PaymentProcessor(self.test_payment) params = [ (u'txnid', u'48384464'), (u'orderid', unicode(self.test_payment.id)), (u'amount', payproc.format_amount(self.test_payment.amount)), (u'currency', u'208'), (u'date', u'20150716'), (u'time', u'1638'), (u'txnfee', u'0'), (u'paymenttype', u'1'), (u'cardno', u'444444XXXXXX4000'), ] md5hash = payproc.compute_hash(OrderedDict(params)) params.append(('hash', md5hash)) query = urlencode(params) url = reverse('getpaid-epaydk-online') + '?' + query response = self.client.get(url, data=params) self.assertEqual(response.content, b'OK') self.assertEqual(response.status_code, 200) Payment = get_model('getpaid', 'Payment') actual = Payment.objects.get(id=self.test_payment.id) self.assertEqual(actual.status, 'paid') def test_online_wrong_hash(self): payproc = getpaid.backends.epaydk.PaymentProcessor(self.test_payment) params = [ (u'txnid', u'48384464'), (u'orderid', unicode(self.test_payment.id)), (u'amount', payproc.format_amount(self.test_payment.amount)), (u'currency', u'208'), (u'date', u'20150716'), (u'time', u'1638'), (u'txnfee', u'0'), (u'paymenttype', u'1'), (u'cardno', u'444444XXXXXX4000'), ] params.append(('hash', '1234567')) query = urlencode(params) url = reverse('getpaid-epaydk-online') + '?' + query response = self.client.get(url, data=params) self.assertEqual(response.content, b'400 Bad Request') self.assertEqual(response.status_code, 400) Payment = get_model('getpaid', 'Payment') actual = Payment.objects.get(id=self.test_payment.id) self.assertEqual(actual.status, 'new') def test_online_post(self): data = {'test': 'data'} response = self.client.post(reverse('getpaid-epaydk-online'), data=data) self.assertEqual(response.content, b'') self.assertEqual(response.status_code, 405) def test_cancelled(self): query = '?orderid=%s&error=-5543' % self.test_payment.id url = reverse('getpaid-epaydk-failure') + query response = self.client.get(url) expected = reverse('getpaid-failure-fallback', kwargs=dict(pk=self.test_payment.pk)) self.assertRedirects(response, expected, 302, 302) Payment = get_model('getpaid', 'Payment') actual = Payment.objects.get(id=self.test_payment.id) self.assertEqual(actual.status, 'cancelled')
{ "content_hash": "dc1ced455a2cba946ed884a523ac2553", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 77, "avg_line_length": 40.77472527472528, "alnum_prop": 0.5966850828729282, "repo_name": "kamilglod/django-getpaid", "id": "82300f956d4777a5e7f20cb81574a0f61db4ecc1", "size": "7437", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "getpaid_test_project/getpaid_test_project/orders/tests/test_epaydk.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "6266" }, { "name": "Python", "bytes": "163697" } ], "symlink_target": "" }
layout: single title: "Git: Git Log since" date: 2018-09-27 10:14 modified: 2018-09-27 10:14 categories: til tags: - git - til --- At the end of each day, I try to record what I did, to jog my memory during the next morning's standup. This is a helpful aid: ```bash git log --since="24 hours ago" ``` I SSH into my work machine and run this in my project's root directory. Combined with an alias from the Hashrocket Dotmatrix, `glg` (`git log --graph --oneline --decorate --color --all`), I get a terse summary of the day's work, ready to be pasted into your note-taking or project management tool of choice: ```bash $ glg --since="24 hours ago" * 7191b92 (HEAD, origin/master, origin/HEAD, master) Good changes * 3f4d61e More good changes * ecd9dcd Even more ... ``` Via [jwworth/til](https://github.com/jwworth/til).
{ "content_hash": "061de411d59a6fd85203933061cb2202", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 79, "avg_line_length": 25.875, "alnum_prop": 0.7101449275362319, "repo_name": "proinsias/proinsias.github.io", "id": "23541b177f087925e1ec3ad6e8b58ed16990d639", "size": "832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2018/2018-09-27-Git-Log-Since.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "97103" }, { "name": "JavaScript", "bytes": "196005" }, { "name": "Ruby", "bytes": "1508" }, { "name": "SCSS", "bytes": "99094" }, { "name": "Shell", "bytes": "2830" } ], "symlink_target": "" }
const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false } case 'TOGGLE_TODO': if (state.id !== action.id) { return state } return Object.assign({}, state, { completed: !state.completed }) default: return state } } const todos = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [ ...state, todo(undefined, action) ] case 'TOGGLE_TODO': return state.map(t => todo(t, action) ) default: return state } } export default todos
{ "content_hash": "2e5417169013a9913ea3f1b388fa0483", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 39, "avg_line_length": 17.82051282051282, "alnum_prop": 0.5050359712230216, "repo_name": "Blackmagicbox/react-redux-todo-tuto", "id": "a292c7a8e6ae0ebb1948612deae0f67e86f0bad1", "size": "695", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/reducers/todos.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "210" }, { "name": "JavaScript", "bytes": "7693" } ], "symlink_target": "" }
// Collides two cpShape structures. // Returns the number of contact points added to arr // which should be at least CP_MAX_CONTACTS_PER_ARBITER in length. // This function is very lonely in this header :( int cpCollideShapes(const cpShape *a, const cpShape *b, cpContact *arr);
{ "content_hash": "c8823f5ce6cb2bab374756983b8df286", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 72, "avg_line_length": 40.142857142857146, "alnum_prop": 0.7544483985765125, "repo_name": "artifacts/ste", "id": "e05efc5b2ece5cd259266726ac7193180fcec676", "size": "1398", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/3rdparty/Chipmunk-5.3.2/Objective-Chipmunk/Objective-Chipmunk/Objective-Chipmunk-simulator/chipmunk/cpCollision.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "785125" }, { "name": "JavaScript", "bytes": "20786" }, { "name": "Objective-C", "bytes": "1372528" }, { "name": "Perl", "bytes": "6875" }, { "name": "Ruby", "bytes": "19409" }, { "name": "Shell", "bytes": "1529" } ], "symlink_target": "" }
/* @flow */ import React, {PropTypes} from 'react'; import nbem from 'nbem'; const propTypes = { memberSummary: PropTypes.object.isRequired }; export default class MemberSummary extends React.Component { /** * render * * @return {ReactElement} */ render(): React.Element { const m = nbem(); const {memberSummary} = this.props; return ( <div className={m('MemberSummary')}> <div className={m('&member')}> <img className={m('&&thumb')} src={memberSummary.member.avatarUrl} /> </div> <div className={m('&content')}> <div className={m('&&time')}> <p> <span className={m('&&&spent')}>{memberSummary.spent}</span> / <span className={m('&&&es50')}>{memberSummary.es50}</span> / <span className={m('&&&es90')}>{memberSummary.es90}</span> </p> </div> </div> </div> ); } } MemberSummary.propTypes = propTypes;
{ "content_hash": "cb76f537ffda07f215cd4a1724ac01e8", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 74, "avg_line_length": 24.232558139534884, "alnum_prop": 0.5134357005758158, "repo_name": "tongariboyz/5rolli", "id": "f967b08017cfc8481bc75bbeac89c2be715fc203", "size": "1042", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/js/renderer/components/MemberSummary.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9568" }, { "name": "HTML", "bytes": "176" }, { "name": "JavaScript", "bytes": "35260" } ], "symlink_target": "" }
/** * The rules for building the language as a JSON-ish object. * @module lang/rules */ /** * The language rules model. * @typedef {Object} LanguageRules * @proprety {Object[]} types - An array of the types existing in the language. * @property {String} types[].name - The name of the type. * @property {String} types[].class - The class of the type. * @property {RegExp} types[].rule - The evaluation rule for the given type. * @property {Object[]} scopeDelimiters - The scope delimiters for the language. * @property {RegExp} scopeDelimiters[].startDelimiter - The evaluation rule for the start delimiter for that scope. * @property {RegExp} scopeDelimiters[].stopDelimiter - The evaluation rule for the stop delimiter for the given scope. * @property {String} scopeDelimiters[].scope - The scope name. * @property {RegExp} wordDelimiters - The evaluation rule for the word delimiters. * @property {Object[]} errors - The errors defined for the language. * @property {String} errors[].code - The error code. * @property {String} errors[].message - The error message. * @property {String} errors[].scope - The error scope. */ //TODO: add BNF like representation of the rules for inerpolation and/or use, maybe functions? module.exports = { 'types': [ { 'name': 'integer', 'class': 'C3', 'rule': /^\d+$/, 'precedence': 1 }, { 'name': 'float', 'class': 'C6', 'rule': /^\d*\.\d+$/, 'precedence': 1 }, { 'name': 'identifier', 'class': 'C1', 'rule': /^[a-z]+\w*$/, 'precedence': 3 }, { 'name': 'reservedWord', 'class': 'C2', 'rule': /^program|begin|end|var|real|integer|procedure|read|write|while|do|if|else|then$/, 'precedence': 2 }, { 'name': 'specialCharacter', 'class': 'C4', 'rule': /^<>|:=|<=|>=|\(|\)|\*|\/|-|\+|=|>|<|\$|\:|;|\,|\.$/, 'precedence': 3 }, { 'name': 'comments', 'class': 'C5', 'rule': /^\{.*?\}|\/\*.*?\*\/$/, 'precedence': 4 }, { 'name': 'whitespace', 'class': 'C6', 'rule': /^\s+$/, 'precedence': 5 }, { 'name': 'unknown', 'class': 'C7', 'rule': /.+?/, 'precedence': 6 } ], 'scopeDelimiters': [ { 'startDelimiter': /program/, 'stopDelimiter': /\./, 'scope': 'global', 'precedence': 1 }, { 'startDelimiter': /procedure[.\n]*begin/, 'stopDelimiter': /end/, 'scope': 'procedure', 'precedence': 2 }, { 'startDelimiter': /begin/, 'stopDelimiter': /end/, 'scope': 'block', 'precedence': 3 } ], 'syntaxRules': function(api){ return [ { 'name': '', 'rule': /.*?/, 'fn': function(){ } } ]; }, //Organized list of all the above tests so that the tokenizer has less work to do in classifying the tokens, but may be slower than char-by-chat testing 'wordDelimiters': /\{.*?\}|\/\*.*?\*\/|program|begin|end|var|real|integer|procedure|read|write|while|do|if|else|then|\d*\.\d+|\d+|<>|:=|<=|>=|\(|\)|\*|\/|-|\+|=|>|<|\$|\:|;|,|\.|[a-z]+\w*|\s+|.+?/ig, //TODO: implement errors 'errors': [ //File errors { 'code': '001', 'alias': 'file not found', 'message': 'File not found.', 'scope': 'File' }, { 'code': '002', 'alias': 'cant open file', 'message': 'Can\'t open file.', 'scope': 'File' }, { 'code': '003', 'alias': 'empty source code', 'message': 'Empty source code.', 'scope': 'Lexical' }, //Tokenizer errors { 'code': '004', 'alias': 'source dont contain tokens', 'message': 'Source conde don\'t contain any token.', 'scope': 'Lexical' }, { 'code': '005', 'alias': 'unknown token', 'message': 'This token is unknown.', 'scope': 'Lexical' }, //Scopifyer errors { 'code': '006', 'alias': 'not starting in global scope', 'message': 'Not starting in global scope.', 'scope': 'Syntax' }, { 'code': '007', 'alias': 'scope ending before starting', 'message': 'Scope ending before starting.', 'scope': 'Syntax' }, ] };
{ "content_hash": "ca1dd3c6292b730b847500812fb28ab6", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 200, "avg_line_length": 25.29299363057325, "alnum_prop": 0.5678670360110804, "repo_name": "madcampos/compilador", "id": "81cdf1cec3cd1e0724625d7bcddb3a1fe1399f83", "size": "3971", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lang/rules.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "11483" } ], "symlink_target": "" }
<#ftl output_format="HTML" auto_esc=true> <#import "layout/default.html" as layout> <@layout.default> <p style="margin: 0 0 1em 0;">Hello ${notificationTarget.name},</p> <p style="margin: 0 0 1em 0;">We have received a request to change the password for your account. You can do this through the link below.</p> <@layout.button href="${passwordResetLink}" text="Reset password" /> <p style="margin: 0 0 1em 0;">If you didn't request this, please ignore this email.</p> <p style="margin: 0 0 1em 0;">Your password won't change until you access the link above and create a new one.</p> <@layout.senderHTML /> </@layout.default>
{ "content_hash": "cb50d64014026a894a0b3f055a4b1d00", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 143, "avg_line_length": 63.8, "alnum_prop": 0.7021943573667712, "repo_name": "InnovateUKGitHub/innovation-funding-service", "id": "bf0cb938d81a4e6b71eabed4ecf0c7a23609ccbc", "size": "638", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "ifs-data-layer/ifs-data-service/src/main/resources/templates/notifications/email/reset_password_text_html.html", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "1972" }, { "name": "HTML", "bytes": "6342985" }, { "name": "Java", "bytes": "26591674" }, { "name": "JavaScript", "bytes": "269444" }, { "name": "Python", "bytes": "58983" }, { "name": "RobotFramework", "bytes": "3317394" }, { "name": "SCSS", "bytes": "100274" }, { "name": "Shell", "bytes": "60248" } ], "symlink_target": "" }
@interface BitlyAPIHelper : NSObject { NSString *login; NSString *apiKey; } -(BitlyAPIHelper*) initWithLogin: (NSString*) bitlyLogin andAPIKey: (NSString*) bitlyApiKey; -(NSString*) shortenURL: (NSString*) longUrl; @end
{ "content_hash": "9411f55e77a9f10b4bef44abb920a803", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 92, "avg_line_length": 22.5, "alnum_prop": 0.7422222222222222, "repo_name": "dak180/vienna", "id": "460999e2a3e73218f449c3a25b5de3147665c202", "size": "965", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/BitlyAPIHelper.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "54035" }, { "name": "HTML", "bytes": "522159" }, { "name": "Makefile", "bytes": "1005" }, { "name": "Objective-C", "bytes": "1247115" }, { "name": "Ruby", "bytes": "1349" }, { "name": "Shell", "bytes": "16896" }, { "name": "Swift", "bytes": "842" } ], "symlink_target": "" }
/** * This is the file where the bot commands are located * * @license MIT license */ var http = require('http'); var sys = require('sys'); if (config.serverid === 'showdown') { var https = require('https'); var csv = require('csv-parse'); } exports.commands = { /** * Help commands * * These commands are here to provide information about the bot. */ credits: 'about', about: function(arg, by, room, con) { if (this.hasRank(by, '#~') || room.charAt(0) === ',') { var text = ''; } else { var text = '/pm ' + by + ', '; } text += '**Pokémon Showdown Bot** by: Quinella, TalkTakesTime, and Morfent'; this.say(con, room, text); }, help: 'guide', guide: function(arg, by, room, con) { if (this.hasRank(by, '#~') || room.charAt(0) === ',') { var text = ''; } else { var text = '/pm ' + by + ', '; } if (config.botguide) { text += 'A guide on how to use this bot can be found here: ' + config.botguide; } else { text += 'There is no guide for this bot. PM the owner with any questions.'; } this.say(con, room, text); }, /** * Dev commands * * These commands are here for highly ranked users (or the creator) to use * to perform arbitrary actions that can't be done through any other commands * or to help with upkeep of the bot. */ reload: function(arg, by, room, con) { if (!this.hasRank(by, '#~')) return false; try { this.uncacheTree('./commands.js'); Commands = require('./commands.js').commands; this.say(con, room, 'Commands reloaded.'); } catch (e) { error('failed to reload: ' + sys.inspect(e)); } }, custom: function(arg, by, room, con) { if (!this.hasRank(by, '~')) return false; // Custom commands can be executed in an arbitrary room using the syntax // ".custom [room] command", e.g., to do !data pikachu in the room lobby, // the command would be ".custom [lobby] !data pikachu". However, using // "[" and "]" in the custom command to be executed can mess this up, so // be careful with them. if (arg.indexOf('[') === 0 && arg.indexOf(']') > -1) { var tarRoom = arg.slice(1, arg.indexOf(']')); arg = arg.substr(arg.indexOf(']') + 1).trim(); } this.say(con, tarRoom || room, arg); }, js: function(arg, by, room, con) { if (config.excepts.indexOf(toId(by)) === -1) return false; try { var result = eval(arg.trim()); this.say(con, room, JSON.stringify(result)); } catch (e) { this.say(con, room, e.name + ": " + e.message); } }, /** * Room Owner commands * * These commands allow room owners to personalise settings for moderation and command use. */ settings: 'set', set: function(arg, by, room, con) { if (!this.hasRank(by, '%@&#~') || room.charAt(0) === ',') return false; var settable = { say: 1, joke: 1, choose: 1, usagestats: 1, buzz: 1, '8ball': 1, survivor: 1, games: 1, wifi: 1, monotype: 1, autoban: 1, happy: 1, guia: 1, studio: 1, 'switch': 1, banword: 1 }; var modOpts = { flooding: 1, caps: 1, stretching: 1, bannedwords: 1 }; var opts = arg.split(','); var cmd = toId(opts[0]); if (cmd === 'mod' || cmd === 'm' || cmd === 'modding') { if (!opts[1] || !toId(opts[1]) || !(toId(opts[1]) in modOpts)) return this.say(con, room, 'Incorrect command: correct syntax is ' + config.commandcharacter + 'set mod, [' + Object.keys(modOpts).join('/') + '](, [on/off])'); if (!this.settings['modding']) this.settings['modding'] = {}; if (!this.settings['modding'][room]) this.settings['modding'][room] = {}; if (opts[2] && toId(opts[2])) { if (!this.hasRank(by, '#~')) return false; if (!(toId(opts[2]) in {on: 1, off: 1})) return this.say(con, room, 'Incorrect command: correct syntax is ' + config.commandcharacter + 'set mod, [' + Object.keys(modOpts).join('/') + '](, [on/off])'); if (toId(opts[2]) === 'off') { this.settings['modding'][room][toId(opts[1])] = 0; } else { delete this.settings['modding'][room][toId(opts[1])]; } this.writeSettings(); this.say(con, room, 'Moderation for ' + toId(opts[1]) + ' in this room is now ' + toId(opts[2]).toUpperCase() + '.'); return; } else { this.say(con, room, 'Moderation for ' + toId(opts[1]) + ' in this room is currently ' + (this.settings['modding'][room][toId(opts[1])] === 0 ? 'OFF' : 'ON') + '.'); return; } } else { if (!Commands[cmd]) return this.say(con, room, config.commandcharacter + '' + opts[0] + ' is not a valid command.'); var failsafe = 0; while (!(cmd in settable)) { if (typeof Commands[cmd] === 'string') { cmd = Commands[cmd]; } else if (typeof Commands[cmd] === 'function') { if (cmd in settable) { break; } else { this.say(con, room, 'The settings for ' + config.commandcharacter + '' + opts[0] + ' cannot be changed.'); return; } } else { this.say(con, room, 'Something went wrong. PM TalkTakesTime here or on Smogon with the command you tried.'); return; } failsafe++; if (failsafe > 5) { this.say(con, room, 'The command "' + config.commandcharacter + '' + opts[0] + '" could not be found.'); return; } } var settingsLevels = { off: false, disable: false, '+': '+', '%': '%', '@': '@', '&': '&', '#': '#', '~': '~', on: true, enable: true }; if (!opts[1] || !opts[1].trim()) { var msg = ''; if (!this.settings[cmd] || (!this.settings[cmd][room] && this.settings[cmd][room] !== false)) { msg = '.' + cmd + ' is available for users of rank ' + ((cmd === 'autoban' || cmd === 'banword') ? '#' : config.defaultrank) + ' and above.'; } else if (this.settings[cmd][room] in settingsLevels) { msg = '.' + cmd + ' is available for users of rank ' + this.settings[cmd][room] + ' and above.'; } else if (this.settings[cmd][room] === true) { msg = '.' + cmd + ' is available for all users in this room.'; } else if (this.settings[cmd][room] === false) { msg = '' + config.commandcharacter+''+ cmd + ' is not available for use in this room.'; } this.say(con, room, msg); return; } else { if (!this.hasRank(by, '#~')) return false; var newRank = opts[1].trim(); if (!(newRank in settingsLevels)) return this.say(con, room, 'Unknown option: "' + newRank + '". Valid settings are: off/disable, +, %, @, &, #, ~, on/enable.'); if (!this.settings[cmd]) this.settings[cmd] = {}; this.settings[cmd][room] = settingsLevels[newRank]; this.writeSettings(); this.say(con, room, 'The command ' + config.commandcharacter + '' + cmd + ' is now ' + (settingsLevels[newRank] === newRank ? ' available for users of rank ' + newRank + ' and above.' : (this.settings[cmd][room] ? 'available for all users in this room.' : 'unavailable for use in this room.'))) } } }, blacklist: 'autoban', ban: 'autoban', ab: 'autoban', autoban: function(arg, by, room, con) { if (!this.canUse('autoban', room, by) || room.charAt(0) === ',') return false; if (!this.hasRank(this.ranks[room] || ' ', '@&#~')) return this.say(con, room, config.nick + ' requires rank of @ or higher to (un)blacklist.'); arg = arg.split(','); var added = []; var illegalNick = []; var alreadyAdded = []; if (!arg.length || (arg.length === 1 && !arg[0].trim().length)) return this.say(con, room, 'You must specify at least one user to blacklist.'); for (var i = 0; i < arg.length; i++) { var tarUser = toId(arg[i]); if (tarUser.length < 1 || tarUser.length > 18) { illegalNick.push(tarUser); continue; } if (!this.blacklistUser(tarUser, room)) { alreadyAdded.push(tarUser); continue; } this.say(con, room, '/roomban ' + tarUser + ', Blacklisted user'); this.say(con,room, '/modnote ' + tarUser + ' was added to the blacklist by ' + by + '.'); added.push(tarUser); } var text = ''; if (added.length) { text += 'User(s) "' + added.join('", "') + '" added to blacklist successfully. '; this.writeSettings(); } if (alreadyAdded.length) text += 'User(s) "' + alreadyAdded.join('", "') + '" already present in blacklist. '; if (illegalNick.length) text += 'All ' + (text.length ? 'other ' : '') + 'users had illegal nicks and were not blacklisted.'; this.say(con, room, text); }, unblacklist: 'unautoban', unban: 'unautoban', unab: 'unautoban', unautoban: function(arg, by, room, con) { if (!this.canUse('autoban', room, by) || room.charAt(0) === ',') return false; if (!this.hasRank(this.ranks[room] || ' ', '@&#~')) return this.say(con, room, config.nick + ' requires rank of @ or higher to (un)blacklist.'); arg = arg.split(','); var removed = []; var notRemoved = []; if (!arg.length || (arg.length === 1 && !arg[0].trim().length)) return this.say(con, room, 'You must specify at least one user to unblacklist.'); for (var i = 0; i < arg.length; i++) { var tarUser = toId(arg[i]); if (tarUser.length < 1 || tarUser.length > 18) { notRemoved.push(tarUser); continue; } if (!this.unblacklistUser(tarUser, room)) { notRemoved.push(tarUser); continue; } this.say(con, room, '/roomunban ' + tarUser); removed.push(tarUser); } var text = ''; if (removed.length) { text += 'User(s) "' + removed.join('", "') + '" removed from blacklist successfully. '; this.writeSettings(); } if (notRemoved.length) text += (text.length ? 'No other ' : 'No ') + 'specified users were present in the blacklist.'; this.say(con, room, text); }, viewbans: 'viewblacklist', vab: 'viewblacklist', viewautobans: 'viewblacklist', viewblacklist: function(arg, by, room, con) { if (!this.canUse('autoban', room, by) || room.charAt(0) === ',') return false; var text = ''; if (!this.settings.blacklist || !this.settings.blacklist[room]) { text = 'No users are blacklisted in this room.'; } else { if (arg.length) { var nick = toId(arg); if (nick.length < 1 || nick.length > 18) { text = 'Invalid nickname: "' + nick + '".'; } else { text = 'User "' + nick + '" is currently ' + (nick in this.settings.blacklist[room] ? '' : 'not ') + 'blacklisted in ' + room + '.'; } } else { var nickList = Object.keys(this.settings.blacklist[room]); if (!nickList.length) return this.say(con, room, '/pm ' + by + ', No users are blacklisted in this room.'); this.uploadToHastebin(con, room, by, 'The following users are banned in ' + room + ':\n\n' + nickList.join('\n')) return; } } this.say(con, room, '/pm ' + by + ', ' + text); }, banphrase: 'banword', banword: function(arg, by, room, con) { if (!this.canUse('banword', room, by)) return false; if (!this.settings.bannedphrases) this.settings.bannedphrases = {}; arg = arg.trim().toLowerCase(); if (!arg) return false; var tarRoom = room; if (room.charAt(0) === ',') { if (!this.hasRank(by, '~')) return false; tarRoom = 'global'; } if (!this.settings.bannedphrases[tarRoom]) this.settings.bannedphrases[tarRoom] = {}; if (arg in this.settings.bannedphrases[tarRoom]) return this.say(con, room, "Phrase \"" + arg + "\" is already banned."); this.settings.bannedphrases[tarRoom][arg] = 1; this.writeSettings(); this.say(con, room, "Phrase \"" + arg + "\" is now banned."); }, unbanphrase: 'unbanword', unbanword: function(arg, by, room, con) { if (!this.canUse('banword', room, by)) return false; arg = arg.trim().toLowerCase(); if (!arg) return false; var tarRoom = room; if (room.charAt(0) === ',') { if (!this.hasRank(by, '~')) return false; tarRoom = 'global'; } if (!this.settings.bannedphrases || !this.settings.bannedphrases[tarRoom] || !(arg in this.settings.bannedphrases[tarRoom])) return this.say(con, room, "Phrase \"" + arg + "\" is not currently banned."); delete this.settings.bannedphrases[tarRoom][arg]; if (!Object.size(this.settings.bannedphrases[tarRoom])) delete this.settings.bannedphrases[tarRoom]; if (!Object.size(this.settings.bannedphrases)) delete this.settings.bannedphrases; this.writeSettings(); this.say(con, room, "Phrase \"" + arg + "\" is no longer banned."); }, viewbannedphrases: 'viewbannedwords', vbw: 'viewbannedwords', viewbannedwords: function(arg, by, room, con) { if (!this.canUse('banword', room, by)) return false; arg = arg.trim().toLowerCase(); var tarRoom = room; if (room.charAt(0) === ',') { if (!this.hasRank(by, '~')) return false; tarRoom = 'global'; } var text = ""; if (!this.settings.bannedphrases || !this.settings.bannedphrases[tarRoom]) { text = "No phrases are banned in this room."; } else { if (arg.length) { text = "The phrase \"" + arg + "\" is currently " + (arg in this.settings.bannedphrases[tarRoom] ? "" : "not ") + "banned " + (room.charAt(0) === ',' ? "globally" : "in " + room) + "."; } else { var banList = Object.keys(this.settings.bannedphrases[tarRoom]); if (!banList.length) return this.say(con, room, "No phrases are banned in this room."); this.uploadToHastebin(con, room, by, "The following phrases are banned " + (room.charAt(0) === ',' ? "globally" : "in " + room) + ":\n\n" + banList.join('\n')) return; } } this.say(con, room, text); }, /** * General commands * * Add custom commands here. */ tell: 'say', say: function(arg, by, room, con) { if (!this.canUse('say', room, by)) return false; this.say(con, room, stripCommands(arg) + ' (' + by + ' said this)'); }, joke: function(arg, by, room, con) { if (!this.canUse('joke', room, by) || room.charAt(0) === ',') return false; var self = this; var reqOpt = { hostname: 'api.icndb.com', path: '/jokes/random', method: 'GET' }; var req = http.request(reqOpt, function(res) { res.on('data', function(chunk) { try { var data = JSON.parse(chunk); self.say(con, room, data.value.joke.replace(/&quot;/g, "\"")); } catch (e) { self.say(con, room, 'Sorry, couldn\'t fetch a random joke... :('); } }); }); req.end(); }, choose: function(arg, by, room, con) { if (arg.indexOf(',') === -1) { var choices = arg.split(' '); } else { var choices = arg.split(','); } choices = choices.filter(function(i) {return (toId(i) !== '')}); if (choices.length < 2) return this.say(con, room, (room.charAt(0) === ',' ? '': '/pm ' + by + ', ') + '.choose: You must give at least 2 valid choices.'); var choice = choices[Math.floor(Math.random()*choices.length)]; this.say(con, room, ((this.canUse('choose', room, by) || room.charAt(0) === ',') ? '':'/pm ' + by + ', ') + stripCommands(choice)); }, usage: 'usagestats', usagestats: function(arg, by, room, con) { if (this.canUse('usagestats', room, by) || room.charAt(0) === ',') { var text = ''; } else { var text = '/pm ' + by + ', '; } text += 'http://www.smogon.com/stats/2015-01/'; this.say(con, room, text); }, seen: function(arg, by, room, con) { // this command is still a bit buggy var text = (room.charAt(0) === ',' ? '' : '/pm ' + by + ', '); arg = toId(arg); if (!arg || arg.length > 18) return this.say(con, room, text + 'Invalid username.'); if (arg === toId(by)) { text += 'Have you looked in the mirror lately?'; } else if (arg === toId(config.nick)) { text += 'You might be either blind or illiterate. Might want to get that checked out.'; } else if (!this.chatData[arg] || !this.chatData[arg].seenAt) { text += 'The user ' + arg + ' has never been seen.'; } else { text += arg + ' was last seen ' + this.getTimeAgo(this.chatData[arg].seenAt) + ' ago' + ( this.chatData[arg].lastSeen ? ', ' + this.chatData[arg].lastSeen : '.'); } this.say(con, room, text); }, helix: function(arg, by, room, con) { if (this.canUse('8ball', room, by) || room.charAt(0) === ',') { var text = ''; } else { var text = '/pm ' + by + ', '; } this.say(con, room, 'This command has been renamed to .8ball so it wouldn\'t have such a cancerous name anymore.'); }, '8ball': function(arg, by, room, con) { if (this.canUse('8ball', room, by) || room.charAt(0) === ',') { var text = ''; } else { var text = '/pm ' + by + ', '; } var rand = ~~(20 * Math.random()) + 1; switch (rand) { case 1: text += "Signs point to yes."; break; case 2: text += "Yes."; break; case 3: text += "Reply hazy, try again."; break; case 4: text += "Without a doubt."; break; case 5: text += "My sources say no."; break; case 6: text += "As I see it, yes."; break; case 7: text += "You may rely on it."; break; case 8: text += "Concentrate and ask again."; break; case 9: text += "Outlook not so good."; break; case 10: text += "It is decidedly so."; break; case 11: text += "Better not tell you now."; break; case 12: text += "Very doubtful."; break; case 13: text += "Yes - definitely."; break; case 14: text += "It is certain."; break; case 15: text += "Cannot predict now."; break; case 16: text += "Most likely."; break; case 17: text += "Ask again later."; break; case 18: text += "My reply is no."; break; case 19: text += "Outlook good."; break; case 20: text += "Don't count on it."; break; } this.say(con, room, text); }, /** * Room specific commands * * These commands are used in specific rooms on the Smogon server. */ espaol: 'esp', ayuda: 'esp', esp: function(arg, by, room, con) { // links to relevant sites for the Wi-Fi room if (config.serverid !== 'showdown') return false; var text = ''; if (room = 'espaol') { if (!this.canUse('guia', room, by)) text += '/pm ' + by + ', '; } else if (room.charAt(0) !== ',') { return false; } var messages = { reglas: 'Recuerda seguir las reglas de nuestra sala en todo momento: http://ps-salaespanol.weebly.com/reglas.html', faq: 'Preguntas frecuentes sobre el funcionamiento del chat: http://ps-salaespanol.weebly.com/faq.html', faqs: 'Preguntas frecuentes sobre el funcionamiento del chat: http://ps-salaespanol.weebly.com/faq.html', foro: '¡Visita nuestro foro para participar en multitud de actividades! http://ps-salaespanol.proboards.com/', guia: 'Desde este índice (http://ps-salaespanol.proboards.com/thread/575/ndice-de-gu) podrás acceder a toda la información importante de la sala. By: Lost Seso', liga: '¿Tienes alguna duda sobre la Liga? ¡Revisa el **índice de la Liga** aquí!: (http://goo.gl/CxH2gi) By: xJoelituh' }; text += (toId(arg) ? (messages[toId(arg)] || '¡Bienvenidos a la comunidad de habla hispana! Si eres nuevo o tienes dudas revisa nuestro índice de guías: http://ps-salaespanol.proboards.com/thread/575/ndice-de-gu') : '¡Bienvenidos a la comunidad de habla hispana! Si eres nuevo o tienes dudas revisa nuestro índice de guías: http://ps-salaespanol.proboards.com/thread/575/ndice-de-gu'); this.say(con, room, text); }, studio: function(arg, by, room, con) { if (config.serverid !== 'showdown') return false; var text = ''; if (room === 'thestudio') { if (!this.canUse('studio', room, by)) text += '/pm ' + by + ', '; } else if (room.charAt(0) !== ',') { return false; } var messages = { plug: '/announce The Studio\'s plug.dj can be found here: https://plug.dj/the-studio/' }; this.say(con, room, text + (messages[toId(arg)] || ('Welcome to The Studio, a music sharing room on PS!. If you have any questions, feel free to PM a room staff member. Available commands for .studio: ' + Object.keys(messages).join(', ')))); }, 'switch': function(arg, by, room, con) { if (room !== 'gamecorner' || config.serverid !== 'showdown' || !this.canUse('switch', room, by)) return false; this.say(con, room, 'Taking over the world. Starting with Game Corner. Room deregistered.'); this.say(con, room, '/k ' + (toId(arg) || by) + ', O3O YOU HAVE TOUCHED THE SWITCH'); }, wifi: function(arg, by, room, con) { // links to relevant sites for the Wi-Fi room if (config.serverid !== 'showdown') return false; var text = ''; if (room === 'wifi') { if (!this.canUse('wifi', room, by)) text += '/pm ' + by + ', '; } else if (room.charAt(0) !== ',') { return false; } arg = arg.split(','); var msgType = toId(arg[0]); if (!msgType) return this.say(con, room, 'Welcome to the Wi-Fi room! Links can be found here: http://pstradingroom.weebly.com/links.html'); switch (msgType) { case 'intro': return this.say(con, room, text + 'Here is an introduction to Wi-Fi: http://tinyurl.com/welcome2wifi'); case 'rules': return this.say(con, room, text + 'The rules for the Wi-Fi room can be found here: http://pstradingroom.weebly.com/rules.html'); case 'faq': case 'faqs': return this.say(con, room, text + 'Wi-Fi room FAQs: http://pstradingroom.weebly.com/faqs.html'); case 'scammers': return this.say(con, room, text + 'List of known scammers: http://tinyurl.com/psscammers'); case 'cloners': return this.say(con, room, text + 'List of approved cloners: http://goo.gl/WO8Mf4'); case 'tips': return this.say(con, room, text + 'Scamming prevention tips: http://pstradingroom.weebly.com/scamming-prevention-tips.html'); case 'breeders': return this.say(con, room, text + 'List of breeders: http://tinyurl.com/WiFIBReedingBrigade'); case 'signup': return this.say(con, room, text + 'Breeders Sign Up: http://tinyurl.com/GetBreeding'); case 'bans': case 'banappeals': return this.say(con, room, text + 'Ban appeals: http://tinyurl.com/WifiBanAppeals'); case 'lists': return this.say(con, room, text + 'Major and minor list compilation: http://tinyurl.com/WifiSheets'); case 'trainers': return this.say(con, room, text + 'List of EV trainers: http://tinyurl.com/WifiEVtrainingCrew'); case 'youtube': return this.say(con, room, text + 'Wi-Fi room\'s official YouTube channel: http://tinyurl.com/wifiyoutube'); case 'league': return this.say(con, room, text + 'Wi-Fi Room Pokemon League: http://tinyurl.com/wifiroomleague'); case 'checkfc': if (!config.googleapikey) return this.say(con, room, text + 'A Google API key has not been provided and is required for this command to work.'); if (arg.length < 2) return this.say(con, room, text + 'Usage: .wifi checkfc, [fc]'); this.wifiRoom = this.wifiroom || {docRevs: ['', ''], scammers : {}, cloners: []}; var self = this; this.getDocMeta('0AvygZBLXTtZZdFFfZ3hhVUplZm5MSGljTTJLQmJScEE', function (err, meta) { if (err) return self.say(con, room, text + 'An error occured while processing your command.'); var value = arg[1].replace(/\D/g, ''); if (value.length !== 12) return self.say(con, room, text + '"' + arg[1] + '" is not a valid FC.'); if (self.wifiRoom.docRevs[1] === meta.version) { value = self.wifiRoom.scammers[value]; if (value) return self.say(con, room, text + '**The FC ' + arg[1] + ' belongs to a known scammer: ' + (value.length > 61 ? value + '..' : value) + '.**'); return self.say(con, room, text + 'This FC does not belong to a known scammer.') } self.wifiRoom.docRevs[1] = meta.version; self.getDocCsv(meta, function (data) { csv(data, function (err, data) { if (err) return self.say(con, room, text + 'An error occured while processing your command.'); for (var i = 0, len = data.length; i < len; i++) { var str = data[i][1].replace(/\D/g, ''); var strLen = str.length; if (str && strLen > 11) { for (var j = 0; j < strLen; j += 12) { self.wifiRoom.scammers[str.substr(j, 12)] = data[i][0]; } } } value = self.wifiRoom.scammers[value]; if (value) return self.say(con, room, text + '**The FC ' + arg[1] + ' belongs to a known scammer: ' + (value.length > 61 ? value.substr(0, 61) + '..' : value) + '.**'); return self.say(con, room, 'This FC does not belong to a known scammer.'); }); }); }); break; /* case 'ocloners': case 'onlinecloners': if (!config.googleapikey) return this.say(con, room, text + 'A Google API key has not been provided and is required for this command to work.'); this.wifiRoom = this.wifiroom || {docRevs: ['', ''], scammers : {}, cloners: []}; var self = this; self.getDocMeta('0Avz7HpTxAsjIdFFSQ3BhVGpCbHVVdTJ2VVlDVVV6TWc', function (err, meta) { if (err) { console.log(err); return self.say(con, room, text + 'An error occured while processing your command. Please report this!'); } text = '/pm ' + by + ', '; if (self.wifiRoom.docRevs[0] == meta.version) { var found = []; for (var i in self.wifiRoom.cloners) { if (self.chatData[toId(self.wifiRoom.cloners[i][0])]) { found.push('Name: ' + self.wifiRoom.cloners[i][0] + ' | FC: ' + self.wifiRoom.cloners[i][1] + ' | IGN: ' + self.wifiRoom.cloners[i][2]); } } if (!found.length) { self.say(con, room, text + 'No cloners were found online.'); return; } var foundstr = found.join(' '); if(foundstr.length > 266) { self.uploadToHastebin(con, room, by, "The following cloners are online :\n\n" + found.join('\n')); return; } self.say(con, room, by, "The following cloners are online :\n\n" + foundstr); return; } self.say(con, room, text + 'Cloners List changed. Updating...'); self.wifiRoom.docRevs[0] = meta.version; self.getDocCsv(meta, function (data) { csv(data, function (err, data) { if (err) { console.log(err); this.say(con, room, text + 'An error occured while processing your command. Please report this!'); return; } data.forEach(function (ent) { var str = ent[1].replace(/\D/g, ''); if (str && str.length >= 12) { self.wifiRoom.cloners.push([ent[0], ent[1], ent[2]]); } }); var found = []; for (var i in self.wifiRoom.cloners) { if (self.chatData[toId(self.wifiRoom.cloners[i][0])]) { found.push('Name: ' + self.wifiRoom.cloners[i][0] + ' | FC: ' + self.wifiRoom.cloners[i][1] + ' | IGN: ' + self.wifiRoom.cloners[i][2]); } } if (!found.length) { self.say(con, room, text + 'No cloners were found online.'); return; } var foundstr = found.join(' '); if (foundstr.length > 266) { self.uploadToHastebin(con, room, by, "The following cloners are online :\n\n" + found.join('\n')); return; } self.say(con, room, by, "The following cloners are online :\n\n" + foundstr); }); }); }); break; */ default: return this.say(con, room, text + 'Unknown option. General links can be found here: http://pstradingroom.weebly.com/links.html'); } }, mono: 'monotype', monotype: function(arg, by, room, con) { // links and info for the monotype room if (config.serverid !== 'showdown') return false; var text = ''; if (room === 'monotype') { if (!this.canUse('monotype', room, by)) text += '/pm ' + by + ', '; } else if (room.charAt(0) !== ',') { return false; } var messages = { forums: 'The monotype room\'s forums can be found here: http://psmonotypeforum.createaforum.com/index.php', plug: 'The monotype room\'s plug can be found here: http://plug.dj/monotype-3-am-club/', rules: 'The monotype room\'s rules can be found here: http://psmonotype.wix.com/psmono#!rules/cnnz', site: 'The monotype room\'s site can be found here: http://www.psmonotype.wix.com/psmono', league: 'Information on the Monotype League can be found here: http://themonotypeleague.weebly.com/' }; text += messages[toId(arg)] || 'Unknown option. General information can be found here: http://www.psmonotype.wix.com/psmono'; this.say(con, room, text); }, survivor: function(arg, by, room, con) { // contains links and info for survivor in the Survivor room if (config.serverid !== 'showdown') return false; var text = ''; if (room === 'survivor') { if (!this.canUse('survivor', room, by)) text += '/pm ' + by + ', '; } else if (room.charAt(0) !== ',') { return false; } var gameTypes = { hg: "The rules for this game type can be found here: http://survivor-ps.weebly.com/hunger-games.html", hungergames: "The rules for this game type can be found here: http://survivor-ps.weebly.com/hunger-games.html", classic: "The rules for this game type can be found here: http://survivor-ps.weebly.com/classic.html" }; arg = toId(arg); if (!arg) return this.say(con, room, text + "The list of game types can be found here: http://survivor-ps.weebly.com/themes.html"); text += gameTypes[arg] || "Invalid game type. The game types can be found here: http://survivor-ps.weebly.com/themes.html"; this.say(con, room, text); }, games: function(arg, by, room, con) { // lists the games for the games room if (config.serverid !== 'showdown') return false; var text = ''; if (room === 'gamecorner') { if (!this.canUse('games', room, by)) text += '/pm ' + by + ', '; } else if (room.charAt(0) !== ',') { return false; } this.say(con, room, text + 'Game List: 1. Would You Rather, 2. NickGames, 3. Scattegories, 4. Commonyms, 5. Questionnaires, 6. Funarios, 7. Anagrams, 8. Spot the Reference, 9. Pokemath, 10. Liar\'s Dice'); this.say(con, room, text + '11. Pun Game, 12. Dice Cup, 13. Who\'s That Pokemon?, 14. Pokemon V Pokemon (BST GAME), 15. Letter Getter, 16. Missing Link, 17. Parameters! More information can be found here: http://psgamecorner.weebly.com/games.html'); }, happy: function(arg, by, room, con) { // info for The Happy Place if (config.serverid !== 'showdown') return false; var text = ''; if (room === 'thehappyplace') { if (!this.canUse('happy', room, by)) text += '/pm ' + by + ', '; } else if (room.charAt(0) !== ',') { return false; } arg = toId(arg); if (arg === 'askstaff' || arg === 'ask' || arg === 'askannie') { text += "http://thepshappyplace.weebly.com/ask-the-staff.html"; } else { text += "The Happy Place, at its core, is a friendly environment for anyone just looking for a place to hang out and relax. We also specialize in taking time to give advice on life problems for users. Need a place to feel at home and unwind? Look no further!"; } this.say(con, room, text); }, /** * Jeopardy commands * * The following commands are used for Jeopardy in the Academics room * on the Smogon server. */ b: 'buzz', buzz: function(arg, by, room, con) { if (this.buzzed || !this.canUse('buzz', room, by) || room.charAt(0) === ',') return false; this.say(con, room, '**' + by.substr(1) + ' has buzzed in!**'); this.buzzed = by; this.buzzer = setTimeout(function(con, room, buzzMessage) { this.say(con, room, buzzMessage); this.buzzed = ''; }.bind(this), 7 * 1000, con, room, by + ', your time to answer is up!'); }, reset: function(arg, by, room, con) { if (!this.buzzed || !this.hasRank(by, '%@&#~') || room.charAt(0) === ',') return false; clearTimeout(this.buzzer); this.buzzed = ''; this.say(con, room, 'The buzzer has been reset.'); }, };
{ "content_hash": "38590e5ee7ca134f2c551b2f753ca60a", "timestamp": "", "source": "github", "line_count": 774, "max_line_length": 387, "avg_line_length": 40.13953488372093, "alnum_prop": 0.6046092442384448, "repo_name": "Mollete21/FrenchB0T", "id": "f8c025f201d71694b7b7d8411ed87f53355cf630", "size": "31083", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "commands.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "60973" } ], "symlink_target": "" }
# Makefile.in generated by automake 1.10.1 from Makefile.am. # src/Makefile. Generated from Makefile.in by configure. # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, # 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. pkgdatadir = $(datadir)/neethi-src pkglibdir = $(libdir)/neethi-src pkgincludedir = $(includedir)/neethi-src am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = x86_64-unknown-linux-gnu host_triplet = x86_64-unknown-linux-gnu target_triplet = x86_64-unknown-linux-gnu subdir = src DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = `echo $$p | sed -e 's|^.*/||'`; am__installdirs = "$(DESTDIR)$(libdir)" libLTLIBRARIES_INSTALL = $(INSTALL) LTLIBRARIES = $(lib_LTLIBRARIES) libneethi_la_DEPENDENCIES = ../../axiom/src/om/libaxis2_axiom.la \ ../../util/src/libaxutil.la secpolicy/builder/librp_builder.la \ rmpolicy/librm_policy.la secpolicy/model/librp_model.la am_libneethi_la_OBJECTS = all.lo assertion.lo engine.lo exactlyone.lo \ operator.lo policy.lo reference.lo registry.lo \ assertion_builder.lo util.lo libneethi_la_OBJECTS = $(am_libneethi_la_OBJECTS) libneethi_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(libneethi_la_LDFLAGS) $(LDFLAGS) -o $@ DEFAULT_INCLUDES = -I. -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) CCLD = $(CC) LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ $(LDFLAGS) -o $@ SOURCES = $(libneethi_la_SOURCES) DIST_SOURCES = $(libneethi_la_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ html-recursive info-recursive install-data-recursive \ install-dvi-recursive install-exec-recursive \ install-html-recursive install-info-recursive \ install-pdf-recursive install-ps-recursive install-recursive \ installcheck-recursive installdirs-recursive pdf-recursive \ ps-recursive uninstall-recursive RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = ${SHELL} /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/missing --run aclocal-1.10 AMTAR = ${SHELL} /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/missing --run tar AR = ar AUTOCONF = ${SHELL} /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/missing --run autoconf AUTOHEADER = ${SHELL} /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/missing --run autoheader AUTOMAKE = ${SHELL} /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/missing --run automake-1.10 AWK = mawk CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 -D_LARGEFILE64_SOURCE -ansi -Wall -Wno-implicit-function-declaration CPP = gcc -E CPPFLAGS = CXX = g++ CXXCPP = g++ -E CXXDEPMODE = depmode=gcc3 CXXFLAGS = -g -O2 CYGPATH_W = echo DEFS = -DHAVE_CONFIG_H DEPDIR = .deps DSYMUTIL = ECHO = echo ECHO_C = ECHO_N = -n ECHO_T = EGREP = /bin/grep -E EXEEXT = F77 = FFLAGS = GREP = /bin/grep INSTALL = /usr/bin/install -c INSTALL_DATA = ${INSTALL} -m 644 INSTALL_PROGRAM = ${INSTALL} INSTALL_SCRIPT = ${INSTALL} INSTALL_STRIP_PROGRAM = $(install_sh) -c -s LDFLAGS = -lpthread LIBOBJS = LIBS = -ldl LIBTOOL = $(SHELL) $(top_builddir)/libtool LN_S = ln -s LTLIBOBJS = MAKEINFO = ${SHELL} /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/missing --run makeinfo MKDIR_P = /bin/mkdir -p NMEDIT = OBJEXT = o PACKAGE = neethi-src PACKAGE_BUGREPORT = PACKAGE_NAME = neethi-src PACKAGE_STRING = neethi-src 0.1 PACKAGE_TARNAME = neethi-src PACKAGE_VERSION = 0.1 PATH_SEPARATOR = : RANLIB = ranlib SED = /bin/sed SET_MAKE = SHELL = /bin/bash STRIP = strip VERSION = 0.1 VERSION_NO = 1:0:1 abs_builddir = /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/src abs_srcdir = /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/src abs_top_builddir = /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi abs_top_srcdir = /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi ac_ct_CC = gcc ac_ct_CXX = g++ ac_ct_F77 = am__include = include am__leading_dot = . am__quote = am__tar = ${AMTAR} chof - "$$tardir" am__untar = ${AMTAR} xf - bindir = ${exec_prefix}/bin build = x86_64-unknown-linux-gnu build_alias = build_cpu = x86_64 build_os = linux-gnu build_vendor = unknown builddir = . datadir = ${datarootdir} datarootdir = ${prefix}/share docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} dvidir = ${docdir} exec_prefix = ${prefix} host = x86_64-unknown-linux-gnu host_alias = host_cpu = x86_64 host_os = linux-gnu host_vendor = unknown htmldir = ${docdir} includedir = ${prefix}/include infodir = ${datarootdir}/info install_sh = $(SHELL) /home/kkruger/wso2-wsf-php-src-2.1.0/wsf_c/axis2c/neethi/install-sh libdir = ${exec_prefix}/lib libexecdir = ${exec_prefix}/libexec localedir = ${datarootdir}/locale localstatedir = ${prefix}/var mandir = ${datarootdir}/man mkdir_p = /bin/mkdir -p oldincludedir = /usr/include pdfdir = ${docdir} prefix = /usr/lib/php5/20090626/wsf_c program_transform_name = s,x,x, psdir = ${docdir} sbindir = ${exec_prefix}/sbin sharedstatedir = ${prefix}/com srcdir = . sysconfdir = ${prefix}/etc target = x86_64-unknown-linux-gnu target_alias = target_cpu = x86_64 target_os = linux-gnu target_vendor = unknown top_build_prefix = ../ top_builddir = .. top_srcdir = .. SUBDIRS = secpolicy rmpolicy util lib_LTLIBRARIES = libneethi.la libneethi_la_SOURCES = all.c \ assertion.c \ engine.c \ exactlyone.c \ operator.c \ policy.c \ reference.c \ registry.c \ assertion_builder.c \ util.c libneethi_la_LIBADD = ../../axiom/src/om/libaxis2_axiom.la \ ../../util/src/libaxutil.la \ secpolicy/builder/librp_builder.la \ rmpolicy/librm_policy.la \ secpolicy/model/librp_model.la #libneethi_LIBADD=$(top_builddir)/src/core/description/libaxis2_description.la \ # $(top_builddir)/src/core/receivers/libaxis2_receivers.la \ # $(top_builddir)/src/core/deployment/libaxis2_deployment.la \ # $(top_builddir)/src/core/context/libaxis2_context.la \ # $(top_builddir)/src/core/addr/libaxis2_addr.la \ # $(top_builddir)/src/core/clientapi/libaxis2_clientapi.la \ # $(top_builddir)/src/core/phaseresolver/libaxis2_phaseresolver.la \ # $(top_builddir)/src/core/util/libaxis2_core_utils.la \ # $(top_builddir)/src/core/transport/http/common/libaxis2_http_common.la \ # $(top_builddir)/src/core/transport/http/util/libaxis2_http_util.la \ # $(top_builddir)/util/src/libaxutil.la \ # $(top_builddir)/axiom/src/om/libaxis2_axiom.la libneethi_la_LDFLAGS = -version-info $(VERSION_NO) INCLUDES = -I$(top_builddir)/include \ -I ../../util/include \ -I ../../axiom/include \ -I ../../include all: all-recursive .SUFFIXES: .SUFFIXES: .c .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu src/Makefile'; \ cd $(top_srcdir) && \ $(AUTOMAKE) --gnu src/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)" @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ if test -f $$p; then \ f=$(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) '$$p' '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(libLTLIBRARIES_INSTALL) $(INSTALL_STRIP_FLAG) "$$p" "$(DESTDIR)$(libdir)/$$f"; \ else :; fi; \ done uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ p=$(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$p'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$p"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ test "$$dir" != "$$p" || dir=.; \ echo "rm -f \"$${dir}/so_locations\""; \ rm -f "$${dir}/so_locations"; \ done libneethi.la: $(libneethi_la_OBJECTS) $(libneethi_la_DEPENDENCIES) $(libneethi_la_LINK) -rpath $(libdir) $(libneethi_la_OBJECTS) $(libneethi_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c include ./$(DEPDIR)/all.Plo include ./$(DEPDIR)/assertion.Plo include ./$(DEPDIR)/assertion_builder.Plo include ./$(DEPDIR)/engine.Plo include ./$(DEPDIR)/exactlyone.Plo include ./$(DEPDIR)/operator.Plo include ./$(DEPDIR)/policy.Plo include ./$(DEPDIR)/reference.Plo include ./$(DEPDIR)/registry.Plo include ./$(DEPDIR)/util.Plo .c.o: $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po # source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(COMPILE) -c $< .c.obj: $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po # source='$<' object='$@' libtool=no \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(COMPILE) -c `$(CYGPATH_W) '$<'` .c.lo: $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo # source='$<' object='$@' libtool=yes \ # DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ # $(LTCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run `make' without going through this Makefile. # To change the values of `make' variables: instead of editing Makefiles, # (1) if the variable is set in `config.status', edit `config.status' # (which will cause the Makefiles to be regenerated when you run `make'); # (2) otherwise, pass the desired values on the `make' command line. $(RECURSIVE_TARGETS): @failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ list='$(SUBDIRS)'; for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" $(RECURSIVE_CLEAN_TARGETS): @failcom='exit 1'; \ for f in x $$MAKEFLAGS; do \ case $$f in \ *=* | --[!k]*);; \ *k*) failcom='fail=yes';; \ esac; \ done; \ dot_seen=no; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ rev=''; for subdir in $$list; do \ if test "$$subdir" = "."; then :; else \ rev="$$subdir $$rev"; \ fi; \ done; \ rev="$$rev ."; \ target=`echo $@ | sed s/-recursive//`; \ for subdir in $$rev; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done && test -z "$$fail" tags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ done ctags-recursive: list='$(SUBDIRS)'; for subdir in $$list; do \ test "$$subdir" = . || (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ done ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonemtpy = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ mkid -fID $$unique tags: TAGS TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) tags=; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$tags $$unique; \ fi ctags: CTAGS CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ $(TAGS_FILES) $(LISP) tags=; \ list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | \ $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in files) print i; }; }'`; \ test -z "$(CTAGS_ARGS)$$tags$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$tags $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && cd $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) $$here distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \ fi; \ cp -pR $$d/$$file $(distdir)$$dir || exit 1; \ else \ test -f $(distdir)/$$file \ || cp -p $$d/$$file $(distdir)/$$file \ || exit 1; \ fi; \ done list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ distdir=`$(am__cd) $(distdir) && pwd`; \ top_distdir=`$(am__cd) $(top_distdir) && pwd`; \ (cd $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$top_distdir" \ distdir="$$distdir/$$subdir" \ am__remove_distdir=: \ am__skip_length_check=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ `test -z '$(STRIP)' || \ echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." clean: clean-recursive clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-exec-am: install-libLTLIBRARIES install-html: install-html-recursive install-info: install-info-recursive install-man: install-pdf: install-pdf-recursive install-ps: install-ps-recursive installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) install-am \ install-strip .PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ all all-am check check-am clean clean-generic \ clean-libLTLIBRARIES clean-libtool ctags ctags-recursive \ distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-libLTLIBRARIES install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs installdirs-am \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-recursive uninstall uninstall-am \ uninstall-libLTLIBRARIES # -I$(top_builddir)/src/wsdl \ # -I$(top_builddir)/src/core/description \ # -I$(top_builddir)/src/core/engine \ # -I$(top_builddir)/src/core/phaseresolver \ # -I$(top_builddir)/src/core/deployment \ # -I$(top_builddir)/src/core/context \ # -I$(top_builddir)/src/core/util \ # -I$(top_builddir)/src/core/clientapi \ # -I$(top_builddir)/util/include \ # -I$(top_builddir)/axiom/include # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT:
{ "content_hash": "8a2208c18ef352d5a183033341c17cee", "timestamp": "", "source": "github", "line_count": 646, "max_line_length": 156, "avg_line_length": 33.088235294117645, "alnum_prop": 0.640327485380117, "repo_name": "krugerke/ext-wsf", "id": "67a654d1275139564907d78ed5c8e24cdb5b8e63", "size": "21375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wsf_c/axis2c/neethi/src/Makefile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "2688" }, { "name": "C", "bytes": "11214262" }, { "name": "C++", "bytes": "2329118" }, { "name": "CSS", "bytes": "2721" }, { "name": "JavaScript", "bytes": "3212" }, { "name": "Objective-C", "bytes": "3528" }, { "name": "PHP", "bytes": "1065007" }, { "name": "Perl", "bytes": "11749" }, { "name": "Shell", "bytes": "3079172" }, { "name": "XSLT", "bytes": "415208" } ], "symlink_target": "" }
namespace Google.Cloud.Compute.V1.Snippets { // [START compute_v1_generated_RegionInstances_BulkInsert_async_flattened] using Google.Cloud.Compute.V1; using System.Threading.Tasks; using lro = Google.LongRunning; public sealed partial class GeneratedRegionInstancesClientSnippets { /// <summary>Snippet for BulkInsertAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task BulkInsertAsync() { // Create client RegionInstancesClient regionInstancesClient = await RegionInstancesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string region = ""; BulkInsertInstanceResource bulkInsertInstanceResourceResource = new BulkInsertInstanceResource(); // Make the request lro::Operation<Operation, Operation> response = await regionInstancesClient.BulkInsertAsync(project, region, bulkInsertInstanceResourceResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await regionInstancesClient.PollOnceBulkInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } } } // [END compute_v1_generated_RegionInstances_BulkInsert_async_flattened] }
{ "content_hash": "491cab25e3e4c602657a33c9e535c107", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 157, "avg_line_length": 49.18181818181818, "alnum_prop": 0.6732902033271719, "repo_name": "jskeet/gcloud-dotnet", "id": "a8b98e0b6fe51ad32a79b868e75294e9ed340f47", "size": "2818", "binary": false, "copies": "1", "ref": "refs/heads/bq-migration", "path": "apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/RegionInstancesClient.BulkInsertAsyncSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1725" }, { "name": "C#", "bytes": "1829733" } ], "symlink_target": "" }
package com.airbnb.epoxy; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.lang.CharSequence; import java.lang.IllegalArgumentException; import java.lang.Number; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.BitSet; /** * Generated file. Do not modify! */ public class GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ extends EpoxyModel<GroupPropMultipleSupportedAttributeDifferentNameModelView> implements GeneratedModel<GroupPropMultipleSupportedAttributeDifferentNameModelView>, GroupPropMultipleSupportedAttributeDifferentNameModelViewModelBuilder { private final BitSet assignedAttributes_epoxyGeneratedModel = new BitSet(2); private OnModelBoundListener<GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_, GroupPropMultipleSupportedAttributeDifferentNameModelView> onModelBoundListener_epoxyGeneratedModel; private OnModelUnboundListener<GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_, GroupPropMultipleSupportedAttributeDifferentNameModelView> onModelUnboundListener_epoxyGeneratedModel; private OnModelVisibilityStateChangedListener<GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_, GroupPropMultipleSupportedAttributeDifferentNameModelView> onModelVisibilityStateChangedListener_epoxyGeneratedModel; private OnModelVisibilityChangedListener<GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_, GroupPropMultipleSupportedAttributeDifferentNameModelView> onModelVisibilityChangedListener_epoxyGeneratedModel; /** * Bitset index: 0 */ @NonNull private String titleString_String; /** * Bitset index: 1 */ private int titleInt_Int = 0; @Override public void addTo(EpoxyController controller) { super.addTo(controller); addWithDebugValidation(controller); } @Override public void handlePreBind(final EpoxyViewHolder holder, final GroupPropMultipleSupportedAttributeDifferentNameModelView object, final int position) { validateStateHasNotChangedSinceAdded("The model was changed between being added to the controller and being bound.", position); } @Override public void bind(final GroupPropMultipleSupportedAttributeDifferentNameModelView object) { super.bind(object); if (assignedAttributes_epoxyGeneratedModel.get(0)) { object.setTitleString(titleString_String); } else if (assignedAttributes_epoxyGeneratedModel.get(1)) { object.setTitleInt(titleInt_Int); } else { object.setTitleInt(titleInt_Int); } } @Override public void bind(final GroupPropMultipleSupportedAttributeDifferentNameModelView object, EpoxyModel previousModel) { if (!(previousModel instanceof GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_)) { bind(object); return; } GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ that = (GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_) previousModel; super.bind(object); if (assignedAttributes_epoxyGeneratedModel.get(0)) { if (!that.assignedAttributes_epoxyGeneratedModel.get(0) || (titleString_String != null ? !titleString_String.equals(that.titleString_String) : that.titleString_String != null)) { object.setTitleString(titleString_String); } } else if (assignedAttributes_epoxyGeneratedModel.get(1)) { if ((titleInt_Int != that.titleInt_Int)) { object.setTitleInt(titleInt_Int); } } // A value was not set so we should use the default value, but we only need to set it if the previous model had a custom value set. else if (that.assignedAttributes_epoxyGeneratedModel.get(0) || that.assignedAttributes_epoxyGeneratedModel.get(1)) { object.setTitleInt(titleInt_Int); } } @Override public void handlePostBind(final GroupPropMultipleSupportedAttributeDifferentNameModelView object, int position) { if (onModelBoundListener_epoxyGeneratedModel != null) { onModelBoundListener_epoxyGeneratedModel.onModelBound(this, object, position); } validateStateHasNotChangedSinceAdded("The model was changed during the bind call.", position); } /** * Register a listener that will be called when this model is bound to a view. * <p> * The listener will contribute to this model's hashCode state per the {@link * com.airbnb.epoxy.EpoxyAttribute.Option#DoNotHash} rules. * <p> * You may clear the listener by setting a null value, or by calling {@link #reset()} */ public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ onBind( OnModelBoundListener<GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_, GroupPropMultipleSupportedAttributeDifferentNameModelView> listener) { onMutation(); this.onModelBoundListener_epoxyGeneratedModel = listener; return this; } @Override public void unbind(GroupPropMultipleSupportedAttributeDifferentNameModelView object) { super.unbind(object); if (onModelUnboundListener_epoxyGeneratedModel != null) { onModelUnboundListener_epoxyGeneratedModel.onModelUnbound(this, object); } } /** * Register a listener that will be called when this model is unbound from a view. * <p> * The listener will contribute to this model's hashCode state per the {@link * com.airbnb.epoxy.EpoxyAttribute.Option#DoNotHash} rules. * <p> * You may clear the listener by setting a null value, or by calling {@link #reset()} */ public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ onUnbind( OnModelUnboundListener<GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_, GroupPropMultipleSupportedAttributeDifferentNameModelView> listener) { onMutation(); this.onModelUnboundListener_epoxyGeneratedModel = listener; return this; } @Override public void onVisibilityStateChanged(int visibilityState, final GroupPropMultipleSupportedAttributeDifferentNameModelView object) { if (onModelVisibilityStateChangedListener_epoxyGeneratedModel != null) { onModelVisibilityStateChangedListener_epoxyGeneratedModel.onVisibilityStateChanged(this, object, visibilityState); } super.onVisibilityStateChanged(visibilityState, object); } /** * Register a listener that will be called when this model visibility state has changed. * <p> * The listener will contribute to this model's hashCode state per the {@link * com.airbnb.epoxy.EpoxyAttribute.Option#DoNotHash} rules. */ public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ onVisibilityStateChanged( OnModelVisibilityStateChangedListener<GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_, GroupPropMultipleSupportedAttributeDifferentNameModelView> listener) { onMutation(); this.onModelVisibilityStateChangedListener_epoxyGeneratedModel = listener; return this; } @Override public void onVisibilityChanged(float percentVisibleHeight, float percentVisibleWidth, int visibleHeight, int visibleWidth, final GroupPropMultipleSupportedAttributeDifferentNameModelView object) { if (onModelVisibilityChangedListener_epoxyGeneratedModel != null) { onModelVisibilityChangedListener_epoxyGeneratedModel.onVisibilityChanged(this, object, percentVisibleHeight, percentVisibleWidth, visibleHeight, visibleWidth); } super.onVisibilityChanged(percentVisibleHeight, percentVisibleWidth, visibleHeight, visibleWidth, object); } /** * Register a listener that will be called when this model visibility has changed. * <p> * The listener will contribute to this model's hashCode state per the {@link * com.airbnb.epoxy.EpoxyAttribute.Option#DoNotHash} rules. */ public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ onVisibilityChanged( OnModelVisibilityChangedListener<GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_, GroupPropMultipleSupportedAttributeDifferentNameModelView> listener) { onMutation(); this.onModelVisibilityChangedListener_epoxyGeneratedModel = listener; return this; } /** * <i>Required.</i> * * @see GroupPropMultipleSupportedAttributeDifferentNameModelView#setTitleString(String) */ public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ titleString( @NonNull String titleString) { if (titleString == null) { throw new IllegalArgumentException("titleString cannot be null"); } assignedAttributes_epoxyGeneratedModel.set(0); assignedAttributes_epoxyGeneratedModel.clear(1); this.titleInt_Int = 0; onMutation(); this.titleString_String = titleString; return this; } @NonNull public String titleStringString() { return titleString_String; } /** * <i>Optional</i>: Default value is 0 * * @see GroupPropMultipleSupportedAttributeDifferentNameModelView#setTitleInt(int) */ public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ titleInt(int titleInt) { assignedAttributes_epoxyGeneratedModel.set(1); assignedAttributes_epoxyGeneratedModel.clear(0); this.titleString_String = null; onMutation(); this.titleInt_Int = titleInt; return this; } public int titleIntInt() { return titleInt_Int; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ id(long id) { super.id(id); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ id( @Nullable Number... ids) { super.id(ids); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ id(long id1, long id2) { super.id(id1, id2); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ id( @Nullable CharSequence key) { super.id(key); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ id( @Nullable CharSequence key, @Nullable CharSequence... otherKeys) { super.id(key, otherKeys); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ id( @Nullable CharSequence key, long id) { super.id(key, id); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ layout( @LayoutRes int layoutRes) { super.layout(layoutRes); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ spanSizeOverride( @Nullable EpoxyModel.SpanSizeOverrideCallback spanSizeCallback) { super.spanSizeOverride(spanSizeCallback); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ show() { super.show(); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ show(boolean show) { super.show(show); return this; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ hide() { super.hide(); return this; } @Override @LayoutRes protected int getDefaultLayout() { return 1; } @Override public GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ reset() { onModelBoundListener_epoxyGeneratedModel = null; onModelUnboundListener_epoxyGeneratedModel = null; onModelVisibilityStateChangedListener_epoxyGeneratedModel = null; onModelVisibilityChangedListener_epoxyGeneratedModel = null; assignedAttributes_epoxyGeneratedModel.clear(); this.titleString_String = null; this.titleInt_Int = 0; super.reset(); return this; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_)) { return false; } if (!super.equals(o)) { return false; } GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ that = (GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_) o; if (((onModelBoundListener_epoxyGeneratedModel == null) != (that.onModelBoundListener_epoxyGeneratedModel == null))) { return false; } if (((onModelUnboundListener_epoxyGeneratedModel == null) != (that.onModelUnboundListener_epoxyGeneratedModel == null))) { return false; } if (((onModelVisibilityStateChangedListener_epoxyGeneratedModel == null) != (that.onModelVisibilityStateChangedListener_epoxyGeneratedModel == null))) { return false; } if (((onModelVisibilityChangedListener_epoxyGeneratedModel == null) != (that.onModelVisibilityChangedListener_epoxyGeneratedModel == null))) { return false; } if ((titleString_String != null ? !titleString_String.equals(that.titleString_String) : that.titleString_String != null)) { return false; } if ((titleInt_Int != that.titleInt_Int)) { return false; } return true; } @Override public int hashCode() { int _result = super.hashCode(); _result = 31 * _result + (onModelBoundListener_epoxyGeneratedModel != null ? 1 : 0); _result = 31 * _result + (onModelUnboundListener_epoxyGeneratedModel != null ? 1 : 0); _result = 31 * _result + (onModelVisibilityStateChangedListener_epoxyGeneratedModel != null ? 1 : 0); _result = 31 * _result + (onModelVisibilityChangedListener_epoxyGeneratedModel != null ? 1 : 0); _result = 31 * _result + (titleString_String != null ? titleString_String.hashCode() : 0); _result = 31 * _result + titleInt_Int; return _result; } @Override public String toString() { return "GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_{" + "titleString_String=" + titleString_String + ", titleInt_Int=" + titleInt_Int + "}" + super.toString(); } public static GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ from( ModelProperties properties) { GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_ model = new GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_(); model.id(properties.getId()); if (properties.has("titleString")) { model.titleString(properties.getString("titleString")); } else if (properties.has("titleInt")) { model.titleInt(properties.getInt("titleInt")); } return model; } @Override public int getSpanSize(int totalSpanCount, int position, int itemCount) { return totalSpanCount; } }
{ "content_hash": "492fcc496d9d37492067346ca1bcc941", "timestamp": "", "source": "github", "line_count": 384, "max_line_length": 312, "avg_line_length": 38.203125, "alnum_prop": 0.7633265167007498, "repo_name": "airbnb/epoxy", "id": "31ad583112abc179f8677cbc80880b569502dbbc", "size": "14670", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "epoxy-modelfactorytest/src/test/resources/GroupPropMultipleSupportedAttributeDifferentNameModelViewModel_.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2695" }, { "name": "HTML", "bytes": "2958" }, { "name": "Java", "bytes": "3068867" }, { "name": "JavaScript", "bytes": "5252" }, { "name": "Kotlin", "bytes": "1111468" } ], "symlink_target": "" }
ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a2b0e38bdb1faaede7b17926ecf0f057", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.076923076923077, "alnum_prop": 0.6779661016949152, "repo_name": "mdoering/backbone", "id": "a50f9ef99aa650fa61fdc1bf09f1ab60058d05b9", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Onagraceae/Oenothera/Oenothera communis/Oenothera communis communis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Rx; interface ObservableInterface { /** * @param ObserverInterface $observer * @return DisposableInterface */ public function subscribe(ObserverInterface $observer); }
{ "content_hash": "5e0a4606dfca50495c9de6fa064ca553", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 59, "avg_line_length": 17.416666666666668, "alnum_prop": 0.69377990430622, "repo_name": "asm89/Rx.PHP", "id": "ae2ff97de37f48a06c53d79665b18cd519267505", "size": "209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Rx/ObservableInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "546344" } ], "symlink_target": "" }
from __future__ import unicode_literals from .utils import HandlerProxy handler = HandlerProxy()
{ "content_hash": "f4465a3d4154067d795e42a51aef8f5b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 39, "avg_line_length": 19.8, "alnum_prop": 0.7777777777777778, "repo_name": "charettes/django-mutant", "id": "2648628a74208c235e7f859e5d3029fc0629b708", "size": "99", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mutant/state/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "247110" } ], "symlink_target": "" }
package main import ( "fmt" "io/ioutil" "github.com/moovweb/gokogiri" "github.com/moovweb/gokogiri/xml" ) func parseOEBPSPackage(ef *epubFile, c *container) error { epub := ef.data file := findZipFile(ef.r, c.OEBPSPackagePath) if file == nil { return UnexpectedError } fr, err := file.Open() if err != nil { return fmt.Errorf("could not open %s, %s", c.OEBPSPackagePath, err) } defer fr.Close() data, err := ioutil.ReadAll(fr) if err != nil { return UnexpectedError } doc, err := gokogiri.ParseXml(data) if err != nil { return InvalidXMLError } defer doc.Free() doc.RecursivelyRemoveNamespaces() epub.Version = doc.Root().Attr("version") res, _ := doc.Search("/package/metadata") if len(res) != 1 { return NoEPUBError } mn := res[0] creators, _ := mn.Search("creator") contributors, _ := mn.Search("contributor") epub.Titles = parseTitles(mn) epub.Creators = parsePeople(creators) epub.Contributors = parsePeople(contributors) epub.Subjects = parseSubjects(mn) epub.Description = parseDescription(mn) epub.Publisher = parsePublisher(mn) epub.Dates = parseDates(mn) epub.Identifiers = parseIdentifiers(mn) epub.Source = parseSource(mn) epub.Languages = parseLanguages(mn) epub.Rights = parseRights(mn) return nil } func parseTitles(m xml.Node) []string { titles := []string{} res, _ := m.Search("title") for _, n := range res { titles = append(titles, n.Content()) } return titles } func parsePeople(s []xml.Node) []*Person { people := []*Person{} for _, n := range s { person := &Person{ Name: n.Content(), FileAs: n.Attr("file-as"), Role: n.Attr("role"), } people = append(people, person) } return people } func parseSubjects(m xml.Node) []string { subjects := []string{} res, _ := m.Search("subject") for _, n := range res { subjects = append(subjects, n.Content()) } return subjects } func parseDescription(m xml.Node) string { description := "" res, _ := m.Search("description") if len(res) > 0 { description = res[0].Content() } return description } func parsePublisher(m xml.Node) string { publisher := "" res, _ := m.Search("publisher") if len(res) > 0 { publisher = res[0].Content() } return publisher } func parseDates(m xml.Node) []*Date { dates := []*Date{} res, _ := m.Search("date") for _, n := range res { date := Date{Date: n.Content(), Event: n.Attr("event")} dates = append(dates, &date) } res, _ = m.Search("meta[@property='dcterms:modified']") if len(res) > 0 { date := Date{Date: res[0].Content(), Event: "modified"} dates = append(dates, &date) } return dates } func parseIdentifiers(m xml.Node) []*Identifier { identifiers := []*Identifier{} res, _ := m.Search("identifier") for _, n := range res { identifier := Identifier{Identifier: n.Content(), Scheme: n.Attr("scheme")} identifiers = append(identifiers, &identifier) } return identifiers } func parseSource(m xml.Node) string { res, _ := m.Search("source") if len(res) > 0 { return res[0].Content() } return "" } func parseLanguages(m xml.Node) []string { languages := []string{} res, _ := m.Search("language") for _, n := range res { languages = append(languages, n.Content()) } return languages } func parseRights(m xml.Node) string { res, _ := m.Search("rights") if len(res) > 0 { return res[0].Content() } return "" }
{ "content_hash": "6cca404b862881fa777ab4e0c9d09d5a", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 77, "avg_line_length": 18.905027932960895, "alnum_prop": 0.6450945626477541, "repo_name": "reapub/parser", "id": "a8d01c4aed2b9ea062488daa2a0d638c96000757", "size": "3384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "oebpspackage.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "5851" } ], "symlink_target": "" }
================ Changelog - 2017 ================ .. note:: Please see :doc:`news` for the latest changes 19.7.1 / 2017/03/21 =================== - fix: continue if SO_REUSEPORT seems to be available but fails (:issue:`1480`) - fix: support non-decimal values for the umask command line option (:issue:`1325`) 19.7.0 / 2017/03/01 =================== - The previously deprecated ``gunicorn_django`` command has been removed. Use the :ref:`gunicorn-cmd` command-line interface instead. - The previously deprecated ``django_settings`` setting has been removed. Use the :ref:`raw-env` setting instead. - The default value of :ref:`ssl-version` has been changed from ``ssl.PROTOCOL_TLSv1`` to ``ssl.PROTOCOL_SSLv23``. - fix: initialize the group access list when initgroups is set (:issue:`1297`) - add environment variables to gunicorn access log format (:issue:`1291`) - add --paste-global-conf option (:issue:`1304`) - fix: print access logs to STDOUT (:issue:`1184`) - remove upper limit on max header size config (:issue:`1313`) - fix: print original exception on AppImportError (:issue:`1334`) - use SO_REUSEPORT if available (:issue:`1344`) - `fix leak <https://github.com/benoitc/gunicorn/commit/b4c41481e2d5ef127199a4601417a6819053c3fd>`_ of duplicate file descriptor for bound sockets. - add --reload-engine option, support inotify and other backends (:issue:`1368`, :issue:`1459`) - fix: reject request with invalid HTTP versions - add ``child_exit`` callback (:issue:`1394`) - add support for eventlets _AlreadyHandled object (:issue:`1406`) - format boot tracebacks properly with reloader (:issue:`1408`) - refactor socket activation and fd inheritance for better support of SystemD (:issue:`1310`) - fix: o fds are given by default in gunicorn (:issue:`1423`) - add ability to pass settings to GUNICORN_CMD_ARGS environment variable which helps in container world (:issue:`1385`) - fix: catch access denied to pid file (:issue:`1091`) - many additions and improvements to the documentation Breaking Change +++++++++++++++ - **Python 2.6.0** is the last supported version
{ "content_hash": "04522e83a8ae62b824f2dda70c39a2cc", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 147, "avg_line_length": 45.65217391304348, "alnum_prop": 0.7095238095238096, "repo_name": "cloudera/hue", "id": "0fb201e61f5adf4184e991e891eadfeabfc0d8ea", "size": "2100", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "desktop/core/ext-py/gunicorn-19.9.0/docs/source/2017-news.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ABAP", "bytes": "962" }, { "name": "ActionScript", "bytes": "1133" }, { "name": "Ada", "bytes": "99" }, { "name": "Assembly", "bytes": "2347" }, { "name": "AutoHotkey", "bytes": "720" }, { "name": "BASIC", "bytes": "2884" }, { "name": "Batchfile", "bytes": "143575" }, { "name": "C", "bytes": "5129166" }, { "name": "C#", "bytes": "83" }, { "name": "C++", "bytes": "718011" }, { "name": "COBOL", "bytes": "4" }, { "name": "CSS", "bytes": "680715" }, { "name": "Cirru", "bytes": "520" }, { "name": "Clojure", "bytes": "794" }, { "name": "Closure Templates", "bytes": "1072" }, { "name": "CoffeeScript", "bytes": "403" }, { "name": "ColdFusion", "bytes": "86" }, { "name": "Common Lisp", "bytes": "632" }, { "name": "Cython", "bytes": "1016963" }, { "name": "D", "bytes": "324" }, { "name": "Dart", "bytes": "489" }, { "name": "Dockerfile", "bytes": "13576" }, { "name": "EJS", "bytes": "752" }, { "name": "Eiffel", "bytes": "375" }, { "name": "Elixir", "bytes": "692" }, { "name": "Elm", "bytes": "487" }, { "name": "Emacs Lisp", "bytes": "411907" }, { "name": "Erlang", "bytes": "487" }, { "name": "Forth", "bytes": "979" }, { "name": "FreeMarker", "bytes": "1017" }, { "name": "G-code", "bytes": "521" }, { "name": "GAP", "bytes": "29873" }, { "name": "GLSL", "bytes": "512" }, { "name": "Genshi", "bytes": "946" }, { "name": "Gherkin", "bytes": "699" }, { "name": "Go", "bytes": "641" }, { "name": "Groovy", "bytes": "1080" }, { "name": "HTML", "bytes": "28328425" }, { "name": "Haml", "bytes": "920" }, { "name": "Handlebars", "bytes": "173" }, { "name": "Haskell", "bytes": "512" }, { "name": "Haxe", "bytes": "447" }, { "name": "HiveQL", "bytes": "43" }, { "name": "Io", "bytes": "140" }, { "name": "Java", "bytes": "457398" }, { "name": "JavaScript", "bytes": "39181239" }, { "name": "Jinja", "bytes": "356" }, { "name": "Julia", "bytes": "210" }, { "name": "LSL", "bytes": "2080" }, { "name": "Lean", "bytes": "213" }, { "name": "Less", "bytes": "396102" }, { "name": "Lex", "bytes": "218764" }, { "name": "Liquid", "bytes": "1883" }, { "name": "LiveScript", "bytes": "5747" }, { "name": "Lua", "bytes": "78382" }, { "name": "M4", "bytes": "1751" }, { "name": "MATLAB", "bytes": "203" }, { "name": "Makefile", "bytes": "1025937" }, { "name": "Mako", "bytes": "3644004" }, { "name": "Mask", "bytes": "597" }, { "name": "Myghty", "bytes": "936" }, { "name": "Nix", "bytes": "2212" }, { "name": "OCaml", "bytes": "539" }, { "name": "Objective-C", "bytes": "2672" }, { "name": "OpenSCAD", "bytes": "333" }, { "name": "PHP", "bytes": "662" }, { "name": "PLSQL", "bytes": "29403" }, { "name": "PLpgSQL", "bytes": "6006" }, { "name": "Pascal", "bytes": "84273" }, { "name": "Perl", "bytes": "4327" }, { "name": "PigLatin", "bytes": "371" }, { "name": "PowerShell", "bytes": "6235" }, { "name": "Procfile", "bytes": "47" }, { "name": "Pug", "bytes": "584" }, { "name": "Python", "bytes": "92881549" }, { "name": "R", "bytes": "2445" }, { "name": "Roff", "bytes": "484108" }, { "name": "Ruby", "bytes": "1098" }, { "name": "Rust", "bytes": "495" }, { "name": "SCSS", "bytes": "78508" }, { "name": "Sass", "bytes": "770" }, { "name": "Scala", "bytes": "1541" }, { "name": "Scheme", "bytes": "559" }, { "name": "Shell", "bytes": "249165" }, { "name": "Smarty", "bytes": "130" }, { "name": "SourcePawn", "bytes": "948" }, { "name": "Stylus", "bytes": "682" }, { "name": "Tcl", "bytes": "899" }, { "name": "TeX", "bytes": "165743" }, { "name": "Thrift", "bytes": "341963" }, { "name": "Twig", "bytes": "761" }, { "name": "TypeScript", "bytes": "1241396" }, { "name": "VBScript", "bytes": "938" }, { "name": "VHDL", "bytes": "830" }, { "name": "Vala", "bytes": "485" }, { "name": "Verilog", "bytes": "274" }, { "name": "Vim Snippet", "bytes": "226931" }, { "name": "Vue", "bytes": "350385" }, { "name": "XQuery", "bytes": "114" }, { "name": "XSLT", "bytes": "522199" }, { "name": "Yacc", "bytes": "1070437" }, { "name": "jq", "bytes": "4" } ], "symlink_target": "" }
include(${CMAKE_ROOT}/Modules/CMakeDetermineCompiler.cmake) # Load system-specific compiler preferences for this language. include(Platform/${CMAKE_SYSTEM_NAME}-Determine-CXX OPTIONAL) include(Platform/${CMAKE_SYSTEM_NAME}-CXX OPTIONAL) if(NOT CMAKE_CXX_COMPILER_NAMES) set(CMAKE_CXX_COMPILER_NAMES CC) endif() if(${CMAKE_GENERATOR} MATCHES "Visual Studio") elseif("${CMAKE_GENERATOR}" MATCHES "Xcode") set(CMAKE_CXX_COMPILER_XCODE_TYPE sourcecode.cpp.cpp) _cmake_find_compiler_path(CXX) else() if(NOT CMAKE_CXX_COMPILER) set(CMAKE_CXX_COMPILER_INIT NOTFOUND) # prefer the environment variable CXX if(NOT $ENV{CXX} STREQUAL "") get_filename_component(CMAKE_CXX_COMPILER_INIT $ENV{CXX} PROGRAM PROGRAM_ARGS CMAKE_CXX_FLAGS_ENV_INIT) if(CMAKE_CXX_FLAGS_ENV_INIT) set(CMAKE_CXX_COMPILER_ARG1 "${CMAKE_CXX_FLAGS_ENV_INIT}" CACHE STRING "First argument to CXX compiler") endif() if(NOT EXISTS ${CMAKE_CXX_COMPILER_INIT}) message(FATAL_ERROR "Could not find compiler set in environment variable CXX:\n$ENV{CXX}.\n${CMAKE_CXX_COMPILER_INIT}") endif() endif() # next prefer the generator specified compiler if(CMAKE_GENERATOR_CXX) if(NOT CMAKE_CXX_COMPILER_INIT) set(CMAKE_CXX_COMPILER_INIT ${CMAKE_GENERATOR_CXX}) endif() endif() # finally list compilers to try if(NOT CMAKE_CXX_COMPILER_INIT) set(CMAKE_CXX_COMPILER_LIST CC ${_CMAKE_TOOLCHAIN_PREFIX}c++ ${_CMAKE_TOOLCHAIN_PREFIX}g++ aCC cl bcc xlC clang++) endif() _cmake_find_compiler(CXX) else() _cmake_find_compiler_path(CXX) endif() mark_as_advanced(CMAKE_CXX_COMPILER) # Each entry in this list is a set of extra flags to try # adding to the compile line to see if it helps produce # a valid identification file. set(CMAKE_CXX_COMPILER_ID_TEST_FLAGS_FIRST) set(CMAKE_CXX_COMPILER_ID_TEST_FLAGS # Try compiling to an object file only. "-c" ) endif() # Build a small source file to identify the compiler. if(NOT CMAKE_CXX_COMPILER_ID_RUN) set(CMAKE_CXX_COMPILER_ID_RUN 1) # Try to identify the compiler. set(CMAKE_CXX_COMPILER_ID) set(CMAKE_CXX_PLATFORM_ID) file(READ ${CMAKE_ROOT}/Modules/CMakePlatformId.h.in CMAKE_CXX_COMPILER_ID_PLATFORM_CONTENT) # The IAR compiler produces weird output. # See https://gitlab.kitware.com/cmake/cmake/issues/10176#note_153591 list(APPEND CMAKE_CXX_COMPILER_ID_VENDORS IAR) set(CMAKE_CXX_COMPILER_ID_VENDOR_FLAGS_IAR ) set(CMAKE_CXX_COMPILER_ID_VENDOR_REGEX_IAR "IAR .+ Compiler") # Match the link line from xcodebuild output of the form # Ld ... # ... # /path/to/cc ...CompilerIdCXX/... # to extract the compiler front-end for the language. set(CMAKE_CXX_COMPILER_ID_TOOL_MATCH_REGEX "\nLd[^\n]*(\n[ \t]+[^\n]*)*\n[ \t]+([^ \t\r\n]+)[^\r\n]*-o[^\r\n]*CompilerIdCXX/(\\./)?(CompilerIdCXX.xctest/)?CompilerIdCXX[ \t\n\\\"]") set(CMAKE_CXX_COMPILER_ID_TOOL_MATCH_INDEX 2) include(${CMAKE_ROOT}/Modules/CMakeDetermineCompilerId.cmake) CMAKE_DETERMINE_COMPILER_ID(CXX CXXFLAGS CMakeCXXCompilerId.cpp) # Set old compiler and platform id variables. if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set(CMAKE_COMPILER_IS_GNUCXX 1) endif() if(CMAKE_CXX_PLATFORM_ID MATCHES "MinGW") set(CMAKE_COMPILER_IS_MINGW 1) elseif(CMAKE_CXX_PLATFORM_ID MATCHES "Cygwin") set(CMAKE_COMPILER_IS_CYGWIN 1) endif() endif() if (NOT _CMAKE_TOOLCHAIN_LOCATION) get_filename_component(_CMAKE_TOOLCHAIN_LOCATION "${CMAKE_CXX_COMPILER}" PATH) endif () # if we have a g++ cross compiler, they have usually some prefix, like # e.g. powerpc-linux-g++, arm-elf-g++ or i586-mingw32msvc-g++ , optionally # with a 3-component version number at the end (e.g. arm-eabi-gcc-4.5.2). # The other tools of the toolchain usually have the same prefix # NAME_WE cannot be used since then this test will fail for names like # "arm-unknown-nto-qnx6.3.0-gcc.exe", where BASENAME would be # "arm-unknown-nto-qnx6" instead of the correct "arm-unknown-nto-qnx6.3.0-" if (CMAKE_CROSSCOMPILING AND NOT _CMAKE_TOOLCHAIN_PREFIX) if("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU" OR "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") get_filename_component(COMPILER_BASENAME "${CMAKE_CXX_COMPILER}" NAME) if (COMPILER_BASENAME MATCHES "^(.+-)(clan)?[gc]\\+\\+(-[0-9]+\\.[0-9]+\\.[0-9]+)?(\\.exe)?$") set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_MATCH_1}) elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") if(CMAKE_CXX_COMPILER_TARGET) set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_CXX_COMPILER_TARGET}-) endif() elseif(COMPILER_BASENAME MATCHES "QCC(\\.exe)?$") if(CMAKE_CXX_COMPILER_TARGET MATCHES "gcc_nto([^_le]+)(le)?") set(_CMAKE_TOOLCHAIN_PREFIX nto${CMAKE_MATCH_1}-) endif() endif () # if "llvm-" is part of the prefix, remove it, since llvm doesn't have its own binutils # but uses the regular ar, objcopy, etc. (instead of llvm-objcopy etc.) if ("${_CMAKE_TOOLCHAIN_PREFIX}" MATCHES "(.+-)?llvm-$") set(_CMAKE_TOOLCHAIN_PREFIX ${CMAKE_MATCH_1}) endif () elseif("${CMAKE_CXX_COMPILER_ID}" MATCHES "TI") # TI compilers are named e.g. cl6x, cl470 or armcl.exe get_filename_component(COMPILER_BASENAME "${CMAKE_CXX_COMPILER}" NAME) if (COMPILER_BASENAME MATCHES "^(.+)?cl([^.]+)?(\\.exe)?$") set(_CMAKE_TOOLCHAIN_PREFIX "${CMAKE_MATCH_1}") set(_CMAKE_TOOLCHAIN_SUFFIX "${CMAKE_MATCH_2}") endif () endif() endif () include(CMakeFindBinUtils) set(_CMAKE_PROCESSING_LANGUAGE "CXX") include(Compiler/${CMAKE_CXX_COMPILER_ID}-FindBinUtils OPTIONAL) unset(_CMAKE_PROCESSING_LANGUAGE) if(MSVC_CXX_ARCHITECTURE_ID) set(SET_MSVC_CXX_ARCHITECTURE_ID "set(MSVC_CXX_ARCHITECTURE_ID ${MSVC_CXX_ARCHITECTURE_ID})") endif() if(CMAKE_CXX_XCODE_CURRENT_ARCH) set(SET_CMAKE_XCODE_CURRENT_ARCH "set(CMAKE_XCODE_CURRENT_ARCH ${CMAKE_CXX_XCODE_CURRENT_ARCH})") endif() # configure all variables set in this file configure_file(${CMAKE_ROOT}/Modules/CMakeCXXCompiler.cmake.in ${CMAKE_PLATFORM_INFO_DIR}/CMakeCXXCompiler.cmake @ONLY ) set(CMAKE_CXX_COMPILER_ENV_VAR "CXX")
{ "content_hash": "4ca90fed23e3f26299ffab812ac86884", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 183, "avg_line_length": 37.94444444444444, "alnum_prop": 0.6917195379860094, "repo_name": "dava/dava.engine", "id": "9150962d9c15ac1194f8b41fda584c6225a07c21", "size": "6931", "binary": false, "copies": "3", "ref": "refs/heads/development", "path": "Bin/CMakeMac/CMake.app/Contents/share/cmake-3.9/Modules/CMakeDetermineCXXCompiler.cmake", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "166572" }, { "name": "Batchfile", "bytes": "18562" }, { "name": "C", "bytes": "61621347" }, { "name": "C#", "bytes": "574524" }, { "name": "C++", "bytes": "50229645" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "11439187" }, { "name": "CSS", "bytes": "32773" }, { "name": "Cuda", "bytes": "37073" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Emacs Lisp", "bytes": "44259" }, { "name": "Fortran", "bytes": "8835" }, { "name": "GLSL", "bytes": "3726" }, { "name": "Go", "bytes": "1235" }, { "name": "HTML", "bytes": "8621333" }, { "name": "Java", "bytes": "232072" }, { "name": "JavaScript", "bytes": "2560" }, { "name": "Lua", "bytes": "43080" }, { "name": "M4", "bytes": "165145" }, { "name": "Makefile", "bytes": "1349214" }, { "name": "Mathematica", "bytes": "4633" }, { "name": "Module Management System", "bytes": "15224" }, { "name": "Objective-C", "bytes": "1909821" }, { "name": "Objective-C++", "bytes": "498191" }, { "name": "Pascal", "bytes": "99390" }, { "name": "Perl", "bytes": "396608" }, { "name": "Python", "bytes": "782784" }, { "name": "QML", "bytes": "43105" }, { "name": "QMake", "bytes": "156" }, { "name": "Roff", "bytes": "71083" }, { "name": "Ruby", "bytes": "22742" }, { "name": "SAS", "bytes": "16030" }, { "name": "Shell", "bytes": "2482394" }, { "name": "Slash", "bytes": "117430" }, { "name": "Smalltalk", "bytes": "5908" }, { "name": "TeX", "bytes": "428489" }, { "name": "Vim script", "bytes": "133255" }, { "name": "Visual Basic", "bytes": "54056" }, { "name": "WebAssembly", "bytes": "13987" } ], "symlink_target": "" }
package in.manrajsingh.volley; import android.app.Application; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; /** * Created by manraj singh on 2/10/2016. */ public class AppController extends Application{ public static final String TAG = AppController.class.getSimpleName(); private RequestQueue mRQ; private static AppController mI; @Override public void onCreate(){ super.onCreate(); mI = this; } public static synchronized AppController getInstance(){ return mI; } public RequestQueue getRequestQueue(){ if(mRQ == null){ mRQ = Volley.newRequestQueue(getApplicationContext()); } return mRQ; } public <T> void addToRequestQueue(Request<T> req){ req.setTag(TAG); getRequestQueue().add(req); } public <T> void cancelPendingRequest(Object tag){ if(mRQ != null){ mRQ.cancelAll(tag); } } }
{ "content_hash": "3353e1908decf71752c2a730dfbe2e0b", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 73, "avg_line_length": 24.837209302325583, "alnum_prop": 0.6198501872659176, "repo_name": "ManrajGrover/Mastering-Android", "id": "59f08a3d379c5d054da08e9cb55cc58c7345adcc", "size": "1068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Volley/app/src/main/java/in/manrajsingh/volley/AppController.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "81273" } ], "symlink_target": "" }
require 'dfp_api' require 'dfp_api_statement' API_VERSION = :v201411 def get_placements_by_statement() # Get DfpApi instance and load configuration from ~/dfp_api.yml. dfp = DfpApi::Api.new # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in # the configuration file or provide your own logger: # dfp.logger = Logger.new('dfp_xml.log') # Get the PlacementService. placement_service = dfp.service(:PlacementService, API_VERSION) # Create a statement to only select active placements. statement = DfpApiStatement::FilterStatement.new( 'WHERE status = :status ORDER BY id ASC', [ {:key => 'status', :value => {:value => 'ACTIVE', :xsi_type => 'TextValue'}} ] } begin # Get placements by statement. page = placement_service.get_placements_by_statement( statement.toStatement()) if page and page[:results] page[:results].each_with_index do |placement, index| puts "%d) Placement ID: %d, name: %s, status: %s." % [ index + statement.offset, placement[:id], placement[:name], placement[:status]] end end statement.offset += DfpApiStatement::SUGGESTED_PAGE_LIMIT end while statement.offset < page[:total_result_set_size] # Print a footer. if page.include?(:total_result_set_size) puts "Number of results found: %d" % page[:total_result_set_size] end end if __FILE__ == $0 begin get_placements_by_statement() # HTTP errors. rescue AdsCommon::Errors::HttpError => e puts "HTTP Error: %s" % e # API errors. rescue DfpApi::Errors::ApiException => e puts "Message: %s" % e.message puts 'Errors:' e.errors.each_with_index do |error, index| puts "\tError [%d]:" % (index + 1) error.each do |field, value| puts "\t\t%s: %s" % [field, value] end end end end
{ "content_hash": "f68cf6dc842cc7f7df3f0738d9dc6216", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 77, "avg_line_length": 28.53030303030303, "alnum_prop": 0.636218799787573, "repo_name": "aditya01933/google-api-ads-ruby", "id": "bb6ec969dd2ec1d7e7cc413985ffa56544b753a6", "size": "2727", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dfp_api/examples/v201411/placement_service/get_placements_by_statement.rb", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1028" }, { "name": "HTML", "bytes": "7762" }, { "name": "JavaScript", "bytes": "757" }, { "name": "Python", "bytes": "187" }, { "name": "Ruby", "bytes": "8519404" } ], "symlink_target": "" }
using content::BrowserThread; using content::PasswordForm; using testing::_; using testing::DoAll; using ::testing::Exactly; using ::testing::WithArg; using ::testing::Return; class MockPasswordManagerDelegate : public PasswordManagerDelegate { public: MOCK_METHOD1(FillPasswordForm, void(const autofill::PasswordFormFillData&)); MOCK_METHOD1(AddSavePasswordInfoBarIfPermitted, void(PasswordFormManager*)); MOCK_METHOD0(GetProfile, Profile*()); MOCK_METHOD0(DidLastPageLoadEncounterSSLErrors, bool()); }; ACTION_P(InvokeConsumer, forms) { arg0->OnGetPasswordStoreResults(forms); } ACTION_P(SaveToScopedPtr, scoped) { scoped->reset(arg0); } class PasswordManagerTest : public ChromeRenderViewHostTestHarness { public: PasswordManagerTest() : ui_thread_(BrowserThread::UI, MessageLoopForUI::current()) {} virtual ~PasswordManagerTest() {} protected: virtual void SetUp() { testing_profile_ = new TestingProfile; store_ = static_cast<MockPasswordStore*>( PasswordStoreFactory::GetInstance()->SetTestingFactoryAndUse( testing_profile_, MockPasswordStore::Build).get()); browser_context_.reset(testing_profile_); ChromeRenderViewHostTestHarness::SetUp(); EXPECT_CALL(delegate_, GetProfile()).WillRepeatedly(Return(profile())); PasswordManager::CreateForWebContentsAndDelegate( web_contents(), &delegate_); EXPECT_CALL(delegate_, DidLastPageLoadEncounterSSLErrors()) .WillRepeatedly(Return(false)); } virtual void TearDown() { store_ = NULL; ChromeRenderViewHostTestHarness::TearDown(); } PasswordForm MakeSimpleForm() { PasswordForm form; form.origin = GURL("http://www.google.com/a/LoginAuth"); form.action = GURL("http://www.google.com/a/Login"); form.username_element = ASCIIToUTF16("Email"); form.password_element = ASCIIToUTF16("Passwd"); form.username_value = ASCIIToUTF16("google"); form.password_value = ASCIIToUTF16("password"); // Default to true so we only need to add tests in autocomplete=off cases. form.password_autocomplete_set = true; form.submit_element = ASCIIToUTF16("signIn"); form.signon_realm = "http://www.google.com"; return form; } PasswordManager* manager() { return PasswordManager::FromWebContents(web_contents()); } // We create a UI thread to satisfy PasswordStore. content::TestBrowserThread ui_thread_; scoped_refptr<MockPasswordStore> store_; MockPasswordManagerDelegate delegate_; // Owned by manager_. TestingProfile* testing_profile_; }; MATCHER_P(FormMatches, form, "") { return form.signon_realm == arg.signon_realm && form.origin == arg.origin && form.action == arg.action && form.username_element == arg.username_element && form.password_element == arg.password_element && form.password_autocomplete_set == arg.password_autocomplete_set && form.submit_element == arg.submit_element; } TEST_F(PasswordManagerTest, FormSubmitEmptyStore) { // Test that observing a newly submitted form shows the save password bar. std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillOnce(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. // And the form submit contract is to call ProvisionallySavePassword. manager()->ProvisionallySavePassword(form); scoped_ptr<PasswordFormManager> form_to_save; EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)) .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); manager()->OnPasswordFormsParsed(observed); // The post-navigation load. manager()->OnPasswordFormsRendered(observed); // The post-navigation layout. ASSERT_TRUE(form_to_save.get()); EXPECT_CALL(*store_, AddLogin(FormMatches(form))); // Simulate saving the form, as if the info bar was accepted. form_to_save->Save(); } TEST_F(PasswordManagerTest, GeneratedPasswordFormSubmitEmptyStore) { // This test is the same FormSubmitEmptyStore, except that it simulates the // user generating the password through the browser. std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillOnce(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. // Simulate the user generating the password and submitting the form. manager()->SetFormHasGeneratedPassword(form); manager()->ProvisionallySavePassword(form); // The user should not be presented with an infobar as they have already given // consent by using the generated password. The form should be saved once // navigation occurs. EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)).Times(Exactly(0)); EXPECT_CALL(*store_, AddLogin(FormMatches(form))); // Now the password manager waits for the navigation to complete. observed.clear(); manager()->OnPasswordFormsParsed(observed); // The post-navigation load. manager()->OnPasswordFormsRendered(observed); // The post-navigation layout. } TEST_F(PasswordManagerTest, FormSubmitNoGoodMatch) { // Same as above, except with an existing form for the same signon realm, // but different origin. Detailed cases like this are covered by // PasswordFormManagerTest. std::vector<PasswordForm*> result; PasswordForm* existing_different = new PasswordForm(MakeSimpleForm()); existing_different->username_value = ASCIIToUTF16("google2"); result.push_back(existing_different); EXPECT_CALL(delegate_, FillPasswordForm(_)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillOnce(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. manager()->ProvisionallySavePassword(form); // We still expect an add, since we didn't have a good match. scoped_ptr<PasswordFormManager> form_to_save; EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)) .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save))); // Now the password manager waits for the navigation to complete. observed.clear(); manager()->OnPasswordFormsParsed(observed); // The post-navigation load. manager()->OnPasswordFormsRendered(observed); // The post-navigation layout. ASSERT_TRUE(form_to_save.get()); EXPECT_CALL(*store_, AddLogin(FormMatches(form))); // Simulate saving the form. form_to_save->Save(); } TEST_F(PasswordManagerTest, FormSeenThenLeftPage) { std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillOnce(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. PasswordForm empty_form(form); empty_form.username_value = string16(); empty_form.password_value = string16(); content::LoadCommittedDetails details; content::FrameNavigateParams params; params.password_form = empty_form; manager()->DidNavigateAnyFrame(details, params); // No expected calls. EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)).Times(0); observed.clear(); manager()->OnPasswordFormsParsed(observed); // The post-navigation load. manager()->OnPasswordFormsRendered(observed); // The post-navigation layout. } TEST_F(PasswordManagerTest, FormSubmitAfterNavigateSubframe) { // Test that navigating a subframe does not prevent us from showing the save // password infobar. std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillOnce(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. // Simulate navigating a sub-frame. content::LoadCommittedDetails details; details.is_main_frame = false; content::FrameNavigateParams params; manager()->DidNavigateAnyFrame(details, params); // Simulate navigating the real page. details.is_main_frame = true; params.password_form = form; manager()->DidNavigateAnyFrame(details, params); // Now the password manager waits for the navigation to complete. scoped_ptr<PasswordFormManager> form_to_save; EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)) .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save))); observed.clear(); manager()->OnPasswordFormsParsed(observed); // The post-navigation load. manager()->OnPasswordFormsRendered(observed); // The post-navigation layout. ASSERT_FALSE(NULL == form_to_save.get()); EXPECT_CALL(*store_, AddLogin(FormMatches(form))); // Simulate saving the form, as if the info bar was accepted. form_to_save->Save(); } // This test verifies a fix for http://crbug.com/236673 TEST_F(PasswordManagerTest, FormSubmitWithFormOnPreviousPage) { std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); PasswordForm first_form(MakeSimpleForm()); first_form.origin = GURL("http://www.nytimes.com/"); first_form.action = GURL("https://myaccount.nytimes.com/auth/login"); first_form.signon_realm = "http://www.nytimes.com/"; PasswordForm second_form(MakeSimpleForm()); second_form.origin = GURL("https://myaccount.nytimes.com/auth/login"); second_form.action = GURL("https://myaccount.nytimes.com/auth/login"); second_form.signon_realm = "https://myaccount.nytimes.com/"; // Pretend that the form is hidden on the first page. std::vector<PasswordForm> observed; observed.push_back(first_form); manager()->OnPasswordFormsParsed(observed); observed.clear(); manager()->OnPasswordFormsRendered(observed); // Now navigate to a second page. content::LoadCommittedDetails details; details.is_main_frame = true; content::FrameNavigateParams params; manager()->DidNavigateAnyFrame(details, params); // This page contains a form with the same markup, but on a different // URL. observed.push_back(second_form); manager()->OnPasswordFormsParsed(observed); manager()->OnPasswordFormsRendered(observed); // Now submit this form params.password_form = second_form; manager()->DidNavigateAnyFrame(details, params); // Navigation after form submit. scoped_ptr<PasswordFormManager> form_to_save; EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)) .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save))); observed.clear(); manager()->OnPasswordFormsParsed(observed); manager()->OnPasswordFormsRendered(observed); // Make sure that the saved form matches the second form, not the first. ASSERT_TRUE(form_to_save.get()); EXPECT_CALL(*store_, AddLogin(FormMatches(second_form))); // Simulate saving the form, as if the info bar was accepted. form_to_save->Save(); } TEST_F(PasswordManagerTest, FormSubmitFailedLogin) { std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. manager()->ProvisionallySavePassword(form); // The form reappears, and is visible in the layout: // No expected calls to the PasswordStore... manager()->OnPasswordFormsParsed(observed); manager()->OnPasswordFormsRendered(observed); } TEST_F(PasswordManagerTest, FormSubmitInvisibleLogin) { // Tests fix of issue 28911: if the login form reappears on the subsequent // page, but is invisible, it shouldn't count as a failed login. std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. manager()->ProvisionallySavePassword(form); // Expect info bar to appear: scoped_ptr<PasswordFormManager> form_to_save; EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)) .WillOnce(WithArg<0>(SaveToScopedPtr(&form_to_save))); // The form reappears, but is not visible in the layout: manager()->OnPasswordFormsParsed(observed); observed.clear(); manager()->OnPasswordFormsRendered(observed); ASSERT_TRUE(form_to_save.get()); EXPECT_CALL(*store_, AddLogin(FormMatches(form))); // Simulate saving the form. form_to_save->Save(); } TEST_F(PasswordManagerTest, InitiallyInvisibleForm) { // Make sure an invisible login form still gets autofilled. std::vector<PasswordForm*> result; PasswordForm* existing = new PasswordForm(MakeSimpleForm()); result.push_back(existing); EXPECT_CALL(delegate_, FillPasswordForm(_)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. observed.clear(); manager()->OnPasswordFormsRendered(observed); // The initial layout. manager()->OnPasswordFormsParsed(observed); // The post-navigation load. manager()->OnPasswordFormsRendered(observed); // The post-navigation layout. } TEST_F(PasswordManagerTest, SavingDependsOnManagerEnabledPreference) { // Test that saving passwords depends on the password manager enabled // preference. TestingPrefServiceSyncable* prefService = testing_profile_->GetTestingPrefService(); prefService->SetUserPref(prefs::kPasswordManagerEnabled, Value::CreateBooleanValue(true)); EXPECT_TRUE(manager()->IsSavingEnabled()); prefService->SetUserPref(prefs::kPasswordManagerEnabled, Value::CreateBooleanValue(false)); EXPECT_FALSE(manager()->IsSavingEnabled()); } TEST_F(PasswordManagerTest, FillPasswordsOnDisabledManager) { // Test fix for issue 158296: Passwords must be filled even if the password // manager is disabled. std::vector<PasswordForm*> result; PasswordForm* existing = new PasswordForm(MakeSimpleForm()); result.push_back(existing); TestingPrefServiceSyncable* prefService = testing_profile_->GetTestingPrefService(); prefService->SetUserPref(prefs::kPasswordManagerEnabled, Value::CreateBooleanValue(false)); EXPECT_CALL(delegate_, FillPasswordForm(_)); EXPECT_CALL(*store_, GetLogins(_, _)) .WillRepeatedly(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); observed.push_back(form); manager()->OnPasswordFormsParsed(observed); } TEST_F(PasswordManagerTest, FormNotSavedAutocompleteOff) { // Test password form with non-generated password will not be saved if // autocomplete=off. std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillOnce(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); form.password_autocomplete_set = false; observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. // And the form submit contract is to call ProvisionallySavePassword. manager()->ProvisionallySavePassword(form); // Password form should not be saved. EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)).Times(Exactly(0)); EXPECT_CALL(*store_, AddLogin(FormMatches(form))).Times(Exactly(0)); // Now the password manager waits for the navigation to complete. observed.clear(); manager()->OnPasswordFormsParsed(observed); // The post-navigation load. manager()->OnPasswordFormsRendered(observed); // The post-navigation layout. } TEST_F(PasswordManagerTest, GeneratedPasswordFormSavedAutocompleteOff) { // Test password form with generated password will still be saved if // autocomplete=off. std::vector<PasswordForm*> result; // Empty password store. EXPECT_CALL(delegate_, FillPasswordForm(_)).Times(Exactly(0)); EXPECT_CALL(*store_, GetLogins(_,_)) .WillOnce(DoAll(WithArg<1>(InvokeConsumer(result)), Return(1))); std::vector<PasswordForm> observed; PasswordForm form(MakeSimpleForm()); form.password_autocomplete_set = false; observed.push_back(form); manager()->OnPasswordFormsParsed(observed); // The initial load. manager()->OnPasswordFormsRendered(observed); // The initial layout. // Simulate the user generating the password and submitting the form. manager()->SetFormHasGeneratedPassword(form); manager()->ProvisionallySavePassword(form); // The user should not be presented with an infobar as they have already given // consent by using the generated password. The form should be saved once // navigation occurs. EXPECT_CALL(delegate_, AddSavePasswordInfoBarIfPermitted(_)).Times(Exactly(0)); EXPECT_CALL(*store_, AddLogin(FormMatches(form))); // Now the password manager waits for the navigation to complete. observed.clear(); manager()->OnPasswordFormsParsed(observed); // The post-navigation load. manager()->OnPasswordFormsRendered(observed); // The post-navigation layout. }
{ "content_hash": "96bc8332744a34a450a1b83801f1af31", "timestamp": "", "source": "github", "line_count": 467, "max_line_length": 80, "avg_line_length": 41.04710920770878, "alnum_prop": 0.7306067087485002, "repo_name": "loopCM/chromium", "id": "661d34fc7f3c9e87c52af9d32963f5e58331d0ad", "size": "20298", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "chrome/browser/password_manager/password_manager_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
require 'date' require 'ffaker' require 'common/validation_error_tools' FactoryBot.define do trait :common_meeting_team_score_fields do rank { ((rand * 100) % 25).to_i + 1 } sum_individual_points { (rand * 1000).to_i } sum_relay_points { (rand * 1000).to_i } sum_team_points { (rand * 1000).to_i } meeting_individual_points { (rand * 1000).to_i } meeting_relay_points { (rand * 1000).to_i } meeting_team_points { (rand * 1000).to_i } season_individual_points { (rand * 1000).to_i } season_relay_points { (rand * 1000).to_i } season_team_points { (rand * 1000).to_i } user end #-- ------------------------------------------------------------------------- #++ factory :meeting_team_score do team_affiliation team { team_affiliation.team } season { team_affiliation.season } meeting { create(:meeting, season: season) } common_meeting_team_score_fields before(:create) do |built_instance| if built_instance.invalid? puts "\r\nFactory def. error => " << ValidationErrorTools.recursive_error_for(built_instance) puts built_instance.inspect end end factory :meeting_team_score_with_relay_results do after(:create) do |created_instance, _evaluator| ms = create(:meeting_session, meeting: created_instance.meeting) me = create(:meeting_event_relay, meeting_session: ms) mps = create_list( :meeting_program_relay, ((rand * 3) % 2).to_i + 1, meeting_event: me ) mps.each do |mp| create_list( :meeting_relay_result, ((rand * 3) % 2).to_i + 1, meeting_program: mp, team: created_instance.team, team_affiliation: created_instance.team_affiliation ) end end end end #-- ------------------------------------------------------------------------- #++ end
{ "content_hash": "b90918b72ead58e38c4ba331f07bad08", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 101, "avg_line_length": 34.43333333333333, "alnum_prop": 0.515972894482091, "repo_name": "steveoro/goggles_core", "id": "c96ec32110f1fa814e90c15f8230c89b052b9078", "size": "2097", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/factories/meeting_team_score.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "674" }, { "name": "HTML", "bytes": "3787" }, { "name": "JavaScript", "bytes": "1252" }, { "name": "Ruby", "bytes": "2366031" }, { "name": "Shell", "bytes": "30" } ], "symlink_target": "" }
namespace _04_AnonymousCache { using System; using System.Collections.Generic; using System.Linq; public class StartUp { public static void Main() { var allDataSetsNames = new List<string>(); var allDataSetValues = new Dictionary<string,Dictionary<string,long>>(); string input; while ((input = Console.ReadLine()) != "thetinggoesskrra") { var inputArgs = input.Split(new string[] { " -> " }, StringSplitOptions.RemoveEmptyEntries); if (inputArgs.Length==1) { if (!allDataSetsNames.Contains(input)) { allDataSetsNames.Add(input); } } else { var secondPart = inputArgs[1].Split(new string[] { " | " }, StringSplitOptions.RemoveEmptyEntries); var dataKey = inputArgs[0]; var dataSize = long.Parse(secondPart[0]); var dataSet = secondPart[1]; if (allDataSetValues.ContainsKey(dataSet)) { allDataSetValues[dataSet].Add(dataKey, dataSize); } else { allDataSetValues[dataSet] = new Dictionary<string, long>(); allDataSetValues[dataSet].Add(dataKey, dataSize); } } } var finalColection = allDataSetValues.Where(x => allDataSetsNames.Contains(x.Key)).ToDictionary(x=>x.Key,x=>x.Value); foreach (var item in finalColection.OrderByDescending(x=>x.Value.Values.Sum())) { Console.WriteLine($"Data Set: {item.Key}, Total Size: {item.Value.Values.Sum()}"); foreach (var key in item.Value) { Console.WriteLine($"$.{key.Key}"); } break; } } } }
{ "content_hash": "5340ff00cd13ee517d312a9b070c8af8", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 129, "avg_line_length": 33.645161290322584, "alnum_prop": 0.46931927133269413, "repo_name": "MrPIvanov/SoftUni", "id": "fedc40bad35b8122e73259cac4f7078c60e947da", "size": "2088", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "02-Progr Fundamentals/30-Exam/30-PracticalExam/04-AnonymousCache/StartUp.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "108" }, { "name": "Batchfile", "bytes": "3626" }, { "name": "C#", "bytes": "4493116" }, { "name": "CSS", "bytes": "5970658" }, { "name": "Dockerfile", "bytes": "576" }, { "name": "HTML", "bytes": "7383994" }, { "name": "Hack", "bytes": "5211" }, { "name": "Java", "bytes": "16968" }, { "name": "JavaScript", "bytes": "3319467" }, { "name": "PHP", "bytes": "14435" }, { "name": "PLSQL", "bytes": "583827" }, { "name": "PLpgSQL", "bytes": "16958" }, { "name": "Ruby", "bytes": "5904" }, { "name": "TSQL", "bytes": "2034451" } ], "symlink_target": "" }
export const STYLE_SWITCHES = { accent: 'mdc-linear-progress--accent' } export const LP_CLASS = 'mdc-linear-progress' export const BUF_DOTS_CLASS = 'mdc-linear-progress__buffering-dots' export const BUF_CLASS = 'mdc-linear-progress__buffer' export const BAR_CLASS = 'mdc-linear-progress__bar' export const PRIMARY_CLASS = 'mdc-linear-progress__primary-bar' export const SECONDARY_CLASS = 'mdc-linear-progress__secondary-bar' export const INNER_CLASS = 'mdc-linear-progress__bar-inner'
{ "content_hash": "7341b0e1012ead570d76376fad99a5c1", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 71, "avg_line_length": 32.8, "alnum_prop": 0.7560975609756098, "repo_name": "lopsch/snabbdom-material-components", "id": "0ae8ea6392684a2c21b2627afa92315acf292e83", "size": "492", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/linear-progress/styles.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "60230" } ], "symlink_target": "" }
<!-- HTML header for doxygen 1.8.9.1--> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>Lums: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="stylesheet.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Lums </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li class="current"><a href="functions.html#index_a"><span>a</span></a></li> <li><a href="functions_b.html#index_b"><span>b</span></a></li> <li><a href="functions_c.html#index_c"><span>c</span></a></li> <li><a href="functions_d.html#index_d"><span>d</span></a></li> <li><a href="functions_e.html#index_e"><span>e</span></a></li> <li><a href="functions_f.html#index_f"><span>f</span></a></li> <li><a href="functions_g.html#index_g"><span>g</span></a></li> <li><a href="functions_h.html#index_h"><span>h</span></a></li> <li><a href="functions_i.html#index_i"><span>i</span></a></li> <li><a href="functions_k.html#index_k"><span>k</span></a></li> <li><a href="functions_l.html#index_l"><span>l</span></a></li> <li><a href="functions_m.html#index_m"><span>m</span></a></li> <li><a href="functions_o.html#index_o"><span>o</span></a></li> <li><a href="functions_p.html#index_p"><span>p</span></a></li> <li><a href="functions_r.html#index_r"><span>r</span></a></li> <li><a href="functions_s.html#index_s"><span>s</span></a></li> <li><a href="functions_t.html#index_t"><span>t</span></a></li> <li><a href="functions_u.html#index_u"><span>u</span></a></li> <li><a href="functions_v.html#index_v"><span>v</span></a></li> <li><a href="functions_w.html#index_w"><span>w</span></a></li> <li><a href="functions_x.html#index_x"><span>x</span></a></li> <li><a href="functions_y.html#index_y"><span>y</span></a></li> <li><a href="functions_~.html#index_~"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div> <h3><a class="anchor" id="index_a"></a>- a -</h3><ul> <li>advance : <a class="el" href="structlm_1_1_glyph.html#a9be7c603b96310775fd575a7aa72b71d">lm::Glyph</a> </li> <li>Angle() : <a class="el" href="classlm_1_1_angle.html#a5128c164b47782001ec59ee549c925b8">lm::Angle</a> </li> <li>append() : <a class="el" href="classlm_1_1_shader_pipeline.html#ae51f0a50859ab30b849b43e444b6b9a2">lm::ShaderPipeline</a> </li> <li>atlas() : <a class="el" href="classlm_1_1_sprite.html#a2e03615ff467524b10ea476816d99003">lm::Sprite</a> , <a class="el" href="classlm_1_1_texture.html#a5eeb6175e0d38870aac74f85d1eb6bf5">lm::Texture</a> </li> <li>attach() : <a class="el" href="classlm_1_1_game_object.html#a00ea48a39b06fdbc49c113285bdbcac1">lm::GameObject&lt; Derived, ComponentType &gt;</a> , <a class="el" href="classlm_1_1_shader_program.html#a1e3620e5bfa37edb9b79941a02bf5d39">lm::ShaderProgram</a> </li> </ul> </div><!-- contents --> <!-- HTML footer for doxygen 1.8.9.1--> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> </small></address> </body> </html>
{ "content_hash": "5b7a5e675c5a876662e99f6c1acfa274", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 154, "avg_line_length": 45.63576158940398, "alnum_prop": 0.6306776955449137, "repo_name": "flhorizon/Lums", "id": "87582bb74e6b76e429e49fd14c2c937bc1758caa", "size": "6891", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/functions.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1322779" }, { "name": "C++", "bytes": "421318" }, { "name": "CMake", "bytes": "8630" }, { "name": "CSS", "bytes": "2101" }, { "name": "GLSL", "bytes": "4165" }, { "name": "HTML", "bytes": "2367" }, { "name": "Objective-C++", "bytes": "17817" }, { "name": "Ruby", "bytes": "15057" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- --> <mapping strict="1"> <fields> <title> <selector>[name$="[title]"]</selector> <strategy>css selector</strategy> </title> <type> <selector>[name$='[type]']</selector> <strategy>css selector</strategy> <input>select</input> </type> <required> <selector>[name$="[required]"]</selector> <strategy>css selector</strategy> <input>select</input> </required> <position> <selector>[name$='[position]']</selector> <strategy>css selector</strategy> </position> </fields> </mapping>
{ "content_hash": "2ea1b04491cd9b2d88c8bfaa000e6067", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 53, "avg_line_length": 26.692307692307693, "alnum_prop": 0.4899135446685879, "repo_name": "fabiensebban/magento", "id": "e04b2e6185970db3dadd60e5e5b8d26cf7038e47", "size": "1653", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dev/tests/functional/tests/app/Mage/Bundle/Test/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "20063" }, { "name": "ApacheConf", "bytes": "8150" }, { "name": "Batchfile", "bytes": "1036" }, { "name": "CSS", "bytes": "1781578" }, { "name": "HTML", "bytes": "5498183" }, { "name": "JavaScript", "bytes": "1292137" }, { "name": "PHP", "bytes": "48139973" }, { "name": "PowerShell", "bytes": "1028" }, { "name": "Ruby", "bytes": "288" }, { "name": "Shell", "bytes": "3879" }, { "name": "XSLT", "bytes": "2135" } ], "symlink_target": "" }
Contributors to Friendly ======================== * James Golick - http://jamesgolick.com (github: jamesgolick) * Jonathan Palardy - http://technotales.wordpress.com (github: jpalardy) * Jeff Rafter - http://socialorange.com (github: jeffrafter) * Scott Fleckenstein - http://nullstyle.com (github: nullstyle)
{ "content_hash": "686faf1e2a393268d163169f03cad16c", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 77, "avg_line_length": 48.285714285714285, "alnum_prop": 0.6420118343195266, "repo_name": "jamesgolick/friendly", "id": "bf3590d387c3fcd1d1e767ab032aa7cb7e2e7415", "size": "338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CONTRIBUTORS.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "48397" }, { "name": "Ruby", "bytes": "139582" } ], "symlink_target": "" }
use remove_dir_all::remove_dir_all; use std::fs::{self, File}; macro_rules! assert_not_found { ($path:expr) => {{ match fs::metadata($path) { Ok(_) => panic!("did not expect to retrieve metadata for {}", $path), Err(ref err) if err.kind() != ::std::io::ErrorKind::NotFound => { panic!("expected path {} to be NotFound, was {:?}", $path, err) } _ => {} } }}; } #[test] fn removes_empty() { fs::create_dir_all("./empty").unwrap(); assert!(fs::metadata("./empty").unwrap().is_dir()); remove_dir_all("./empty").unwrap(); assert_not_found!("./empty"); } #[test] fn removes_files() { fs::create_dir_all("./files").unwrap(); for i in 0..5 { let path = format!("./files/empty-{}.txt", i); { let mut _file = File::create(&path); } assert!(fs::metadata(&path).unwrap().is_file()); } remove_dir_all("./files").unwrap(); assert_not_found!("./files"); } #[test] fn removes_dirs() { for i in 0..5 { let path = format!("./dirs/{}/subdir", i); fs::create_dir_all(&path).unwrap(); assert!(fs::metadata(&path).unwrap().is_dir()); } remove_dir_all("./dirs").unwrap(); assert_not_found!("./dirs"); } #[test] fn removes_read_only() { env_logger::init(); for i in 0..5 { let path = format!("./readonly/{}/subdir", i); fs::create_dir_all(&path).unwrap(); let file_path = format!("{}/file.txt", path); { let file = File::create(&file_path).unwrap(); if i % 2 == 0 { let metadata = file.metadata().unwrap(); let mut permissions = metadata.permissions(); permissions.set_readonly(true); fs::set_permissions(&file_path, permissions).unwrap(); } } assert_eq!( i % 2 == 0, fs::metadata(&file_path).unwrap().permissions().readonly() ); if i % 2 == 1 { let metadata = fs::metadata(&path).unwrap(); let mut permissions = metadata.permissions(); permissions.set_readonly(true); fs::set_permissions(&path, permissions).unwrap(); assert!(fs::metadata(&path).unwrap().permissions().readonly()); } } remove_dir_all("./readonly").unwrap(); assert_not_found!("./readonly"); } // TODO: Should probably test readonly hard links...
{ "content_hash": "09ad520d72cf29085112e759cbe47adc", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 81, "avg_line_length": 25.232323232323232, "alnum_prop": 0.5064051240992794, "repo_name": "XAMPPRocky/remove_dir_all", "id": "264ff0e1414b6197a646a4289ff38ddf259aabce", "size": "2515", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/windows.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "14996" } ], "symlink_target": "" }
import {Component, OnInit} from "angular2/core"; import {WidgetComponent} from "../generic-component/widget/widget.component"; import {WidgetHeaderComponent} from "../generic-component/widget-header/widget-header.component"; import {WidgetBodyComponent} from "../generic-component/widget-body/widget-body.component"; import {LoadingComponent} from "../generic-component/loading/loading.component"; import {ServerListViewComponent} from "../list-view/server-list-view/server-list-view.component"; import {ServerListService} from "../service/servers_list.service"; @Component({ selector: 'my-tables', templateUrl: 'app/dev/4-AngularTheme/tables/tables.tpl.html', directives: [WidgetComponent, WidgetHeaderComponent, WidgetBodyComponent, LoadingComponent, ServerListViewComponent] }) export class TablesComponent implements OnInit { servers: any[]; constructor( private _serverListService: ServerListService ) { } ngOnInit():any { this.servers = this._serverListService.getAllServers(); } }
{ "content_hash": "aafb19963e24356bbc43f10dbab97d37", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 120, "avg_line_length": 41.56, "alnum_prop": 0.7564966313763234, "repo_name": "trewpog/AngularDev", "id": "4590a77f7986d31fc60a741068f2b19d2038aede", "size": "1039", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/dev/4-AngularTheme/tables/tables.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12639" }, { "name": "HTML", "bytes": "28429" }, { "name": "JavaScript", "bytes": "13246" }, { "name": "TypeScript", "bytes": "48246" } ], "symlink_target": "" }
<ng-include src="'templates/sidebar.html'"></ng-include> <div class="welcome"> <h1>Welcome to Bloc Chat</h1> <h3>Where Community begins</h3> </div>
{ "content_hash": "acbef27d21b646c1939d13db51126ef5", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 56, "avg_line_length": 31, "alnum_prop": 0.6709677419354839, "repo_name": "dwaite498/second-bloc-chat", "id": "b3f625220390b40c91ddb4258b8277201adb2f86", "size": "155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/templates/room.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "492" }, { "name": "HTML", "bytes": "6102" }, { "name": "JavaScript", "bytes": "11430" } ], "symlink_target": "" }
package com.avsystem.commons package jsiop trait JsInterop object JsInterop extends JsInterop
{ "content_hash": "c3728850fed48f5e36d0115801fc8982", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 34, "avg_line_length": 19, "alnum_prop": 0.8631578947368421, "repo_name": "AVSystem/scala-commons", "id": "cc258d4b13755f0f67ede13a87a4f80fb9a8c02c", "size": "95", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "commons-core/jvm/src/main/scala/com/avsystem/commons/jsiop/JsInterop.scala", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "328" }, { "name": "Scala", "bytes": "2072517" }, { "name": "Shell", "bytes": "302" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Chung-kuo Ti Chen-chun, [Fungi of China] 107 (1964) #### Original name Trametes circinatus Fr. ### Remarks null
{ "content_hash": "9c8b4a601e2e826efe8388d071734e1c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 51, "avg_line_length": 15.307692307692308, "alnum_prop": 0.7085427135678392, "repo_name": "mdoering/backbone", "id": "9bc829a57918466d0fd325371a66866660e9867d", "size": "259", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Hymenochaetales/Hymenochaetaceae/Onnia/Onnia circinata/ Syn. Inonotus circinatus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@interface BOXFileCommentsRequest () - (NSArray *)commentsFromJSONDictionary:(NSDictionary *)JSONDictionary; @end @interface BOXFileCommentsRequestTests : BOXRequestTestCase @end @implementation BOXFileCommentsRequestTests #pragma mark - create URL - (void)test_request_has_correct_url { NSString *fileID = @"12345"; BOXFileCommentsRequest *request = [[BOXFileCommentsRequest alloc] initWithFileID:fileID]; NSURL *expectedURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@/files/%@/comments", BOXAPIBaseURL, BOXAPIVersion, fileID]]; XCTAssertEqualObjects(expectedURL, request.urlRequest.URL); XCTAssertEqualObjects(BOXAPIHTTPMethodGET, request.urlRequest.HTTPMethod); } - (void)test_shared_link_properties { NSString *fileID = @"123"; BOXFileCommentsRequest *request = [[BOXFileCommentsRequest alloc] initWithFileID:fileID]; XCTAssertEqualObjects([request itemIDForSharedLink], fileID); XCTAssertEqualObjects([request itemTypeForSharedLink], BOXAPIItemTypeFile); } #pragma mark - Perform the request - (void)test_request_returns_expected_comments { NSString *fileID = @"1234567"; BOXFileCommentsRequest *request = [[BOXFileCommentsRequest alloc] initWithFileID:fileID]; NSData *cannedData = [self cannedResponseDataWithName:@"get_comments"]; NSHTTPURLResponse *response = [self cannedURLResponseWithStatusCode:200 responseData:cannedData]; NSDictionary *expectedResults = [NSJSONSerialization JSONObjectWithData:cannedData options:kNilOptions error:nil]; NSArray *expectedComments = [request commentsFromJSONDictionary:expectedResults]; [self setCannedURLResponse:response cannedResponseData:cannedData forRequest:request]; XCTestExpectation *expectation = [self expectationWithDescription:@"expectation"]; [request performRequestWithCompletion:^(NSArray *objects, NSError *error) { XCTAssertNil(error); XCTAssertEqual(objects.count, expectedComments.count); for (NSUInteger i = 0; i < objects.count ; i++) { [self assertModel:objects[i] isEquivalentTo:expectedComments[i]]; } [expectation fulfill]; }]; [self waitForExpectationsWithTimeout:2.0 handler:nil]; } @end
{ "content_hash": "4a38f4b470b99d3fc45252b1b58cb2ea", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 140, "avg_line_length": 34.223880597014926, "alnum_prop": 0.7378979502834714, "repo_name": "irvingruan/box-ios-content-sdk", "id": "7e2e1a679e82114ad1c29efa45b73020e1393075", "size": "2539", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "BoxContentSDK/BoxContentSDKTests/BOXFileCommentsRequestTests.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1023" }, { "name": "Objective-C", "bytes": "1242340" }, { "name": "Ruby", "bytes": "3046" } ], "symlink_target": "" }
"""Implements jaccard metric computing routines.""" def compute_one_jaccard_distance(arg): """Computes a distance between a pair of clusters. Args: arg: ComputeDistanceArg instance. Returns: 3-tuple (a_id, b_id, distance). """ distance = jaccard_distance(set(arg.tags_a), set(arg.tags_b)) return (arg.shred_a_id, arg.shred_b_id, distance) def jaccard_distance(tags_a, tags_b): """ 0 <= J <= 1 0 - tags_a & tags_a sets are equal 1 - tags_a have nothing in common with tags_b See http://en.wikipedia.org/wiki/Jaccard_index for details """ return 1 - len(tags_a.intersection(tags_b)) / len(tags_a.union(tags_b))
{ "content_hash": "d6e8c8c16db244ef053c281f22501ba7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 75, "avg_line_length": 28.458333333333332, "alnum_prop": 0.6383601756954612, "repo_name": "dchaplinsky/unshred-tag", "id": "b8af54cc9a072e76109a7c8d05bee8b9fc994d2d", "size": "683", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "metrics/jaccard.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10799" }, { "name": "HTML", "bytes": "32197" }, { "name": "JavaScript", "bytes": "37015" }, { "name": "Python", "bytes": "76506" } ], "symlink_target": "" }
package org.apache.pulsar.client.impl; import static org.apache.pulsar.client.impl.UnAckedMessageTracker.addChunkedMessageIdsAndRemoveFromSequenceMap; import com.google.common.annotations.VisibleForTesting; import io.netty.util.Timeout; import io.netty.util.Timer; import java.io.Closeable; import java.util.HashMap; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.client.api.RedeliveryBackoff; import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData; class NegativeAcksTracker implements Closeable { private HashMap<MessageId, Long> nackedMessages = null; private final ConsumerBase<?> consumer; private final Timer timer; private final long nackDelayNanos; private final long timerIntervalNanos; private final RedeliveryBackoff negativeAckRedeliveryBackoff; private Timeout timeout; // Set a min delay to allow for grouping nacks within a single batch private static final long MIN_NACK_DELAY_NANOS = TimeUnit.MILLISECONDS.toNanos(100); public NegativeAcksTracker(ConsumerBase<?> consumer, ConsumerConfigurationData<?> conf) { this.consumer = consumer; this.timer = consumer.getClient().timer(); this.nackDelayNanos = Math.max(TimeUnit.MICROSECONDS.toNanos(conf.getNegativeAckRedeliveryDelayMicros()), MIN_NACK_DELAY_NANOS); this.negativeAckRedeliveryBackoff = conf.getNegativeAckRedeliveryBackoff(); if (negativeAckRedeliveryBackoff != null) { this.timerIntervalNanos = Math.max( TimeUnit.MILLISECONDS.toNanos(negativeAckRedeliveryBackoff.next(0)), MIN_NACK_DELAY_NANOS) / 3; } else { this.timerIntervalNanos = nackDelayNanos / 3; } } private synchronized void triggerRedelivery(Timeout t) { if (nackedMessages.isEmpty()) { this.timeout = null; return; } // Group all the nacked messages into one single re-delivery request Set<MessageId> messagesToRedeliver = new HashSet<>(); long now = System.nanoTime(); nackedMessages.forEach((msgId, timestamp) -> { if (timestamp < now) { addChunkedMessageIdsAndRemoveFromSequenceMap(msgId, messagesToRedeliver, this.consumer); messagesToRedeliver.add(msgId); } }); messagesToRedeliver.forEach(nackedMessages::remove); consumer.onNegativeAcksSend(messagesToRedeliver); consumer.redeliverUnacknowledgedMessages(messagesToRedeliver); this.timeout = timer.newTimeout(this::triggerRedelivery, timerIntervalNanos, TimeUnit.NANOSECONDS); } public synchronized void add(MessageId messageId) { add(messageId, 0); } public synchronized void add(Message<?> message) { add(message.getMessageId(), message.getRedeliveryCount()); } private synchronized void add(MessageId messageId, int redeliveryCount) { if (messageId instanceof TopicMessageIdImpl) { TopicMessageIdImpl topicMessageId = (TopicMessageIdImpl) messageId; messageId = topicMessageId.getInnerMessageId(); } if (messageId instanceof BatchMessageIdImpl) { BatchMessageIdImpl batchMessageId = (BatchMessageIdImpl) messageId; messageId = new MessageIdImpl(batchMessageId.getLedgerId(), batchMessageId.getEntryId(), batchMessageId.getPartitionIndex()); } if (nackedMessages == null) { nackedMessages = new HashMap<>(); } long backoffNs; if (negativeAckRedeliveryBackoff != null) { backoffNs = TimeUnit.MILLISECONDS.toNanos(negativeAckRedeliveryBackoff.next(redeliveryCount)); } else { backoffNs = nackDelayNanos; } nackedMessages.put(messageId, System.nanoTime() + backoffNs); if (this.timeout == null) { // Schedule a task and group all the redeliveries for same period. Leave a small buffer to allow for // nack immediately following the current one will be batched into the same redeliver request. this.timeout = timer.newTimeout(this::triggerRedelivery, timerIntervalNanos, TimeUnit.NANOSECONDS); } } @VisibleForTesting Optional<Integer> getNackedMessagesCount() { return Optional.ofNullable(nackedMessages).map(HashMap::size); } @Override public synchronized void close() { if (timeout != null && !timeout.isCancelled()) { timeout.cancel(); timeout = null; } if (nackedMessages != null) { nackedMessages.clear(); nackedMessages = null; } } }
{ "content_hash": "e9365fd03799955b7da28eb347fef1ee", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 113, "avg_line_length": 38.3046875, "alnum_prop": 0.6806037120130533, "repo_name": "merlimat/pulsar", "id": "86121dd2c34c7dedc994381d1a26f8a572d9b42c", "size": "5711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pulsar-client/src/main/java/org/apache/pulsar/client/impl/NegativeAcksTracker.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15099" }, { "name": "Dockerfile", "bytes": "20167" }, { "name": "Go", "bytes": "117008" }, { "name": "HCL", "bytes": "14529" }, { "name": "HTML", "bytes": "822" }, { "name": "Java", "bytes": "31398615" }, { "name": "JavaScript", "bytes": "1385" }, { "name": "Lua", "bytes": "5454" }, { "name": "Python", "bytes": "243009" }, { "name": "Shell", "bytes": "159739" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- --> <resources> <dimen name="default_key_height">50dip</dimen> <dimen name="default_key_half_height">38dip</dimen> <dimen name="default_key_tall_height">62dip</dimen> <dimen name="default_key_horizontal_gap">2dp</dimen> <dimen name="key_text_size">24sp</dimen> <dimen name="key_label_text_size">17sp</dimen> </resources>
{ "content_hash": "8748302c9323a3dd2b69fe2c13c33d90", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 56, "avg_line_length": 26.733333333333334, "alnum_prop": 0.6433915211970075, "repo_name": "AnySoftKeyboard/AnySoftKeyboard", "id": "0b5ae0f8ab96aad3038e8ac4e2a64f92be662a5e", "size": "1011", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "addons/themes/three_d/pack/src/main/res/values-large/dimens.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2631" }, { "name": "C", "bytes": "36897" }, { "name": "C++", "bytes": "196172" }, { "name": "Dockerfile", "bytes": "30" }, { "name": "Groovy", "bytes": "1692" }, { "name": "HTML", "bytes": "528564" }, { "name": "Java", "bytes": "3559273" }, { "name": "Kotlin", "bytes": "29619" }, { "name": "Makefile", "bytes": "723" }, { "name": "Python", "bytes": "2623" }, { "name": "Shell", "bytes": "30772" } ], "symlink_target": "" }
layout: article title: "PAZUR XVII" categories: archiwum date: 2016-05-17 modified: 2016-05-23 tags: [pazur] comments: false image: feature: teaser: thumb: ads: false --- 17 maja 2016 roku na Uniwersytecie Ekonomicznym w Poznaniu odbył się XVII Poznański Akademicki Zlot Użytkowników R. Na spotkaniu zostały wygłoszone następujące referaty: 1. Integracja MS SQL Server z R - Łukasz Grala (Tidk) Opis: *W tym roku ma premierę najnowsza wersja SQL Server 2016, nie jest to tylko serwer bazodanowy a raczej zaawansowana platforma danych. Do zestawu rozwiązań do budowania modeli analitycznych, serwera raportowania, mechanizmów integracji, czy też czyszczenia danych i wielu innych dołączył w tej edycji język R. Nie w formie kolejnego narzędzia, a integracji wraz z SQL Server. Oczywiście jeżeli analityk przyzwyczajony jest do pracy z językiem R w swoim narzędziu jest taka możliwość, ale bardzo ciekawą rzeczą jest możliwość wykorzystywania skryptów języka R w obiektach programowalnych w języku TSQL, co może dać nowe możliwości serwera, czy też Reporting Services w zakresie zaawansowanej analizy danych. W czasie sesji zobaczymy na żywo jak to działa i jak przykładowo można siłę tej integracji wykorzystywać.* R Services w SQL Server 2016 przedstawi architekt i wieloletni Microsoft Data Platform MVP – Łukasz Grala 2. Interoperacyjność R z C# i Knime - Grzegorz Melniczak (Analyx)
{ "content_hash": "71521bc6992e87d4599b01eb60168d67", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 818, "avg_line_length": 60.78260869565217, "alnum_prop": 0.8082975679542204, "repo_name": "PoznanUseR/PoznanUseR.github.io", "id": "9aa3d38c2ad8bedd698d58c00cb0e2d0b4fffceb", "size": "1454", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/archiwum/2016-05-19-pazur-17.md", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "3274" }, { "name": "CSS", "bytes": "63101" }, { "name": "HTML", "bytes": "7399188" }, { "name": "JavaScript", "bytes": "9317" }, { "name": "R", "bytes": "33525" }, { "name": "Ruby", "bytes": "2354" } ], "symlink_target": "" }
from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) import sys import os from restclient.restclient import RestClient, RestError from pprint import pprint def main(): # This allows us to use a plain HTTP callback os.environ['DEBUG'] = "1" rc = RestClient(ssl_verify=False) try: result = rc.get("https://localhost:9090/api/test") pprint(result) result = rc.post("https://localhost:9091/api/info", payload=result) pprint(result) except RestError as e: print e.value except Exception as e: print e if __name__ == '__main__': main()
{ "content_hash": "cb80f10b49922de82c9f45cf228d6d96", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 69, "avg_line_length": 19.933333333333334, "alnum_prop": 0.7023411371237458, "repo_name": "bboortz/ost-test-webapp", "id": "a3b83cff772e514529ec45ce6a5d96ef688ce0f8", "size": "621", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "msa-test-job/skeleton.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "19912" }, { "name": "Shell", "bytes": "369" } ], "symlink_target": "" }
using base::TimeDelta; using base::TimeTicks; namespace net { ProxyList::ProxyList() = default; ProxyList::ProxyList(const ProxyList& other) = default; ProxyList::~ProxyList() = default; void ProxyList::Set(const std::string& proxy_uri_list) { proxies_.clear(); base::StringTokenizer str_tok(proxy_uri_list, ";"); while (str_tok.GetNext()) { ProxyServer uri = ProxyServer::FromURI(str_tok.token_piece(), ProxyServer::SCHEME_HTTP); // Silently discard malformed inputs. if (uri.is_valid()) proxies_.push_back(uri); } } void ProxyList::SetSingleProxyServer(const ProxyServer& proxy_server) { proxies_.clear(); AddProxyServer(proxy_server); } void ProxyList::AddProxyServer(const ProxyServer& proxy_server) { if (proxy_server.is_valid()) proxies_.push_back(proxy_server); } void ProxyList::DeprioritizeBadProxies( const ProxyRetryInfoMap& proxy_retry_info) { // Partition the proxy list in two: // (1) the known bad proxies // (2) everything else std::vector<ProxyServer> good_proxies; std::vector<ProxyServer> bad_proxies_to_try; std::vector<ProxyServer>::const_iterator iter = proxies_.begin(); for (; iter != proxies_.end(); ++iter) { auto bad_proxy = proxy_retry_info.find(iter->ToURI()); if (bad_proxy != proxy_retry_info.end()) { // This proxy is bad. Check if it's time to retry. if (bad_proxy->second.bad_until >= TimeTicks::Now()) { // still invalid. if (bad_proxy->second.try_while_bad) bad_proxies_to_try.push_back(*iter); continue; } } good_proxies.push_back(*iter); } // "proxies_ = good_proxies + bad_proxies" proxies_.swap(good_proxies); proxies_.insert(proxies_.end(), bad_proxies_to_try.begin(), bad_proxies_to_try.end()); } void ProxyList::RemoveProxiesWithoutScheme(int scheme_bit_field) { for (auto it = proxies_.begin(); it != proxies_.end();) { if (!(scheme_bit_field & it->scheme())) { it = proxies_.erase(it); continue; } ++it; } } void ProxyList::Clear() { proxies_.clear(); } bool ProxyList::IsEmpty() const { return proxies_.empty(); } size_t ProxyList::size() const { return proxies_.size(); } // Returns true if |*this| lists the same proxies as |other|. bool ProxyList::Equals(const ProxyList& other) const { if (size() != other.size()) return false; return proxies_ == other.proxies_; } const ProxyServer& ProxyList::Get() const { DCHECK(!proxies_.empty()); return proxies_[0]; } const std::vector<ProxyServer>& ProxyList::GetAll() const { return proxies_; } void ProxyList::SetFromPacString(const std::string& pac_string) { base::StringTokenizer entry_tok(pac_string, ";"); proxies_.clear(); while (entry_tok.GetNext()) { ProxyServer uri = ProxyServer::FromPacString(entry_tok.token_piece()); // Silently discard malformed inputs. if (uri.is_valid()) proxies_.push_back(uri); } // If we failed to parse anything from the PAC results list, fallback to // DIRECT (this basically means an error in the PAC script). if (proxies_.empty()) { proxies_.push_back(ProxyServer::Direct()); } } std::string ProxyList::ToPacString() const { std::string proxy_list; auto iter = proxies_.begin(); for (; iter != proxies_.end(); ++iter) { if (!proxy_list.empty()) proxy_list += ";"; proxy_list += iter->ToPacString(); } return proxy_list.empty() ? std::string() : proxy_list; } std::unique_ptr<base::ListValue> ProxyList::ToValue() const { std::unique_ptr<base::ListValue> list(new base::ListValue()); for (size_t i = 0; i < proxies_.size(); ++i) list->AppendString(proxies_[i].ToURI()); return list; } bool ProxyList::Fallback(ProxyRetryInfoMap* proxy_retry_info, int net_error, const NetLogWithSource& net_log) { if (proxies_.empty()) { NOTREACHED(); return false; } // By default, proxies are not retried for 5 minutes. UpdateRetryInfoOnFallback(proxy_retry_info, TimeDelta::FromMinutes(5), true, std::vector<ProxyServer>(), net_error, net_log); // Remove this proxy from our list. proxies_.erase(proxies_.begin()); return !proxies_.empty(); } void ProxyList::AddProxyToRetryList(ProxyRetryInfoMap* proxy_retry_info, base::TimeDelta retry_delay, bool try_while_bad, const ProxyServer& proxy_to_retry, int net_error, const NetLogWithSource& net_log) const { // Mark this proxy as bad. TimeTicks bad_until = TimeTicks::Now() + retry_delay; std::string proxy_key = proxy_to_retry.ToURI(); auto iter = proxy_retry_info->find(proxy_key); if (iter == proxy_retry_info->end() || bad_until > iter->second.bad_until) { ProxyRetryInfo retry_info; retry_info.current_delay = retry_delay; retry_info.bad_until = bad_until; retry_info.try_while_bad = try_while_bad; retry_info.net_error = net_error; (*proxy_retry_info)[proxy_key] = retry_info; } net_log.AddEvent(NetLogEventType::PROXY_LIST_FALLBACK, NetLog::StringCallback("bad_proxy", &proxy_key)); } void ProxyList::UpdateRetryInfoOnFallback( ProxyRetryInfoMap* proxy_retry_info, base::TimeDelta retry_delay, bool reconsider, const std::vector<ProxyServer>& additional_proxies_to_bypass, int net_error, const NetLogWithSource& net_log) const { DCHECK(!retry_delay.is_zero()); if (proxies_.empty()) { NOTREACHED(); return; } if (!proxies_[0].is_direct()) { AddProxyToRetryList(proxy_retry_info, retry_delay, reconsider, proxies_[0], net_error, net_log); // If any additional proxies to bypass are specified, add to the retry map // as well. for (const ProxyServer& additional_proxy : additional_proxies_to_bypass) { AddProxyToRetryList(proxy_retry_info, retry_delay, reconsider, additional_proxy, net_error, net_log); } } } } // namespace net
{ "content_hash": "65b1fada8805c0c9c7052d4605a19727", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 78, "avg_line_length": 30.681372549019606, "alnum_prop": 0.623582041859722, "repo_name": "youtube/cobalt_sandbox", "id": "2c4ba1a2fd3250c36dfc05e7508638fa68699de0", "size": "6770", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "net/proxy_resolution/proxy_list.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <alpha xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator" android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="@android:integer/config_mediumAnimTime" />
{ "content_hash": "b307cc0e87c1de11c591380dc14875f8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 61, "avg_line_length": 39.714285714285715, "alnum_prop": 0.7553956834532374, "repo_name": "dgrlucky/Awesome", "id": "f6af70ef71d4d8e0fba07c185349020ccc2c8b57", "size": "278", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/src/main/res/Res-Animation/anim/fade_out_exit.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1709" }, { "name": "Java", "bytes": "2366511" }, { "name": "Kotlin", "bytes": "23462" } ], "symlink_target": "" }
// Copyright 2013 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 "chrome/browser/android/favicon_helper.h" #include <jni.h> #include <stddef.h> #include <vector> #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/android/compose_bitmaps_helper.h" #include "chrome/browser/favicon/favicon_service_factory.h" #include "chrome/browser/favicon/history_ui_favicon_request_handler_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_android.h" #include "chrome/browser/ui/android/favicon/jni_headers/FaviconHelper_jni.h" #include "components/favicon/core/favicon_service.h" #include "components/favicon/core/favicon_util.h" #include "components/favicon/core/history_ui_favicon_request_handler.h" #include "components/favicon_base/favicon_util.h" #include "content/public/browser/web_contents.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_rep.h" using base::android::JavaParamRef; using base::android::JavaRef; using base::android::ScopedJavaGlobalRef; using base::android::ScopedJavaLocalRef; using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF16; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; using JobFinishedCallback = base::OnceCallback<void(void)>; namespace { void OnEnsureIconIsAvailableFinished( const ScopedJavaGlobalRef<jobject>& j_availability_callback, bool newly_available) { JNIEnv* env = AttachCurrentThread(); Java_IconAvailabilityCallback_onIconAvailabilityChecked( env, j_availability_callback, newly_available); } } // namespace static jlong JNI_FaviconHelper_Init(JNIEnv* env) { return reinterpret_cast<intptr_t>(new FaviconHelper()); } // This is used by the FaviconHelper::GetComposedFaviconImageInternal, and it is // used to manage multiple FaviconService::GetRawFaviconForPageURL calls. The // number of calls is the size of the urls_. The Job is destroyed after the // number of calls have been reached, and the result_callback_ is finished. class FaviconHelper::Job { public: Job(FaviconHelper* favicon_helper, favicon::FaviconService* favicon_service, std::vector<std::string> urls, int desire_size_in_pixel, JobFinishedCallback job_finished_callback, favicon_base::FaviconResultsCallback result_callback); Job(const Job&) = delete; Job& operator=(const Job&) = delete; void Start(); private: void OnFaviconAvailable(int favicon_index, const favicon_base::FaviconRawBitmapResult& result); FaviconHelper* favicon_helper_; favicon::FaviconService* favicon_service_; std::vector<std::string> urls_; int desire_size_in_pixel_; JobFinishedCallback job_finished_callback_; favicon_base::FaviconResultsCallback result_callback_; int favicon_expected_count_; std::vector<favicon_base::FaviconRawBitmapResult> favicon_raw_bitmap_results_; int favicon_result_count_; base::WeakPtrFactory<Job> weak_ptr_factory_{this}; }; FaviconHelper::Job::Job(FaviconHelper* favicon_helper, favicon::FaviconService* favicon_service, std::vector<std::string> urls, int desire_size_in_pixel, JobFinishedCallback job_finished_callback, favicon_base::FaviconResultsCallback result_callback) : favicon_helper_(favicon_helper), favicon_service_(favicon_service), urls_(urls), desire_size_in_pixel_(desire_size_in_pixel), job_finished_callback_(std::move(job_finished_callback)), result_callback_(std::move(result_callback)), favicon_raw_bitmap_results_(4), favicon_result_count_(0) { favicon_expected_count_ = urls_.size(); } void FaviconHelper::Job::Start() { size_t urls_size = urls_.size(); DCHECK(urls_size > 1 && urls_size <= 4); if (urls_size <= 1 || urls_size > 4) return; for (size_t i = 0; i < urls_size; i++) { favicon_base::FaviconRawBitmapCallback callback = base::BindOnce(&FaviconHelper::Job::OnFaviconAvailable, weak_ptr_factory_.GetWeakPtr(), i); favicon_helper_->GetLocalFaviconImageForURLInternal( favicon_service_, GURL(urls_.at(i)), desire_size_in_pixel_, std::move(callback)); } } void FaviconHelper::Job::OnFaviconAvailable( int favicon_index, const favicon_base::FaviconRawBitmapResult& result) { DCHECK(favicon_index >= 0 && favicon_index < 4); if (result.is_valid()) { favicon_raw_bitmap_results_.at(favicon_index) = result; favicon_result_count_++; } else { favicon_expected_count_--; } if (favicon_result_count_ == favicon_expected_count_) { size_t i = 0; while (i < favicon_raw_bitmap_results_.size()) { if (!favicon_raw_bitmap_results_[i].is_valid()) { favicon_raw_bitmap_results_.erase(favicon_raw_bitmap_results_.begin() + i); continue; } i++; } std::move(result_callback_).Run(favicon_raw_bitmap_results_); std::move(job_finished_callback_).Run(); } } FaviconHelper::FaviconHelper() : last_used_job_id_(0) { cancelable_task_tracker_.reset(new base::CancelableTaskTracker()); } void FaviconHelper::Destroy(JNIEnv* env) { delete this; } jboolean FaviconHelper::GetComposedFaviconImage( JNIEnv* env, const base::android::JavaParamRef<jobject>& j_profile, const base::android::JavaParamRef<jobjectArray>& j_urls, jint j_desired_size_in_pixel, const base::android::JavaParamRef<jobject>& j_favicon_image_callback) { Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile); DCHECK(profile); if (!profile) return false; favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(profile, ServiceAccessType::EXPLICIT_ACCESS); DCHECK(favicon_service); if (!favicon_service) return false; int desired_size_in_pixel = static_cast<int>(j_desired_size_in_pixel); favicon_base::FaviconResultsCallback callback_runner = base::BindOnce(&FaviconHelper::OnFaviconBitmapResultsAvailable, weak_ptr_factory_.GetWeakPtr(), ScopedJavaGlobalRef<jobject>(j_favicon_image_callback), desired_size_in_pixel); std::vector<std::string> urls; base::android::AppendJavaStringArrayToStringVector(env, j_urls, &urls); GetComposedFaviconImageInternal(favicon_service, urls, static_cast<int>(j_desired_size_in_pixel), std::move(callback_runner)); return true; } void FaviconHelper::GetComposedFaviconImageInternal( favicon::FaviconService* favicon_service, std::vector<std::string> urls, int desired_size_in_pixel, favicon_base::FaviconResultsCallback callback_runner) { DCHECK(favicon_service); JobFinishedCallback job_finished_callback = base::BindOnce(&FaviconHelper::OnJobFinished, weak_ptr_factory_.GetWeakPtr(), ++last_used_job_id_); auto job = std::make_unique<Job>( this, favicon_service, urls, desired_size_in_pixel, std::move(job_finished_callback), std::move(callback_runner)); id_to_job_[last_used_job_id_] = std::move(job); id_to_job_[last_used_job_id_]->Start(); } void ::FaviconHelper::OnJobFinished(int job_id) { DCHECK(id_to_job_.count(job_id)); id_to_job_.erase(job_id); } jboolean FaviconHelper::GetLocalFaviconImageForURL( JNIEnv* env, const JavaParamRef<jobject>& j_profile, const JavaParamRef<jstring>& j_page_url, jint j_desired_size_in_pixel, const JavaParamRef<jobject>& j_favicon_image_callback) { Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile); DCHECK(profile); if (!profile) return false; favicon::FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(profile, ServiceAccessType::EXPLICIT_ACCESS); DCHECK(favicon_service); if (!favicon_service) return false; favicon_base::FaviconRawBitmapCallback callback_runner = base::BindOnce(&FaviconHelper::OnFaviconBitmapResultAvailable, weak_ptr_factory_.GetWeakPtr(), ScopedJavaGlobalRef<jobject>(j_favicon_image_callback)); GetLocalFaviconImageForURLInternal( favicon_service, GURL(ConvertJavaStringToUTF16(env, j_page_url)), static_cast<int>(j_desired_size_in_pixel), std::move(callback_runner)); return true; } void FaviconHelper::GetLocalFaviconImageForURLInternal( favicon::FaviconService* favicon_service, GURL url, int desired_size_in_pixel, favicon_base::FaviconRawBitmapCallback callback_runner) { DCHECK(favicon_service); if (!favicon_service) return; // |j_page_url| is an origin, and it may not have had a favicon associated // with it. A trickier case is when |j_page_url| only has domain-scoped // cookies, but visitors are redirected to HTTPS on visiting. Then // |j_page_url| defaults to a HTTP scheme, but the favicon will be associated // with the HTTPS URL and hence won't be found if we include the scheme in the // lookup. Set |fallback_to_host|=true so the favicon database will fall back // to matching only the hostname to have the best chance of finding a favicon. const bool fallback_to_host = true; favicon_service->GetRawFaviconForPageURL( url, {favicon_base::IconType::kFavicon, favicon_base::IconType::kTouchIcon, favicon_base::IconType::kTouchPrecomposedIcon, favicon_base::IconType::kWebManifestIcon}, desired_size_in_pixel, fallback_to_host, std::move(callback_runner), cancelable_task_tracker_.get()); } jboolean FaviconHelper::GetForeignFaviconImageForURL( JNIEnv* env, const JavaParamRef<jobject>& jprofile, const JavaParamRef<jstring>& j_page_url, jint j_desired_size_in_pixel, const base::android::JavaParamRef<jobject>& j_favicon_image_callback) { Profile* profile = ProfileAndroid::FromProfileAndroid(jprofile); if (!profile) return false; GURL page_url(ConvertJavaStringToUTF8(env, j_page_url)); favicon::HistoryUiFaviconRequestHandler* history_ui_favicon_request_handler = HistoryUiFaviconRequestHandlerFactory::GetForBrowserContext(profile); // Can be null in tests. if (!history_ui_favicon_request_handler) return false; history_ui_favicon_request_handler->GetRawFaviconForPageURL( page_url, static_cast<int>(j_desired_size_in_pixel), base::BindOnce(&FaviconHelper::OnFaviconBitmapResultAvailable, weak_ptr_factory_.GetWeakPtr(), ScopedJavaGlobalRef<jobject>(j_favicon_image_callback)), favicon::HistoryUiFaviconRequestOrigin::kRecentTabs); return true; } void FaviconHelper::EnsureIconIsAvailable( JNIEnv* env, const JavaParamRef<jobject>& j_profile, const JavaParamRef<jobject>& j_web_contents, const JavaParamRef<jstring>& j_page_url, const JavaParamRef<jstring>& j_icon_url, jboolean j_is_large_icon, const JavaParamRef<jobject>& j_availability_callback) { Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile); DCHECK(profile); content::WebContents* web_contents = content::WebContents::FromJavaWebContents(j_web_contents); DCHECK(web_contents); GURL page_url(ConvertJavaStringToUTF8(env, j_page_url)); GURL icon_url(ConvertJavaStringToUTF8(env, j_icon_url)); favicon_base::IconType icon_type = j_is_large_icon ? favicon_base::IconType::kTouchIcon : favicon_base::IconType::kFavicon; // TODO(treib): Optimize this by creating a FaviconService::HasFavicon method // so that we don't have to actually get the image. ScopedJavaGlobalRef<jobject> j_scoped_callback(env, j_availability_callback); favicon_base::FaviconImageCallback callback_runner = base::BindOnce( &FaviconHelper::OnFaviconImageResultAvailable, j_scoped_callback, profile, web_contents, page_url, icon_url, icon_type); favicon::FaviconService* service = FaviconServiceFactory::GetForProfile( profile, ServiceAccessType::IMPLICIT_ACCESS); favicon::GetFaviconImageForPageURL(service, page_url, icon_type, std::move(callback_runner), cancelable_task_tracker_.get()); } void FaviconHelper::TouchOnDemandFavicon( JNIEnv* env, const JavaParamRef<jobject>& j_profile, const JavaParamRef<jstring>& j_icon_url) { Profile* profile = ProfileAndroid::FromProfileAndroid(j_profile); DCHECK(profile); GURL icon_url(ConvertJavaStringToUTF8(env, j_icon_url)); favicon::FaviconService* service = FaviconServiceFactory::GetForProfile( profile, ServiceAccessType::IMPLICIT_ACCESS); service->TouchOnDemandFavicon(icon_url); } FaviconHelper::~FaviconHelper() {} // Return the index of |sizes| whose area is largest but not exceeds int type // range. If all |sizes|'s area exceed int type range, return the first one. size_t FaviconHelper::GetLargestSizeIndex(const std::vector<gfx::Size>& sizes) { DCHECK(!sizes.empty()); size_t ret = 0; // Find the first element whose area doesn't exceed max value, then use it // to compare with rest elements to find largest size index. for (size_t i = 0; i < sizes.size(); ++i) { base::CheckedNumeric<int> checked_area = sizes[i].GetCheckedArea(); if (checked_area.IsValid()) { ret = i; int largest_area = checked_area.ValueOrDie(); for (i = ret + 1; i < sizes.size(); ++i) { int area = sizes[i].GetCheckedArea().ValueOrDefault(-1); if (largest_area < area) { ret = i; largest_area = area; } } } } return ret; } // static void FaviconHelper::OnFaviconDownloaded( const ScopedJavaGlobalRef<jobject>& j_availability_callback, Profile* profile, const GURL& page_url, favicon_base::IconType icon_type, int download_request_id, int http_status_code, const GURL& image_url, const std::vector<SkBitmap>& bitmaps, const std::vector<gfx::Size>& original_sizes) { if (bitmaps.empty()) { OnEnsureIconIsAvailableFinished(j_availability_callback, /*newly_available=*/false); return; } // Only keep the largest icon available. gfx::Image image = gfx::Image(gfx::ImageSkia( gfx::ImageSkiaRep(bitmaps[GetLargestSizeIndex(original_sizes)], 0))); favicon_base::SetFaviconColorSpace(&image); favicon::FaviconService* service = FaviconServiceFactory::GetForProfile( profile, ServiceAccessType::IMPLICIT_ACCESS); service->SetOnDemandFavicons(page_url, image_url, icon_type, image, base::BindOnce(&OnEnsureIconIsAvailableFinished, j_availability_callback)); } // static void FaviconHelper::OnFaviconImageResultAvailable( const ScopedJavaGlobalRef<jobject>& j_availability_callback, Profile* profile, content::WebContents* web_contents, const GURL& page_url, const GURL& icon_url, favicon_base::IconType icon_type, const favicon_base::FaviconImageResult& result) { // If there already is a favicon, return immediately. // Can |web_contents| be null here? crbug.com/688249 if (!result.image.IsEmpty() || !web_contents) { // Either the image already exists in the FaviconService, or it doesn't and // we can't download it. Either way, it's not *newly* available. OnEnsureIconIsAvailableFinished(j_availability_callback, /*newly_available=*/false); return; } web_contents->DownloadImage( icon_url, true, 0, 0, false, base::BindOnce(&FaviconHelper::OnFaviconDownloaded, j_availability_callback, profile, page_url, icon_type)); } void FaviconHelper::OnFaviconBitmapResultAvailable( const JavaRef<jobject>& j_favicon_image_callback, const favicon_base::FaviconRawBitmapResult& result) { JNIEnv* env = AttachCurrentThread(); // Convert favicon_image_result to java objects. ScopedJavaLocalRef<jstring> j_icon_url = ConvertUTF8ToJavaString(env, result.icon_url.spec()); ScopedJavaLocalRef<jobject> j_favicon_bitmap; if (result.is_valid()) { SkBitmap favicon_bitmap; gfx::PNGCodec::Decode(result.bitmap_data->front(), result.bitmap_data->size(), &favicon_bitmap); if (!favicon_bitmap.isNull()) j_favicon_bitmap = gfx::ConvertToJavaBitmap(&favicon_bitmap); } // Call java side OnFaviconBitmapResultAvailable method. Java_FaviconImageCallback_onFaviconAvailable(env, j_favicon_image_callback, j_favicon_bitmap, j_icon_url); } void FaviconHelper::OnFaviconBitmapResultsAvailable( const JavaRef<jobject>& j_favicon_image_callback, const int desired_size_in_pixel, const std::vector<favicon_base::FaviconRawBitmapResult>& results) { std::vector<SkBitmap> result_bitmaps; for (size_t i = 0; i < results.size(); i++) { favicon_base::FaviconRawBitmapResult result = results[i]; if (!result.is_valid()) continue; SkBitmap favicon_bitmap; gfx::PNGCodec::Decode(result.bitmap_data->front(), result.bitmap_data->size(), &favicon_bitmap); result_bitmaps.push_back(std::move(favicon_bitmap)); } ScopedJavaLocalRef<jobject> j_favicon_bitmap; JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_icon_url; if (!result_bitmaps.empty()) { std::unique_ptr<SkBitmap> composed_bitmap = compose_bitmaps_helper::ComposeBitmaps(std::move(result_bitmaps), desired_size_in_pixel); if (composed_bitmap && !composed_bitmap->isNull()) { j_favicon_bitmap = gfx::ConvertToJavaBitmap(composed_bitmap.get()); } } // Call java side OnFaviconBitmapResultAvailable method. Java_FaviconImageCallback_onFaviconAvailable(env, j_favicon_image_callback, j_favicon_bitmap, j_icon_url); }
{ "content_hash": "f3e14e716625db7a086cc649df19005a", "timestamp": "", "source": "github", "line_count": 489, "max_line_length": 80, "avg_line_length": 38.31083844580777, "alnum_prop": 0.6882139425643216, "repo_name": "endlessm/chromium-browser", "id": "9ac419841fa5a1163b5af10361cd4ce4d59a0052", "size": "18734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/browser/android/favicon_helper.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
myLookup :: Eq a => a -> [(a, b)] -> Maybe b myLookup _ [] = Nothing myLookup keyl ((key, value):rest) | keyl == key = Just value | otherwise = myLookup keyl rest
{ "content_hash": "a48f12641f1a8a5a27cd942bcbbe4e1d", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 44, "avg_line_length": 33.8, "alnum_prop": 0.591715976331361, "repo_name": "EricYT/real-world", "id": "dedf61cd48845b66b147044f63470a0ac9ed7407", "size": "170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/chapter-13/lookup.hs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Haskell", "bytes": "10385" } ], "symlink_target": "" }
#ifndef Ancona_Util2D_Box3_H_ #define Ancona_Util2D_Box3_H_ #include <SFML/System.hpp> namespace ild { /** * @brief Represents a box in 3rd space with a dimension, position, * and rotation * @author Jeff Swenson */ class Box3 { public: /** * @brief Initialize a 3 dimensional box * * @param position The position of the box * @param dimension The size of the box * @param rotation The rotation of the box */ Box3(const sf::Vector3f & position, const sf::Vector3f & dimension, const sf::Vector2f & rotation=sf::Vector2f()); /** * @brief Position of the box. The position is at the center * of the box. */ sf::Vector3f Position; /** * @brief Dimension of the box: Length X Width X Height */ sf::Vector3f Dimension; /** * @brief The rotation of the box. */ sf::Vector2f Rotation; /** * @brief Test if the two boxes intersect * * @param box Box to be tested * * @return True if they intersect. False otherwise. */ bool Intersects(const Box3 & box); /** * @brief Test if the box contains the argument box. * * @param box Box that may be contained. * * @return True if the box is contained. False otherwise. */ bool Contains(const Box3 & box); }; } #endif
{ "content_hash": "02738da9d4ea64d070618733008ce525", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 69, "avg_line_length": 24.43548387096774, "alnum_prop": 0.5346534653465347, "repo_name": "tlein/Ancona", "id": "2a290d702bf54dadc5b34b26572053607e127247", "size": "1515", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Engine/Src/Ancona/Util2D/Collision/Box3.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1937" }, { "name": "C++", "bytes": "3581971" }, { "name": "CMake", "bytes": "22577" }, { "name": "M4", "bytes": "19093" }, { "name": "Makefile", "bytes": "73338" }, { "name": "Python", "bytes": "190686" }, { "name": "Shell", "bytes": "343386" } ], "symlink_target": "" }
package com.google.cloud.storage.jqwik; import static com.google.cloud.storage.PackagePrivateMethodWorkarounds.ifNonNull; import com.google.storage.v2.Bucket; import com.google.storage.v2.BucketName; import java.util.Collections; import java.util.Set; import javax.annotation.ParametersAreNonnullByDefault; import net.jqwik.api.Arbitrary; import net.jqwik.api.Combinators; import net.jqwik.api.Tuple; import net.jqwik.api.providers.ArbitraryProvider; import net.jqwik.api.providers.TypeUsage; import org.checkerframework.checker.nullness.qual.NonNull; @ParametersAreNonnullByDefault public final class BucketArbitraryProvider implements ArbitraryProvider { @Override public boolean canProvideFor(TypeUsage targetType) { return targetType.isOfType(Bucket.class); } @NonNull @Override public Set<Arbitrary<?>> provideFor(TypeUsage targetType, SubtypeProvider subtypeProvider) { Arbitrary<Bucket> as = Combinators.combine( Combinators.combine( StorageArbitraries.buckets().name(), StorageArbitraries.buckets().name(), StorageArbitraries.storageClass(), StorageArbitraries.buckets().location(), StorageArbitraries.buckets().locationType(), StorageArbitraries.metageneration(), StorageArbitraries.buckets().versioning().injectNull(0.25), StorageArbitraries.timestamp().injectNull(0.25)) // ctime .as(Tuple::of), Combinators.combine( StorageArbitraries.timestamp().injectNull(0.25), // utime StorageArbitraries.buckets().website().injectNull(0.75), StorageArbitraries.bool(), StorageArbitraries.buckets().rpo(), StorageArbitraries.buckets().billing().injectNull(0.01), StorageArbitraries.buckets().encryption().injectNull(0.9), StorageArbitraries.buckets().retentionPolicy().injectNull(0.5), StorageArbitraries.buckets().lifecycle().injectNull(0.5)) .as(Tuple::of), Combinators.combine( StorageArbitraries.buckets().logging().injectNull(0.5), StorageArbitraries.buckets().cors(), StorageArbitraries.buckets().objectAccessControl().injectNull(0.5), StorageArbitraries.buckets().bucketAccessControl().injectNull(0.5), StorageArbitraries.owner().injectNull(0.01), StorageArbitraries.buckets().iamConfig().injectNull(0.5), StorageArbitraries.buckets().labels(), StorageArbitraries.etag()) .as(Tuple::of)) .as( (t1, t2, t3) -> { Bucket.Builder b = Bucket.newBuilder(); ifNonNull(t1.get1(), BucketName::getBucket, b::setBucketId); ifNonNull(t1.get2(), BucketName::toString, b::setName); ifNonNull(t1.get3(), b::setStorageClass); ifNonNull(t1.get4(), b::setLocation); ifNonNull(t1.get5(), b::setLocationType); ifNonNull(t1.get6(), b::setMetageneration); ifNonNull(t1.get7(), b::setVersioning); ifNonNull(t1.get8(), b::setCreateTime); ifNonNull(t2.get1(), b::setUpdateTime); ifNonNull(t2.get2(), b::setWebsite); ifNonNull(t2.get3(), b::setDefaultEventBasedHold); ifNonNull(t2.get4(), b::setRpo); ifNonNull(t2.get5(), b::setBilling); ifNonNull(t2.get6(), b::setEncryption); ifNonNull(t2.get7(), b::setRetentionPolicy); ifNonNull(t2.get8(), b::setLifecycle); ifNonNull(t3.get1(), b::setLogging); ifNonNull(t3.get2(), b::addAllCors); ifNonNull(t3.get3(), b::addAllDefaultObjectAcl); ifNonNull(t3.get4(), b::addAllAcl); ifNonNull(t3.get5(), b::setOwner); ifNonNull(t3.get6(), b::setIamConfig); ifNonNull(t3.get7(), b::putAllLabels); ifNonNull(t3.get8(), b::setEtag); // TODO: add CustomPlacementConfig return b.build(); }); return Collections.singleton(as); } }
{ "content_hash": "33abc4fbbc6b1a300112a91b8ccf0e36", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 94, "avg_line_length": 48.92553191489362, "alnum_prop": 0.5688193085453359, "repo_name": "googleapis/java-storage", "id": "799626ac2294aaf14514b7815d27bf64fe520e2a", "size": "5194", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "google-cloud-storage/src/test/java/com/google/cloud/storage/jqwik/BucketArbitraryProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "6736240" }, { "name": "Python", "bytes": "1489" }, { "name": "Shell", "bytes": "22837" } ], "symlink_target": "" }
RSpec.describe Nib::Run do let(:service) { 'web' } let(:command) { 'puma' } subject { described_class.new(service, command) } context 'with a command specified' do it 'inserts the --rm arg and includes history' do expect(subject.script).to match( / docker-compose .* run .* --rm .* #{service} (.|\n)* export\sHISTFILE (.|\n)* #{command}$ /x ) end end context 'without a command specified' do let(:command) { nil } it 'does not include history' do expect(subject.script).to_not include('HISTORY') end end end
{ "content_hash": "d97e2cb165fafd0dc5339ea70a3e3788", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 54, "avg_line_length": 20.294117647058822, "alnum_prop": 0.5115942028985507, "repo_name": "technekes/nib", "id": "0f48d1d3480a646dbc51e3f212f80cb62543d59b", "size": "690", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/unit/run_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "514" }, { "name": "JavaScript", "bytes": "93" }, { "name": "Ruby", "bytes": "47768" }, { "name": "Shell", "bytes": "1333" } ], "symlink_target": "" }
export class BlobUpload { $key: string; file: Blob; fileData: any; name: string; url: string; progress: number; createdAt: Date = new Date(); constructor(file: Blob, filedata: any) { this.file = file; this.fileData = filedata; this.name = this.fileData.objectname; } }
{ "content_hash": "8b009f9219858a9e6ba984e8ec85e4b7", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 42, "avg_line_length": 20, "alnum_prop": 0.6466666666666666, "repo_name": "chimple/lplatform", "id": "3b818bad5f3e63e5f59a3d52d0d24d02f7908415", "size": "300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/shared/uploads/blob-upload.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10783" }, { "name": "HTML", "bytes": "64769" }, { "name": "JavaScript", "bytes": "1962" }, { "name": "TypeScript", "bytes": "143862" } ], "symlink_target": "" }
LooRoleMonitor ============== Monitor the number of remaining loo roles on the holder to prevent running out.
{ "content_hash": "087ba12cc7079b66f8b1cea228732b11", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 79, "avg_line_length": 27.75, "alnum_prop": 0.7117117117117117, "repo_name": "Tinamous/LooRoleMonitor", "id": "10a0216e8b244aafe4dd68e4754e6c1c001cea99", "size": "111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>qcert: 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.7.1+2 / qcert - 1.0.7</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> qcert <small> 1.0.7 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-02-24 00:36:37 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-02-24 00:36:37 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.11 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.7.1+2 Formal proof management system. num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.0 Official release 4.09.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://querycert.github.io&quot; dev-repo: &quot;git+https://github.com/querycert/qcert&quot; bug-reports: &quot;https://github.com/querycert/qcert/issues&quot; authors: [ &quot;Josh Auerbach&quot; &quot;Martin Hirzel&quot; &quot;Louis Mandel&quot; &quot;Avi Shinnar&quot; &quot;Jerome Simeon&quot; ] license: &quot;Apache-2.0&quot; build: [ [make &quot;-j%{jobs}%&quot; &quot;qcert-coq&quot;] ] install: [ [make &quot;install-coq&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7.2&quot; &amp; &lt; &quot;8.8&quot;} &quot;coq-flocq&quot; {&gt;= &quot;2.6.0&quot; &amp; &lt; &quot;3.0~&quot;} &quot;coq-jsast&quot; {&gt;= &quot;1.0.7&quot;} ] synopsis: &quot;Verified compiler for data-centric languages&quot; url { src: &quot;https://github.com/querycert/qcert/archive/v1.0.7.tar.gz&quot; checksum: &quot;md5=36fd7cda0fae7887d8c17bb4822e599b&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-qcert.1.0.7 coq.8.7.1+2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+2). The following dependencies couldn&#39;t be met: - coq-qcert -&gt; coq &gt;= 8.7.2 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-qcert.1.0.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"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </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": "d130ba1a291d2c77400eb4869a9a59b2", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 157, "avg_line_length": 40.24242424242424, "alnum_prop": 0.5295180722891566, "repo_name": "coq-bench/coq-bench.github.io", "id": "3c35b9cd526bd1de9359cd5265a162d5f0a06136", "size": "6642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.09.0-2.0.5/released/8.7.1+2/qcert/1.0.7.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.example.tests; import java.io.File; import java.util.List; public class GroupDataGenerator { public static void main(String[] args) { if (args.length < 3){ System.out.println("Please specify parameters: <amount of test data> <file> <format>"); return; } int amount = Integer.parseInt(args[0]); File file = new File(args[1]); String format = args[2]; List<GroupData> groups = generateRandomGroups(amount); if ("csv".equals(format)){ saveGroupsToCsvFile(groups, file); } else if ("xml".equals(format)){ saveGroupsToXMLFile(groups, file); } else { System.out.println("Unknown format " + format); } } }
{ "content_hash": "6dedc59fb7b3e7287ad170336d9cef69", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 90, "avg_line_length": 24.333333333333332, "alnum_prop": 0.6773211567732116, "repo_name": "AnnaTretyakova/programming-for-testers", "id": "4b369a2b1f30ba4f744fb2d2781569cd868ad329", "size": "657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "addressbook_selenium_test/src/com/example/tests/GroupDataGenerator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "30962" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Earthquakemodels: code.addLL Namespace Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="real2005eastjapan.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Earthquakemodels </div> <div id="projectbrief">Here is the official documentation for generating Earthquake Risk Models using Genetic Algorithms.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('namespacecode_1_1add_l_l.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">code.addLL Namespace Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:a9c471023777b6f7b2593ed3143f1e9c8"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacecode_1_1add_l_l.html#a9c471023777b6f7b2593ed3143f1e9c8">addLoglike2</a> (type, region, depth, year_begin, year_end)</td></tr> <tr class="separator:a9c471023777b6f7b2593ed3143f1e9c8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac3e16cc60c2ed2b4aec99176c5e4687f"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacecode_1_1add_l_l.html#ac3e16cc60c2ed2b4aec99176c5e4687f">addLoglike2SC</a> (type, region, depth, year_begin, year_end)</td></tr> <tr class="separator:ac3e16cc60c2ed2b4aec99176c5e4687f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a03f8b179b69e620c74d5c55fd97cbf41"><td class="memItemLeft" align="right" valign="top">def&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespacecode_1_1add_l_l.html#a03f8b179b69e620c74d5c55fd97cbf41">main</a> ()</td></tr> <tr class="separator:a03f8b179b69e620c74d5c55fd97cbf41"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function Documentation</h2> <a id="a9c471023777b6f7b2593ed3143f1e9c8"></a> <h2 class="memtitle"><span class="permalink"><a href="#a9c471023777b6f7b2593ed3143f1e9c8">&#9670;&nbsp;</a></span>addLoglike2()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def code.addLL.addLoglike2 </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>type</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>region</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>depth</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>year_begin</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>year_end</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="code_2add_l_l_8py_source.html#l00006">6</a> of file <a class="el" href="code_2add_l_l_8py_source.html">addLL.py</a>.</p> </div> </div> <a id="ac3e16cc60c2ed2b4aec99176c5e4687f"></a> <h2 class="memtitle"><span class="permalink"><a href="#ac3e16cc60c2ed2b4aec99176c5e4687f">&#9670;&nbsp;</a></span>addLoglike2SC()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def code.addLL.addLoglike2SC </td> <td>(</td> <td class="paramtype">&#160;</td> <td class="paramname"><em>type</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>region</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>depth</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>year_begin</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">&#160;</td> <td class="paramname"><em>year_end</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="code_2add_l_l_8py_source.html#l00048">48</a> of file <a class="el" href="code_2add_l_l_8py_source.html">addLL.py</a>.</p> <div class="dynheader"> Here is the caller graph for this function:</div> <div class="dyncontent"> <div class="center"><img src="namespacecode_1_1add_l_l_ac3e16cc60c2ed2b4aec99176c5e4687f_icgraph.png" border="0" usemap="#namespacecode_1_1add_l_l_ac3e16cc60c2ed2b4aec99176c5e4687f_icgraph" alt=""/></div> <!-- MAP 0 --> </div> </div> </div> <a id="a03f8b179b69e620c74d5c55fd97cbf41"></a> <h2 class="memtitle"><span class="permalink"><a href="#a03f8b179b69e620c74d5c55fd97cbf41">&#9670;&nbsp;</a></span>main()</h2> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">def code.addLL.main </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p class="definition">Definition at line <a class="el" href="code_2add_l_l_8py_source.html#l00162">162</a> of file <a class="el" href="code_2add_l_l_8py_source.html">addLL.py</a>.</p> <div class="dynheader"> Here is the call graph for this function:</div> <div class="dyncontent"> <div class="center"><img src="namespacecode_1_1add_l_l_a03f8b179b69e620c74d5c55fd97cbf41_cgraph.png" border="0" usemap="#namespacecode_1_1add_l_l_a03f8b179b69e620c74d5c55fd97cbf41_cgraph" alt=""/></div> <!-- MAP 1 --> </div> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespacecode.html">code</a></li><li class="navelem"><a class="el" href="namespacecode_1_1add_l_l.html">addLL</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
{ "content_hash": "b415e2de0dd57d04bd18ca2081c32aa4", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 316, "avg_line_length": 40.55833333333333, "alnum_prop": 0.62584754468872, "repo_name": "PyQuake/earthquakemodels", "id": "74d05aecf72a07f7919c1643dda3857b72dd7a6b", "size": "9734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "html/namespacecode_1_1add_l_l.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using sien.entityframework; using sien.models; using WebMatrix.WebData; namespace sien.dao { public class BaseDao { public List<Dropdownlist> anos; public List<Dropdownlist> escolas; public List<Dropdownlist> series; public List<Dropdownlist> bimestres; public int idPerfil { get; set; } public string nomeUsuario { get; set; } public BaseDao() { entityframework.Usuario usu = dbContext.Usuario.FirstOrDefault(f => f.id == WebSecurity.CurrentUserId); idPerfil = usu.webpages_Roles.FirstOrDefault().RoleId; nomeUsuario = usu.nome; anos = dbContext.Ano. Select(s => new Dropdownlist() { id = s.id, nome = s.id.ToString() }).ToList(); if (idPerfil == (int)Perfil.Administrador) { //Administradores escolas = dbContext.Instituicao. Select(s => new Dropdownlist() { id = s.id, nome = s.nome }). Distinct().ToList(); } else if (idPerfil == (int)Perfil.Diretor || idPerfil == (int)Perfil.Secretario || idPerfil == (int)Perfil.Professor) { //Diretores, secretarios e professores escolas = dbContext.InstituicaoColaborador. Where(w => w.idUsuarioColaborador == WebSecurity.CurrentUserId && dbContext.Turma.Select(s => s.idInstituicao).Contains(w.idInstituicao)). Select(s => new Dropdownlist() { id = s.Instituicao.id, nome = s.Instituicao.nome }). Distinct().ToList(); } else { //Alunos e Responsáveis List<int> alunos = dbContext.Usuario.Where(w => w.idUsuarioResponsavel == WebSecurity.CurrentUserId). Select(s => s.id).ToList(); escolas = dbContext.Matricula. Where(w => w.idUsuarioAluno == WebSecurity.CurrentUserId || alunos.Contains(w.idUsuarioAluno)). Select(s => new Dropdownlist() { id = s.Instituicao.id, nome = s.Instituicao.nome }). Distinct().ToList(); } series = dbContext.Turma. Select(s => new { id = s.Serie.id, nome = s.Serie.nome, nivelEnsino = s.Serie.NivelEnsino.nome }).Distinct().ToList(). Select(s => new Dropdownlist() { id = s.id, nome = string.Concat(s.nome, " - ", s.nivelEnsino) }).ToList(); bimestres = new List<Dropdownlist>() { new Dropdownlist(){id=1,nome="1° Bimestre"}, new Dropdownlist(){id=2,nome="2° Bimestre"}, new Dropdownlist(){id=3,nome="3° Bimestre"}, new Dropdownlist(){id=4,nome="4° Bimestre"} }; } private Entities _DbContext; public Entities dbContext { get { if (_DbContext == null) { _DbContext = new Entities(); } return _DbContext; } } public enum Perfil : int { Administrador = 1, Diretor = 2, Secretario = 3, Professor = 4, Aluno = 5, Responsavel = 6 } public List<Dropdownlist> carregaTurmas(int idAno, int idEscola, int idSerie) { if (idPerfil == (int)Perfil.Aluno) { return dbContext.Matricula.Where(w => w.idAno == idAno && w.idInstituicao == idEscola && w.Turma.idSerie == idSerie && w.idUsuarioAluno == WebSecurity.CurrentUserId). Select(s => new Dropdownlist() { id = s.idTurma, nome = s.Turma.nome }).ToList(); } else if (idPerfil == (int)Perfil.Responsavel) { List<int> idUsuarios = dbContext.Usuario.Where(w => w.idUsuarioResponsavel == WebSecurity.CurrentUserId).Select(s => s.id).ToList(); return dbContext.Matricula.Where(w => w.idAno == idAno && w.idInstituicao == idEscola && w.Turma.idSerie == idSerie). Join(dbContext.Usuario.Where(w => w.idUsuarioResponsavel == WebSecurity.CurrentUserId), m => m.idUsuarioAluno, u => u.id, (m, u) => new { m = m, u = u }). Select(s => new Dropdownlist() { id = s.m.idTurma, nome = s.m.Turma.nome }).Distinct().ToList(); } else { return dbContext.Turma.Where(w => w.idAno == idAno && w.idInstituicao == idEscola && w.idSerie == idSerie). Select(s => new Dropdownlist() { id = s.id, nome = s.nome }).ToList(); } } public object carregaDisciplinasAlunos(int idAno, int idEscola, int idSerie, int idTurma) { return new { disciplinas = dbContext.TurmaDisciplinaProfessor.Where(w => w.Turma.idAno == idAno && w.Turma.idInstituicao == idEscola && w.Turma.idSerie == idSerie && w.idTurma == idTurma). Select(s => new Dropdownlist() { id = s.Disciplina.id, nome = s.Disciplina.nome }).ToList(), alunos = dbContext.Matricula.Where(w => w.idAno == idAno && w.idInstituicao == idEscola && w.idTurma == idTurma). Select(s => new Dropdownlist() { id = s.Usuario.id, nome = s.Usuario.nome }).ToList() }; } public List<Dropdownlist> carregaAlunos(int idAno, int idEscola, int idSerie, int idTurma) { if (idPerfil == (int)Perfil.Aluno) { return dbContext.Matricula.Where(w => w.idAno == idAno && w.idUsuarioAluno == WebSecurity.CurrentUserId && w.idInstituicao == idEscola && w.idTurma == idTurma). Select(s => new Dropdownlist() { id = s.Usuario.id, nome = s.Usuario.nome }).ToList(); } else { return dbContext.Matricula.Where(w => w.idAno == idAno && w.Usuario.idUsuarioResponsavel == WebSecurity.CurrentUserId && w.idInstituicao == idEscola && w.idTurma == idTurma). Select(s => new Dropdownlist() { id = s.Usuario.id, nome = s.Usuario.nome }).ToList(); } } public List<Dropdownlist> carregaDisciplinas(int idAno, int idEscola, int idSerie, int idTurma) { return dbContext.TurmaDisciplinaProfessor.Where(w => w.Turma.idAno == idAno && w.Turma.idInstituicao == idEscola && w.Turma.idSerie == idSerie && w.idTurma == idTurma). Select(s => new Dropdownlist() { id = s.Disciplina.id, nome = s.Disciplina.nome }).ToList(); } public List<sien.entityframework.Usuario> listagemUsuario(int idAno, int idEscola, int idSerie, int idTurma, int idAluno) { var lista = dbContext.Matricula. Where(w => (w.idAno == idAno || idAno == 0) && (w.idInstituicao == idEscola || idEscola == 0) && (w.Turma.idSerie == idSerie || idSerie == 0) && (w.idTurma == idTurma || idTurma == 0) && (w.idUsuarioAluno == idAluno || idAluno == 0)).ToList(); if (lista.Count > 0) { return lista.Select(s => new sien.entityframework.Usuario() { id = s.id, nome = s.Usuario.nome }).ToList(); } return new List<sien.entityframework.Usuario>(); } public List<Dropdownlist> carregaUsuarioAluno(int idAno) { var usuariosAlunos = dbContext.webpages_Roles.FirstOrDefault(w => w.RoleId == (int)Perfil.Aluno).Usuario.ToList(); var usuarios = usuariosAlunos.Except(dbContext.Matricula.Where(w => w.idAno == idAno).Select(s => s.Usuario).ToList()).ToList(); return usuarios.Select(s => new Dropdownlist() { id = s.id, nome = s.nome }).ToList(); } } }
{ "content_hash": "b10e70acd81f3f807ea26435ebd03f09", "timestamp": "", "source": "github", "line_count": 196, "max_line_length": 148, "avg_line_length": 43.505102040816325, "alnum_prop": 0.5154216019702123, "repo_name": "gustavoisensee/sien", "id": "71f6999653ee8f4848a549662a6d0aa623c14f7d", "size": "8534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sien.dao/BaseDao.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "99" }, { "name": "C#", "bytes": "233278" }, { "name": "CSS", "bytes": "10008" }, { "name": "HTML", "bytes": "5125" }, { "name": "JavaScript", "bytes": "143050" }, { "name": "SQLPL", "bytes": "2314" } ], "symlink_target": "" }
using System; using System.IO; using System.Net; using System.Security.Cryptography; namespace Google.GData.Client { /// <summary> /// A request factory to generate an authorization header suitable for use /// with OAuth 2.0. /// </summary> public class GOAuth2RequestFactory : GDataGAuthRequestFactory { /// <summary>this factory's agent</summary> public const string GDataGAuthSubAgent = "GOAuth2RequestFactory-CS/1.0.0"; /// <summary> /// Constructor. /// </summary> public GOAuth2RequestFactory(string service, string applicationName, OAuth2Parameters parameters) : base(service, applicationName) { this.Parameters = parameters; } /// <summary> /// default constructor. /// </summary> public override IGDataRequest CreateRequest(GDataRequestType type, Uri uriTarget) { return new GOAuth2Request(type, uriTarget, this); } public OAuth2Parameters Parameters { get; set; } } /// <summary> /// GOAuthSubRequest implementation. /// </summary> public class GOAuth2Request : GDataGAuthRequest { /// <summary>holds the factory instance</summary> private GOAuth2RequestFactory factory; /// <summary> /// default constructor. /// </summary> internal GOAuth2Request(GDataRequestType type, Uri uriTarget, GOAuth2RequestFactory factory) : base(type, uriTarget, factory) { this.factory = factory; } /// <summary> /// sets up the correct credentials for this call. /// </summary> protected override void EnsureCredentials() { HttpWebRequest http = this.Request as HttpWebRequest; if (string.IsNullOrEmpty(this.factory.Parameters.AccessToken)) { throw new GDataRequestException("An access token must be provided to use GOAuthRequestFactory"); } this.Request.Headers.Remove("Authorization"); // needed? this.Request.Headers.Add("Authorization", String.Format( "{0} {1}", this.factory.Parameters.TokenType, this.factory.Parameters.AccessToken)); } public override void Execute() { try { base.Execute(); } catch (GDataRequestException re) { HttpWebResponse webResponse = re.Response as HttpWebResponse; if (webResponse != null && webResponse.StatusCode == HttpStatusCode.Unauthorized) { Tracing.TraceMsg("Access token might have expired, refreshing."); Reset(); try { OAuthUtil.RefreshAccessToken(this.factory.Parameters); } catch (WebException e) { Tracing.TraceMsg("Failed to refresh access token: " + e.StackTrace); throw re; } base.Execute(); } else { throw; } } } } }
{ "content_hash": "5ffed7cba0b7098b9acb132b8593a4c1", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 112, "avg_line_length": 36.758620689655174, "alnum_prop": 0.5619136960600375, "repo_name": "michael-jia-sage/libgoogle", "id": "64cd75d591ff95f5c8e44f7993905c399caff94c", "size": "3859", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/core/goauth2request.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7502" }, { "name": "C#", "bytes": "3772190" }, { "name": "CSS", "bytes": "1083" }, { "name": "HTML", "bytes": "58186" }, { "name": "Makefile", "bytes": "6965" }, { "name": "Python", "bytes": "6338" }, { "name": "Shell", "bytes": "1222" } ], "symlink_target": "" }
pod trunk push --allow-warnings
{ "content_hash": "cd457c4d031891e6eb7ecaae6d75921f", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 31, "avg_line_length": 32, "alnum_prop": 0.78125, "repo_name": "e-Sixt/Swen", "id": "d4811aa94ef78d5ae64ace2cc59a0e7afab22ff6", "size": "43", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/release.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Ruby", "bytes": "7243" }, { "name": "Shell", "bytes": "94" }, { "name": "Swift", "bytes": "16364" } ], "symlink_target": "" }
import React from 'react' import test from 'ava' import { mount } from 'enzyme' import jsdom from 'jsdom-global' import { Grid } from '../src' let wrapper let inner jsdom() window.matchMedia = () => ({ matches: false, addListener: () => {}, removeListener: () => {} }) test('renders', t => { t.notThrows(() => { wrapper = mount(<Grid col={6} p={2} />) inner = wrapper.find('ReflexWrap') }) }) test('passes props', t => { t.deepEqual(inner.props(), { className: 'Grid', inlineBlock: true, col: 6, p: 2, style: { verticalAlign: 'top' } }) }) test('passes align prop', t => { wrapper = mount(<Grid align='middle' />) inner = wrapper.find('ReflexWrap') t.is(inner.props().style.verticalAlign, 'middle') }) test('passes className prop', t => { wrapper = mount(<Grid className='hello' />) inner = wrapper.find('ReflexWrap') t.is(inner.props().className, 'Grid hello') }) test('applies vertical-align styles', t => { t.is(inner.props().style.verticalAlign, 'top') }) test('applies styles', t => { wrapper = mount(<Grid m={2} />) inner = wrapper.find('div') t.is(typeof inner.props().style.margin, 'number') })
{ "content_hash": "46627cdacb9caf9986735038a9fedf2a", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 51, "avg_line_length": 20.43103448275862, "alnum_prop": 0.6033755274261603, "repo_name": "HasanSa/hackathon", "id": "6bf53cdbc581a14a5c7f43e5d04a2cbddf0930bc", "size": "1186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/reflexbox/test/Grid.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "70205" }, { "name": "HTML", "bytes": "45959" }, { "name": "JavaScript", "bytes": "405428" }, { "name": "Shell", "bytes": "1085" } ], "symlink_target": "" }
local _, ns = ... local config = ns.Config if not config.units.boss.show then return end local function EnableMouseOver(self) self.Health.Value:Hide() if self.Power and self.Power.Value then self.Power.Value:Hide() end self:HookScript("OnEnter", function(self) self.Health.Value:Show() if self.Power and self.Power.Value then self.Power.Value:Show() end end) self:HookScript("OnLeave", function(self) self.Health.Value:Hide() if self.Power and self.Power.Value then self.Power.Value:Hide() end end) end local function UpdateHealth(Health, unit, cur, max) if UnitIsDeadOrGhost(unit) or not UnitIsConnected(unit) then Health:SetStatusBarColor(0.5, 0.5, 0.5) else Health:SetStatusBarColor(0, 1, 0) end Health.Value:SetText(ns.GetHealthText(unit, cur, max)) local self = Health:GetParent() if self.Name.Bg then self.Name.Bg:SetVertexColor(GameTooltip_UnitColor(unit)) end end local function UpdatePower(Power, unit, cur, min, max) if UnitIsDead(unit) then Power:SetValue(0) end Power.Value:SetText(ns.GetPowerText(unit, cur, max)) end local function CreateBossLayout(self, unit) self:RegisterForClicks("AnyUp") self:EnableMouse(true) self:SetScript("OnEnter", UnitFrame_OnEnter) self:SetScript("OnLeave", UnitFrame_OnLeave) self:SetSize(132, 46) self:SetScale(config.units.boss.scale) self:SetFrameStrata("LOW") -- Healthbar self.Health = CreateFrame("StatusBar", "$parentHealthBar", self) -- Texture self.Texture = self.Health:CreateTexture("$parentTexture", "ARTWORK") self.Texture:SetSize(250, 129) self.Texture:SetPoint("CENTER", self, 31, -24) self.Texture:SetTexture("Interface\\TargetingFrame\\UI-UnitFrame-Boss") self.Health:SetStatusBarTexture(config.media.statusbar, "BORDER") self.Health:SetSize(115, 8) self.Health:SetPoint("TOPRIGHT", self.Texture, -105, -43) self.Health:SetBackdrop({bgFile = "Interface\\Buttons\\WHITE8x8"}) self.Health:SetBackdropColor(0, 0, 0, 0.55) self.Health.frequentUpdates = true self.Health.Smooth = true self.Health.PostUpdate = UpdateHealth -- Health Text self.Health.Value = self.Health:CreateFontString("$parentTexture", "ARTWORK") self.Health.Value:SetFont(config.font.normal, config.font.normalSize) self.Health.Value:SetShadowOffset(1, -1) self.Health.Value:SetPoint("CENTER", self.Health) -- Powerbar self.Power = CreateFrame("StatusBar", "$parentPowerBar", self) self.Power:SetStatusBarTexture(config.media.statusbar, "BORDER") self.Power:SetPoint("TOPLEFT", self.Health, "BOTTOMLEFT", 0, -4) self.Power:SetPoint("TOPRIGHT", self.Health, "BOTTOMRIGHT", 0, -4) self.Power:SetHeight(self.Health:GetHeight()) self.Power:SetBackdrop({bgFile = "Interface\\Buttons\\WHITE8x8"}) self.Power:SetBackdropColor(0, 0, 0, 0.55) self.Power.PostUpdate = UpdatePower self.Power.frequentUpdates = true self.Power.Smooth = true self.Power.colorPower = true -- Power Text self.Power.Value = self.Health:CreateFontString("$parentPowerText", "ARTWORK") self.Power.Value:SetFont(config.font.normal, config.font.normalSize) self.Power.Value:SetShadowOffset(1, -1) self.Power.Value:SetPoint("CENTER", self.Power) -- Name self.Name = self.Health:CreateFontString("$parentNameText", "ARTWORK") self.Name:SetFontObject("Neav_FontName") self.Name:SetJustifyH("CENTER") self.Name:SetSize(110, 10) self.Name:SetPoint("BOTTOM", self.Health, "TOP", 0, 6) self:Tag(self.Name, "[neav:name]") -- Name Background self.Name.Bg = self.Health:CreateTexture("$parentBackground", "BACKGROUND") self.Name.Bg:SetHeight(18) self.Name.Bg:SetTexCoord(0.2, 0.8, 0.3, 0.85) self.Name.Bg:SetPoint("BOTTOMRIGHT", self.Health, "TOPRIGHT") self.Name.Bg:SetPoint("BOTTOMLEFT", self.Health, "TOPLEFT") self.Name.Bg:SetTexture("Interface\\AddOns\\oUF_Neav\\media\\nameBackground") -- Level self.Level = self.Health:CreateFontString("$parentLevelText", "ARTWORK") self.Level:SetFont(config.font.numberFont, 16, "OUTLINE") self.Level:SetShadowOffset(0, 0) self.Level:SetPoint("CENTER", self.Texture, 23, -2) self:Tag(self.Level, "[neav:level]") -- Raid Target Indicator self.RaidTargetIndicator = self.Health:CreateTexture("$parentRaidTargetIndicator", "OVERLAY", self) self.RaidTargetIndicator:SetPoint("CENTER", self, "TOPRIGHT", -9, -5) self.RaidTargetIndicator:SetTexture("Interface\\TargetingFrame\\UI-RaidTargetingIcons") self.RaidTargetIndicator:SetSize(26, 26) -- Threat Glow Texture self.ThreatGlow = self:CreateTexture("$parentThreatGlow", "OVERLAY") self.ThreatGlow:SetAlpha(0) self.ThreatGlow:SetSize(241, 100) self.ThreatGlow:SetPoint("TOPRIGHT", self.Texture, -11, 4) self.ThreatGlow:SetTexture("Interface\\TargetingFrame\\UI-UnitFrame-Boss-Flash") self.ThreatGlow:SetTexCoord(0.0, 0.945, 0.0, 0.73125) self.feedbackUnit = "player" -- Buffs self.Buffs = CreateFrame("Frame", "$parentBuffs", self) self.Buffs.size = 25 self.Buffs:SetHeight(self.Buffs.size * 1.1) self.Buffs:SetWidth(self.Buffs.size * 5) self.Buffs:SetPoint("TOPLEFT", self, "BOTTOMLEFT", 0, -5) self.Buffs.initialAnchor = "TOPLEFT" self.Buffs["growth-x"] = "RIGHT" self.Buffs["growth-y"] = "DOWN" self.Buffs.num = 4 self.Buffs.spacing = 4.5 self.Buffs.PostCreateIcon = ns.UpdateAuraIcons self.Buffs.PostUpdateIcon = ns.PostUpdateIcon -- Castbar if config.units.boss.castbar.show then self.Castbar = CreateFrame("StatusBar", self:GetName().."Castbar", self) self.Castbar:SetStatusBarTexture(config.media.statusbar) self.Castbar:SetPoint("BOTTOM", self, "TOP", 10, 13) self.Castbar:SetHeight(config.units.boss.castbar.height) self.Castbar:SetWidth(config.units.boss.castbar.width) self.Castbar.castColor = config.units.boss.castbar.castColor self.Castbar.channeledColor = config.units.boss.castbar.channeledColor self.Castbar.nonInterruptibleColor = config.units.boss.castbar.nonInterruptibleColor self.Castbar.failedCastColor = config.units.boss.castbar.failedCastColor self.Castbar.timeToHold = 1 self.Castbar.Background = self.Castbar:CreateTexture("$parentBackground", "BACKGROUND") self.Castbar.Background:SetTexture("Interface\\Buttons\\WHITE8x8") self.Castbar.Background:SetAllPoints(self.Castbar) self.Castbar:CreateBeautyBorder(11) self.Castbar:SetBeautyBorderPadding(3) ns.CreateCastbarStrings(self, false) self.Castbar.CustomDelayText = ns.CustomDelayText self.Castbar.CustomTimeText = ns.CustomTimeText self.Castbar.PostCastStart = ns.UpdateCastbarColor self.Castbar.PostChannelStart = ns.UpdateCastbarColor self.Castbar.PostCastInterruptible = ns.UpdateCastbarColor self.Castbar.PostCastNotInterruptible = ns.UpdateCastbarColor self.Castbar.PostCastInterrupted = function(self, unit) self:SetStatusBarColor(unpack(self.failedCastColor)) self.Background:SetVertexColor(self.failedCastColor[1]*0.3, self.failedCastColor[2]*0.3, self.failedCastColor[3]*0.3) end end -- Mouseover Text if config.units.boss.mouseoverText then EnableMouseOver(self) end return self end oUF:RegisterStyle("oUF_Neav_Boss", CreateBossLayout) oUF:Factory(function(self) oUF:SetActiveStyle("oUF_Neav_Boss") local boss = {} for i = 1, MAX_BOSS_FRAMES do boss[i] = self:Spawn("boss"..i, "oUF_Neav_BossFrame"..i) boss[i]:SetFrameStrata("LOW") if i == 1 then boss[i]:SetPoint(unpack(config.units.boss.position)) else boss[i]:SetPoint("TOPLEFT", boss[i-1], "BOTTOMLEFT", 0, (config.units.boss.castbar.show and -80) or -50) end end end)
{ "content_hash": "1acdff19614aa9a4b40edbcd16d325e8", "timestamp": "", "source": "github", "line_count": 242, "max_line_length": 129, "avg_line_length": 33.764462809917354, "alnum_prop": 0.686084934524538, "repo_name": "renstrom/NeavUI", "id": "c2aa294fb0747c5d692621aba988d85721beecc8", "size": "8172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Interface/AddOns/oUF_Neav/boss.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "453689" }, { "name": "Makefile", "bytes": "691" } ], "symlink_target": "" }
All notable changes to this add-on will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased ### Added - Add Send button to Response tab. - Add shortcut to Send buttons (Issue 6448). - Add button to allow to regenerate Anti-CSRF tokens (Issue 111). - Provide the necessary infrastructure for other add-ons (e.g. WebSocket) to send messages. - On ZAP versions newer than 2.11: - Manage the send/resend Manual Request Editor dialogues. - Add a Tools menu item to open the send Manual Request Editor. - Add a context menu item to open the resend Manual Request Editor. ### Changed - Improve reporting of TLS errors (Issue 2699). - Maintenance changes. - Promoted to Beta. - Now following Semantic Versioning. ## [6] - 2022-05-10 ### Added - Support for renaming tabs. - More help. ### Changed - Update minimum ZAP version to 2.11.1. - Maintenance changes. - Moved Help button to the Response tab. ## [5] - 2021-10-07 ### Changed - Warn when unable to save (malformed) HTTP message (Issue 4235). - Update minimum ZAP version to 2.11.0. - Maintenance changes. - Add button to automatically update content length (Issue 6254). ## [4] - 2020-07-15 ### Added - Add help. - Add info and repo URLs. - Allow to disable cookies (Issue 4934). ### Changed - Update minimum ZAP version to 2.9.0. ### Fixed - Add the requests to the Sites tree to be able to active scan them (Issue 5778). - Enforce the mode when sending the request and following redirections. ## 3 - 2018-10-15 - Maintenance changes. - Change default accelerator for Requester tab. - Dynamically unload the add-on. - Ensure use of title caps (Issue 2000). ## 2 - 2017-11-28 - Code changes for Java 9 (Issue 2602). ## 1 - 2016-05-13 [6]: https://github.com/zaproxy/zap-extensions/releases/requester-v6 [5]: https://github.com/zaproxy/zap-extensions/releases/requester-v5 [4]: https://github.com/zaproxy/zap-extensions/releases/requester-v4
{ "content_hash": "cf9eb383aed385913dac55f8e9187791", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 91, "avg_line_length": 29.585714285714285, "alnum_prop": 0.7267020762916465, "repo_name": "psiinon/zap-extensions", "id": "ce1d66a3ce7ecced8c3cbdf5e7b63bbe88bd3fd3", "size": "2083", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "addOns/requester/CHANGELOG.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "50766" }, { "name": "Groovy", "bytes": "29975" }, { "name": "HTML", "bytes": "14600029" }, { "name": "Haskell", "bytes": "2592943" }, { "name": "Java", "bytes": "16013658" }, { "name": "JavaScript", "bytes": "220869" }, { "name": "Kotlin", "bytes": "123828" }, { "name": "Python", "bytes": "27312" }, { "name": "Ruby", "bytes": "16548" }, { "name": "XSLT", "bytes": "9433" } ], "symlink_target": "" }
local skynet = require "skynet" require "skynet.manager" local cluster = require "skynet.cluster.core" local config_name = skynet.getenv "cluster" local node_address = {} local node_sender = {} local command = {} local config = {} local nodename = cluster.nodename() local connecting = {} local function open_channel(t, key) local ct = connecting[key] if ct then local co = coroutine.running() table.insert(ct, co) skynet.wait(co) return assert(ct.channel) end ct = {} connecting[key] = ct local address = node_address[key] if address == nil and not config.nowaiting then local co = coroutine.running() assert(ct.namequery == nil) ct.namequery = co skynet.error("Waiting for cluster node [".. key.."]") skynet.wait(co) address = node_address[key] end local succ, err, c if address then local host, port = string.match(address, "([^:]+):(.*)$") c = node_sender[key] if c == nil then c = skynet.newservice("clustersender", key, nodename, host, port) if node_sender[key] then -- double check skynet.kill(c) c = node_sender[key] else node_sender[key] = c end end succ = pcall(skynet.call, c, "lua", "changenode", host, port) if succ then t[key] = c ct.channel = c else err = string.format("changenode [%s] (%s:%s) failed", key, host, port) end else err = string.format("cluster node [%s] is %s.", key, address == false and "down" or "absent") end connecting[key] = nil for _, co in ipairs(ct) do skynet.wakeup(co) end assert(succ, err) if node_address[key] ~= address then return open_channel(t,key) end return c end local node_channel = setmetatable({}, { __index = open_channel }) local function loadconfig(tmp) if tmp == nil then tmp = {} if config_name then local f = assert(io.open(config_name)) local source = f:read "*a" f:close() assert(load(source, "@"..config_name, "t", tmp))() end end local reload = {} for name,address in pairs(tmp) do if name:sub(1,2) == "__" then name = name:sub(3) config[name] = address skynet.error(string.format("Config %s = %s", name, address)) else assert(address == false or type(address) == "string") if node_address[name] ~= address then -- address changed if rawget(node_channel, name) then node_channel[name] = nil -- reset connection table.insert(reload, name) end node_address[name] = address end local ct = connecting[name] if ct and ct.namequery and not config.nowaiting then skynet.error(string.format("Cluster node [%s] resloved : %s", name, address)) skynet.wakeup(ct.namequery) end end end if config.nowaiting then -- wakeup all connecting request for name, ct in pairs(connecting) do if ct.namequery then skynet.wakeup(ct.namequery) end end end for _, name in ipairs(reload) do -- open_channel would block skynet.fork(open_channel, node_channel, name) end end function command.reload(source, config) loadconfig(config) skynet.ret(skynet.pack(nil)) end function command.listen(source, addr, port) local gate = skynet.newservice("gate") if port == nil then local address = assert(node_address[addr], addr .. " is down") addr, port = string.match(address, "([^:]+):(.*)$") end skynet.call(gate, "lua", "open", { address = addr, port = port }) skynet.ret(skynet.pack(nil)) end function command.sender(source, node) skynet.ret(skynet.pack(node_channel[node])) end function command.senders(source) skynet.retpack(node_sender) end local proxy = {} function command.proxy(source, node, name) if name == nil then node, name = node:match "^([^@.]+)([@.].+)" if name == nil then error ("Invalid name " .. tostring(node)) end end local fullname = node .. "." .. name local p = proxy[fullname] if p == nil then p = skynet.newservice("clusterproxy", node, name) -- double check if proxy[fullname] then skynet.kill(p) p = proxy[fullname] else proxy[fullname] = p end end skynet.ret(skynet.pack(p)) end local cluster_agent = {} -- fd:service local register_name = {} local function clearnamecache() for fd, service in pairs(cluster_agent) do if type(service) == "number" then skynet.send(service, "lua", "namechange") end end end function command.register(source, name, addr) assert(register_name[name] == nil) addr = addr or source local old_name = register_name[addr] if old_name then register_name[old_name] = nil clearnamecache() end register_name[addr] = name register_name[name] = addr skynet.ret(nil) skynet.error(string.format("Register [%s] :%08x", name, addr)) end function command.queryname(source, name) skynet.ret(skynet.pack(register_name[name])) end function command.socket(source, subcmd, fd, msg) if subcmd == "open" then skynet.error(string.format("socket accept from %s", msg)) -- new cluster agent cluster_agent[fd] = false local agent = skynet.newservice("clusteragent", skynet.self(), source, fd) local closed = cluster_agent[fd] cluster_agent[fd] = agent if closed then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else if subcmd == "close" or subcmd == "error" then -- close cluster agent local agent = cluster_agent[fd] if type(agent) == "boolean" then cluster_agent[fd] = true elseif agent then skynet.send(agent, "lua", "exit") cluster_agent[fd] = nil end else skynet.error(string.format("socket %s %d %s", subcmd, fd, msg or "")) end end end skynet.start(function() loadconfig() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(source, ...) end) end)
{ "content_hash": "c6dbb4748b7b54f1372893a9880586b3", "timestamp": "", "source": "github", "line_count": 229, "max_line_length": 96, "avg_line_length": 24.641921397379914, "alnum_prop": 0.6668438773701931, "repo_name": "JiessieDawn/skynet", "id": "5bf36e7a4ecddd86b74cb500b6d9eb9104b555ef", "size": "5643", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "service/clusterd.lua", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1134844" }, { "name": "C++", "bytes": "29510" }, { "name": "HTML", "bytes": "57879" }, { "name": "Lua", "bytes": "349693" }, { "name": "Makefile", "bytes": "13623" }, { "name": "SourcePawn", "bytes": "56" } ], "symlink_target": "" }
struct CompleteSt{ int a; }; struct CompleteSt1{ #pragma omp threadprivate(1) // expected-error {{expected unqualified-id}} int a; } d; // expected-note {{'d' defined here}} int a; // expected-note {{'a' defined here}} #pragma omp threadprivate(a) #pragma omp threadprivate(u) // expected-error {{use of undeclared identifier 'u'}} #pragma omp threadprivate(d, a) int foo() { // expected-note {{declared here}} static int l; #pragma omp threadprivate(l)) // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} return (a); } #pragma omp threadprivate (a) ( // expected-warning@-1 {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} #pragma omp threadprivate (a) [ // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} #pragma omp threadprivate (a) { // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} #pragma omp threadprivate (a) ) // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} #pragma omp threadprivate (a) ] // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} #pragma omp threadprivate (a) } // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} #pragma omp threadprivate a // expected-error {{expected '(' after 'threadprivate'}} #pragma omp threadprivate(d // expected-error {{expected ')'}} expected-note {{to match this '('}} #pragma omp threadprivate(d)) // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} int x, y; #pragma omp threadprivate(x)) // expected-warning {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} #pragma omp threadprivate(y)), // expected-warning@-1 {{extra tokens at the end of '#pragma omp threadprivate' are ignored}} #pragma omp threadprivate(a,d) #pragma omp threadprivate(d.a) // expected-error {{expected identifier}} #pragma omp threadprivate((float)a) // expected-error {{expected unqualified-id}} int foa; // expected-note {{'foa' declared here}} #pragma omp threadprivate(faa) // expected-error {{use of undeclared identifier 'faa'; did you mean 'foa'?}} #pragma omp threadprivate(foo) // expected-error {{'foo' is not a global variable, static local variable or static data member}} #pragma omp threadprivate (int a=2) // expected-error {{expected unqualified-id}} struct IncompleteSt; // expected-note {{forward declaration of 'IncompleteSt'}} extern IncompleteSt e; #pragma omp threadprivate (e) // expected-error {{threadprivate variable with incomplete type 'IncompleteSt'}} int &f = a; // expected-note {{'f' defined here}} #pragma omp threadprivate (f) // expected-error {{arguments of '#pragma omp threadprivate' cannot be of reference type 'int &'}} class TestClass { private: int a; // expected-note {{declared here}} static int b; // expected-note {{'b' declared here}} TestClass() : a(0){} public: TestClass (int aaa) : a(aaa) {} #pragma omp threadprivate (b, a) // expected-error {{'a' is not a global variable, static local variable or static data member}} } g(10); #pragma omp threadprivate (b) // expected-error {{use of undeclared identifier 'b'}} #pragma omp threadprivate (TestClass::b) // expected-error {{'#pragma omp threadprivate' must appear in the scope of the 'TestClass::b' variable declaration}} #pragma omp threadprivate (g) namespace ns { int m; #pragma omp threadprivate (m, m) } #pragma omp threadprivate (m) // expected-error {{use of undeclared identifier 'm'}} #pragma omp threadprivate (ns::m) #pragma omp threadprivate (ns:m) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'?}} const int h = 12; const volatile int i = 10; #pragma omp threadprivate (h, i) template <class T> class TempClass { private: T a; TempClass() : a(){} public: TempClass (T aaa) : a(aaa) {} static T s; #pragma omp threadprivate (s) }; #pragma omp threadprivate (s) // expected-error {{use of undeclared identifier 's'}} static __thread int t; // expected-note {{'t' defined here}} #pragma omp threadprivate (t) // expected-error {{variable 't' cannot be threadprivate because it is thread-local}} // Register "0" is currently an invalid register for global register variables. // Use "esp" instead of "0". // register int reg0 __asm__("0"); register int reg0 __asm__("esp"); // expected-note {{'reg0' defined here}} #pragma omp threadprivate (reg0) // expected-error {{variable 'reg0' cannot be threadprivate because it is a global named register variable}} int o; // expected-note {{candidate found by name lookup is 'o'}} #pragma omp threadprivate (o) namespace { int o; // expected-note {{candidate found by name lookup is '(anonymous namespace)::o'}} #pragma omp threadprivate (o) #pragma omp threadprivate (o) } #pragma omp threadprivate (o) // expected-error {{reference to 'o' is ambiguous}} #pragma omp threadprivate (::o) int main(int argc, char **argv) { // expected-note {{'argc' defined here}} int x, y = argc; // expected-note 2 {{'y' defined here}} static double d1; static double d2; static double d3; // expected-note {{'d3' defined here}} static double d4; static TestClass LocalClass(y); // expected-error {{variable with local storage in initial value of threadprivate variable}} #pragma omp threadprivate(LocalClass) d.a = a; d2++; ; #pragma omp threadprivate(argc+y) // expected-error {{expected identifier}} #pragma omp threadprivate(argc,y) // expected-error 2 {{arguments of '#pragma omp threadprivate' must have static storage duration}} #pragma omp threadprivate(d2) // expected-error {{'#pragma omp threadprivate' must precede all references to variable 'd2'}} #pragma omp threadprivate(d1) { ++a;d2=0; #pragma omp threadprivate(d3) // expected-error {{'#pragma omp threadprivate' must appear in the scope of the 'd3' variable declaration}} } #pragma omp threadprivate(d3) label: #pragma omp threadprivate(d4) // expected-error {{'#pragma omp threadprivate' cannot be an immediate substatement}} #pragma omp threadprivate(a) // expected-error {{'#pragma omp threadprivate' must appear in the scope of the 'a' variable declaration}} return (y); #pragma omp threadprivate(d) // expected-error {{'#pragma omp threadprivate' must appear in the scope of the 'd' variable declaration}} }
{ "content_hash": "a01acc206f5f3b25d82ff7c7eedea2b9", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 158, "avg_line_length": 47.029411764705884, "alnum_prop": 0.7157598499061913, "repo_name": "ensemblr/llvm-project-boilerplate", "id": "9775bfa458f49101f9e79a262210287327aa49da", "size": "6993", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "include/llvm/tools/clang/test/OpenMP/threadprivate_messages.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "32" }, { "name": "AppleScript", "bytes": "1429" }, { "name": "Assembly", "bytes": "15649629" }, { "name": "Awk", "bytes": "1747037" }, { "name": "Batchfile", "bytes": "34481" }, { "name": "Brainfuck", "bytes": "284" }, { "name": "C", "bytes": "85584624" }, { "name": "C#", "bytes": "20737" }, { "name": "C++", "bytes": "168418524" }, { "name": "CMake", "bytes": "1174816" }, { "name": "CSS", "bytes": "49900" }, { "name": "Cuda", "bytes": "414703" }, { "name": "Emacs Lisp", "bytes": "110018" }, { "name": "Forth", "bytes": "1490" }, { "name": "Fortran", "bytes": "356707" }, { "name": "GAP", "bytes": "6167" }, { "name": "Go", "bytes": "132137" }, { "name": "HTML", "bytes": "1751124" }, { "name": "JavaScript", "bytes": "141512" }, { "name": "LLVM", "bytes": "62219250" }, { "name": "Limbo", "bytes": "7437" }, { "name": "Logos", "bytes": "1572537943" }, { "name": "Lua", "bytes": "86606" }, { "name": "M", "bytes": "2008" }, { "name": "M4", "bytes": "109560" }, { "name": "Makefile", "bytes": "616437" }, { "name": "Mathematica", "bytes": "7845" }, { "name": "Matlab", "bytes": "53817" }, { "name": "Mercury", "bytes": "1194" }, { "name": "Mirah", "bytes": "1079943" }, { "name": "OCaml", "bytes": "407143" }, { "name": "Objective-C", "bytes": "5910944" }, { "name": "Objective-C++", "bytes": "1720450" }, { "name": "OpenEdge ABL", "bytes": "690534" }, { "name": "PHP", "bytes": "15986" }, { "name": "POV-Ray SDL", "bytes": "19471" }, { "name": "Perl", "bytes": "591927" }, { "name": "PostScript", "bytes": "845774" }, { "name": "Protocol Buffer", "bytes": "20013" }, { "name": "Python", "bytes": "1895427" }, { "name": "QMake", "bytes": "15580" }, { "name": "RenderScript", "bytes": "741" }, { "name": "Roff", "bytes": "94555" }, { "name": "Rust", "bytes": "200" }, { "name": "Scheme", "bytes": "2654" }, { "name": "Shell", "bytes": "1144090" }, { "name": "Smalltalk", "bytes": "144607" }, { "name": "SourcePawn", "bytes": "1544" }, { "name": "Standard ML", "bytes": "2841" }, { "name": "Tcl", "bytes": "8285" }, { "name": "TeX", "bytes": "320484" }, { "name": "Vim script", "bytes": "17239" }, { "name": "Yacc", "bytes": "163484" } ], "symlink_target": "" }
class AP_API apGLSampler : public apAllocatedObject { public: // Self functions: apGLSampler(GLuint name = 0); apGLSampler(const apGLSampler& other); virtual ~apGLSampler(); apGLSampler& operator=(const apGLSampler& other); // Overrides osTransferableObject: virtual osTransferableObjectType type() const; virtual bool writeSelfIntoChannel(osChannel& ipcChannel) const; virtual bool readSelfFromChannel(osChannel& ipcChannel); void bindToTextureUnit(GLuint textureUnit); bool unbindToTextureUnit(GLuint textureUnit); // ******** // Getters: // ******** GLuint samplerName() const { return m_name; }; void getBoundTextures(gtVector<GLuint>& buffer) const; void getSamplerRgbaColor(GLfloat& r, GLfloat& g, GLfloat& b, GLfloat& a) const; GLenum getSamplerComparisonFunction() const { return m_textureCompareFunc; } GLenum getSamplerComparisonMode() const { return m_textureCompareMode; } bool getSamplerComparisonModeAsString(gtString& buffer) const; GLfloat getTextureLodBias() const { return m_textureLodBias; } GLfloat getTextureMaxLod() const { return m_textureMaxLod; } GLfloat getTextureMinLod() const { return m_textureMinLod; } GLenum getTextureMagFilter() const { return m_textureMagFilter; } GLenum getTextureMinFilter() const { return m_textureMinFilter; } GLenum getTextureWrapS() const { return m_textureWrapS; } GLenum getTextureWrapT() const { return m_textureWrapT; } GLenum getTextureWrapR() const { return m_textureWrapR; } // ******** // Setters: // ******** // sets the RGBA color for the specified sampler. void setSamplerColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a); void setSamplerComparisonFunction(GLenum comparisonFunction); void setSamplerComparisonMode(GLenum comparisonMode); void setSamplerLodBias(GLfloat lodBias); void setSamplerMaxLod(GLfloat maxLod); void setSamplerMinLod(GLfloat minLod); void setSamplerMagnificationFunction(GLenum magFunction); void setSamplerMinificationFunction(GLenum minFunction); void setSwrapMode(GLenum sWrapMode); void setTwrapMode(GLenum tWrapMode); void setRwrapMode(GLenum rWrapMode); private: // Holds the name of the bound textures. gtVector<GLuint> m_boundTextures; GLuint m_name; // The Red part of RGBA. GLfloat m_textureBorderColorRed; // The Green part of RGBA. GLfloat m_textureBorderColorGreen; // The Blue part of RGBA. GLfloat m_textureBorderColorBlue; // The Alpha part of RGBA. GLfloat m_textureBorderColorAlpha; // Comparison function. GLenum m_textureCompareFunc; // Comparison mode. GLenum m_textureCompareMode; // Texture level of detail bias. GLfloat m_textureLodBias; // Max level of detail. GLfloat m_textureMaxLod; // Min level of detail. GLfloat m_textureMinLod; // Magnification function. GLenum m_textureMagFilter; // ********************************************************************************************************* // Note for the following data members: m_textureMinFilter, m_textureWrapS, m_textureWrapT, m_textureWrapR - // These members get their default value assuming that the bound texture object is not a rectangle. // This wouldn't matter, since the actual object state would be retrieved in runtime from the OGL API // (during context data snapshot update) and override this default value anyway: // ********************************************************************************************************* // Minification function. GLenum m_textureMinFilter; // Texcoord s wrap mode. GLenum m_textureWrapS; // Texcoord t wrap mode (2D, 3D, cube map textures only). GLenum m_textureWrapT; // Texcoord r wrap mode (3D textures only). GLenum m_textureWrapR; }; #endif // __APGLSAMPLER
{ "content_hash": "6ff3fe9f7579cf651517ff594e5cbe6d", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 112, "avg_line_length": 31.133858267716537, "alnum_prop": 0.6727364693980779, "repo_name": "ilangal-amd/CodeXL", "id": "1910b004a178bdd20c935d0e6ee7c0e19dd0f75c", "size": "5059", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Common/Src/AMDTAPIClasses/Include/apGLSampler.h", "mode": "33188", "license": "mit", "language": [ { "name": "AutoIt", "bytes": "1717" }, { "name": "Batchfile", "bytes": "153761" }, { "name": "C", "bytes": "26807731" }, { "name": "C#", "bytes": "82169" }, { "name": "C++", "bytes": "190144939" }, { "name": "CMake", "bytes": "415367" }, { "name": "CSS", "bytes": "9343" }, { "name": "GLSL", "bytes": "368361" }, { "name": "Groff", "bytes": "54" }, { "name": "HLSL", "bytes": "14823" }, { "name": "HTML", "bytes": "4808344" }, { "name": "JavaScript", "bytes": "58859" }, { "name": "Lua", "bytes": "22593" }, { "name": "M4", "bytes": "75125" }, { "name": "Makefile", "bytes": "774619" }, { "name": "Objective-C", "bytes": "1008522" }, { "name": "Objective-C++", "bytes": "25122" }, { "name": "PHP", "bytes": "3065" }, { "name": "Perl", "bytes": "171205" }, { "name": "PowerShell", "bytes": "10405" }, { "name": "Python", "bytes": "299498" }, { "name": "QMake", "bytes": "9443" }, { "name": "Shell", "bytes": "448554" }, { "name": "Visual Basic", "bytes": "860" }, { "name": "Yacc", "bytes": "93875" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ISO-8859-1"?> <?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?> <current_observation version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd"> <credit>NOAA's National Weather Service</credit> <credit_URL>http://weather.gov/</credit_URL> <image> <url>http://weather.gov/images/xml_logo.gif</url> <title>NOAA's National Weather Service</title> <link>http://weather.gov</link> </image> <suggested_pickup>15 minutes after the hour</suggested_pickup> <suggested_pickup_period>60</suggested_pickup_period> <location>Unknown Station</location> <station_id>63105</station_id> <observation_time>Last Updated on Jan 4 2016, 10:00 pm AST</observation_time> <observation_time_rfc822>Mon, 04 Jan 2016 22:00:00 -0400</observation_time_rfc822> <temperature_string>36.9 F (2.7 C)</temperature_string> <temp_f>36.9</temp_f> <temp_c>2.7</temp_c> <wind_string>South at 11.4 MPH (9.91 KT)</wind_string> <wind_dir>South</wind_dir> <wind_degrees>180</wind_degrees> <wind_mph>11.4</wind_mph> <wind_gust_mph>0.0</wind_gust_mph> <wind_kt>9.91</wind_kt> <pressure_string>1003.3 mb</pressure_string> <pressure_mb>1003.3</pressure_mb> <pressure_tendency_mb>0.3</pressure_tendency_mb> <dewpoint_string>18.3 F (-7.6 C)</dewpoint_string> <dewpoint_f>18.3</dewpoint_f> <dewpoint_c>-7.6</dewpoint_c> <windchill_string>29 F (-2 C)</windchill_string> <windchill_f>29</windchill_f> <windchill_c>-2</windchill_c> <visibility_mi>27.00</visibility_mi> <mean_wave_dir>Northeast</mean_wave_dir> <mean_wave_degrees></mean_wave_degrees> <disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url> <copyright_url>http://weather.gov/disclaimer.html</copyright_url> <privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url> </current_observation>
{ "content_hash": "cb1669b5dec1d38f2aa96c8853ce1bb1", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 90, "avg_line_length": 44.65909090909091, "alnum_prop": 0.7180661577608143, "repo_name": "pjconsidine/codingclass", "id": "5f333bc28dbe313f4fe7635b8f2561d6b20de0b5", "size": "1965", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WeatherApp/data/63105.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8178" }, { "name": "HTML", "bytes": "12855" }, { "name": "JavaScript", "bytes": "5031361" }, { "name": "Python", "bytes": "305" }, { "name": "Shell", "bytes": "2810" } ], "symlink_target": "" }
public: false image: "/media/landings/last-mile-integration/rules.png" imageAlt: "Create your own rules to customize your authentication pipeline." budicon: 342 color: "#EB5424" title: "Last mile integration through JavaScript" --- If you need further customization, you can always use Auth0’s rules engine. Rules are JavaScript code snippets that run in Auth0 and empowers you to control and customize any stage of the authentication and authorization pipeline. We know that every case is completely different! See the [Rules documentation](https://auth0.com/docs/rules) for more information.
{ "content_hash": "c22c06d32b410625b4ce66dbbf95baaa", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 279, "avg_line_length": 59.4, "alnum_prop": 0.8013468013468014, "repo_name": "miparnisari/docs", "id": "98df9f6226aa84f9fc52744e174ce913698c4dbf", "size": "600", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "landings/modules/sso-last-mile-integration-depth.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1587" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "1fec2cb53f0883ae26b5d17707a4bde8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "bf60faca516b25871de097dfbbcf053f44844d8c", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Stipa/Stipa nardoides/ Syn. Danthonia nardoides/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#region License #endregion using System; using System.Collections.Generic; using System.ComponentModel; using CircuitCrawlerEditor.Entities; namespace CircuitCrawlerEditor.Triggers { public class EffectRaiseBridge : Effect { [Category("Values"), Description("The X index of the tileset tile to activate.")] public int TileX { get; set; } [Category("Values"), Description("The Y index of the tileset tile to activate.")] public int TileY { get; set; } } }
{ "content_hash": "36262e94e3f7616e9b5a6bc23e8ec57b", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 83, "avg_line_length": 24.3, "alnum_prop": 0.7222222222222222, "repo_name": "LightningDevStudios/CircuitCrawlerEditor", "id": "b41d967a62afa6f864e67631fc99b9b0e8e7f13a", "size": "1670", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CircuitCrawlerEditor/Triggers/EffectRaiseBridge.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "254114" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace BuffergasHardwareControl.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BuffergasHardwareControl.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
{ "content_hash": "ee81c2f4877837aafaedee2db0a7f3f8", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 190, "avg_line_length": 44.61904761904762, "alnum_prop": 0.6168623265741728, "repo_name": "ColdMatter/EDMSuite", "id": "171e4548552fd3cb80f3421502b0772ea1c9a5ec", "size": "2813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BuffergasHardwareControl/Properties/Resources.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2489" }, { "name": "C#", "bytes": "6547131" }, { "name": "F#", "bytes": "1565" }, { "name": "Forth", "bytes": "767" }, { "name": "HTML", "bytes": "241926" }, { "name": "Mathematica", "bytes": "452861" }, { "name": "Python", "bytes": "798129" }, { "name": "Shell", "bytes": "33" }, { "name": "TSQL", "bytes": "1768" }, { "name": "TeX", "bytes": "8393" } ], "symlink_target": "" }
import os.path from IPython.html import nbextensions def prepare_js(): """ This is needed to map js/css to the nbextensions folder """ pkgdir = os.path.join(os.path.dirname(__file__), "static") nbextensions.install_nbextension(pkgdir, symlink=True, user=True, destination='phyui') prepare_js() from ._session_model import ClusteringSessionModel from .cluster_view import add_cluster_view
{ "content_hash": "b5836e7dbf8b6490674f50c2739c292f", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 69, "avg_line_length": 29.666666666666668, "alnum_prop": 0.6741573033707865, "repo_name": "kwikteam/phyui", "id": "0d94bea9555cc764d9155bff49bb43a8631ae8ee", "size": "534", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "phyui/ipython/__init__.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1337" }, { "name": "HTML", "bytes": "2009" }, { "name": "JavaScript", "bytes": "22553" }, { "name": "Makefile", "bytes": "1275" }, { "name": "Python", "bytes": "17234" } ], "symlink_target": "" }
.class public final Landroid/provider/Telephony$Mms; .super Ljava/lang/Object; .source "Telephony.java" # interfaces .implements Landroid/provider/Telephony$BaseMmsColumns; # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/provider/Telephony; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x19 name = "Mms" .end annotation .annotation system Ldalvik/annotation/MemberClasses; value = { Landroid/provider/Telephony$Mms$Addr;, Landroid/provider/Telephony$Mms$Draft;, Landroid/provider/Telephony$Mms$Inbox;, Landroid/provider/Telephony$Mms$Intents;, Landroid/provider/Telephony$Mms$Outbox;, Landroid/provider/Telephony$Mms$Part;, Landroid/provider/Telephony$Mms$Rate;, Landroid/provider/Telephony$Mms$Sent; } .end annotation # static fields .field public static final CONTENT_URI:Landroid/net/Uri; .field public static final DEFAULT_SORT_ORDER:Ljava/lang/String; = "date DESC" .field public static final NAME_ADDR_EMAIL_PATTERN:Ljava/util/regex/Pattern; .field public static final REPORT_REQUEST_URI:Landroid/net/Uri; .field public static final REPORT_STATUS_URI:Landroid/net/Uri; # direct methods .method static constructor <clinit>()V .locals 2 const-string/jumbo v0, "content://mms" invoke-static {v0}, Landroid/net/Uri;->parse(Ljava/lang/String;)Landroid/net/Uri; move-result-object v0 sput-object v0, Landroid/provider/Telephony$Mms;->CONTENT_URI:Landroid/net/Uri; sget-object v0, Landroid/provider/Telephony$Mms;->CONTENT_URI:Landroid/net/Uri; const-string/jumbo v1, "report-request" invoke-static {v0, v1}, Landroid/net/Uri;->withAppendedPath(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri; move-result-object v0 sput-object v0, Landroid/provider/Telephony$Mms;->REPORT_REQUEST_URI:Landroid/net/Uri; sget-object v0, Landroid/provider/Telephony$Mms;->CONTENT_URI:Landroid/net/Uri; const-string/jumbo v1, "report-status" invoke-static {v0, v1}, Landroid/net/Uri;->withAppendedPath(Landroid/net/Uri;Ljava/lang/String;)Landroid/net/Uri; move-result-object v0 sput-object v0, Landroid/provider/Telephony$Mms;->REPORT_STATUS_URI:Landroid/net/Uri; const-string/jumbo v0, "\\s*(\"[^\"]*\"|[^<>\"]+)\\s*<([^<>]+)>\\s*" invoke-static {v0}, Ljava/util/regex/Pattern;->compile(Ljava/lang/String;)Ljava/util/regex/Pattern; move-result-object v0 sput-object v0, Landroid/provider/Telephony$Mms;->NAME_ADDR_EMAIL_PATTERN:Ljava/util/regex/Pattern; return-void .end method .method private constructor <init>()V .locals 0 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method .method public static extractAddrSpec(Ljava/lang/String;)Ljava/lang/String; .locals 2 sget-object v1, Landroid/provider/Telephony$Mms;->NAME_ADDR_EMAIL_PATTERN:Ljava/util/regex/Pattern; invoke-virtual {v1, p0}, Ljava/util/regex/Pattern;->matcher(Ljava/lang/CharSequence;)Ljava/util/regex/Matcher; move-result-object v0 invoke-virtual {v0}, Ljava/util/regex/Matcher;->matches()Z move-result v1 if-eqz v1, :cond_0 const/4 v1, 0x2 invoke-virtual {v0, v1}, Ljava/util/regex/Matcher;->group(I)Ljava/lang/String; move-result-object v1 return-object v1 :cond_0 return-object p0 .end method .method public static isEmailAddress(Ljava/lang/String;)Z .locals 3 invoke-static {p0}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z move-result v2 if-eqz v2, :cond_0 const/4 v2, 0x0 return v2 :cond_0 invoke-static {p0}, Landroid/provider/Telephony$Mms;->extractAddrSpec(Ljava/lang/String;)Ljava/lang/String; move-result-object v1 sget-object v2, Landroid/util/Patterns;->EMAIL_ADDRESS:Ljava/util/regex/Pattern; invoke-virtual {v2, v1}, Ljava/util/regex/Pattern;->matcher(Ljava/lang/CharSequence;)Ljava/util/regex/Matcher; move-result-object v0 invoke-virtual {v0}, Ljava/util/regex/Matcher;->matches()Z move-result v2 return v2 .end method .method public static isPhoneNumber(Ljava/lang/String;)Z .locals 2 invoke-static {p0}, Landroid/text/TextUtils;->isEmpty(Ljava/lang/CharSequence;)Z move-result v1 if-eqz v1, :cond_0 const/4 v1, 0x0 return v1 :cond_0 sget-object v1, Landroid/util/Patterns;->PHONE:Ljava/util/regex/Pattern; invoke-virtual {v1, p0}, Ljava/util/regex/Pattern;->matcher(Ljava/lang/CharSequence;)Ljava/util/regex/Matcher; move-result-object v0 invoke-virtual {v0}, Ljava/util/regex/Matcher;->matches()Z move-result v1 return v1 .end method .method public static query(Landroid/content/ContentResolver;[Ljava/lang/String;)Landroid/database/Cursor; .locals 6 const/4 v3, 0x0 sget-object v1, Landroid/provider/Telephony$Mms;->CONTENT_URI:Landroid/net/Uri; const-string/jumbo v5, "date DESC" move-object v0, p0 move-object v2, p1 move-object v4, v3 invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor; move-result-object v0 return-object v0 .end method .method public static query(Landroid/content/ContentResolver;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor; .locals 6 const/4 v4, 0x0 sget-object v1, Landroid/provider/Telephony$Mms;->CONTENT_URI:Landroid/net/Uri; if-nez p3, :cond_0 const-string/jumbo v5, "date DESC" :goto_0 move-object v0, p0 move-object v2, p1 move-object v3, p2 invoke-virtual/range {v0 .. v5}, Landroid/content/ContentResolver;->query(Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor; move-result-object v0 return-object v0 :cond_0 move-object v5, p3 goto :goto_0 .end method
{ "content_hash": "e45689cc660e6ab0d9950ef6f33116ff", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 195, "avg_line_length": 26.19047619047619, "alnum_prop": 0.7135537190082645, "repo_name": "BatMan-Rom/ModdedFiles", "id": "25c7e063cc1def4c6294ab2c315e92c2be83799e", "size": "6050", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "framework.jar.out/smali_classes2/android/provider/Telephony$Mms.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
<!-- # mondrian A component for messing around with the `mondrian.js` layout library. --> <style> .mondrian { background: rgba(0,0,0,0.5); position: relative; overflow: hidden; } .mondrian > * { object-fit: cover; border-radius: 0.5px; /* without this, object-fit is broken in Chrome */ position: absolute; transition: 0.5s ease-out; } .mondrian-label { padding: 4px; display: inline-block; } </style> <div class="mondrian" data-bind="style(height)=_component_.containerHeight" data-event="click:_component_.focus" > <video src="test/video/portrait1.mov" autoplay=true loop=true></video> <video src="test/video/portrait2.mov" autoplay=true loop=true></video> <video src="test/video/portrait3.mov" autoplay=true loop=true></video> <video src="test/video/landscape1.mov" autoplay=true loop=true></video> <div style="overflow: hidden"> <video src="test/video/portrait3.mov" style="display: none" autoplay=true loop=true></video> <video style="width: 100%; height: 100%; object-fit: cover;" src="test/video/landscape2.mov" autoplay=true loop=true ></video> </div> <video src="test/video/landscape3.mov" autoplay=true loop=true></video> <img src="test/portraits/tentacle.png"> <img src="test/portraits/weasel.png"> <canvas width="128" height="128"></canvas> </div> <button class="hide" data-event="click:_component_.hideRandom">Hide Random</button> <button class="show" data-event="click:_component_.showRandom">Show Random</button> <label class="mondrian-label"> <input class="randomChanges" type="checkbox" checked>Randomly add/remove/focus items </label> <label class="mondrian-label"> <select data-bind="value=_component_.desiredAspectRatio" > <option value="0.33">3:1 Extreme Portrait</option> <option value="0.67">3:2 Portrait</option> <option value="1" selected>Square</option> <option value="1.33">4:3 Landscape</option> <option value="1.78">16:9 Widescreen</option> <option value="2">2:1 Extreme Widescreen</option> <option value="4">4:1 Extreme Widescreen</option> </select> Desired Aspect Ratio </label> <select data-bind="value=_component_.containerHeight" > <option value="800px">Tall</option> <option value="400px">Normal</option> <option value="200px" selected>Wide</option> </select> Container Shape </label> <label class="mondrian-label"> <input type="checkbox" data-bind="checked=_component_.focusEnabled" data-event="change:_component_.changeFocusEnabled" > Focus Enabled (click to toggle focus on elements) </label> <label class="mondrian-label"> <input type="checkbox" data-bind="checked=_component_.letterboxEnabled"> Letterbox Enabled </label> <label class="mondrian-label" data-bind="show_if=_component_.letterboxEnabled"> <input type="range" min="1" max="2" step="0.05" data-bind="value=_component_.letterbox" > (<span data-bind="fixed(2)=_component_.letterbox"></span>) Letterbox Threshold </label> <script> /* jshint latedef:false */ /* global find, findOne, register, b8r, on, get */ const mondrian = await import('../lib/mondrian.js'); const resize = await import('../lib/resize.js'); const visible = () => find('.mondrian > *').filter(div => !div.matches('.hidden')); const hidden = () => find('.mondrian > .hidden'); const randomChanges = findOne('.randomChanges'); const canvas = findOne('canvas'); on('change,update,resize', '_component_.update'); /* test canvas */ const g = canvas.getContext('2d'); g.fillStyle = 'red'; g.fillRect(0,0,64,64); g.fillStyle = 'green'; g.fillRect(64,0,64,64); g.fillStyle = 'blue'; g.fillRect(0,64,64,64); g.fillStyle = 'yellow'; g.fillRect(64,64,64,64); const update = () => requestAnimationFrame(() => { mondrian.arrangeWithFocus( visible(), { aspectRatio: get('desiredAspectRatio'), letterbox: get('letterboxEnabled') && get('letterbox') } ); }); const container = findOne('.mondrian'); resize.relayTo(container); function pickRandom(arr) { return arr[Math.floor(Math.random() * arr.length)]; } function randomBehavior () { if(randomChanges.checked) { if(hidden().length === 0) { hideRandom(); } else if (visible().length === 0) { showRandom(); } else { switch (Math.floor(Math.random() * 4)) { case 0: hideRandom(); break; case 1: showRandom(); break; case 3: pickRandom(visible()).click(); break; } } } } const {domInterval} = await import('../lib/dom-timers.js'); domInterval(container, randomBehavior, 2000); function hideRandom () { const elt = pickRandom(visible()); if (elt) { elt.classList.add('hidden'); b8r.trigger('change', container); } } function showRandom () { const elt = pickRandom(hidden()); if (elt) { elt.classList.remove('hidden'); b8r.trigger('change', container); } } register ({ hideRandom, showRandom, update, containerHeight: '400px', desiredAspectRatio: 1, focusEnabled: true, letterboxEnabled: true, letterbox: 1.25, changeFocusEnabled: () => { if (! get('focusEnabled')) { find('.mondrian-focus').forEach(elt => elt.classList.remove('mondrian-focus')); update(); } }, focus: evt => { if (! get('focusEnabled')) { return; } const target = evt.target.closest('.mondrian > *'); if (target && target.classList.contains('mondrian-focus')) { target.classList.remove('mondrian-focus'); } else { find('.mondrian-focus').forEach(elt => elt.classList.remove('mondrian-focus')); if (target) target.classList.add('mondrian-focus'); } update(); } }); update(); </script>
{ "content_hash": "c64c6516f3f52a578bfeb08ad1ff11ae", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 96, "avg_line_length": 31.047120418848166, "alnum_prop": 0.630185497470489, "repo_name": "tonioloewald/Bind-O-Matic.js", "id": "6d1da1f751dfad02688433fe45a4e516554ff2cd", "size": "5930", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/mondrian.component.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4506" }, { "name": "HTML", "bytes": "50940" }, { "name": "JavaScript", "bytes": "33173" } ], "symlink_target": "" }
import flask import json import logging from datetime import datetime import inflection from functools import wraps from flask import render_template, request, url_for from werkzeug.exceptions import HTTPException from tessera_client.api.model import * from . import database from . import helpers from .application import db mgr = database.DatabaseManager(db) log = logging.getLogger(__name__) api = flask.Blueprint('api', __name__) # ============================================================================= # API Helpers # ============================================================================= def route_api(application, *args, **kwargs): def decorator(fn): @application.route(*args, **kwargs) @wraps(fn) def wrapper(*args, **kwargs): headers = None status_code = 200 try: value = fn(*args, **kwargs) except HTTPException as e: raise helpers.set_exception_response(e) if isinstance(value, tuple): if len(value) > 2: headers = value[2] status_code = value[1] value = value[0] return helpers.jsonify(value, status_code, headers) return fn return decorator def _dashboard_sort_column(): """Return a SQLAlchemy column descriptor to sort results by, based on the 'sort' and 'order' request parameters. """ columns = { 'created' : database.DashboardRecord.creation_date, 'modified' : database.DashboardRecord.last_modified_date, 'category' : database.DashboardRecord.category, 'id' : database.DashboardRecord.id, 'title' : database.DashboardRecord.title } colname = helpers.get_param('sort', 'created') order = helpers.get_param('order') column = database.DashboardRecord.creation_date if colname in columns: column = columns[colname] if order == 'desc' or order == u'desc': return column.desc() else: return column.asc() def _set_dashboard_hrefs(dash): """Add the various ReSTful hrefs to an outgoing dashboard representation. dash should be the dictionary for of the dashboard, not the model object. """ id = dash['id'] dash['href'] = url_for('api.dashboard_get', id=id) dash['definition_href'] = url_for('api.dashboard_get_definition', id=id) dash['view_href'] = url_for('ui.dashboard_with_slug', id=id, slug=inflection.parameterize(dash['title'])) if 'definition' in dash: definition = dash['definition'] definition['href'] = url_for('api.dashboard_get_definition', id=id) return dash def _dashboards_response(dashboards): """Return a Flask response object for a list of dashboards in API format. dashboards must be a list of dashboard model objects, which will be converted to their JSON representation. """ if not isinstance(dashboards, list): dashboards = [dashboards] include_definition = helpers.get_param_boolean('definition', False) return [ _set_dashboard_hrefs(d.to_json(include_definition=include_definition)) for d in dashboards] def _set_tag_hrefs(tag): """Add ReSTful href attributes to a tag's dictionary representation. """ id = tag['id'] tag['href'] = url_for('api.tag_get', id=id) return tag def _tags_response(tags): """Return a Flask response object for a list of tags in API format. tags must be a list of tag model objects, which will be converted to their JSON representation. """ if not isinstance(tags, list): tags = [tags] return [_set_tag_hrefs(t.to_json()) for t in tags] # ============================================================================= # Dashboards # ============================================================================= @route_api(api, '/dashboard/') def dashboard_list(): """Listing for all dashboards. Returns just the metadata, not the definitions. """ imported_from = request.args.get('imported_from') if imported_from: query = database.DashboardRecord.query.filter_by(imported_from=imported_from) \ .order_by(_dashboard_sort_column()) else: query = database.DashboardRecord.query.order_by(_dashboard_sort_column()) dashboards = [d for d in query.all()] return _dashboards_response(dashboards) @route_api(api, '/dashboard/tagged/<tag>') def dashboard_list_tagged(tag): """Listing for a set of dashboards with a tag applied. Returns just the metadata, not the definitions. """ tag = database.TagRecord.query.filter_by(name=tag).first() if not tag: return _dashboards_response([]) dashboards = [d for d in tag.dashboards.order_by(_dashboard_sort_column()) if tag] return _dashboards_response(dashboards) @route_api(api, '/dashboard/category/<category>') def dashboard_list_dashboards_in_category(category): """Listing for a set of dashboards in a specified category. Returns just the metadata, not the definitions. """ dashboards = [d for d in database.DashboardRecord.query .filter_by(category=category) .order_by(_dashboard_sort_column()) ] return _dashboards_response(dashboards) @route_api(api, '/dashboard/category/') def dashboard_list_all_dashboard_categories(): result = db.session.query( database.DashboardRecord.category, db.func.count(database.DashboardRecord.category) ).group_by(database.DashboardRecord.category).all() categories = [] for (name, count) in result: categories.append({ 'name' : name, 'count' : count, }) return categories @route_api(api, '/dashboard/<id>') def dashboard_get(id): """Get the metadata for a single dashboard. """ dashboard = database.DashboardRecord.query.get_or_404(id) rendering = helpers.get_param('rendering', False) include_definition = helpers.get_param_boolean('definition', False) dash = _set_dashboard_hrefs(dashboard.to_json(rendering or include_definition)) if rendering: dash['preferences'] = helpers.get_preferences() return dash @route_api(api, '/dashboard/<id>/for-rendering') def dashboard_get_for_rendering(id): """Get a dashboard with its definition, and current settings necessary for rendering. """ dashboard = database.DashboardRecord.query.get_or_404(id) dash = _set_dashboard_hrefs(dashboard.to_json(True)) return { 'dashboard' : dash, 'preferences' : helpers.get_preferences() } @route_api(api, '/dashboard/', methods=['POST']) def dashboard_create(): """Create a new dashboard with an empty definition. """ dashboard = database.DashboardRecord.from_json(request.json) if 'definition' in request.json: dashboard.definition = database.DefinitionRecord(dumps(request.json['definition'])) else: dashboard.definition = database.DefinitionRecord(dumps(DashboardDefinition())) mgr.store_dashboard(dashboard) href = url_for('api.dashboard_get', id=dashboard.id) return { 'dashboard_href' : href, 'view_href' : url_for('ui.dashboard_with_slug', id=dashboard.id, slug=inflection.parameterize(dashboard.title)) }, 201, { 'Location' : href } @route_api(api, '/dashboard/<id>', methods=['PUT']) def dashboard_update(id): """Update the metadata for an existing dashboard. """ body = json.loads(request.data) dashboard = database.DashboardRecord.query.get_or_404(id) dashboard.merge_from_json(body) mgr.store_dashboard(dashboard) # TODO - return similar to create, above return {} @route_api(api, '/dashboard/<id>', methods=['DELETE']) def dashboard_delete(id): """Delete a dashboard. Use with caution. """ dashboard = database.DashboardRecord.query.get_or_404(id) db.session.delete(dashboard) db.session.commit() return {}, 204 @route_api(api, '/dashboard/<id>/definition') def dashboard_get_definition(id): """Fetch the definition for a dashboard. This returns the representation to use when modifiying a dashboard. """ dashboard = database.DashboardRecord.query.filter_by(id=id)[0] definition = database.DashboardRecord.query.get_or_404(id).definition.to_json() definition['href'] = url_for('api.dashboard_get_definition', id=id) definition['dashboard_href'] = url_for('api.dashboard_get', id=id) return definition @route_api(api, '/dashboard/<id>/definition', methods=['PUT']) def dashboard_update_definition(id): """Update the definition of the dashboard. This should use the representation returned by /api/dashboard/<id>/definition, and should NOT have any embedded variables expanded, nor should it have complete graphite URLs in the queries. """ dashboard = database.DashboardRecord.query.get_or_404(id) # Validate the payload definition = DashboardDefinition.from_json(json.loads(request.data.decode('utf-8'))) if dashboard.definition: dashboard.definition.definition = dumps(definition) else: dashboard.definition = database.DashboardRecordDef(request.data) mgr.store_dashboard(dashboard) return {} # ============================================================================= # Tags # ============================================================================= @route_api(api, '/tag/') def tag_list(): """Listing for all tags. """ tags = db.session.query(database.TagRecord).all() return _tags_response(tags) @route_api(api, '/tag/<id>') def tag_get(id): tag = database.TagRecord.query.get_or_404(id) return _tags_response(tag) # ============================================================================= # Miscellany # ============================================================================= @route_api(api, '/preferences/') def preferences_get(): return helpers.get_preferences() @route_api(api, '/preferences/', methods=['PUT']) def preferences_put(): helpers.set_preferences(request.json) return helpers.get_preferences()
{ "content_hash": "5ddbe259eb75824c27917bb1dafe7ffb", "timestamp": "", "source": "github", "line_count": 297, "max_line_length": 104, "avg_line_length": 34.69023569023569, "alnum_prop": 0.6177812287683199, "repo_name": "jmptrader/tessera", "id": "20ac44bc49e8624f8b02bb46abd34dfead201971", "size": "10326", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tessera-server/tessera/views_api.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "70527" }, { "name": "HTML", "bytes": "68436" }, { "name": "JavaScript", "bytes": "242186" }, { "name": "Mako", "bytes": "412" }, { "name": "Python", "bytes": "52652" }, { "name": "Shell", "bytes": "2064" }, { "name": "TypeScript", "bytes": "250474" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><%= title %></title> <link type="text/css" rel="stylesheet" href="/stylesheets/components/bootstrap/bootstrap.min.css"> <script type="text/javascript" src="/javascripts/components/jquery/jquery-3.1.1.min.js"></script> <script type="text/javascript" src="/javascripts/components/bootstrap/bootstrap.min.js"></script> <!-- inject:css --> <!-- endinject --> <style> body { font-family: "微软雅黑"; } </style> </head> <body> <%-body %> <!-- inject:js --> <!-- endinject --> </body> </html>
{ "content_hash": "1b4381184d527c79b8b7498db6534cdc", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 102, "avg_line_length": 27.5, "alnum_prop": 0.5950413223140496, "repo_name": "koregvg/elasticSearch", "id": "dd060b98b34b8106a771223459f92b27e0e60d98", "size": "613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/views/layout.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "476" }, { "name": "HTML", "bytes": "42902" }, { "name": "JavaScript", "bytes": "1163041" } ], "symlink_target": "" }
import { Injectable } from '@angular/core'; import { User } from '../models/user'; import { Headers, Http, RequestOptions, Response } from '@angular/http'; import { Observable } from 'rxjs'; import { environment as env } from '../../environments/environment'; import { TokenService } from './token.service'; @Injectable() export class ApiService { private apiUrl = `${env.apiSchema || 'http'}://${env.apiHost || 'localhost'}:${env.apiPort || 8080}/${env.apiPrefix || ''}`; constructor(private http: Http, private tokenService: TokenService) { } registerUser(user: User): Observable<void> { const headers = new Headers({ 'Content-Type': 'application/json' }); const options = new RequestOptions({ headers: headers }); return this.http.post(this.apiUrl + '/user', JSON.stringify(user), options) .map(_ => null) .catch(this.handleError); } login(email: string, passwd: string): Observable<string> { const headers = new Headers({ 'Content-Type': 'application/json' }); const options = new RequestOptions({ headers: headers }); return this.http.post(this.apiUrl + '/session', { email: email, password: passwd }, options) .map(res => res.json().token) .catch(this.handleError); } doPayment(amount: number, token: string): Observable<void> { const headers = new Headers({ 'Content-Type': 'application/json' }); headers.append('Authorization', 'Bearer ' + this.tokenService.token); const options = new RequestOptions({ headers: headers }); return this.http.post(this.apiUrl + '/payment', { token: token, amount: amount }, options) .map(_ => null) .catch(this.handleError); } getCredits(): Observable<number> { const headers = new Headers({ 'Content-Type': 'application/json' }); headers.append('Authorization', 'Bearer ' + this.tokenService.token); const options = new RequestOptions({ headers: headers }); return this.http.get(this.apiUrl + '/status', options) .map(res => res.json().credits) .catch(this.handleError); } private handleError(error: Response | any) { let errMsg: string; if (error instanceof Response) { const body = error.json() || ''; const err = body.error || JSON.stringify(body); errMsg = `${error.status} - ${error.statusText || ''} ${err}`; } else { errMsg = error.message ? error.message : error.toString(); } console.error(errMsg); return Observable.throw(errMsg); } }
{ "content_hash": "d90dd226cb53928029eb5d260846ac85", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 126, "avg_line_length": 37.515151515151516, "alnum_prop": 0.6498384491114702, "repo_name": "DevWurm/node-express-stripe-kata", "id": "238247faf8a63af1ec90f2511df2f643bd149b49", "size": "2476", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/shared/api.service.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "243" }, { "name": "HTML", "bytes": "2381" }, { "name": "JavaScript", "bytes": "2877" }, { "name": "TypeScript", "bytes": "36892" } ], "symlink_target": "" }
const SSH = require('node-ssh'); const AWS = require('aws-sdk'); const SPINE_DOCKER_PULL_COMMAND = 'sudo docker pull lynckia/licode:TAG'; const SPINE_RUN_COMMAND = 'sudo docker run --rm --name spine_TEST_PREFIX_TEST_ID --log-driver none --detach --network="host" \ -e TESTPREFIX=TEST_PREFIX -e TESTID=TEST_ID -e DURATION=TEST_DURATION \ -v $(pwd)/licode_default.js:/opt/licode/licode_config.js \ -v $(pwd)/runSpineTest.sh:/opt/licode/test/runSpineTest.sh \ -v $(pwd)/runSpineClients.js:/opt/licode/spine/runSpineClients.js \ -v $(pwd)/simpleNativeConnection.js:/opt/licode/spine/simpleNativeConnection.js \ -v $(pwd)/results/:/opt/licode/results/ --workdir "/opt/licode/" \ --entrypoint "test/runSpineTest.sh" lynckia/licode:TAG'; const SPINE_GET_RESULT_COMMAND = 'cat results/output_PREFIX_TEST_ID.json'; const LICODE_RUN_COMMAND = 'sudo docker run --name licode --log-driver none \ --network="host" \ -e "PUBLIC_IP=INSTANCE_PUBLIC_IP" \ -v $(pwd)/licode_default.js:/opt/licode/scripts/licode_default.js \ --rm --detach lynckia/licode:TAG'; const LICODE_STOP_COMMAND= 'sudo docker stop licode'; const EC2_API_VERSION = '2016-11-15'; const SSH_RETRY_TIMEOUT = 5000; const SSH_MAX_RETRIES = 20; const EC2_INSTANCE_LIFETIME = 50; // minutes const VERBOSE = process.env.TEST_VERBOSE || false; const log = (...args) => VERBOSE && console.log.apply(null, args); class RemoteInstance { constructor(id, host, ip, username, privateKey, dockerTag) { this.id = id; this.ssh = new SSH(); this.host = host; this.ip = ip; this.username = username; this.privateKey = privateKey; this.dockerTag = dockerTag; this.retries = 0; } _connect(success = () => {}, fail = () => {}) { this.ssh.connect({ host: this.host, username: this.username, privateKey: this.privateKey, }).then(() => { success(); }).catch(() => { this.retries += 1; if (this.retries > SSH_MAX_RETRIES) { fail('unable to connect'); return; } setTimeout(() => { this._connect(success, fail); }, SSH_RETRY_TIMEOUT); }); } connect() { return new Promise((resolve, reject) => { this._connect(resolve, reject); }); } _execCommand(...args) { log(this.id, '- Exec Command:', ...args); return this.ssh.execCommand(...args) .then(data => { if (data /* && data.code === 0 */) { return data.stdout; } else { log(this.id, '- Error:', data.stdout, data.stderr); throw Error(data.stderr); } }); } wait(duration) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, duration); }); } setup() { log('Setting up instance', this.id); return this._execCommand('sudo yum update -y') .then(() => this._execCommand('sudo sh -c \'echo "root hard nofile 65536" >> /etc/security/limits.conf\'')) .then(() => this._execCommand('sudo sh -c \'echo "root soft nofile 65536" >> /etc/security/limits.conf\'')) .then(() => this._execCommand('sudo sh -c \'echo "* hard nofile 65536" >> /etc/security/limits.conf\'')) .then(() => this._execCommand('sudo sh -c \'echo "* soft nofile 65536" >> /etc/security/limits.conf\'')) .then(() => this.disconnect()) .then(() => this.connect()) .then(() => this._execCommand('ulimit -n')) .then(data => { log(data); return 'ok'; }) .then(() => this._execCommand('sudo yum install -y docker')) .then(() => this._execCommand('sudo service docker start')) .then(() => this._execCommand(SPINE_DOCKER_PULL_COMMAND.replace(/TAG/, this.dockerTag))) .then(() => this.ssh.mkdir('results')) .then(() => this.ssh.putFiles([{local: 'licode_default.js', remote: 'licode_default.js'}, {local: 'rtp_media_config_default.js', remote: 'rtp_media_config_default.js'}, {local: 'runSpineTest.sh', remote: 'runSpineTest.sh'}, {local: '../spine/runSpineClients.js', remote: 'runSpineClients.js'}, {local: '../spine/simpleNativeConnection.js', remote: 'simpleNativeConnection.js'}])) .then(() => this._execCommand('chmod +x runSpineTest.sh')); } runLicode() { log('Running licode'); return this._execCommand(LICODE_RUN_COMMAND .replace(/INSTANCE_PUBLIC_IP/g, this.ip) .replace(/TAG/g, this.dockerTag)) .then(() => this.wait(30 * 1000)); } stopLicode() { return this._execCommand(LICODE_STOP_COMMAND); } runTest(settings) { const settingsText = JSON.stringify(settings); return this._execCommand('echo ' + JSON.stringify(settingsText) + ' > results/config_' + settings.testId + '_' + settings.id + '.json') .then(() => this._execCommand(SPINE_RUN_COMMAND .replace(/TEST_ID/g, settings.id) .replace(/TEST_PREFIX/g, settings.testId) .replace(/TEST_DURATION/g, Math.floor(settings.duration / 10)) .replace(/TAG/g, this.dockerTag))); } stopTest(settings) { return this._execCommand(SPINE_RUN_COMMAND .replace(/TEST_ID/g, settings.id) .replace(/TEST_PREFIX/g, settings.testId)); } getResult(settings) { const promise = this._execCommand(SPINE_GET_RESULT_COMMAND .replace(/TEST_ID/g, settings.id) .replace(/PREFIX/g, settings.testId)); return promise.then((data) => { return JSON.parse(data); }); } downloadAllResults() { let dirname = 'results/'; let filename = this.id + '_results.tgz'; return this._execCommand('tar czvf ' + filename + ' ' + dirname) .then(() => this.ssh.getFile(filename, filename)); } disconnect() { this.ssh.dispose(); } } // more info: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html class Factory { constructor(settings) { this.ec2 = new AWS.EC2({ apiVersion: EC2_API_VERSION, region: settings.region }); this.numberOfInstances = settings.numberOfInstances; this.imageId = settings.imageId; this.instanceType = settings.instanceType; this.username = settings.username; this.privateKey = settings.privateKey; this.keyName = settings.keyName; this.dockerTag = settings.dockerTag; this.securityGroup = settings.securityGroup; this.instances = []; } run() { return new Promise((resolve, reject) => { this.params = { ImageId: this.imageId, MaxCount: this.numberOfInstances, MinCount: this.numberOfInstances, KeyName: this.keyName, Monitoring: { Enabled: false, }, SecurityGroups: [ this.securityGroup, ], InstanceType: this.instanceType, InstanceInitiatedShutdownBehavior: 'terminate', UserData: new Buffer(`#!/bin/bash sudo shutdown -h +${EC2_INSTANCE_LIFETIME}`).toString('base64'), // automatically terminate instances TagSpecifications: [ { ResourceType: 'instance', Tags: [ { Key: 'Name', Value: 'Tests - licode-stress-test', }, ] }, ], }; log('Running instances'); this.ec2.runInstances(this.params, (err, data) => { if (err) { reject(err); return; } this.data = data; log('Waiting for instances to be running'); this.waitForRunning() .then(() => { resolve(); }).catch((reason) => { reject(reason); }); }); }); } waitForRunning() { return new Promise((resolve, reject) => { const params = { Filters: [{ Name: 'reservation-id', Values: [this.data.ReservationId], }], }; this.ec2.waitFor('instanceRunning', params, (err, data) => { if (err) { reject(err); return; } let promises = []; data.Reservations[0].Instances.forEach((instance) => { const host = instance.PublicDnsName; const ip = instance.PublicIpAddress const spine = new RemoteInstance(instance.InstanceId, host, ip, this.username, this.privateKey, this.dockerTag); this.instances.push(spine); let promise = spine.connect() .then(() => spine.setup()); promises.push(promise); }); Promise.all(promises) .then(() => { resolve(); }) .catch((reason) => { reject(reason); }); }); }); } terminate() { return new Promise((resolve, reject) => { const params = { InstanceIds: [], }; let downloadJobs = []; this.instances.forEach((instance) => { downloadJobs.push(instance.downloadAllResults()); params.InstanceIds.push(instance.id); }); let stopInstances = () => { this.ec2.terminateInstances(params, (err, data) => { if (err) { reject(err); return; } resolve(); }); }; Promise.all(downloadJobs).then(stopInstances).catch(stopInstances); }); } } exports.Factory = Factory;
{ "content_hash": "2ab5106d2967878b5fb54bbd32688bec", "timestamp": "", "source": "github", "line_count": 288, "max_line_length": 122, "avg_line_length": 32.84375, "alnum_prop": 0.5657046199386827, "repo_name": "MModal/licode", "id": "93852deeaa4248765ec2600c6cd4d97be9666c6c", "size": "9459", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "test/utils/remote-spine.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6144" }, { "name": "C++", "bytes": "1434554" }, { "name": "CMake", "bytes": "7858" }, { "name": "HTML", "bytes": "10430" }, { "name": "JavaScript", "bytes": "870028" }, { "name": "Python", "bytes": "7010" }, { "name": "Ruby", "bytes": "4432" }, { "name": "Shell", "bytes": "40686" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <title>Scale, Transposition, and Fingering Chart</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <link href="//fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> </head> <body> <div id="container" class="container-fluid"></div> <script type="text/javascript" src="${js/app.js}"></script> </body> </html>
{ "content_hash": "d72a8e400d03d5dc345e2153a2f52726", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 212, "avg_line_length": 55.375, "alnum_prop": 0.7302483069977427, "repo_name": "christianromney/trumpet", "id": "41c834334efb9dd8a71383250ce968389658f98e", "size": "886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "Clojure", "bytes": "15680" }, { "name": "HTML", "bytes": "886" }, { "name": "Shell", "bytes": "94" } ], "symlink_target": "" }
package org.elasticsearch.search.fetch; import org.apache.lucene.search.Query; import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.query.SearchExecutionContext; import org.elasticsearch.search.SearchExtBuilder; import org.elasticsearch.search.fetch.subphase.FetchDocValuesContext; import org.elasticsearch.search.fetch.subphase.FetchFieldsContext; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.search.fetch.subphase.FieldAndFormat; import org.elasticsearch.search.fetch.subphase.InnerHitsContext; import org.elasticsearch.search.fetch.subphase.InnerHitsContext.InnerHitSubContext; import org.elasticsearch.search.fetch.subphase.ScriptFieldsContext; import org.elasticsearch.search.fetch.subphase.highlight.SearchHighlightContext; import org.elasticsearch.search.internal.ContextIndexSearcher; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.lookup.SearchLookup; import org.elasticsearch.search.lookup.SourceLookup; import org.elasticsearch.search.rescore.RescoreContext; import java.util.Collections; import java.util.List; /** * Encapsulates state required to execute fetch phases */ public class FetchContext { private final SearchContext searchContext; private final SearchLookup searchLookup; /** * Create a FetchContext based on a SearchContext */ public FetchContext(SearchContext searchContext) { this.searchContext = searchContext; this.searchLookup = searchContext.getSearchExecutionContext().lookup(); } /** * The name of the index that documents are being fetched from */ public String getIndexName() { return searchContext.indexShard().shardId().getIndexName(); } /** * The point-in-time searcher the original query was executed against */ public ContextIndexSearcher searcher() { return searchContext.searcher(); } /** * The {@code SearchLookup} for the this context */ public SearchLookup searchLookup() { return searchLookup; } /** * The original query, not rewritten. */ public Query query() { return searchContext.query(); } /** * The original query in its rewritten form. */ public Query rewrittenQuery() { return searchContext.rewrittenQuery(); } /** * The original query with additional filters and named queries */ public ParsedQuery parsedQuery() { return searchContext.parsedQuery(); } /** * Any post-filters run as part of the search */ public ParsedQuery parsedPostFilter() { return searchContext.parsedPostFilter(); } /** * Configuration for fetching _source */ public FetchSourceContext fetchSourceContext() { return searchContext.fetchSourceContext(); } /** * Should the response include `explain` output */ public boolean explain() { return searchContext.explain() && searchContext.query() != null; } /** * The rescorers included in the original search, used for explain output */ public List<RescoreContext> rescore() { return searchContext.rescore(); } /** * Should the response include sequence number and primary term metadata */ public boolean seqNoAndPrimaryTerm() { return searchContext.seqNoAndPrimaryTerm(); } /** * Configuration for fetching docValues fields */ public FetchDocValuesContext docValuesContext() { FetchDocValuesContext dvContext = searchContext.docValuesContext(); if (searchContext.collapse() != null) { // retrieve the `doc_value` associated with the collapse field String name = searchContext.collapse().getFieldName(); if (dvContext == null) { return new FetchDocValuesContext( searchContext.getSearchExecutionContext(), Collections.singletonList(new FieldAndFormat(name, null)) ); } else if (searchContext.docValuesContext().fields().stream().map(ff -> ff.field).anyMatch(name::equals) == false) { dvContext.fields().add(new FieldAndFormat(name, null)); } } return dvContext; } /** * Configuration for highlighting */ public SearchHighlightContext highlight() { return searchContext.highlight(); } /** * Does the index analyzer for this field have token filters that may produce * backwards offsets in term vectors */ public boolean containsBrokenAnalysis(String field) { return getSearchExecutionContext().containsBrokenAnalysis(field); } /** * Should the response include scores, even if scores were not calculated in the original query */ public boolean fetchScores() { return searchContext.sort() != null && searchContext.trackScores(); } /** * Configuration for returning inner hits */ public InnerHitsContext innerHits() { return searchContext.innerHits(); } /** * Should the response include version metadata */ public boolean version() { return searchContext.version(); } /** * Configuration for the 'fields' response */ public FetchFieldsContext fetchFieldsContext() { return searchContext.fetchFieldsContext(); } /** * Configuration for script fields */ public ScriptFieldsContext scriptFields() { return searchContext.scriptFields(); } /** * Configuration for external fetch phase plugins */ public SearchExtBuilder getSearchExt(String name) { return searchContext.getSearchExt(name); } public SearchExecutionContext getSearchExecutionContext() { return searchContext.getSearchExecutionContext(); } /** * For a hit document that's being processed, return the source lookup representing the * root document. This method is used to pass down the root source when processing this * document's nested inner hits. * * @param hitContext The context of the hit that's being processed. */ public SourceLookup getRootSourceLookup(FetchSubPhase.HitContext hitContext) { // Usually the root source simply belongs to the hit we're processing. But if // there are multiple layers of inner hits and we're in a nested context, then // the root source is found on the inner hits context. if (searchContext instanceof InnerHitSubContext && hitContext.hit().getNestedIdentity() != null) { InnerHitSubContext innerHitsContext = (InnerHitSubContext) searchContext; return innerHitsContext.getRootLookup(); } else { return hitContext.sourceLookup(); } } }
{ "content_hash": "7bdc2e4b5e4121f7827be8619d9a0bdc", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 128, "avg_line_length": 31.724770642201836, "alnum_prop": 0.6788606130711394, "repo_name": "GlenRSmith/elasticsearch", "id": "811f591ba560d31195bfa45a948eb182ef3c2c34", "size": "7269", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "server/src/main/java/org/elasticsearch/search/fetch/FetchContext.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11082" }, { "name": "Batchfile", "bytes": "11057" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "337461" }, { "name": "HTML", "bytes": "2186" }, { "name": "Java", "bytes": "43224931" }, { "name": "Perl", "bytes": "11756" }, { "name": "Python", "bytes": "19852" }, { "name": "Shell", "bytes": "99571" } ], "symlink_target": "" }
package net.ontrack.core.model; import lombok.Data; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.annotate.JsonCreator; public class ID { @Data public static class IDAck { public static IDAck test(boolean b) { return new IDAck(b); } private final boolean success; public ID withId(int id) { if (success) { return ID.success(id); } else { return ID.failure(); } } } public static ID failure() { return new ID(false, -1); } public static ID success(int value) { return new ID(true, value); } public static IDAck count(int count) { return IDAck.test(count == 1); } @JsonCreator public static ID fromJson(JsonNode node) { return new ID( node.get("success").getBooleanValue(), node.get("value").getIntValue() ); } private final boolean success; private final int value; protected ID(boolean success, int value) { this.success = success; this.value = value; } public boolean isSuccess() { return success; } public int getValue() { return value; } public Ack ack() { return Ack.validate(isSuccess()); } }
{ "content_hash": "85b62953cc1b9a3849516ddcced3127c", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 54, "avg_line_length": 19.926470588235293, "alnum_prop": 0.5520295202952029, "repo_name": "dcoraboeuf/ontrack", "id": "e8f45710413f938c7fbb3e50cb4b40413cd730c8", "size": "1355", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ontrack-core/src/main/java/net/ontrack/core/model/ID.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "139796" }, { "name": "Java", "bytes": "1674221" }, { "name": "JavaScript", "bytes": "484737" }, { "name": "LiveScript", "bytes": "76282" }, { "name": "Objective-C++", "bytes": "15086" }, { "name": "Python", "bytes": "6159" }, { "name": "Shell", "bytes": "19657" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <title>class apache::peruser - RDoc Documentation</title> <link type="text/css" media="screen" href="../rdoc.css" rel="stylesheet"> <script type="text/javascript"> var rdoc_rel_prefix = "../"; </script> <script type="text/javascript" charset="utf-8" src="../js/jquery.js"></script> <script type="text/javascript" charset="utf-8" src="../js/navigation.js"></script> <script type="text/javascript" charset="utf-8" src="../js/search_index.js"></script> <script type="text/javascript" charset="utf-8" src="../js/search.js"></script> <script type="text/javascript" charset="utf-8" src="../js/searcher.js"></script> <script type="text/javascript" charset="utf-8" src="../js/darkfish.js"></script> <body id="top" class="class"> <nav id="metadata"> <nav id="home-section" class="section"> <h3 class="section-header"> <a href="../index.html">Home</a> <a href="../table_of_contents.html#classes">Classes</a> <a href="../table_of_contents.html#methods">Methods</a> </h3> </nav> <nav id="search-section" class="section project-section" class="initially-hidden"> <form action="#" method="get" accept-charset="utf-8"> <h3 class="section-header"> <input type="text" name="search" placeholder="Search" id="search-field" title="Type to search, Up and Down to navigate, Enter to load"> </h3> </form> <ul id="search-results" class="initially-hidden"></ul> </nav> <div id="file-metadata"> <nav id="file-list-section" class="section"> <h3 class="section-header">Defined In</h3> <ul> </ul> </nav> </div> <div id="class-metadata"> <nav id="parent-class-section" class="section"> <h3 class="section-header">Parent</h3> <p class="link"> </nav> <!-- Method Quickref --> <nav id="method-list-section" class="section"> <h3 class="section-header">Methods</h3> <ul class="link-list"> <li ><a href="#method-i-multiplexer">#multiplexer</a> <li ><a href="#method-i-processor">#processor</a> </ul> </nav> </div> <div id="project-metadata"> <nav id="fileindex-section" class="section project-section"> <h3 class="section-header">Pages</h3> <ul> <li class="file"><a href="../modules/apache/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="../modules/apache/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="../modules/apache/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/apache/LICENSE.html">LICENSE</a> <li class="file"><a href="../modules/apache/README_md.html">README</a> <li class="file"><a href="../modules/apache/README_passenger_md.html">README.passenger</a> <li class="file"><a href="../modules/apache/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/apache/checksums_json.html">checksums.json</a> <li class="file"><a href="../modules/apache/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/apt/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="../modules/apt/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="../modules/apt/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/apt/LICENSE.html">LICENSE</a> <li class="file"><a href="../modules/apt/README_md.html">README</a> <li class="file"><a href="../modules/apt/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/apt/checksums_json.html">checksums.json</a> <li class="file"><a href="../modules/apt/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/base/Modulefile.html">Modulefile</a> <li class="file"><a href="../modules/base/README.html">README</a> <li class="file"><a href="../modules/concat/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="../modules/concat/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="../modules/concat/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/concat/LICENSE.html">LICENSE</a> <li class="file"><a href="../modules/concat/README_md.html">README</a> <li class="file"><a href="../modules/concat/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/concat/checksums_json.html">checksums.json</a> <li class="file"><a href="../modules/concat/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/firewall/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="../modules/firewall/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="../modules/firewall/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/firewall/LICENSE.html">LICENSE</a> <li class="file"><a href="../modules/firewall/README_markdown.html">README.markdown</a> <li class="file"><a href="../modules/firewall/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/firewall/checksums_json.html">checksums.json</a> <li class="file"><a href="../modules/firewall/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/heartbeat/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/module_data/Modulefile.html">Modulefile</a> <li class="file"><a href="../modules/module_data/README_md.html">README</a> <li class="file"><a href="../modules/module_data/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/mysql/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="../modules/mysql/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/mysql/Gemfile_lock.html">Gemfile.lock</a> <li class="file"><a href="../modules/mysql/LICENSE.html">LICENSE</a> <li class="file"><a href="../modules/mysql/README_md.html">README</a> <li class="file"><a href="../modules/mysql/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/mysql/TODO.html">TODO</a> <li class="file"><a href="../modules/mysql/checksums_json.html">checksums.json</a> <li class="file"><a href="../modules/mysql/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/nginx/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="../modules/nginx/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/nginx/Gemfile_lock.html">Gemfile.lock</a> <li class="file"><a href="../modules/nginx/LICENSE_md.html">LICENSE</a> <li class="file"><a href="../modules/nginx/README_markdown.html">README.markdown</a> <li class="file"><a href="../modules/nginx/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/nginx/checksums_json.html">checksums.json</a> <li class="file"><a href="../modules/nginx/composer_json.html">composer.json</a> <li class="file"><a href="../modules/nginx/data/common_yaml.html">common.yaml</a> <li class="file"><a href="../modules/nginx/data/hiera_yaml.html">hiera.yaml</a> <li class="file"><a href="../modules/nginx/data/operatingsystem/SmartOS_yaml.html">SmartOS.yaml</a> <li class="file"><a href="../modules/nginx/data/osfamily/Archlinux_yaml.html">Archlinux.yaml</a> <li class="file"><a href="../modules/nginx/data/osfamily/Debian_yaml.html">Debian.yaml</a> <li class="file"><a href="../modules/nginx/data/osfamily/FreeBSD_yaml.html">FreeBSD.yaml</a> <li class="file"><a href="../modules/nginx/data/osfamily/Solaris_yaml.html">Solaris.yaml</a> <li class="file"><a href="../modules/nginx/docs/hiera_md.html">hiera</a> <li class="file"><a href="../modules/nginx/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/profiles/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/profiles/README_md.html">README</a> <li class="file"><a href="../modules/profiles/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/profiles/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/roles/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/roles/README_md.html">README</a> <li class="file"><a href="../modules/roles/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/roles/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/stdlib/CHANGELOG_md.html">CHANGELOG</a> <li class="file"><a href="../modules/stdlib/CONTRIBUTING_md.html">CONTRIBUTING</a> <li class="file"><a href="../modules/stdlib/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/stdlib/LICENSE.html">LICENSE</a> <li class="file"><a href="../modules/stdlib/README_markdown.html">README.markdown</a> <li class="file"><a href="../modules/stdlib/README_DEVELOPER_markdown.html">README_DEVELOPER.markdown</a> <li class="file"><a href="../modules/stdlib/README_SPECS_markdown.html">README_SPECS.markdown</a> <li class="file"><a href="../modules/stdlib/RELEASE_PROCESS_markdown.html">RELEASE_PROCESS.markdown</a> <li class="file"><a href="../modules/stdlib/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/stdlib/checksums_json.html">checksums.json</a> <li class="file"><a href="../modules/stdlib/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/thing/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/thomas-base/Modulefile.html">Modulefile</a> <li class="file"><a href="../modules/thomas-base/README.html">README</a> <li class="file"><a href="../modules/thomas-profiles/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/thomas-profiles/README_md.html">README</a> <li class="file"><a href="../modules/thomas-profiles/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/thomas-profiles/metadata_json.html">metadata.json</a> <li class="file"><a href="../modules/thomas-roles/Gemfile.html">Gemfile</a> <li class="file"><a href="../modules/thomas-roles/README_md.html">README</a> <li class="file"><a href="../modules/thomas-roles/Rakefile.html">Rakefile</a> <li class="file"><a href="../modules/thomas-roles/metadata_json.html">metadata.json</a> </ul> </nav> <nav id="classindex-section" class="section project-section"> <h3 class="section-header">Class and Module Index</h3> <ul class="link-list"> <li><a href="../__site__.html">__site__</a> <li><a href="../admin.html">admin</a> <li><a href="../admin/__functions__.html">admin::__functions__</a> <li><a href="../admin/percona_repo.html">admin::percona_repo</a> <li><a href="../admin/stages.html">admin::stages</a> <li><a href="../admin/stages/me_first.html">admin::stages::me_first</a> <li><a href="../admin/stages/me_last.html">admin::stages::me_last</a> <li><a href="../admin_user.html">admin_user</a> <li><a href="../apache.html">apache</a> <li><a href="../apache.cookbook.html">apache.cookbook</a> <li><a href="../apache.cookbook/apache.html">apache.cookbook::apache</a> <li><a href="../apache/__types__.html">apache::__types__</a> <li><a href="../apache/confd.html">apache::confd</a> <li><a href="../apache/confd/no_accf.html">apache::confd::no_accf</a> <li><a href="../apache/default_confd_files.html">apache::default_confd_files</a> <li><a href="../apache/default_mods.html">apache::default_mods</a> <li><a href="../apache/dev.html">apache::dev</a> <li><a href="../apache/mod.html">apache::mod</a> <li><a href="../apache/mod/actions.html">apache::mod::actions</a> <li><a href="../apache/mod/alias.html">apache::mod::alias</a> <li><a href="../apache/mod/auth_basic.html">apache::mod::auth_basic</a> <li><a href="../apache/mod/auth_kerb.html">apache::mod::auth_kerb</a> <li><a href="../apache/mod/authnz_ldap.html">apache::mod::authnz_ldap</a> <li><a href="../apache/mod/autoindex.html">apache::mod::autoindex</a> <li><a href="../apache/mod/cache.html">apache::mod::cache</a> <li><a href="../apache/mod/cgi.html">apache::mod::cgi</a> <li><a href="../apache/mod/cgid.html">apache::mod::cgid</a> <li><a href="../apache/mod/dav.html">apache::mod::dav</a> <li><a href="../apache/mod/dav_fs.html">apache::mod::dav_fs</a> <li><a href="../apache/mod/dav_svn.html">apache::mod::dav_svn</a> <li><a href="../apache/mod/deflate.html">apache::mod::deflate</a> <li><a href="../apache/mod/dev.html">apache::mod::dev</a> <li><a href="../apache/mod/dir.html">apache::mod::dir</a> <li><a href="../apache/mod/disk_cache.html">apache::mod::disk_cache</a> <li><a href="../apache/mod/event.html">apache::mod::event</a> <li><a href="../apache/mod/expires.html">apache::mod::expires</a> <li><a href="../apache/mod/fastcgi.html">apache::mod::fastcgi</a> <li><a href="../apache/mod/fcgid.html">apache::mod::fcgid</a> <li><a href="../apache/mod/headers.html">apache::mod::headers</a> <li><a href="../apache/mod/include.html">apache::mod::include</a> <li><a href="../apache/mod/info.html">apache::mod::info</a> <li><a href="../apache/mod/itk.html">apache::mod::itk</a> <li><a href="../apache/mod/ldap.html">apache::mod::ldap</a> <li><a href="../apache/mod/mime.html">apache::mod::mime</a> <li><a href="../apache/mod/mime_magic.html">apache::mod::mime_magic</a> <li><a href="../apache/mod/negotiation.html">apache::mod::negotiation</a> <li><a href="../apache/mod/nss.html">apache::mod::nss</a> <li><a href="../apache/mod/pagespeed.html">apache::mod::pagespeed</a> <li><a href="../apache/mod/passenger.html">apache::mod::passenger</a> <li><a href="../apache/mod/perl.html">apache::mod::perl</a> <li><a href="../apache/mod/peruser.html">apache::mod::peruser</a> <li><a href="../apache/mod/php.html">apache::mod::php</a> <li><a href="../apache/mod/prefork.html">apache::mod::prefork</a> <li><a href="../apache/mod/proxy.html">apache::mod::proxy</a> <li><a href="../apache/mod/proxy_ajp.html">apache::mod::proxy_ajp</a> <li><a href="../apache/mod/proxy_balancer.html">apache::mod::proxy_balancer</a> <li><a href="../apache/mod/proxy_html.html">apache::mod::proxy_html</a> <li><a href="../apache/mod/proxy_http.html">apache::mod::proxy_http</a> <li><a href="../apache/mod/python.html">apache::mod::python</a> <li><a href="../apache/mod/reqtimeout.html">apache::mod::reqtimeout</a> <li><a href="../apache/mod/rewrite.html">apache::mod::rewrite</a> <li><a href="../apache/mod/rpaf.html">apache::mod::rpaf</a> <li><a href="../apache/mod/setenvif.html">apache::mod::setenvif</a> <li><a href="../apache/mod/speling.html">apache::mod::speling</a> <li><a href="../apache/mod/ssl.html">apache::mod::ssl</a> <li><a href="../apache/mod/status.html">apache::mod::status</a> <li><a href="../apache/mod/suexec.html">apache::mod::suexec</a> <li><a href="../apache/mod/suphp.html">apache::mod::suphp</a> <li><a href="../apache/mod/userdir.html">apache::mod::userdir</a> <li><a href="../apache/mod/vhost_alias.html">apache::mod::vhost_alias</a> <li><a href="../apache/mod/worker.html">apache::mod::worker</a> <li><a href="../apache/mod/wsgi.html">apache::mod::wsgi</a> <li><a href="../apache/mod/xsendfile.html">apache::mod::xsendfile</a> <li><a href="../apache/package.html">apache::package</a> <li><a href="../apache/params.html">apache::params</a> <li><a href="../apache/peruser.html">apache::peruser</a> <li><a href="../apache/php.html">apache::php</a> <li><a href="../apache/proxy.html">apache::proxy</a> <li><a href="../apache/python.html">apache::python</a> <li><a href="../apache/service.html">apache::service</a> <li><a href="../apache/ssl.html">apache::ssl</a> <li><a href="../apache/version.html">apache::version</a> <li><a href="../apt.html">apt</a> <li><a href="../apt/__facts__.html">apt::__facts__</a> <li><a href="../apt/__types__.html">apt::__types__</a> <li><a href="../apt/apt.html">apt::apt</a> <li><a href="../apt/backports.html">apt::backports</a> <li><a href="../apt/debian.html">apt::debian</a> <li><a href="../apt/debian/testing.html">apt::debian::testing</a> <li><a href="../apt/debian/unstable.html">apt::debian::unstable</a> <li><a href="../apt/params.html">apt::params</a> <li><a href="../apt/release.html">apt::release</a> <li><a href="../apt/unattended_upgrades.html">apt::unattended_upgrades</a> <li><a href="../apt/update.html">apt::update</a> <li><a href="../base.html">base</a> <li><a href="../base/base.html">base::base</a> <li><a href="../base/ssh_host.html">base::ssh_host</a> <li><a href="../concat.html">concat</a> <li><a href="../concat/__facts__.html">concat::__facts__</a> <li><a href="../concat/__functions__.html">concat::__functions__</a> <li><a href="../concat/setup.html">concat::setup</a> <li><a href="../cookbook.html">cookbook</a> <li><a href="../cookbook/__functions__.html">cookbook::__functions__</a> <li><a href="../cron.html">cron</a> <li><a href="../cron/cron.html">cron::cron</a> <li><a href="../db.html">db</a> <li><a href="../db/client.html">db::client</a> <li><a href="../db/server.html">db::server</a> <li><a href="../debug.html">debug</a> <li><a href="../debug/debug.html">debug::debug</a> <li><a href="../drupal.html">drupal</a> <li><a href="../drupal/drupal.html">drupal::drupal</a> <li><a href="../enc.html">enc</a> <li><a href="../enc/enc.html">enc::enc</a> <li><a href="../facts.html">facts</a> <li><a href="../firewall.html">firewall</a> <li><a href="../firewall/__types__.html">firewall::__types__</a> <li><a href="../firewall/firewall.html">firewall::firewall</a> <li><a href="../firewall/linux.html">firewall::linux</a> <li><a href="../firewall/linux/archlinux.html">firewall::linux::archlinux</a> <li><a href="../firewall/linux/debian.html">firewall::linux::debian</a> <li><a href="../firewall/linux/redhat.html">firewall::linux::redhat</a> <li><a href="../greeting.html">greeting</a> <li><a href="../greeting/greeting.html">greeting::greeting</a> <li><a href="../haproxy.html">haproxy</a> <li><a href="../haproxy/config.html">haproxy::config</a> <li><a href="../haproxy/master.html">haproxy::master</a> <li><a href="../haproxy/slave.html">haproxy::slave</a> <li><a href="../heartbeat.html">heartbeat</a> <li><a href="../heartbeat/heartbeat.html">heartbeat::heartbeat</a> <li><a href="../heartbeat/vip.html">heartbeat::vip</a> <li><a href="../jumpbox.html">jumpbox</a> <li><a href="../jumpbox/jumpbox.html">jumpbox::jumpbox</a> <li><a href="../lisa.html">lisa</a> <li><a href="../module_data.html">module_data</a> <li><a href="../myfw.html">myfw</a> <li><a href="../myfw/myfw.html">myfw::myfw</a> <li><a href="../myfw/post.html">myfw::post</a> <li><a href="../myfw/pre.html">myfw::pre</a> <li><a href="../mysql.html">mysql</a> <li><a href="../mysql.cookbook.html">mysql.cookbook</a> <li><a href="../mysql.cookbook/mysql.html">mysql.cookbook::mysql</a> <li><a href="../mysql/__functions__.html">mysql::__functions__</a> <li><a href="../mysql/__types__.html">mysql::__types__</a> <li><a href="../mysql/backup.html">mysql::backup</a> <li><a href="../mysql/bindings.html">mysql::bindings</a> <li><a href="../mysql/bindings/java.html">mysql::bindings::java</a> <li><a href="../mysql/bindings/perl.html">mysql::bindings::perl</a> <li><a href="../mysql/bindings/php.html">mysql::bindings::php</a> <li><a href="../mysql/bindings/python.html">mysql::bindings::python</a> <li><a href="../mysql/bindings/ruby.html">mysql::bindings::ruby</a> <li><a href="../mysql/client.html">mysql::client</a> <li><a href="../mysql/client/install.html">mysql::client::install</a> <li><a href="../mysql/params.html">mysql::params</a> <li><a href="../mysql/server.html">mysql::server</a> <li><a href="../mysql/server/account_security.html">mysql::server::account_security</a> <li><a href="../mysql/server/backup.html">mysql::server::backup</a> <li><a href="../mysql/server/config.html">mysql::server::config</a> <li><a href="../mysql/server/install.html">mysql::server::install</a> <li><a href="../mysql/server/monitor.html">mysql::server::monitor</a> <li><a href="../mysql/server/mysqltuner.html">mysql::server::mysqltuner</a> <li><a href="../mysql/server/providers.html">mysql::server::providers</a> <li><a href="../mysql/server/root_password.html">mysql::server::root_password</a> <li><a href="../mysql/server/service.html">mysql::server::service</a> <li><a href="../nfs.html">nfs</a> <li><a href="../nfs/exports.html">nfs::exports</a> <li><a href="../nfs/server.html">nfs::server</a> <li><a href="../nfs/server/debian.html">nfs::server::debian</a> <li><a href="../nfs/server/redhat.html">nfs::server::redhat</a> <li><a href="../nginx.html">nginx</a> <li><a href="../nginx/config.html">nginx::config</a> <li><a href="../nginx/nginx.html">nginx::nginx</a> <li><a href="../nginx/notice.html">nginx::notice</a> <li><a href="../nginx/notice/puppet_module_data.html">nginx::notice::puppet_module_data</a> <li><a href="../nginx/package.html">nginx::package</a> <li><a href="../nginx/package/archlinux.html">nginx::package::archlinux</a> <li><a href="../nginx/package/debian.html">nginx::package::debian</a> <li><a href="../nginx/package/freebsd.html">nginx::package::freebsd</a> <li><a href="../nginx/package/gentoo.html">nginx::package::gentoo</a> <li><a href="../nginx/package/redhat.html">nginx::package::redhat</a> <li><a href="../nginx/package/solaris.html">nginx::package::solaris</a> <li><a href="../nginx/package/suse.html">nginx::package::suse</a> <li><a href="../nginx/resource.html">nginx::resource</a> <li><a href="../nginx/resource/upstream.html">nginx::resource::upstream</a> <li><a href="../nginx/service.html">nginx::service</a> <li><a href="../nothing.html">nothing</a> <li><a href="../nothing/nothing.html">nothing::nothing</a> <li><a href="../one.html">one</a> <li><a href="../one/one.html">one::one</a> <li><a href="../profiles.html">profiles</a> <li><a href="../profiles/apache.html">profiles::apache</a> <li><a href="../profiles/base.html">profiles::base</a> <li><a href="../profiles/profiles.html">profiles::profiles</a> <li><a href="../puppet.html">puppet</a> <li><a href="../puppet/puppet.html">puppet::puppet</a> <li><a href="../roles.html">roles</a> <li><a href="../roles/roles.html">roles::roles</a> <li><a href="../roles/webserver.html">roles::webserver</a> <li><a href="../ssh_user.html">ssh_user</a> <li><a href="../stdlib.html">stdlib</a> <li><a href="../stdlib/__facts__.html">stdlib::__facts__</a> <li><a href="../stdlib/__functions__.html">stdlib::__functions__</a> <li><a href="../stdlib/__types__.html">stdlib::__types__</a> <li><a href="../stdlib/stages.html">stdlib::stages</a> <li><a href="../stdlib/stdlib.html">stdlib::stdlib</a> <li><a href="../thing.html">thing</a> <li><a href="../thing/thing.html">thing::thing</a> <li><a href="../thomas-base.html">thomas-base</a> <li><a href="../thomas-profiles.html">thomas-profiles</a> <li><a href="../thomas-roles.html">thomas-roles</a> <li><a href="../two.html">two</a> <li><a href="../two/two.html">two::two</a> <li><a href="../user.html">user</a> <li><a href="../user/developers.html">user::developers</a> <li><a href="../user/sysadmins.html">user::sysadmins</a> <li><a href="../user/virtual.html">user::virtual</a> <li><a href="../virtual.html">virtual</a> <li><a href="../virtual/virtual.html">virtual::virtual</a> <li><a href="../wordpress.html">wordpress</a> <li><a href="../wordpress/wordpress.html">wordpress::wordpress</a> </ul> </nav> </div> </nav> <div id="documentation"> <h1 class="class">class apache::peruser</h1> <div id="description" class="description"> </div><!-- description --> <section id="5Buntitled-5D" class="documentation-section"> <!-- Methods --> <section id="public-instance-5Buntitled-5D-method-details" class="method-section section"> <h3 class="section-header">Public Instance Methods</h3> <div id="method-i-multiplexer" class="method-detail "> <div class="method-heading"> <span class="method-name">multiplexer</span><span class="method-args">( $user => '::apache::user', $group => '::apache::group', $file => 'undef' )</span> </div> <div class="method-description"> </div> </div><!-- multiplexer-method --> <div id="method-i-processor" class="method-detail "> <div class="method-heading"> <span class="method-name">processor</span><span class="method-args">( $user, $group, $file => 'undef' )</span> </div> <div class="method-description"> </div> </div><!-- processor-method --> </section><!-- public-instance-method-details --> </section><!-- 5Buntitled-5D --> </div><!-- documentation --> <footer id="validator-badges"> <p><a href="http://validator.w3.org/check/referer">[Validate]</a> <p>Generated by <a href="https://github.com/rdoc/rdoc">RDoc</a> 4.0.1. <p>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish Rdoc Generator</a> 3. </footer>
{ "content_hash": "451c27837c0995570f9951baeae222ad", "timestamp": "", "source": "github", "line_count": 819, "max_line_length": 115, "avg_line_length": 32.63003663003663, "alnum_prop": 0.5988624457416555, "repo_name": "uphillian/puppetcookbook", "id": "9fba371f7f4bc9be9b9658edeaa0a40a54bc4132", "size": "26724", "binary": false, "copies": "1", "ref": "refs/heads/puppet5", "path": "10/doc/apache/peruser.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10365" }, { "name": "Emacs Lisp", "bytes": "334" }, { "name": "JavaScript", "bytes": "16758" }, { "name": "Pascal", "bytes": "4356" }, { "name": "Puppet", "bytes": "68359" }, { "name": "Ruby", "bytes": "472562" }, { "name": "Shell", "bytes": "1714" }, { "name": "Vim script", "bytes": "28" } ], "symlink_target": "" }
create schema v5_dashboard;
{ "content_hash": "1199434216eeddb1f14e0085048b6c32", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 27, "avg_line_length": 28, "alnum_prop": 0.8214285714285714, "repo_name": "votinginfoproject/data-processor", "id": "3d0791a103808fcfccf3bd53cd4c3303a21bd2c1", "size": "28", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "resources/migrations/20161130-01-create-dashboard-schema.up.sql", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Clojure", "bytes": "734456" }, { "name": "Dockerfile", "bytes": "361" }, { "name": "PLpgSQL", "bytes": "147808" }, { "name": "Shell", "bytes": "2422" } ], "symlink_target": "" }
#ifdef HAVE_OPENSSL #include <openssl/md5.h> #elif !defined(_MD5_H) #define _MD5_H /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned int MD5_u32plus; typedef struct { MD5_u32plus lo, hi; MD5_u32plus a, b, c, d; unsigned char buffer[64]; MD5_u32plus block[16]; } MD5_CTX; extern void MD5_Init(MD5_CTX *ctx); extern void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size); extern void MD5_Final(unsigned char *result, MD5_CTX *ctx); #endif
{ "content_hash": "cd953c98b799b1ef9269d7fd1791438c", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 75, "avg_line_length": 23.318181818181817, "alnum_prop": 0.6783625730994152, "repo_name": "kikoqiu/r2diff", "id": "377b7aa0da41b9348b46c7e8bc5a94dadf4fae31", "size": "1458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "r2diff/md5.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package jenkins.metrics.impl; import com.codahale.metrics.health.HealthCheck; import com.codahale.metrics.health.jvm.ThreadDeadlockHealthCheck; import jenkins.metrics.api.HealthCheckProvider; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.Extension; import hudson.PluginManager; import hudson.model.Computer; import hudson.model.ComputerSet; import hudson.node_monitors.DiskSpaceMonitor; import hudson.node_monitors.DiskSpaceMonitorDescriptor; import hudson.node_monitors.TemporarySpaceMonitor; import jenkins.model.Jenkins; import java.util.List; import java.util.Map; /** * Provides some simple standard health checks. */ @Extension public class JenkinsHealthCheckProviderImpl extends HealthCheckProvider { @NonNull @Override public Map<String, HealthCheck> getHealthChecks() { return checks( check("plugins", new HealthCheck() { @Override protected Result check() throws Exception { List<PluginManager.FailedPlugin> failedPlugins = Jenkins.getInstance().getPluginManager().getFailedPlugins(); if (failedPlugins.isEmpty()) { return Result.healthy("No failed plugins"); } StringBuilder failedNames = new StringBuilder(); boolean first = true; for (PluginManager.FailedPlugin p: failedPlugins) { if (first) first = false; else failedNames.append("; "); failedNames.append(p.name); } return Result.unhealthy("There are %s failed plugins: %s", failedPlugins.size(), failedNames); } }), check("thread-deadlock", new ThreadDeadlockHealthCheck()), check("disk-space", new HealthCheck() { @Override protected Result check() throws Exception { DiskSpaceMonitor m = ComputerSet.getMonitors().get(DiskSpaceMonitor.class); if (m == null) { return Result.healthy(); } for (Computer c : Jenkins.getInstance().getComputers()) { DiskSpaceMonitorDescriptor.DiskSpace freeSpace = m.getFreeSpace(c); if (freeSpace != null && m.getThresholdBytes() > freeSpace.size) { return Result.unhealthy("Only %s Gb free on %s", freeSpace.getGbLeft(), c.getNode() instanceof Jenkins ? "(master)" : c.getName()); } } return Result.healthy(); } }, ComputerSet.getMonitors().get(DiskSpaceMonitor.class) != null), check("temporary-space", new HealthCheck() { @Override protected Result check() throws Exception { TemporarySpaceMonitor m = ComputerSet.getMonitors().get(TemporarySpaceMonitor.class); if (m == null) { return Result.healthy(); } for (Computer c : Jenkins.getInstance().getComputers()) { DiskSpaceMonitorDescriptor.DiskSpace freeSpace = m.getFreeSpace(c); if (freeSpace != null && m.getThresholdBytes() > freeSpace.size) { return Result.unhealthy("Only %s Gb free on %s", freeSpace.getGbLeft(), c.getNode() instanceof Jenkins ? "(master)" : c.getName()); } } return Result.healthy(); } }, ComputerSet.getMonitors().get(DiskSpaceMonitor.class) != null) ); } }
{ "content_hash": "5a77ca55a4743d5353db9d954a79bd52", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 118, "avg_line_length": 48.18604651162791, "alnum_prop": 0.5127895752895753, "repo_name": "oleg-nenashev/metrics-plugin", "id": "35263f2e66b69d6c2edb00163bd4725f8f1b7133", "size": "5286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/jenkins/metrics/impl/JenkinsHealthCheckProviderImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3347" }, { "name": "Java", "bytes": "155791" }, { "name": "Shell", "bytes": "537" } ], "symlink_target": "" }
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> extern bool fWalletUnlockStakingOnly; AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case UnlockStaking: ui->stakingCheckBox->setChecked(true); ui->stakingCheckBox->show(); // fall through case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR ILOVEYOUCOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("ILoveYouCoins will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your iloveyoucoins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case UnlockStaking: case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked(); QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case UnlockStaking: case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); }
{ "content_hash": "9648dd26f618f7758d4b6cdb0ff54989", "timestamp": "", "source": "github", "line_count": 261, "max_line_length": 200, "avg_line_length": 39.21455938697318, "alnum_prop": 0.5598436736687836, "repo_name": "dev-ily/ILoveYouCoins", "id": "7e2e60757da58ca83aef63754608b0bdbab17947", "size": "10235", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/qt/askpassphrasedialog.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "32009" }, { "name": "C++", "bytes": "2755377" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50620" }, { "name": "Makefile", "bytes": "12807" }, { "name": "NSIS", "bytes": "6067" }, { "name": "Objective-C", "bytes": "1052" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "36247" }, { "name": "QMake", "bytes": "30684" }, { "name": "Shell", "bytes": "8627" } ], "symlink_target": "" }
using MaratonBusiness.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; namespace MaratonBusiness.Code { public class MaratonAPI { string ip = "10.0.0.219"; int port = 91; string PostData(string url , string json) { WebClient wc = new WebClient(); wc.Headers["Content-Type"] = "application/json"; return wc.UploadString("http://" + ip + url, "POST", json); } T PostData<T>(string url, string json) { //var t = Models.CFService.Config(); //ip = t.MaratonAddress;// System.Configuration.ConfigurationManager.AppSettings["MaratonIP"]; //port = t.MaratonPort; //int.TryParse(System.Configuration.ConfigurationManager.AppSettings["MaratonPort"] , out port); WebClient wc = new WebClient(); string data = wc.UploadString("http://" + ip+ ":" + port + url, "POST", json); try { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(data); } catch { return default(T); } } public MaratonAPI() { var t = Models.CFService.Config(); ip = t.MaratonAddress; port = t.MaratonPort; } public MaratonAPI(string ip) { this.ip = ip; } public List<Message.MessageServantStateReply> ServantList() { List<Message.MessageServantStateReply> result = new List<Message.MessageServantStateReply>(); Message.MessageServantState state = new Message.MessageServantState(); state.code = 0; var msg = PostData<List<Message.MessageServantStateReply>>("/servant/status", Newtonsoft.Json.JsonConvert.SerializeObject(state)); result.AddRange(msg); //sock.Send<Message.MessageServantState>(Message.MessageServantState.SerializeToBytes(state)); //var msg = sock.Receive() as Message.MessageServantStateReply; //sock.Close(); return result; } public Message.MessageTaskDeliverReply TaskDeliver(DbTask task , DbPipeline line) { var servants = ServantList(); Message.MessageTaskDeliver td = new Message.MessageTaskDeliver(); td.id = task.Id; td.input = task.Inputs; td.servants = servants.Select(m=>m.id).ToList(); td.resources = new List<string>(); td.isParallel = line.IsParallel; td.originalID = td.id; td.pipeline = (new Message.MessagePipeline() { id = line.Id, name = line.Name, pipes = new List<Message.MessagePipe>() }); using (MDB db = new MDB()) { for (int i = 0; i < line.PipeIds.Count; i++) { var pipe = db.FindOne<DbPipe>(x => x.Id == line.PipeIds[i]); var p = new Message.MessagePipe() { id = pipe.Id, executor = pipe.Executor, multipleInput = pipe.IsMultipleInput, multipleThread = pipe.IsMultipleThread, parameters = pipe.Parameters, name = pipe.Name }; td.pipeline.pipes.Add(p); } } var msg = PostData<Message.MessageTaskDeliverReply>("/task/deliver", Newtonsoft.Json.JsonConvert.SerializeObject(td)); //sock.Send<Message.MessageTaskDeliver>(Message.MessageTaskDeliver.SerializeToBytes(td)); //msg = sock.Receive() as Message.MessageTaskDeliverReply; //sock.Close(); return msg; } } }
{ "content_hash": "c567ab055669c8be08cca1d6c832f08d", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 142, "avg_line_length": 35.02654867256637, "alnum_prop": 0.5336028297119757, "repo_name": "Yhgenomics/MaratonBusiness", "id": "717acfede412e60aa37fba54333ec5ac75ba1c4a", "size": "3960", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TestEmpty/Code/MaratonAPI.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "C#", "bytes": "318177" }, { "name": "CSS", "bytes": "195591" }, { "name": "HTML", "bytes": "5200" }, { "name": "JavaScript", "bytes": "468909" }, { "name": "Protocol Buffer", "bytes": "1142" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.shb.somershotbagels"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".Splash" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SHBActivity" android:screenOrientation="portrait"> </activity> <activity android:name=".CheckoutActivity" android:screenOrientation="portrait" > </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> </manifest>
{ "content_hash": "6cc3974aa7bd50c85b0800b891cff239", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 91, "avg_line_length": 42.46666666666667, "alnum_prop": 0.652276295133438, "repo_name": "hunterdquant/SomersHotBagels", "id": "897afd331499cf2ffc45f302d511389320a5c098", "size": "1274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/AndroidManifest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "83592" } ], "symlink_target": "" }