text
stringlengths
2
1.04M
meta
dict
package org.apache.avro.hadoop.io; import org.apache.avro.Schema; import org.apache.avro.io.BinaryData; import org.apache.avro.mapred.AvroKey; import org.apache.avro.mapreduce.AvroJob; import org.apache.avro.reflect.ReflectData; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.RawComparator; /** * The {@link org.apache.hadoop.io.RawComparator} used by jobs configured with * {@link org.apache.avro.mapreduce.AvroJob}. * * <p>Compares AvroKeys output from the map phase for sorting.</p> */ public class AvroKeyComparator<T> extends Configured implements RawComparator<AvroKey<T>> { /** The schema of the Avro data in the key to compare. */ private Schema mSchema; /** {@inheritDoc} */ @Override public void setConf(Configuration conf) { super.setConf(conf); if (null != conf) { // The MapReduce framework will be using this comparator to sort AvroKey objects // output from the map phase, so use the schema defined for the map output key. mSchema = AvroJob.getMapOutputKeySchema(conf); } } /** {@inheritDoc} */ @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return BinaryData.compare(b1, s1, b2, s2, mSchema); } /** {@inheritDoc} */ @Override public int compare(AvroKey<T> x, AvroKey<T> y) { return ReflectData.get().compare(x.datum(), y.datum(), mSchema); } }
{ "content_hash": "5124df6359ccf2cf8dfe7e80022bc202", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 91, "avg_line_length": 31.391304347826086, "alnum_prop": 0.7070637119113573, "repo_name": "RallySoftware/avro", "id": "1f7c5ee8490b15a670ac049547f55738669352f5", "size": "2251", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "lang/java/mapred/src/main/java/org/apache/avro/hadoop/io/AvroKeyComparator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1154701" }, { "name": "C#", "bytes": "416924" }, { "name": "C++", "bytes": "614960" }, { "name": "Java", "bytes": "2618505" }, { "name": "JavaScript", "bytes": "91289" }, { "name": "PHP", "bytes": "204357" }, { "name": "Python", "bytes": "254112" }, { "name": "Ruby", "bytes": "116997" }, { "name": "Shell", "bytes": "323650" }, { "name": "VimL", "bytes": "2764" } ], "symlink_target": "" }
<? include "session.php"; include "DB_connection.php"; include "conn.php"; include "header1.html"; $sql=conn("SELECT stu_name,stu_br,stu_roll,stu_reg,stu_sem,stu_sec,stu_yr_add,stu_cgpa FROM student WHERE stu_reg='$_SESSION[reg]'"); // find out the number of columns in result $column_count = mysql_num_fields($sql) or die("display_db_query:" . mysql_error()); // Here the table attributes from the $table_params variable are added print("<TABLE border='3' >\n"); // print a bold header at top of table print("<TR>"); print("<TH>Name</th>"); print("<TH>Branch</th>"); print("<TH>Roll No</th>"); print("<TH>Reg No</th>"); print("<TH>Semester</th>"); print("<TH>Section</th>"); print("<TH>Year Of Admission</th>"); print("<TH>CGPA</th>"); print("</TR>\n"); // print the body of the table while($row=mysql_fetch_row($sql)) { print("<TR ALIGN=CENTER VALIGN=TOP>"); for($column_num = 0;$column_num < $column_count;$column_num++) { print("<TD>$row[$column_num]</TD>\n");} print("</TR>\n"); } print("</TABLE>\n"); ?> <br> <h2>In case of any error in this information,please contact the system administrator</h2><p> <input type="button" name="goBack" value="Go Back" onclick="history.back(1)"> <p>&nbsp; </p> </body></html>
{ "content_hash": "6476f21f5dc2a735fa529858e7af5a97", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 133, "avg_line_length": 27.210526315789473, "alnum_prop": 0.5170857511283043, "repo_name": "aloktherocker/student-info-mgmt-sys", "id": "e3c1a69d9c98f895d5f6d7ffdb51c1692cd254bd", "size": "1551", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SIMS/mit/info.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import time from datetime import datetime from webgpio.constants import (REDIS_DEVICE_STATUS_KEY, REDIS_USER_TASK_KEY, REDIS_TASK_ACTIONS, REDIS_DEVICE_TASK_VALUE) async def device_status_update(redis, device): async with redis.get() as conn: await conn.set(REDIS_DEVICE_STATUS_KEY.format(device=device), time.time()) async def gather_redis_tasks(redis, user): async with redis.get() as conn: return await conn.zrangebyscore( REDIS_USER_TASK_KEY.format(user=user), 0, float('+inf')) async def device_tasks_add(redis, db, user, device, gpios=None, **kwargs): gpios = gpios or [] action = kwargs.get('action') try: gpio = int(kwargs.get('gpio')) except (TypeError, ValueError): gpio = 0 if gpio in gpios and action in REDIS_TASK_ACTIONS: dt_stamps = kwargs.get('date', '').split(',') # try to validate timestamps try: timestamps = [datetime.strptime(date, '%Y-%m-%dT%H:%M:%S') for date in dt_stamps] except ValueError: timestamps = [] key = REDIS_USER_TASK_KEY.format(user=user) async with redis.get() as conn: for timestamp in timestamps: tm_stamp = int(timestamp.timestamp()) value = REDIS_DEVICE_TASK_VALUE.format(timestamp=tm_stamp, device=device, gpio=gpio, action=action) await conn.zadd(key, tm_stamp, value) async def device_task_delete(redis, user, value): key = REDIS_USER_TASK_KEY.format(user=user) ret = None async with redis.get() as conn: ret = await conn.zrem(key, value) return ret
{ "content_hash": "eee662b770a85f1bcf892ae70cfe6cb4", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 76, "avg_line_length": 33.05263157894737, "alnum_prop": 0.5498938428874734, "repo_name": "dmitriyminer/webgpio", "id": "521ac519dd2d250f367c8fb012781723413cd729", "size": "1884", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webgpio/device/redis.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "150268" }, { "name": "HTML", "bytes": "19961" }, { "name": "Mako", "bytes": "494" }, { "name": "Python", "bytes": "44297" } ], "symlink_target": "" }
#include <assert.h> #include <string.h> #include <errno.h> #include "qterror.h" /* * An array to contain valid error codes and corresponding descriptive * strings. The member err contains the actual error code. The member * str is a pointer to a constant string which describes the error. */ static struct { const enum qterror err; const char* const str; } qterror_map[QTELAST] = { { QTSUCCESS, "Success" }, { QTEERRNO, "Check errno for more information" }, { QTEFQFULL, "The function queue was full" }, { QTEFQEMPTY, "The function queue was empty" }, { QTEPTMLOCK, "An error occurred while locking the mutex, check errno for more information" }, { QTEPTMTRYLOCK, "An error occurred while locking the mutex without blocking, check errno for more information" }, { QTEPTMUNLOCK, "An error occurred while unlocking the mutex, check errno for more information" }, { QTEPTMAINIT, "An error occurred while initializing the mutex attributes" }, { QTEPTMDESTROY, "An error occurred while destroying a mutex, check errno for more information" }, { QTEPTONCE, "An error occurred during dynamic initialization, check errno for more information" }, { QTEPTCREATE, "An error occurred while creating a thread, check errno for more information" }, { QTEMALLOC, "An error occurred while allocating memory, check errno for more information" }, { QTEPTCINIT, "An error occurred while initializing a condition variable, check errno for more information" }, { QTEPTCDESTROY, "An error occurred while destroying a condition variable, check errno for more information" }, { QTEINVALID, "An invalid value was encountered" }, { QTEPTMINIT, "An error occurred while initializing the mutex" }, }; /* * Copy a string from src to dst. * * This procedure copies at most n characters from the buffer pointed to * by src to the buffer pointed to by dst. The character after the last * character copied is set to NUL. The string dst is always properly * null-terminated. This procedure returns the value of dst. Neither the * value of dst nor the value of src may be NULL. The buffer pointed to * by src must be null-terminated unless its length is n or less. */ static char* qtstrncpy(char* dst, const char* src, size_t n) { assert(dst != NULL); assert(src != NULL); dst[0] = '\0'; return strncat(dst, src, n); } /* * Retrieve a string describing the given error code. * * This procedure copies at most len-1 bytes from the error description * string in qterror_map which corresponds to the given error code into * the buffer pointed to by buf. This procedure always succeeds and * returns 0. The value of err must be a valid qterror value. The value * of buf must not be NULL. If the buffer pointed to by buf is modified * then it will be null-terminated. */ int qtstrerror_r(enum qterror err, char* buf, size_t len) { if(len > 0) { if(err >= QTELAST || err < QTSUCCESS) { errno = EINVAL; return 1; } assert(err == qterror_map[err].err); (void) qtstrncpy(buf, qterror_map[err].str, len - 1); if(strlen(qterror_map[err].str) >= len - 2) { errno = ERANGE; return 1; } } return 0; }
{ "content_hash": "afbca2061da71c511d5629d16a54d27c", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 115, "avg_line_length": 36.02298850574713, "alnum_prop": 0.721442246330568, "repo_name": "byannoni/qthreads", "id": "927dbdee6032d4f3e098788791aaf289b0b05581", "size": "3732", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "qterror.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "45812" }, { "name": "Makefile", "bytes": "1825" } ], "symlink_target": "" }
layout: "azurerm" page_title: "Azure Resource Manager: azure_virtual_network" sidebar_current: "docs-azurerm-resource-network-virtual-network" description: |- Creates a new virtual network including any configured subnets. Each subnet can optionally be configured with a security group to be associated with the subnet. --- # azurerm\_virtual\_network Creates a new virtual network including any configured subnets. Each subnet can optionally be configured with a security group to be associated with the subnet. ## Example Usage ``` resource "azurerm_virtual_network" "test" { name = "virtualNetwork1" resource_group_name = "${azurerm_resource_group.test.name}" address_space = ["10.0.0.0/16"] location = "West US" dns_servers = ["10.0.0.4", "10.0.0.5"] subnet { name = "subnet1" address_prefix = "10.0.1.0/24" } subnet { name = "subnet2" address_prefix = "10.0.2.0/24" } subnet { name = "subnet3" address_prefix = "10.0.3.0/24" security_group = "${azurerm_network_security_group.test.id}" } tags { environment = "Production" } } ``` ## Argument Reference The following arguments are supported: * `name` - (Required) The name of the virtual network. Changing this forces a new resource to be created. * `resource_group_name` - (Required) The name of the resource group in which to create the virtual network. * `address_space` - (Required) The address space that is used the virtual network. You can supply more than one address space. Changing this forces a new resource to be created. * `location` - (Required) The location/region where the virtual network is created. Changing this forces a new resource to be created. * `dns_servers` - (Optional) List of IP addresses of DNS servers * `subnet` - (Optional) Can be specified multiple times to define multiple subnets. Each `subnet` block supports fields documented below. * `tags` - (Optional) A mapping of tags to assign to the resource. The `subnet` block supports: * `name` - (Required) The name of the subnet. * `address_prefix` - (Required) The address prefix to use for the subnet. * `security_group` - (Optional) The Network Security Group to associate with the subnet. (Referenced by `id`, ie. `azurerm_network_security_group.test.id`) ## Attributes Reference The following attributes are exported: * `id` - The virtual NetworkConfiguration ID. * `name` - The name of the virtual network. * `resource_group_name` - The name of the resource group in which to create the virtual network. * `location` - The location/region where the virtual network is created * `address_space` - The address space that is used the virtual network. ## Import Virtual Networks can be imported using the `resource id`, e.g. ``` terraform import azurerm_virtual_network.testNetwork /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/mygroup1/providers/Microsoft.Network/virtualNetworks/myvnet1 ```
{ "content_hash": "3d299fc1fef9b8837178cb5d642e5535", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 180, "avg_line_length": 30.747474747474747, "alnum_prop": 0.7072930354796321, "repo_name": "stardog-union/stardog-graviton", "id": "987cb15e1978369ad26b19537b989c5958153620", "size": "3048", "binary": false, "copies": "21", "ref": "refs/heads/develop", "path": "vendor/github.com/hashicorp/terraform/website/source/docs/providers/azurerm/r/virtual_network.html.markdown", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "BitBake", "bytes": "50002" }, { "name": "Dockerfile", "bytes": "1212" }, { "name": "Go", "bytes": "195457" }, { "name": "HCL", "bytes": "26587" }, { "name": "Makefile", "bytes": "602" }, { "name": "Python", "bytes": "43992" }, { "name": "Shell", "bytes": "11173" }, { "name": "Smarty", "bytes": "2192" } ], "symlink_target": "" }
exports.logout = { name: 'logout', description: 'ends the user session', inputs: { 'required' : [], 'optional' : [] }, // authorisedGroups: void(0), blockedConnectionTypes: [], outputExample: { }, run: function(api, connection, next){ api.session.delete(connection, next); } };
{ "content_hash": "5154474cb0f58cd734d82608872a69ec", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 41, "avg_line_length": 20.6, "alnum_prop": 0.6084142394822006, "repo_name": "agilgur5/NeverEndingBookBackEnd", "id": "490ce443737b0143bddbee132db5b6c24a8a4511", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "actions/logout.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "24548" } ], "symlink_target": "" }
#import "ANDescriptor.h" #define kClientConfigurationDescriptorUUIDString @"2902" @interface ANClientConfigurationDescriptor : ANDescriptor @end
{ "content_hash": "6721a3a1a1ae6c48b1f3598451c10875", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 57, "avg_line_length": 15.1, "alnum_prop": 0.8211920529801324, "repo_name": "AngelSensor/angel-sdk", "id": "e23b3ece6269da8f078e23b6eb90885c2bac1e43", "size": "1741", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "iOS/SDK/Services/Descriptors/ANClientConfigurationDescriptor.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "30660" }, { "name": "Java", "bytes": "161924" }, { "name": "Objective-C", "bytes": "1820098" }, { "name": "Python", "bytes": "76162" }, { "name": "Ruby", "bytes": "63" }, { "name": "Shell", "bytes": "7953" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8" ?> <INTERACTIONS> <INTERACTION> <SOURCE> <CLINICAL_SOURCE>ANSM</CLINICAL_SOURCE> <SOURCE_FILE>30-AMBRISENTAN.html </SOURCE_FILE> </SOURCE> <DRUG1> <DRUG name="AMBRISENTAN" rxcui="358274"> <ATC code="C02KX02" /> </DRUG> </DRUG1> <DRUG2> <DRUG name="CICLOSPORIN" rxcui="3008"> <ATC code="S01XA18" /> </DRUG> </DRUG2> <DESCRIPTION>Doubling of the concentrations of ambrisentan, with increase of the vasodilator effect (severe headaches )</DESCRIPTION> <SEVERITY>Take into account</SEVERITY> </INTERACTION> </INTERACTIONS>
{ "content_hash": "05e144a6e090e600b0875d0bb8c0e137", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 133, "avg_line_length": 25.272727272727273, "alnum_prop": 0.7320143884892086, "repo_name": "glilly/osdi", "id": "362289ebcbf6ca549acf41378a22181b16a5f910", "size": "556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "eng_sept2016_v3/sept2016_tables_xml/30-AMBRISENTAN.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "4008323" }, { "name": "Perl", "bytes": "37370" }, { "name": "Shell", "bytes": "213" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) sisane: The stunning micro-library that helps you to develop easily AJAX web applications by using Angular.js 1.x & sisane-server sisane is distributed under the MIT License (MIT) Sources at https://github.com/rafaelaznar/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <div id="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading" style="font-family:Oswald , serif;" ng-include="'js/system/header.html'"></div> <div class="panel-body" ng-cloak> <div class="row-fluid" ng-show="status"> <div class="col-xs-12"> <div class="alert alert-danger" role="alert"> <br> <h3 class="bg-danger">{{status}}</h3> <br> <a class="btn btn-default" ng-click="back()">Volver</a> </div> </div> </div> <div class="row-fluid" ng-show="!status"> <div class="span6 offset3"> <table class="table table-striped table-condensed"> <thead> <tr> <th>campo</th> <th>valor</th> </tr> </thead> <tbody> <tr ng-repeat="f in fields" class="text-left"> <td>{{f.longname}}</td> <!-- ----------------------------- --> <td ng-show="f.type == 'id'"><b>{{bean[f.name]}}</b></td> <td ng-show="f.type == 'textarea'" ng-bind-html="bean[f.name] | breakFilter"></td> <td ng-show="f.type == 'date'">{{bean[f.name]}}</td> <td ng-show="f.type == 'integer'">{{bean[f.name]}}</td> <td ng-show="f.type == 'decimal'">{{bean[f.name]}}</td> <td ng-show="f.type == 'text'">{{bean[f.name]}}</td> <td ng-show="f.type == 'boolean'" ng-bind-html="bean[f.name] | booleanizate"></td> <!-- ----------------------------- --> <td ng-show="f.name == 'obj_medicamento'">{{bean[f.name].descripcion}}</td> </tr> </tbody> </table> <div class="text-right"> <a class="btn btn-primary" href="{{ob}}/edit/{{bean.id}}">Editar</a> <a class="btn btn-danger" href="{{ob}}/remove/{{bean.id}}">Borrar</a> <a class="btn btn-default" ng-click="plist()">Ir al listado de Tipo de muestra</a> <a class="btn btn-default" ng-click="close()">Cerrar</a> </div> </div> </div> </div> <div class="panel-footer" style="font-family: Questrial, serif;" ng-include="'js/system/footer.html'"></div> </div> </div> </div> </div> </div>
{ "content_hash": "78f3f9b9c81f6f56b40d80f29ae2dfae", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 128, "avg_line_length": 56.87356321839081, "alnum_prop": 0.44421988682295876, "repo_name": "Ecoivan/sisane-client", "id": "7cee2b394e414649bc21890034ec6967954fc6a7", "size": "4948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public_html/js/tipomuestra/view.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1079" }, { "name": "CSS", "bytes": "150982" }, { "name": "HTML", "bytes": "1713745" }, { "name": "JavaScript", "bytes": "1019614" } ], "symlink_target": "" }
/* tslint:disable */ import { ReaderFragment } from "relay-runtime"; export type PriceSummary_calculatedCost = { readonly buyersPremium: { readonly display: string | null; } | null; readonly subtotal: { readonly display: string | null; } | null; readonly " $refType": "PriceSummary_calculatedCost"; }; const node: ReaderFragment = (function(){ var v0 = [ { "kind": "ScalarField", "alias": null, "name": "display", "args": null, "storageKey": null } ]; return { "kind": "Fragment", "name": "PriceSummary_calculatedCost", "type": "CalculatedCost", "metadata": null, "argumentDefinitions": [], "selections": [ { "kind": "LinkedField", "alias": null, "name": "buyersPremium", "storageKey": null, "args": null, "concreteType": "Money", "plural": false, "selections": (v0/*: any*/) }, { "kind": "LinkedField", "alias": null, "name": "subtotal", "storageKey": null, "args": null, "concreteType": "Money", "plural": false, "selections": (v0/*: any*/) } ] }; })(); (node as any).hash = '9c7744edb1c8e9493c18b47100faee78'; export default node;
{ "content_hash": "338453877869fa31eec35e1cb15945fd", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 56, "avg_line_length": 21.473684210526315, "alnum_prop": 0.5637254901960784, "repo_name": "artsy/emission", "id": "622fac6c3ad616e005f340dd340a7de6823abe1d", "size": "1224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/__generated__/PriceSummary_calculatedCost.graphql.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "104" }, { "name": "HTML", "bytes": "6064" }, { "name": "JavaScript", "bytes": "37812" }, { "name": "Makefile", "bytes": "3788" }, { "name": "Objective-C", "bytes": "304142" }, { "name": "Ruby", "bytes": "11317" }, { "name": "Shell", "bytes": "462" }, { "name": "Swift", "bytes": "116" }, { "name": "TypeScript", "bytes": "2067401" } ], "symlink_target": "" }
<CapabilityStatement xmlns="http://hl7.org/fhir"> <status value="draft"/> <date value="2017-03-21T09:00:00-05:00"/> <description value="FHIR CapabilityStatement"/> <kind value="capability"/> <fhirVersion value="3.0.0"/> <acceptUnknown value="both"/> <format value="xml"/> <format value="json"/> <rest> <mode value="server"/> <resource> <type value="Patient"/> <interaction> <code value="create"/> </interaction> <interaction> <code value="read"/> </interaction> <interaction> <code value="update"/> </interaction> <interaction> <code value="delete"/> </interaction> <interaction> <code value="history-instance"/> </interaction> <interaction> <code value="search-type"/> </interaction> <updateCreate value="true"/> <searchParam> <name value="family"/> <type value="string"/> </searchParam> <searchParam> <name value="given"/> <type value="string"/> </searchParam> </resource> </rest> </CapabilityStatement>
{ "content_hash": "e39eeef89ca1df04e9e409d15a51a345", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 49, "avg_line_length": 23.6046511627907, "alnum_prop": 0.6315270935960591, "repo_name": "fhir-crucible/plan_executor", "id": "9eb1d089314ff6854cbb97ab7a4e457754929f2d", "size": "1015", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/tests/testscripts/scripts/connectathon/Patient-01-Intro/_reference/capabilities/PatientCapabilityStatement.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "7504" }, { "name": "Ruby", "bytes": "617980" } ], "symlink_target": "" }
Then google-cloud-trace gem provides a Rack Middleware class that integrates with Rack-based application frameworks, such as Rails and Sinatra. When installed, the middleware collects performance traces of requests and, subject to sampling constraints, submits them to the Stackdriver Trace service. Additionally, the google-cloud-trace gem provides a Railtie class that automatically enables the Rack Middleware in Rails applications when used. ## Configuration The default configuration enables Stackdriver instrumentation features to run on Google Cloud Platform. You can easily configure the instrumentation library if you want to run on a non Google Cloud environment or you want to customize the default behavior. See the [Configuration Guide](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/stackdriver/guides/instrumentation_configuration) for full configuration parameters. ## Rails Integration To use the Stackdriver Logging Railtie for Ruby on Rails applications, simply add this line to config/application.rb: ```ruby require "google/cloud/trace/rails" ``` Alternatively, check out the [stackdriver](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/stackdriver) gem, which enables this Railtie by default. ## Rack Integration Other Rack base frameworks can also directly leverage the built-in Middleware. ```ruby require "google/cloud/trace" use Google::Cloud::Trace::Middleware ```
{ "content_hash": "cd6671f288be58a89bc4ad8a7dc144c4", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 299, "avg_line_length": 47.833333333333336, "alnum_prop": 0.8132404181184669, "repo_name": "swcloud/google-cloud-ruby", "id": "b00f230fcb8a260ab3eab3ab7367e98b152e609a", "size": "1472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "google-cloud-trace/docs/instrumentation.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "22511" }, { "name": "CSS", "bytes": "1422" }, { "name": "DIGITAL Command Language", "bytes": "2216" }, { "name": "HTML", "bytes": "10040" }, { "name": "JavaScript", "bytes": "1862" }, { "name": "Ruby", "bytes": "6810261" } ], "symlink_target": "" }
package com.base.modules.sys.web; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.base.common.util.JsonResult; import com.base.modules.sys.entity.User; import com.base.modules.sys.service.IUserService; /** * @desc * @author zhengzy * @version 2016年6月12日 */ @Controller @RequestMapping("/user") public class UserController { private static Logger logger = Logger.getLogger(UserController.class); @Resource public IUserService userService; @ResponseBody @RequestMapping(value = "/getUserById", method = RequestMethod.POST) public JsonResult getUserById() { JsonResult json = new JsonResult(); User user = userService.getUserById(1); if (user == null) { json.failure(); } else { // 如果有中文,要考虑乱码问题,此处不处理 json.success(user); } return json; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String login(){ logger.info("登录成功") ; // return "redirect:main"; return "main"; } }
{ "content_hash": "1f07be9b3506f05fa6586d908d678b2e", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 71, "avg_line_length": 24.1, "alnum_prop": 0.7485477178423237, "repo_name": "zheng-zy/zssm", "id": "a4f7400ea234d1513352cce7c54404c8f6f4c235", "size": "1257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/base/modules/sys/web/UserController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "139" }, { "name": "CSS", "bytes": "1336354" }, { "name": "HTML", "bytes": "178709" }, { "name": "Java", "bytes": "89543" }, { "name": "JavaScript", "bytes": "1162424" } ], "symlink_target": "" }
{% spaceless %} {% if support_email_header %} {{support_email_header|safe}} {% endif %} {% endspaceless %} Hello {{user}}, Your resource request for {{request}} has been denied. Reason: {{reason}} If you have questions you may contact us at {{support_email}}. Thank you, {% spaceless %} {% if support_email_footer %} {{support_email_footer|safe}} {% endif %} {% endspaceless %}
{ "content_hash": "857bcf0c805401238aa18ac9c9481036", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 62, "avg_line_length": 20.105263157894736, "alnum_prop": 0.6649214659685864, "repo_name": "CCI-MOC/GUI-Backend", "id": "24d38980d2b4ed6a75c3a9ca8579b2640435181b", "size": "382", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/templates/core/email/resource_request_denied.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "11571" }, { "name": "Python", "bytes": "2565922" }, { "name": "Ruby", "bytes": "1345" }, { "name": "Shell", "bytes": "42018" } ], "symlink_target": "" }
package org.elasticsearch.example.expertscript; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.Term; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.ScriptPlugin; import org.elasticsearch.script.ScoreScript; import org.elasticsearch.script.ScoreScript.LeafFactory; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.script.ScriptEngine; import org.elasticsearch.script.ScriptFactory; import org.elasticsearch.search.lookup.SearchLookup; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Collection; import java.util.Map; import java.util.Set; /** * An example script plugin that adds a {@link ScriptEngine} * implementing expert scoring. */ public class ExpertScriptPlugin extends Plugin implements ScriptPlugin { @Override public ScriptEngine getScriptEngine( Settings settings, Collection<ScriptContext<?>> contexts ) { return new MyExpertScriptEngine(); } /** An example {@link ScriptEngine} that uses Lucene segment details to * implement pure document frequency scoring. */ // tag::expert_engine private static class MyExpertScriptEngine implements ScriptEngine { @Override public String getType() { return "expert_scripts"; } @Override public <T> T compile( String scriptName, String scriptSource, ScriptContext<T> context, Map<String, String> params ) { if (context.equals(ScoreScript.CONTEXT) == false) { throw new IllegalArgumentException(getType() + " scripts cannot be used for context [" + context.name + "]"); } // we use the script "source" as the script identifier if ("pure_df".equals(scriptSource)) { ScoreScript.Factory factory = new PureDfFactory(); return context.factoryClazz.cast(factory); } throw new IllegalArgumentException("Unknown script name " + scriptSource); } @Override public void close() { // optionally close resources } @Override public Set<ScriptContext<?>> getSupportedContexts() { return Set.of(ScoreScript.CONTEXT); } private static class PureDfFactory implements ScoreScript.Factory, ScriptFactory { @Override public boolean isResultDeterministic() { // PureDfLeafFactory only uses deterministic APIs, this // implies the results are cacheable. return true; } @Override public LeafFactory newFactory( Map<String, Object> params, SearchLookup lookup ) { return new PureDfLeafFactory(params, lookup); } } private static class PureDfLeafFactory implements LeafFactory { private final Map<String, Object> params; private final SearchLookup lookup; private final String field; private final String term; private PureDfLeafFactory( Map<String, Object> params, SearchLookup lookup) { if (params.containsKey("field") == false) { throw new IllegalArgumentException( "Missing parameter [field]"); } if (params.containsKey("term") == false) { throw new IllegalArgumentException( "Missing parameter [term]"); } this.params = params; this.lookup = lookup; field = params.get("field").toString(); term = params.get("term").toString(); } @Override public boolean needs_score() { return false; // Return true if the script needs the score } @Override public ScoreScript newInstance(LeafReaderContext context) throws IOException { PostingsEnum postings = context.reader().postings( new Term(field, term)); if (postings == null) { /* * the field and/or term don't exist in this segment, * so always return 0 */ return new ScoreScript(params, lookup, context) { @Override public double execute( ExplanationHolder explanation ) { return 0.0d; } }; } return new ScoreScript(params, lookup, context) { int currentDocid = -1; @Override public void setDocument(int docid) { /* * advance has undefined behavior calling with * a docid <= its current docid */ if (postings.docID() < docid) { try { postings.advance(docid); } catch (IOException e) { throw new UncheckedIOException(e); } } currentDocid = docid; } @Override public double execute(ExplanationHolder explanation) { if (postings.docID() != currentDocid) { /* * advance moved past the current doc, so this * doc has no occurrences of the term */ return 0.0d; } try { return postings.freq(); } catch (IOException e) { throw new UncheckedIOException(e); } } }; } } } // end::expert_engine }
{ "content_hash": "c56a33571604dba5a8b8b4ac730e93db", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 75, "avg_line_length": 36.78212290502793, "alnum_prop": 0.5031895504252734, "repo_name": "robin13/elasticsearch", "id": "7281c6b2be0657464af45d820fa5ed5ead6b7e95", "size": "6937", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "plugins/examples/script-expert-scoring/src/main/java/org/elasticsearch/example/expertscript/ExpertScriptPlugin.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11082" }, { "name": "Batchfile", "bytes": "14049" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "315863" }, { "name": "HTML", "bytes": "3399" }, { "name": "Java", "bytes": "40107206" }, { "name": "Perl", "bytes": "7271" }, { "name": "Python", "bytes": "54437" }, { "name": "Shell", "bytes": "108937" } ], "symlink_target": "" }
class Time { public static currentTime(): number { // tslint:disable-next-line return Date.now() / 1000 | 0; } } export default Time; export { Time };
{ "content_hash": "89ac801c4293ab783725b4f494b114cd", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 41, "avg_line_length": 19.555555555555557, "alnum_prop": 0.5909090909090909, "repo_name": "ratatoskr/ratatoskr", "id": "d9b497ca6664f0a1bd24060bec330671d378e6f6", "size": "176", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/util/time.ts", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "79754" } ], "symlink_target": "" }
Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **commseq_email_uuids** | **string[]** | | [optional] **commseq_step_uuids** | **string[]** | | [optional] **days** | **int** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{ "content_hash": "b20623dee535e796ef00e1724e69d220", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 161, "avg_line_length": 45.22222222222222, "alnum_prop": 0.5257985257985258, "repo_name": "UltraCart/rest_api_v2_sdk_php", "id": "9156d54d34e394e622950306199f7ed1d291f30c", "size": "448", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Model/EmailStatSummaryRequest.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "13351968" } ], "symlink_target": "" }
//Michael Doescher //October 10, 2013 //This program reports overlapping boxes //Input = an array of box coordinates. Each box is defined as an array of points. The points represent the lower left and upper right corner. //Output = A two dimensional array. Each row contains two values indicating the index value of the boxes from the input that overlap module.exports = function(boxes) { // if (!isInputOk(boxes)) {return null;} var events = generateEvents(boxes); events.sort(compare); overlaps = new Array(); var overlaps = generateOvelapList(boxes, events, overlaps); return overlaps; } function isInputOk(boxes) { return true; } /* [ [[0, 0], [1, 1]], //box 1 [[0.5, 0.5], [10, 10]] //box 2 ] */ function generateEvents(boxes) { var events = new Array(); var event = new Object(); for (i = 0; i < boxes.length; i++) { // traverse the list of boxes var leftx = Math.min(boxes[i][0][0], boxes[i][1][0]); var rightx = Math.max(boxes[i][0][0], boxes[i][1][0]); event = new Object(); event.x = leftx; event.type = "add"; event.index = i; events.unshift(event); event = new Object(); event.x = rightx; event.type = "remove"; event.index = i; events.push(event); } return events; } function compare(a,b) { if (a.x < b.x) return -1; if (a.x > b.x) return 1; if (a.x == b.x && a.type == "add" && b.type == "remove") return -1; // adding before removing allows for boxes that overlap if (a.x == b.x && a.type == "remove" && b.type == "add") return 1; // only on the edge to count as overlapping. return 0; } function generateOvelapList(boxes, events, overlaps) { var Q = new Array(); // a list of indices into the boxes array of boxes that intersect the sweeping plane var overlaps = new Array(); // pairs of boxes that overlap (indices into the boxes array for (i = 0; i < events.length; i++) { if (events[i].type == "add") { overlaps = findOverlap(Q, events[i].index, overlaps, boxes); Q.push(events[i].index); } if (events[i].type == "remove") { var ind = Q.indexOf(events[i].index); Q.splice(ind, 1); } } return overlaps; } function findOverlap(Q, box, overlaps, boxes){ if (Q.length == 0) {return overlaps;} for (j = 0; j<Q.length; j++) { var y1 = Math.min(boxes[Q[j]][0][1], boxes[Q[j]][1][1]); var y2 = Math.max(boxes[Q[j]][0][1], boxes[Q[j]][1][1]); var ey1 = Math.min(boxes[box][0][1], boxes[box][1][1]); var ey2 = Math.max(boxes[box][0][1], boxes[box][1][1]); var add = false; if (ey1 >= y1 && ey1 <= y2) { add = true; } if (ey2 >= y1 && ey2 <= y2) { add = true; } if (ey1 < y1 && ey2 > y2) { add = true; } if (add) { var overlap = [Math.min(Q[j], box), Math.max(Q[j], box)]; overlaps.push(overlap); } } return overlaps; }
{ "content_hash": "83c5e35b43f7405fbc4a95754b243c29", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 143, "avg_line_length": 27.87, "alnum_prop": 0.6110513096519555, "repo_name": "mdoescher/BoxOverlap", "id": "b3f5f2649a828acd0b824c088b8b72d7e940c0eb", "size": "2787", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BoxOverlap.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3401" } ], "symlink_target": "" }
YUI.add("storekeeper-views-dashboard", function (Y) { Y.namespace('SK').DashboardView = Y.Base.create("dashboardView", Y.View, [], { template: Handlebars.templates['dashboard/layout'], render: function () { var container = this.get("container"); container.setContent( this.template() ); this._renderViews(); return this; }, _renderViews: function () { }, }, { ATTRS: { ordersOverview: {} } }); }, "0.0.1", {requires: ['view']});
{ "content_hash": "70734ac8554db4cc234821d0e9a739ff", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 80, "avg_line_length": 19.53846153846154, "alnum_prop": 0.5649606299212598, "repo_name": "hojberg/storekeeper", "id": "e385ab1d85f045ee2bc021ef1f6d0cc4bc591102", "size": "508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/js/app/views/dashboard_view.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "22025" } ], "symlink_target": "" }
package aegis //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. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" ) // DescribeRisks invokes the aegis.DescribeRisks API synchronously // api document: https://help.aliyun.com/api/aegis/describerisks.html func (client *Client) DescribeRisks(request *DescribeRisksRequest) (response *DescribeRisksResponse, err error) { response = CreateDescribeRisksResponse() err = client.DoAction(request, response) return } // DescribeRisksWithChan invokes the aegis.DescribeRisks API asynchronously // api document: https://help.aliyun.com/api/aegis/describerisks.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) DescribeRisksWithChan(request *DescribeRisksRequest) (<-chan *DescribeRisksResponse, <-chan error) { responseChan := make(chan *DescribeRisksResponse, 1) errChan := make(chan error, 1) err := client.AddAsyncTask(func() { defer close(responseChan) defer close(errChan) response, err := client.DescribeRisks(request) if err != nil { errChan <- err } else { responseChan <- response } }) if err != nil { errChan <- err close(responseChan) close(errChan) } return responseChan, errChan } // DescribeRisksWithCallback invokes the aegis.DescribeRisks API asynchronously // api document: https://help.aliyun.com/api/aegis/describerisks.html // asynchronous document: https://help.aliyun.com/document_detail/66220.html func (client *Client) DescribeRisksWithCallback(request *DescribeRisksRequest, callback func(response *DescribeRisksResponse, err error)) <-chan int { result := make(chan int, 1) err := client.AddAsyncTask(func() { var response *DescribeRisksResponse var err error defer close(result) response, err = client.DescribeRisks(request) callback(response, err) result <- 1 }) if err != nil { defer close(result) callback(nil, err) result <- 0 } return result } // DescribeRisksRequest is the request struct for api DescribeRisks type DescribeRisksRequest struct { *requests.RpcRequest SourceIp string `position:"Query" name:"SourceIp"` ResourceOwnerId requests.Integer `position:"Query" name:"ResourceOwnerId"` RiskId requests.Integer `position:"Query" name:"RiskId"` RiskName string `position:"Query" name:"RiskName"` Limit requests.Integer `position:"Query" name:"Limit"` } // DescribeRisksResponse is the response struct for api DescribeRisks type DescribeRisksResponse struct { *responses.BaseResponse RequestId string `json:"RequestId" xml:"RequestId"` TotalCount int `json:"TotalCount" xml:"TotalCount"` Risks []Risk `json:"Risks" xml:"Risks"` } // CreateDescribeRisksRequest creates a request to invoke DescribeRisks API func CreateDescribeRisksRequest() (request *DescribeRisksRequest) { request = &DescribeRisksRequest{ RpcRequest: &requests.RpcRequest{}, } request.InitWithApiInfo("aegis", "2016-11-11", "DescribeRisks", "vipaegis", "openAPI") return } // CreateDescribeRisksResponse creates a response to parse from DescribeRisks response func CreateDescribeRisksResponse() (response *DescribeRisksResponse) { response = &DescribeRisksResponse{ BaseResponse: &responses.BaseResponse{}, } return }
{ "content_hash": "a505abfe06cc2ab81118db782e61e352", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 150, "avg_line_length": 36.43119266055046, "alnum_prop": 0.7537144296147066, "repo_name": "xiaozhu36/terraform-provider", "id": "3fa5fb251e758306b54ca7bb0ee2eb88bdfbdd55", "size": "3971", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/aegis/describe_risks.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2195403" }, { "name": "HCL", "bytes": "818" }, { "name": "HTML", "bytes": "40750" }, { "name": "Makefile", "bytes": "1899" }, { "name": "Shell", "bytes": "1341" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@drawable/plugin_camera_send_focused" /> <item android:state_pressed="true" android:drawable="@drawable/plugin_camera_send_pressed" /> <item android:state_selected="true" android:drawable="@drawable/plugin_camera_send_pressed" /> <item android:drawable="@drawable/plugin_camera_send_unselected" /> </selector>
{ "content_hash": "c4c342045a9e5eb13288f19183d801bb", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 98, "avg_line_length": 62, "alnum_prop": 0.7237903225806451, "repo_name": "456838/usefulCode", "id": "74da09986f979e4e4d6b7f421dac956eb41f2a22", "size": "496", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "YHamburgGit/app/src/main/res/drawable/plugin_camera_ok_btn_state.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6258" }, { "name": "HTML", "bytes": "245591" }, { "name": "Java", "bytes": "1498326" }, { "name": "Python", "bytes": "454881" }, { "name": "Shell", "bytes": "10632" } ], "symlink_target": "" }
Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
{ "content_hash": "498266b582087b192824ef991ad2fb03", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 161, "avg_line_length": 43.333333333333336, "alnum_prop": 0.5307692307692308, "repo_name": "eliksir/mailmojo-python-sdk", "id": "a2f7a97c2eeae5895760d735e26c6db0d589e114", "size": "284", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Schema.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "671904" }, { "name": "Shell", "bytes": "1667" } ], "symlink_target": "" }
export const generalMessages = {}; export const successMessages = { // Defaults defaultForm: 'Success - Form Saved', // Member login: 'You are now logged in', signUp: 'You are now signed up. Please login to continue.', forgotPassword: 'Password reset. Please check your email.', }; export const errorMessages = { // Defaults default: 'Hmm, an unknown error occured', timeout: 'Server Timed Out. Check your internet connection', invalidJson: 'Response returned is not valid JSON', missingData: 'Missing data', // Member memberNotAuthd: 'You need to be logged in, to update your profile', memberExists: 'Member already exists', missingFirstName: 'First name is missing', missingLastName: 'Last name is missing', missingEmail: 'Email is missing', missingPassword: 'Password is missing', passwordsDontMatch: 'Passwords do not match', // Articles articlesEmpty: 'No articles found', articles404: 'This article could not be found', };
{ "content_hash": "3a24317b2ca0ada1237701f617abc69e", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 69, "avg_line_length": 30.5625, "alnum_prop": 0.7188139059304703, "repo_name": "mcnamee/react-native-starter-app", "id": "cddcfaedc18702f177b20a122e576e15f77a30a0", "size": "978", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/constants/messages.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2384" }, { "name": "HTML", "bytes": "3240" }, { "name": "JavaScript", "bytes": "186654" }, { "name": "Shell", "bytes": "58" } ], "symlink_target": "" }
module Homecoming class Find def initialize(filename, start_dir = Dir.pwd) @start_dir = start_dir @filename = filename end # Returns all found files with the given filename in the current and all # parent directories. # # # Given the following directory structure: # # / # home/ # rrrene/ # projects/ # your_project/ # .yourconfig # .yourconfig # # Homecoming.find(".yourconfig", "/home/rrrene/projects/your_project") # # => ["/home/rrrene/.yourconfig", # "/home/rrrene/projects/your_project/.yourconfig"] # def files Traversal.new(@start_dir).map do |dir| filename = File.join(dir, @filename) File.exist?(filename) ? filename : nil end.compact.reverse end end end
{ "content_hash": "c4f6e8436de0063cfafb53a79434f627", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 76, "avg_line_length": 26.8125, "alnum_prop": 0.5629370629370629, "repo_name": "rrrene/homecoming", "id": "05dba40f1ae28a393a7fa7a295e4bf69bb05ffbe", "size": "858", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/homecoming/find.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4675" } ], "symlink_target": "" }
from scrapy.spider import BaseSpider class JoySpider(BaseSpider): name = "joy" allowed_domains = ["dmoz.org"] start_urls = [ "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/", "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/" ] def parse(self, response): filename = response.url.split("/")[-2] open(filename, 'wb').write(response.body)
{ "content_hash": "e8afd89376422f2f53f526e75b07a60c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 79, "avg_line_length": 33, "alnum_prop": 0.655011655011655, "repo_name": "jake1036/spider", "id": "dd40c6df0710954f7ec0528985c2cb7d5c3d16c7", "size": "429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "joy/joy/spiders/JoySpider.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "9681" }, { "name": "Makefile", "bytes": "2225" }, { "name": "Python", "bytes": "1230388" }, { "name": "Shell", "bytes": "2059" } ], "symlink_target": "" }
var debug = require('debug'); var name = require('../package.json').name; var MAX = 220; function json(js) { // Don't json encode the string if debug is disabled. if (this.enabled) { var s = JSON.stringify(js); if (s.length < MAX) return s; return s.substring(0, MAX) + '...'; } return ''; } module.exports = function(tag) { var fn = debug(name + ':' + tag); fn.json = json; return fn; };
{ "content_hash": "ac13f6ab1905eb835af533b83997738f", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 55, "avg_line_length": 19.318181818181817, "alnum_prop": 0.5835294117647059, "repo_name": "tsiry95/openshift-strongloop-cartridge", "id": "0346c4038bdf60fc7bcd8abe47aface98f0c3d8a", "size": "651", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "strongloop/node_modules/strong-control-channel/lib/debug.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2028852" }, { "name": "C++", "bytes": "569460" }, { "name": "Groff", "bytes": "4748" }, { "name": "HTML", "bytes": "690" }, { "name": "JavaScript", "bytes": "25268" }, { "name": "Shell", "bytes": "13019" } ], "symlink_target": "" }
import CustomFeatureLayer from './CustomFeatureLayer'; import ArcGISMap from "esri/Map"; import MapView from 'esri/views/MapView'; const map = new ArcGISMap({ basemap: "gray-vector" }); /** * Initialize application */ const view = new MapView({ container: 'viewDiv', map, center: [-118.2437, 34.0522], zoom: 10 }); const layer = new CustomFeatureLayer(); map.add(layer); view.when();
{ "content_hash": "0274b2acf7c7bcd9a4dd00a9d6c7410f", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 54, "avg_line_length": 17.434782608695652, "alnum_prop": 0.6882793017456359, "repo_name": "ycabon/presentations", "id": "5f7ae561e63990a63545c5fef71e93157967dbf1", "size": "401", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2020-devsummit/ArcGIS-API-for-JavaScript-Under-The-Hood/src/demo2/index.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "40074" }, { "name": "Batchfile", "bytes": "2168" }, { "name": "CSS", "bytes": "1863111" }, { "name": "HTML", "bytes": "1743503" }, { "name": "JavaScript", "bytes": "10424211" }, { "name": "Julia", "bytes": "11944" }, { "name": "Less", "bytes": "1357954" }, { "name": "PHP", "bytes": "76208" }, { "name": "SCSS", "bytes": "506990" }, { "name": "Shell", "bytes": "2052" }, { "name": "Stylus", "bytes": "15294" }, { "name": "TeX", "bytes": "4673" }, { "name": "TypeScript", "bytes": "1430265" }, { "name": "XSLT", "bytes": "94766" } ], "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" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>delete-network-acl-entry &#8212; AWS CLI 1.0.0 documentation</title> <link rel="stylesheet" type="text/css" href="../../_static/bootstrap.min.css" /> <script type="text/javascript" src="../../_static/jquery-1.9.1.min.js.html"></script> <link rel="stylesheet" href="../../_static/guzzle.css" type="text/css" /> <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" /> <script type="text/javascript"><![CDATA[ var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../', VERSION: '1.0.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; ]]></script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/underscore.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <link rel="top" title="AWS CLI 1.0.0 documentation" href="../../index.html" /> <link rel="up" title="ec2" href="index.html" /> <link rel="next" title="delete-network-interface" href="delete-network-interface.html" /> <link rel="prev" title="delete-network-acl" href="delete-network-acl.html" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="../../_static/bootstrap-responsive.min.css" /> </head> <body> <div class="navbar navbar-fixed-top "> <div class="navbar-inner"> <div class="container"> <a class="brand" href="../../index.html">AWS CLI</a> <ul class="nav"> <li><a href="../../index.html">Home</a></li> <li><a href="http://aws.amazon.com/documentation/cli/">Documentation</a></li> <li><a href="https://forums.aws.amazon.com/forum.jspa?forumID=150">Forum</a></li> <li><a href="https://github.com/aws/aws-cli">GitHub</a></li> </ul> <div class="pull-right" id="github-stars"> <iframe src="http://ghbtns.com/github-btn.html?user=aws&amp;repo=aws-cli&amp;type=watch&amp;count=true&amp;size=small" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe> </div> </div> </div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right"> <a href="delete-network-interface.html" title="delete-network-interface" accesskey="N">next</a> |</li> <li class="right"> <a href="delete-network-acl.html" title="delete-network-acl" accesskey="P">previous</a> |</li> <li><a href="../../index.html">AWS CLI 1.0.0 documentation</a> &#187;</li> <li><a href="../index.html">aws</a> &#187;</li> <li><a href="index.html" accesskey="U">ec2</a> &#187;</li> </ul> </div> <div class="container"> <div class="top-links"> <ul class="breadcrumb pull-right"> <li> <a href="delete-network-acl.html" title="previous chapter (use the left arrow)">&#8592; delete-network-acl</a> <span class="divider">/</span> </li> <li><a href="delete-network-interface.html" title="next chapter (use the right arrow)">delete-network-interface &#8594;</a></li> </ul> </div> <div class="document clearer"> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"><p class="logo left-bar-other"> <a href="../../index.html"> <img class="logo" src="../../_static/logo.png" alt="Logo" height="63" /> </a> </p> <h3><a href="../../index.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">delete-network-acl-entry</a><ul> <li><a class="reference internal" href="#description">Description</a></li> <li><a class="reference internal" href="#synopsis">Synopsis</a></li> <li><a class="reference internal" href="#options">Options</a></li> </ul> </li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="form-search margin-top-1em" action="../../search.html" method="get"> <input type="text" name="q" style="width: 105px" class="input-small search-query" /> <button type="submit" class="btn btn-small">Search</button> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript"><![CDATA[$('#searchbox').show(0);]]></script><div class="left-bar-other"> <h3>Feedback</h3> <p class="feedback">Did you find this page useful? Do you have a suggestion? <a href="https://portal.aws.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_02?service_name=AWSCLI&amp;guide_name=Guide&amp;api_version=1.0&amp;file_name=reference/ec2/delete-network-acl-entry">Give us feedback</a> or send us a <a href="https://github.com/aws/aws-cli">pull request</a> on GitHub.</p> </div> </div> </div> <div class="body"> <p>[ <a class="reference internal" href="../index.html"><em>aws</em></a> . <a class="reference internal" href="index.html"><em>ec2</em></a> ]</p> <div class="section" id="delete-network-acl-entry"> <h1>delete-network-acl-entry<a class="headerlink" href="#delete-network-acl-entry" title="Permalink to this headline">&#182;</a></h1> <div class="section" id="description"> <h2>Description<a class="headerlink" href="#description" title="Permalink to this headline">&#182;</a></h2> <p>Deletes an ingress or egress entry (i.e., rule) from a network ACL. For more information about network ACLs, go to Network ACLs in the Amazon Virtual Private Cloud User Guide.</p> </div> <div class="section" id="synopsis"> <h2>Synopsis<a class="headerlink" href="#synopsis" title="Permalink to this headline">&#182;</a></h2> <div class="highlight-python"><pre> delete-network-acl-entry [--dry-run | --no-dry-run] --network-acl-id &lt;value&gt; --rule-number &lt;value&gt; --egress | --ingress</pre> </div> </div> <div class="section" id="options"> <h2>Options<a class="headerlink" href="#options" title="Permalink to this headline">&#182;</a></h2> <p><tt class="docutils literal"><a name="//apple_ref/cpp/Option/--dry-run" class="dashAnchor" id="dry-run"></a><span class="pre">--dry-run</span></tt> | <tt class="docutils literal"><a name="//apple_ref/cpp/Option/--no-dry-run" class="dashAnchor" id="no-dry-run"></a><span class="pre">--no-dry-run</span></tt> (boolean)</p> <p>Checks whether you have the required permissions for the action, without actually making the request. Using this option will result in one of two possible errorresponses. If you have the required permissions, the error response will be <tt class="docutils literal"><span class="pre">DryRunOperation</span></tt> . Otherwise it will be <tt class="docutils literal"><span class="pre">UnauthorizedOperation</span></tt> .</p> <p><tt class="docutils literal"><a name="//apple_ref/cpp/Option/--network-acl-id" class="dashAnchor" id="network-acl-id"></a><span class="pre">--network-acl-id</span></tt> (string)</p> <blockquote> <div>ID of the network ACL.</div></blockquote> <p><tt class="docutils literal"><a name="//apple_ref/cpp/Option/--rule-number" class="dashAnchor" id="rule-number"></a><span class="pre">--rule-number</span></tt> (integer)</p> <blockquote> <div>Rule number for the entry to delete.</div></blockquote> <p><tt class="docutils literal"><a name="//apple_ref/cpp/Option/--egress" class="dashAnchor" id="egress"></a><span class="pre">--egress</span></tt> | <tt class="docutils literal"><a name="//apple_ref/cpp/Option/--ingress" class="dashAnchor" id="ingress"></a><span class="pre">--ingress</span></tt> (boolean)</p> <blockquote> <div>Whether the rule to delete is an egress rule (<tt class="docutils literal"><span class="pre">true</span></tt> ) or ingress rule (<tt class="docutils literal"><span class="pre">false</span></tt> ).</div></blockquote> </div> </div> </div> <div class="clearfix"></div> </div> <div class="footer-links"> <ul class="breadcrumb pull-right"> <li> <a href="delete-network-acl.html" title="previous chapter (use the left arrow)">&#8592; delete-network-acl</a> <span class="divider">/</span> </li> <li><a href="delete-network-interface.html" title="next chapter (use the right arrow)">delete-network-interface &#8594;</a></li> </ul> </div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../genindex.html" title="General Index">index</a></li> <li class="right"> <a href="delete-network-interface.html" title="delete-network-interface">next</a> |</li> <li class="right"> <a href="delete-network-acl.html" title="delete-network-acl">previous</a> |</li> <li><a href="../../index.html">AWS CLI 1.0.0 documentation</a> &#187;</li> <li><a href="../index.html">aws</a> &#187;</li> <li><a href="index.html">ec2</a> &#187;</li> </ul> </div> <div class="footer container"> &#169; Copyright 2013, Amazon Web Services. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>. </div> <script type="text/javascript"><![CDATA[ $(document).keydown(function(e){ if (e.keyCode == 37) { window.location = 'delete-network-acl.html'; return false; } else if (e.keyCode == 39) { window.location = 'delete-network-interface.html'; return false; } }); ]]></script> </body> </html>
{ "content_hash": "9d330c97a0233edccfc25099f856c769", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 425, "avg_line_length": 49, "alnum_prop": 0.6160899142265602, "repo_name": "Smolations/more-dash-docsets", "id": "f35adeec3a908af535ae6ff9a2b73b4c1ea98c66", "size": "10143", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docsets/AWS-CLI.docset/Contents/Resources/Documents/reference/ec2/delete-network-acl-entry.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1456655" }, { "name": "Emacs Lisp", "bytes": "3680" }, { "name": "JavaScript", "bytes": "139712" }, { "name": "Puppet", "bytes": "15851" }, { "name": "Ruby", "bytes": "66500" }, { "name": "Shell", "bytes": "11437" } ], "symlink_target": "" }
package com.xinqihd.sns.gameserver.transport; import static org.junit.Assert.*; import java.io.File; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.xinqihd.sns.gameserver.Stat; import com.xinqihd.sns.gameserver.bootstrap.ReloadClassLoader; import com.xinqihd.sns.gameserver.config.GlobalConfig; import com.xinqihd.sns.gameserver.proto.XinqiBceLogin.BceLogin; import com.xinqihd.sns.gameserver.server.GameServer; public class GameClientTest { GameServer server = GameServer.getInstance(); String host = "localhost"; int port = 65500; @Before public void setUp() throws Exception { File classFile = new File("target/classes"); ReloadClassLoader.newClassloader(classFile.toURL()); server.startServer(host, port); } @After public void tearDown() throws Exception { server.stopServer(); } @Test public void testConnectToServer() { try { GameClient client = new GameClient(host, port); assertTrue(client.connectToServer()); } catch (Exception e) { e.printStackTrace(); } } @Test public void testSessionIdle() throws Exception { GlobalConfig.getInstance().overrideProperty("message.heartbeat.second", "1"); GameClient client = new GameClient(host, port); assertTrue(client.connectToServer()); Thread.sleep(2000); assertTrue(Stat.getInstance().messageHearbeatSent>=1); } @Test public void testDisconnect() throws Exception { GameClient client = new GameClient(host, port); assertTrue(client.connectToServer()); Thread.sleep(1000); client.disconnectFromServer(); Thread.sleep(1000); client.connectToServer(); } public void testStress() throws Exception { BceLogin.Builder login = BceLogin.newBuilder(); login.setUsername("test-001"); login.setPassword("000000"); BceLogin payload = login.build(); XinqiMessage msg = new XinqiMessage(); msg.index = 0; msg.type = MessageToId.messageToId(payload); msg.payload = payload; GameClient client = new GameClient(host, port); assertTrue(client.connectToServer()); for ( int i=0; i<100; i++ ) { client.sendMessageToServer(msg); System.out.println("send message #" + i); } Thread.sleep(100); System.out.println(Stat.getInstance().toString()); } }
{ "content_hash": "ab36d5dd42f08a5534454878b15fe8a2", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 79, "avg_line_length": 26.583333333333332, "alnum_prop": 0.7348858038513211, "repo_name": "wangqi/gameserver", "id": "09a6817804f838bdfd4598ffefa51e66b2976ebe", "size": "2233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/test/java/com/xinqihd/sns/gameserver/transport/GameClientTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "IDL", "bytes": "33142" }, { "name": "Java", "bytes": "7197480" }, { "name": "Lua", "bytes": "2013259" }, { "name": "Shell", "bytes": "37724" } ], "symlink_target": "" }
<?php namespace VivifyIdeas\Acl; use Illuminate\Support\Facades\Config; /** * Main ACL class for managing system and user permissions. */ class Manager { private $provider; private $allPermissions = array(); private $cached = array(); public function __construct(PermissionsProviderAbstract $provider) { $this->provider = $provider; // set system default permissions $this->allPermissions = $this->provider->getAllPermissions(); } /** * Get user permissions (together with system permissions) * * @param integer $userId * * @return array */ public function getUserPermissions($userId) { if (!isset($this->cached[$userId])) { // get user permissions $userPermissions = $this->provider->getUserPermissions($userId); // get user permissions from user roles $userPermissionsBasedOnRoles = $this->provider->getUserPermissionsBasedOnRoles($userId); $permissions = array(); // get all permissions foreach ($this->allPermissions as $permission) { $permission['allowed_ids'] = null; $permission['excluded_ids'] = null; unset($permission['name']); $permissions[$permission['id']] = $permission; } // overwrite system permissions with user permissions from roles foreach ($userPermissionsBasedOnRoles as $userRolePermission) { if (@$userRolePermission['allowed'] === null) { // allowed is not set, so use from system default unset($userRolePermission['allowed']); } $temp = $permissions[$userRolePermission['id']]; $temp = array_merge($temp, $userRolePermission); $permissions[$userRolePermission['id']] = $temp; } // overwrite system permissions and user permissions from roles with user permissions foreach ($userPermissions as $userPermission) { if (@$userPermission['allowed'] === null) { // allowed is not set, so use from system default unset($userPermission['allowed']); } $temp = $permissions[$userPermission['id']]; $temp = array_merge($temp, $userPermission); $permissions[$userPermission['id']] = $temp; } // set finall permissions for particular user $this->cached[$userId] = $permissions; } return $this->cached[$userId]; } /** * Reload system permission from config file * * @param boolean $onlySystemPermissions * * @return array Old permissions that not exists anymore */ public function reloadPermissions($onlySystemPermissions = false) { $permissions = Config::get('acl::permissions'); $forDelete = array(); if ($onlySystemPermissions) { // delete not existing permissions from users_permissions // get old permissions $old = $this->provider->getAllPermissions(); foreach ($old as $oldPermission) { $exist = false; foreach ($permissions as $newPermissions) { $exist = $newPermissions['id'] == $oldPermission['id']; if ($exist) { break; } } if (!$exist) { // delete only user permissions that not exist anymore $forDelete[] = $oldPermission['id']; } } foreach ($forDelete as $id) { $this->removeUserPermission(null, $id); } } else { $this->deleteAllUsersPermissions(); } $this->deleteAllPermissions(); foreach ($permissions as $permission) { $this->createPermission( $permission['id'], $permission['allowed'], $permission['route'], $permission['resource_id_required'], $permission['name'], @$permission['group_id'] ); } return $forDelete; } /** * Reload groups from config file into DB * * @param string $parentGroup * @param array $groups * * @return type */ public function reloadGroups($parentGroup = null, $groups = null) { if (empty($groups)) { $groups = Config::get('acl::groups'); } if ($parentGroup === null) { $this->deleteAllGroups(); } $newGroups = array(); foreach ($groups as $group) { if (empty($group['children'])) { $newGroups[$group['id']] = $parentGroup; $this->insertGroup($group['id'], $group['name'], @$group['route'], $parentGroup); } else { $newGroups[$group['id']] = $parentGroup; $this->insertGroup($group['id'], $group['name'], @$group['route'], $parentGroup); $newGroups = array_merge( $newGroups, $this->reloadGroups($group['id'], $group['children']) ); } } return $newGroups; } /** * Reload roles from config file into DB * * @param string $parentRole * @param array $roles * * @return type */ public function reloadRoles($parentRole = null, $roles = null) { if (empty($roles)) { $roles = Config::get('acl::roles'); } if ($parentRole === null) { $this->deleteAllRoles(); } $newRoles = array(); foreach ($roles as $role) { if (empty($role['children'])) { $newRoles[$role['id']] = $parentRole; $this->insertRole($role['id'], $role['name'], $parentRole); } else { $newRoles[$role['id']] = $parentRole; $this->insertRole($role['id'], $role['name'], $parentRole); $newRoles = array_merge( $newRoles, $this->reloadRoles($role['id'], $role['children']) ); } } return $newRoles; } /** * Insert new group with specific provider * * @param string $id * @param string $name * @param array|string $route * @param type $parentId * * @return type */ public function insertGroup($id, $name, $route = null, $parentId = null) { return $this->provider->insertGroup($id, $name, $route, $parentId); } /** * Insert new role with specific provider * * @param string $id * @param string $name * @param array|string $permissionIds * @param type $parentId * * @return type */ public function insertRole($id, $name, $parentId = null) { return $this->provider->insertRole($id, $name, $parentId); } /** * Delete all groups using provider. */ public function deleteAllGroups() { return $this->provider->deleteAllGroups(); } /** * Delete all roles using provider. */ public function deleteAllRoles() { return $this->provider->deleteAllRoles(); } /** * Update user permissions (user permissions needs to exist). * * @param integer $userId * @param array $permissions */ public function updateUserPermissions($userId, array $permissions) { foreach ($permissions as $permission) { $this->updateUserPermission( $userId, $permission['id'], @$permission['allowed'], @$permission['allowed_ids'], @$permission['excluded_ids'] ); } } /** * Delete all system permissions */ public function deleteAllPermissions() { return $this->provider->deleteAllPermissions(); } /** * Delete all users permissions */ public function deleteAllUsersPermissions() { return $this->provider->deleteAllUsersPermissions(); } /** * Create new system permission * * @param integer $id * @param boolean $allowed * @param string|array $route * @param boolean $resourceIdRequired * @param string $name * @param string $groupId */ public function createPermission($id, $allowed, $route, $resourceIdRequired, $name, $groupId = null) { return $this->provider->createPermission($id, $allowed, $route, $resourceIdRequired, $name, $groupId); } /** * Remove system permission * * @param string $id */ public function removePermission($id) { return $this->provider->removePermission($id); } /** * Assign system permission to the specific user. * * @param integer $userId * @param string $permissionId * @param boolean $allowed * @param array $allowedIds * @param array $excludedIds */ public function assignPermission( $userId, $permissionId, $allowed = null, array $allowedIds = null, array $excludedIds = null ) { return $this->provider->assignPermission($userId, $permissionId, $allowed, $allowedIds, $excludedIds); } /** * Remove permission from the user. * * @param integer $userId * @param string $permissionId */ public function removeUserPermission($userId, $permissionId) { return $this->provider->removeUserPermission($userId, $permissionId); } /** * Remove all user's permissions * * @param integer $userId */ public function removeUserPermissions($userId) { return $this->provider->removeUserPermissions($userId); } /** * Update user permission (only if that user permission exist). * * @param integer $userId * @param string $permissionId * @param boolean $allowed * @param array $allowedIds * @param array $excludedIds */ public function updateUserPermission( $userId, $permissionId, $allowed = null, array $allowedIds = null, array $excludedIds = null ) { return $this->provider->updateUserPermission($userId, $permissionId, $allowed, $allowedIds, $excludedIds); } /** * Get specific user permission * * @param integer $userId * @param string $permissionId * * @return array */ public function getUserPermission($userId, $permissionId) { return $this->provider->getUserPermission($userId, $permissionId); } /** * Set user permission. If permission exist update, otherwise create. * * @param integer $userId * @param string $permissionId * @param boolean $allowed * @param array $allowedIds * @param array $excludedIds */ public function setUserPermission( $userId, $permissionId, $allowed = null, array $allowedIds = null, array $excludedIds = null ) { $permission = $this->getUserPermission($userId, $permissionId); if (empty($permission)) { return $this->provider->assignPermission($userId, $permissionId, $allowed, $allowedIds, $excludedIds); } else { return $this->provider->updateUserPermission($userId, $permissionId, $allowed, $allowedIds, $excludedIds); } } /** * Get all system permissions. * * @return array */ public function getAllPermissions() { return $this->allPermissions; } /** * Get all permission placed into proper groups as children nodes. * * @param array $grouped * @param array $groups * * @return array */ public function getAllPermissionsGrouped($grouped = null, $groups = null) { $permissions = null; if ($grouped === null) { $permissions = $this->provider->getAllPermissions(); $grouped = array(); foreach ($permissions as $key => $permission) { if (isset($permission['group_id'])) { $grouped[$permission['group_id']][] = $permission; unset($permissions[$key]); } } } if ($groups === null) { $groups = Config::get('acl::groups'); } foreach ($groups as &$group) { if (!empty($group['children'])) { $temp = $this->getAllPermissionsGrouped($grouped, $group['children']); $group['children'] = $temp; if (!empty($grouped[$group['id']])) { if (!isset($group['children'])) { $group['children'] = array(); } $group['children'] = array_merge($group['children'], $grouped[$group['id']]); } } else { if (!empty($grouped[$group['id']])) { if (!isset($group['children'])) { $group['children'] = array(); } $group['children'] = array_merge($group['children'], $grouped[$group['id']]); } } } if ($permissions !== null) { return array_merge($groups, $permissions); } return $groups; } /** * List all groups (linear structure) */ public function getGroups() { return $this->provider->getGroups(); } /** * List all children of a group * * @param string|int $id Group ID * @param boolean $selfinclude Should we return also the group with provided id * @param boolean $recursive Should we return also child of child groups * @return array List of children groups */ public function getChildGroups($id, $selfinclude = true, $recursive = true) { $groups = $this->getGroups(); $childs = array(); foreach ($groups as $group) { if ($group['parent_id'] == $id || ($selfinclude && $group['id'] == $id)) { $childs[$group['id']] = $group; if ($recursive && $group['id'] != $id) { $childs = array_merge($childs, $this->getChildGroups($group['id'])); } } } return $childs; } /** * Get user roles * * @param integer $userId * * @return array */ public function getUserRoles($userId) { return $this->provider->getUserRoles($userId); } }
{ "content_hash": "913356432f93acf42fce1b4802d840dd", "timestamp": "", "source": "github", "line_count": 519, "max_line_length": 118, "avg_line_length": 28.57996146435453, "alnum_prop": 0.5282815344165037, "repo_name": "esolitos/linguistics-databases", "id": "3e7a803de5a9f91cfc4a70c1ec99b0017bc1c36b", "size": "14833", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/vivify-ideas/acl/src/VivifyIdeas/Acl/Manager.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "71610" }, { "name": "HTML", "bytes": "380885" }, { "name": "JavaScript", "bytes": "586838" }, { "name": "PHP", "bytes": "534818" }, { "name": "Ruby", "bytes": "1736" } ], "symlink_target": "" }
CREATE TABLE IF NOT EXISTS user_metrics ( user_id integer NOT NULL, score integer NOT NULL, total_fixed integer, total_false_positive integer, total_already_fixed integer, total_too_hard integer, total_skipped integer );; CREATE TABLE IF NOT EXISTS user_metrics_history ( user_id integer NOT NULL, score integer NOT NULL, total_fixed integer, total_false_positive integer, total_already_fixed integer, total_too_hard integer, total_skipped integer, snapshot_date timestamp without time zone DEFAULT NOW() );; SELECT create_index_if_not_exists('user_metrics', 'user_id', '(user_id)');; SELECT create_index_if_not_exists('user_metrics_history', 'user_id', '(user_id)');; SELECT create_index_if_not_exists('user_metrics_history', 'user_id_snapshot_date', '(user_id, snapshot_date)');; INSERT INTO user_metrics (user_id, score, total_fixed, total_false_positive, total_already_fixed, total_too_hard, total_skipped) SELECT users.id, SUM(CASE sa.status WHEN 1 THEN 5 WHEN 2 THEN 3 WHEN 5 THEN 3 WHEN 6 THEN 1 WHEN 3 THEN 0 ELSE 0 END) AS score, SUM(CASE WHEN sa.status = 1 then 1 else 0 end) total_fixed, SUM(CASE WHEN sa.status = 2 then 1 else 0 end) total_false_positive, SUM(CASE WHEN sa.status = 5 then 1 else 0 end) total_already_fixed, SUM(CASE WHEN sa.status = 6 then 1 else 0 end) total_too_hard, SUM(CASE WHEN sa.status = 3 then 1 else 0 end) total_skipped FROM status_actions sa, users WHERE users.osm_id = sa.osm_user_id AND sa.old_status <> sa.status GROUP BY sa.osm_user_id, users.id;; # --- !Downs --DROP TABLE IF EXISTS user_metrics;; --DROP TABLE IF EXISTS user_metrics_history;;
{ "content_hash": "66d6b3156433101d20a5a88af4b2dfa2", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 112, "avg_line_length": 34.68627450980392, "alnum_prop": 0.6721311475409836, "repo_name": "mvexel/maproulette2", "id": "ffc26cacc487b52d9ac9fb415fd0bd946fffefc6", "size": "1842", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "conf/evolutions/default/26.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "406" }, { "name": "PLSQL", "bytes": "217" }, { "name": "PLpgSQL", "bytes": "59216" }, { "name": "Python", "bytes": "2366" }, { "name": "Scala", "bytes": "880330" }, { "name": "Shell", "bytes": "1671" }, { "name": "TSQL", "bytes": "22066" } ], "symlink_target": "" }
package com.jpattern.core.textfiles; import java.io.Serializable; /** * * @author Francesco Cina' * * 09/giu/2010 */ public interface IFile extends Serializable { String getPath(); String getName(); IFileReader getFileReader(); IFileWriter getFileWriter(boolean append); boolean exists(); }
{ "content_hash": "323077e7d8a69d360ab08d03e7995037", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 45, "avg_line_length": 14.73913043478261, "alnum_prop": 0.6548672566371682, "repo_name": "ufoscout/jpattern", "id": "9180e08da5a21d939b89a59cdff108e6fb80ad95", "size": "339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/com/jpattern/core/textfiles/IFile.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "33062" }, { "name": "Java", "bytes": "1384577" } ], "symlink_target": "" }
package com.amazonaws.services.connect.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.connect.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import static com.fasterxml.jackson.core.JsonToken.*; /** * UpdateQueueOutboundCallerConfigResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateQueueOutboundCallerConfigResultJsonUnmarshaller implements Unmarshaller<UpdateQueueOutboundCallerConfigResult, JsonUnmarshallerContext> { public UpdateQueueOutboundCallerConfigResult unmarshall(JsonUnmarshallerContext context) throws Exception { UpdateQueueOutboundCallerConfigResult updateQueueOutboundCallerConfigResult = new UpdateQueueOutboundCallerConfigResult(); return updateQueueOutboundCallerConfigResult; } private static UpdateQueueOutboundCallerConfigResultJsonUnmarshaller instance; public static UpdateQueueOutboundCallerConfigResultJsonUnmarshaller getInstance() { if (instance == null) instance = new UpdateQueueOutboundCallerConfigResultJsonUnmarshaller(); return instance; } }
{ "content_hash": "ed65194dd594787de7994370255f238d", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 156, "avg_line_length": 36.93939393939394, "alnum_prop": 0.8162428219852338, "repo_name": "aws/aws-sdk-java", "id": "3dc4660b492f74362535cb8ac7e6e01de4b81471", "size": "1799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-connect/src/main/java/com/amazonaws/services/connect/model/transform/UpdateQueueOutboundCallerConfigResultJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* See the file "LICENSE" for the full license governing this code. */ namespace CSJSONBacklog.Model.Projects { public class Change { public string Field { get; set; } public string New_value { get; set; } public string Old_value { get; set; } public string Type { get; set; } public override string ToString() { return string.Format("Change: {0} New_value: {1} Old_value: {2} Type: {3}", Field, New_value, Old_value, Type); } } }
{ "content_hash": "b80ec6daf4d85fcdb159300adc98f25b", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 123, "avg_line_length": 31.235294117647058, "alnum_prop": 0.5668549905838042, "repo_name": "mtaniuchi/CSJSONBacklog", "id": "2d2f655fc8ddd9ec64423477b14ab3a2db6e9861", "size": "533", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CSJSONBacklog/Model/Projects/Change.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "109401" }, { "name": "PowerShell", "bytes": "1107" } ], "symlink_target": "" }
// <copyright file="FileWriter.cs" company="Automate The Planet Ltd."> // Copyright 2021 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>http://automatetheplanet.com/</site> using System; using System.IO; namespace WhichWorksFasterNullDefault { public static class FileWriter { public static void WriteToDesktop(string fileName, string content, bool appendToFile = true) { var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); var resultsPath = Path.Combine(desktopPath, string.Concat(fileName, ".txt")); using (var writer = new StreamWriter(resultsPath, appendToFile)) { writer.WriteLine(content); } } } }
{ "content_hash": "7892c3ada703abdbec678624756160c8", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 100, "avg_line_length": 42.74193548387097, "alnum_prop": 0.7033962264150944, "repo_name": "angelovstanton/AutomateThePlanet", "id": "aecc4dcac06893782f9ce90fd645e8c6a30fecd5", "size": "1327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dotnet/Development-Series/WhichWorksFasterNullDefault/FileWriter.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "5412058" }, { "name": "Gherkin", "bytes": "5274" }, { "name": "HTML", "bytes": "144064" }, { "name": "JavaScript", "bytes": "1250402" }, { "name": "PowerShell", "bytes": "33290" }, { "name": "Puppet", "bytes": "112" } ], "symlink_target": "" }
package org.apache.solr.cloud; import org.apache.commons.codec.binary.StringUtils; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.TestUtil; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.client.solrj.request.CollectionAdminRequest; import org.apache.solr.client.solrj.request.CoreAdminRequest; import org.apache.solr.client.solrj.response.CollectionAdminResponse; import org.apache.solr.client.solrj.response.CoreAdminResponse; import org.apache.solr.common.cloud.ClusterState; import org.apache.solr.common.cloud.DocCollection; import org.apache.solr.common.cloud.Replica; import org.apache.solr.common.cloud.Slice; import org.apache.solr.common.cloud.ZkStateReader; import org.apache.solr.common.params.CoreAdminParams; import org.apache.solr.common.util.NamedList; import org.apache.zookeeper.KeeperException; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import static org.apache.solr.cloud.ReplicaPropertiesBase.verifyUniqueAcrossCollection; @LuceneTestCase.Slow public class CollectionsAPISolrJTests extends AbstractFullDistribZkTestBase { @Test public void test() throws Exception { testCreateAndDeleteCollection(); testCreateAndDeleteShard(); testReloadCollection(); testCreateAndDeleteAlias(); testSplitShard(); testCreateCollectionWithPropertyParam(); testAddAndDeleteReplica(); testClusterProp(); testAddAndRemoveRole(); testOverseerStatus(); testList(); testAddAndDeleteReplicaProp(); testBalanceShardUnique(); } protected void testCreateAndDeleteCollection() throws Exception { String collectionName = "solrj_test"; CollectionAdminRequest.Create createCollectionRequest = new CollectionAdminRequest.Create(); createCollectionRequest.setCollectionName(collectionName); createCollectionRequest.setNumShards(2); createCollectionRequest.setReplicationFactor(2); createCollectionRequest.setConfigName("conf1"); createCollectionRequest.setRouterField("myOwnField"); CollectionAdminResponse response = createCollectionRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); Map<String, NamedList<Integer>> coresStatus = response.getCollectionCoresStatus(); assertEquals(4, coresStatus.size()); for (int i=0; i<4; i++) { NamedList<Integer> status = coresStatus.get(collectionName + "_shard" + (i/2+1) + "_replica" + (i%2+1)); assertEquals(0, (int)status.get("status")); assertTrue(status.get("QTime") > 0); } cloudClient.setDefaultCollection(collectionName); CollectionAdminRequest.Delete deleteCollectionRequest = new CollectionAdminRequest.Delete(); deleteCollectionRequest.setCollectionName(collectionName); response = deleteCollectionRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); Map<String,NamedList<Integer>> nodesStatus = response.getCollectionNodesStatus(); assertNull("Deleted collection " + collectionName + "still exists", cloudClient.getZkStateReader().getClusterState().getCollectionOrNull(collectionName)); assertEquals(4, nodesStatus.size()); // Test Creating a collection with new stateformat. collectionName = "solrj_newstateformat"; createCollectionRequest = new CollectionAdminRequest.Create(); createCollectionRequest.setCollectionName(collectionName); createCollectionRequest.setNumShards(2); createCollectionRequest.setConfigName("conf1"); createCollectionRequest.setStateFormat(2); response = createCollectionRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); waitForRecoveriesToFinish(collectionName, false); assertTrue("Collection state does not exist", cloudClient.getZkStateReader().getZkClient() .exists(ZkStateReader.getCollectionPath(collectionName), true)); } protected void testCreateAndDeleteShard() throws IOException, SolrServerException { // Create an implicit collection String collectionName = "solrj_implicit"; CollectionAdminRequest.Create createCollectionRequest = new CollectionAdminRequest.Create(); createCollectionRequest.setCollectionName(collectionName); createCollectionRequest.setShards("shardA,shardB"); createCollectionRequest.setConfigName("conf1"); createCollectionRequest.setRouterName("implicit"); CollectionAdminResponse response = createCollectionRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); Map<String, NamedList<Integer>> coresStatus = response.getCollectionCoresStatus(); assertEquals(2, coresStatus.size()); cloudClient.setDefaultCollection(collectionName); // Add a shard to the implicit collection CollectionAdminRequest.CreateShard createShardRequest = new CollectionAdminRequest .CreateShard(); createShardRequest.setCollectionName(collectionName); createShardRequest.setShardName("shardC"); response = createShardRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); coresStatus = response.getCollectionCoresStatus(); assertEquals(1, coresStatus.size()); assertEquals(0, (int) coresStatus.get(collectionName + "_shardC_replica1").get("status")); CollectionAdminRequest.DeleteShard deleteShardRequest = new CollectionAdminRequest .DeleteShard(); deleteShardRequest.setCollectionName(collectionName); deleteShardRequest.setShardName("shardC"); response = deleteShardRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); Map<String, NamedList<Integer>> nodesStatus = response.getCollectionNodesStatus(); assertEquals(1, nodesStatus.size()); } protected void testReloadCollection() throws IOException, SolrServerException { cloudClient.setDefaultCollection(DEFAULT_COLLECTION); CollectionAdminRequest.Reload reloadCollectionRequest = new CollectionAdminRequest.Reload(); reloadCollectionRequest.setCollectionName("collection1"); CollectionAdminResponse response = reloadCollectionRequest.process(cloudClient); assertEquals(0, response.getStatus()); } protected void testCreateAndDeleteAlias() throws IOException, SolrServerException { CollectionAdminRequest.CreateAlias createAliasRequest = new CollectionAdminRequest .CreateAlias(); createAliasRequest.setAliasName("solrj_alias"); createAliasRequest.setAliasedCollections(DEFAULT_COLLECTION); CollectionAdminResponse response = createAliasRequest.process(cloudClient); assertEquals(0, response.getStatus()); CollectionAdminRequest.DeleteAlias deleteAliasRequest = new CollectionAdminRequest.DeleteAlias(); deleteAliasRequest.setAliasName("solrj_alias"); deleteAliasRequest.process(cloudClient); assertEquals(0, response.getStatus()); } protected void testSplitShard() throws Exception { String collectionName = "solrj_test_splitshard"; cloudClient.setDefaultCollection(collectionName); CollectionAdminRequest.Create createCollectionRequest = new CollectionAdminRequest.Create(); createCollectionRequest.setConfigName("conf1"); createCollectionRequest.setNumShards(2); createCollectionRequest.setCollectionName(collectionName); createCollectionRequest.process(cloudClient); CollectionAdminRequest.SplitShard splitShardRequest = new CollectionAdminRequest.SplitShard(); splitShardRequest.setCollectionName(collectionName); splitShardRequest.setShardName("shard1"); CollectionAdminResponse response = splitShardRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); Map<String, NamedList<Integer>> coresStatus = response.getCollectionCoresStatus(); assertEquals(0, (int) coresStatus.get(collectionName + "_shard1_0_replica1").get("status")); assertEquals(0, (int) coresStatus.get(collectionName + "_shard1_1_replica1").get("status")); waitForRecoveriesToFinish(collectionName, false); waitForThingsToLevelOut(10); // Test splitting using split.key splitShardRequest = new CollectionAdminRequest.SplitShard(); splitShardRequest.setCollectionName(collectionName); splitShardRequest.setSplitKey("b!"); response = splitShardRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); waitForRecoveriesToFinish(collectionName, false); waitForThingsToLevelOut(10); ClusterState clusterState = cloudClient.getZkStateReader().getClusterState(); Collection<Slice> slices = clusterState.getActiveSlices(collectionName); assertEquals("ClusterState: "+ clusterState.getActiveSlices(collectionName), 5, slices.size()); } private void testCreateCollectionWithPropertyParam() throws Exception { String collectionName = "solrj_test_core_props"; File tmpDir = createTempDir("testPropertyParamsForCreate").toFile(); File instanceDir = new File(tmpDir, "instanceDir-" + TestUtil.randomSimpleString(random(), 1, 5)); File dataDir = new File(tmpDir, "dataDir-" + TestUtil.randomSimpleString(random(), 1, 5)); File ulogDir = new File(tmpDir, "ulogDir-" + TestUtil.randomSimpleString(random(), 1, 5)); Properties properties = new Properties(); properties.put(CoreAdminParams.INSTANCE_DIR, instanceDir.getAbsolutePath()); properties.put(CoreAdminParams.DATA_DIR, dataDir.getAbsolutePath()); properties.put(CoreAdminParams.ULOG_DIR, ulogDir.getAbsolutePath()); CollectionAdminRequest.Create createReq = new CollectionAdminRequest.Create(); createReq.setCollectionName(collectionName); createReq.setNumShards(1); createReq.setConfigName("conf1"); createReq.setProperties(properties); CollectionAdminResponse response = createReq.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); Map<String, NamedList<Integer>> coresStatus = response.getCollectionCoresStatus(); assertEquals(1, coresStatus.size()); DocCollection testCollection = cloudClient.getZkStateReader() .getClusterState().getCollection(collectionName); Replica replica1 = testCollection.getReplica("core_node1"); try (HttpSolrClient client = new HttpSolrClient(replica1.getStr("base_url"))) { CoreAdminResponse status = CoreAdminRequest.getStatus(replica1.getStr("core"), client); NamedList<Object> coreStatus = status.getCoreStatus(replica1.getStr("core")); String dataDirStr = (String) coreStatus.get("dataDir"); String instanceDirStr = (String) coreStatus.get("instanceDir"); assertEquals("Instance dir does not match param passed in property.instanceDir syntax", new File(instanceDirStr).getAbsolutePath(), instanceDir.getAbsolutePath()); assertEquals("Data dir does not match param given in property.dataDir syntax", new File(dataDirStr).getAbsolutePath(), dataDir.getAbsolutePath()); } CollectionAdminRequest.Delete deleteCollectionRequest = new CollectionAdminRequest.Delete(); deleteCollectionRequest.setCollectionName(collectionName); deleteCollectionRequest.process(cloudClient); } private void testAddAndDeleteReplica() throws Exception { String collectionName = "solrj_replicatests"; createCollection(collectionName, cloudClient, 1, 2); cloudClient.setDefaultCollection(collectionName); String newReplicaName = Assign.assignNode(collectionName, cloudClient.getZkStateReader().getClusterState()); ArrayList<String> nodeList = new ArrayList<>(cloudClient.getZkStateReader().getClusterState().getLiveNodes()); Collections.shuffle(nodeList, random()); CollectionAdminRequest.AddReplica addReplica = new CollectionAdminRequest.AddReplica(); addReplica.setCollectionName(collectionName); addReplica.setShardName("shard1"); addReplica.setNode(nodeList.get(0)); CollectionAdminResponse response = addReplica.process(cloudClient); assertEquals(0, response.getStatus()); assertTrue(response.isSuccess()); long timeout = System.currentTimeMillis() + 3000; Replica newReplica = null; while (System.currentTimeMillis() < timeout && newReplica == null) { Slice slice = cloudClient.getZkStateReader().getClusterState().getSlice(collectionName, "shard1"); newReplica = slice.getReplica(newReplicaName); } assertNotNull(newReplica); assertEquals("Replica should be created on the right node", cloudClient.getZkStateReader().getBaseUrlForNodeName(nodeList.get(0)), newReplica.getStr(ZkStateReader.BASE_URL_PROP) ); // Test DELETEREPLICA CollectionAdminRequest.DeleteReplica deleteReplicaRequest = new CollectionAdminRequest.DeleteReplica(); deleteReplicaRequest.setCollectionName(collectionName); deleteReplicaRequest.setShardName("shard1"); deleteReplicaRequest.setReplica(newReplicaName); response = deleteReplicaRequest.process(cloudClient); assertEquals(0, response.getStatus()); timeout = System.currentTimeMillis() + 3000; while (System.currentTimeMillis() < timeout && newReplica != null) { Slice slice = cloudClient.getZkStateReader().getClusterState().getSlice(collectionName, "shard1"); newReplica = slice.getReplica(newReplicaName); } assertNull(newReplica); } private void testClusterProp() throws InterruptedException, IOException, SolrServerException { CollectionAdminRequest.ClusterProp clusterPropRequest = new CollectionAdminRequest.ClusterProp(); clusterPropRequest.setPropertyName(ZkStateReader.LEGACY_CLOUD); clusterPropRequest.setPropertyValue("false"); CollectionAdminResponse response = clusterPropRequest.process(cloudClient); assertEquals(0, response.getStatus()); long timeOut = System.currentTimeMillis() + 3000; boolean changed = false; while(System.currentTimeMillis() < timeOut){ Thread.sleep(10); changed = Objects.equals("false", cloudClient.getZkStateReader().getClusterProps().get(ZkStateReader.LEGACY_CLOUD)); if(changed) break; } assertTrue("The Cluster property wasn't set", changed); // Unset ClusterProp that we set. clusterPropRequest = new CollectionAdminRequest.ClusterProp(); clusterPropRequest.setPropertyName(ZkStateReader.LEGACY_CLOUD); clusterPropRequest.setPropertyValue(null); clusterPropRequest.process(cloudClient); timeOut = System.currentTimeMillis() + 3000; changed = false; while(System.currentTimeMillis() < timeOut){ Thread.sleep(10); changed = (cloudClient.getZkStateReader().getClusterProps().get(ZkStateReader.LEGACY_CLOUD) == null); if(changed) break; } assertTrue("The Cluster property wasn't unset", changed); } private void testAddAndRemoveRole() throws InterruptedException, IOException, SolrServerException { cloudClient.setDefaultCollection(DEFAULT_COLLECTION); Replica replica = cloudClient.getZkStateReader().getLeaderRetry(DEFAULT_COLLECTION, SHARD1); CollectionAdminRequest.AddRole addRoleRequest = new CollectionAdminRequest.AddRole(); addRoleRequest.setNode(replica.getNodeName()); addRoleRequest.setRole("overseer"); addRoleRequest.process(cloudClient); CollectionAdminRequest.ClusterStatus clusterStatusRequest = new CollectionAdminRequest.ClusterStatus(); clusterStatusRequest.setCollectionName(DEFAULT_COLLECTION); CollectionAdminResponse response = clusterStatusRequest.process(cloudClient); NamedList<Object> rsp = response.getResponse(); NamedList<Object> cluster = (NamedList<Object>) rsp.get("cluster"); assertNotNull("Cluster state should not be null", cluster); Map<String, Object> roles = (Map<String, Object>) cluster.get("roles"); assertNotNull("Role information should not be null", roles); List<String> overseer = (List<String>) roles.get("overseer"); assertNotNull(overseer); assertEquals(1, overseer.size()); assertTrue(overseer.contains(replica.getNodeName())); // Remove role CollectionAdminRequest.RemoveRole removeRoleRequest = new CollectionAdminRequest.RemoveRole(); removeRoleRequest.setNode(replica.getNodeName()); removeRoleRequest.setRole("overseer"); removeRoleRequest.process(cloudClient); clusterStatusRequest = new CollectionAdminRequest.ClusterStatus(); clusterStatusRequest.setCollectionName(DEFAULT_COLLECTION); response = clusterStatusRequest.process(cloudClient); rsp = response.getResponse(); cluster = (NamedList<Object>) rsp.get("cluster"); assertNotNull("Cluster state should not be null", cluster); roles = (Map<String, Object>) cluster.get("roles"); assertNotNull("Role information should not be null", roles); overseer = (List<String>) roles.get("overseer"); assertFalse(overseer.contains(replica.getNodeName())); } private void testOverseerStatus() throws IOException, SolrServerException { CollectionAdminRequest.OverseerStatus overseerStatusRequest = new CollectionAdminRequest.OverseerStatus(); CollectionAdminResponse response = overseerStatusRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertNotNull("overseer_operations shouldn't be null", response.getResponse().get("overseer_operations")); } private void testList() throws IOException, SolrServerException { CollectionAdminRequest.List listRequest = new CollectionAdminRequest.List(); CollectionAdminResponse response = listRequest.process(cloudClient); assertEquals(0, response.getStatus()); assertNotNull("collection list should not be null", response.getResponse().get("collections")); } private void testAddAndDeleteReplicaProp() throws InterruptedException, IOException, SolrServerException { Replica replica = cloudClient.getZkStateReader().getLeaderRetry(DEFAULT_COLLECTION, SHARD1); CollectionAdminRequest.AddReplicaProp addReplicaPropRequest = new CollectionAdminRequest.AddReplicaProp(); addReplicaPropRequest.setCollectionName(DEFAULT_COLLECTION); addReplicaPropRequest.setShardName(SHARD1); addReplicaPropRequest.setReplica(replica.getName()); addReplicaPropRequest.setPropertyName("preferredleader"); addReplicaPropRequest.setPropertyValue("true"); CollectionAdminResponse response = addReplicaPropRequest.process(cloudClient); assertEquals(0, response.getStatus()); long timeout = System.currentTimeMillis() + 20000; String propertyValue = null; String replicaName = replica.getName(); while (System.currentTimeMillis() < timeout) { ClusterState clusterState = cloudClient.getZkStateReader().getClusterState(); replica = clusterState.getReplica(DEFAULT_COLLECTION, replicaName); propertyValue = replica.getStr("property.preferredleader"); if(StringUtils.equals("true", propertyValue)) break; Thread.sleep(50); } assertEquals("Replica property was not updated, Latest value: " + cloudClient.getZkStateReader().getClusterState().getReplica(DEFAULT_COLLECTION, replicaName), "true", propertyValue); CollectionAdminRequest.DeleteReplicaProp deleteReplicaPropRequest = new CollectionAdminRequest.DeleteReplicaProp(); deleteReplicaPropRequest.setCollectionName(DEFAULT_COLLECTION); deleteReplicaPropRequest.setShardName(SHARD1); deleteReplicaPropRequest.setReplica(replicaName); deleteReplicaPropRequest.setPropertyName("property.preferredleader"); response = deleteReplicaPropRequest.process(cloudClient); assertEquals(0, response.getStatus()); timeout = System.currentTimeMillis() + 20000; boolean updated = false; while (System.currentTimeMillis() < timeout) { ClusterState clusterState = cloudClient.getZkStateReader().getClusterState(); replica = clusterState.getReplica(DEFAULT_COLLECTION, replicaName); updated = replica.getStr("property.preferredleader") == null; if(updated) break; Thread.sleep(50); } assertTrue("Replica property was not removed", updated); } private void testBalanceShardUnique() throws IOException, SolrServerException, KeeperException, InterruptedException { CollectionAdminRequest.BalanceShardUnique balanceShardUniqueRequest = new CollectionAdminRequest.BalanceShardUnique(); cloudClient.setDefaultCollection(DEFAULT_COLLECTION); balanceShardUniqueRequest.setCollection(DEFAULT_COLLECTION); balanceShardUniqueRequest.setPropertyName("preferredLeader"); CollectionAdminResponse response = balanceShardUniqueRequest.process(cloudClient); assertEquals(0, response.getStatus()); verifyUniqueAcrossCollection(cloudClient, DEFAULT_COLLECTION, "property.preferredleader"); } }
{ "content_hash": "4b0b92c1b0f9b9c79ac9b107f19bee5b", "timestamp": "", "source": "github", "line_count": 469, "max_line_length": 119, "avg_line_length": 45.437100213219615, "alnum_prop": 0.764007508212107, "repo_name": "yida-lxw/solr-5.2.0", "id": "89a3a08f1a27f72cb1619d3dc5398e6ed1999f20", "size": "22111", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "solr/core/src/test/org/apache/solr/cloud/CollectionsAPISolrJTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "53286" }, { "name": "C++", "bytes": "13377" }, { "name": "CSS", "bytes": "226047" }, { "name": "GAP", "bytes": "11057" }, { "name": "Gnuplot", "bytes": "2444" }, { "name": "HTML", "bytes": "1590759" }, { "name": "JFlex", "bytes": "108436" }, { "name": "Java", "bytes": "46317546" }, { "name": "JavaScript", "bytes": "1170431" }, { "name": "Perl", "bytes": "86514" }, { "name": "Python", "bytes": "218341" }, { "name": "Shell", "bytes": "167334" }, { "name": "XSLT", "bytes": "160271" } ], "symlink_target": "" }
* Fixed bug in POS Calculator function where certain control tags were being identified as `FOR` tags. --- Notice any issues? Report them here: https://github.com/mghweb/sublime-miva-ide/issues
{ "content_hash": "bb34273cdf573e28fad0ec185b55308b", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 102, "avg_line_length": 32.5, "alnum_prop": 0.7743589743589744, "repo_name": "mghweb/sublime-miva-ide", "id": "8b9ca97a4526335de5b1b22ed73e0df6cb634466", "size": "239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "messages/3.4.4.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "44903" } ], "symlink_target": "" }
import React from 'react'; import cx from 'classnames'; import { Group } from '@vx/group'; import { arc as d3Arc, pie as d3Pie } from 'd3-shape'; import additionalProps from '../util/additionalProps'; export default function Arc({ className = '', top = 0, left = 0, data, centroid, innerRadius = 0, outerRadius, cornerRadius, startAngle = 0, endAngle, padAngle, padRadius, pieSort, pieValue, ...restProps }) { const path = d3Arc(); path.innerRadius(innerRadius); if (outerRadius) path.outerRadius(outerRadius); if (cornerRadius) path.cornerRadius(cornerRadius); if (padRadius) path.padRadius(padRadius); const pie = d3Pie(); if (pieSort) pie.sort(pieSort); if (pieValue) pie.value(pieValue); if (padAngle) pie.padAngle(padAngle); const arcs = pie(data); return ( <Group className="vx-arcs-group" top={top} left={left}> {arcs.map((arc, i) => { let c; if (centroid) c = path.centroid(arc); return ( <g key={`arc-${i}`}> <path className={cx('vx-arc', className)} d={path(arc)} {...additionalProps(restProps, { ...arc, index: i, centroid: c })} /> {centroid && centroid(c, arc)} </g> ); })} </Group> ); }
{ "content_hash": "d0da89f3457de3d603d05a6d71ee7bde", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 80, "avg_line_length": 25.115384615384617, "alnum_prop": 0.5819295558958653, "repo_name": "Flaque/vx", "id": "832bbcd1bd189b6fe84745604819d84a9f04ec27", "size": "1306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/vx-shape/src/shapes/Arc.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14998" }, { "name": "HTML", "bytes": "141351" }, { "name": "JavaScript", "bytes": "616760" }, { "name": "Makefile", "bytes": "1344" } ], "symlink_target": "" }
namespace blink { TEST(NetworkUtilsTest, IsReservedIPAddress) { // Unreserved IPv4 addresses (in various forms). EXPECT_FALSE(network_utils::IsReservedIPAddress("8.8.8.8")); EXPECT_FALSE(network_utils::IsReservedIPAddress("99.64.0.0")); EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15.0.0")); EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15")); EXPECT_FALSE(network_utils::IsReservedIPAddress("212.15.0")); EXPECT_FALSE(network_utils::IsReservedIPAddress("3557752832")); // Reserved IPv4 addresses (in various forms). EXPECT_TRUE(network_utils::IsReservedIPAddress("192.168.0.0")); EXPECT_TRUE(network_utils::IsReservedIPAddress("192.168.0.6")); EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0.0.5")); EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0.0")); EXPECT_TRUE(network_utils::IsReservedIPAddress("10.0")); EXPECT_TRUE(network_utils::IsReservedIPAddress("3232235526")); // Unreserved IPv6 addresses. EXPECT_FALSE(network_utils::IsReservedIPAddress( "[FFC0:ba98:7654:3210:FEDC:BA98:7654:3210]")); EXPECT_FALSE(network_utils::IsReservedIPAddress( "[2000:ba98:7654:2301:EFCD:BA98:7654:3210]")); // IPv4-mapped to IPv6 EXPECT_FALSE(network_utils::IsReservedIPAddress("[::ffff:8.8.8.8]")); // Reserved IPv6 addresses. EXPECT_TRUE(network_utils::IsReservedIPAddress("[::1]")); EXPECT_TRUE(network_utils::IsReservedIPAddress("[::192.9.5.5]")); EXPECT_TRUE(network_utils::IsReservedIPAddress("[::ffff:192.168.1.1]")); EXPECT_TRUE(network_utils::IsReservedIPAddress("[FEED::BEEF]")); EXPECT_TRUE(network_utils::IsReservedIPAddress( "[FEC0:ba98:7654:3210:FEDC:BA98:7654:3210]")); // Not IP addresses at all. EXPECT_FALSE(network_utils::IsReservedIPAddress("example.com")); EXPECT_FALSE(network_utils::IsReservedIPAddress("127.0.0.1.example.com")); // Moar IPv4 for (int i = 0; i < 256; i++) { net::IPAddress address(i, 0, 0, 1); std::string address_string = address.ToString(); if (i == 0 || i == 10 || i == 127 || i == 192 || i > 223) { EXPECT_TRUE(network_utils::IsReservedIPAddress( String::FromUTF8(address_string.data(), address_string.length()))); } else { EXPECT_FALSE(network_utils::IsReservedIPAddress( String::FromUTF8(address_string.data(), address_string.length()))); } } } TEST(NetworkUtilsTest, GetDomainAndRegistry) { EXPECT_EQ("", network_utils::GetDomainAndRegistry( "", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("", network_utils::GetDomainAndRegistry( ".", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("", network_utils::GetDomainAndRegistry( "..", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("", network_utils::GetDomainAndRegistry( "com", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("", network_utils::GetDomainAndRegistry( ".com", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("", network_utils::GetDomainAndRegistry( "www.example.com:8000", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("", network_utils::GetDomainAndRegistry( "localhost", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("", network_utils::GetDomainAndRegistry( "127.0.0.1", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("example.com", network_utils::GetDomainAndRegistry( "example.com", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("example.com", network_utils::GetDomainAndRegistry( "www.example.com", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("example.com", network_utils::GetDomainAndRegistry( "static.example.com", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("example.com", network_utils::GetDomainAndRegistry( "multilevel.www.example.com", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("example.co.uk", network_utils::GetDomainAndRegistry( "www.example.co.uk", network_utils::kIncludePrivateRegistries)); // Verify proper handling of 'private registries'. EXPECT_EQ("foo.appspot.com", network_utils::GetDomainAndRegistry( "www.foo.appspot.com", network_utils::kIncludePrivateRegistries)); EXPECT_EQ("appspot.com", network_utils::GetDomainAndRegistry( "www.foo.appspot.com", network_utils::kExcludePrivateRegistries)); // Verify that unknown registries are included. EXPECT_EQ("example.notarealregistry", network_utils::GetDomainAndRegistry( "www.example.notarealregistry", network_utils::kIncludePrivateRegistries)); } } // namespace blink
{ "content_hash": "cfaf77b299f5f7845a4c06079f0e01c7", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 80, "avg_line_length": 47.75238095238095, "alnum_prop": 0.6519744714798564, "repo_name": "nwjs/chromium.src", "id": "381ab9a1f72f6a6ee855b15c78ac25ebca0ba282", "size": "5402", "binary": false, "copies": "3", "ref": "refs/heads/nw70", "path": "third_party/blink/renderer/platform/network/network_utils_test.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("07_SentenceTheThief")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("07_SentenceTheThief")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9415629e-5c13-4ed6-b924-b34a70a9b705")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "118bdbae80ee8cbfc82af82c0959a055", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.19444444444444, "alnum_prop": 0.7462792345854005, "repo_name": "nellypeneva/SoftUniProjects", "id": "c21915f8ea7f6ff242975d281a815b986feab437", "size": "1414", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "01_ProgrFundamentalsMay/12_Data-Types-More-Exercises/07_SentenceTheThief/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "689865" }, { "name": "CSS", "bytes": "154047" }, { "name": "HTML", "bytes": "26587" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.Diagnostics.Runtime.DacInterface; using Microsoft.Diagnostics.Runtime.Utilities; namespace Microsoft.Diagnostics.Runtime.Implementation { public sealed class ClrmdModule : ClrModule { private const int mdtTypeDef = 0x02000000; private const int mdtTypeRef = 0x01000000; private readonly IModuleData? _data; private readonly IModuleHelpers _helpers; private int _debugMode = int.MaxValue; private MetadataImport? _metadata; private PdbInfo? _pdb; private (ulong MethodTable, int Token)[]? _typeDefMap; private (ulong MethodTable, int Token)[]? _typeRefMap; public override ClrAppDomain AppDomain { get; } public override string? Name { get; } public override string? AssemblyName { get; } public override ulong AssemblyAddress { get; } public override ulong Address { get; } public override bool IsPEFile { get; } public override ulong ImageBase { get; } public override ModuleLayout Layout { get; } public override ulong Size { get; } public override ulong MetadataAddress { get; } public override ulong MetadataLength { get; } public override bool IsDynamic { get; } public override MetadataImport? MetadataImport => _metadata ??= _helpers.GetMetadataImport(this); public ClrmdModule(ClrAppDomain parent, IModuleData data) { if (data is null) throw new ArgumentNullException(nameof(data)); _data = data; _helpers = data.Helpers; AppDomain = parent; Name = data.Name ?? data.FileName; AssemblyName = data.AssemblyName ?? data.FileName; AssemblyAddress = data.AssemblyAddress; Address = data.Address; IsPEFile = data.IsPEFile; ImageBase = data.ILImageBase; Layout = data.IsFlatLayout ? ModuleLayout.Flat : ModuleLayout.Unknown; Size = data.Size; MetadataAddress = data.MetadataStart; MetadataLength = data.MetadataLength; IsDynamic = data.IsReflection || data.IsDynamic; } public ClrmdModule(ClrAppDomain parent, IModuleHelpers helpers, ulong addr) { AppDomain = parent; _helpers = helpers; Address = addr; } public override PdbInfo? Pdb { get { if (_pdb is null) { // Not correct, but as close as we can get until we add more information to the dac. bool virt = Layout != ModuleLayout.Flat; using ReadVirtualStream stream = new ReadVirtualStream(_helpers.DataReader, (long)ImageBase, (long)(Size > 0 ? Size : int.MaxValue)); using PEImage pefile = new PEImage(stream, leaveOpen: true, isVirtual: virt); if (pefile.IsValid) _pdb = pefile.DefaultPdb; } return _pdb; } } public override DebuggableAttribute.DebuggingModes DebuggingMode { get { if (_debugMode == int.MaxValue) _debugMode = GetDebugAttribute(); DebugOnly.Assert(_debugMode != int.MaxValue); return (DebuggableAttribute.DebuggingModes)_debugMode; } } private unsafe int GetDebugAttribute() { MetadataImport? metadata = MetadataImport; if (metadata != null) { try { if (metadata.GetCustomAttributeByName(0x20000001, "System.Diagnostics.DebuggableAttribute", out IntPtr data, out uint cbData) && cbData >= 4) { byte* b = (byte*)data.ToPointer(); ushort opt = b[2]; ushort dbg = b[3]; return (dbg << 8) | opt; } } catch (SEHException) { } } return (int)DebuggableAttribute.DebuggingModes.None; } public override IEnumerable<(ulong MethodTable, int Token)> EnumerateTypeDefToMethodTableMap() { _typeDefMap ??= _helpers.GetSortedTypeDefMap(this); return _typeDefMap.Select(t => (t.MethodTable, t.Token | mdtTypeDef)); } public override ClrType? GetTypeByName(string name) { if (name is null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException($"{nameof(name)} cannot be empty"); // First, look for already constructed types and see if their name matches. List<ulong> lookup = new List<ulong>(256); foreach ((ulong mt, _) in EnumerateTypeDefToMethodTableMap()) { ClrType? type = _helpers.TryGetType(mt); if (type is null) lookup.Add(mt); else if (type.Name == name) return type; } // Since we didn't find pre-constructed types matching, look up the names for all // remaining types without constructing them until we find the right one. foreach (ulong mt in lookup) { string? typeName = _helpers.GetTypeName(mt); if (typeName == name) return _helpers.Factory.GetOrCreateType(mt, 0); } return null; } public override ClrType? ResolveToken(int typeDefOrRefToken) { if (typeDefOrRefToken == 0) return null; ClrHeap? heap = AppDomain?.Runtime?.Heap; if (heap is null) return null; (ulong MethodTable, int Token)[] map; if ((typeDefOrRefToken & mdtTypeDef) != 0) map = _typeDefMap ??= _helpers.GetSortedTypeDefMap(this); else if ((typeDefOrRefToken & mdtTypeRef) != 0) map = _typeRefMap ??= _helpers.GetSortedTypeRefMap(this); else throw new NotSupportedException($"ResolveToken does not support this token type: {typeDefOrRefToken:x}"); int index = map.Search(typeDefOrRefToken & (int)~0xff000000, CompareTo); if (index == -1) return null; return _helpers.Factory.GetOrCreateType(map[index].MethodTable, 0); } private static int CompareTo((ulong MethodTable, int Token) entry, int token) => entry.Token.CompareTo(token); } }
{ "content_hash": "49cbbeb1cf99814c034255f271f78323", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 161, "avg_line_length": 37.909574468085104, "alnum_prop": 0.5655956222814649, "repo_name": "cshung/clrmd", "id": "ff41316d51e5424b2356df3674012a975661f603", "size": "7129", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Microsoft.Diagnostics.Runtime/src/Implementation/ClrmdModule.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "783" }, { "name": "C#", "bytes": "2017678" }, { "name": "CMake", "bytes": "9446" }, { "name": "PowerShell", "bytes": "150642" }, { "name": "Shell", "bytes": "91238" } ], "symlink_target": "" }
package uk.ac.ed.ph.snuggletex.dombuilding; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import uk.ac.ed.ph.snuggletex.definitions.BuiltinCommand; import uk.ac.ed.ph.snuggletex.internal.DOMBuilder; import uk.ac.ed.ph.snuggletex.internal.SnuggleParseException; import uk.ac.ed.ph.snuggletex.tokens.CommandToken; /** * Defines how a {@link BuiltinCommand} should append children to the outgoing * DOM tree. * <p> * An instance of this interface must be stateless once created. * * @author David McKain * @version $Revision$ */ public interface CommandHandler { /** * Called when a {@link CommandToken} is being handled by the {@link DOMBuilder}. * * @param builder {@link DOMBuilder} running this process, which provides access * to convenience method for appending Nodes to the DOM * @param parentElement parent Element that the resulting Nodes should (can) be * added to * @param token Token representing the command being processed. * * @throws SnuggleParseException to indicate a client error * @throws DOMException if the usual errors occur when building the DOM. */ void handleCommand(DOMBuilder builder, Element parentElement, CommandToken token) throws SnuggleParseException; }
{ "content_hash": "e809e969681257f7d54012040fa49589", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 85, "avg_line_length": 34.10526315789474, "alnum_prop": 0.7291666666666666, "repo_name": "kduske-n4/snuggletex", "id": "075d4d5ac790f9bd317553746133e09d67bb2a83", "size": "1390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "snuggletex-core/src/main/java/uk/ac/ed/ph/snuggletex/dombuilding/CommandHandler.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "14653" }, { "name": "Java", "bytes": "1113418" }, { "name": "JavaScript", "bytes": "68568" }, { "name": "TeX", "bytes": "381581" }, { "name": "XSLT", "bytes": "287838" } ], "symlink_target": "" }
package supernovae.world.terrain; import com.fasterxml.jackson.annotation.JsonProperty; public class TerrainTexture { private final String diffuse; private final String normal; private final double scale; public TerrainTexture(@JsonProperty("diffuse")String diffuse, @JsonProperty("normal")String normal, @JsonProperty("scale")double scale) { this.diffuse = diffuse; this.normal = normal; this.scale = scale; } public String getDiffuse() { return diffuse; } public String getNormal() { return normal; } public double getScale() { return scale; } }
{ "content_hash": "7886400d62aae58ecd7a6c248366e1fb", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 62, "avg_line_length": 21.137931034482758, "alnum_prop": 0.7014681892332789, "repo_name": "meltzow/supernovae", "id": "6c3944bdf209e56a72a03e520b520c8547150c2c", "size": "613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/supernovae/world/terrain/TerrainTexture.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3407" }, { "name": "GLSL", "bytes": "27129" }, { "name": "Java", "bytes": "419671" } ], "symlink_target": "" }
package com.manabreak.libclicker; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * A container for all the clicker objects * * @author Harri Pellikka */ public class World implements Serializable { /** * Active generators */ private ArrayList<Generator> mGenerators = new ArrayList<>(); /** * Active automators */ private ArrayList<Automator> mAutomators = new ArrayList<>(); /** * Currencies in use */ private ArrayList<Currency> mCurrencies = new ArrayList<>(); /** * Modifiers in use */ private ArrayList<Modifier> mModifiers = new ArrayList<>(); /** * Speed multiplier - used to multiply the time the world advances */ private double mSpeedMultiplier = 1.0; /** * Should automators be updated? */ private boolean mUpdateAutomators = true; /** * Constructs a new world. All the other components require an existing * "world" to function. A world is a container for the whole system. */ public World() { } /** * Adds a new generator to this world * @param generator Generator to add */ void addGenerator(Generator generator) { if(generator != null && !mGenerators.contains(generator)) { mGenerators.add(generator); } } /** * Returns the number of generators in this world * @return The number of generators in this world */ public int getGeneratorCount() { return mGenerators.size(); } /** * Removes a generator * @param generator Generator to remove */ void removeGenerator(Generator generator) { if(generator != null && mGenerators.contains(generator)) { mGenerators.remove(generator); } } /** * Removes all the generators from this world */ void removeAllGenerators() { mGenerators.clear(); } void addCurrency(Currency c) { if(c != null && !mCurrencies.contains(c)) { mCurrencies.add(c); } } void removeCurrency(Currency c) { if(c != null) { mCurrencies.remove(c); } } Currency getCurrency(int index) { return mCurrencies.get(index); } List<Currency> getCurrencies() { return mCurrencies; } void removeAllCurrencies() { mCurrencies.clear(); } /** * Advances the world state by the given amount of seconds. * Useful when calculating away-from-keyboard income etc. * * @param seconds Seconds to advance */ public void update(double seconds) { seconds *= mSpeedMultiplier; if(mUpdateAutomators) { for(Automator a : mAutomators) { a.update(seconds); } } } void addAutomator(Automator automator) { if(automator != null && !mAutomators.contains(automator)) { mAutomators.add(automator); } } void addModifier(Modifier modifier) { if(modifier != null && !mModifiers.contains(modifier)) { mModifiers.add(modifier); } } double getSpeedMultiplier() { return mSpeedMultiplier; } void setSpeedMultiplier(double multiplier) { mSpeedMultiplier = multiplier; } void disableAutomators() { mUpdateAutomators = false; } void enableAutomators() { mUpdateAutomators = true; } void removeAutomator(Automator automator) { if(automator != null) { mAutomators.remove(automator); } } List<Automator> getAutomators() { return mAutomators; } List<Modifier> getModifiers() { return mModifiers; } void removeModifier(Modifier modifier) { if(modifier != null) { mModifiers.remove(modifier); } } boolean isAutomationEnabled() { return mUpdateAutomators; } }
{ "content_hash": "ef7a1aa099be353e79b28055487fcef7", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 75, "avg_line_length": 21.151658767772513, "alnum_prop": 0.5269997759354694, "repo_name": "manabreak/libclicker", "id": "9b733fadb026ec1eb256bbde5abe5f31d89a006e", "size": "5622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/manabreak/libclicker/World.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "91896" } ], "symlink_target": "" }
/**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include "os_internal.h" #include "up_internal.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: up_copyfullstate * * Description: * Copy the entire register save area (including the floating point * registers if applicable). This is a little faster than most memcpy's * since it does 32-bit transfers. * ****************************************************************************/ void up_copyfullstate(uint32_t *dest, uint32_t *src) { int i; /* In the current ARM model, the state is always copied to and from the * stack and TCB. */ for (i = 0; i < XCPTCONTEXT_REGS; i++) { *dest++ = *src++; } }
{ "content_hash": "3767f73fd13bf1ab2a2e9822297df611", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 78, "avg_line_length": 31.365384615384617, "alnum_prop": 0.2752912323727774, "repo_name": "gcds/project_xxx", "id": "cdc43a9bdb7bf6bdb09d4cf334b5ad08d0208b40", "size": "3444", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "nuttx/arch/arm/src/armv7-a/arm_copyfullstate.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<component name="libraryTable"> <library name="Maven: org.springframework:spring-test:4.3.13.RELEASE"> <CLASSES> <root url="jar://$MAVEN_REPOSITORY$/org/springframework/spring-test/4.3.13.RELEASE/spring-test-4.3.13.RELEASE.jar!/" /> </CLASSES> <JAVADOC> <root url="jar://$MAVEN_REPOSITORY$/org/springframework/spring-test/4.3.13.RELEASE/spring-test-4.3.13.RELEASE-javadoc.jar!/" /> </JAVADOC> <SOURCES> <root url="jar://$MAVEN_REPOSITORY$/org/springframework/spring-test/4.3.13.RELEASE/spring-test-4.3.13.RELEASE-sources.jar!/" /> </SOURCES> </library> </component>
{ "content_hash": "934a5a2136c87605663508d1c0b3f09d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 133, "avg_line_length": 47, "alnum_prop": 0.6808510638297872, "repo_name": "Caua539/OnlineSebum", "id": "0c0fcbf15b593bf1346ed9a32955d24836d49797", "size": "611", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": ".idea/libraries/Maven__org_springframework_spring_test_4_3_13_RELEASE.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20436" }, { "name": "HTML", "bytes": "88530" }, { "name": "Java", "bytes": "680" }, { "name": "JavaScript", "bytes": "2660" } ], "symlink_target": "" }
package clink.impl.async; import java.io.Closeable; import java.io.IOException; import java.util.Objects; import clink.core.Frame; import clink.core.IoArgs; import clink.core.SendPacket; import clink.core.ds.BytePriorityNode; import clink.frame.AbsSendPacketFrame; import clink.frame.CancelSendFrame; import clink.frame.HeartbeatSendFrame; import clink.frame.SendEntityFrame; import clink.frame.SendHeaderFrame; /** * 负责帧级别的读取与发送。 * * @author Ztiany * Email ztiany3@gmail.com * Date 2018/11/27 22:53 */ class AsyncPacketReader implements Closeable { private final PacketProvider mPacketProvider; private volatile IoArgs mIoArgs = new IoArgs(); private volatile BytePriorityNode<Frame> mNode;//帧队列 private volatile int mNodeSize = 0;//节点数量 //唯一标识从 1 开始,最大为 255,理论上最大支持并发 255 个 packet 同时发送 private short mLastIdentifier = 0;//记录最后一次唯一标识 AsyncPacketReader(PacketProvider packetProvider) { mPacketProvider = Objects.requireNonNull(packetProvider); } /** * 取消Packet对应的帧发送,如果当前Packet已发送部分数据(就算只是头数据) * 也应该在当前帧队列中发送一份取消发送的标志{@link CancelSendFrame} * * @param packet 待取消的packet */ synchronized void cancel(SendPacket packet) { if (mNodeSize == 0) { return; } //遍历找到那个需要取消的packet对应的frame for (BytePriorityNode<Frame> x = mNode, before = null; x != null; before = x, x = x.next) { Frame frame = x.item; if (frame instanceof AbsSendPacketFrame) {//是发包的frame才需要被取消 AbsSendPacketFrame sendPacketFrame = (AbsSendPacketFrame) frame; if (sendPacketFrame.getPacket() == packet) {//找到对应的帧(队列中对于每一个包,同时最多只会有一个帧,因为帧是顺序发送的。) boolean removable = sendPacketFrame.abort(); //removable表示是否完美中止 if (removable) { //是完美中止就移除吧 removeFrame(x, before); if (sendPacketFrame instanceof SendHeaderFrame) { // 头帧,并且未被发送任何数据,直接取消后不需要添加取消发送帧 break; } }//removable end //没有完美取消,或者完美取消的不是头帧,则需要发送一个取消帧告知接收方该包被取消了 CancelSendFrame cancelSendFrame = new CancelSendFrame(sendPacketFrame.getBodyIdentifier()); appendNewFrame(cancelSendFrame); // 取消则认为是意外终止,返回失败 mPacketProvider.completedPacket(packet, false); break; }//endPacketFrame.getPacket() == packet end } } } private synchronized void removeFrame(BytePriorityNode<Frame> remove, BytePriorityNode<Frame> before) { if (before == null) { mNode = remove.next; } else { before.next = remove.next; } mNodeSize--; //如果队列空了,看看是否还有需要发送到包。 if (mNode == null) { requestTakePacket(); } } /** * 请求从 {@link #mPacketProvider}队列中拿一份Packet进行发送 * * @return 如果当前Reader中有可以用于网络发送的数据,则返回True */ boolean requestTakePacket() { //如果mNodeSize>=1,直接返回true,表示还有要发送的数据,mNodeSize可以再设置得大一点,用于支持多个线程并发发送。 synchronized (this) { if (mNodeSize >= 1) { return true; } } SendPacket sendPacket = mPacketProvider.takePacket(); if (sendPacket != null) { short identifier = generateIdentifier(); //根据新的包,构建一个头帧添加到节点中 SendHeaderFrame sendHeaderFrame = new SendHeaderFrame(identifier, sendPacket); appendNewFrame(sendHeaderFrame); } synchronized (this) { return mNodeSize > 0; } } boolean requestSendHeartbeatFrame() { synchronized (this) { for (BytePriorityNode<Frame> x = mNode; x != null; x = x.next) { Frame frame = x.item; if (frame.getBodyType() == Frame.TYPE_COMMAND_HEARTBEAT) { return false; } } // 添加心跳帧 appendNewFrame(new HeartbeatSendFrame()); return true; } } /*添加一个新的帧都队列中*/ private synchronized void appendNewFrame(Frame frame) { BytePriorityNode<Frame> newNode = new BytePriorityNode<>(frame); if (mNode != null) { mNode.appendWithPriority(newNode); } else { mNode = newNode; } mNodeSize++; } /** * 关闭当前Reader,关闭时应关闭所有的Frame对应的Packet */ @Override public synchronized void close() { BytePriorityNode<Frame> node = mNode; while (node != null) { Frame frame = mNode.item; if (frame instanceof AbsSendPacketFrame) { ((AbsSendPacketFrame) frame).abort(); mPacketProvider.completedPacket(((AbsSendPacketFrame) frame).getPacket(), false); } node = node.next; } mNode = null; mNodeSize = 0; } /** * 构建一份Packet惟一标志 * * @return 标志为:1~255 */ private short generateIdentifier() { short identifier = ++mLastIdentifier; if (identifier == 255) { mLastIdentifier = 0; } return identifier; } /** * 填充数据到IoArgs中 * * @return 如果当前有可用于发送的帧,则填充数据并返回,如果填充失败可返回null */ IoArgs fillData() { //没有数据了,则返回null Frame currentFrame = getCurrentFrame(); if (currentFrame == null) { return null; } try { //返回true表示该帧的数据消费完了,handle方法是同步的。 if (currentFrame.handle(mIoArgs)) { //因为handle方法是同步的,不可能有两个线程同事进入到该条件块内 Frame nextFrame = currentFrame.nextFrame(); //nextFrame 方法是同步的 if (nextFrame != null) { appendNewFrame(nextFrame); } else if (currentFrame instanceof SendEntityFrame) {//是实体帧,且它的nextFrame 为 null,则说明其对应的包发送完了。 mPacketProvider.completedPacket(((SendEntityFrame) currentFrame).getPacket(), true); } //既然当前帧发完了,就弹出来 popCurrentFrame(); } return mIoArgs; } catch (IOException e) { e.printStackTrace(); } return null; } private synchronized void popCurrentFrame() { mNode = mNode.next; mNodeSize--; //如果队列空了,看看是否还有需要发送到包。 if (mNode == null) { requestTakePacket(); } } private synchronized Frame getCurrentFrame() { if (mNode != null) { return mNode.item; } return null; } /** * Packet提供者 */ interface PacketProvider { /** * 拿Packet操作 * * @return 如果队列有可以发送的Packet则返回不为null */ SendPacket takePacket(); /** * 结束一份Packet * * @param sendPacket 发送包 * @param isSucceed 是否成功发送完成 */ void completedPacket(SendPacket sendPacket, boolean isSucceed); } }
{ "content_hash": "ed831c0e79eaf6556217a308028c4e6e", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 111, "avg_line_length": 28.55421686746988, "alnum_prop": 0.5589310829817159, "repo_name": "Ztiany/CodeRepository", "id": "85bec5eb96910adfa061a963bd877bed759ca2ea", "size": "8360", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Java/Imooc-Socket/Java-Socket/src/main/chat-room-optimize/clink/impl/async/AsyncPacketReader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "104421" }, { "name": "C++", "bytes": "43060" }, { "name": "CMake", "bytes": "7529" }, { "name": "CSS", "bytes": "9794" }, { "name": "Groovy", "bytes": "193822" }, { "name": "HTML", "bytes": "239910" }, { "name": "Java", "bytes": "3587367" }, { "name": "JavaScript", "bytes": "294734" }, { "name": "Kotlin", "bytes": "203000" }, { "name": "Makefile", "bytes": "15406" }, { "name": "Python", "bytes": "17218" }, { "name": "Shell", "bytes": "1356" } ], "symlink_target": "" }
#include "lapacke.h" #include "lapacke_utils.h" lapack_int LAPACKE_clauum( int matrix_order, char uplo, lapack_int n, lapack_complex_float* a, lapack_int lda ) { if( matrix_order != LAPACK_COL_MAJOR && matrix_order != LAPACK_ROW_MAJOR ) { LAPACKE_xerbla( "LAPACKE_clauum", -1 ); return -1; } #ifndef LAPACK_DISABLE_NAN_CHECK /* Optionally check input matrices for NaNs */ if( LAPACKE_csy_nancheck( matrix_order, uplo, n, a, lda ) ) { return -4; } #endif return LAPACKE_clauum_work( matrix_order, uplo, n, a, lda ); }
{ "content_hash": "9d66478d243fddbe01619ab681bccc39", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 80, "avg_line_length": 29.75, "alnum_prop": 0.6100840336134454, "repo_name": "jmfranck/pyspecdata", "id": "030bc4036ceb5b39682e2df9945d277a38aaed3f", "size": "2498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lapack-3.4.0/lapacke/src/lapacke_clauum.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "5068" }, { "name": "Batchfile", "bytes": "4997" }, { "name": "C", "bytes": "8900726" }, { "name": "C++", "bytes": "1180920" }, { "name": "CMake", "bytes": "98271" }, { "name": "Fortran", "bytes": "37850006" }, { "name": "Gnuplot", "bytes": "2847" }, { "name": "Makefile", "bytes": "90858" }, { "name": "Python", "bytes": "874744" }, { "name": "Shell", "bytes": "91118" }, { "name": "TeX", "bytes": "575084" }, { "name": "UnrealScript", "bytes": "2877" } ], "symlink_target": "" }
package org.gradle.test.performance.mediummonolithicjavaproject.p193; public class Production3868 { private String property0; public String getProperty0() { return property0; } public void setProperty0(String value) { property0 = value; } private String property1; public String getProperty1() { return property1; } public void setProperty1(String value) { property1 = value; } private String property2; public String getProperty2() { return property2; } public void setProperty2(String value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
{ "content_hash": "a74171759a8eb0dfe6523f345ae25213", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 69, "avg_line_length": 18.00952380952381, "alnum_prop": 0.6171337916446324, "repo_name": "oehme/analysing-gradle-performance", "id": "cb14219d3ef55d3674e758e0a4385c50964ec164", "size": "1891", "binary": false, "copies": "1", "ref": "refs/heads/before", "path": "my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p193/Production3868.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "40770723" } ], "symlink_target": "" }
/** * Created by cghislai on 15/01/16. */ import {Injectable, Inject} from 'angular2/core'; import {Http} from 'angular2/http'; import {Pos, PosFactory} from './domain/pos'; import {CachedWSClient} from './utils/cachedWsClient'; import {COMPTOIR_SERVICE_URL} from '../config/service'; @Injectable() export class PosClient extends CachedWSClient<Pos> { constructor(@Inject(Http) http:Http, @Inject(COMPTOIR_SERVICE_URL) serviceUrl:string) { super(); this.http = http; this.resourcePath = '/pos'; this.webServiceUrl = serviceUrl; this.jsonReviver = PosFactory.fromJSONReviver; } }
{ "content_hash": "8d4d2cb681c83477b88b8139c3f0d7bf", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 91, "avg_line_length": 28.727272727272727, "alnum_prop": 0.6819620253164557, "repo_name": "cghislai/comptoir", "id": "34767a26140bb529eefd890e727e36d0a7bfdd6a", "size": "632", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/client/pos.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "72700" }, { "name": "HTML", "bytes": "75947" }, { "name": "JavaScript", "bytes": "134" }, { "name": "Shell", "bytes": "146" }, { "name": "TypeScript", "bytes": "390409" } ], "symlink_target": "" }
class GamesController < ApplicationController before_action :set_game, only: [:show, :edit, :update, :destroy] before_action :set_user, only: [:index, :new, :create, :edit, :update] before_action :login_required, only: [:edit, :update, :new, :create, :destroy, :invite] def invite @game = Game.find(params[:game_id]) @user = User.find(params[:user_id]) UserMailer.invitation(@game, @user).deliver redirect_to @game, notice: 'Invitation sent!' end def index @games = Game.all end def new @game = Game.new end def show @weather = Wunderground.new(ENV['wu_key']) # @reservation = @game.reservations.find_by(:player_id => current_user.id) end # creates new game object from params hash def create @game = Game.new(game_params) if @game.save @user.host = true redirect_to @game, notice: "Congrats! You're hosting a game." end end # update game attributes def update if @game.update(game_params) redirect_to @game, notice: 'Game updated.' else redirect_to @game, notice: 'Sorry, unable to update game.' end end # destroy game and dependents (reservations) def destroy @game.destroy respond_to do |format| format.html { redirect_to games_path } # format.json { head :no_content } end end private # finds existing game object in database using params[:id] def set_game @game = Game.find(params[:id]) end # sets @user to current_user def set_user @user = current_user end # strong params def game_params params.require(:game).permit(:id, :description, :date, :time, :game_category, :player_limit, :park_id, :host_id, :additional_info, reservations_attributes: [:player_id, :game_id]) end end
{ "content_hash": "278d5488a9cfe71af333a9d6b694148a", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 183, "avg_line_length": 25.63768115942029, "alnum_prop": 0.6546071226681741, "repo_name": "laranicole70/park_friends", "id": "4f189626fa994a21e4f06f68e9ac6092d058d006", "size": "1769", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/controllers/games_controller.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15162" }, { "name": "HTML", "bytes": "38790" }, { "name": "JavaScript", "bytes": "1122" }, { "name": "Ruby", "bytes": "58195" } ], "symlink_target": "" }
'use strict'; // Configuring the Articles module angular.module('orders').run(['Menus','USER_ROLES', function(Menus, USER_ROLES) { // Set top bar menu items Menus.addMenuItem('topbar', '订单', 'orders', 'dropdown', '/orders(/create)?', false, [USER_ROLES.service]); Menus.addSubMenuItem('topbar', 'orders', '订单列表', 'orders'); Menus.addSubMenuItem('topbar', 'orders', '新建订单', 'orders/create'); } ]);
{ "content_hash": "a40262d2bb8a84ef07ffeb131f3fbd71", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 108, "avg_line_length": 37, "alnum_prop": 0.6683046683046683, "repo_name": "brooklynb7/nnb-mean", "id": "adca77d1831ab1cf11ffad8349d764e9780b9df1", "size": "427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/modules/orders/config/orders.client.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1048" }, { "name": "HTML", "bytes": "42417" }, { "name": "JavaScript", "bytes": "160608" }, { "name": "Shell", "bytes": "664" } ], "symlink_target": "" }
<div class="panel panel-default" > <div class="panel-heading"> <h3 class="panel-title" translate>addWorker</h3> <i class="glyphicon glyphicon-remove action action-close right" ng-click="closeThisDialog(true)"></i> </div> <div class="panel-body"> <ul> <li ng-repeat=""> </li> </ul> <label class="btn btn-primary" ng-model="checkModel.left" uib-btn-checkbox>Left</label> <label class="btn btn-primary" ng-model="checkModel.middle" uib-btn-checkbox>Middle</label> <label class="btn btn-primary" ng-model="checkModel.right" uib-btn-checkbox>Right</label> </div> <div class="col-lg-12 tools"> <button type="submit" class="btn btn-primary" ng-click="save()" translate><i class="glyphicon glyphicon-floppy-disk"></i> save</button> <button class="btn btn-default right" ng-click="closeThisDialog(true)" style="margin-right: 15px;">Cancel</button> </div> </div> </div>
{ "content_hash": "87fb27143c25ad34459060538afdadb0", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 137, "avg_line_length": 40.72727272727273, "alnum_prop": 0.6941964285714286, "repo_name": "kutsaniuk/hotels", "id": "cbc04bcf20b47cec08a39d6abfb8564a2bd0f3d4", "size": "896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/webapp/app/modules/hotel/action/hotel.action.new.worker.view.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17866" }, { "name": "HTML", "bytes": "37211" }, { "name": "Java", "bytes": "31640" }, { "name": "JavaScript", "bytes": "52772" } ], "symlink_target": "" }
import React from 'react' import reactCSS from 'reactcss' export const ChromePointerCircle = () => { const styles = reactCSS({ 'default': { picker: { width: '12px', height: '12px', borderRadius: '6px', boxShadow: 'inset 0 0 0 1px #fff', transform: 'translate(-6px, -6px)', }, }, }) return ( <div style={ styles.picker } /> ) } export default ChromePointerCircle
{ "content_hash": "6b1188ec14053aefdce7250cf8f893e5", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 43, "avg_line_length": 19.863636363636363, "alnum_prop": 0.5652173913043478, "repo_name": "casesandberg/react-color", "id": "a5fb6a2b89fcc75dd54beea0d1b4f366e07cee8d", "size": "437", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/chrome/ChromePointerCircle.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "143718" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Eelly\SDK\Im\Service; /** * Interface TeamMemberStatInterface. * * @author zhangyangxun */ interface TeamMemberStatInterface { /** * 初始化群成员订单数据 * @internal * @Async(route=initMemberStat) * * @param array $data * @return bool * * @author zhangyangxun * @since 2019-04-23 */ public function initMemberStat(array $data): bool; /** * 订单支付后更新群统计 * @internal * * @param array $data * @return bool * * @author zhangyangxun * @since 2019-04-22 */ public function afterPayOrderSuccess(array $data): bool; /** * 订单完成后更新群统计 * @internal * * @param array $data * @return bool * * @author zhangyangxun * @since 2019-04-23 */ public function afterFinishedOrderSuccess(array $data): bool; }
{ "content_hash": "3d166f60c1a4f77df8bfb4da88cec345", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 65, "avg_line_length": 16.830188679245282, "alnum_prop": 0.5751121076233184, "repo_name": "zydZhang/eelly-sdk-php", "id": "f9eaf519f988108b73e589e9d195d0a401d16957", "size": "1147", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/SDK/Im/Service/TeamMemberStatInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "4296311" } ], "symlink_target": "" }
class TreeBuilderOps < TreeBuilder # common methods for OPS subclasses has_kids_for LdapRegion, [:x_get_tree_lr_kids] has_kids_for Zone, [:x_get_tree_zone_kids] private def active_node_set(_tree_nodes) # FIXME: check all below case @name when :vmdb_tree @tree_state.x_node_set("root", @name) else @tree_state.x_node_set("svr-#{to_cid(MiqServer.my_server(true).id)}", @name) unless @tree_state.x_node(@name) end end def x_get_tree_zone_kids(object, count_only) count_only_or_objects(count_only, object.miq_servers, "name") end # Get root nodes count/array for explorer tree def x_get_tree_roots(count_only, _options) region = MiqRegion.my_region objects = region.zones.sort_by { |z| z.name.downcase } count_only_or_objects(count_only, objects, nil) end def x_get_tree_lr_kids(object, count_only) if count_only return (object.ldap_domains.count) else return (object.ldap_domains.sort_by { |a| a.name.to_s }) end end end
{ "content_hash": "9e83ed3106b7587ac12e5c79f769a25d", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 115, "avg_line_length": 28.36111111111111, "alnum_prop": 0.6660137120470128, "repo_name": "KevinLoiseau/manageiq", "id": "f72487adaac490a51c06c6ab05c5bb11f0e7436b", "size": "1021", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/presenters/tree_builder_ops.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2289" }, { "name": "CSS", "bytes": "92091" }, { "name": "HTML", "bytes": "1624415" }, { "name": "JavaScript", "bytes": "965445" }, { "name": "Makefile", "bytes": "827" }, { "name": "Perl", "bytes": "1846" }, { "name": "PowerShell", "bytes": "5869" }, { "name": "Ruby", "bytes": "21922596" }, { "name": "Shell", "bytes": "2605" } ], "symlink_target": "" }
module Azure::Network::Mgmt::V2019_11_01 module Models # # ExpressRouteCircuit resource. # class ExpressRouteCircuit < Resource include MsRestAzure # @return [ExpressRouteCircuitSku] The SKU. attr_accessor :sku # @return [Boolean] Allow classic operations. attr_accessor :allow_classic_operations # @return [String] The CircuitProvisioningState state of the resource. attr_accessor :circuit_provisioning_state # @return [ServiceProviderProvisioningState] The # ServiceProviderProvisioningState state of the resource. Possible values # include: 'NotProvisioned', 'Provisioning', 'Provisioned', # 'Deprovisioning' attr_accessor :service_provider_provisioning_state # @return [Array<ExpressRouteCircuitAuthorization>] The list of # authorizations. attr_accessor :authorizations # @return [Array<ExpressRouteCircuitPeering>] The list of peerings. attr_accessor :peerings # @return [String] The ServiceKey. attr_accessor :service_key # @return [String] The ServiceProviderNotes. attr_accessor :service_provider_notes # @return [ExpressRouteCircuitServiceProviderProperties] The # ServiceProviderProperties. attr_accessor :service_provider_properties # @return [SubResource] The reference to the ExpressRoutePort resource # when the circuit is provisioned on an ExpressRoutePort resource. attr_accessor :express_route_port # @return [Float] The bandwidth of the circuit when the circuit is # provisioned on an ExpressRoutePort resource. attr_accessor :bandwidth_in_gbps # @return [Integer] The identifier of the circuit traffic. Outer tag for # QinQ encapsulation. attr_accessor :stag # @return [ProvisioningState] The provisioning state of the express route # circuit resource. Possible values include: 'Succeeded', 'Updating', # 'Deleting', 'Failed' attr_accessor :provisioning_state # @return [String] The GatewayManager Etag. attr_accessor :gateway_manager_etag # @return [Boolean] Flag denoting Global reach status. attr_accessor :global_reach_enabled # @return [String] A unique read-only string that changes whenever the # resource is updated. attr_accessor :etag # # Mapper for ExpressRouteCircuit class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ExpressRouteCircuit', type: { name: 'Composite', class_name: 'ExpressRouteCircuit', model_properties: { id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } }, name: { client_side_validation: true, required: false, read_only: true, serialized_name: 'name', type: { name: 'String' } }, type: { client_side_validation: true, required: false, read_only: true, serialized_name: 'type', type: { name: 'String' } }, location: { client_side_validation: true, required: false, serialized_name: 'location', type: { name: 'String' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, sku: { client_side_validation: true, required: false, serialized_name: 'sku', type: { name: 'Composite', class_name: 'ExpressRouteCircuitSku' } }, allow_classic_operations: { client_side_validation: true, required: false, serialized_name: 'properties.allowClassicOperations', type: { name: 'Boolean' } }, circuit_provisioning_state: { client_side_validation: true, required: false, serialized_name: 'properties.circuitProvisioningState', type: { name: 'String' } }, service_provider_provisioning_state: { client_side_validation: true, required: false, serialized_name: 'properties.serviceProviderProvisioningState', type: { name: 'String' } }, authorizations: { client_side_validation: true, required: false, serialized_name: 'properties.authorizations', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ExpressRouteCircuitAuthorizationElementType', type: { name: 'Composite', class_name: 'ExpressRouteCircuitAuthorization' } } } }, peerings: { client_side_validation: true, required: false, serialized_name: 'properties.peerings', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ExpressRouteCircuitPeeringElementType', type: { name: 'Composite', class_name: 'ExpressRouteCircuitPeering' } } } }, service_key: { client_side_validation: true, required: false, serialized_name: 'properties.serviceKey', type: { name: 'String' } }, service_provider_notes: { client_side_validation: true, required: false, serialized_name: 'properties.serviceProviderNotes', type: { name: 'String' } }, service_provider_properties: { client_side_validation: true, required: false, serialized_name: 'properties.serviceProviderProperties', type: { name: 'Composite', class_name: 'ExpressRouteCircuitServiceProviderProperties' } }, express_route_port: { client_side_validation: true, required: false, serialized_name: 'properties.expressRoutePort', type: { name: 'Composite', class_name: 'SubResource' } }, bandwidth_in_gbps: { client_side_validation: true, required: false, serialized_name: 'properties.bandwidthInGbps', type: { name: 'Double' } }, stag: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.stag', type: { name: 'Number' } }, provisioning_state: { client_side_validation: true, required: false, read_only: true, serialized_name: 'properties.provisioningState', type: { name: 'String' } }, gateway_manager_etag: { client_side_validation: true, required: false, serialized_name: 'properties.gatewayManagerEtag', type: { name: 'String' } }, global_reach_enabled: { client_side_validation: true, required: false, serialized_name: 'properties.globalReachEnabled', type: { name: 'Boolean' } }, etag: { client_side_validation: true, required: false, read_only: true, serialized_name: 'etag', type: { name: 'String' } } } } } end end end end
{ "content_hash": "aa0b1bc4df61b43ba3ba969312159fd7", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 85, "avg_line_length": 33.47766323024055, "alnum_prop": 0.46468897556969824, "repo_name": "Azure/azure-sdk-for-ruby", "id": "5c4a9d778fd63ffe3b7d83246ab78b812bf8a851", "size": "9906", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "management/azure_mgmt_network/lib/2019-11-01/generated/azure_mgmt_network/models/express_route_circuit.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "345216400" }, { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]--> <!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]--> <!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]--> <head> <meta charset="utf-8"> <title>A Portable Hack for Parallella - RayHightower.com</title> <meta name="author" content="Raymond T. Hightower - Chicago Ruby on Rails & iOS Developer"> <meta name="description" content="Portability for Parallella-sized devices. Beaglebone Black, Raspberry Pi, and Parallella are three small, powerful Linux-based computers. But in &hellip;"> <!-- http://t.co/dKP3o1e --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="canonical" href="http://RayHightower.com/blog/2013/11/10/a-portable-hack-for-parallella"> <link href="/favicon.png" rel="icon"> <link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css"> <link href="/atom.xml" rel="alternate" title="RayHightower.com" type="application/atom+xml"> <script src="/javascripts/modernizr-2.0.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- next two lines copied from octopress-yortz example --> <!-- <link rel="stylesheet" href="http://localhost:4000/blog/assets/app-1094520b91e86929a538822f9bde7657.css"> &#8211;> <script src="http://localhost:4000/blog/assets/app-f6a144c800a4818350bed53d612cb244.js"></script> <script>!window.jQuery && document.write(unescape('%3Cscript src="/javascripts/libs/jquery.min.js"%3E%3C/script%3E'))</script> <script src="/javascripts/octopress.js" type="text/javascript"></script> <!--Fonts from Google"s Web font directory at http://google.com/webfonts --> <link href="http://fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic" rel="stylesheet" type="text/css"> <!-- Arvo is like Rockwell. Added by RTH on 12/27/2012. --> <link href='http://fonts.googleapis.com/css?family=Arvo:700' rel='stylesheet' type='text/css'> <script id="search-results-template" type="text/x-handlebars-template"> {{#entries}} <article> <h3> <small><time datetime="{{date}}" pubdate>{{date}}</time></small> <a href="{{url}}">{{title}}</a> <p>tagged: {{ tags }} | category: <a href="/categories/{{category }}">{{category}}</a></p> </h3> </article> {{/entries}} </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-330946-28']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body > <header role="banner"><hgroup> <h1><a href="/">RayHightower.com</a></h1> <h2>Thoughts about Ruby, Rails, iOS, the Internet of Things, software development, and business growth.</h2> </hgroup> </header> <nav role="navigation"><ul class="subscription" data-subscription="rss"> <li><a href="/atom.xml" rel="subscribe-rss" title="subscribe via RSS">RSS</a></li> </ul> <form action="/search" method="get"> <fieldset role ="search"> <input type="text" id="search-query" name="q" placeholder="Search" autocomplete="off" class="search" /> </fieldset> </form> <ul class="main-navigation"> <li><a href="/">Home</a></li> <li><a href="/blog/archives">Archives</a></li> <li><a href="/speaking">Speaking</a></li> <li><a href="/if-rudyard-kipling">If</a></li> <li><a href="/contact">Contact</a></li> </ul> </nav> <div id="main"> <div id="content"> <div> <article class="hentry" role="article"> <header> <h1 class="entry-title">A Portable Hack for Parallella</h1> <p class="meta"> <time class='entry-date' datetime='2013-11-10T23:05:00-06:00'><span class='date'>November 10, 2013</span> <span class='time'></span></time> </p> </header> <div class="entry-content"><p><span class='caption-wrapper left'><img class='caption' src='/images/parallella-portable.png' width='' height='' alt='Portability for Parallella-sized devices.' title='Portability for Parallella-sized devices.'><span class='caption-text'>Portability for Parallella-sized devices.</span></span> <a href="/blog/2013/05/22/beaglebone-black-running-ruby-on-rails/">Beaglebone Black</a>, <a href="/blog/2012/12/03/ruby-on-raspberry-pi/">Raspberry Pi</a>, and <a href="/blog/2013/06/22/preparing-for-parallella-64-cores-installing-go-on-mac-os-x/">Parallella</a> are three small, powerful Linux-based computers. But in order to make these devices truly portable, we need a way to carry a monitor and keyboard along. This article describes one hack that works.</p> <h3>Inspiration in a Suitcase</h3> <p>The HP 5036 Microprocessor Lab gave me my first exposure to assembler language. I was eighteen, working my first software internship, and loving every minute of it. When I devised ways to complete my <em>regular work</em> faster than management expected, I had some time on my hands. So I spent time learning assembler with the HP 5036.</p> <!--more--> <p><span class='caption-wrapper'><img class='caption' src='/images/hp-5036.png' width='' height='' alt='HP 5036 Microprocessor Lab' title='HP 5036 Microprocessor Lab'><span class='caption-text'>HP 5036 Microprocessor Lab</span></span></p> <p>The entire 5036 fits in a suitcase&hellip; how cool is that! Here&rsquo;s how the 5036 works:</p> <ol> <li>Start by writing assembler-level code by hand on paper.</li> <li>Grab the reference book for the microprocessor running on the board, Intel 8080.</li> <li>For each assembler-level command, find the corresponding 2-digit hexidecimal operation code.</li> <li>Key the op code into the 5036 by hand.</li> <li>Run the program.</li> </ol> <p>Working with the 5036 was addictive in a positive way. In a subsequent job, where I wrote assembler to drive hardware devices, I was ready.</p> <h3>Portability Needed</h3> <p>Fast forward a few decades. We now have the Raspberry Pi, BeagleBone Black, and Parallella. Wonderful devices with one flaw in common: No portability. That&rsquo;s when I had a flashback to my days with the 5036.</p> <p>I bought a $35 technician box from Home Depot and I ripped out the insides. Micro Center had 720p LCD monitors on sale for $90, so I bought one of those. I didn&rsquo;t want to spend the extra bucks for a 1080p LCD because you never know how something like this might work out! Finally, I topped everything off with a $25 keyboard/trackpad combo from Amazon. The result appears in the photo at the top of this article. Special thanks to Ericka [last name unknown] from Home Depot who gave me tons of ideas on how to securely fasten the monitor to the case.</p> <h3>Why?</h3> <p>Why did I spend the time and money to assemble this kit? It&rsquo;s all about learning. Devs learn more when we interact with other devs &ndash; people who are learning some of the same things that we&rsquo;re wrestling with. And sometimes the things we need to learn are too new for books.</p> <p>By carrying my Raspberry Pi, BeagleBone Black, and Parallella with me in a portable unit, I can share my experiences with other devs and learn more in the process. Everybody wins when that happens.</p> <h3>Thanks SCNA!</h3> <p>The organizers of <a href="http://scna.softwarecraftsmanship.org/">Software Craftsmanship North America (SCNA)</a> gave me the opportunity to present this story as a lightning talk at the conference. Slides are here:</p> <center><script async class="speakerdeck-embed" data-id="b3558fd02cac0131cfc62a9baba32394" data-ratio="1.29456384323641" src="//speakerdeck.com/assets/embed.js"></script></center> <p>Thank you SCNA! As I shared with the other devs at SCNA, I will gladly post my mistakes and <em>gotchas</em> here for people who want to build a unit like this. Let&rsquo;s build!</p> </div> <footer> <p class="meta"> <span class="byline author vcard">Posted by <span class="fn">Raymond T. Hightower - Chicago Ruby on Rails & iOS Developer</span></span> <time class='entry-date' datetime='2013-11-10T23:05:00-06:00'><span class='date'>November 10, 2013</span> <span class='time'></span></time> <span class="categories"> <a class='category' href='/blog/categories/beaglebone-black/'>beaglebone black</a>, <a class='category' href='/blog/categories/education/'>education</a>, <a class='category' href='/blog/categories/high-performance-computing/'>high performance computing</a>, <a class='category' href='/blog/categories/parallella/'>parallella</a>, <a class='category' href='/blog/categories/raspberry-pi/'>raspberry pi</a> </span> </p> <div class="sharing"> <a href="//twitter.com/share" class="twitter-share-button" data-url="http://RayHightower.com/blog/2013/11/10/a-portable-hack-for-parallella/" data-via="" data-counturl="http://RayHightower.com/blog/2013/11/10/a-portable-hack-for-parallella/" >Tweet</a> </div> <p class="meta"> <a class="basic-alignment left" href="/blog/2013/11/01/building-an-os-x-app-with-rubymotion/" title="Previous Post: Building an OS X App With RubyMotion">&laquo; Building an OS X App With RubyMotion</a> <a class="basic-alignment right" href="/blog/2013/11/11/os-x-and-rubymotion-finishing-up/" title="Next Post: OS X and RubyMotion, Finishing Up">OS X and RubyMotion, Finishing Up &raquo;</a> </p> </footer> </article> <section> <h1>Comments</h1> <div id="disqus_thread" aria-live="polite"><noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </section> </div> <aside class="sidebar"> <section> <h1>About</h1> <p>Raymond T. Hightower is a software developer, founder of <a href="http://wisdomgroup.com">WisdomGroup</a>, organizer of <a href="http://chicagoruby.org">ChicagoRuby</a>, and producer of <a href="http://windycityrails.org">WindyCityRails</a> & <a href="http://rubycaribe.com">RubyCaribe</a>. He is currently exploring parallelism and concurrency. </p> <p> <a href="http://windycityrails.org"><img src="/images/windycityrails.jpg" width="191" height="42" alt="WindyCityRails - Ruby on Rails Conference in Chicago, IL USA" title="WindyCityRails - Ruby on Rails Conference in Chicago, IL USA"/></a><br/> <a href="http://wisdomgroup.com"><img src="/images/wisdomgroup.jpg" width="191" height="42" alt="WisdomGroup - Ruby on Rails. MVP. iPhone. iPad." title="WisdomGroup - Ruby on Rails. MVP. iPhone. iPad."/></a><br/> <a href="http://rubycaribe.com"><img src="/images/rubycaribe.jpg" width="191" height="42" alt="RubyCaribe - Ruby conference in Barbados. Ruby in the Caribbean. Ruby on Rails." title="RubyCaribe - Ruby conference in Barbados. Ruby in the Caribbean. Ruby on Rails."/></a><br/> <a href="http://chicagoruby.org"><img src="/images/chicagoruby.jpg" width="191" height="42" alt="ChicagoRuby - Ruby on Rails in Chicago, IL USA" title="ChicagoRuby - Ruby on Rails in Chicago, IL USA" /></a><br/> </p> </section> <section> <h1>Observations</h1> <ul> <li>The best way to make dreams come true is to wake up.<br/> ~Mae C. Jemison</li> <li>Tact is the art of making a point without making an enemy.<br/>~Isaac Newton</li> <li>Find a need and fulfill it. Successful businesses are founded on the needs of people.<br/>~A. G. Gaston</li> <li>It&#8217;s kind of fun to do the impossible.<br/>~Walt Disney</li> <li>If one ox could not do the job they did not try to grow a bigger ox, but used two oxen. When we need greater computer power, the answer is not to get a bigger computer, but to build systems of computers and operate them in parallel.<br/>~Grace Hopper</li> <li>A person with a new idea is a crank until the idea succeeds.<br/> ~Mark Twain</li> <li>My over arching framework is 1) Pure appreciation. 2) Spend time with good people. 3) Leave the world a little better.<br/>~Mellody Hobson</li> <li>Everybody told me no at first, including my wife. I turned the nos into yeses and the disadvantages into advantages.<br/>~John H. Johnson</li> <li>I would have been fired a hundred times at a company run by MBAs. But I never went into business to make money. I went&#8230; so that I could do interesting things that hadn&#8217;t been done before.<br/>~Amar Bose</li> <li>Don&#8217;t undertake a project unless it is manifestly important and nearly impossible.<br/>~Edwin Land</li> </ul> </section> <section> <h1>Speaking</h1> <ul> <li><a href="http://in5.ae/">in5 hub Innovation Hub</a><br/>in Dubai, UAE</li> <li><a href="https://www.eventbrite.com/e/devnights-robot-tickets-15433389684">DevNights at The Cribb</a><br/>in Dubai, UAE</li> <li><a href="http://rubyfuza.org/">Rubyfuza</a><br/>in Cape Town, South Africa</li> <li><a href="http://www.meetup.com/nodejs/events/206159562/">NYC Node JS Meetup</a><br/>in New York, NY</li> <li><a href="http://www.meetup.com/Chicago-Nodejs/events/177556202">Chicago Node.js</a><br/>in Chicago, IL</li> <li><a href="https://www.eventbrite.com/e/cloudcamp-chicago-developer-night-registration-11736697779">CloudCamp Chicago - Developer Night</a><br/>in Chicago, IL</li> <li><a href="http://LinuxBarbados.org">LinuxBarbados</a><br/>at University of the West Indies<br/>at Cave Hill, Barbados</li> <li><a href="http://flourishconf.com/2014/">Flourish Open Source Conference</a><br/>at University of Illinois at Chicago</li> <li><a href="http://www.meetup.com/Chicago-RubyMotion/events/143412442/">Chicago RubyMotion</a> at DevBootcamp<br/>in Chicago, IL</li> <li><a href="http://chippewavalleycodecamp.com/">Chippewa Valley Code Camp</a><br/>in Eau Claire, WI</li> <li><a href="/blog/2012/10/29/building-ios-apps-with-ruby-motion/">Aloha Ruby</a> in Honolulu, HI</li> <li><a href="/blog/2012/10/29/building-ios-apps-with-ruby-motion/">Magic Ruby</a> in Orlando, FL</li> </ul> </section> <section> <h1>Social Media</h1> <ul class="social" id="css3"> <li class="twitter"> <a href="http://twitter.com/rayhightower"><strong>Twitter</strong></a> </li> <li class="github"> <a href="http://www.github.com/rayhightower"><strong>GitHub</strong></a> </li> <li class="linkedin"> <a href="http://www.linkedin.com/in/rayhightower"><strong>LinkedIn</strong></a> </li> <li class="vimeo"> <a href="http://vimeo.com/chicagoruby"><strong>Vimeo</strong></a> </li> </ul> <p>&nbsp;<br/>&nbsp;</p> </section> <!-- added by RTH 1/9/2013 from http://www.dotnetguy.co.uk/post/2012/06/25/octopress-category-list-plugin/ --> <section> <h1>Blog Categories</h1> <ul id="categories"> <li class='category'><a href='/blog/categories/arduino/'>arduino (2)</a></li> <li class='category'><a href='/blog/categories/beaglebone-black/'>beaglebone black (8)</a></li> <li class='category'><a href='/blog/categories/business/'>business (35)</a></li> <li class='category'><a href='/blog/categories/community/'>community (38)</a></li> <li class='category'><a href='/blog/categories/education/'>education (48)</a></li> <li class='category'><a href='/blog/categories/environment-of-respect/'>environment of respect (3)</a></li> <li class='category'><a href='/blog/categories/functional-programming/'>functional programming (1)</a></li> <li class='category'><a href='/blog/categories/git/'>git (6)</a></li> <li class='category'><a href='/blog/categories/high-performance-computing/'>high performance computing (8)</a></li> <li class='category'><a href='/blog/categories/ios/'>ios (13)</a></li> <li class='category'><a href='/blog/categories/iot/'>iot (13)</a></li> <li class='category'><a href='/blog/categories/linux/'>linux (15)</a></li> <li class='category'><a href='/blog/categories/node/'>node (4)</a></li> <li class='category'><a href='/blog/categories/objective-c/'>objective-c (5)</a></li> <li class='category'><a href='/blog/categories/openrov/'>openrov (13)</a></li> <li class='category'><a href='/blog/categories/os-x/'>os x (13)</a></li> <li class='category'><a href='/blog/categories/parallella/'>parallella (10)</a></li> <li class='category'><a href='/blog/categories/rails/'>rails (11)</a></li> <li class='category'><a href='/blog/categories/raspberri-pi/'>raspberri pi (1)</a></li> <li class='category'><a href='/blog/categories/raspberry-pi/'>raspberry pi (4)</a></li> <li class='category'><a href='/blog/categories/ruby/'>ruby (27)</a></li> <li class='category'><a href='/blog/categories/rubymotion/'>rubymotion (13)</a></li> <li class='category'><a href='/blog/categories/solar/'>solar (1)</a></li> <li class='category'><a href='/blog/categories/ux/'>ux (3)</a></li> <li class='category'><a href='/blog/categories/vim/'>vim (5)</a></li> <li class='category'><a href='/blog/categories/xcode/'>xcode (5)</a></li> </ul> </section> <section> <h1>Featured Articles</h1> <ul> <li><a href="/blog/2014/07/07/parallella-quick-start-guide-with-gotchas/">Parallella Quick Start Guide</a></li> <li><a href="/blog/2014/06/16/citizen-science-with-openrov/">Citizen Science With OpenROV</a></li> <li><a href="/blog/2014/01/02/beaglebone-black-ubuntu-part-1/">Ruby on BeagleBone Black</a></li> <li><a href="/blog/2012/12/03/ruby-on-raspberry-pi/">Ruby on Raspberry Pi</a></li> <li><a href="/blog/2014/04/12/recursion-and-memoization/">Recursion and Memoization</a></li> <li><a href="/blog/2014/05/30/how-to-grow-a-user-group/">How to Grow a User Group</a></li> <li><a href="/blog/2013/05/16/upgrading-ruby-with-rvm/">Upgrading Ruby With RVM</a></li> </ul> </section> <section> <h1>Vim</h1> <p>I don&#8217;t always use a modal editor. But when I do, I use <a href="/blog/2013/01/12/why-i-use-vim/">Vim</a>.</p> <p> <a href="/blog/2013/01/12/why-i-use-vim/"><img src="/images/vim_editor.gif" width="125" height="60" alt="Vim, the editor" title="Vim, the editor"/></a> </p> </section> </aside> </div> </div> <footer role="contentinfo"><p> Copyright &copy; 2015 - Raymond T. Hightower - Chicago Ruby on Rails & iOS Developer - <span class="credit">Powered by <a href="http://octopress.org">Octopress</a></span> </p> </footer> <script type="text/javascript"> var disqus_shortname = 'rayhightower'; // var disqus_developer = 1; var disqus_identifier = 'http://RayHightower.com/blog/2013/11/10/a-portable-hack-for-parallella/'; var disqus_url = 'http://RayHightower.com/blog/2013/11/10/a-portable-hack-for-parallella/'; var disqus_script = 'embed.js'; (function () { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); }()); </script> <script type="text/javascript"> (function(){ var twitterWidgets = document.createElement('script'); twitterWidgets.type = 'text/javascript'; twitterWidgets.async = true; twitterWidgets.src = '//platform.twitter.com/widgets.js'; document.getElementsByTagName('head')[0].appendChild(twitterWidgets); })(); </script> </body> </html>
{ "content_hash": "0898cc03519114bba5f7743489b01ce3", "timestamp": "", "source": "github", "line_count": 395, "max_line_length": 564, "avg_line_length": 50.32658227848101, "alnum_prop": 0.6832335630564917, "repo_name": "RayHightower/rayhightower.github.octo-broken", "id": "0c8a07593d9aaf118a4dce0cb5f1425862aa6e92", "size": "19880", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blog/2013/11/10/a-portable-hack-for-parallella/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "4211" }, { "name": "HTML", "bytes": "5614450" }, { "name": "JavaScript", "bytes": "276918" }, { "name": "Ruby", "bytes": "6093" } ], "symlink_target": "" }
namespace _01.Person { using System; public class Child : Person { public Child(string name, int age) : base(name, age) { } public override int Age { get => base.Age; protected set { if (value > 15) { throw new ArgumentException("Child's age must be less than 15!"); } base.Age = value; } } } }
{ "content_hash": "26ce3e608fec19dd3542e5ace519a32d", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 85, "avg_line_length": 19.74074074074074, "alnum_prop": 0.3771106941838649, "repo_name": "stoyanov7/SoftwareUniversity", "id": "2f0e41d81bbe6beea992388e4d39d8abf4b518fa", "size": "535", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "C#Development/C#OOPBasics/Inheritance-Exercise/01.Person/01.Person/Child.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "108" }, { "name": "C#", "bytes": "2704772" }, { "name": "CSS", "bytes": "133306" }, { "name": "HTML", "bytes": "248344" }, { "name": "Handlebars", "bytes": "4195" }, { "name": "JavaScript", "bytes": "398638" }, { "name": "PLpgSQL", "bytes": "5115" }, { "name": "TSQL", "bytes": "46837" }, { "name": "TypeScript", "bytes": "19883" } ], "symlink_target": "" }
package talecraft.network; import static net.minecraftforge.fml.relauncher.Side.CLIENT; import static net.minecraftforge.fml.relauncher.Side.SERVER; import static talecraft.TaleCraft.network; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.relauncher.Side; import talecraft.network.packets.CreateMovingBlockPacket; import talecraft.network.packets.DecoratorGuiPacket; import talecraft.network.packets.DecoratorPacket; import talecraft.network.packets.DialogueOpenPacket; import talecraft.network.packets.DoorPacket; import talecraft.network.packets.FadePacket; import talecraft.network.packets.ForceF1Packet; import talecraft.network.packets.GameruleSyncPacket; import talecraft.network.packets.GunReloadPacket; import talecraft.network.packets.MovingBlockDataUpdatePacket; import talecraft.network.packets.NPCDataPacket; import talecraft.network.packets.NPCDataUpdatePacket; import talecraft.network.packets.NPCDialogueOptionPacket; import talecraft.network.packets.NPCOpenPacket; import talecraft.network.packets.PlayerNBTDataMergePacket; import talecraft.network.packets.SoundsPacket; import talecraft.network.packets.StringNBTCommandPacket; import talecraft.network.packets.StringNBTCommandPacketClient; import talecraft.network.packets.TriggerItemPacket; import talecraft.network.packets.UndoGuiPacket; import talecraft.network.packets.UndoPacket; import talecraft.network.packets.VoxelatorGuiPacket; import talecraft.network.packets.VoxelatorPacket; import talecraft.network.packets.WorkbenchCraftingPacket; public class TaleCraftNetwork { private static int discriminator = 0; public static void preInit(){ network = NetworkRegistry.INSTANCE.newSimpleChannel("TalecraftNet"); register(PlayerNBTDataMergePacket.Handler.class, PlayerNBTDataMergePacket.class, CLIENT); register(VoxelatorGuiPacket.Handler.class, VoxelatorGuiPacket.class, CLIENT); register(DoorPacket.Handler.class, DoorPacket.class, CLIENT); register(VoxelatorPacket.Handler.class, VoxelatorPacket.class, SERVER); register(NPCDataPacket.Handler.class, NPCDataPacket.class, SERVER); register(NPCOpenPacket.Handler.class, NPCOpenPacket.class, CLIENT); register(NPCDataUpdatePacket.Handler.class, NPCDataUpdatePacket.class, CLIENT); register(MovingBlockDataUpdatePacket.Handler.class, MovingBlockDataUpdatePacket.class, CLIENT); register(SoundsPacket.Handler.class, SoundsPacket.class, CLIENT); register(FadePacket.Handler.class, FadePacket.class, CLIENT); register(GunReloadPacket.Handler.class, GunReloadPacket.class, SERVER); register(WorkbenchCraftingPacket.Handler.class, WorkbenchCraftingPacket.class, SERVER); register(StringNBTCommandPacket.Handler.class, StringNBTCommandPacket.class, SERVER); register(StringNBTCommandPacketClient.Handler.class, StringNBTCommandPacketClient.class, CLIENT); register(ForceF1Packet.Handler.class, ForceF1Packet.class, CLIENT); register(DecoratorPacket.Handler.class, DecoratorPacket.class, SERVER); register(DecoratorGuiPacket.Handler.class, DecoratorGuiPacket.class, CLIENT); register(TriggerItemPacket.Handler.class, TriggerItemPacket.class, SERVER); register(DialogueOpenPacket.Handler.class, DialogueOpenPacket.class, CLIENT); register(NPCDialogueOptionPacket.Handler.class, NPCDialogueOptionPacket.class, SERVER); register(CreateMovingBlockPacket.Handler.class, CreateMovingBlockPacket.class, SERVER); register(GameruleSyncPacket.Handler.class, GameruleSyncPacket.class, CLIENT); register(UndoGuiPacket.Handler.class, UndoGuiPacket.class, CLIENT); register(UndoPacket.Handler.class, UndoPacket.class, SERVER); } private static <REQ extends IMessage, REPLY extends IMessage> void register(Class<? extends IMessageHandler<REQ, REPLY>> handler, Class<REQ> packet, Side side){ network.registerMessage(handler, packet, discriminator, side); discriminator++; } }
{ "content_hash": "1fc20f703f81acfd36ab6cbcaf9cef5f", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 161, "avg_line_length": 54.391891891891895, "alnum_prop": 0.84472049689441, "repo_name": "tiffit/TaleCraft", "id": "c5e6e13d6d73676b9343b1c35551879da66b3df0", "size": "4025", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/talecraft/network/TaleCraftNetwork.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "4144104" }, { "name": "JavaScript", "bytes": "1833" } ], "symlink_target": "" }
{% extends "layout.html" %} {% block page_title %} Home Office - Visa and Immigration {% endblock %} {% block content %} <main id="content" role="main"> {% include "includes/phase_banner_alpha.html" %} {% include "includes/outgoing-header.html" %} <h2 class="heading-medium" style="margin-top: 20px;">Find an applicant</h2> <form action="/outgoing-comms/5/check-input" method="get" class="form"> <fieldset> <div class="form-group error"> <label class="form-label-bold" for="cid"> Unique application number (UAN) <span class="error-message">Unknown UAN</span> </label> <input class="form-control form-control-1-4" id="cid" name="pnn" type="text" autocomplete="off" placeholder="UAN or CID case ID"> </div> </fieldset> <div class="form-group"> <input type="submit" class="button continue-button" value="Find"> </div> </form> </main> {% endblock %}
{ "content_hash": "6e954cdcef05798b899ac235ff190a44", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 145, "avg_line_length": 35.37931034482759, "alnum_prop": 0.5750487329434698, "repo_name": "christaylor-hod/home-office-notifying-people", "id": "b69dec7ac5d11f11d31ab3ba47eeee595d710626", "size": "1026", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/outgoing-comms/5/index-errors.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "188716" }, { "name": "HTML", "bytes": "407241" }, { "name": "JavaScript", "bytes": "108422" }, { "name": "Shell", "bytes": "649" } ], "symlink_target": "" }
require 'spork' #require 'spork/ext/ruby-debug' Spork.prefork do ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| # ## Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false end end Spork.each_run do # This code will be run each time you run your specs. end
{ "content_hash": "3f5ab43ff245429fe050e831aacf7096", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 81, "avg_line_length": 31.642857142857142, "alnum_prop": 0.6975169300225733, "repo_name": "cmaitchison/coming_soon", "id": "28f831530423743d3a7641b7c2849cf589eb0eec", "size": "1329", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "9781" }, { "name": "JavaScript", "bytes": "616" }, { "name": "Ruby", "bytes": "31407" } ], "symlink_target": "" }
var express = require('express'), app = express(), http = require('http').Server(app), io = require('socket.io')(http), port = process.env.PORT || 3000; app.use(express.static('client')); app.use(express.static('node_modules/d3/')); app.use(express.static('node_modules/socket.io-client/')); io.on('connect', function (socket) { console.log('a user connected..'); io.emit('get_speedtest_history'); socket.on('disconnect', function () { console.log('a user disconnected'); }); socket.on('broadcast_results', function (data) { io.emit('display_results', data); }); }); var runLoggers = function () { setTimeout(function () { console.log('Running automated speedtest') io.emit('run_speedtest'); runLoggers(); }, 10000); }; runLoggers(); var server = http.listen(port, function () { console.log('Server running on http://localhost:' + port + '/'); });
{ "content_hash": "557771077b25a6654169f72b78677fb7", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 68, "avg_line_length": 25.62162162162162, "alnum_prop": 0.6107594936708861, "repo_name": "teodoran/d3-speedtest-tutorial", "id": "2ed6ac5ce885dfb5d58f04da483dc729bbd116fd", "size": "948", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14495" }, { "name": "HTML", "bytes": "763" }, { "name": "JavaScript", "bytes": "4460" } ], "symlink_target": "" }
package de.mbdevelopment.android.rbtvsendeplan; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; /** * Dialog to confirm the deletion of a recurring reminder */ public class DeleteReminderDialogFragment extends DialogFragment { /** * Fragment tag */ public static final String TAG = "delete_reminder_dialog_fragment"; /** * Argument key for the event */ public static final String ARG_EVENT = "arg_event"; /** * Callbacks to be used on option selection */ private SelectionListener callbacks; /** * Callback methods that have to be implemented by the attaching {@link android.app.Activity} */ public interface SelectionListener { /** * Is called if the deletion of a recurring reminder has been confirmed by the user * @param event The selected event holding an recurringEventId */ public void onDeletionConfirmed(Event event); /** * Is called if the deletion of a recurring reminder has been cancelled by the user */ public void onDeletionCancelled(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { callbacks = (SelectionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + "must implement SelectionListener"); } } @Override public void onDetach() { super.onDetach(); callbacks = null; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Get parameter final Event event = (Event) getArguments().get(ARG_EVENT); // Construct dialog AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.reminder_remove_dialog_message) .setPositiveButton(R.string.reminder_remove_dialog_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (callbacks != null) callbacks.onDeletionConfirmed(event); } }) .setNegativeButton(R.string.reminder_remove_dialog_negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (callbacks != null) callbacks.onDeletionCancelled(); } }); // Create dialog and return it return builder.create(); } }
{ "content_hash": "40156e522b75c5c429842bc3175026dd", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 116, "avg_line_length": 32.92941176470588, "alnum_prop": 0.6259378349410504, "repo_name": "Any1s/RBTV-Sendeplan", "id": "12122822d1d6c71d1f3624b95a45be5767aa4908", "size": "2799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/de/mbdevelopment/android/rbtvsendeplan/DeleteReminderDialogFragment.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "136253" } ], "symlink_target": "" }
package manning.chapterNine; import java.util.Collection; import manning.utils.Portfolio; import manning.utils.PortfolioServiceInterface; import manning.utils.User; import com.opensymphony.xwork2.ActionSupport; /* * This action retrieves the data model for building the Struts 2 Portfolio HomePage. * This mostly consists of a list of the current user/accounts. */ public class PortfolioHomePage extends ActionSupport { public String execute(){ Collection users = getPortfolioService().getUsers(); setUsers( users ); String selectedUsername = getPortfolioService().getDefaultUser(); setDefaultUsername( selectedUsername ); return SUCCESS; } /* JavaBeans Properties to Receive Request Parameters */ private Collection users; private String defaultUsername; public Collection getUsers() { return users; } public void setUsers(Collection users) { this.users = users; } public String getDefaultUsername() { return defaultUsername; } public void setDefaultUsername(String username) { this.defaultUsername = username; } /* * Field with getter and setter for PortfolioService object, which will be injected * via Spring. */ PortfolioServiceInterface portfolioService; public PortfolioServiceInterface getPortfolioService( ) { return portfolioService; } public void setPortfolioService(PortfolioServiceInterface portfolioService) { this.portfolioService = portfolioService; } }
{ "content_hash": "c99ae826f38c625d075674d909ffaabd", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 85, "avg_line_length": 22.791044776119403, "alnum_prop": 0.730844793713163, "repo_name": "myid999/struts2demo", "id": "6d16c0198e4277ef09b0ba57d05a34a0bac9137c", "size": "1527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "s2ia/src/manning/chapterNine/PortfolioHomePage.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "146" }, { "name": "FreeMarker", "bytes": "314" }, { "name": "HTML", "bytes": "217" }, { "name": "Java", "bytes": "325935" }, { "name": "JavaScript", "bytes": "5048" } ], "symlink_target": "" }
package com.johnathangilday.autograder.cv import org.scalatest.{FlatSpec, Matchers} import com.johnathangilday.autograder.testutils.TestImgFactory class GraderSpec extends FlatSpec with Matchers with GraderComponentImpl with CropperComponentImpl with SheetProcessorComponentImpl { it should "use the sheet processor to grade an exam" in { val img = TestImgFactory.wholeSheetFile val rows = grader.grade(img) assert (rows match { case Seq( Seq(false, true, false, false), Seq(true, false, false, false), Seq(false, false, false, true), Seq(false, false, false, false), Seq(false, false, true, false), Seq(true, false, false, false), Seq(false, true, false, false), Seq(false, false, false, false), Seq(true, false, false, false), Seq(false, true, false, false), Seq(false, false, true, false), Seq(false, false, false, true), Seq(false, false, false, false), Seq(true, false, false, false), Seq(false, true, false, false), Seq(false, true, false, false), Seq(true, false, false, false) ) => true case _ => false }) } }
{ "content_hash": "e902ca0b68beb9ea5bac80dea217f26e", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 133, "avg_line_length": 33.2, "alnum_prop": 0.6523235800344234, "repo_name": "gilday/fast-grades", "id": "e237508ac55b1f71da33f8db46d74b8b166135e1", "size": "1162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/scala/com/johnathangilday/autograder/cv/GraderSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "30474" }, { "name": "JavaScript", "bytes": "17882" }, { "name": "Scala", "bytes": "24149" } ], "symlink_target": "" }
define(['jquery', 'narrativeConfig', 'kbase/js/widgets/appInfoPanel', 'testUtil'], ( $, Config, InfoPanel, TestUtil ) => { 'use strict'; function makeDummyPanel() { return InfoPanel.make({ appId: 'SomeModule/some_app', appModule: 'SomeModule', tag: 'release', }); } /** * Mock data for the NMS.get_method_full_info call. */ const methodFullInfoMock = [ [ { description: 'This is a KBase wrapper for SomeModule.', authors: ['author1', 'author2'], }, ], ]; /** * Mock data for the Catalog.get_exec_aggr_stats call. */ const getExecAggrStatsMock = [ [ { number_of_calls: 5, }, ], ]; /** * Mock data for the Catalog.get_module_info call. */ const getModuleInfoMock = [ { module_name: 'SomeModule', release: { timestamp: 1555098756211, }, }, ]; describe('Test the App Info Panel module', () => { beforeEach(() => { jasmine.Ajax.install(); jasmine.Ajax.stubRequest( Config.url('narrative_method_store'), /get_method_full_info/ ).andReturn({ status: 200, statusText: 'HTTP/1 200 OK', contentType: 'application/json', responseText: JSON.stringify({ version: '1.1', id: '12345', result: methodFullInfoMock, }), }); jasmine.Ajax.stubRequest(Config.url('catalog'), /get_exec_aggr_stats/).andReturn({ status: 200, statusText: 'HTTP/1 200 OK', contentType: 'application/json', responseText: JSON.stringify({ version: '1.1', id: '12345', result: getExecAggrStatsMock, }), }); jasmine.Ajax.stubRequest(Config.url('catalog'), /get_module_info/).andReturn({ status: 200, statusText: 'HTTP/1 200 OK', contentType: 'application/json', responseText: JSON.stringify({ version: '1.1', id: '12345', result: getModuleInfoMock, }), }); }); afterEach(() => { jasmine.Ajax.uninstall(); TestUtil.clearRuntime(); }); it('Loads the module with its expected constructor', () => { expect(InfoPanel).not.toBe(null); expect(InfoPanel.make).toBeDefined(); }); it('Has expected functions when instantiated', () => { const panel = makeDummyPanel(); ['start', 'stop'].forEach((fn) => { expect(panel[fn]).toBeDefined(); }); }); it('Can render with "start" and return a Promise', () => { const panel = makeDummyPanel(); const myNode = $('<div>'); return panel.start({ node: myNode }).then(() => { expect(myNode.find('.kb-app-cell-info-desc').text()).toContain( 'This is a KBase wrapper for SomeModule.' ); }); }); it('Can unrender with "stop" and return a Promise', () => { const panel = makeDummyPanel(); const myNode = $('<div>'); return panel .start({ node: myNode }) .then(() => { return panel.stop(); }) .then(() => { expect(myNode.text()).toEqual(''); }); }); }); });
{ "content_hash": "410f06211fbb95aab5b2c4fe3239113e", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 94, "avg_line_length": 29.515151515151516, "alnum_prop": 0.43711498973305957, "repo_name": "briehl/narrative", "id": "ccf6f180ef895eb509f93a825b9f7c7d2a7f2c4c", "size": "3896", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "test/unit/spec/appWidgets/infoPanelSpec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7500" }, { "name": "Dockerfile", "bytes": "5410" }, { "name": "HTML", "bytes": "60140" }, { "name": "JavaScript", "bytes": "9978264" }, { "name": "Makefile", "bytes": "2040" }, { "name": "PHP", "bytes": "1691" }, { "name": "Python", "bytes": "1514459" }, { "name": "R", "bytes": "743" }, { "name": "Ruby", "bytes": "3328" }, { "name": "SCSS", "bytes": "149018" }, { "name": "Shell", "bytes": "24864" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <id>cadastrar-empresas-que-utilizam-benzeno</id> <dbId>833</dbId> <nome>Cadastrar empresas que utilizam Benzeno</nome> <sigla></sigla> <nomes-populares> <item id="660">CETRAB</item> </nomes-populares> <descricao>Este serviço permite o cadastro, junto ao Ministério do Trabalho, das empresas que produzem ou lidam com Benzeno, como demanda a legislação.</descricao> <contato>Departamento de Segurança e Saúde no Trabalho (Secretaria de Inspeção do Trabalho) * Fone: (61) 2031-6689</contato> <gratuito>true</gratuito> <porcentagem-digital>0</porcentagem-digital> <solicitantes> <solicitante id="852"> <tipo>Empresas</tipo> <requisitos>Que produzem, transportam, armazenam, utilizam ou manipulam o produto Benzeno e suas misturas líquidas contendo 1% ou mais de volume</requisitos> </solicitante> </solicitantes> <tempo-total-estimado> <entre min="7" max="15" unidade="dias-corridos"/> <descricao></descricao> </tempo-total-estimado> <validade-documento/> <etapas> <etapa id="2229"> <titulo>Preenchimento e entrega do formulário</titulo> <descricao>O representante da empresa irá retirar, preencher e entregar o formulário no local de atendimento.</descricao> <documentos> <default> <item id="2365">Formulário</item> <item id="2366">Documentação da empresa</item> </default> </documentos> <custos> <default/> </custos> <canais-de-prestacao> <default> <canal-de-prestacao id="2789" tipo="presencial"> <descricao>Superintendências Regionais de Trabalho e Emprego</descricao> </canal-de-prestacao> </default> </canais-de-prestacao> </etapa> <etapa id="2230"> <titulo>Confirmação do registro</titulo> <descricao>A empresa receberá ofício confirmando seu cadastro.</descricao> <documentos> <default/> </documentos> <custos> <default/> </custos> <canais-de-prestacao> <default> <canal-de-prestacao id="2790" tipo="postal"> <descricao>Endereço informado da sede da empresa</descricao> </canal-de-prestacao> </default> </canais-de-prestacao> </etapa> </etapas> <orgao id="2844"/> <segmentos-da-sociedade> <item idSegmento="3" idServicoSegmento="2452">Empresas</item> </segmentos-da-sociedade> <areas-de-interesse> <item>Fiscalização do Estado</item> <item>Segurança e Ordem Pública</item> </areas-de-interesse> <palavras-chave> <item id="1986">Benzeno</item> <item id="1987">Insalubridade</item> <item id="1988">Norma Regulamentadora nº 15</item> </palavras-chave> <legislacoes> <item id="665">[NR-15 ATIVIDADES E OPERAÇÕES INSALUBRES (115.000-6)](http://sislex.previdencia.gov.br/paginas/05/mtb/15.htm)</item> </legislacoes> </servico>
{ "content_hash": "86082b2c09fc08344f9453f806ec5265", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 173, "avg_line_length": 43.407407407407405, "alnum_prop": 0.5918657565415245, "repo_name": "servicosgovbr/cartas-de-homologacao", "id": "bf46f8e3c9ad658cdd7c3ba4813ac7d6cc495567", "size": "3544", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cartas-servico/v3/servicos/cadastrar-empresas-que-utilizam-benzeno.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "906" } ], "symlink_target": "" }
using System; using System.ComponentModel; using System.Collections.Generic; using Newtonsoft.Json; using System.Linq; using STEP; namespace IFC { /// <summary> /// <see href="http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcquantitylength.htm"/> /// </summary> public partial class IfcQuantityLength : IfcPhysicalSimpleQuantity { public IfcLengthMeasure LengthValue{get;set;} public IfcLabel Formula{get;set;} // optional /// <summary> /// Construct a IfcQuantityLength with all required attributes. /// </summary> public IfcQuantityLength(IfcLabel name,IfcLengthMeasure lengthValue):base(name) { LengthValue = lengthValue; } /// <summary> /// Construct a IfcQuantityLength with required and optional attributes. /// </summary> [JsonConstructor] public IfcQuantityLength(IfcLabel name,IfcText description,IfcNamedUnit unit,IfcLengthMeasure lengthValue,IfcLabel formula):base(name,description,unit) { LengthValue = lengthValue; Formula = formula; } public static new IfcQuantityLength FromJSON(string json){ return JsonConvert.DeserializeObject<IfcQuantityLength>(json); } public override string GetStepParameters() { var parameters = new List<string>(); parameters.Add(Name != null ? Name.ToStepValue() : "$"); parameters.Add(Description != null ? Description.ToStepValue() : "$"); parameters.Add(Unit != null ? Unit.ToStepValue() : "$"); parameters.Add(LengthValue != null ? LengthValue.ToStepValue() : "$"); parameters.Add(Formula != null ? Formula.ToStepValue() : "$"); return string.Join(", ", parameters.ToArray()); } } }
{ "content_hash": "3b74d33895ca45c33f40d6083ebdc18b", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 153, "avg_line_length": 31.37735849056604, "alnum_prop": 0.7059530968129886, "repo_name": "ikeough/IFC-gen", "id": "af277de190397648dd3161d53e73eb3acb9d6aeb", "size": "1665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lang/csharp/src/IFC/IfcQuantityLength.g.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "16049" }, { "name": "Batchfile", "bytes": "593" }, { "name": "C#", "bytes": "2679991" }, { "name": "JavaScript", "bytes": "319" }, { "name": "Makefile", "bytes": "1222" }, { "name": "TypeScript", "bytes": "1605804" } ], "symlink_target": "" }
<?php if (!defined('PHPUnit_MAIN_METHOD')) { define('PHPUnit_MAIN_METHOD', 'Zend_Form_SubFormTest::main'); } require_once dirname(__FILE__) . '/../../TestHelper.php'; require_once 'PHPUnit/Framework/TestSuite.php'; require_once 'PHPUnit/TextUI/TestRunner.php'; // error_reporting(E_ALL); require_once 'Zend/Form/SubForm.php'; require_once 'Zend/View.php'; class Zend_Form_SubFormTest extends PHPUnit_Framework_TestCase { public static function main() { require_once "PHPUnit/TextUI/TestRunner.php"; $suite = new PHPUnit_Framework_TestSuite('Zend_Form_SubFormTest'); $result = PHPUnit_TextUI_TestRunner::run($suite); } public function setUp() { Zend_Form::setDefaultTranslator(null); $this->form = new Zend_Form_SubForm(); } public function tearDown() { } // General public function testSubFormUtilizesDefaultDecorators() { $decorators = $this->form->getDecorators(); $this->assertTrue(array_key_exists('Zend_Form_Decorator_FormElements', $decorators)); $this->assertTrue(array_key_exists('Zend_Form_Decorator_HtmlTag', $decorators)); $this->assertTrue(array_key_exists('Zend_Form_Decorator_Fieldset', $decorators)); $this->assertTrue(array_key_exists('Zend_Form_Decorator_DtDdWrapper', $decorators)); $htmlTag = $decorators['Zend_Form_Decorator_HtmlTag']; $tag = $htmlTag->getOption('tag'); $this->assertEquals('dl', $tag); } public function testSubFormIsArrayByDefault() { $this->assertTrue($this->form->isArray()); } public function testElementsBelongToSubFormNameByDefault() { $this->testSubFormIsArrayByDefault(); $this->form->setName('foo'); $this->assertEquals($this->form->getName(), $this->form->getElementsBelongTo()); } // Extensions public function testInitCalledBeforeLoadDecorators() { $form = new Zend_Form_SubFormTest_SubForm(); $decorators = $form->getDecorators(); $this->assertTrue(empty($decorators)); } // Bugfixes /** * @see ZF-2883 */ public function testDisplayGroupsShouldInheritSubFormNamespace() { $this->form->addElement('text', 'foo') ->addElement('text', 'bar') ->addDisplayGroup(array('foo', 'bar'), 'foobar'); $form = new Zend_Form(); $form->addSubForm($this->form, 'attributes'); $html = $form->render(new Zend_View()); $this->assertContains('name="attributes[foo]"', $html); $this->assertContains('name="attributes[bar]"', $html); } /** * @see ZF-3272 */ public function testRenderedSubFormDtShouldContainNoBreakSpace() { $subForm = new Zend_Form_SubForm(array( 'elements' => array( 'foo' => 'text', 'bar' => 'text', ), )); $form = new Zend_Form(); $form->addSubForm($subForm, 'foobar') ->setView(new Zend_View); $html = $form->render(); $this->assertContains('<dt>&nbsp;</dt>', $html); } } class Zend_Form_SubFormTest_SubForm extends Zend_Form_SubForm { public function init() { $this->setDisableLoadDefaultDecorators(true); } } if (PHPUnit_MAIN_METHOD == 'Zend_Form_SubFormTest::main') { Zend_Form_SubFormTest::main(); }
{ "content_hash": "bafb31ca3dbe5138be6b9ce35393ec63", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 93, "avg_line_length": 28.949152542372882, "alnum_prop": 0.6068501170960188, "repo_name": "lortnus/zf1", "id": "6d7f79ff957c50f413231deb8f391f8ca54055f2", "size": "3416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Zend/Form/SubFormTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "19503" }, { "name": "Batchfile", "bytes": "923" }, { "name": "CSS", "bytes": "283009" }, { "name": "HTML", "bytes": "320526" }, { "name": "JavaScript", "bytes": "3569402" }, { "name": "PHP", "bytes": "15011043" }, { "name": "Python", "bytes": "448" }, { "name": "Roff", "bytes": "307" }, { "name": "Shell", "bytes": "8473" }, { "name": "XSLT", "bytes": "44369" } ], "symlink_target": "" }
package ws.leipold.felix.swingutils; /** * * * User: felix * * Date: 19.07.2005 */ public interface ActionStatus { public boolean isCanceled(); /** Appends a message*/ public void appendMessage(String message); /** @param progress value between 0-100 */ public void complete(double progress); }
{ "content_hash": "3f92f604b7f6f8b87ad23e6498ecac26", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 46, "avg_line_length": 21.125, "alnum_prop": 0.6331360946745562, "repo_name": "neher/jgoodies-extensions", "id": "875b785a703ddc9e15e020fed9fb7f9f6b32e1c2", "size": "338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/ws/leipold/felix/swingutils/ActionStatus.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "124043" } ], "symlink_target": "" }
<?php namespace Mustache\Parser\Node; use Mustache\Compiler\CompilerInterface; use Mustache\Lexer\Token\TokenInterface; /** * @package Mustache * @license MIT License <LICENSE> * @link http://github.com/adlawson/mustache */ abstract class Node implements NodeInterface { /** * @var NodeInterface */ protected $next; /** * @var NodeInterface */ protected $previous; /** * @var string */ protected $value; /** * @param string $value */ public function __construct($value) { $this->value = strval($value); } /** * Set the next node * * @param NodeInterface $node */ public function setNext(NodeInterface $node) { $this->next = $node; } /** * Set the previous node * * This also sets self as the next node on the * node given here. * * @param NodeInterface $node */ public function setPrevious(NodeInterface $node) { $this->previous = $node; $node->setNext($this); } }
{ "content_hash": "8fe612d3c4ef3b13bb25613b5425e8d3", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 52, "avg_line_length": 17.770491803278688, "alnum_prop": 0.5608856088560885, "repo_name": "adlawson/php-mustache", "id": "7c6cbde9c8267ca02effafaa5b8921558aa60dc5", "size": "1084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Mustache/Parser/Node/Node.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "54063" } ], "symlink_target": "" }
 using System.Globalization; namespace System.Windows.Controls.PropertyGrid.ComponentModel { public class UInt32Converter : BaseNumberConverter { internal override object FromString(string value, CultureInfo culture) { return uint.Parse(value, culture); } internal override object FromString(string value, NumberFormatInfo formatInfo) { return uint.Parse(value, NumberStyles.Integer, formatInfo); } internal override object FromString(string value, int radix) { return Convert.ToUInt32(value, radix); } internal override string ToString(object value, NumberFormatInfo formatInfo) { uint num = (uint)value; return num.ToString("G", formatInfo); } internal override Type TargetType { get { return typeof(uint); } } } }
{ "content_hash": "a5a176fd16c2aed805e2d205f4cc9b61", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 82, "avg_line_length": 23.6, "alnum_prop": 0.6937046004842615, "repo_name": "DenisVuyka/SPG", "id": "480ac7880dea4df58c48c979fb3d670c1b15dc16", "size": "1429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SPG/ComponentModel/UInt32Converter.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "166185" } ], "symlink_target": "" }
using Core.Common.Reflect; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Core.Common.Crypto; namespace Core.Common.Data { public static class DataContext { } }
{ "content_hash": "bd13fa0fa65285602c383a50b18a4942", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 40, "avg_line_length": 20.857142857142858, "alnum_prop": 0.8127853881278538, "repo_name": "toeb/core.common", "id": "a581a4837f8cf41d984a2e6962595099e51b4aed", "size": "438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core.Common/Data/DataContext.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "109" }, { "name": "C#", "bytes": "958427" } ], "symlink_target": "" }
package com.mailrest.maildal.repository; public interface BoxRef extends DomainRef { String boxId(); }
{ "content_hash": "87664c43b79e7a13127b0f13be7a3c43", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 43, "avg_line_length": 13.625, "alnum_prop": 0.7614678899082569, "repo_name": "mailrest/maildal", "id": "896a202bdd2e04cf584a4682f81bc0e85a6ab08e", "size": "729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/mailrest/maildal/repository/BoxRef.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "210146" } ], "symlink_target": "" }
import time import pygame as pg import sys from game import Game from screens.settings_screen import SettingsScreen from screens.game_screen import GameScreen from settings import * OPTION_COLOR = (128, 135, 239) SELECTED_OPTION_COLOR = (255, 255, 255) INITIAL_V_GAP = 140 V_SPACING = 5 class Menu(GameScreen): def __init__(self, menu, display): super().__init__(display) self.menu = menu self.menu_rects = {} self.last_axis_motion = 0.0 def run(self): self.draw() # draw first time to ignore self.updated while self.playing: self.dt = self.clock.tick(FPS) / 1000 self.events() self.update() self.draw() def events(self): self.updated = False action = None for event in pg.event.get(): if event.type == pg.QUIT: quit_game(self) # keyboard if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: quit_game(self) if event.key == pg.K_DOWN: action = 'down' if event.key == pg.K_UP: action = 'up' if event.key == pg.K_RETURN: action = 'enter' # mouse if event.type == pg.MOUSEMOTION: self.mousex, self.mousey = pg.mouse.get_pos() for i in range(len(self.menu_rects.items())): if self.menu_rects[i].collidepoint(self.mousex, self.mousey): self.menu['selected_option'] = i self.updated = True break if event.type == pg.MOUSEBUTTONDOWN: for i in range(len(self.menu_rects.items())): if self.menu_rects[i].collidepoint(self.mousex, self.mousey): action = 'enter' break # joystick if event.type == pg.JOYBUTTONDOWN: if event.button == J_BUTTONS['A']: action = 'enter' if event.type == pg.JOYAXISMOTION: if event.dict['axis'] == 1: if time.time() >= self.last_axis_motion + 0.3: if event.dict['value'] < -JOYSTICK_THRESHOLD: action = 'up' self.last_axis_motion = time.time() elif event.dict['value'] > JOYSTICK_THRESHOLD: action = 'down' self.last_axis_motion = time.time() if action == 'down': self.menu["selected_option"] += 1 self.menu["selected_option"] %= len(self.menu["options"]) self.updated = True elif action == 'up': self.menu["selected_option"] -= 1 self.menu["selected_option"] %= len(self.menu["options"]) self.updated = True elif action == 'enter': self.menu["options"][self.menu["selected_option"]]["func"](self) def update(self): pass def draw(self): if self.updated: self.display.fill(BG_COLOR) self.draw_game_title() self.draw_options() pg.display.flip() def draw_options(self): count = 0 x_offset = 0 for option in self.menu["options"]: if self.menu["selected_option"] == count: color = SELECTED_OPTION_COLOR else: color = OPTION_COLOR rend = self.font.render(option["name"], True, color) if x_offset == 0: x_offset = SCREEN_WIDTH // 2 - rend.get_width() // 2 rect = rend.get_rect().move( x_offset, INITIAL_V_GAP + (rend.get_height() + V_SPACING) * count) self.menu_rects[count] = rect self.display.blit(rend, rect) count += 1 def draw_game_title(self): surface = self.font.render(GAME_TITLE, True, (255, 255, 255)) x = SCREEN_WIDTH // 2 - surface.get_width() // 2 y = 40 self.display.blit(surface, (x, y)) def new_game(self): self.playing = False game = Game(self.display) game.load() game.run() def quit_game(self): pg.quit() sys.exit() def load_game(self): print("LOAD GAME") # TODO: finish load game option def settings(self): print("SETTINGS") SettingsScreen(self.display).run() self.updated = True def main_menu(display): return Menu({ "selected_option": 0, "options": [ { "name": "NEW GAME", "func": new_game }, { "name": "LOAD GAME", "func": load_game }, { "name": "SETTINGS", "func": settings }, { "name": "QUIT", "func": quit_game }, ] }, display)
{ "content_hash": "0555fb05e6d3270bbde0ebf097995212", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 81, "avg_line_length": 28.931428571428572, "alnum_prop": 0.47639739285008886, "repo_name": "kuroneko1996/cyberlab", "id": "884b2537e4770c30417301d1e6e314ddd28d36aa", "size": "5063", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "screens/menu.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "68176" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <sem:triples uri="http://www.lds.org/vrl/specific-people/latter-day-figures/bishop-ralph" xmlns:sem="http://marklogic.com/semantics"> <sem:triple> <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bishop-ralph</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate> <sem:object datatype="xsd:string" xml:lang="eng">Bishop, Ralph</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bishop-ralph</sem:subject> <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate> <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object> </sem:triple> <sem:triple> <sem:subject>http://www.lds.org/vrl/specific-people/latter-day-figures/bishop-ralph</sem:subject> <sem:predicate>http://www.lds.org/core#entityType</sem:predicate> <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object> </sem:triple> </sem:triples>
{ "content_hash": "de9455653446bbed98e6ebbaa327a4dd", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 133, "avg_line_length": 58.888888888888886, "alnum_prop": 0.7169811320754716, "repo_name": "freshie/ml-taxonomies", "id": "dac123f4c262fe7a07dde4f8259b0261919872ce", "size": "1060", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "roxy/data/gospel-topical-explorer-v2/taxonomies/vrl/specific-people/latter-day-figures/bishop-ralph.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4422" }, { "name": "CSS", "bytes": "38665" }, { "name": "HTML", "bytes": "356" }, { "name": "JavaScript", "bytes": "411651" }, { "name": "Ruby", "bytes": "259121" }, { "name": "Shell", "bytes": "7329" }, { "name": "XQuery", "bytes": "857170" }, { "name": "XSLT", "bytes": "13753" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; namespace CatFight.Util { public static class RandomExtensions { public static T RandomEntry<T>(this Random random, IReadOnlyCollection<T> collection) { int idx = random.Next(collection.Count); return collection.ElementAt(idx); } } }
{ "content_hash": "60fc827dbd5c5ae4a0d571f5e4100c20", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 93, "avg_line_length": 24.2, "alnum_prop": 0.6584022038567493, "repo_name": "Luminoth/CatFight", "id": "03a9b5a873306da1b7ed1561e7d900e63d92be7e", "size": "365", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/Util/RandomExtensions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "745" }, { "name": "C#", "bytes": "4723885" }, { "name": "CSS", "bytes": "1569" }, { "name": "HLSL", "bytes": "86858" }, { "name": "HTML", "bytes": "68126" }, { "name": "JavaScript", "bytes": "21058" }, { "name": "Objective-C++", "bytes": "6492" }, { "name": "ShaderLab", "bytes": "80061" }, { "name": "Smalltalk", "bytes": "208" }, { "name": "TypeScript", "bytes": "27531" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Rabdosia liangshanica C.Y.Wu & H.W.Li ### Remarks null
{ "content_hash": "ecabe101f8ff04cad8b8ba208f916832", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 37, "avg_line_length": 12.23076923076923, "alnum_prop": 0.710691823899371, "repo_name": "mdoering/backbone", "id": "d68ec8bc2e502c04cea90aad5a49e26a2263ac00", "size": "228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Isodon/Isodon liangshanicus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import Ember from 'ember'; export default Ember.Component.extend({ actions: { nextStep() { // check is we are ready to move forward if (this.isReady()) { this.sendAction(); } else { // we're not ready, so show the modal-message this.set('showNotReadyMessage', true); } } }, isReady() { /** Check if our form is filled out */ // if any of this array is true, then we're ready to move forward const options = ['identityData', 'locationData', 'addressData', 'userBehaviourData', 'computerNetworkData', 'financialData', 'otherData']; const self = this; return options.any((option) => { if (self.get(`model.statement.${option}`)) { return true; } }); } });
{ "content_hash": "661286f1fc673bff99a0441ff7a6d776", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 142, "avg_line_length": 24.903225806451612, "alnum_prop": 0.5841968911917098, "repo_name": "Br3nda/priv-o-matic", "id": "29c6c42c23050f0c2bbbc574d7279a773b3736cc", "size": "772", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/components/step-data-types.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6031" }, { "name": "HTML", "bytes": "32489" }, { "name": "JavaScript", "bytes": "23839" } ], "symlink_target": "" }
namespace policy { // Handler that always returns specified error code for a given request type. class FailingRequestHandler : public EmbeddedPolicyTestServer::RequestHandler { public: FailingRequestHandler(ClientStorage* client_storage, PolicyStorage* policy_storage, const std::string& request_type, net::HttpStatusCode error_code); FailingRequestHandler(FailingRequestHandler&& handler) = delete; FailingRequestHandler& operator=(FailingRequestHandler&& handler) = delete; ~FailingRequestHandler() override; // EmbeddedPolicyTestServer::RequestHandler: std::string RequestType() override; std::unique_ptr<net::test_server::HttpResponse> HandleRequest( const net::test_server::HttpRequest& request) override; private: std::string request_type_; net::HttpStatusCode error_code_; }; } // namespace policy #endif // COMPONENTS_POLICY_TEST_SUPPORT_FAILING_REQUEST_HANDLER_H_
{ "content_hash": "4a4161522228c4705bd93ed8eae1a0d7", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 79, "avg_line_length": 37.61538461538461, "alnum_prop": 0.721881390593047, "repo_name": "scheib/chromium", "id": "7b5f2842f2d1d1af37920aac8aca1134b05a8dd4", "size": "1389", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "components/policy/test_support/failing_request_handler.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "1c7867aa478dc2099a9ba34363694b2c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "7427ab808dec7a20935addb1a5926c8b1edf6e74", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Eulophia/Eulophia horsfallii/ Syn. Lissochilus eleogenus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Net; using Amazon.Util; namespace Amazon.SimpleDB { /// <summary> /// Configuration for accessing Amazon Simple DB service /// </summary> public class AmazonSimpleDBConfig { private string serviceVersion = "2009-04-15"; private RegionEndpoint regionEndpoint; private string serviceURL = "https://sdb.amazonaws.com"; private string userAgent = Amazon.Util.AWSSDKUtils.SDKUserAgent; private string signatureVersion = "2"; private string signatureMethod = "HmacSHA256"; private string proxyHost = null; private int proxyPort = -1; private int maxErrorRetry = 3; private bool fUseSecureString = true; private string proxyUsername; private string proxyPassword; private int? connectionLimit; private ICredentials proxyCredentials; /// <summary> /// Gets Service Version /// </summary> public string ServiceVersion { get { return this.serviceVersion; } } /// <summary> /// Gets and sets of the signatureMethod property. /// </summary> public string SignatureMethod { get { return this.signatureMethod; } set { this.signatureMethod = value; } } /// <summary> /// Sets the SignatureMethod property /// </summary> /// <param name="signatureMethod">SignatureMethod property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithSignatureMethod(string signatureMethod) { this.signatureMethod = signatureMethod; return this; } /// <summary> /// Checks if SignatureMethod property is set /// </summary> /// <returns>true if SignatureMethod property is set</returns> public bool IsSetSignatureMethod() { return this.signatureMethod != null; } /// <summary> /// Gets and sets of the SignatureVersion property. /// </summary> public string SignatureVersion { get { return this.signatureVersion; } set { this.signatureVersion = value; } } /// <summary> /// Sets the SignatureVersion property /// </summary> /// <param name="signatureVersion">SignatureVersion property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithSignatureVersion(string signatureVersion) { this.signatureVersion = signatureVersion; return this; } /// <summary> /// Checks if SignatureVersion property is set /// </summary> /// <returns>true if SignatureVersion property is set</returns> public bool IsSetSignatureVersion() { return this.signatureVersion != null; } /// <summary> /// Gets and sets of the UserAgent property. /// </summary> public string UserAgent { get { return this.userAgent; } set { this.userAgent = value; } } /// <summary> /// Sets the UserAgent property /// </summary> /// <param name="userAgent">UserAgent property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithUserAgent(string userAgent) { this.userAgent = userAgent; return this; } /// <summary> /// Checks if UserAgent property is set /// </summary> /// <returns>true if UserAgent property is set</returns> public bool IsSetUserAgent() { return this.userAgent != null; } /// <summary> /// Gets and sets the RegionEndpoint property. The region constant to use that /// determines the endpoint to use. If this is not set /// then the client will fallback to the value of ServiceURL. /// </summary> public RegionEndpoint RegionEndpoint { get { return regionEndpoint; } set { this.regionEndpoint = value; } } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> internal string RegionEndpointServiceName { get { return "sdb"; } } /// <summary> /// Gets and sets of the ServiceURL property. /// This is an optional property; change it /// only if you want to try a different service /// endpoint or want to switch between https and http. /// </summary> public string ServiceURL { get { return this.serviceURL; } set { this.serviceURL = value; } } /// <summary> /// Sets the ServiceURL property /// </summary> /// <param name="serviceURL">ServiceURL property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithServiceURL(string serviceURL) { this.serviceURL = serviceURL; return this; } /// <summary> /// Checks if ServiceURL property is set /// </summary> /// <returns>true if ServiceURL property is set</returns> public bool IsSetServiceURL() { return this.serviceURL != null; } /// <summary> /// Gets and sets of the ProxyHost property. /// </summary> public string ProxyHost { get { return this.proxyHost; } set { this.proxyHost = value; } } /// <summary> /// Sets the ProxyHost property /// </summary> /// <param name="proxyHost">ProxyHost property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithProxyHost(string proxyHost) { this.proxyHost = proxyHost; return this; } /// <summary> /// Checks if ProxyHost property is set /// </summary> /// <returns>true if ProxyHost property is set</returns> public bool IsSetProxyHost() { return this.proxyHost != null; } /// <summary> /// Gets and sets of the ProxyPort property. /// </summary> public int ProxyPort { get { return this.proxyPort; } set { this.proxyPort = value; } } /// <summary> /// Sets the ProxyPort property /// </summary> /// <param name="proxyPort">ProxyPort property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithProxyPort(int proxyPort) { this.proxyPort = proxyPort; return this; } /// <summary> /// Checks if ProxyPort property is set /// </summary> /// <returns>true if ProxyPort property is set</returns> public bool IsSetProxyPort() { return this.proxyPort >= 0; } /// <summary> /// Gets and sets of the MaxErrorRetry property. /// </summary> public int MaxErrorRetry { get { return this.maxErrorRetry; } set { this.maxErrorRetry = value; } } /// <summary> /// Sets the MaxErrorRetry property /// </summary> /// <param name="maxErrorRetry">MaxErrorRetry property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithMaxErrorRetry(int maxErrorRetry) { this.maxErrorRetry = maxErrorRetry; return this; } /// <summary> /// Checks if MaxErrorRetry property is set /// </summary> /// <returns>true if MaxErrorRetry property is set</returns> public bool IsSetMaxErrorRetry() { return this.maxErrorRetry >= 0; } /// <summary> /// Gets and Sets the UseSecureStringForAwsSecretKey property. /// By default, the AWS Secret Access Key is stored /// in a SecureString (true) - this is one of the secure /// ways to store a secret provided by the .NET Framework. /// But, the use of SecureStrings is not supported in Medium /// Trust Windows Hosting environments. If you are building an /// ASP.NET application that needs to run with Medium Trust, /// set this property to false, and the client will /// not save your AWS Secret Key in a secure string. Changing /// the default to false can result in the Secret Key being /// vulnerable; please use this property judiciously. /// </summary> /// <remarks>Storing the AWS Secret Access Key is not /// recommended unless absolutely necessary. /// </remarks> /// <seealso cref="T:System.Security.SecureString"/> public bool UseSecureStringForAwsSecretKey { get { return this.fUseSecureString; } set { this.fUseSecureString = value; } } /// <summary> /// Sets the UseSecureString property. /// By default, the AWS Secret Access Key is stored /// in a SecureString (true) - this is one of the secure /// ways to store a secret provided by the .NET Framework. /// But, the use of SecureStrings is not supported in Medium /// Trust Windows Hosting environments. If you are building an /// ASP.NET application that needs to run with Medium Trust, /// set this property to false, and the client will /// not save your AWS Secret Key in a secure string. Changing /// the default to false can result in the Secret Key being /// vulnerable; please use this property judiciously. /// </summary> /// <param name="fSecure"> /// Whether a secure string should be used or not. /// </param> /// <returns>The Config object with the property set</returns> /// <remarks>Storing the AWS Secret Access Key is not /// recommended unless absolutely necessary. /// </remarks> /// <seealso cref="T:System.Security.SecureString"/> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithUseSecureStringForAwsSecretKey(bool fSecure) { fUseSecureString = fSecure; return this; } /// <summary> /// Gets and sets the ProxyUsername property. /// Used in conjunction with the ProxyPassword /// property to authenticate requests with the /// specified Proxy server. /// </summary> [Obsolete("Use ProxyCredentials instead")] public string ProxyUsername { get { return this.proxyUsername; } set { this.proxyUsername = value; } } /// <summary> /// Sets the ProxyUsername property /// </summary> /// <param name="userName">Value for the ProxyUsername property</param> /// <returns>this instance</returns> [Obsolete("Use WithProxyCredentials instead")] public AmazonSimpleDBConfig WithProxyUsername(string userName) { this.proxyUsername = userName; return this; } /// <summary> /// Checks if ProxyUsername property is set /// </summary> /// <returns>true if ProxyUsername property is set</returns> internal bool IsSetProxyUsername() { return !System.String.IsNullOrEmpty(this.proxyUsername); } /// <summary> /// Gets and sets the ProxyPassword property. /// Used in conjunction with the ProxyUsername /// property to authenticate requests with the /// specified Proxy server. /// </summary> /// <remarks> /// If this property isn't set, String.Empty is used as /// the proxy password. This property isn't /// used if ProxyUsername is null or empty. /// </remarks> [Obsolete("Use ProxyCredentials instead")] public string ProxyPassword { get { return this.proxyPassword; } set { this.proxyPassword = value; } } /// <summary> /// Sets the ProxyPassword property. /// Used in conjunction with the ProxyUsername /// property to authenticate requests with the /// specified Proxy server. /// </summary> /// <remarks> /// If this property isn't set, String.Empty is used as /// the proxy password. This property isn't /// used if ProxyUsername is null or empty. /// </remarks> /// <param name="password">ProxyPassword property</param> /// <returns>this instance</returns> [Obsolete("Use WithProxyCredentials instead")] public AmazonSimpleDBConfig WithProxyPassword(string password) { this.proxyPassword = password; return this; } /// <summary> /// Checks if ProxyPassword property is set /// </summary> /// <returns>true if ProxyPassword property is set</returns> internal bool IsSetProxyPassword() { return !System.String.IsNullOrEmpty(this.proxyPassword); } /// <summary> /// Credentials to use with a proxy. /// </summary> public ICredentials ProxyCredentials { get { ICredentials credentials = this.proxyCredentials; if (credentials == null && this.IsSetProxyUsername()) { credentials = new NetworkCredential(this.proxyUsername, this.proxyPassword ?? String.Empty); } return credentials; } set { this.proxyCredentials = value; } } /// <summary> /// Sets the ProxyCredentials property. /// </summary> /// <param name="proxyCredentials">ProxyCredentials property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonSimpleDBConfig WithProxyCredentials(ICredentials proxyCredentials) { this.proxyCredentials = proxyCredentials; return this; } /// <summary> /// Checks if ProxyCredentials property is set /// </summary> /// <returns>true if ProxyCredentials property is set</returns> internal bool IsSetProxyCredentials() { return (this.ProxyCredentials != null); } /// <summary> /// Gets and sets the connection limit set on the ServicePoint for the WebRequest. /// Default value is 50 connections unless ServicePointManager.DefaultConnectionLimit is set in /// which case ServicePointManager.DefaultConnectionLimit will be used as the default. /// </summary> public int ConnectionLimit { get { return AWSSDKUtils.GetConnectionLimit(this.connectionLimit); } set { this.connectionLimit = value; } } } }
{ "content_hash": "e9eff13d3f7c15807eebb594f5725dc0", "timestamp": "", "source": "github", "line_count": 455, "max_line_length": 177, "avg_line_length": 37.142857142857146, "alnum_prop": 0.582189349112426, "repo_name": "emcvipr/dataservices-sdk-dotnet", "id": "bcab661a35c4eaf25bbcc58dfa6cc59cd07299f3", "size": "17779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AWSSDK/Amazon.SimpleDB/AmazonSimpleDBConfig.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "30500772" }, { "name": "Shell", "bytes": "1726" }, { "name": "XSLT", "bytes": "337772" } ], "symlink_target": "" }
/* eslint react/no-multi-comp: 0, react/prop-types: 0 */ import React from 'react'; import { shallow } from 'enzyme'; import { Col } from 'reactstrap'; describe('Col', () => { it('should render default .col-* markup', () => { const wrapper = shallow(<Col/>); expect(wrapper.html()).toBe('<div class="col-xs-12"></div>'); }); it('should render children', () => { const wrapper = shallow(<Col>Children</Col>); expect(wrapper.text()).toBe('Children'); }); it('should pass additional classNames', () => { const wrapper = shallow(<Col className="extra"/>); expect(wrapper.hasClass('extra')).toBe(true); expect(wrapper.hasClass('col-xs-12')).toBe(true); }); it('should pass col size specific classes as Strings', () => { const wrapper = shallow(<Col sm="6"/>); expect(wrapper.hasClass('col-sm-6')).toBe(true); expect(wrapper.hasClass('col-xs-12')).toBe(true); }); it('should pass col size specific classes as Numbers', () => { const wrapper = shallow(<Col sm={6}/>); expect(wrapper.hasClass('col-sm-6')).toBe(true); expect(wrapper.hasClass('col-xs-12')).toBe(true); }); it('should pass col size specific classes via Objects', () => { const wrapper = shallow(<Col sm={{ size: 6, push: 2, pull: 2, offset: 2 }}/>); expect(wrapper.hasClass('col-sm-6')).toBe(true); expect(wrapper.hasClass('col-xs-12')).toBe(true); expect(wrapper.hasClass('col-sm-push-2')).toBe(true); expect(wrapper.hasClass('col-sm-pull-2')).toBe(true); expect(wrapper.hasClass('col-sm-offset-2')).toBe(true); }); });
{ "content_hash": "df803e63980ca5ba5fd68482e3d72923", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 82, "avg_line_length": 32.44897959183673, "alnum_prop": 0.620125786163522, "repo_name": "cbfx/reactstrap", "id": "2726888271a208a0bbbc255902f431edd6a555a2", "size": "1590", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/Col.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "136458" }, { "name": "Shell", "bytes": "2902" } ], "symlink_target": "" }
const autoprefixer = require('autoprefixer'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path'); const webpack = require('webpack'); const CopyWebpackPlugin = require('copy-webpack-plugin'); //========================================================= // ENVIRONMENT VARS //--------------------------------------------------------- const NODE_ENV = process.env.NODE_ENV; const ENV_DEVELOPMENT = NODE_ENV === 'development'; const ENV_PRODUCTION = NODE_ENV === 'production'; const ENV_TEST = NODE_ENV === 'test'; const HOST = process.env.HOST || 'localhost'; const PORT = process.env.PORT || 3000; //========================================================= // CONFIG //--------------------------------------------------------- const config = {}; module.exports = config; config.resolve = { extensions: ['', '.ts', '.js'], modulesDirectories: ['node_modules'], root: path.resolve('.') }; config.module = { loaders: [ {test: /\.ts$/, loader: 'ts', exclude: /node_modules/}, {test: /\.html$/, loader: 'raw'}, {test: /\.txt$/, loader: 'raw'}, {test: /\.scss$/, loader: 'raw!postcss!sass', exclude: path.resolve('src/views/common/styles'), include: path.resolve('src/views')} ] }; config.plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(NODE_ENV) }) ]; config.postcss = [ autoprefixer({ browsers: ['last 3 versions'] }) ]; config.sassLoader = { outputStyle: 'compressed', precision: 10, sourceComments: false }; //===================================== // DEVELOPMENT or PRODUCTION //------------------------------------- if (ENV_DEVELOPMENT || ENV_PRODUCTION) { config.devtool = 'source-map'; config.entry = { main: [ './src/main' ], vendor: [ 'core-js/es6/array', 'core-js/es6/map', 'core-js/es6/set', 'core-js/es6/string', 'core-js/es6/symbol', 'core-js/fn/object/assign', 'core-js/es7/reflect', 'zone.js', '@angular/common', '@angular/core', '@angular/platform-browser-dynamic', '@angular/router-deprecated', 'angularfire2', 'firebase', 'rxjs/add/operator/map' ] }; config.output = { filename: '[name].js', path: path.resolve('./target'), publicPath: '/' }; config.plugins.push( new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }), new HtmlWebpackPlugin({ filename: 'index.html', hash: true, inject: 'body', template: './src/index.html' }), new HtmlWebpackPlugin({ filename: '200.html', hash: true, inject: 'body', template: './src/index.html' }), new CopyWebpackPlugin([{context: './src', from: 'assets/**/*' },]) ); } //===================================== // DEVELOPMENT //------------------------------------- if (ENV_DEVELOPMENT) { config.entry.main.unshift(`webpack-dev-server/client?http://${HOST}:${PORT}`); config.module.loaders.push( {test: /\.scss$/, loader: 'style!css!postcss!sass', include: path.resolve('src/views/common/styles')} ); config.devServer = { contentBase: './src', historyApiFallback: true, host: HOST, outputPath: config.output.path, port: PORT, publicPath: config.output.publicPath, stats: { cached: true, cachedAssets: true, chunks: true, chunkModules: false, colors: true, hash: false, reasons: true, timings: true, version: false } }; } //===================================== // PRODUCTION //------------------------------------- if (ENV_PRODUCTION) { config.module.loaders.push( {test: /\.scss$/, loader: ExtractTextPlugin.extract('css?-autoprefixer!postcss!sass'), include: path.resolve('src/views/common/styles')} ); config.plugins.push( new ExtractTextPlugin('styles.css'), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { dead_code: true, // eslint-disable-line camelcase screw_ie8: true, // eslint-disable-line camelcase unused: true, warnings: false } }) ); } //===================================== // TEST //------------------------------------- if (ENV_TEST) { config.devtool = 'inline-source-map'; config.module.loaders.push( {test: /\.scss$/, loader: 'style!css!postcss!sass', include: path.resolve('src/views/common/styles')} ); }
{ "content_hash": "b634fa7ff441777ca2ae70e98e41f312", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 140, "avg_line_length": 25.447513812154696, "alnum_prop": 0.5390794615718628, "repo_name": "AntonyBaasan/startupweekend", "id": "3794bdf551339c84ebee2a40c59ed016d0db26ec", "size": "4606", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webpack.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9187" }, { "name": "HTML", "bytes": "25231" }, { "name": "JavaScript", "bytes": "7065" }, { "name": "Shell", "bytes": "68" }, { "name": "TypeScript", "bytes": "28148" } ], "symlink_target": "" }
WXTiles Javascript API. We have released a newer API that works with leaflet: [metocean/wxserver-api](https://github.com/metocean/wxserver-api)
{ "content_hash": "d51829a15ee8123bec9e8da933c693f6", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 65, "avg_line_length": 36.25, "alnum_prop": 0.7931034482758621, "repo_name": "metocean/wxtiles", "id": "dc85a44d3d466c96768f06036b62a0ca8812eedd", "size": "156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "24742" }, { "name": "JavaScript", "bytes": "44980" }, { "name": "PHP", "bytes": "446" }, { "name": "Python", "bytes": "945" } ], "symlink_target": "" }
mkdir -p out rm -f out/* # Build Duktape pushd duktape python2 tools/configure.py \ --output-directory ../out \ --option-file ../config.yaml \ --omit-removed-config-options \ --omit-deprecated-config-options popd
{ "content_hash": "b70bab371cec498fa7c744f09c646e0a", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 36, "avg_line_length": 20.90909090909091, "alnum_prop": 0.6739130434782609, "repo_name": "saghul/sjs", "id": "db37cc29004c92d48d4cf88265a7d60b57b753c1", "size": "270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/build_duktape/build.sh", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "3994222" }, { "name": "CMake", "bytes": "5400" }, { "name": "JavaScript", "bytes": "123900" }, { "name": "Makefile", "bytes": "628" }, { "name": "Python", "bytes": "1808" }, { "name": "Shell", "bytes": "270" } ], "symlink_target": "" }
{-# LANGUAGE RecordWildCards #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import RotationalCipher (rotate) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "rotate" $ for_ cases test where test Case{..} = it description assertion where assertion = rotate number phrase `shouldBe` expected data Case = Case { description :: String , number :: Int , phrase :: String , expected :: String } cases :: [Case] cases = [ Case { description = "rotate a by 0, same output as input" , number = 0 , phrase = "a" , expected = "a" } , Case { description = "rotate a by 1" , number = 1 , phrase = "a" , expected = "b" } , Case { description = "rotate a by 26, same output as input" , number = 26 , phrase = "a" , expected = "a" } , Case { description = "rotate m by 13" , number = 13 , phrase = "m" , expected = "z" } , Case { description = "rotate n by 13 with wrap around alphabet" , number = 13 , phrase = "n" , expected = "a" } , Case { description = "rotate capital letters" , number = 5 , phrase = "OMG" , expected = "TRL" } , Case { description = "rotate spaces" , number = 5 , phrase = "O M G" , expected = "T R L" } , Case { description = "rotate numbers" , number = 4 , phrase = "Testing 1 2 3 testing" , expected = "Xiwxmrk 1 2 3 xiwxmrk" } , Case { description = "rotate punctuation" , number = 21 , phrase = "Let's eat, Grandma!" , expected = "Gzo'n zvo, Bmviyhv!" } , Case { description = "rotate all letters" , number = 13 , phrase = "The quick brown fox jumps over the lazy dog." , expected = "Gur dhvpx oebja sbk whzcf bire gur ynml qbt." } ]
{ "content_hash": "669123aef92640e78d0a5eb507c72034", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 77, "avg_line_length": 34.23376623376623, "alnum_prop": 0.4279210925644917, "repo_name": "c19/Exercism-Haskell", "id": "63c03cb3b8558bb4aece4d25c88f0cbdc2fd48cf", "size": "2636", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "rotational-cipher/test/Tests.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "161692" } ], "symlink_target": "" }
namespace safe_browsing { namespace { constexpr char kCloudBinaryUploadServiceUrlFlag[] = "binary-upload-service-url"; absl::optional<GURL> GetUrlOverride() { // Ignore this flag on Stable and Beta to avoid abuse. if (!g_browser_process || !g_browser_process->browser_policy_connector() ->IsCommandLineSwitchSupported()) { return absl::nullopt; } base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(kCloudBinaryUploadServiceUrlFlag)) { GURL url = GURL( command_line->GetSwitchValueASCII(kCloudBinaryUploadServiceUrlFlag)); if (url.is_valid()) return url; else LOG(ERROR) << "--binary-upload-service-url is set to an invalid URL"; } return absl::nullopt; } } // namespace std::string BinaryUploadService::ResultToString(Result result) { switch (result) { case Result::UNKNOWN: return "UNKNOWN"; case Result::SUCCESS: return "SUCCESS"; case Result::UPLOAD_FAILURE: return "UPLOAD_FAILURE"; case Result::TIMEOUT: return "TIMEOUT"; case Result::FILE_TOO_LARGE: return "FILE_TOO_LARGE"; case Result::FAILED_TO_GET_TOKEN: return "FAILED_TO_GET_TOKEN"; case Result::UNAUTHORIZED: return "UNAUTHORIZED"; case Result::FILE_ENCRYPTED: return "FILE_ENCRYPTED"; case Result::DLP_SCAN_UNSUPPORTED_FILE_TYPE: return "DLP_SCAN_UNSUPPORTED_FILE_TYPE"; case Result::TOO_MANY_REQUESTS: return "TOO_MANY_REQUESTS"; } } BinaryUploadService::Request::Data::Data() = default; BinaryUploadService::Request::Data::Data(Data&&) = default; BinaryUploadService::Request::Data& BinaryUploadService::Request::Data::operator=( BinaryUploadService::Request::Data&& other) = default; BinaryUploadService::Request::Data::~Data() = default; BinaryUploadService::Request::Request( ContentAnalysisCallback callback, enterprise_connectors::CloudOrLocalAnalysisSettings settings) : content_analysis_callback_(std::move(callback)), cloud_or_local_settings_(std::move(settings)) {} BinaryUploadService::Request::~Request() = default; void BinaryUploadService::Request::set_tab_url(const GURL& tab_url) { tab_url_ = tab_url; } const GURL& BinaryUploadService::Request::tab_url() const { return tab_url_; } void BinaryUploadService::Request::set_per_profile_request( bool per_profile_request) { per_profile_request_ = per_profile_request; } bool BinaryUploadService::Request::per_profile_request() const { return per_profile_request_; } void BinaryUploadService::Request::set_fcm_token(const std::string& token) { content_analysis_request_.set_fcm_notification_token(token); } void BinaryUploadService::Request::set_device_token(const std::string& token) { content_analysis_request_.set_device_token(token); } void BinaryUploadService::Request::set_filename(const std::string& filename) { content_analysis_request_.mutable_request_data()->set_filename(filename); } void BinaryUploadService::Request::set_digest(const std::string& digest) { content_analysis_request_.mutable_request_data()->set_digest(digest); } void BinaryUploadService::Request::clear_dlp_scan_request() { auto* tags = content_analysis_request_.mutable_tags(); auto it = std::find(tags->begin(), tags->end(), "dlp"); if (it != tags->end()) tags->erase(it); } void BinaryUploadService::Request::set_analysis_connector( enterprise_connectors::AnalysisConnector connector) { content_analysis_request_.set_analysis_connector(connector); } void BinaryUploadService::Request::set_url(const std::string& url) { content_analysis_request_.mutable_request_data()->set_url(url); } void BinaryUploadService::Request::set_source(const std::string& source) { content_analysis_request_.mutable_request_data()->set_source(source); } void BinaryUploadService::Request::set_destination( const std::string& destination) { content_analysis_request_.mutable_request_data()->set_destination( destination); } void BinaryUploadService::Request::set_csd(ClientDownloadRequest csd) { *content_analysis_request_.mutable_request_data()->mutable_csd() = std::move(csd); } void BinaryUploadService::Request::add_tag(const std::string& tag) { content_analysis_request_.add_tags(tag); } void BinaryUploadService::Request::set_email(const std::string& email) { content_analysis_request_.mutable_request_data()->set_email(email); } void BinaryUploadService::Request::set_client_metadata( enterprise_connectors::ClientMetadata metadata) { *content_analysis_request_.mutable_client_metadata() = std::move(metadata); } void BinaryUploadService::Request::set_content_type(const std::string& type) { content_analysis_request_.mutable_request_data()->set_content_type(type); } std::string BinaryUploadService::Request::SetRandomRequestToken() { DCHECK(request_token().empty()); std::string token = base::RandBytesAsString(128); content_analysis_request_.set_request_token( base::HexEncode(token.data(), token.size())); return content_analysis_request_.request_token(); } enterprise_connectors::AnalysisConnector BinaryUploadService::Request::analysis_connector() { return content_analysis_request_.analysis_connector(); } const std::string& BinaryUploadService::Request::device_token() const { return content_analysis_request_.device_token(); } const std::string& BinaryUploadService::Request::request_token() const { return content_analysis_request_.request_token(); } const std::string& BinaryUploadService::Request::fcm_notification_token() const { return content_analysis_request_.fcm_notification_token(); } const std::string& BinaryUploadService::Request::filename() const { return content_analysis_request_.request_data().filename(); } const std::string& BinaryUploadService::Request::digest() const { return content_analysis_request_.request_data().digest(); } const std::string& BinaryUploadService::Request::content_type() const { return content_analysis_request_.request_data().content_type(); } void BinaryUploadService::Request::FinishRequest( Result result, enterprise_connectors::ContentAnalysisResponse response) { std::move(content_analysis_callback_).Run(result, response); } void BinaryUploadService::Request::SerializeToString( std::string* destination) const { content_analysis_request_.SerializeToString(destination); } GURL BinaryUploadService::Request::GetUrlWithParams() const { DCHECK(absl::holds_alternative<enterprise_connectors::CloudAnalysisSettings>( cloud_or_local_settings_)); GURL url = GetUrlOverride().value_or(cloud_or_local_settings_.analysis_url()); url = net::AppendQueryParameter(url, enterprise::kUrlParamDeviceToken, device_token()); std::string connector; switch (content_analysis_request_.analysis_connector()) { case enterprise_connectors::FILE_ATTACHED: connector = "OnFileAttached"; break; case enterprise_connectors::FILE_DOWNLOADED: connector = "OnFileDownloaded"; break; case enterprise_connectors::BULK_DATA_ENTRY: connector = "OnBulkDataEntry"; break; case enterprise_connectors::PRINT: connector = "OnPrint"; break; case enterprise_connectors::FILE_TRANSFER: connector = "OnFileTransfer"; break; case enterprise_connectors::ANALYSIS_CONNECTOR_UNSPECIFIED: break; } if (!connector.empty()) { url = net::AppendQueryParameter(url, enterprise::kUrlParamConnector, connector); } for (const std::string& tag : content_analysis_request_.tags()) url = net::AppendQueryParameter(url, enterprise::kUrlParamTag, tag); return url; } bool BinaryUploadService::Request::IsAuthRequest() const { return false; } const std::string& BinaryUploadService::Request::access_token() const { return access_token_; } void BinaryUploadService::Request::set_access_token( const std::string& access_token) { access_token_ = access_token; } BinaryUploadService::Ack::Ack( enterprise_connectors::CloudOrLocalAnalysisSettings settings) : cloud_or_local_settings_(std::move(settings)) {} BinaryUploadService::Ack::~Ack() = default; void BinaryUploadService::Ack::set_request_token(const std::string& token) { ack_.set_request_token(token); } void BinaryUploadService::Ack::set_status( enterprise_connectors::ContentAnalysisAcknowledgement::Status status) { ack_.set_status(status); } void BinaryUploadService::Ack::set_final_action( enterprise_connectors::ContentAnalysisAcknowledgement::FinalAction final_action) { ack_.set_final_action(final_action); } // static BinaryUploadService* BinaryUploadService::GetForProfile( Profile* profile, const enterprise_connectors::AnalysisSettings& settings) { // Local content analysis is supported only on desktop platforms. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (settings.cloud_or_local_settings.is_cloud_analysis()) { return CloudBinaryUploadServiceFactory::GetForProfile(profile); } else { return enterprise_connectors::LocalBinaryUploadServiceFactory:: GetForProfile(profile); } #else DCHECK(settings.cloud_or_local_settings.is_cloud_analysis()); return CloudBinaryUploadServiceFactory::GetForProfile(profile); #endif } } // namespace safe_browsing
{ "content_hash": "92f5eefe5de001a1aa85629ad0c0ec1e", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 80, "avg_line_length": 32.53793103448276, "alnum_prop": 0.7259431962696058, "repo_name": "nwjs/chromium.src", "id": "18eb521181d1ca2aa316d45bf35935c448a6e77f", "size": "10476", "binary": false, "copies": "1", "ref": "refs/heads/nw70", "path": "chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
Fast search (sampling) technique for search-based software engineering problems ## Introduction This repo concludes experiments for paper "Sampling as a Baseline Optimizer for Search-based Software Engineering". SWAY is a sampling technique for solving search-based software engineering problems. For more information, please check out our paper! ## Folders Organaization - _Algorithms:_ source code for different optimizers (NSGA-II, SATIBEA and SWAY) - _Benchmarks:_ source code for models tested in the paper. - _Experiments:_ entrance for different experiements - _Metrics:_ source code for measuring results (See Section 5.3 of our paper) ## Other files - _.gitignore:_ untracked files in this repo - _LICENSE:_ the MIT license - _addroot.sh:_ We are assuming that current project path has been added to PYTHONPATH. If not, please run this script. - _debug.py:_ If you include this file inside main function, program will enter debug mode when error arises. - _repeasts.py:_ including auxiliary functions to plot results ## Run experiments To run the experiments, one should go to Folder "Experiments". Each file there contains one experiements. For example, to run NSGA-II for POM3 mode, one should execute ```bash # jump to project folder first source addroot.sh cd Experiments python pom3_nsga2.py ``` In this repo, `godview` = `GroundTruth`. Project was developed under python2.7. Python3 should be compatible but not tested. All results are piped to one folder `tse_rs`. Please make sure you've created such folder within execute path. To get multi-objective metrics(HV,GD,PFS or GS), go to "Metrics" and run `all_metrics.py`
{ "content_hash": "60c210487d892bd91adf2b9cccd1a175", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 148, "avg_line_length": 45.69444444444444, "alnum_prop": 0.7762917933130699, "repo_name": "Ginfung/FSSE", "id": "608cfb48b18fcf914456b4102c49eee38f6a7acd", "size": "1652", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "159840" }, { "name": "Shell", "bytes": "237" } ], "symlink_target": "" }
package com.atlassian.webtest.ui.keys; import java.util.Collections; import java.util.EnumSet; import java.util.Set; /** * Represent key events that occur in browsers upon typing. * */ public enum KeyEventType { KEYDOWN("keydown"), KEYPRESS("keypress"), KEYUP("keyup"); public static final Set<KeyEventType> ALL = Collections.unmodifiableSet(EnumSet.allOf(KeyEventType.class)); private final String eventString; KeyEventType(String eventString) { this.eventString = eventString; } public String getEventString() { return eventString; } }
{ "content_hash": "3bd97d86359df5b71778422232e3de87", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 111, "avg_line_length": 21.321428571428573, "alnum_prop": 0.7051926298157454, "repo_name": "adini121/atlassian", "id": "df7b15f7b46154a424b4c90c871e0e58003fb502", "size": "597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "atlassian-selenium/src/main/java/com/atlassian/webtest/ui/keys/KeyEventType.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "31015" }, { "name": "HTML", "bytes": "58703" }, { "name": "Java", "bytes": "1361103" }, { "name": "JavaScript", "bytes": "362783" }, { "name": "Shell", "bytes": "3317" } ], "symlink_target": "" }
package ru.job4j.chess; /** *@author Nikita Zenkin. *@since 14.06.2017. *@version 1. */ public class OccupiedWayException extends RuntimeException { /** * Exception for unexpected move. * @param msg String. */ public OccupiedWayException(String msg) { super(msg); } }
{ "content_hash": "7672a0ce5342383e4f5484686d46bbee", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 60, "avg_line_length": 19.25, "alnum_prop": 0.6331168831168831, "repo_name": "enekein/nzenkin", "id": "85b46ef31dfb89fb005b30db08128a0bbaa14a26", "size": "308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter_002/src/main/java/ru/job4j/chess/OccupiedWayException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "165458" } ], "symlink_target": "" }
<!doctype html> <html class="no-js" lang="fr"> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>PRUNIER Coussin DOUDOU</title> <!-- Place favicon.ico in the root directory --> <link rel="icon" href="../favicon.ico"> <link rel="apple-touch-icon" href="../apple-touch-icon.png"> <!-- Bootstrap Core CSS --> <link href="../css/bootstrap.min.css" rel="stylesheet"> <!-- lightbox css --> <link rel="stylesheet" href="../css/lightbox.css"> <!-- Custom CSS --> <link href="../css/clean-blog.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Myriad:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="../css/normalize.css"> <link rel="stylesheet" href="../css/bootstrap.css"> <link rel="stylesheet" href="../css/main.css"> <!-- <link rel="stylesheet" href="css/navbar.css"> <link rel="stylesheet" href="css/main_philippe.css"> --> <script src="../js/vendor/modernizr-2.8.3.min.js"></script> </head> <body> <!--[if lt IE 8]> lass="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <!-- Add your site or application content here --> <!-- header - logo--> <section class="logo" id="logo"> <!-- <div class="hidden-xs"> --> <img class="center-block img-responsive hidden-xs" src="../img/LOGO.png" alt="Logo marque PRUNIER"> <!-- </div> --> </section> <!-- /header - logo--> <!-- Navigation --> <!--//////////////////////// NAVBAR //////////////////////////--> <nav class="navbar navbar-default nav-fixed MarginBottom"> <div class="container-fluid"> <div class="navbar-header"> <img id="Logo" class="hidden-sm hidden-md hidden-lg" src="../img/LOGO.png" alt="Logo Prunier" /> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="hidden-xs"><a href="../index.html">HOME</a> <span class="sr-only">(current)</span> </li> <li class="dropdown hidden-xs"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">PRÊT-À-PORTER</a> <ul class="dropdown-menu"> <li><a href="../pret-a-porter/descriptif.html">Descriptif</a></li> <li role="separator" class="divider"></li> <li><a href="#">Robe</a></li> <li><a href="#">Blouse</a></li> <li><a href="#">Combinaison</a></li> <li><a href="#">Pantalon</a></li> </ul> </li> <li class="active unactive hidden-xs">ACCESSOIRES</li> <li class="dropdown hidden-xs"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">BIJOUX</a> <ul class="dropdown-menu"> <li><a href="../bijoux/descriptif.html">Descriptif</a></li> <li role="separator" class="divider"></li> <li><a href="#">Les bracelets</a></li> </ul> </li> <li class="dropdown hidden-xs"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">OBJETS MAISON</a> <ul class="dropdown-menu"> <li><a href="../objet-maison/descriptif.html">Descriptif</a></li> <li role="separator" class="divider"></li> <li><a href="#">Les housses de coussin</a></li> <li><a href="#">Les mobiles bébés cygnes</a></li> </ul> </li> <li class="hidden-xs"><a href="../a-propos/a-propos.html">À PROPOS</a></li> <li class="visible-xs"><a href="../index.html">HOME</a></li> <li class="dropdown visible-xs"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">PRÊT-À-PORTER</a> <ul class="dropdown-menu"> <li><a href="../pret-a-porter/descriptif.html">Descriptif</a></li> <li role="separator" class="divider"></li> <li><a href="#">Robe</a></li> <li><a href="#">Blouse</a></li> <li><a href="#">Combinaison</a></li> <li><a href="#">Pantalon</a></li> </ul> </li> <li class="dropdown visible-xs dpactive"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">ACCESSOIRES</a> <ul class="dropdown-menu"> <li class="unactiveXsDp">Descriptif</li> <li role="separator" class="divider"></li> <li><a href="#">La trousse rectangle</a></li> <li><a href="#">La trousse de toilette doudou</a></li> <li><a href="#">Le grand cabas</a></li> <li><a href="#">Le cabas soleil</a></li> </ul> </li> <li class="dropdown visible-xs"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">BIJOUX</a> <ul class="dropdown-menu"> <li><a href="../bijoux/descriptif.html">Descriptif</a></li> <li role="separator" class="divider"></li> <li><a href="#">Les bracelets</a></li> </ul> </li> <li class="dropdown visible-xs"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">OBJETS MAISON</a> <ul class="dropdown-menu"> <li><a href="../objet-maison/descriptif.html">Descriptif</a></li> <li role="separator" class="divider"></li> <li><a href="#">Les housses de coussin</a></li> <li><a href="#">Les mobiles bébés cygnes</a></li> </ul> </li> <li class="visible-xs"><a href="../a-propos/a-propos.html">À PROPOS</a></li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <nav class="navbar navbar-default hidden-xs MarginBottom" id="secondNav"> <div class="container-fluid"> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li class="active unactive hidden-xs">Descriptif <span class="sr-only">(current)</span> </li> <li class="hidden-xs nopadding"><a href="#">La trousse rectangle</a></li> <li class="hidden-xs nopadding"><a href="#">La trousse de toilette doudou</a></li> <li class="hidden-xs nopadding"><a href="#">Le grand cabas</a></li> <li class="hidden-xs nopadding"><a href="#">Le cabas soleil</a></li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <div class="visible-xs" style="height: 55px;"></div> <!-- /////////////////// CONTAINER AVEC DEUX MARGES DE CHAQUE COTé //////////////--> <!--////////////////////// END NAVBAR ///////////////////////--> <!-- /Navigation --> <!-- content --> <!-- <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" /> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> --> <div class="container"> <div class="row"> <div class="col-md-offset-2 col-md-4 col-sm-8 col-sm-offset-2 hidden-xs"> <div id="carousel" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="item active"> <img src="../img/trousse-doudou-beige.jpeg"> </div> <div class="item"> <img src="../img/trousse-doudou-blanche.jpeg"> </div> <div class="item"> <img src="../img/trousse-doudou-bnache-dentelle.jpeg"> </div> <div class="item"> <img src="../img/trousse-doudou-dentelle.jpeg"> </div> <div class="item"> <img src="../img/trousse-doudou-galon-simple.jpeg"> </div> <div class="item"> <img src="../img/trousse-doudou-gros-galon.jpeg"> </div> <div class="item"> <img src="../img/trousse-doudou.jpeg"> </div> </div> </div> <div class="clearfix"> <div id="thumbcarousel" class="carousel slide" data-interval="false"> <div class="carousel-inner"> <div class="item active"> <div data-target="#carousel" data-slide-to="0" class="thumb"> <img src="../img/trousse-doudou-beige.jpeg" alt="Trousse Doudou beige"></div> <div data-target="#carousel" data-slide-to="1" class="thumb"> <img src="../img/trousse-doudou-blanche.jpeg" alt="Trousse Doudou blanche"></div> <div data-target="#carousel" data-slide-to="2" class="thumb"> <img src="../img/details-trousse-doudou-blanche-dentelle.jpeg" alt="Trousse Doudou dentelle"></div> <div data-target="#carousel" data-slide-to="3" class="thumb"> <img src="../img/trousse-doudou-dentelle.jpeg" alt="Trousse Doudou dentelle"></div> </div> <!-- /item --> <div class="item"> <div data-target="#carousel" data-slide-to="4" class="thumb"> <img src="../img/trousse-doudou-galon-simple.jpeg"></div> <div data-target="#carousel" data-slide-to="4" class="thumb"> <img src="../img/trousse-doudou-galon.jpeg"></div> <div data-target="#carousel" data-slide-to="4" class="thumb"> <img src="../img/trousse-doudou-gros-galon.jpeg"></div> <div data-target="#carousel" data-slide-to="4" class="thumb"> <img src="../img/trousse-doudou.jpeg"></div> </div><!-- /item --> </div><!-- /carousel-inner --> <a class="left carousel-control" href="#thumbcarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> </a> <a class="right carousel-control" href="#thumbcarousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> </a> </div> <!-- /thumbcarousel --> </div><!-- /clearfix --> </div> <!-- /col-sm-6 --> <div class="col-md-4 col-md-pull-2 col-sm-8 col-sm-offset-2 hidden-xs"> <!-- <div class="col-md-4 col-sm-6 hidden-xs separ"> --> <h2 class="titre">La blouse écolière</h2> <h3 class="soustitre">Prix : 99€</h3> <p>Modèles uniques, fabriqués à la main.<br> Blouse courte, manches 3/4 forme ovale.<br> Finitions : coutures rabattues,<br> coutures anglaises et biais.<br> En lin ou en coton.<br> Taille unique.</p> </div> </div> <!-- /row --> </div> <!-- /container --> <!-- /#contenu.container content --> <section class="container"> <div class="row"> <div class="col-xs-6 hidden-sm hidden-md hidden-lg"> <a class="example-image-link" href="../img/trousse-doudou-beige.jpeg" data-lightbox="example-set" data-title="Click the right half of the image to move forward."><img class="example-image thumbnail img-responsive" src="../img/trousse-doudou-beige.jpeg" alt=""/></a> </div> <div class="col-xs-6 hidden-sm hidden-md hidden-lg"> <a class="example-image-link" href="../img/trousse-doudou-blanche.jpeg" data-lightbox="example-set" data-title="Or press the right arrow on your keyboard."><img class="example-image thumbnail img-responsive" src="../img/trousse-doudou-blanche.jpeg" alt="" /></a> </div> </div> <!-- / row --> <div class="row"> <div class="col-xs-6 hidden-sm hidden-md hidden-lg"> <a class="example-image-link" href="../img/trousse-doudou-blanche-dentelle.jpeg" data-lightbox="example-set" data-title="The next image in the set is preloaded as you're viewing."> <img class="example-image thumbnail img-responsive" src="../img/trousse-doudou-blanche-dentelle.jpeg" alt="" /></a> </div> <div class="col-xs-6 hidden-sm hidden-md hidden-lg"> <a class="example-image-link" href="../img/trousse-doudou-dentelle.jpeg" data-lightbox="example-set" data-title="Click anywhere outside the image or the X to the right to close."> <img class="example-image thumbnail img-responsive" src="../img/trousse-doudou-dentelle.jpeg" alt="" /></a> </div> </div> <div class="row"> <div class="col-xs-6 hidden-sm hidden-md hidden-lg"> <a class="example-image-link" href="../img/trousse-doudou-galon-simple.jpeg" data-lightbox="example-set" data-title="The next image in the set is preloaded as you're viewing."> <img class="example-image thumbnail img-responsive" src="../img/trousse-doudou-galon-simple.jpeg" alt="" /></a> </div> </div> <div class="row"> <div class="col-xs-6 hidden-sm hidden-md hidden-lg"> <a class="example-image-link" href="../img/trousse-doudou-galon.jpeg" data-lightbox="example-set" data-title="The next image in the set is preloaded as you're viewing."> <img class="example-image thumbnail img-responsive" src="../img/trousse-doudou-galon.jpeg" alt="" /></a> </div> </div> <div class="row"> <div class="col-xs-6 hidden-sm hidden-md hidden-lg"> <a class="example-image-link" href="../img/trousse-doudou-gros-galon.jpeg" data-lightbox="example-set" data-title="The next image in the set is preloaded as you're viewing."><img class="example-image thumbnail img-responsive" src="../img/trousse-doudou-gros-galon.jpeg" alt="" /></a></div> </div> <div class="row"> <div class="col-xs-6 hidden-sm hidden-md hidden-lg"> <a class="example-image-link" href="../img/trousse-doudou.jpeg" data-lightbox="example-set" data-title="The next image in the set is preloaded as you're viewing."><img class="example-image thumbnail img-responsive" src="../img/trousse-doudou.jpeg" alt="" /></a></div> </div> <div class="col-xs-12 hidden-sm hidden-md hidden-lg"> <h2 class="titre">La blouse écolière</h2> <h3 class="soustitre">Prix : 99€</h3> <p>Modèles uniques, fabriqués à la main. Blouse courte, manches 3/4 forme ovale. Finitions : coutures rabattues, coutures anglaises et biais. En lin ou en coton. Taille unique.</p> </div> </section> <!-- /col-sm-6 --> <!-- footer --> <footer class="container-fluid"> <div class="text-nowrap text-center"> <ul class="list-inline"> <li><a href="mailto:chlo.prunier@yahoo.fr" title="eMail:chlo.prunier@yahoo.fr"> <i class="fa fa-envelope fa-2x img-responsive"></i></a></li> <li><a href="http://www.facebook.com/prunierchloe" title="Facebook/prunierchloe"> <i class="fa fa-facebook fa-2x"></i></a></li> <li><a href="http://www.pinterest.com/chloeprunier" title="Pinterest/chloeprunier"> <i class="fa fa-pinterest fa-2x"></i></a></li> <li><a href="http://chloeprunier.tumblr.com" title="Tumblr/chloeprunier.tumblr.com"> <i class="fa fa-tumblr fa-2x"></i></a></li> <li><a href="http://instagram.com/chloeprunier" title="Instagram/chloeprunier"> <i class="fa fa-instagram fa-2x"></i></a></li> </ul> </div> </footer> <!-- /footer --> <!-- jQuery --> <script src="../js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="../js/bootstrap.min.js"></script> <!-- lightbox js --> <script src="../js/lightbox-plus-jquery.min.js"></script> <!-- Custom Theme JavaScript --> <script src="../js/clean-blog.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="../js/vendor/jquery-1.11.3.min.js"><\/script>')</script> <script src="../js/plugins.js"></script> <script src="../js/main.js"></script> </body> </html>
{ "content_hash": "c6d54084166a1b824fa5e4e4c001bff7", "timestamp": "", "source": "github", "line_count": 350, "max_line_length": 303, "avg_line_length": 60.097142857142856, "alnum_prop": 0.4685271465246743, "repo_name": "Simplon-Roubaix/Prunier", "id": "4da2a28700cd00afbd5d4d502ac03bb12fb4584b", "size": "21059", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "accessoire/doudou.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20436" }, { "name": "HTML", "bytes": "245004" }, { "name": "JavaScript", "bytes": "320546" } ], "symlink_target": "" }
""" This is a set of regression tests for vo. """ from __future__ import absolute_import, division, print_function, unicode_literals from ....extern import six from ....extern.six.moves import range, zip # STDLIB import difflib import io import sys import gzip # THIRD-PARTY from numpy.testing import assert_array_equal import numpy as np # LOCAL from ..table import parse, parse_single_table, validate from .. import tree from ..exceptions import VOTableSpecError, VOWarning from ..xmlutil import validate_schema from ....utils.data import get_pkg_data_filename, get_pkg_data_filenames from ....tests.helper import pytest, raises, catch_warnings try: import pathlib except ImportError: HAS_PATHLIB = False else: HAS_PATHLIB = True # Determine the kind of float formatting in this build of Python if hasattr(sys, 'float_repr_style'): legacy_float_repr = (sys.float_repr_style == 'legacy') else: legacy_float_repr = sys.platform.startswith('win') def assert_validate_schema(filename, version): if sys.platform.startswith('win'): return try: rc, stdout, stderr = validate_schema(filename, version) except OSError: # If xmllint is not installed, we want the test to pass anyway return assert rc == 0, 'File did not validate against VOTable schema' def test_parse_single_table(): table = parse_single_table( get_pkg_data_filename('data/regression.xml'), pedantic=False) assert isinstance(table, tree.Table) assert len(table.array) == 5 def test_parse_single_table2(): table2 = parse_single_table( get_pkg_data_filename('data/regression.xml'), table_number=1, pedantic=False) assert isinstance(table2, tree.Table) assert len(table2.array) == 1 assert len(table2.array.dtype.names) == 28 @raises(IndexError) def test_parse_single_table3(): table2 = parse_single_table( get_pkg_data_filename('data/regression.xml'), table_number=3, pedantic=False) def _test_regression(tmpdir, _python_based=False, binary_mode=1): # Read the VOTABLE votable = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False, _debug_python_based_parser=_python_based) table = votable.get_first_table() dtypes = [ ((str('string test'), str('string_test')), str('|O8')), ((str('fixed string test'), str('string_test_2')), str('|S10')), (str('unicode_test'), str('|O8')), ((str('unicode test'), str('fixed_unicode_test')), str('<U10')), ((str('string array test'), str('string_array_test')), str('|S4')), (str('unsignedByte'), str('|u1')), (str('short'), str('<i2')), (str('int'), str('<i4')), (str('long'), str('<i8')), (str('double'), str('<f8')), (str('float'), str('<f4')), (str('array'), str('|O8')), (str('bit'), str('|b1')), (str('bitarray'), str('|b1'), (3, 2)), (str('bitvararray'), str('|O8')), (str('bitvararray2'), str('|O8')), (str('floatComplex'), str('<c8')), (str('doubleComplex'), str('<c16')), (str('doubleComplexArray'), str('|O8')), (str('doubleComplexArrayFixed'), str('<c16'), (2,)), (str('boolean'), str('|b1')), (str('booleanArray'), str('|b1'), (4,)), (str('nulls'), str('<i4')), (str('nulls_array'), str('<i4'), (2, 2)), (str('precision1'), str('<f8')), (str('precision2'), str('<f8')), (str('doublearray'), str('|O8')), (str('bitarray2'), str('|b1'), (16,)) ] if sys.byteorder == 'big': new_dtypes = [] for dtype in dtypes: dtype = list(dtype) dtype[1] = dtype[1].replace(str('<'), str('>')) new_dtypes.append(tuple(dtype)) dtypes = new_dtypes assert table.array.dtype == dtypes votable.to_xml(str(tmpdir.join("regression.tabledata.xml")), _debug_python_based_parser=_python_based) assert_validate_schema(str(tmpdir.join("regression.tabledata.xml")), votable.version) if binary_mode == 1: votable.get_first_table().format = 'binary' votable.version = '1.1' elif binary_mode == 2: votable.get_first_table()._config['version_1_3_or_later'] = True votable.get_first_table().format = 'binary2' votable.version = '1.3' # Also try passing a file handle with open(str(tmpdir.join("regression.binary.xml")), "wb") as fd: votable.to_xml(fd, _debug_python_based_parser=_python_based) assert_validate_schema(str(tmpdir.join("regression.binary.xml")), votable.version) # Also try passing a file handle with open(str(tmpdir.join("regression.binary.xml")), "rb") as fd: votable2 = parse(fd, pedantic=False, _debug_python_based_parser=_python_based) votable2.get_first_table().format = 'tabledata' votable2.to_xml(str(tmpdir.join("regression.bin.tabledata.xml")), _astropy_version="testing", _debug_python_based_parser=_python_based) assert_validate_schema(str(tmpdir.join("regression.bin.tabledata.xml")), votable.version) with io.open( get_pkg_data_filename( 'data/regression.bin.tabledata.truth.{0}.xml'.format( votable.version)), 'rt', encoding='utf-8') as fd: truth = fd.readlines() with io.open(str(tmpdir.join("regression.bin.tabledata.xml")), 'rt', encoding='utf-8') as fd: output = fd.readlines() # If the lines happen to be different, print a diff # This is convenient for debugging for line in difflib.unified_diff(truth, output): sys.stdout.write( line. encode('unicode_escape'). replace('\\n', '\n')) assert truth == output # Test implicit gzip saving votable2.to_xml( str(tmpdir.join("regression.bin.tabledata.xml.gz")), _astropy_version="testing", _debug_python_based_parser=_python_based) with gzip.GzipFile( str(tmpdir.join("regression.bin.tabledata.xml.gz")), 'rb') as gzfd: output = gzfd.readlines() output = [x.decode('utf-8').rstrip() for x in output] truth = [x.rstrip() for x in truth] assert truth == output @pytest.mark.xfail(str('legacy_float_repr')) def test_regression(tmpdir): _test_regression(tmpdir, False) @pytest.mark.xfail(str('legacy_float_repr')) def test_regression_python_based_parser(tmpdir): _test_regression(tmpdir, True) @pytest.mark.xfail(str('legacy_float_repr')) def test_regression_binary2(tmpdir): _test_regression(tmpdir, False, 2) class TestFixups: def setup_class(self): self.table = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False).get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_implicit_id(self): assert_array_equal(self.array['string_test_2'], self.array['fixed string test']) class TestReferences: def setup_class(self): self.votable = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_fieldref(self): fieldref = self.table.groups[1].entries[0] assert isinstance(fieldref, tree.FieldRef) assert fieldref.get_ref().name == 'boolean' assert fieldref.get_ref().datatype == 'boolean' def test_paramref(self): paramref = self.table.groups[0].entries[0] assert isinstance(paramref, tree.ParamRef) assert paramref.get_ref().name == 'INPUT' assert paramref.get_ref().datatype == 'float' def test_iter_fields_and_params_on_a_group(self): assert len(list(self.table.groups[1].iter_fields_and_params())) == 2 def test_iter_groups_on_a_group(self): assert len(list(self.table.groups[1].iter_groups())) == 1 def test_iter_groups(self): # Because of the ref'd table, there are more logical groups # than actually exist in the file assert len(list(self.votable.iter_groups())) == 9 def test_ref_table(self): tables = list(self.votable.iter_tables()) for x, y in zip(tables[0].array.data[0], tables[1].array.data[0]): assert_array_equal(x, y) def test_iter_coosys(self): assert len(list(self.votable.iter_coosys())) == 1 def test_select_columns_by_index(): columns = [0, 5, 13] table = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False, columns=columns).get_first_table() array = table.array mask = table.array.mask assert array['string_test'][0] == b"String & test" columns = ['string_test', 'unsignedByte', 'bitarray'] for c in columns: assert not np.all(mask[c]) assert np.all(mask['unicode_test']) def test_select_columns_by_name(): columns = ['string_test', 'unsignedByte', 'bitarray'] table = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False, columns=columns).get_first_table() array = table.array mask = table.array.mask assert array['string_test'][0] == b"String & test" for c in columns: assert not np.all(mask[c]) assert np.all(mask['unicode_test']) class TestParse: def setup_class(self): self.votable = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_string_test(self): assert issubclass(self.array['string_test'].dtype.type, np.object_) assert_array_equal( self.array['string_test'], [b'String & test', b'String &amp; test', b'XXXX', b'', b'']) def test_fixed_string_test(self): assert issubclass(self.array['string_test_2'].dtype.type, np.string_) assert_array_equal( self.array['string_test_2'], [b'Fixed stri', b'0123456789', b'XXXX', b'', b'']) def test_unicode_test(self): assert issubclass(self.array['unicode_test'].dtype.type, np.object_) assert_array_equal(self.array['unicode_test'], ["Ceçi n'est pas un pipe", 'வணக்கம்', 'XXXX', '', '']) def test_fixed_unicode_test(self): assert issubclass(self.array['fixed_unicode_test'].dtype.type, np.unicode_) assert_array_equal(self.array['fixed_unicode_test'], ["Ceçi n'est", 'வணக்கம்', '0123456789', '', '']) def test_unsignedByte(self): assert issubclass(self.array['unsignedByte'].dtype.type, np.uint8) assert_array_equal(self.array['unsignedByte'], [128, 255, 0, 255, 255]) assert not np.any(self.mask['unsignedByte']) def test_short(self): assert issubclass(self.array['short'].dtype.type, np.int16) assert_array_equal(self.array['short'], [4096, 32767, -4096, 32767, 32767]) assert not np.any(self.mask['short']) def test_int(self): assert issubclass(self.array['int'].dtype.type, np.int32) assert_array_equal( self.array['int'], [268435456, 2147483647, -268435456, 268435455, 123456789]) assert_array_equal(self.mask['int'], [False, False, False, False, True]) def test_long(self): assert issubclass(self.array['long'].dtype.type, np.int64) assert_array_equal( self.array['long'], [922337203685477, 123456789, -1152921504606846976, 1152921504606846975, 123456789]) assert_array_equal(self.mask['long'], [False, True, False, False, True]) def test_double(self): assert issubclass(self.array['double'].dtype.type, np.float64) assert_array_equal(self.array['double'], [8.999999, 0.0, np.inf, np.nan, -np.inf]) assert_array_equal(self.mask['double'], [False, False, False, True, False]) def test_float(self): assert issubclass(self.array['float'].dtype.type, np.float32) assert_array_equal(self.array['float'], [1.0, 0.0, np.inf, np.inf, np.nan]) assert_array_equal(self.mask['float'], [False, False, False, False, True]) def test_array(self): assert issubclass(self.array['array'].dtype.type, np.object_) match = [[], [[42, 32], [12, 32]], [[12, 34], [56, 78], [87, 65], [43, 21]], [[-1, 23]], [[31, -1]]] for a, b in zip(self.array['array'], match): # assert issubclass(a.dtype.type, np.int64) # assert a.shape[1] == 2 for a0, b0 in zip(a, b): assert issubclass(a0.dtype.type, np.int64) assert_array_equal(a0, b0) assert self.array.data['array'][3].mask[0][0] assert self.array.data['array'][4].mask[0][1] def test_bit(self): assert issubclass(self.array['bit'].dtype.type, np.bool_) assert_array_equal(self.array['bit'], [True, False, True, False, False]) def test_bit_mask(self): assert_array_equal(self.mask['bit'], [False, False, False, False, True]) def test_bitarray(self): assert issubclass(self.array['bitarray'].dtype.type, np.bool_) assert self.array['bitarray'].shape == (5, 3, 2) assert_array_equal(self.array['bitarray'], [[[ True, False], [ True, True], [False, True]], [[False, True], [False, False], [ True, True]], [[ True, True], [ True, False], [False, False]], [[False, False], [False, False], [False, False]], [[False, False], [False, False], [False, False]]]) def test_bitarray_mask(self): assert_array_equal(self.mask['bitarray'], [[[False, False], [False, False], [False, False]], [[False, False], [False, False], [False, False]], [[False, False], [False, False], [False, False]], [[ True, True], [ True, True], [ True, True]], [[ True, True], [ True, True], [ True, True]]]) def test_bitvararray(self): assert issubclass(self.array['bitvararray'].dtype.type, np.object_) match = [[ True, True, True], [False, False, False, False, False], [ True, False, True, False, True], [], []] for a, b in zip(self.array['bitvararray'], match): assert_array_equal(a, b) match_mask = [[False, False, False], [False, False, False, False, False], [False, False, False, False, False], False, False] for a, b in zip(self.array['bitvararray'], match_mask): assert_array_equal(a.mask, b) def test_bitvararray2(self): assert issubclass(self.array['bitvararray2'].dtype.type, np.object_) match = [[], [[[False, True], [False, False], [ True, False]], [[ True, False], [ True, False], [ True, False]]], [[[ True, True], [ True, True], [ True, True]]], [], []] for a, b in zip(self.array['bitvararray2'], match): for a0, b0 in zip(a, b): assert a0.shape == (3, 2) assert issubclass(a0.dtype.type, np.bool_) assert_array_equal(a0, b0) def test_floatComplex(self): assert issubclass(self.array['floatComplex'].dtype.type, np.complex64) assert_array_equal(self.array['floatComplex'], [np.nan+0j, 0+0j, 0+-1j, np.nan+0j, np.nan+0j]) assert_array_equal(self.mask['floatComplex'], [True, False, False, True, True]) def test_doubleComplex(self): assert issubclass(self.array['doubleComplex'].dtype.type, np.complex128) assert_array_equal( self.array['doubleComplex'], [np.nan+0j, 0+0j, 0+-1j, np.nan+(np.inf*1j), np.nan+0j]) assert_array_equal(self.mask['doubleComplex'], [True, False, False, True, True]) def test_doubleComplexArray(self): assert issubclass(self.array['doubleComplexArray'].dtype.type, np.object_) assert ([len(x) for x in self.array['doubleComplexArray']] == [0, 2, 2, 0, 0]) def test_boolean(self): assert issubclass(self.array['boolean'].dtype.type, np.bool_) assert_array_equal(self.array['boolean'], [True, False, True, False, False]) def test_boolean_mask(self): assert_array_equal(self.mask['boolean'], [False, False, False, False, True]) def test_boolean_array(self): assert issubclass(self.array['booleanArray'].dtype.type, np.bool_) assert_array_equal(self.array['booleanArray'], [[ True, True, True, True], [ True, True, False, True], [ True, True, False, True], [False, False, False, False], [False, False, False, False]]) def test_boolean_array_mask(self): assert_array_equal(self.mask['booleanArray'], [[False, False, False, False], [False, False, False, False], [False, False, True, False], [ True, True, True, True], [ True, True, True, True]]) def test_nulls(self): assert_array_equal(self.array['nulls'], [0, -9, 2, -9, -9]) assert_array_equal(self.mask['nulls'], [False, True, False, True, True]) def test_nulls_array(self): assert_array_equal(self.array['nulls_array'], [[[-9, -9], [-9, -9]], [[0, 1], [2, 3]], [[-9, 0], [-9, 1]], [[0, -9], [1, -9]], [[-9, -9], [-9, -9]]]) assert_array_equal(self.mask['nulls_array'], [[[ True, True], [ True, True]], [[False, False], [False, False]], [[ True, False], [ True, False]], [[False, True], [False, True]], [[ True, True], [ True, True]]]) def test_double_array(self): assert issubclass(self.array['doublearray'].dtype.type, np.object_) assert len(self.array['doublearray'][0]) == 0 assert_array_equal(self.array['doublearray'][1], [0, 1, np.inf, -np.inf, np.nan, 0, -1]) assert_array_equal(self.array.data['doublearray'][1].mask, [False, False, False, False, False, False, True]) def test_bit_array2(self): assert_array_equal(self.array['bitarray2'][0], [True, True, True, True, False, False, False, False, True, True, True, True, False, False, False, False]) def test_bit_array2_mask(self): assert not np.any(self.mask['bitarray2'][0]) assert np.all(self.mask['bitarray2'][1:]) def test_get_coosys_by_id(self): coosys = self.votable.get_coosys_by_id('J2000') assert coosys.system == 'eq_FK5' def test_get_field_by_utype(self): fields = list(self.votable.get_fields_by_utype("myint")) assert fields[0].name == "int" assert fields[0].values.min == -1000 def test_get_info_by_id(self): info = self.votable.get_info_by_id('QUERY_STATUS') assert info.value == 'OK' if self.votable.version != '1.1': info = self.votable.get_info_by_id("ErrorInfo") assert info.value == "One might expect to find some INFO here, too..." def test_repr(self): assert '3 tables' in repr(self.votable) assert repr(list(self.votable.iter_fields_and_params())[0]) == \ '<PARAM ID="awesome" arraysize="*" datatype="float" name="INPUT" unit="deg" value="[0.0 0.0]"/>' # Smoke test repr(list(self.votable.iter_groups())) # Resource assert repr(self.votable.resources) == '[</>]' class TestThroughTableData(TestParse): def setup_class(self): votable = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False) self.xmlout = bio = io.BytesIO() votable.to_xml(bio) bio.seek(0) self.votable = parse(bio, pedantic=False) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_bit_mask(self): assert_array_equal(self.mask['bit'], [False, False, False, False, False]) def test_bitarray_mask(self): assert not np.any(self.mask['bitarray']) def test_bit_array2_mask(self): assert not np.any(self.mask['bitarray2']) def test_schema(self, tmpdir): # have to use an actual file because assert_validate_schema only works # on filenames, not file-like objects fn = str(tmpdir.join("test_through_tabledata.xml")) with open(fn, 'wb') as f: f.write(self.xmlout.getvalue()) assert_validate_schema(fn, '1.1') class TestThroughBinary(TestParse): def setup_class(self): votable = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False) votable.get_first_table().format = 'binary' self.xmlout = bio = io.BytesIO() votable.to_xml(bio) bio.seek(0) self.votable = parse(bio, pedantic=False) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask # Masked values in bit fields don't roundtrip through the binary # representation -- that's not a bug, just a limitation, so # override the mask array checks here. def test_bit_mask(self): assert not np.any(self.mask['bit']) def test_bitarray_mask(self): assert not np.any(self.mask['bitarray']) def test_bit_array2_mask(self): assert not np.any(self.mask['bitarray2']) class TestThroughBinary2(TestParse): def setup_class(self): votable = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False) votable.version = '1.3' votable.get_first_table()._config['version_1_3_or_later'] = True votable.get_first_table().format = 'binary2' self.xmlout = bio = io.BytesIO() votable.to_xml(bio) bio.seek(0) self.votable = parse(bio, pedantic=False) self.table = self.votable.get_first_table() self.array = self.table.array self.mask = self.table.array.mask def test_get_coosys_by_id(self): # No COOSYS in VOTable 1.2 or later pass def table_from_scratch(): from ..tree import VOTableFile, Resource, Table, Field # Create a new VOTable file... votable = VOTableFile() # ...with one resource... resource = Resource() votable.resources.append(resource) # ... with one table table = Table(votable) resource.tables.append(table) # Define some fields table.fields.extend([ Field(votable, ID="filename", datatype="char"), Field(votable, ID="matrix", datatype="double", arraysize="2x2")]) # Now, use those field definitions to create the numpy record arrays, with # the given number of rows table.create_arrays(2) # Now table.array can be filled with data table.array[0] = ('test1.xml', [[1, 0], [0, 1]]) table.array[1] = ('test2.xml', [[0.5, 0.3], [0.2, 0.1]]) # Now write the whole thing to a file. # Note, we have to use the top-level votable file object out = io.StringIO() votable.to_xml(out) def test_open_files(): for filename in get_pkg_data_filenames('data', pattern='*.xml'): if filename.endswith('custom_datatype.xml'): continue parse(filename, pedantic=False) @raises(VOTableSpecError) def test_too_many_columns(): votable = parse( get_pkg_data_filename('data/too_many_columns.xml.gz'), pedantic=False) def test_build_from_scratch(tmpdir): # Create a new VOTable file... votable = tree.VOTableFile() # ...with one resource... resource = tree.Resource() votable.resources.append(resource) # ... with one table table = tree.Table(votable) resource.tables.append(table) # Define some fields table.fields.extend([ tree.Field(votable, ID="filename", datatype="char"), tree.Field(votable, ID="matrix", datatype="double", arraysize="2x2")]) # Now, use those field definitions to create the numpy record arrays, with # the given number of rows table.create_arrays(2) # Now table.array can be filled with data table.array[0] = ('test1.xml', [[1, 0], [0, 1]]) table.array[1] = ('test2.xml', [[0.5, 0.3], [0.2, 0.1]]) # Now write the whole thing to a file. # Note, we have to use the top-level votable file object votable.to_xml(str(tmpdir.join("new_votable.xml"))) votable = parse(str(tmpdir.join("new_votable.xml"))) table = votable.get_first_table() assert_array_equal( table.array.mask, np.array([(False, [[False, False], [False, False]]), (False, [[False, False], [False, False]])], dtype=[(str('filename'), str('?')), (str('matrix'), str('?'), (2, 2))])) def test_validate(test_path_object=False): """ test_path_object is needed for test below ``test_validate_path_object`` so that file could be passed as pathlib.Path object. """ output = io.StringIO() fpath = get_pkg_data_filename('data/regression.xml') if test_path_object: fpath = pathlib.Path(fpath) # We can't test xmllint, because we can't rely on it being on the # user's machine. with catch_warnings(): result = validate(fpath, output, xmllint=False) assert result is False output.seek(0) output = output.readlines() # Uncomment to generate new groundtruth # with io.open('validation.txt', 'wt', encoding='utf-8') as fd: # fd.write(u''.join(output)) with io.open( get_pkg_data_filename('data/validation.txt'), 'rt', encoding='utf-8') as fd: truth = fd.readlines() truth = truth[1:] output = output[1:-1] for line in difflib.unified_diff(truth, output): if six.PY2: sys.stdout.write( line.encode('unicode_escape'). replace('\\n', '\n')) else: sys.stdout.write( line.replace('\\n', '\n')) assert truth == output @pytest.mark.skipif('not HAS_PATHLIB') def test_validate_path_object(): """ Validating when source is passed as path object. (#4412) """ test_validate(test_path_object=True) def test_gzip_filehandles(tmpdir): votable = parse( get_pkg_data_filename('data/regression.xml'), pedantic=False) with open(str(tmpdir.join("regression.compressed.xml")), 'wb') as fd: votable.to_xml( fd, compressed=True, _astropy_version="testing") with open(str(tmpdir.join("regression.compressed.xml")), 'rb') as fd: votable = parse( fd, pedantic=False) def test_from_scratch_example(): with catch_warnings(VOWarning) as warning_lines: try: _run_test_from_scratch_example() except ValueError as e: warning_lines.append(str(e)) assert len(warning_lines) == 0 def _run_test_from_scratch_example(): from ..tree import VOTableFile, Resource, Table, Field # Create a new VOTable file... votable = VOTableFile() # ...with one resource... resource = Resource() votable.resources.append(resource) # ... with one table table = Table(votable) resource.tables.append(table) # Define some fields table.fields.extend([ Field(votable, name="filename", datatype="char", arraysize="*"), Field(votable, name="matrix", datatype="double", arraysize="2x2")]) # Now, use those field definitions to create the numpy record arrays, with # the given number of rows table.create_arrays(2) # Now table.array can be filled with data table.array[0] = ('test1.xml', [[1, 0], [0, 1]]) table.array[1] = ('test2.xml', [[0.5, 0.3], [0.2, 0.1]]) assert table.array[0][0] == 'test1.xml' def test_fileobj(): # Assert that what we get back is a raw C file pointer # so it will be super fast in the C extension. from ....utils.xml import iterparser filename = get_pkg_data_filename('data/regression.xml') with iterparser._convert_to_fd_or_read_function(filename) as fd: if sys.platform == 'win32': fd() else: if six.PY2: assert isinstance(fd, file) else: assert isinstance(fd, io.FileIO) def test_nonstandard_units(): from .... import units as u votable = parse( get_pkg_data_filename('data/nonstandard_units.xml'), pedantic=False) assert isinstance( votable.get_first_table().fields[0].unit, u.UnrecognizedUnit) votable = parse( get_pkg_data_filename('data/nonstandard_units.xml'), pedantic=False, unit_format='generic') assert not isinstance( votable.get_first_table().fields[0].unit, u.UnrecognizedUnit) def test_resource_structure(): # Based on issue #1223, as reported by @astro-friedel and @RayPlante from astropy.io.votable import tree as vot vtf = vot.VOTableFile() r1 = vot.Resource() vtf.resources.append(r1) t1 = vot.Table(vtf) t1.name = "t1" t2 = vot.Table(vtf) t2.name = 't2' r1.tables.append(t1) r1.tables.append(t2) r2 = vot.Resource() vtf.resources.append(r2) t3 = vot.Table(vtf) t3.name = "t3" t4 = vot.Table(vtf) t4.name = "t4" r2.tables.append(t3) r2.tables.append(t4) r3 = vot.Resource() vtf.resources.append(r3) t5 = vot.Table(vtf) t5.name = "t5" t6 = vot.Table(vtf) t6.name = "t6" r3.tables.append(t5) r3.tables.append(t6) buff = io.BytesIO() vtf.to_xml(buff) buff.seek(0) vtf2 = parse(buff) assert len(vtf2.resources) == 3 for r in range(len(vtf2.resources)): res = vtf2.resources[r] assert len(res.tables) == 2 assert len(res.resources) == 0 def test_no_resource_check(): output = io.StringIO() with catch_warnings(): # We can't test xmllint, because we can't rely on it being on the # user's machine. result = validate(get_pkg_data_filename('data/no_resource.xml'), output, xmllint=False) assert result is False output.seek(0) output = output.readlines() # Uncomment to generate new groundtruth # with io.open('no_resource.txt', 'wt', encoding='utf-8') as fd: # fd.write(u''.join(output)) with io.open( get_pkg_data_filename('data/no_resource.txt'), 'rt', encoding='utf-8') as fd: truth = fd.readlines() truth = truth[1:] output = output[1:-1] for line in difflib.unified_diff(truth, output): if six.PY2: sys.stdout.write( line.encode('unicode_escape'). replace('\\n', '\n')) else: sys.stdout.write( line.replace('\\n', '\n')) assert truth == output def test_instantiate_vowarning(): # This used to raise a deprecation exception on Python 2.6. # See https://github.com/astropy/astroquery/pull/276 VOWarning(()) def test_custom_datatype(): votable = parse( get_pkg_data_filename('data/custom_datatype.xml'), pedantic=False, datatype_mapping={'bar': 'int'} ) table = votable.get_first_table() assert table.array.dtype['foo'] == np.int32
{ "content_hash": "b913dc6fab271d9a19f76b6ea5bac996", "timestamp": "", "source": "github", "line_count": 1031, "max_line_length": 108, "avg_line_length": 33.64694471387003, "alnum_prop": 0.5424041510521764, "repo_name": "joergdietrich/astropy", "id": "31acb9c9ec23d3f40fd78eb62213136f386d9624", "size": "34834", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "astropy/io/votable/tests/vo_test.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "366874" }, { "name": "C++", "bytes": "1825" }, { "name": "HTML", "bytes": "1172" }, { "name": "Jupyter Notebook", "bytes": "62553" }, { "name": "Python", "bytes": "7616749" }, { "name": "Shell", "bytes": "425" }, { "name": "TeX", "bytes": "778" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Debug\Tests\FatalErrorHandler; use Composer\Autoload\ClassLoader as ComposerClassLoader; use PHPUnit\Framework\TestCase; use Symfony\Component\Debug\DebugClassLoader; use Symfony\Component\Debug\Exception\ClassNotFoundException; use Symfony\Component\Debug\Exception\FatalErrorException; use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler; /** * @group legacy */ class ClassNotFoundFatalErrorHandlerTest extends TestCase { public static function setUpBeforeClass(): void { foreach (spl_autoload_functions() as $function) { if (!\is_array($function)) { continue; } // get class loaders wrapped by DebugClassLoader if ($function[0] instanceof DebugClassLoader) { $function = $function[0]->getClassLoader(); if (!\is_array($function)) { continue; } } if ($function[0] instanceof ComposerClassLoader) { $function[0]->add('Symfony_Component_Debug_Tests_Fixtures', \dirname(__DIR__, 5)); break; } } } /** * @dataProvider provideClassNotFoundData */ public function testHandleClassNotFound($error, $translatedMessage, $autoloader = null) { if ($autoloader) { // Unregister all autoloaders to ensure the custom provided // autoloader is the only one to be used during the test run. $autoloaders = spl_autoload_functions(); array_map('spl_autoload_unregister', $autoloaders); spl_autoload_register($autoloader); } $handler = new ClassNotFoundFatalErrorHandler(); $exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line'])); if ($autoloader) { spl_autoload_unregister($autoloader); array_map('spl_autoload_register', $autoloaders); } $this->assertInstanceOf(ClassNotFoundException::class, $exception); $this->assertMatchesRegularExpression($translatedMessage, $exception->getMessage()); $this->assertSame($error['type'], $exception->getSeverity()); $this->assertSame($error['file'], $exception->getFile()); $this->assertSame($error['line'], $exception->getLine()); } public function provideClassNotFoundData() { $autoloader = new ComposerClassLoader(); $autoloader->add('Symfony\Component\Debug\Exception\\', realpath(__DIR__.'/../../Exception')); $autoloader->add('Symfony_Component_Debug_Tests_Fixtures', realpath(__DIR__.'/../../Tests/Fixtures')); $debugClassLoader = new DebugClassLoader([$autoloader, 'loadClass']); return [ [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class "WhizBangFactory" not found', ], "/^Attempted to load class \"WhizBangFactory\" from the global namespace.\nDid you forget a \"use\" statement\?$/", ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'WhizBangFactory\' not found', ], "/^Attempted to load class \"WhizBangFactory\" from the global namespace.\nDid you forget a \"use\" statement\?$/", ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'Foo\\Bar\\WhizBangFactory\' not found', ], "/^Attempted to load class \"WhizBangFactory\" from namespace \"Foo\\\\Bar\".\nDid you forget a \"use\" statement for another namespace\?$/", ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class "Foo\\Bar\\WhizBangFactory" not found', ], "/^Attempted to load class \"WhizBangFactory\" from namespace \"Foo\\\\Bar\".\nDid you forget a \"use\" statement for another namespace\?$/", ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Interface "Foo\\Bar\\WhizBangInterface" not found', ], "/^Attempted to load interface \"WhizBangInterface\" from namespace \"Foo\\\\Bar\".\nDid you forget a \"use\" statement for another namespace\?$/", ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Trait "Foo\\Bar\\WhizBangTrait" not found', ], "/^Attempted to load trait \"WhizBangTrait\" from namespace \"Foo\\\\Bar\".\nDid you forget a \"use\" statement for another namespace\?$/", ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'UndefinedFunctionException\' not found', ], "/^Attempted to load class \"UndefinedFunctionException\" from the global namespace.\nDid you forget a \"use\" statement for .*\"Symfony\\\\Component\\\\Debug\\\\Exception\\\\UndefinedFunctionException\"\?$/", [$debugClassLoader, 'loadClass'], ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'PEARClass\' not found', ], "/^Attempted to load class \"PEARClass\" from the global namespace.\nDid you forget a \"use\" statement for \"Symfony_Component_Debug_Tests_Fixtures_PEARClass\"\?$/", [$debugClassLoader, 'loadClass'], ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found', ], "/^Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\\\\Bar\".\nDid you forget a \"use\" statement for .*\"Symfony\\\\Component\\\\Debug\\\\Exception\\\\UndefinedFunctionException\"\?$/", [$debugClassLoader, 'loadClass'], ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found', ], "/^Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\\\\Bar\".\nDid you forget a \"use\" statement for \"Symfony\\\\Component\\\\Debug\\\\Exception\\\\UndefinedFunctionException\"\?$/", [$autoloader, 'loadClass'], ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found', ], "/^Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\\\\Bar\".\nDid you forget a \"use\" statement for \"Symfony\\\\Component\\\\Debug\\\\Exception\\\\UndefinedFunctionException\"\?/", [$debugClassLoader, 'loadClass'], ], [ [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found', ], "/^Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\\\\Bar\".\nDid you forget a \"use\" statement for another namespace\?$/", function ($className) { /* do nothing here */ }, ], ]; } public function testCannotRedeclareClass() { if (!file_exists(__DIR__.'/../FIXTURES2/REQUIREDTWICE.PHP')) { $this->markTestSkipped('Can only be run on case insensitive filesystems'); } require_once __DIR__.'/../FIXTURES2/REQUIREDTWICE.PHP'; $error = [ 'type' => 1, 'line' => 12, 'file' => 'foo.php', 'message' => 'Class \'Foo\\Bar\\RequiredTwice\' not found', ]; $handler = new ClassNotFoundFatalErrorHandler(); $exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line'])); $this->assertInstanceOf(ClassNotFoundException::class, $exception); } }
{ "content_hash": "b52b841a022f3c2869846410ae40c9d1", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 229, "avg_line_length": 42.16589861751152, "alnum_prop": 0.4946448087431694, "repo_name": "zerkms/symfony", "id": "7e2406dda95f067e53f7085fa746bdc9eccc4c07", "size": "9379", "binary": false, "copies": "3", "ref": "refs/heads/4.4", "path": "src/Symfony/Component/Debug/Tests/FatalErrorHandler/ClassNotFoundFatalErrorHandlerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "48219" }, { "name": "HTML", "bytes": "16735" }, { "name": "Hack", "bytes": "48" }, { "name": "JavaScript", "bytes": "28639" }, { "name": "PHP", "bytes": "20620388" }, { "name": "Shell", "bytes": "3136" }, { "name": "Twig", "bytes": "390641" } ], "symlink_target": "" }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; namespace NakedObjects { /// <summary> /// This interface is intended for use with 'Interface Associations' and specifically /// to work in conjunction with NakedObjects.Services.ObjectFinder. /// If the class being associated implements IHasGuid, then the compound key will use this /// Guid (together with the fully qualified type name) to form the compound key. This has the /// advantage that the Guid may be set up when the object is created rather than waiting until /// the object is persisted (if the keys are database generated, that is). This is /// important when defining interface associations between transient objects that are all /// persisted in one transaction. /// </summary> public interface IHasGuid { /// <summary> /// The Guid property should be set up with a new Guid when the object is created, /// for example in the Created() method. /// </summary> Guid Guid { get; set; } } }
{ "content_hash": "54b93e115f83ee2f02d06104dc8bdb85", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 136, "avg_line_length": 59.57142857142857, "alnum_prop": 0.7008393285371702, "repo_name": "NakedObjectsGroup/NakedObjectsFramework", "id": "a4264286841fc535b52fd140efb9ee1209d18af0", "size": "1670", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Programming Model/NakedObjects/NakedObjects.Helpers/Interfaces/IHasGuid.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3010" }, { "name": "C#", "bytes": "17252161" }, { "name": "CSS", "bytes": "87105" }, { "name": "F#", "bytes": "2080309" }, { "name": "HTML", "bytes": "77491" }, { "name": "JavaScript", "bytes": "7967" }, { "name": "TSQL", "bytes": "5089" }, { "name": "TypeScript", "bytes": "683807" }, { "name": "Vim Snippet", "bytes": "41860" }, { "name": "Visual Basic .NET", "bytes": "288499" } ], "symlink_target": "" }
32 bit hash versions for 4, 8, 16 byte inputs
{ "content_hash": "e40903b1e205d782adc14e1ca87e98c7", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 45, "avg_line_length": 45, "alnum_prop": 0.7555555555555555, "repo_name": "jimon/murmur3unrolled", "id": "d5617463d56e0973dbeff944644b745be0639f8a", "size": "70", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "readme.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3820" }, { "name": "Shell", "bytes": "122" } ], "symlink_target": "" }
(function() { define(['d3'], function() { var StreamGraphLayout; return StreamGraphLayout = (function() { function StreamGraphLayout(options) { this.svg = options.svg, this.xScale = options.xScale, this.yScale = options.yScale, this.symbols = options.symbols, this.generators = options.generators, this.color = options.color, this.height = options.height, this.width = options.width, this.duration = options.duration, this.delay = options.delay, this.onAnimationEnd = options.onAnimationEnd; this.prepareSymbols(); } StreamGraphLayout.prototype.prepareSymbols = function() { var stack, symbolNodes, _this = this; stack = d3.layout.stack().values(function(d) { return d.values; }).x(function(d) { return d.date; }).y(function(d) { return d.price; }).out(function(d, y0, y) { return d.price0 = y0; }).order('reverse').offset('wiggle'); stack(this.symbols); this.generators.line.y(function(d) { return _this.yScale(d.price0); }); symbolNodes = this.svg.selectAll('.symbol').transition().duration(this.duration); symbolNodes.select('path.area').attr('d', function(d) { return _this.generators.area(d.values); }); symbolNodes.select('path.line').style('stroke-opacity', 1e-6).attr('d', function(d) { return _this.generators.line(d.values); }); symbolNodes.select('text').attr('transform', function(d) { d = d.values[d.values.length - 1]; return "translate(" + (_this.width - 60) + ", " + (_this.yScale(d.price / 2 + d.price0)) + ")"; }); return setTimeout(this.onAnimationEnd, this.duration + this.delay); }; return StreamGraphLayout; })(); }); }).call(this);
{ "content_hash": "47cf81a037a2c5ed7e3fbb85982d4377", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 355, "avg_line_length": 39.5531914893617, "alnum_prop": 0.5949435180204411, "repo_name": "mnmly/d3-show-reel-in-coffee", "id": "ef46271aa58d4631440bd531bbc3a7ffc07b3c80", "size": "1894", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "javascripts/layouts/stream-graph.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "34338" }, { "name": "JavaScript", "bytes": "39146" }, { "name": "Shell", "bytes": "192" } ], "symlink_target": "" }
package com.chinamobile.bcbsp.ml.math; import java.util.Iterator; public final class NamedDoubleVector implements DoubleVector { private final String name; private final DoubleVector vector; public NamedDoubleVector(String name, DoubleVector deepCopy) { super(); this.name = name; this.vector = deepCopy; } @Override public double get(int index) { return vector.get(index); } @Override public int getLength() { return vector.getLength(); } @Override public int getDimension() { return vector.getDimension(); } @Override public void set(int index, double value) { vector.set(index, value); } @Override public DoubleVector applyToElements(DoubleFunction func) { return vector.applyToElements(func); } @Override public DoubleVector applyToElements(DoubleVector other, DoubleDoubleFunction func) { return vector.applyToElements(other, func); } @Override public DoubleVector addUnsafe(DoubleVector vector2) { return vector.addUnsafe(vector2); } @Override public DoubleVector add(DoubleVector vector2) { return vector.add(vector2); } @Override public DoubleVector add(double scalar) { return vector.add(scalar); } @Override public DoubleVector subtractUnsafe(DoubleVector vector2) { return vector.subtractUnsafe(vector2); } @Override public DoubleVector subtract(DoubleVector vector2) { return vector.subtract(vector2); } @Override public DoubleVector subtract(double scalar) { return vector.subtract(scalar); } @Override public DoubleVector subtractFrom(double scalar) { return vector.subtractFrom(scalar); } @Override public DoubleVector multiply(double scalar) { return vector.multiply(scalar); } @Override public DoubleVector multiplyUnsafe(DoubleVector vector2) { return vector.multiplyUnsafe(vector2); } @Override public DoubleVector multiply(DoubleVector vector2) { return vector.multiply(vector2); } @Override public DoubleVector multiply(DoubleMatrix matrix) { return vector.multiply(matrix); } @Override public DoubleVector multiplyUnsafe(DoubleMatrix matrix) { return vector.multiplyUnsafe(matrix); } @Override public DoubleVector divide(double scalar) { return vector.divide(scalar); } @Override public DoubleVector divideFrom(double scalar) { return vector.divideFrom(scalar); } @Override public DoubleVector pow(int x) { return vector.pow(x); } @Override public DoubleVector abs() { return vector.abs(); } @Override public DoubleVector sqrt() { return vector.sqrt(); } @Override public double sum() { return vector.sum(); } @Override public double dotUnsafe(DoubleVector vector2) { return vector.dotUnsafe(vector2); } @Override public double dot(DoubleVector vector2) { return vector.dot(vector2); } @Override public DoubleVector slice(int length) { return vector.slice(length); } @Override public DoubleVector sliceUnsafe(int length) { return vector.sliceUnsafe(length); } @Override public DoubleVector slice(int start, int end) { return vector.slice(start, end); } @Override public DoubleVector sliceUnsafe(int start, int end) { return vector.sliceUnsafe(start, end); } @Override public double max() { return vector.max(); } @Override public double min() { return vector.min(); } @Override public double[] toArray() { return vector.toArray(); } @Override public DoubleVector deepCopy() { return new NamedDoubleVector(name, vector.deepCopy()); } @Override public Iterator<DoubleVectorElement> iterateNonZero() { return vector.iterateNonZero(); } @Override public Iterator<DoubleVectorElement> iterate() { return vector.iterate(); } @Override public boolean isSparse() { return vector.isSparse(); } @Override public boolean isNamed() { return true; } @Override public String getName() { return name; } @Override public String toString() { return String.format("%s: %s", name, vector.toString()); } }
{ "content_hash": "bc44b06f15d62a84fb5e7cff2a53917c", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 64, "avg_line_length": 19.201834862385322, "alnum_prop": 0.6942188246536073, "repo_name": "LiuJianan/Graduate-Graph", "id": "51eff55bfd7ac7ea137f1ab74dece54bd8ceae5c", "size": "4992", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/com/chinamobile/bcbsp/ml/math/NamedDoubleVector.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "591" }, { "name": "C++", "bytes": "116080" }, { "name": "CSS", "bytes": "23109" }, { "name": "HTML", "bytes": "882" }, { "name": "Java", "bytes": "2721932" }, { "name": "JavaScript", "bytes": "15201" }, { "name": "Makefile", "bytes": "5881" }, { "name": "Shell", "bytes": "1407" } ], "symlink_target": "" }
package org.starschema.hadoop.yarn.applications.distributedshell; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.ApplicationConstants.Environment; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.LocalResourceType; import org.apache.hadoop.yarn.api.records.LocalResourceVisibility; import org.apache.hadoop.yarn.api.records.NodeReport; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.QueueACL; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.api.records.YarnClusterMetrics; import org.apache.hadoop.yarn.api.records.timeline.TimelineDomain; import org.apache.hadoop.yarn.client.api.TimelineClient; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.YarnClientApplication; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.timeline.TimelineUtils; /** * Client for Distributed Shell application submission to YARN. * * <p> The distributed shell client allows an application master to be launched that in turn would run * the provided shell command on a set of containers. </p> * * <p>This client is meant to act as an example on how to write yarn-based applications. </p> * * <p> To submit an application, a client first needs to connect to the <code>ResourceManager</code> * aka ApplicationsManager or ASM via the {@link ApplicationClientProtocol}. The {@link ApplicationClientProtocol} * provides a way for the client to get access to cluster information and to request for a * new {@link ApplicationId}. <p> * * <p> For the actual job submission, the client first has to create an {@link ApplicationSubmissionContext}. * The {@link ApplicationSubmissionContext} defines the application details such as {@link ApplicationId} * and application name, the priority assigned to the application and the queue * to which this application needs to be assigned. In addition to this, the {@link ApplicationSubmissionContext} * also defines the {@link ContainerLaunchContext} which describes the <code>Container</code> with which * the {@link ApplicationMaster} is launched. </p> * * <p> The {@link ContainerLaunchContext} in this scenario defines the resources to be allocated for the * {@link ApplicationMaster}'s container, the local resources (jars, configuration files) to be made available * and the environment to be set for the {@link ApplicationMaster} and the commands to be executed to run the * {@link ApplicationMaster}. <p> * * <p> Using the {@link ApplicationSubmissionContext}, the client submits the application to the * <code>ResourceManager</code> and then monitors the application by requesting the <code>ResourceManager</code> * for an {@link ApplicationReport} at regular time intervals. In case of the application taking too long, the client * kills the application by submitting a {@link KillApplicationRequest} to the <code>ResourceManager</code>. </p> * */ @InterfaceAudience.Public @InterfaceStability.Unstable public class Client { private static final Log LOG = LogFactory.getLog(Client.class); // Configuration private Configuration conf; private YarnClient yarnClient; // Application master specific info to register a new Application with RM/ASM private String appName = ""; // App master priority private int amPriority = 0; // Queue for App master private String amQueue = ""; // Amt. of memory resource to request for to run the App Master private int amMemory = 10; // Amt. of virtual core resource to request for to run the App Master private int amVCores = 1; // Application master jar file private String appMasterJar = ""; // Main class to invoke application master private final String appMasterMainClass; // Shell command to be executed private String shellCommand = ""; //Hazelcast zip private String hazelcastZip = ""; // Location of shell script private String shellScriptPath = ""; // Args to be passed to the shell command private String[] shellArgs = new String[] {}; // Env variables to be setup for the shell command private Map<String, String> shellEnv = new HashMap<String, String>(); // Shell Command Container priority private int shellCmdPriority = 0; // Amt of memory to request for container in which shell script will be executed private int containerMemory = 10; // Amt. of virtual cores to request for container in which shell script will be executed private int containerVirtualCores = 1; // No. of containers in which the shell script needs to be executed private int numContainers = 1; private String nodeLabelExpression = null; // log4j.properties file // if available, add to local resources and set into classpath private String log4jPropFile = ""; // Start time for client private final long clientStartTime = System.currentTimeMillis(); // Timeout threshold for client. Kill app after time interval expires. private long clientTimeout = 600000; // flag to indicate whether to keep containers across application attempts. private boolean keepContainers = false; private long attemptFailuresValidityInterval = -1; // Debug flag boolean debugFlag = false; // Timeline domain ID private String domainId = null; // Flag to indicate whether to create the domain of the given ID private boolean toCreateDomain = false; // Timeline domain reader access control private String viewACLs = null; // Timeline domain writer access control private String modifyACLs = null; // Command line options private Options opts; private static final String shellCommandPath = "shellCommands"; private static final String shellArgsPath = "shellArgs"; private static final String appMasterJarPath = "AppMaster.jar"; // Hardcoded path to custom log_properties private static final String log4jPath = "log4j.properties"; public static final String SCRIPT_PATH = "ExecScript"; public static final String HAZELCAST_PATH = "Hazelcast"; /** * @param args Command line arguments */ public static void main(String[] args) { boolean result = false; try { Client client = new Client(); LOG.info("Initializing Client"); try { boolean doRun = client.init(args); if (!doRun) { System.exit(0); } } catch (IllegalArgumentException e) { System.err.println(e.getLocalizedMessage()); client.printUsage(); System.exit(-1); } result = client.run(); } catch (Throwable t) { LOG.fatal("Error running Client", t); System.exit(1); } if (result) { LOG.info("Application completed successfully"); System.exit(0); } LOG.error("Application failed to complete successfully"); System.exit(2); } /** */ public Client(Configuration conf) throws Exception { this( "org.starschema.hadoop.yarn.applications.distributedshell.ApplicationMaster", conf); } Client(String appMasterMainClass, Configuration conf) { this.conf = conf; this.appMasterMainClass = appMasterMainClass; yarnClient = YarnClient.createYarnClient(); yarnClient.init(conf); opts = new Options(); opts.addOption("appname", true, "Application Name. Default value - DistributedShell"); opts.addOption("priority", true, "Application Priority. Default 0"); opts.addOption("queue", true, "RM Queue in which this application is to be submitted"); opts.addOption("timeout", true, "Application timeout in milliseconds"); opts.addOption("master_memory", true, "Amount of memory in MB to be requested to run the application master"); opts.addOption("master_vcores", true, "Amount of virtual cores to be requested to run the application master"); opts.addOption("jar", true, "Jar file containing the application master"); opts.addOption("shell_command", true, "Shell command to be executed by " + "the Application Master. Can only specify either --shell_command " + "or --shell_script"); opts.addOption("shell_script", true, "Location of the shell script to be " + "executed. Can only specify either --shell_command or --shell_script"); opts.addOption("hazelcast_zip", true, "Location of the hazelcast zip."); opts.addOption("shell_args", true, "Command line args for the shell script." + "Multiple args can be separated by empty space."); opts.getOption("shell_args").setArgs(Option.UNLIMITED_VALUES); opts.addOption("shell_env", true, "Environment for shell script. Specified as env_key=env_val pairs"); opts.addOption("shell_cmd_priority", true, "Priority for the shell command containers"); opts.addOption("container_memory", true, "Amount of memory in MB to be requested to run the shell command"); opts.addOption("container_vcores", true, "Amount of virtual cores to be requested to run the shell command"); opts.addOption("num_containers", true, "No. of containers on which the shell command needs to be executed"); opts.addOption("log_properties", true, "log4j.properties file"); opts.addOption("keep_containers_across_application_attempts", false, "Flag to indicate whether to keep containers across application attempts." + " If the flag is true, running containers will not be killed when" + " application attempt fails and these containers will be retrieved by" + " the new application attempt "); opts.addOption("attempt_failures_validity_interval", true, "when attempt_failures_validity_interval in milliseconds is set to > 0," + "the failure number will not take failures which happen out of " + "the validityInterval into failure count. " + "If failure count reaches to maxAppAttempts, " + "the application will be failed."); opts.addOption("debug", false, "Dump out debug information"); opts.addOption("domain", true, "ID of the timeline domain where the " + "timeline entities will be put"); opts.addOption("view_acls", true, "Users and groups that allowed to " + "view the timeline entities in the given domain"); opts.addOption("modify_acls", true, "Users and groups that allowed to " + "modify the timeline entities in the given domain"); opts.addOption("create", false, "Flag to indicate whether to create the " + "domain specified with -domain."); opts.addOption("help", false, "Print usage"); opts.addOption("node_label_expression", true, "Node label expression to determine the nodes" + " where all the containers of this application" + " will be allocated, \"\" means containers" + " can be allocated anywhere, if you don't specify the option," + " default node_label_expression of queue will be used."); } /** */ public Client() throws Exception { this(new YarnConfiguration()); } /** * Helper function to print out usage */ private void printUsage() { new HelpFormatter().printHelp("Client", opts); } /** * Parse command line options * @param args Parsed command line options * @return Whether the init was successful to run the client * @throws ParseException */ public boolean init(String[] args) throws ParseException { CommandLine cliParser = new GnuParser().parse(opts, args); if (args.length == 0) { throw new IllegalArgumentException("No args specified for client to initialize"); } if (cliParser.hasOption("log_properties")) { String log4jPath = cliParser.getOptionValue("log_properties"); try { Log4jPropertyHelper.updateLog4jConfiguration(Client.class, log4jPath); } catch (Exception e) { LOG.warn("Can not set up custom log4j properties. " + e); } } if (cliParser.hasOption("help")) { printUsage(); return false; } if (cliParser.hasOption("debug")) { debugFlag = true; } if (cliParser.hasOption("keep_containers_across_application_attempts")) { LOG.info("keep_containers_across_application_attempts"); keepContainers = true; } appName = cliParser.getOptionValue("appname", "DistributedShell"); amPriority = Integer.parseInt(cliParser.getOptionValue("priority", "0")); amQueue = cliParser.getOptionValue("queue", "default"); amMemory = Integer.parseInt(cliParser.getOptionValue("master_memory", "10")); amVCores = Integer.parseInt(cliParser.getOptionValue("master_vcores", "1")); if (amMemory < 0) { throw new IllegalArgumentException("Invalid memory specified for application master, exiting." + " Specified memory=" + amMemory); } if (amVCores < 0) { throw new IllegalArgumentException("Invalid virtual cores specified for application master, exiting." + " Specified virtual cores=" + amVCores); } if (!cliParser.hasOption("jar")) { throw new IllegalArgumentException("No jar file specified for application master"); } appMasterJar = cliParser.getOptionValue("jar"); if (!cliParser.hasOption("shell_command") && !cliParser.hasOption("shell_script")) { throw new IllegalArgumentException( "No shell command or shell script specified to be executed by application master"); } else if (cliParser.hasOption("shell_command") && cliParser.hasOption("shell_script")) { throw new IllegalArgumentException("Can not specify shell_command option " + "and shell_script option at the same time"); } else if (cliParser.hasOption("shell_command")) { shellCommand = cliParser.getOptionValue("shell_command"); } else { shellScriptPath = cliParser.getOptionValue("shell_script"); } if (cliParser.hasOption("hazelcast_zip")) { hazelcastZip = cliParser.getOptionValue("hazelcast_zip"); } if (cliParser.hasOption("shell_args")) { shellArgs = cliParser.getOptionValues("shell_args"); } if (cliParser.hasOption("shell_env")) { String envs[] = cliParser.getOptionValues("shell_env"); for (String env : envs) { env = env.trim(); int index = env.indexOf('='); if (index == -1) { shellEnv.put(env, ""); continue; } String key = env.substring(0, index); String val = ""; if (index < (env.length()-1)) { val = env.substring(index+1); } shellEnv.put(key, val); } } shellCmdPriority = Integer.parseInt(cliParser.getOptionValue("shell_cmd_priority", "0")); containerMemory = Integer.parseInt(cliParser.getOptionValue("container_memory", "10")); containerVirtualCores = Integer.parseInt(cliParser.getOptionValue("container_vcores", "1")); numContainers = Integer.parseInt(cliParser.getOptionValue("num_containers", "1")); if (containerMemory < 0 || containerVirtualCores < 0 || numContainers < 1) { throw new IllegalArgumentException("Invalid no. of containers or container memory/vcores specified," + " exiting." + " Specified containerMemory=" + containerMemory + ", containerVirtualCores=" + containerVirtualCores + ", numContainer=" + numContainers); } nodeLabelExpression = cliParser.getOptionValue("node_label_expression", null); clientTimeout = Integer.parseInt(cliParser.getOptionValue("timeout", "600000")); attemptFailuresValidityInterval = Long.parseLong(cliParser.getOptionValue( "attempt_failures_validity_interval", "-1")); log4jPropFile = cliParser.getOptionValue("log_properties", ""); // Get timeline domain options if (cliParser.hasOption("domain")) { domainId = cliParser.getOptionValue("domain"); toCreateDomain = cliParser.hasOption("create"); if (cliParser.hasOption("view_acls")) { viewACLs = cliParser.getOptionValue("view_acls"); } if (cliParser.hasOption("modify_acls")) { modifyACLs = cliParser.getOptionValue("modify_acls"); } } return true; } /** * Main run function for the client * @return true if application completed successfully * @throws IOException * @throws YarnException */ public boolean run() throws IOException, YarnException { LOG.info("Running Client"); yarnClient.start(); YarnClusterMetrics clusterMetrics = yarnClient.getYarnClusterMetrics(); LOG.info("Got Cluster metric info from ASM" + ", numNodeManagers=" + clusterMetrics.getNumNodeManagers()); List<NodeReport> clusterNodeReports = yarnClient.getNodeReports( NodeState.RUNNING); LOG.info("Got Cluster node info from ASM"); for (NodeReport node : clusterNodeReports) { LOG.info("Got node report from ASM for" + ", nodeId=" + node.getNodeId() + ", nodeAddress" + node.getHttpAddress() + ", nodeRackName" + node.getRackName() + ", nodeNumContainers" + node.getNumContainers()); } QueueInfo queueInfo = yarnClient.getQueueInfo(this.amQueue); LOG.info("Queue info" + ", queueName=" + queueInfo.getQueueName() + ", queueCurrentCapacity=" + queueInfo.getCurrentCapacity() + ", queueMaxCapacity=" + queueInfo.getMaximumCapacity() + ", queueApplicationCount=" + queueInfo.getApplications().size() + ", queueChildQueueCount=" + queueInfo.getChildQueues().size()); List<QueueUserACLInfo> listAclInfo = yarnClient.getQueueAclsInfo(); for (QueueUserACLInfo aclInfo : listAclInfo) { for (QueueACL userAcl : aclInfo.getUserAcls()) { LOG.info("User ACL Info for Queue" + ", queueName=" + aclInfo.getQueueName() + ", userAcl=" + userAcl.name()); } } if (domainId != null && domainId.length() > 0 && toCreateDomain) { prepareTimelineDomain(); } // Get a new application id YarnClientApplication app = yarnClient.createApplication(); GetNewApplicationResponse appResponse = app.getNewApplicationResponse(); // TODO get min/max resource capabilities from RM and change memory ask if needed // If we do not have min/max, we may not be able to correctly request // the required resources from the RM for the app master // Memory ask has to be a multiple of min and less than max. // Dump out information about cluster capability as seen by the resource manager int maxMem = appResponse.getMaximumResourceCapability().getMemory(); LOG.info("Max mem capabililty of resources in this cluster " + maxMem); // A resource ask cannot exceed the max. if (amMemory > maxMem) { LOG.info("AM memory specified above max threshold of cluster. Using max value." + ", specified=" + amMemory + ", max=" + maxMem); amMemory = maxMem; } int maxVCores = appResponse.getMaximumResourceCapability().getVirtualCores(); LOG.info("Max virtual cores capabililty of resources in this cluster " + maxVCores); if (amVCores > maxVCores) { LOG.info("AM virtual cores specified above max threshold of cluster. " + "Using max value." + ", specified=" + amVCores + ", max=" + maxVCores); amVCores = maxVCores; } // set the application name ApplicationSubmissionContext appContext = app.getApplicationSubmissionContext(); ApplicationId appId = appContext.getApplicationId(); appContext.setKeepContainersAcrossApplicationAttempts(keepContainers); appContext.setApplicationName(appName); if (attemptFailuresValidityInterval >= 0) { appContext .setAttemptFailuresValidityInterval(attemptFailuresValidityInterval); } // set local resources for the application master // local files or archives as needed // In this scenario, the jar file for the application master is part of the local resources Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); LOG.info("Copy App Master jar from local filesystem and add to local environment"); // Copy the application master jar to the filesystem // Create a local resource to point to the destination jar path FileSystem fs = FileSystem.get(conf); addToLocalResources(fs, appMasterJar, appMasterJarPath, appId.toString(), localResources, null); // Set the log4j properties if needed if (!log4jPropFile.isEmpty()) { addToLocalResources(fs, log4jPropFile, log4jPath, appId.toString(), localResources, null); } // The shell script has to be made available on the final container(s) // where it will be executed. // To do this, we need to first copy into the filesystem that is visible // to the yarn framework. // We do not need to set this as a local resource for the application // master as the application master does not need it. String hdfsShellScriptLocation = ""; long hdfsShellScriptLen = 0; long hdfsShellScriptTimestamp = 0; if (!shellScriptPath.isEmpty()) { Path shellSrc = new Path(shellScriptPath); String shellPathSuffix = appName + "/" + appId.toString() + "/" + SCRIPT_PATH; Path shellDst = new Path(fs.getHomeDirectory(), shellPathSuffix); fs.copyFromLocalFile(false, true, shellSrc, shellDst); hdfsShellScriptLocation = shellDst.toUri().toString(); FileStatus shellFileStatus = fs.getFileStatus(shellDst); hdfsShellScriptLen = shellFileStatus.getLen(); hdfsShellScriptTimestamp = shellFileStatus.getModificationTime(); } LOG.info("Copy Hazelcast zip from local filesystem and add to local environment"); String hdfsHazelLocation = ""; long hdfsHazelLen = 0; long hdfsHazelTimestamp = 0; if (!hazelcastZip.isEmpty()) { Path hazelSrc = new Path(hazelcastZip); String hazelPathSuffix = appName + "/" + appId.toString() + "/" + HAZELCAST_PATH; Path hazelDst = new Path(fs.getHomeDirectory(), hazelPathSuffix); fs.copyFromLocalFile(false, true, hazelSrc, hazelDst); hdfsHazelLocation = hazelDst.toUri().toString(); LOG.info("Hazelcast zip location: " + hdfsHazelLocation); FileStatus hazelFileStatus = fs.getFileStatus(hazelDst); hdfsHazelLen = hazelFileStatus.getLen(); hdfsHazelTimestamp = hazelFileStatus.getModificationTime(); } if (!shellCommand.isEmpty()) { addToLocalResources(fs, null, shellCommandPath, appId.toString(), localResources, shellCommand); } if (shellArgs.length > 0) { addToLocalResources(fs, null, shellArgsPath, appId.toString(), localResources, StringUtils.join(shellArgs, " ")); } // Set the necessary security tokens as needed //amContainer.setContainerTokens(containerToken); // Set the env variables to be setup in the env where the application master will be run LOG.info("Set the environment for the application master"); Map<String, String> env = new HashMap<String, String>(); // put location of shell script into env // using the env info, the application master will create the correct local resource for the // eventual containers that will be launched to execute the shell scripts env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTLOCATION, hdfsShellScriptLocation); env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTTIMESTAMP, Long.toString(hdfsShellScriptTimestamp)); env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTLEN, Long.toString(hdfsShellScriptLen)); env.put(DSConstants.HAZELLOCATION, hdfsHazelLocation); env.put(DSConstants.HAZELTIMESTAMP, Long.toString(hdfsHazelTimestamp)); env.put(DSConstants.HAZELLEN, Long.toString(hdfsHazelLen)); if (domainId != null && domainId.length() > 0) { env.put(DSConstants.DISTRIBUTEDSHELLTIMELINEDOMAIN, domainId); } // Add AppMaster.jar location to classpath // At some point we should not be required to add // the hadoop specific classpaths to the env. // It should be provided out of the box. // For now setting all required classpaths including // the classpath to "." for the application jar StringBuilder classPathEnv = new StringBuilder(Environment.CLASSPATH.$$()) .append(ApplicationConstants.CLASS_PATH_SEPARATOR).append("./*"); for (String c : conf.getStrings( YarnConfiguration.YARN_APPLICATION_CLASSPATH, YarnConfiguration.DEFAULT_YARN_CROSS_PLATFORM_APPLICATION_CLASSPATH)) { classPathEnv.append(ApplicationConstants.CLASS_PATH_SEPARATOR); classPathEnv.append(c.trim()); } classPathEnv.append(ApplicationConstants.CLASS_PATH_SEPARATOR).append( "./log4j.properties"); // add the runtime classpath needed for tests to work if (conf.getBoolean(YarnConfiguration.IS_MINI_YARN_CLUSTER, false)) { classPathEnv.append(':'); classPathEnv.append(System.getProperty("java.class.path")); } env.put("CLASSPATH", classPathEnv.toString()); // Set the necessary command to execute the application master Vector<CharSequence> vargs = new Vector<CharSequence>(30); // Set java executable command LOG.info("Setting up app master command"); vargs.add(Environment.JAVA_HOME.$$() + "/bin/java"); // Set Xmx based on am memory size vargs.add("-Xmx" + amMemory + "m"); // Set class name vargs.add(appMasterMainClass); // Set params for Application Master vargs.add("--container_memory " + String.valueOf(containerMemory)); vargs.add("--container_vcores " + String.valueOf(containerVirtualCores)); vargs.add("--num_containers " + String.valueOf(numContainers)); if (null != nodeLabelExpression) { appContext.setNodeLabelExpression(nodeLabelExpression); } vargs.add("--priority " + String.valueOf(shellCmdPriority)); for (Map.Entry<String, String> entry : shellEnv.entrySet()) { vargs.add("--shell_env " + entry.getKey() + "=" + entry.getValue()); } if (debugFlag) { vargs.add("--debug"); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stdout"); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stderr"); // Get final commmand StringBuilder command = new StringBuilder(); for (CharSequence str : vargs) { command.append(str).append(" "); } LOG.info("Completed setting up app master command " + command.toString()); List<String> commands = new ArrayList<String>(); commands.add(command.toString()); // Set up the container launch context for the application master ContainerLaunchContext amContainer = ContainerLaunchContext.newInstance( localResources, env, commands, null, null, null); // Set up resource type requirements // For now, both memory and vcores are supported, so we set memory and // vcores requirements Resource capability = Resource.newInstance(amMemory, amVCores); appContext.setResource(capability); // Service data is a binary blob that can be passed to the application // Not needed in this scenario // amContainer.setServiceData(serviceData); // Setup security tokens if (UserGroupInformation.isSecurityEnabled()) { // Note: Credentials class is marked as LimitedPrivate for HDFS and MapReduce Credentials credentials = new Credentials(); String tokenRenewer = conf.get(YarnConfiguration.RM_PRINCIPAL); if (tokenRenewer == null || tokenRenewer.length() == 0) { throw new IOException( "Can't get Master Kerberos principal for the RM to use as renewer"); } // For now, only getting tokens for the default file-system. final Token<?> tokens[] = fs.addDelegationTokens(tokenRenewer, credentials); if (tokens != null) { for (Token<?> token : tokens) { LOG.info("Got dt for " + fs.getUri() + "; " + token); } } DataOutputBuffer dob = new DataOutputBuffer(); credentials.writeTokenStorageToStream(dob); ByteBuffer fsTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); amContainer.setTokens(fsTokens); } appContext.setAMContainerSpec(amContainer); // Set the priority for the application master // TODO - what is the range for priority? how to decide? Priority pri = Priority.newInstance(amPriority); appContext.setPriority(pri); // Set the queue to which this application is to be submitted in the RM appContext.setQueue(amQueue); // Submit the application to the applications manager // SubmitApplicationResponse submitResp = applicationsManager.submitApplication(appRequest); // Ignore the response as either a valid response object is returned on success // or an exception thrown to denote some form of a failure LOG.info("Submitting application to ASM"); yarnClient.submitApplication(appContext); // TODO // Try submitting the same request again // app submission failure? // Monitor the application return monitorApplication(appId); } /** * Monitor the submitted application for completion. * Kill application if time expires. * @param appId Application Id of application to be monitored * @return true if application completed successfully * @throws YarnException * @throws IOException */ private boolean monitorApplication(ApplicationId appId) throws YarnException, IOException { while (true) { // Check app status every 1 second. try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.debug("Thread sleep in monitoring loop interrupted"); } // Get application report for the appId we are interested in ApplicationReport report = yarnClient.getApplicationReport(appId); LOG.info("Got application report from ASM for" + ", appId=" + appId.getId() + ", clientToAMToken=" + report.getClientToAMToken() + ", appDiagnostics=" + report.getDiagnostics() + ", appMasterHost=" + report.getHost() + ", appQueue=" + report.getQueue() + ", appMasterRpcPort=" + report.getRpcPort() + ", appStartTime=" + report.getStartTime() + ", yarnAppState=" + report.getYarnApplicationState().toString() + ", distributedFinalState=" + report.getFinalApplicationStatus().toString() + ", appTrackingUrl=" + report.getTrackingUrl() + ", appUser=" + report.getUser()); YarnApplicationState state = report.getYarnApplicationState(); FinalApplicationStatus dsStatus = report.getFinalApplicationStatus(); if (YarnApplicationState.FINISHED == state) { if (FinalApplicationStatus.SUCCEEDED == dsStatus) { LOG.info("Application has completed successfully. Breaking monitoring loop"); return true; } else { LOG.info("Application did finished unsuccessfully." + " YarnState=" + state.toString() + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop"); return false; } } else if (YarnApplicationState.KILLED == state || YarnApplicationState.FAILED == state) { LOG.info("Application did not finish." + " YarnState=" + state.toString() + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop"); return false; } // if (System.currentTimeMillis() > (clientStartTime + clientTimeout)) { // LOG.info("Reached client specified timeout for application. Killing application"); // forceKillApplication(appId); // return false; // } } } /** * Kill a submitted application by sending a call to the ASM * @param appId Application Id to be killed. * @throws YarnException * @throws IOException */ private void forceKillApplication(ApplicationId appId) throws YarnException, IOException { // TODO clarify whether multiple jobs with the same app id can be submitted and be running at // the same time. // If yes, can we kill a particular attempt only? // Response can be ignored as it is non-null on success or // throws an exception in case of failures yarnClient.killApplication(appId); } private void addToLocalResources(FileSystem fs, String fileSrcPath, String fileDstPath, String appId, Map<String, LocalResource> localResources, String resources) throws IOException { String suffix = appName + "/" + appId + "/" + fileDstPath; Path dst = new Path(fs.getHomeDirectory(), suffix); if (fileSrcPath == null) { FSDataOutputStream ostream = null; try { ostream = FileSystem .create(fs, dst, new FsPermission((short) 0710)); ostream.writeUTF(resources); } finally { IOUtils.closeQuietly(ostream); } } else { fs.copyFromLocalFile(new Path(fileSrcPath), dst); } FileStatus scFileStatus = fs.getFileStatus(dst); LocalResource scRsrc = LocalResource.newInstance( ConverterUtils.getYarnUrlFromURI(dst.toUri()), LocalResourceType.FILE, LocalResourceVisibility.APPLICATION, scFileStatus.getLen(), scFileStatus.getModificationTime()); localResources.put(fileDstPath, scRsrc); } private void addToLocalResourcesCompressed(FileSystem fs, String fileSrcPath, String fileDstPath, String appId, Map<String, LocalResource> localResources, String resources) throws IOException { String suffix = appName + "/" + appId + "/" + fileDstPath; Path dst = new Path(fs.getHomeDirectory(), suffix); if (fileSrcPath == null) { FSDataOutputStream ostream = null; try { ostream = FileSystem .create(fs, dst, new FsPermission((short) 0710)); ostream.writeUTF(resources); } finally { IOUtils.closeQuietly(ostream); } } else { fs.copyFromLocalFile(new Path(fileSrcPath), dst); } FileStatus scFileStatus = fs.getFileStatus(dst); LocalResource scRsrc = LocalResource.newInstance( ConverterUtils.getYarnUrlFromURI(dst.toUri()), LocalResourceType.ARCHIVE, LocalResourceVisibility.APPLICATION, scFileStatus.getLen(), scFileStatus.getModificationTime()); localResources.put(fileDstPath, scRsrc); } private void prepareTimelineDomain() { TimelineClient timelineClient = null; if (conf.getBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, YarnConfiguration.DEFAULT_TIMELINE_SERVICE_ENABLED)) { timelineClient = TimelineClient.createTimelineClient(); timelineClient.init(conf); timelineClient.start(); } else { LOG.warn("Cannot put the domain " + domainId + " because the timeline service is not enabled"); return; } try { //TODO: we need to check and combine the existing timeline domain ACLs, //but let's do it once we have client java library to query domains. TimelineDomain domain = new TimelineDomain(); domain.setId(domainId); domain.setReaders( viewACLs != null && viewACLs.length() > 0 ? viewACLs : " "); domain.setWriters( modifyACLs != null && modifyACLs.length() > 0 ? modifyACLs : " "); timelineClient.putDomain(domain); LOG.info("Put the timeline domain: " + TimelineUtils.dumpTimelineRecordtoJSON(domain)); } catch (Exception e) { LOG.error("Error when putting the timeline domain", e); } finally { timelineClient.stop(); } } }
{ "content_hash": "5f0921e31cb920d415e5a8bda227c0d3", "timestamp": "", "source": "github", "line_count": 903, "max_line_length": 118, "avg_line_length": 42.02768549280177, "alnum_prop": 0.6927617190587864, "repo_name": "starschema/yarn-hazelcast", "id": "eb687ec89409883aa76aafb9d3c847badadbc2fc", "size": "38757", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/starschema/hadoop/yarn/applications/distributedshell/Client.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "92251" } ], "symlink_target": "" }