text
stringlengths
2
1.04M
meta
dict
/* @flow */ import React from 'react'; import { StyleSheet, View } from 'react-native'; import Emoji from './Emoji'; const styles = StyleSheet.create({ container: { flexDirection: 'row', }, }); export default class EmojiPicker extends React.Component { render() { return ( <View style={styles.container}> <Emoji name="briefcase" /> </View> ); } }
{ "content_hash": "4e4a800d191ce8986e84b0c8e6cb2a6e", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 58, "avg_line_length": 19.45, "alnum_prop": 0.6143958868894601, "repo_name": "nashvail/zulip-mobile", "id": "bfda0edc03cc6a9b0a27a53be2db7503260aacc5", "size": "389", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/emoji/EmojiPicker.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "67421" }, { "name": "Java", "bytes": "52280" }, { "name": "JavaScript", "bytes": "698246" }, { "name": "Objective-C", "bytes": "20413" }, { "name": "Python", "bytes": "1508" } ], "symlink_target": "" }
static float doCollisionSound(cpArbiter *arb, CollisionSounds *sounds) { float gain = 0; //Sound if (cpArbiterIsFirstContact(arb)) { cpVect total = cpArbiterTotalImpulse(arb); float lenSq = cpvlengthsq(total); static const float min = 900.0f; //NSLog(@"Coll Force Squared: %.2f", lenSq); //Theshold if (lenSq > (min * min)) { CP_ARBITER_GET_SHAPES(arb, shapeA, shapeB); NSArray *soundFiles = [sounds collisionSoundsForFirstType:shapeA->collision_type secondType:shapeB->collision_type]; if (soundFiles) { static const float max = 2400.0f; float len = cpfsqrt(lenSq); //NSLog(@"Coll Force: %.2f", len); //Volume based on impact force gain = cpfmin((len-min)/(max-min), 1.0f); //NSLog(@"Gain: %.2f", gain); //Random pitch (based upon volume too), but not too low or high (0.7 - 1.2) float pitch = 0.7f + ((rand()%51) * gain)/100.0f; //Play a random sound from the array NSString *file = [soundFiles objectAtIndex:rand()%[soundFiles count]]; [[SimpleAudioEngine sharedEngine] playEffect:file pitch:pitch pan:0.0f gain:gain]; //NSLog(@"Play FX: %@ for type:%li and type:%li", file, shapeA->collision_type, shapeB->collision_type); } } } return gain; } void collisionSound(cpArbiter *arb, cpSpace *space, void *data) { // CP_ARBITER_GET_SHAPES(arb, shapeA, shapeB); // NSLog(@"Play FX for type:%li and type:%li", shapeA->collision_type, shapeB->collision_type); doCollisionSound(arb, [CollisionSounds sharedSounds]); } @interface CollisionSounds () { NSMutableDictionary *_library; } @end @implementation CollisionSounds // // singleton stuff // static CollisionSounds *_sharedCollisionSounds = nil; +(CollisionSounds*) sharedSounds { if (!_sharedCollisionSounds) { _sharedCollisionSounds = [[self alloc] init]; } return _sharedCollisionSounds; } +(void) destroy { [_sharedCollisionSounds release]; } +(id) alloc { NSAssert(_sharedCollisionSounds == nil, @"Attempted to allocate a second instance of a singleton."); if (_sharedCollisionSounds) return nil; else return [super alloc]; } -(id) init { if ((self = [super init])) { _library = [[NSMutableDictionary dictionaryWithCapacity:20] retain]; } return self; } -(void) dealloc { [_library release]; [super dealloc]; } -(void) addCollisionSoundForFirstType:(int)type1 secondType:(int)type2 soundFile:(NSString*)soundFile; { NSMutableDictionary *secondary = [_library objectForKey:[NSNumber numberWithInt:type1]]; NSMutableArray *soundFiles = nil; if (!secondary) { secondary = [NSMutableDictionary dictionaryWithCapacity:10]; [_library setObject:secondary forKey:[NSNumber numberWithInt:type1]]; soundFiles = [NSMutableArray arrayWithCapacity:5]; [secondary setObject:soundFiles forKey:[NSNumber numberWithInt:type2]]; } else { soundFiles = [secondary objectForKey:[NSNumber numberWithInt:type2]]; if (!soundFiles) { soundFiles = [NSMutableArray arrayWithCapacity:5]; [secondary setObject:soundFiles forKey:[NSNumber numberWithInt:type2]]; } } [soundFiles addObject:soundFile]; } -(NSArray*) collisionSoundsForFirstType:(int)type1 secondType:(int)type2 { NSDictionary *first = [_library objectForKey:[NSNumber numberWithInt:type1]]; NSArray *sounds = [first objectForKey:[NSNumber numberWithInt:type2]]; return sounds; } @end
{ "content_hash": "08106a0b2787b67f9bd5a266f89ce372", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 128, "avg_line_length": 27.3125, "alnum_prop": 0.6020849224510552, "repo_name": "Tinybop/Boidlings", "id": "35965957617c15be9bd3e186239192f3ddb0c177", "size": "4177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Flockers/CollisionSounds.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "564541" }, { "name": "C++", "bytes": "306853" }, { "name": "M", "bytes": "333590" }, { "name": "Matlab", "bytes": "1875" }, { "name": "Objective-C", "bytes": "1798626" }, { "name": "Objective-C++", "bytes": "57744" } ], "symlink_target": "" }
A real-life benchmark for NoSQL databases. It simulates the use case of powering the newsfeed for a social app. The benchmark is open source and easy to replicate. It uses [Stream-Framework](https://github.com/tschellenbach/stream-framework), the most widely used open source package for building scalable newsfeeds and activity streams. CloudFormation, Fabric, Boto and Cloud-init are used to automatically setup the infrastructure and run the benchmark. # Running the benchmark Note that running a benchmark can be expensive. ## Setup your development environment ``` git clone https://github.com/GetStream/Stream-Framework-Bench.git ``` Create a new python virtual env ``` mkvirtualenv bench ``` Install the dependencies ``` pip install -r requirements ``` Ensure you have your AWS cli [installed and configured](http://docs.aws.amazon.com/cli/latest/userguide/installing.html). Configure your [credentials file](https://boto3.readthedocs.org/en/latest/guide/quickstart.html#configuration) Change the key pair name used for starting the instances by editing stack.template ## Start the cluster Start the cluster on AWS (warning, this is expensive). By default the stack will be created in the us-west-2 region. ``` fab create_stack:stack=cassandra,key_name=yourkeyname ``` Optionally you can use datadog to track the benchmark metrics: ``` fab create_stack:stack=cassandra,datadog=yourapikeyhere ``` You can view the progress in your Cloudformation dashboard. Note that cloud-init will take a while to run. (cassandra-driver takes a while to install) ## Running the benchmark using stream framework ``` fab run_bench:stack=cassandra ``` Note: This step will fail if your stack didn't complete the cloud-init configuration step. The benchmark will slowly increase the number of users in the graph and measure: * The time it takes to read a feed * The fanout delay for feed updates ## Stopping the stack ``` fab delete_stack:stack=cassandra ``` # Testing another NoSQL database Fork Stream-Framework https://github.com/tschellenbach/stream-framework Implement your own storage backend Fork Stream-Framework-Bench Update requirements.txt and reference your Stream-Framework fork Copy the cassandra.json cloudformation file and make the required changes # Benchmarks using Stream-Framework-Bench * HighScalability post # A typical stack A stack will typically start several components * RabbitMQ (message queue) & Admin instance - 1 large node * Task workers/ Celery - An autoscaling group of task workers * A cluster of your database instances - 3 by default # Development tips * Running a celery worker locally ``` celery -A benchmark worker -l debug ``` * Set CELERY_ALWAYS_EAGER to False
{ "content_hash": "079221b748e845d45c58a262adf15701", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 338, "avg_line_length": 26.54368932038835, "alnum_prop": 0.780175566934894, "repo_name": "GetStream/Stream-Framework-Bench", "id": "eb2d30b5e946f4a0388e2515ceb4317205bb81b6", "size": "2761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "1689" }, { "name": "Python", "bytes": "18450" } ], "symlink_target": "" }
const { injectBabelPlugin } = require('react-app-rewired'); const rewireLess = require('react-app-rewire-less'); module.exports = function override(config, env) { config = injectBabelPlugin(['import', { libraryName: 'antd', style: true }], config); // change importing css to less config = rewireLess(config, env, { modifyVars: { "@primary-color": "#E4692B" }, }); return config; };
{ "content_hash": "63b0998a2e38a47716c57ba3ef106cf5", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 120, "avg_line_length": 33.916666666666664, "alnum_prop": 0.6633906633906634, "repo_name": "RisenEsports/RisenEsports.github.io", "id": "4e807ac996b5e569c711616bab49eb5a275e3a7e", "size": "407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Console/app/config-overrides.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "583" }, { "name": "HTML", "bytes": "8106" }, { "name": "JavaScript", "bytes": "25228" } ], "symlink_target": "" }
package org.eclipse.php.internal.ui.search; import org.eclipse.osgi.util.NLS; public class Messages extends NLS { private static final String BUNDLE_NAME = "org.eclipse.php.internal.ui.search.messages"; //$NON-NLS-1$ public static String OccurrencesSearchQuery_0; static { // initialize resource bundle NLS.initializeMessages(BUNDLE_NAME, Messages.class); } private Messages() { } }
{ "content_hash": "5c787e8ec3c996bf70ee717be2de06a3", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 103, "avg_line_length": 27.4, "alnum_prop": 0.7299270072992701, "repo_name": "rajeevanv89/developer-studio", "id": "c1f9fbc75ffb327c402a513773d67b92acff0384", "size": "411", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "jaggery/org.eclipse.php.ui/src/org/eclipse/php/internal/ui/search/Messages.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "884" }, { "name": "CSS", "bytes": "62302" }, { "name": "GAP", "bytes": "14192" }, { "name": "Java", "bytes": "78811689" }, { "name": "JavaScript", "bytes": "171473" }, { "name": "PHP", "bytes": "4691550" }, { "name": "Shell", "bytes": "429" }, { "name": "XSLT", "bytes": "10672" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>finger-tree: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.13.1 / finger-tree - 8.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> finger-tree <small> 8.5.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-02 22:22:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-02 22:22:55 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/finger-tree&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/FingerTree&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;keyword:data structures&quot; &quot;keyword:dependent types&quot; &quot;keyword:finger trees&quot; &quot;category:Computer Science/Data Types and Data Structures&quot; &quot;date:2009-02&quot; ] authors: [ &quot;Matthieu Sozeau &lt;[email protected]&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/finger-tree/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/finger-tree.git&quot; synopsis: &quot;Dependent Finger Trees&quot; description: &quot;A verified generic implementation of Finger Trees&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/finger-tree/archive/v8.5.0.tar.gz&quot; checksum: &quot;md5=2e6ac43bdbddaa8882a0d6fc2effaa09&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-finger-tree.8.5.0 coq.8.13.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.1). The following dependencies couldn&#39;t be met: - coq-finger-tree -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-finger-tree.8.5.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "ce22677c5e9e694c2234f6dfd7b94833", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 208, "avg_line_length": 42.60493827160494, "alnum_prop": 0.5423065778035352, "repo_name": "coq-bench/coq-bench.github.io", "id": "701cd6f5123fc300434c49ee3ad8b8cf88df1862", "size": "6927", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.13.1/finger-tree/8.5.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Azure.Core.Amqp; using Microsoft.Azure.WebJobs.ServiceBus.Triggers; using NUnit.Framework; using Azure.Messaging.ServiceBus; using Microsoft.Azure.WebJobs.Extensions.ServiceBus.Triggers; namespace Microsoft.Azure.WebJobs.ServiceBus.UnitTests { public class MessageToStringConverterTests { private const string TestString = "This is a test!"; private const string TestJson = "{ value: 'This is a test!' }"; [Test] [TestCase(ContentTypes.TextPlain, TestString)] [TestCase(ContentTypes.ApplicationJson, TestJson)] [TestCase(ContentTypes.ApplicationOctetStream, TestString)] [TestCase(null, TestJson)] [TestCase("application/xml", TestJson)] [TestCase(ContentTypes.TextPlain, null)] public void Convert_ReturnsExpectedResult_WithBinarySerializer(string contentType, string value) { byte[] bytes; using (MemoryStream ms = new MemoryStream()) { DataContractBinarySerializer<string>.Instance.WriteObject(ms, value); bytes = ms.ToArray(); } ServiceBusReceivedMessage message = ServiceBusModelFactory.ServiceBusReceivedMessage(body: new BinaryData(bytes), contentType: contentType); MessageToStringConverter converter = new MessageToStringConverter(); string result = converter.Convert(message); Assert.AreEqual(value, result); } [Theory] [TestCase(ContentTypes.TextPlain, TestString)] [TestCase(ContentTypes.ApplicationJson, TestJson)] [TestCase(ContentTypes.ApplicationOctetStream, TestString)] [TestCase(null, TestJson)] [TestCase("application/xml", TestJson)] [TestCase(ContentTypes.TextPlain, null)] [TestCase(ContentTypes.TextPlain, "")] public void Convert_ReturnsExpectedResult_WithSerializedString(string contentType, string value) { ServiceBusReceivedMessage message = ServiceBusModelFactory.ServiceBusReceivedMessage( body: value == null ? null : new BinaryData(value), contentType: contentType); MessageToStringConverter converter = new MessageToStringConverter(); string result = converter.Convert(message); // A received message will never have a null body as a body section is required when sending even if it // is empty. This was true in Track 1 as well, but in Track 1 the actual body property could be null when // constructing the message, but in practice it wouldn't be null when receiving. if (value == null) { Assert.AreEqual("", result); } else { Assert.AreEqual(value, result); } } [Test] public void Convert_ReturnsExpectedResult_WithSerializedObject() { byte[] bytes; using (MemoryStream ms = new MemoryStream()) { DataContractBinarySerializer<TestObject>.Instance.WriteObject(ms, new TestObject() { Text = "Test" }); bytes = ms.ToArray(); } ServiceBusReceivedMessage message = ServiceBusModelFactory.ServiceBusReceivedMessage(body: new BinaryData(bytes)); MessageToStringConverter converter = new MessageToStringConverter(); string result = converter.Convert(message); Assert.AreEqual(message.Body.ToString(), result); } [Test] public void Convert_ValueBodyMessage_String() { ServiceBusReceivedMessage message = ServiceBusModelFactory.ServiceBusReceivedMessage(); message.GetRawAmqpMessage().Body = AmqpMessageBody.FromValue("value"); MessageToStringConverter converter = new MessageToStringConverter(); string result = converter.Convert(message); Assert.AreEqual("value", result); } [Test] public void Convert_ValueBodyMessage_NonStringThrows() { ServiceBusReceivedMessage message = ServiceBusModelFactory.ServiceBusReceivedMessage(); message.GetRawAmqpMessage().Body = AmqpMessageBody.FromValue(5); MessageToStringConverter converter = new MessageToStringConverter(); Assert.That( () => converter.Convert(message), Throws.InstanceOf<NotSupportedException>()); } [Test] public void Convert_SequenceBodyMessage_Throws() { ServiceBusReceivedMessage message = ServiceBusModelFactory.ServiceBusReceivedMessage(); message.GetRawAmqpMessage().Body = AmqpMessageBody.FromSequence(new IList<object>[]{ new object[] {"sequence"}}); MessageToStringConverter converter = new MessageToStringConverter(); Assert.That( () => converter.Convert(message), Throws.InstanceOf<NotSupportedException>()); } [Serializable] public class TestObject { public string Text { get; set; } } } }
{ "content_hash": "025df692ba080d6e04426714d40526bc", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 152, "avg_line_length": 40.6865671641791, "alnum_prop": 0.646551724137931, "repo_name": "Azure/azure-sdk-for-net", "id": "8fb4728e1d9ab0c3b6c5c57ff28111816f3d56b6", "size": "5454", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "sdk/servicebus/Microsoft.Azure.WebJobs.Extensions.ServiceBus/tests/MessageToStringConverterTests.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package pool import ( "fmt" "os" "time" "github.com/garyburd/redigo/redis" ) // Manager manages different redis connections type Manager struct { messageChan chan message connections map[string]*redis.Pool } // NewManager constructs a new Manager func NewManager(messageChan chan message) *Manager { connections := make(map[string]*redis.Pool) return &Manager{messageChan, connections} } // Manage tells the manager to manage. I'm a // people person func (manager *Manager) Manage() { for { msg := <-manager.messageChan manager.message(msg) } } func (manager *Manager) message(msg message) { connection := manager.connection(msg.redisURI) defer connection.Close() _, err := connection.Do("LPUSH", msg.redisQueueName, msg.data) if err != nil { fmt.Fprintln(os.Stderr, "LPUSH failed", err.Error()) } } func (manager *Manager) connection(redisURI string) redis.Conn { pool := manager.pool(redisURI) return pool.Get() } func (manager *Manager) pool(redisURI string) *redis.Pool { pool, ok := manager.connections[redisURI] if ok { return pool } pool = newPool(redisURI) manager.connections[redisURI] = pool return pool } func newPool(redisURI string) *redis.Pool { fmt.Println("newPool", redisURI) return &redis.Pool{ MaxIdle: 1, IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { return redis.DialURL(redisURI) }, TestOnBorrow: func(conn redis.Conn, t time.Time) error { _, err := conn.Do("PING") return err }, } }
{ "content_hash": "c906058b572d133c45ab56c8431e49f6", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 64, "avg_line_length": 21.08450704225352, "alnum_prop": 0.7020708082832331, "repo_name": "octoblu/vulcand-bundle", "id": "313df886525bc8b1a5f76181c1f4baefaa5e6123", "size": "1497", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/github.com/octoblu/vulcand-job-logger/pool/manager.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "1522" }, { "name": "Shell", "bytes": "1181" } ], "symlink_target": "" }
package org.pac.games.physics; import java.util.Vector; import java.util.List; import java.util.LinkedList; /** * This is a high level grid for figuring out which rectangles *might* collide. */ public class CollisionGrid{ private int xDim, yDim; private boolean autoresize; private Vector[][] potentialColliders; private double minX, minY, maxX, maxY; @SuppressWarnings("rawtypes") public CollisionGrid( int xDivisions, int yDivisions, double minX, double minY, double maxX, double maxY, boolean autoresize ){ xDim = xDivisions; yDim = yDivisions; potentialColliders = new Vector[xDim][yDim]; for(int x = 0; x < xDim; x++){ for(int y = 0; y < yDim; y++){ potentialColliders[x][y] = new Vector<MovingRectangle>(); } } this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; this.autoresize = autoresize; } public CollisionGrid(int xDivisions, int yDivisions){ this(xDivisions, yDivisions, 0,0,640,480, true); } public CollisionGrid(){ this(32,32); } private void resize(Iterable<MovingRectangle> rectangles, double dt){ double minX = Double.POSITIVE_INFINITY; double minY = Double.POSITIVE_INFINITY; double maxX = Double.NEGATIVE_INFINITY; double maxY = Double.NEGATIVE_INFINITY; for(MovingRectangle rectangle:rectangles){ Rectangle motionBounds = rectangle.getMotionBounds(dt); if(motionBounds.leftX()<minX) minX = motionBounds.leftX(); if(motionBounds.rightX()>maxX) maxX = motionBounds.rightX(); if(motionBounds.topY()<minY) minY = motionBounds.topY(); if(motionBounds.bottomY()>maxY) maxY = motionBounds.bottomY(); } if(minX < Double.POSITIVE_INFINITY){ this.minX = minX; this.minY = minY; this.maxX = maxX; this.maxY = maxY; } } private void clearPotentials(){ for(int x = 0; x < xDim; x++){ for(int y = 0; y < yDim; y++){ potentialColliders[x][y].clear(); } } } @SuppressWarnings("unchecked") private void fillPotentials(Iterable<MovingRectangle> rectangles, double dt){ double cellWidth = (maxX-minX)/xDim; double cellHeight = (maxY-minY)/yDim; for(MovingRectangle rectangle:rectangles){ Rectangle motionBounds = rectangle.getMotionBounds(dt); int gridStartX = (int)((motionBounds.leftX()-minX)/cellWidth); int gridEndX = (int)((motionBounds.rightX()-minX)/cellWidth); gridEndX = Math.min(gridEndX,xDim-1); int gridStartY = (int)((motionBounds.topY()-minY)/cellHeight); int gridEndY = (int)((motionBounds.bottomY()-minY)/cellHeight); gridEndY = Math.min(gridEndY,yDim-1); for(int x = gridStartX; x<=gridEndX; x++){ for(int y = gridStartY; y<=gridEndY; y++){ potentialColliders[x][y].add(rectangle); } } } } private void updatePotentials(Iterable<MovingRectangle> rectangles, double dt){ resize(rectangles, dt); clearPotentials(); fillPotentials(rectangles, dt); } /** * returns the time of the next collision(s). * Fills 'nextCollisions' with the next collisions. **/ private double getNextCollisions( List<MovingRectangle> rectangles, //input CollisionsState curCollisions, //input double dt, //input double nextCollisionTime, //input LinkedList<CollisionInstance> nextCollisions //output ){ for(int i = 0; i < rectangles.size(); i++){ MovingRectangle a = rectangles.get(i); for(int j = i+1; j<rectangles.size(); j++){ MovingRectangle b = rectangles.get(j); double whenIntersects = a.firstIntersect( b, b.getDX()-a.getDX(), b.getDY()-a.getDY() ); if(whenIntersects!=Double.NaN && whenIntersects>=0 && whenIntersects<dt){ if(whenIntersects<nextCollisionTime){ CollisionInstance collision = new CollisionInstance(a,b); if(!curCollisions.contains(collision)){ nextCollisionTime = whenIntersects; nextCollisions.clear(); nextCollisions.add(collision); } } else if(whenIntersects==nextCollisionTime){ CollisionInstance collision = new CollisionInstance(a,b); if(!curCollisions.contains(collision) && !nextCollisions.contains(collision) ){ nextCollisions.add(collision); } } } } } return nextCollisionTime; } /** * returns the time of the next collision(s). * Fills 'nextCollisions' with the next collisions. **/ @SuppressWarnings("unchecked") public double getNextCollisions( Iterable<MovingRectangle> rectangles, //input CollisionsState curCollisions, double dt, //input LinkedList<CollisionInstance> nextCollisions //output ){ updatePotentials(rectangles, dt); double nextCollisionTime = Double.POSITIVE_INFINITY; for(int x = 0; x < xDim; x++){ for(int y = 0; y < yDim; y++){ nextCollisionTime = getNextCollisions( (Vector<MovingRectangle>)potentialColliders[x][y], curCollisions, dt, nextCollisionTime, nextCollisions ); } } return nextCollisionTime; } }
{ "content_hash": "9824e06caf53eeb2c3d833a09c939ddb", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 89, "avg_line_length": 37.75776397515528, "alnum_prop": 0.5543674946537259, "repo_name": "Glank/PACGameDev", "id": "6f82515e724bef4d5c2f8d420f661fbe28eb5f73", "size": "6079", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "org/pac/games/physics/CollisionGrid.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2972" }, { "name": "HTML", "bytes": "42353" }, { "name": "Java", "bytes": "65561" }, { "name": "Makefile", "bytes": "994" }, { "name": "Shell", "bytes": "88" } ], "symlink_target": "" }
package com.lovecws.mumu.data.car.service; import com.lovecws.mumu.data.car.entity.DataCarAttribute; import java.util.List; import java.util.Map; public interface DataCarAttributeService { /** ========app后台接口======= */ /** * 添加汽车配置信息 */ public void addSystemCarAttr(DataCarAttribute carAttribute); /** * 车型是否已经存在 * * @param id * @return */ public boolean idIsExist(String id); /** * 获取车系所属的所有车型的图片及图片数量(外观、中控、座椅、细节) * @param parentId * @return */ public List<DataCarAttribute> getSystemCarAttrImages(String parentId); /** ========web后台接口======= */ /** * 获取车型的配置信息 * * @param id * @param from * basic:基本信息,body:车体,engine:发动机,gearbox:变速箱,chassisbrake:底盘制动,safe:安全配置,wheel:车轮,drivingauxiliary:行车辅助,doormirror:门窗/后视镜,light:灯光,internalconfig:内部配置,seat:车座,entcom:娱乐通讯,aircondrefrigerator:空调/冰箱,actualtest:实际测试,facade:外观图片,interior:内饰图片,space:空间图片,diagram:图解图片,official:官方图片 * @return */ public Map<String, Object> getSystemCarAttrById(String id, String from); /** * 修改车型配置信息 * * @param systemCarAttrEntity * @return */ public boolean updateSystemCarAttr(DataCarAttribute systemCarAttrEntity); /** * 删除车型配置信息 * @param id * @return */ public boolean deleteSystemCarAttr(String id); public DataCarAttribute getDataCarAttributeById(String id); }
{ "content_hash": "5691a0740cc41e7df620e5c26bad90df", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 288, "avg_line_length": 22.96551724137931, "alnum_prop": 0.7004504504504504, "repo_name": "babymm/mumu", "id": "bf2e8011ab5cc7b88c6cff5dd23a7e6d17ae4e45", "size": "1714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mumu-data/mumu-data-api/src/main/java/com/lovecws/mumu/data/car/service/DataCarAttributeService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "137891" }, { "name": "HTML", "bytes": "82463" }, { "name": "Java", "bytes": "1291798" }, { "name": "JavaScript", "bytes": "395955" } ], "symlink_target": "" }
<div class="navigate-instruction"> <div class="navigation-direction pull-left"> <span class="glyphicon" ng-class="navigate.step.turnIcon"></span> </div> <div class="navigation-text"> <span class="navigate-mi">{{ navigate.step.distance | distance }} </span> <span class="navigate-min">({{ navigate.step.time }})</span> <p class="navigation-directions">{{ navigate.step.text }} <span ng-show="navigate.step.images.length" ng-repeat="imageSrc in navigate.step.images"> <img class="navigation-icon" ng-src="{{ imageSrc }}" /> </span> </p> </div> </div> <leaflet class="content map map-navigate" bounds="navigate.map.bounds" center="navigate.map.center" layers="navigate.map.layers" markers="navigate.map.markers" geojson="navigate.map.geojson"> </leaflet> <footer class="container-fluid"> <nav class="row row-temporary"> <div class="btn-group-nav btn-group-justified btn-group-temporary"> <a ng-click="navigate.offCourse()" type="button" class="btn btn-primary btn-block">Off-Course</a> <a ng-click="navigate.nextStep()" type="button" class="btn btn-primary btn-block">Next Step</a> </div> </nav> <nav class="row"> <div class="btn-group-nav btn-group-justified"> <a ng-click="navigate.footer.left.onClick()" type="button" class="btn btn-primary btn-block">{{ navigate.footer.left.text }}</a> <a ng-click="navigate.footer.right.onClick()" type="button" class="btn btn-primary btn-block">{{ navigate.footer.right.text }}</a> </div> </nav> </footer>
{ "content_hash": "753c3b5801a59fd5bd22e448ea23ed38", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 142, "avg_line_length": 45.45945945945946, "alnum_prop": 0.6159334126040428, "repo_name": "azavea/nih-wayfinding", "id": "0cc722f7113b9d295e88e6bf162018edf4f8d30e", "size": "1682", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/nih_wayfinding/app/scripts/views/navigate/navigate-partial.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "42138" }, { "name": "HTML", "bytes": "36483" }, { "name": "JavaScript", "bytes": "230252" } ], "symlink_target": "" }
"use strict"; var EOL = require( "os" ).EOL, expect = require( "chai" ).expect, fs = require( "fs" ), utils = require( "../utils.js" ), TargetHTML = require( "../../lib/private/TargetHTML.js" ); describe( "private / TargetHTML <更新対象のHTMLファイルを操作するクラス>", function(){ var testHTMLFilePath = "./.tmp/utf8/htdocs/index.html"; beforeEach( utils.prepareSampleFiles ); after( utils.deleteSampleFiles ); describe( "Constructor( path )", function(){ it( "管理対象のHTMLファイルの格納場所を、引数pathで受け取る。", function(){ var targetHTML = new TargetHTML( testHTMLFilePath ); expect( targetHTML.path ).to.equal( testHTMLFilePath ); } ); } ); describe( "init()", function(){ it( "管理対象のHTMLファイルを読み込み、内部の変数に格納する。", function( done ){ var targetHTML = new TargetHTML( testHTMLFilePath ); targetHTML.init().done( function(){ expect( targetHTML.srcHTMLCode ).to.contain( "<!doctype html>" ); done(); } ); } ); } ); describe( "update( HTMLCode )", function(){ it( "与えられたHTMLCodeで、対象のHTMLファイルの内容を更新する。", function( done ){ var testHTMLCode = "<dummy></dummy>", targetHTML = new TargetHTML( testHTMLFilePath ); targetHTML.update( testHTMLCode ).done( function(){ expect( fs.readFileSync( testHTMLFilePath, "utf-8" ) ).to.equal( testHTMLCode ); done(); } ); } ); } ); describe( "detectTemplateId()", function(){ var targetHTML; before( function( done ){ utils.prepareSampleFiles(); targetHTML = new TargetHTML( testHTMLFilePath ); targetHTML.init().done( function(){ done(); } ); } ); it( "関連付けされたテンプレートのIDを返却する。", function(){ expect( targetHTML.detectTemplateId() ).to.equal( "Templates/base.tmpl" ); } ); } ); describe( "pickOutValues()", function(){ var targetHTML, values; before( function( done ){ utils.prepareSampleFiles(); targetHTML = new TargetHTML( testHTMLFilePath ); targetHTML.init().done( function(){ values = targetHTML.pickOutValues(); done(); } ); } ); describe( "管理対象のHTMLファイルから、テンプレートへの適用対象となる内容を抽出し、オブジェクトとして返却する。", function(){ it( "返却値は、オブジェクトである。", function(){ expect( values ).to.be.an( "object" ); } ); it( "<!-- InstanceBegin template -->の属性", function(){ expect( values.__template_attr__ ).to.equal( ' test_attr="test"' ); } ); it( "InstanceEditable", function(){ expect( values.main ).to.contain( "<h1>/index.html</h1>" ); expect( values.main.split( EOL ) ).to.have.length( 7 ); } ); } ); describe( "各種の文字列", function(){ it( "日本語の文字列も、そのまま抽出できる。", function(){ expect( values.main ).to.contain( "<p>ノン・アスキーの文字列</p>" ); } ); it( "特殊文字も、そのまま抽出できる。", function(){ expect( values.main ).to.contain( "<p>&copy;&amp;&trade;</p>" ); } ); it( "<!-- comment -->", function(){ expect( values.main ).to.contain( "<!-- comment -->" ); } ); it( "&lt;!-- not comment --&gt;", function(){ expect( values.main ).to.contain( "&lt;!-- not comment --&gt;" ); } ); } ); } ); describe( "activateInstanceTags( HTMLCode )", function(){ var activateTemplateTags = TargetHTML.prototype.activateInstanceTags; it( "InstanceBeginEditable -> <InstanceEditable>", function(){ expect( activateTemplateTags( "<!-- InstanceBeginEditable name=\"main\" --><!-- InstanceBeginEditable name=\"sub\" -->" ) ) .to.equal( "<InstanceEditable name=\"main\"><InstanceEditable name=\"sub\">" ); } ); it( "InstanceEndEditable -> </InstanceEditable>", function(){ expect( activateTemplateTags( "<!-- InstanceEndEditable --><!-- InstanceEndEditable -->" ) ) .to.equal( "</InstanceEditable></InstanceEditable>" ); } ); } ); } );
{ "content_hash": "544e4434a845362b49a6ce301e066f2a", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 135, "avg_line_length": 34.56, "alnum_prop": 0.5261574074074075, "repo_name": "daikiueda/htmlcommenttemplate", "id": "6a2cc49d09e34829e05dca4da9f5f8b31d7bd390", "size": "4780", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/private/TargetHTML.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "66" }, { "name": "HTML", "bytes": "290" }, { "name": "JavaScript", "bytes": "59377" } ], "symlink_target": "" }
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("zerver", "0203_realm_message_content_allowed_in_email_notifications"), ] operations = [ migrations.RemoveField( model_name="realm", name="has_seat_based_plan", ), migrations.RemoveField( model_name="realm", name="seat_limit", ), ]
{ "content_hash": "c75f890a3db353632c176e9fe77a96df", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 80, "avg_line_length": 22.63157894736842, "alnum_prop": 0.5627906976744186, "repo_name": "andersk/zulip", "id": "98da63f4dbfdb70868228745440e98405faeab43", "size": "481", "binary": false, "copies": "8", "ref": "refs/heads/main", "path": "zerver/migrations/0204_remove_realm_billing_fields.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "490256" }, { "name": "Dockerfile", "bytes": "4025" }, { "name": "Emacs Lisp", "bytes": "157" }, { "name": "HTML", "bytes": "749848" }, { "name": "Handlebars", "bytes": "377098" }, { "name": "JavaScript", "bytes": "4006373" }, { "name": "Perl", "bytes": "10163" }, { "name": "Puppet", "bytes": "112128" }, { "name": "Python", "bytes": "10168530" }, { "name": "Ruby", "bytes": "3459" }, { "name": "Shell", "bytes": "146797" }, { "name": "TypeScript", "bytes": "284837" } ], "symlink_target": "" }
#ifndef __SNMP_COMMON_H__ #define __SNMP_COMMON_H__ #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <net/if_arp.h> #include "lagopus_apis.h" // expected only MAC address #define PHYSADDRESS_MAXLEN 6 /* Typical data structure for a row entry (auto generated by the 'iterate' template)*/ struct ifTable_entry { /* Index values */ int32_t ifIndex; /* Column values */ char ifDescr[IFNAMSIZ + 1]; size_t ifDescr_len; int32_t ifType; int32_t ifMtu; uint32_t ifSpeed; char ifPhysAddress[PHYSADDRESS_MAXLEN]; size_t ifPhysAddress_len; int32_t ifAdminStatus; int32_t old_ifAdminStatus; int32_t ifOperStatus; uint32_t ifLastChange; uint32_t ifInOctets; uint32_t ifInUcastPkts; uint32_t ifInNUcastPkts; uint32_t ifInDiscards; uint32_t ifInErrors; uint32_t ifInUnknownProtos; uint32_t ifOutOctets; uint32_t ifOutUcastPkts; uint32_t ifOutNUcastPkts; uint32_t ifOutDiscards; uint32_t ifOutErrors; uint32_t ifOutQLen; /* for Bridge MIB */ int32_t dot1dBasePortIfIndex; /* TODO set a valid value if needed */ /* oid dot1dBasePortCircuit[10]; */ /* size_t dot1dBasePortCircuit_len; */ uint32_t dot1dBasePortDelayExceededDiscards; uint32_t dot1dBasePortMtuExceededDiscards; }; #endif /* ! __SNMP_COMMON_H__ */
{ "content_hash": "d6fb5731caddbec43467d1cbce466956", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 47, "avg_line_length": 23.20689655172414, "alnum_prop": 0.7161961367013373, "repo_name": "lagopus/lagopus", "id": "d57cd4736d1d64a8ea5e03bb1f3ecc4f04c4d4fc", "size": "1975", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/snmp/ifTable_type.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "9818181" }, { "name": "C++", "bytes": "59091" }, { "name": "Lex", "bytes": "644" }, { "name": "M4", "bytes": "19365" }, { "name": "Makefile", "bytes": "45909" }, { "name": "Objective-C", "bytes": "105221" }, { "name": "Python", "bytes": "264408" }, { "name": "Ruby", "bytes": "7077" }, { "name": "Shell", "bytes": "364911" }, { "name": "Yacc", "bytes": "3875" } ], "symlink_target": "" }
package cz.zcu.fav.remotestimulatorcontrol.model.media; import android.databinding.BaseObservable; import android.databinding.Bindable; import android.graphics.Bitmap; import android.os.Parcel; import android.os.Parcelable; import java.io.File; import cz.zcu.fav.remotestimulatorcontrol.BR; import cz.zcu.fav.remotestimulatorcontrol.model.configuration.MediaType; /** * Abstraktní třída média konfigurace */ public abstract class AMedia extends BaseObservable implements Parcelable { // region Constants public static final int THUMBNAIL_SIZE = 75; // endregion // region Variables // Soubor s médiem protected File mMediaFile; // Název média @Bindable protected String mName; // Thumbnail @Bindable protected Bitmap thumbnail; // Přiznak pro audio médium, zda-li se má zobrazit přehrávací ikona @Bindable protected boolean showPlayingIcon = false; // endregion // region Constructors /** * Konstruktor třídy {@link AMedia} * * @param mediaFile Soubor s médiem * @param name Název média */ public AMedia(File mediaFile, String name) { mMediaFile = mediaFile; mName = name; } // endregion /** * Vrátí typ média * * @return Typ média */ public abstract MediaType getMediaType(); // region Public methods /** * Vrátí ikonu média * * @return Ikonu média */ public Bitmap getThumbnail() { return thumbnail; } /** * Nastaví ikonu média * * @param thumbnail Ikona */ public void setThumbnail(Bitmap thumbnail) { this.thumbnail = thumbnail; notifyPropertyChanged(BR.thumbnail); } /** * Vrátí název média * * @return Název média */ public String getName() { return mName; } /** * Vrátí soubor, kde se nachází médium * * @return Soubor */ public File getMediaFile() { return mMediaFile; } /** * Zjistí, zda-li se má zobrazit ikona indikující přehrávání * * @return True, pokud se má ikona zobrazit, jinak false */ public boolean isShowPlayingIcon() { return showPlayingIcon; } /** * Nastaví, zda-li se má zobrazit ikona indikující přehrávání * * @param showPlayingIcon True, pro zobrazení, jinak false */ public void setShowPlayingIcon(boolean showPlayingIcon) { this.showPlayingIcon = showPlayingIcon; notifyPropertyChanged(BR.showPlayingIcon); } // endregion @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AMedia aMedia = (AMedia) o; return mName.equals(aMedia.mName); } @Override public int hashCode() { return mName.hashCode(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.mMediaFile.getAbsolutePath()); dest.writeString(this.mName); } protected AMedia(Parcel in) { this.mMediaFile = new File(in.readString()); this.mName = in.readString(); } }
{ "content_hash": "23c7702a344d95950937b201af0a2f3a", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 75, "avg_line_length": 22.568493150684933, "alnum_prop": 0.6251896813353566, "repo_name": "stechy1/Remote-stimulator-control", "id": "7607e74221f37c55a8ac8f0143cbf220012f68f4", "size": "3352", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/cz/zcu/fav/remotestimulatorcontrol/model/media/AMedia.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "654310" } ], "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("CupCakeHeaven")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CupCakeHeaven")] [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("731f5843-4949-4e8f-8956-7bedcb1846b6")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "7403f20ccf2e609cb639e173d31802a1", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 38.68571428571428, "alnum_prop": 0.7518463810930576, "repo_name": "wulfland/DemoShop", "id": "f6c0cc14a842ef06b265e2364a9226c3c5e84c29", "size": "1357", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/CupCakeHeaven/CupCakeHeaven/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "107" }, { "name": "C#", "bytes": "160284" }, { "name": "CSS", "bytes": "2626" }, { "name": "HTML", "bytes": "17848" }, { "name": "JavaScript", "bytes": "10318" }, { "name": "PowerShell", "bytes": "6801" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe Branch do let(:branch) { create :branch } describe 'FactoryGirl' do describe 'normalize' do subject! { branch } it { expect(subject).not_to be_new_record } end end end
{ "content_hash": "a250a009246faa7a851e7fb24f52e00f", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 49, "avg_line_length": 19.5, "alnum_prop": 0.6538461538461539, "repo_name": "JRF-tw/sunshine.jrf.org.tw", "id": "ef6cff5729372d5ca86c1e3e4358033dc4570188", "size": "577", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "spec/models/branch_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "240019" }, { "name": "CoffeeScript", "bytes": "19683" }, { "name": "HTML", "bytes": "289894" }, { "name": "JavaScript", "bytes": "437338" }, { "name": "Ruby", "bytes": "1184957" } ], "symlink_target": "" }
<?php namespace MNS\Responses; use MNS\Constants; use MNS\Exception\MnsException; use MNS\Exception\QueueNotExistException; use MNS\Exception\MessageNotExistException; use MNS\Responses\BaseResponse; use MNS\Common\XMLParser; use MNS\Model\Message; class BatchReceiveMessageResponse extends BaseResponse { protected $messages; // boolean, whether the message body will be decoded as base64 protected $base64; public function __construct($base64 = TRUE) { $this->messages = array(); $this->base64 = $base64; } public function setBase64($base64) { $this->base64 = $base64; } public function isBase64() { return ($this->base64 == TRUE); } public function getMessages() { return $this->messages; } public function parseResponse($statusCode, $content) { $this->statusCode = $statusCode; if ($statusCode == 200) { $this->succeed = TRUE; } else { $this->parseErrorResponse($statusCode, $content); } $xmlReader = $this->loadXmlContent($content); try { while ($xmlReader->read()) { if ($xmlReader->nodeType == \XMLReader::ELEMENT && $xmlReader->name == 'Message') { $this->messages[] = Message::fromXML($xmlReader, $this->base64); } } } catch (\Exception $e) { throw new MnsException($statusCode, $e->getMessage(), $e); } catch (\Throwable $t) { throw new MnsException($statusCode, $t->getMessage()); } } public function parseErrorResponse($statusCode, $content, MnsException $exception = NULL) { $this->succeed = FALSE; $xmlReader = $this->loadXmlContent($content); try { $result = XMLParser::parseNormalError($xmlReader); if ($result['Code'] == Constants::QUEUE_NOT_EXIST) { throw new QueueNotExistException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']); } if ($result['Code'] == Constants::MESSAGE_NOT_EXIST) { throw new MessageNotExistException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']); } throw new MnsException($statusCode, $result['Message'], $exception, $result['Code'], $result['RequestId'], $result['HostId']); } catch (\Exception $e) { if ($exception != NULL) { throw $exception; } elseif($e instanceof MnsException) { throw $e; } else { throw new MnsException($statusCode, $e->getMessage()); } } catch (\Throwable $t) { throw new MnsException($statusCode, $t->getMessage()); } } } ?>
{ "content_hash": "9abf1e953eecb2f3825fbfd6393c3a86", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 154, "avg_line_length": 30.316326530612244, "alnum_prop": 0.5557051497812184, "repo_name": "ifintech/phplib", "id": "d1f748155de3a12c7062af95179558ed841fdfe0", "size": "2971", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ext/Aliyun/MNS/Responses/BatchReceiveMessageResponse.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "108359" }, { "name": "PHP", "bytes": "8092651" } ], "symlink_target": "" }
package parser import "github.com/pkg/errors" type normalizableExpr interface { Expr normalize(*normalizeVisitor) TypedExpr } func (expr *CastExpr) normalize(v *normalizeVisitor) TypedExpr { if expr.Expr == DNull { return DNull } return expr } func (expr *CoalesceExpr) normalize(v *normalizeVisitor) TypedExpr { // This normalization checks whether COALESCE can be simplified // based on constant expressions at the start of the COALESCE // argument list. All known-null constant arguments are simply // removed, and any known-nonnull constant argument before // non-constant argument cause the entire COALESCE expression to // collapse to that argument. last := len(expr.Exprs) - 1 for i := range expr.Exprs { subExpr := expr.TypedExprAt(i) if i == last { return subExpr } if !v.isConst(subExpr) { exprCopy := *expr exprCopy.Exprs = expr.Exprs[i:] return &exprCopy } val, err := subExpr.Eval(v.ctx) if err != nil { v.err = err return expr } if val != DNull { return subExpr } } return expr } func (expr *IfExpr) normalize(v *normalizeVisitor) TypedExpr { if v.isConst(expr.Cond) { cond, err := expr.TypedCondExpr().Eval(v.ctx) if err != nil { v.err = err return expr } if d, err := GetBool(cond); err == nil { if d { return expr.TypedTrueExpr() } return expr.TypedElseExpr() } return DNull } return expr } func (expr *UnaryExpr) normalize(v *normalizeVisitor) TypedExpr { val := expr.TypedInnerExpr() if val == DNull { return val } switch expr.Operator { case UnaryPlus: // +a -> a return val case UnaryMinus: // -0 -> 0 (except for float which has negative zero) if !val.ReturnType().TypeEqual(TypeFloat) && IsNumericZero(val) { return val } switch b := val.(type) { // -(a - b) -> (b - a) case *BinaryExpr: if b.Operator == Minus { newBinExpr := newBinExprIfValidOverload(Minus, b.TypedRight(), b.TypedLeft()) if newBinExpr != nil { newBinExpr.memoizeFn() b = newBinExpr } return b } // - (- a) -> a case *UnaryExpr: if b.Operator == UnaryMinus { return b.TypedInnerExpr() } } } return expr } func (expr *BinaryExpr) normalize(v *normalizeVisitor) TypedExpr { left := expr.TypedLeft() right := expr.TypedRight() expectedType := expr.ReturnType() if left == DNull || right == DNull { return DNull } var final TypedExpr switch expr.Operator { case Plus: if IsNumericZero(right) { final, v.err = ReType(left, expectedType) break } if IsNumericZero(left) { final, v.err = ReType(right, expectedType) break } case Minus: if IsNumericZero(right) { final, v.err = ReType(left, expectedType) break } case Mult: if IsNumericOne(right) { final, v.err = ReType(left, expectedType) break } if IsNumericOne(left) { final, v.err = ReType(right, expectedType) break } // We can't simplify multiplication by zero to zero, // because if the other operand is NULL during evaluation // the result must be NULL. case Div, FloorDiv: if IsNumericOne(right) { final, v.err = ReType(left, expectedType) break } } if final == nil { return expr } return final } func (expr *AndExpr) normalize(v *normalizeVisitor) TypedExpr { left := expr.TypedLeft() right := expr.TypedRight() var dleft, dright Datum if left == DNull && right == DNull { return DNull } // Use short-circuit evaluation to simplify AND expressions. if v.isConst(left) { dleft, v.err = left.Eval(v.ctx) if v.err != nil { return expr } if dleft != DNull { if d, err := GetBool(dleft); err == nil { if !d { return dleft } return right } return DNull } return NewTypedAndExpr( dleft, right, ) } if v.isConst(right) { dright, v.err = right.Eval(v.ctx) if v.err != nil { return expr } if dright != DNull { if d, err := GetBool(dright); err == nil { if !d { return right } return left } return DNull } return NewTypedAndExpr( left, dright, ) } return expr } func (expr *ComparisonExpr) normalize(v *normalizeVisitor) TypedExpr { switch expr.Operator { case EQ, GE, GT, LE, LT: // We want var nodes (VariableExpr, QualifiedName, etc) to be immediate // children of the comparison expression and not second or third // children. That is, we want trees that look like: // // cmp cmp // / \ / \ // a op op a // / \ / \ // 1 2 1 2 // // Not trees that look like: // // cmp cmp cmp cmp // / \ / \ / \ / \ // op 2 op 2 1 op 1 op // / \ / \ / \ / \ // a 1 1 a a 2 2 a // // We loop attempting to simplify the comparison expression. As a // pre-condition, we know there is at least one variable in the expression // tree or we would not have entered this code path. exprCopied := false for { if expr.TypedLeft() == DNull || expr.TypedRight() == DNull { return DNull } if v.isConst(expr.Left) { switch expr.Right.(type) { case *BinaryExpr, VariableExpr: break default: return expr } invertedOp, err := invertComparisonOp(expr.Operator) if err != nil { v.err = nil return expr } // The left side is const and the right side is a binary expression or a // variable. Flip the comparison op so that the right side is const and // the left side is a binary expression or variable. // Create a new ComparisonExpr so the function cache isn't reused. if !exprCopied { exprCopy := *expr expr = &exprCopy exprCopied = true } expr = NewTypedComparisonExpr(invertedOp, expr.TypedRight(), expr.TypedLeft()) } else if !v.isConst(expr.Right) { return expr } left, ok := expr.Left.(*BinaryExpr) if !ok { return expr } // The right is const and the left side is a binary expression. Rotate the // comparison combining portions that are const. switch { case v.isConst(left.Right) && (left.Operator == Plus || left.Operator == Minus || left.Operator == Div): // cmp cmp // / \ / \ // [+-/] 2 -> a [-+*] // / \ / \ // a 1 2 1 var op BinaryOperator switch left.Operator { case Plus: op = Minus case Minus: op = Plus case Div: op = Mult } newBinExpr := newBinExprIfValidOverload(op, expr.TypedRight(), left.TypedRight()) if newBinExpr == nil { // Substitution is not possible type-wise. Nothing else to do. break } if !exprCopied { exprCopy := *expr expr = &exprCopy exprCopied = true } expr.Left = left.Left expr.Right, v.err = newBinExpr.Eval(v.ctx) if v.err != nil { return expr } expr.memoizeFn() if !isVar(expr.Left) { // Continue as long as the left side of the comparison is not a // variable. continue } case v.isConst(left.Left) && (left.Operator == Plus || left.Operator == Minus): // cmp cmp // / \ / \ // [+-] 2 -> [+-] a // / \ / \ // 1 a 1 2 op := expr.Operator var newBinExpr *BinaryExpr switch left.Operator { case Plus: // // (A + X) cmp B => X cmp (B - C) // newBinExpr = newBinExprIfValidOverload(Minus, expr.TypedRight(), left.TypedLeft()) case Minus: // // (A - X) cmp B => X cmp' (A - B) // newBinExpr = newBinExprIfValidOverload(Minus, left.TypedLeft(), expr.TypedRight()) op, v.err = invertComparisonOp(op) if v.err != nil { return expr } } if newBinExpr == nil { break } if !exprCopied { exprCopy := *expr expr = &exprCopy exprCopied = true } expr.Operator = op expr.Left = left.Right expr.Right, v.err = newBinExpr.Eval(v.ctx) if v.err != nil { return nil } expr.memoizeFn() if !isVar(expr.Left) { // Continue as long as the left side of the comparison is not a // variable. continue } } // We've run out of work to do. break } case In, NotIn: if expr.TypedLeft() == DNull { return DNull } // If the right tuple in an In or NotIn comparison expression is constant, it can // be normalized. tuple, ok := expr.Right.(*DTuple) if ok { tupleCopy := *tuple tupleCopy.Normalize() exprCopy := *expr expr = &exprCopy expr.Right = &tupleCopy } case NE, Like, NotLike, ILike, NotILike, SimilarTo, NotSimilarTo, RegMatch, NotRegMatch, RegIMatch, NotRegIMatch: if expr.TypedLeft() == DNull || expr.TypedRight() == DNull { return DNull } } return expr } func (expr *OrExpr) normalize(v *normalizeVisitor) TypedExpr { left := expr.TypedLeft() right := expr.TypedRight() var dleft, dright Datum if left == DNull && right == DNull { return DNull } // Use short-circuit evaluation to simplify OR expressions. if v.isConst(left) { dleft, v.err = left.Eval(v.ctx) if v.err != nil { return expr } if dleft != DNull { if d, err := GetBool(dleft); err == nil { if d { return dleft } return right } return DNull } return NewTypedOrExpr( dleft, right, ) } if v.isConst(right) { dright, v.err = right.Eval(v.ctx) if v.err != nil { return expr } if dright != DNull { if d, err := GetBool(dright); err == nil { if d { return right } return left } return DNull } return NewTypedOrExpr( left, dright, ) } return expr } func (expr *ParenExpr) normalize(v *normalizeVisitor) TypedExpr { newExpr := expr.TypedInnerExpr() if normalizeable, ok := newExpr.(normalizableExpr); ok { newExpr = normalizeable.normalize(v) if v.err != nil { return expr } } return newExpr } func (expr *AnnotateTypeExpr) normalize(v *normalizeVisitor) TypedExpr { // Type annotations have no runtime effect, so they can be removed after // semantic analysis. return expr.TypedInnerExpr() } func (expr *RangeCond) normalize(v *normalizeVisitor) TypedExpr { left, from, to := expr.TypedLeft(), expr.TypedFrom(), expr.TypedTo() if left == DNull || from == DNull || to == DNull { return DNull } if expr.Not { // "a NOT BETWEEN b AND c" -> "a < b OR a > c" newLeft := NewTypedComparisonExpr(LT, left, from).normalize(v) if v.err != nil { return expr } newRight := NewTypedComparisonExpr(GT, left, to).normalize(v) if v.err != nil { return expr } return NewTypedOrExpr(newLeft, newRight).normalize(v) } // "a BETWEEN b AND c" -> "a >= b AND a <= c" newLeft := NewTypedComparisonExpr(GE, left, from).normalize(v) if v.err != nil { return expr } newRight := NewTypedComparisonExpr(LE, left, to).normalize(v) if v.err != nil { return expr } return NewTypedAndExpr(newLeft, newRight).normalize(v) } // NormalizeExpr normalizes a typed expression, simplifying where possible, // but guaranteeing that the result of evaluating the expression is // unchanged and that resulting expression tree is still well-typed. // Example normalizations: // // (a) -> a // a = 1 + 1 -> a = 2 // a + 1 = 2 -> a = 1 // a BETWEEN b AND c -> (a >= b) AND (a <= c) // a NOT BETWEEN b AND c -> (a < b) OR (a > c) func (ctx *EvalContext) NormalizeExpr(typedExpr TypedExpr) (TypedExpr, error) { v := normalizeVisitor{ctx: ctx} expr, _ := WalkExpr(&v, typedExpr) if v.err != nil { return nil, v.err } return expr.(TypedExpr), nil } type normalizeVisitor struct { ctx *EvalContext err error isConstVisitor isConstVisitor } var _ Visitor = &normalizeVisitor{} func (v *normalizeVisitor) VisitPre(expr Expr) (recurse bool, newExpr Expr) { if v.err != nil { return false, expr } switch expr.(type) { case *Subquery: // Avoid normalizing subqueries. We need the subquery to be expanded in // order to do so properly. // TODO(knz) This should happen when the prepare and execute phases are // separated for SelectClause. return false, expr } return true, expr } func (v *normalizeVisitor) VisitPost(expr Expr) Expr { if v.err != nil { return expr } // Normalize expressions that know how to normalize themselves. if normalizeable, ok := expr.(normalizableExpr); ok { expr = normalizeable.normalize(v) if v.err != nil { return expr } } // Evaluate all constant expressions. if v.isConst(expr) { newExpr, err := expr.(TypedExpr).Eval(v.ctx) if err != nil { return expr } expr = newExpr } return expr } func (v *normalizeVisitor) isConst(expr Expr) bool { return v.isConstVisitor.run(expr) } func invertComparisonOp(op ComparisonOperator) (ComparisonOperator, error) { switch op { case EQ: return EQ, nil case GE: return LE, nil case GT: return LT, nil case LE: return GE, nil case LT: return GT, nil default: return op, errors.Errorf("internal error: unable to invert: %s", op) } } type isConstVisitor struct { isConst bool } var _ Visitor = &isConstVisitor{} func (v *isConstVisitor) VisitPre(expr Expr) (recurse bool, newExpr Expr) { if v.isConst { if isVar(expr) { v.isConst = false return false, expr } switch t := expr.(type) { case *FuncExpr: if t.fn.impure { v.isConst = false return false, expr } } } return true, expr } func (*isConstVisitor) VisitPost(expr Expr) Expr { return expr } func (v *isConstVisitor) run(expr Expr) bool { v.isConst = true WalkExprConst(v, expr) return v.isConst } func isVar(expr Expr) bool { _, ok := expr.(VariableExpr) return ok } type containsVarsVisitor struct { containsVars bool } var _ Visitor = &containsVarsVisitor{} func (v *containsVarsVisitor) VisitPre(expr Expr) (recurse bool, newExpr Expr) { if !v.containsVars && isVar(expr) { v.containsVars = true } if v.containsVars { return false, expr } return true, expr } func (*containsVarsVisitor) VisitPost(expr Expr) Expr { return expr } // ContainsVars returns true if the expression contains any variables. func ContainsVars(expr Expr) bool { v := containsVarsVisitor{containsVars: false} WalkExprConst(&v, expr) return v.containsVars } // DecimalZero represents the constant 0 as DECIMAL. var DecimalZero DDecimal // DecimalOne represents the constant 1 as DECIMAL. var DecimalOne DDecimal func init() { DecimalOne.Dec.SetUnscaled(1).SetScale(0) DecimalZero.Dec.SetUnscaled(0).SetScale(0) } // IsNumericZero returns true if the datum is a number and equal to // zero. func IsNumericZero(expr TypedExpr) bool { if d, ok := expr.(Datum); ok { switch t := d.(type) { case *DDecimal: return t.Dec.Cmp(&DecimalZero.Dec) == 0 case *DFloat: return *t == 0 case *DInt: return *t == 0 } } return false } // IsNumericOne returns true if the datum is a number and equal to // one. func IsNumericOne(expr TypedExpr) bool { if d, ok := expr.(Datum); ok { switch t := d.(type) { case *DDecimal: return t.Dec.Cmp(&DecimalOne.Dec) == 0 case *DFloat: return *t == 1.0 case *DInt: return *t == 1 } } return false } // ReType ensures that the given numeric expression evaluates // to the requested type, inserting a cast if necessary. func ReType(expr TypedExpr, wantedType Datum) (TypedExpr, error) { if expr.ReturnType().TypeEqual(wantedType) { return expr, nil } reqType, err := DatumTypeToColumnType(wantedType) if err != nil { return nil, err } res := &CastExpr{Expr: expr, Type: reqType} res.typ = wantedType return res, nil }
{ "content_hash": "e89db45f9205cfd262647a159b5d02c4", "timestamp": "", "source": "github", "line_count": 715, "max_line_length": 83, "avg_line_length": 22.142657342657344, "alnum_prop": 0.6210838807478525, "repo_name": "vivekmenezes/cockroach", "id": "e0af4cc9b1f60e43ef730dce8afdc7f124e2a594", "size": "16485", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sql/parser/normalize.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1029" }, { "name": "C", "bytes": "8865" }, { "name": "C++", "bytes": "78110" }, { "name": "CSS", "bytes": "34505" }, { "name": "Go", "bytes": "7739607" }, { "name": "HCL", "bytes": "34987" }, { "name": "HTML", "bytes": "18016" }, { "name": "JavaScript", "bytes": "273005" }, { "name": "Makefile", "bytes": "19082" }, { "name": "Protocol Buffer", "bytes": "216449" }, { "name": "Ruby", "bytes": "2554" }, { "name": "Shell", "bytes": "46243" }, { "name": "Smarty", "bytes": "4831" }, { "name": "Tcl", "bytes": "17987" }, { "name": "TypeScript", "bytes": "286322" }, { "name": "Vim script", "bytes": "1650" }, { "name": "Yacc", "bytes": "123215" } ], "symlink_target": "" }
function is_touch_device() { return 'ontouchstart' in window // works on most browsers || navigator.maxTouchPoints; // works on IE10/11 and Surface }; function replace_iframe_sizes(w,h){ var $iframe = $('#fb-inline-content iframe:first'); if ($iframe.length == 1){ $iframe.attr('width', w); $iframe.attr('height', h); } } $(document).on("ready page:change", function() { if ($(".fb-image").length > 0 || $(".fb-inline").length > 0){ var fitView = false; if($('.story-wrapper .fb-image.fit-view').length) { fitView = true; } $(".fb-image").fancybox({parent: 'body', fitToView: fitView, padding: 0}); var options = {parent: 'body', padding: 0}; $inline = $(".fb-inline"); if ($inline.length > 0){ var w = $(window).width()-10; var h = $(window).height()-10; $inline.each(function(){ var $t = $(this); switch($t.data('type')){ case 'radio': options.minWidth = w > 500 ? 500 : w; break; default: //fullscreen options.minWidth = w; options.minHeight = h; replace_iframe_sizes(w,h); break; } $t.fancybox(options); }); } } });
{ "content_hash": "c3481a88b86c3cb8dfbb68f51c8c50fc", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 78, "avg_line_length": 28.431818181818183, "alnum_prop": 0.5251798561151079, "repo_name": "JumpStartGeorgia/Air-Pollution", "id": "124466156a2dd174c4530ba28629fcaa44adc2d4", "size": "1251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/assets/javascripts/application/story.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "38546" }, { "name": "HTML", "bytes": "88465" }, { "name": "JavaScript", "bytes": "64678" }, { "name": "Ruby", "bytes": "231250" } ], "symlink_target": "" }
package demo.thrift; import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.thrift.transport.TSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GenericConnectionProvider { private static final Logger logger = LoggerFactory .getLogger(GenericConnectionProvider.class); /** 服务的IP地址 */ private String serviceIP; /** 服务的端口 */ private int servicePort; public String getServiceIP() { return serviceIP; } public void setServiceIP(String serviceIP) { this.serviceIP = serviceIP; } public int getServicePort() { return servicePort; } public void setServicePort(int servicePort) { this.servicePort = servicePort; } public int getConTimeOut() { return conTimeOut; } public void setConTimeOut(int conTimeOut) { this.conTimeOut = conTimeOut; } public int getMaxActive() { return maxActive; } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } public int getMaxIdle() { return maxIdle; } public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } public int getMinIdle() { return minIdle; } public void setMinIdle(int minIdle) { this.minIdle = minIdle; } public long getMaxWait() { return maxWait; } public void setMaxWait(long maxWait) { this.maxWait = maxWait; } /** 连接超时配置 */ private int conTimeOut; /** 可以从缓存池中分配对象的最大数量 */ private int maxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE; /** 缓存池中最大空闲对象数量 */ private int maxIdle = GenericObjectPool.DEFAULT_MAX_IDLE; /** 缓存池中最小空闲对象数量 */ private int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE; /** 阻塞的最大数量 */ private long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT; /** 从缓存池中分配对象,是否执行PoolableObjectFactory.validateObject方法 */ private boolean testOnBorrow = true; private boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN; private boolean testWhileIdle = true; /** 对象缓存池 */ private GenericObjectPool objectPool = null; @SuppressWarnings("deprecation") public void init() { // 对象池 objectPool = new GenericObjectPool(); // objectPool.setMaxActive(maxActive); objectPool.setMaxIdle(maxIdle); objectPool.setMinIdle(minIdle); objectPool.setMaxWait(maxWait); objectPool.setTestOnBorrow(testOnBorrow); objectPool.setTestOnReturn(testOnReturn); objectPool.setTestWhileIdle(testWhileIdle); objectPool .setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); ThriftPoolableObjectFactory thriftPoolableObjectFactory = new ThriftPoolableObjectFactory( serviceIP, servicePort, conTimeOut); objectPool.setFactory(thriftPoolableObjectFactory); logger.debug("{}:{}的thrift连接池初始化完成", serviceIP, servicePort); } public void destroy() { try { objectPool.close(); } catch (Exception e) { logger.error("关闭thrift连接池异常", e); throw new RuntimeException("erorr destroy()", e); } } /** * 获取连接 * * @return */ public TSocket getConnection() { try { TSocket socket = (TSocket) objectPool.borrowObject(); return socket; } catch (Exception e) { throw new RuntimeException("error getConnection()", e); } } /** * 归还连接 * * @param socket */ public void returnCon(TSocket socket) { try { socket.close(); objectPool.invalidateObject(socket); //这里是因为在server重启后,不能自动重连,所以这里先不需要连接池了 // objectPool.returnObject(socket); } catch (Exception e) { throw new RuntimeException("error returnCon()", e); } } /** * 归还操作异常的连接 * @param socket */ public void returnBrokenCon(TSocket socket) { try { socket.close(); objectPool.invalidateObject(socket); } catch (Exception e) { throw new RuntimeException("error returnBrokenCon()", e); } } }
{ "content_hash": "ee1b2fb8ca88efa4885480cb10a6093f", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 92, "avg_line_length": 22.341463414634145, "alnum_prop": 0.7229803493449781, "repo_name": "SongYu-King/hello-github", "id": "b831197a4a9735f06fa49afc7e686770996ab8ae", "size": "3962", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/demo/thrift/GenericConnectionProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "333" } ], "symlink_target": "" }
package org.apache.servicecomb.foundation.vertx.metrics; import org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultServerEndpointMetric; import org.apache.servicecomb.foundation.vertx.metrics.metric.DefaultTcpSocketMetric; import io.vertx.core.net.SocketAddress; import io.vertx.core.spi.metrics.TCPMetrics; /** * important: not singleton, every NetServer instance relate to a TcpServerMetrics instance */ public class DefaultTcpServerMetrics implements TCPMetrics<DefaultTcpSocketMetric> { private final DefaultServerEndpointMetric endpointMetric; public DefaultTcpServerMetrics(DefaultServerEndpointMetric endpointMetric) { this.endpointMetric = endpointMetric; } public DefaultServerEndpointMetric getEndpointMetric() { return endpointMetric; } @Override public DefaultTcpSocketMetric connected(SocketAddress remoteAddress, String remoteName) { endpointMetric.onConnect(); return new DefaultTcpSocketMetric(endpointMetric); } @Override public void disconnected(DefaultTcpSocketMetric socketMetric, SocketAddress remoteAddress) { socketMetric.onDisconnect(); } @Override public void bytesRead(DefaultTcpSocketMetric socketMetric, SocketAddress remoteAddress, long numberOfBytes) { endpointMetric.addBytesRead(numberOfBytes); } @Override public void bytesWritten(DefaultTcpSocketMetric socketMetric, SocketAddress remoteAddress, long numberOfBytes) { endpointMetric.addBytesWritten(numberOfBytes); } @Override public void exceptionOccurred(DefaultTcpSocketMetric socketMetric, SocketAddress remoteAddress, Throwable t) { } @Override @Deprecated public boolean isEnabled() { return true; } @Override public void close() { } }
{ "content_hash": "e5e4c0d2129041dbf4319cbc63266050", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 114, "avg_line_length": 29, "alnum_prop": 0.8, "repo_name": "ServiceComb/java-chassis", "id": "a68c56f74b5bee2543c54550bd5312336fc2d49e", "size": "2541", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "foundations/foundation-vertx/src/main/java/org/apache/servicecomb/foundation/vertx/metrics/DefaultTcpServerMetrics.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2679862" }, { "name": "Protocol Buffer", "bytes": "359" }, { "name": "Python", "bytes": "1681" } ], "symlink_target": "" }
<section class="karmora-share-sec"> <div class="container"> <div class="row"> <div class="col-md-12 karmora-share-content text-center"> <h1 class="main-heading">Smokin Hot Deal Ads</h1> <span class="line-spc"></span> <div class="col-md-10 col-md-offset-1"> <?php // echo $description; ?> <?php if (!isset($this->session->userdata['front_data']['id'])) { ?> <p>Share these Smokin Hot Deals daily on Social Media and watch your Shopping Community grow! &nbsp; Our <a class="under-line-text" href="<?php echo base_url().'join-today'; ?>">Premier Shoppers</a> are building massive Shopping Communities and are earning HUGE commissions!</p> <?php }else if ($this->session->userdata['front_data']['user_account_type_id'] != 5){?> <p>Share these Smokin Hot Deals daily on Social Media and watch your Shopping Community grow! Our Premier Shoppers are building massive Shopping Communities and are earning HUGE commissions!</p> <?php } else if ($this->session->userdata['front_data']['user_account_type_id'] == 5){?> <p>Share these Smokin Hot Deals daily on Social Media and watch your Shopping Community grow! Our <a class="under-line-text" href="<?php echo base_url().'join-today'; ?>">Premier Shoppers</a> are building massive Shopping Communities and are earning HUGE commissions!</p> <?php } ?> </div> <div class="clearfix"></div> <span class="line-spc custom-we768"></span><span class="line-spc custom-we768"></span> </div> </div> </section> <div class="col-md-12 extra-links-share"> <span class="line-spc "></span> <div class="clearfix"></div> <div class="text-center gk-6 gk-right"> <a href="<?php echo base_url('share/good-karmora-emails') ?>" class="gk-icon"><i class="fa fa-envelope"></i></a> <div class="gk-right-title gk-title">Good Karmora Emails</div> </div> <div class="text-center gk-7 gk-right"> <a href="<?php echo base_url('share/good-karmora-videos'); ?>" class="gk-icon"><i class="fa fa-camera"></i></a> <div class="gk-right-title gk-title">Good Karmora Vidoes</div> </div> <div class="text-center gk-1 gk-right"> <a href="<?php echo base_url('share/good-karmora-ads/cash-back-ads') ?>" class="gk-icon"> <i class="flaticon-road-ad"></i> <!-- <img src="<?php //echo $themeUrl; ?>/images/ads.png"></a> --> <a href="<?php echo base_url('share/good-karmora-ads/cash-back-ads') ?>" class="gk-right-title gk-title">Cash Back Ads</a> </div> <div class="text-center gk-2 gk-right"> <a href="<?php echo base_url('share/good-karmora-ads/cash-o-palooza-ads') ?>" class="gk-icon"> <i class="flaticon-road-ad"></i> <!-- <img src="<?php //echo $themeUrl; ?>/images/ads.png"></a> --> <a href="<?php echo base_url('share/good-karmora-ads/cash-o-palooza-ads') ?>" class="gk-right-title gk-title">Cash-O-Palooza Ads</a> </div> <div class="text-center gk-4 gk-right"> <a href="<?php echo base_url('share/good-karmora-ads/custom-ads'); ?>" class="gk-icon"> <i class="flaticon-road-ad"></i> <!-- <img src="<?php //echo $themeUrl; ?>/images/ads.png"></a> --> <a href="<?php echo base_url('share/good-karmora-ads/custom-ads'); ?>" class="gk-right-title gk-title">Custom Ads</a> </div> <div class="text-center gk-5 gk-right"> <a href="<?php echo base_url('share/triple-karmora-kash-add'); ?>" class="gk-icon"> <!-- <img src="<?php //echo $themeUrl; ?>/images/ads.png"> --> <i class="flaticon-road-ad"></i> </a> <a href="<?php echo base_url('share/triple-karmora-kash-add'); ?>" class="gk-right-title gk-title">Triple Karmora Kash</a> </div> <div class="clearfix"></div> <span class="line-spc custom-we768"></span> </div> <div class="clearfix"></div> <span class="line-spc"></span><span class="line-spc custom-we768"></span> <section class="cashpalooza-sec pt0"> <div class="container"> <div class="row"> <div class="cop-deals"> <?php if (!empty($deals)) { ?> <!-- Deal Start --> <?php foreach ($deals as $deal) { ?> <div class="col-md-3 col-sm-4 col-xs-6 cop-d cop-m-resp"> <!--<img src="<?php /*echo base_url('share/smokin-hot-deal-ad/' . $deal['store_id']) */?>" alt="as"/>--> <img src="<?php echo $this->themeUrl.'/images/'.$deal['store_not_login_banner']; ?>" alt="as"/> <?php if (!isset($this->session->userdata['front_data'])) { ?> <div class="socialmediaicons custom-ads-social"> <ul class="inline"> <li> <?php $title = 'Special Offer - ' . $custom_ad->banner_ads_title; $caption = $title; $url_p = $custom_ad->banner_ads_redirect_url; $url = base_url().$url_p; $description = $custom_ad->banner_description; $picture = $themeUrl . '/images/banner/' . $custom_ad->banner_ads_image; ?> <?php if (!isset($this->session->userdata['front_data'])) { ?> <a href="<?php echo base_url('login') ?>"> <img src="<?php echo $themeUrl; ?>/images/share-on-facebook.jpg"> </a> <?php } else { ?> <a onClick="sharepost('<?php echo $caption ?>','<?php echo $url ?>','<?php echo $picture ?>','<?php echo $description ?>')" target="_parent" href="javascript: void(0)"> <img src="<?php echo $themeUrl; ?>/images/share-on-facebook.jpg"> </a> <?php } ?> </li> <li> <?php if (!isset($this->session->userdata['front_data'])) { ?> <a href="<?php echo base_url('login') ?>"> <img src="<?php echo $themeUrl; ?>/images/pinit.png"> </a> <?php } else { ?> <a onClick="window.open('http://www.pinterest.com/pin/create/button/?url=<?php echo $url; ?>&media=<?php echo $picture; ?>&description=<?php echo $caption; ?>', 'sharer', 'toolbar=0,status=0,width=548,height=325');" target="_parent" href="javascript: void(0)"> <img src="<?php echo $themeUrl; ?>/images/pinit.png"> </a> <?php } ?> </li> <li> <?php if (!isset($this->session->userdata['front_data'])) { ?> <a href="<?php echo base_url('login') ?>"> <img src="<?php echo $themeUrl; ?>/images/tweeticons.png"> </a> <?php } else { ?> <a onclick="window.open('https://twitter.com/intent/tweet?url=<?php echo $url; ?>&amp;hashtags=TrendingOnKarmora&amp;text=<?php echo $caption; ?>&amp;via=Shopkarmora', 'sharer', 'toolbar=0,status=0,width=548,height=325');" target="_parent" href="javascript: void(0)"> <img src="<?php echo $themeUrl; ?>/images/tweeticons.png"> </a> <?php } ?> </li> </ul> </div> <span class="line-spc"></span> <?php } else { ?> <div class="socialmediaicons"> <ul class="inline"> <li> <?php $title = 'KARMORA SMOKIN HOT DEAL!'; $caption = $title; $url_p = base_url('store-detail/' . $deal['store_id']); $url = $url_p; $description = 'Karmora Smokin Hot Deals combine top Cash Back with great deals offered by '. $deal['store_title'].' and many of our over 2,000 name brand stores. Click on the ad to view all of our Smokin Hot Deals! It’s FREE to join and who doesn’t like saving money, making money, winning money and having fun?'; //$picture = base_url('share/smokin-hot-deal-ad/' . $deal['store_id']); $picture = $this->themeUrl.'/images/'.$deal['store_not_login_banner']; ?> <a onClick="sharepost('<?php echo $caption ?>','<?php echo $url ?>','<?php echo $picture ?>','<?php echo $description ?>')" target="_parent" href="javascript: void(0)"> <img src="<?php echo $themeUrl; ?>/images/share-on-facebook.jpg"> </a> </li> <li> <a onClick="window.open('http://www.pinterest.com/pin/create/button/?url=<?php echo $url; ?>&media=<?php echo $picture; ?>&description=<?php echo $caption; ?>', 'sharer', 'toolbar=0,status=0,width=548,height=325');" target="_parent" href="javascript: void(0)"> <img src="<?php echo $themeUrl; ?>/images/pinit.png"> </a> </li> <li> <a onclick="window.open('https://twitter.com/intent/tweet?url=<?php echo $url; ?>&amp;hashtags=TrendingOnKarmora&amp;text=<?php echo $caption; ?>&amp;via=Shopkarmora', 'sharer', 'toolbar=0,status=0,width=548,height=325');" target="_parent" href="javascript: void(0)"> <img src="<?php echo $themeUrl; ?>/images/tweeticons.png"> </a> </li> </ul> </div> <span class="line-spc"></span> <?php } ?> </div> <?php } } else { echo 'No Record found!'; } ?> </div> </div> </div> </section> <div id="fb-root"></div> <script> (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); window.fbAsyncInit = function () { FB.init({ appId: '1455287054704424', status: true, xfbml: true, cookie: true }); }; /** * FaceBook Share function */ function sharepost(name, url, img, des) { FB.ui({ method: 'feed', name: name, link: url, picture: img, description: des, }, function (response) { }); } </script>
{ "content_hash": "8d21a74b2315743fa2f8bf1f715d8bef", "timestamp": "", "source": "github", "line_count": 216, "max_line_length": 360, "avg_line_length": 60.032407407407405, "alnum_prop": 0.4244620960900748, "repo_name": "fliegen-tech/karmora_v5", "id": "433d8033f491b7bfd713cd6dc211f0d85a638be4", "size": "12971", "binary": false, "copies": "1", "ref": "refs/heads/BR1", "path": "application/views/frontend/share/smokin_hot_deal_ads.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1577438" }, { "name": "HTML", "bytes": "14005798" }, { "name": "JavaScript", "bytes": "595884" }, { "name": "PHP", "bytes": "2616542" } ], "symlink_target": "" }
NS_ASSUME_NONNULL_BEGIN @interface LKAppUserStat : NSObject @property (readonly, nonatomic) NSInteger days; @property (readonly, nonatomic) NSInteger visits; @end @interface LKAppUser : NSObject @property (readonly, strong, nonatomic, nullable) NSString *email; @property (readonly, strong, nonatomic) NSDate *firstVisit; @property (readonly, strong, nonatomic) NSSet *labels; @property (readonly, strong, nonatomic, nullable) NSString *name; @property (readonly, strong, nonatomic) LKAppUserStat *stats; @property (readonly, strong, nonatomic, nullable) NSString *uniqueId; - (instancetype)initWithDictionary:(NSDictionary *)dictionary; - (BOOL)isSuper; @end NS_ASSUME_NONNULL_END
{ "content_hash": "208ca4aaa0e1b912dd27ca72c6f7012e", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 69, "avg_line_length": 28.708333333333332, "alnum_prop": 0.7793904208998549, "repo_name": "pkadams67/PKA-Project---Puff-Dragon", "id": "9f3d9308d726d8531fdcc1f1c587d4b12d4ca87a", "size": "809", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Pods/LaunchKit/LaunchKit/Classes/Analytics/LKAppUser.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2565" }, { "name": "Objective-C", "bytes": "287795" }, { "name": "Ruby", "bytes": "111" }, { "name": "Swift", "bytes": "25773" } ], "symlink_target": "" }
/** * PlatformCachePartitionType.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.sforce.soap._2006._04.metadata; public class PlatformCachePartitionType implements java.io.Serializable { private int allocatedCapacity; private int allocatedPurchasedCapacity; private int allocatedTrialCapacity; private com.sforce.soap._2006._04.metadata.PlatformCacheType cacheType; public PlatformCachePartitionType() { } public PlatformCachePartitionType( int allocatedCapacity, int allocatedPurchasedCapacity, int allocatedTrialCapacity, com.sforce.soap._2006._04.metadata.PlatformCacheType cacheType) { this.allocatedCapacity = allocatedCapacity; this.allocatedPurchasedCapacity = allocatedPurchasedCapacity; this.allocatedTrialCapacity = allocatedTrialCapacity; this.cacheType = cacheType; } /** * Gets the allocatedCapacity value for this PlatformCachePartitionType. * * @return allocatedCapacity */ public int getAllocatedCapacity() { return allocatedCapacity; } /** * Sets the allocatedCapacity value for this PlatformCachePartitionType. * * @param allocatedCapacity */ public void setAllocatedCapacity(int allocatedCapacity) { this.allocatedCapacity = allocatedCapacity; } /** * Gets the allocatedPurchasedCapacity value for this PlatformCachePartitionType. * * @return allocatedPurchasedCapacity */ public int getAllocatedPurchasedCapacity() { return allocatedPurchasedCapacity; } /** * Sets the allocatedPurchasedCapacity value for this PlatformCachePartitionType. * * @param allocatedPurchasedCapacity */ public void setAllocatedPurchasedCapacity(int allocatedPurchasedCapacity) { this.allocatedPurchasedCapacity = allocatedPurchasedCapacity; } /** * Gets the allocatedTrialCapacity value for this PlatformCachePartitionType. * * @return allocatedTrialCapacity */ public int getAllocatedTrialCapacity() { return allocatedTrialCapacity; } /** * Sets the allocatedTrialCapacity value for this PlatformCachePartitionType. * * @param allocatedTrialCapacity */ public void setAllocatedTrialCapacity(int allocatedTrialCapacity) { this.allocatedTrialCapacity = allocatedTrialCapacity; } /** * Gets the cacheType value for this PlatformCachePartitionType. * * @return cacheType */ public com.sforce.soap._2006._04.metadata.PlatformCacheType getCacheType() { return cacheType; } /** * Sets the cacheType value for this PlatformCachePartitionType. * * @param cacheType */ public void setCacheType(com.sforce.soap._2006._04.metadata.PlatformCacheType cacheType) { this.cacheType = cacheType; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof PlatformCachePartitionType)) return false; PlatformCachePartitionType other = (PlatformCachePartitionType) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && this.allocatedCapacity == other.getAllocatedCapacity() && this.allocatedPurchasedCapacity == other.getAllocatedPurchasedCapacity() && this.allocatedTrialCapacity == other.getAllocatedTrialCapacity() && ((this.cacheType==null && other.getCacheType()==null) || (this.cacheType!=null && this.cacheType.equals(other.getCacheType()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; _hashCode += getAllocatedCapacity(); _hashCode += getAllocatedPurchasedCapacity(); _hashCode += getAllocatedTrialCapacity(); if (getCacheType() != null) { _hashCode += getCacheType().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(PlatformCachePartitionType.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "PlatformCachePartitionType")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("allocatedCapacity"); elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "allocatedCapacity")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("allocatedPurchasedCapacity"); elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "allocatedPurchasedCapacity")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("allocatedTrialCapacity"); elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "allocatedTrialCapacity")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("cacheType"); elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "cacheType")); elemField.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "PlatformCacheType")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
{ "content_hash": "e4d36b5bc76c5efbbc68fcae8e51ee0e", "timestamp": "", "source": "github", "line_count": 215, "max_line_length": 133, "avg_line_length": 36.15813953488372, "alnum_prop": 0.646642655003859, "repo_name": "jwiesel/sfdcCommander", "id": "f5fa8c0e3dd8a18291b73cc7acff7c2be1174e43", "size": "7774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sfdcCommander/src/main/java/com/sforce/soap/_2006/_04/metadata/PlatformCachePartitionType.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1155" }, { "name": "CSS", "bytes": "4946" }, { "name": "HTML", "bytes": "8322" }, { "name": "Java", "bytes": "9750742" }, { "name": "JavaScript", "bytes": "1041" }, { "name": "Shell", "bytes": "977" }, { "name": "XSLT", "bytes": "147360" } ], "symlink_target": "" }
using System; using System.Diagnostics; using Armature.Core.Logging; using JetBrains.Annotations; namespace Armature.Core.BuildActions.Creation { /// <summary> /// Build action building a Unit using factory method /// </summary> public class CreateByFactoryMethodBuildAction<TR> : IBuildAction { private readonly Func<IBuildSession, TR> _factoryMethod; [DebuggerStepThrough] public CreateByFactoryMethodBuildAction([NotNull] Func<IBuildSession, TR> factoryMethod) => _factoryMethod = factoryMethod ?? throw new ArgumentNullException(nameof(factoryMethod)); public void Process(IBuildSession buildSession) { if (!buildSession.BuildResult.HasValue) buildSession.BuildResult = new BuildResult(_factoryMethod(buildSession)); } [DebuggerStepThrough] public void PostProcess(IBuildSession buildSession) { } [DebuggerStepThrough] public override string ToString() => string.Format(LogConst.OneParameterFormat, GetType().GetShortName(), _factoryMethod.ToLogString()); } }
{ "content_hash": "8b7750e142c707076621ff6eff0ee52e", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 140, "avg_line_length": 33.645161290322584, "alnum_prop": 0.75071907957814, "repo_name": "Ed-ward/Armature", "id": "c0078754bec5bf3ff800fe1a421b539be5999032", "size": "1045", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Armature.Core/src/BuildActions/Creation/CreateByFactoryMethodBuildAction.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "341302" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Xml.Linq; using Senparc.Weixin.MP.MvcExtension; using Senparc.Weixin.MP.Sample.CommonService.QyMessageHandlers; using Senparc.Weixin.QY.Entities; namespace Senparc.Weixin.MP.Sample.Controllers { /// <summary> /// 企业号对接测试 /// </summary> public class ThirdPartyAuthController : Controller { public static readonly string Token = "W6fnwXWcKnf2SFoypP1";//与微信企业账号后台的Token设置保持一致,区分大小写。 public static readonly string EncodingAESKey = "QrhJL7TdY3Ixk3Ga1p2kytJyDttSFltolCrxGCNGVrH";//与微信企业账号后台的EncodingAESKey设置保持一致,区分大小写。 public static readonly string SuiteId = "tj8946e399c3b2936f";//与微信企业账号后台的EncodingAESKey设置保持一致,区分大小写。 public ThirdPartyAuthController() { } /// <summary> /// 微信后台验证地址(使用Get),微信企业后台应用的“修改配置”的Url填写如:http://weixin.senparc.com/ThirdPartyAuth /// </summary> [HttpGet] [ActionName("Index")] public ActionResult Get(string msg_signature = "", string timestamp = "", string nonce = "", string echostr = "") { //return Content(echostr); //返回随机字符串则表示验证通过 var verifyUrl = QY.Signature.VerifyURL(Token, EncodingAESKey, SuiteId, msg_signature, timestamp, nonce, echostr); if (verifyUrl != null) { var fileStream = System.IO.File.OpenWrite(Server.MapPath("~/1.txt")); fileStream.Write(Encoding.Default.GetBytes(verifyUrl), 0, Encoding.Default.GetByteCount(verifyUrl)); fileStream.Close(); //return Content(verifyUrl); //返回解密后的随机字符串则表示验证通过 return Content("Success"); } else { var fileStream = System.IO.File.OpenWrite(Server.MapPath("~/1.txt")); fileStream.Write(Encoding.Default.GetBytes("asd"), 0, Encoding.Default.GetByteCount("asd")); fileStream.Close(); return Content("如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); } } /// <summary> /// 微信后台验证地址(使用Post),微信企业后台应用的“修改配置”的Url填写如:http://weixin.senparc.com/ThirdPartyAuth /// </summary> [HttpPost] [ActionName("Index")] public ActionResult Post(PostModel postModel) { var maxRecordCount = 10; postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; postModel.CorpId = SuiteId; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new QyCustomMessageHandler(Request.InputStream, postModel, maxRecordCount); if (messageHandler.RequestMessage == null) { //验证不通过或接受信息有错误 } try { //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save(Server.MapPath("~/App_Data/Qy/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 if (!string.IsNullOrEmpty(messageHandler.TextResponseMessage)) { //messageHandler.ResponseDocument.Save(Server.MapPath("~/App_Data/Qy/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); var responseText = messageHandler.TextResponseMessage; using (StreamWriter sw = new StreamWriter(Server.MapPath("~/App_Data/Qy/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt"), true)) { sw.Write(responseText); } if (messageHandler.FinalResponseDocument != null) { //messageHandler.FinalResponseDocument.Save(Server.MapPath("~/App_Data/Qy/" + DateTime.Now.Ticks + "_FinalResponse_" + messageHandler.ResponseMessage.ToUserName + ".txt")); using (StreamWriter sw = new StreamWriter(Server.MapPath("~/App_Data/Qy/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt"), true)) { sw.Write(messageHandler.FinalResponseDocument.ToString()); } } } //自动返回加密后结果 return new FixWeixinBugWeixinResult(messageHandler);//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 } catch (Exception ex) { using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Qy_Error_" + DateTime.Now.Ticks + ".txt"))) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.FinalResponseDocument != null) { tw.WriteLine(messageHandler.FinalResponseDocument.ToString()); } tw.Flush(); tw.Close(); } return Content(""); } } /// <summary> /// 这是一个最简洁的过程演示 /// </summary> /// <param name="postModel"></param> /// <returns></returns> [HttpPost] public ActionResult MiniPost(PostModel postModel) { var maxRecordCount = 10; postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; postModel.CorpId = SuiteId; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new QyCustomMessageHandler(Request.InputStream, postModel, maxRecordCount); //执行微信处理过程 messageHandler.Execute(); //自动返回加密后结果 return new FixWeixinBugWeixinResult(messageHandler); } } }
{ "content_hash": "15114eb75ec59a1dfb29c3292c718b82", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 196, "avg_line_length": 41.513333333333335, "alnum_prop": 0.5749156897382367, "repo_name": "wanddy/WeiXinMPSDK", "id": "2241045006710418527d9b021cf81cdb591511b3", "size": "7027", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Controllers/QY/ThirdPartyAuthController.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "27741" }, { "name": "C#", "bytes": "5122792" }, { "name": "CSS", "bytes": "46818" }, { "name": "HTML", "bytes": "566" }, { "name": "JavaScript", "bytes": "66273" } ], "symlink_target": "" }
package com.fasterxml.jackson.databind.module; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.type.TypeBindings; import com.fasterxml.jackson.databind.type.TypeFactory; import com.fasterxml.jackson.databind.type.TypeModifier; import java.lang.reflect.Type; public class TestTypeModifierNameResolution extends BaseMapTest { interface MyType { String getData(); void setData(String data); } static class MyTypeImpl implements MyType { private String data; @Override public String getData() { return data; } @Override public void setData(String data) { this.data = data; } } static class CustomTypeModifier extends TypeModifier { @Override public JavaType modifyType(JavaType type, Type jdkType, TypeBindings context, TypeFactory typeFactory) { if (type.getRawClass().equals(MyTypeImpl.class)) { return typeFactory.constructType(MyType.class); } return type; } } @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT) public interface Mixin { } // Expect that the TypeModifier kicks in when the type id is written. public void testTypeModiferNameResolution() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setTypeFactory(mapper.getTypeFactory().withModifier(new CustomTypeModifier())); mapper.addMixIn(MyType.class, Mixin.class); MyType obj = new MyTypeImpl(); obj.setData("something"); String s = mapper.writer().writeValueAsString(obj); assertTrue(s.startsWith("{\"TestTypeModifierNameResolution$MyType\":")); } }
{ "content_hash": "4421163ea5bed4b800653c71ca1da509", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 106, "avg_line_length": 27.64406779661017, "alnum_prop": 0.7627222562844881, "repo_name": "FasterXML/jackson-databind", "id": "cdd89ea0760496a35e47dabf29828349856593df", "size": "1631", "binary": false, "copies": "1", "ref": "refs/heads/2.15", "path": "src/test/java/com/fasterxml/jackson/databind/module/TestTypeModifierNameResolution.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "7940640" }, { "name": "Logos", "bytes": "173041" }, { "name": "Shell", "bytes": "264" } ], "symlink_target": "" }
Inspired by Paul Hertz's [glitchSort](http://paulhertz.net/factory/2012/08/glitchsort2/) for Processing using [Kim Asendorf's](http://kimasendorf.tumblr.com/post/32936480093/processing-source-code) algorithm for pixel sorting. (Or at least that's the idea so far.)
{ "content_hash": "4ae8d50d94a3a5ff8491fb949e2cf7dd", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 226, "avg_line_length": 88.33333333333333, "alnum_prop": 0.7886792452830189, "repo_name": "bleedingxedge/Puchi.js", "id": "f6616cd6f3b2ecd7713089ba6b3870c0d365bbd3", "size": "362", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "241" } ], "symlink_target": "" }
<?php //Creating Connection to Database! $con = mysql_connect("localhost", "root", "") or die("Could not connect to MySQL"); mysql_select_db("GenericQuiz") or die("Could not select db"); ?>
{ "content_hash": "d5523a1160291ea71da37858d0a9b9fe", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 83, "avg_line_length": 37.8, "alnum_prop": 0.6931216931216931, "repo_name": "Varun-Bawa/GenericQuiz", "id": "40c09958110607ddd7d87fcf8618bc4fb2d7d60a", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "218728" }, { "name": "HTML", "bytes": "12891" }, { "name": "JavaScript", "bytes": "308120" }, { "name": "PHP", "bytes": "155403" } ], "symlink_target": "" }
class LSystem { constructor (axiom, productionRules) { if (!(Symbol.iterator in productionRules)) { throw new Error('LSystem: productionRules (argument 1) must be iterable') } productionRules = new Map(productionRules) const alphabet = Array.from(productionRules.keys()) const constants = [] if (alphabet.indexOf(axiom) === -1) { throw new Error('LSystem: axiom (argument 0) has to be in productionRules') } for (let [from, to] of productionRules) { if (typeof to === 'string' || !(Symbol.iterator in to)) { to = [to] productionRules.set(from, to) } if (to.length === 1 && to[0] === from) { constants.push(to) } for (let ele of to) { if (alphabet.indexOf(ele) === -1) { throw new Error(`LSystem: unknown value ${ele} in productionRules of ${from}`) } } } Object.assign(this, { axiom: axiom, alphabet: alphabet, constants: constants, productionRules: productionRules }) this.reset() } step () { const next = [] for (let ele of this.current) { next.push(...this.productionRules.get(ele)) } this.current = next } reset () { this.current = [this.axiom] } ended () { for (let ele of this.current) { if (this.constants.indexOf(ele) === -1) { return false } } return true } * generator () { while (true) { yield this.current this.step() if (this.ended()) { break } } } [Symbol.iterator] () { return (new LSystem(this.axiom, this.productionRules)).generator() } } export default LSystem
{ "content_hash": "f165bf1903c5078f68dc55d54e981dab", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 88, "avg_line_length": 20.634146341463413, "alnum_prop": 0.5602836879432624, "repo_name": "ileri/l-system", "id": "45baa4fe35dbc7ff1355831fa867ba21d8ae265c", "size": "1692", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "l-system.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4298" } ], "symlink_target": "" }
define([ 'jquery', 'fn/defined' ], function( $ , defined ){ 'use strict'; return function( name ){ if( !defined(name) ){ name = 'div'; } return $(document.createElement(name)); } });
{ "content_hash": "beaacebbfb7c7d31ac2d661aef25cc9f", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 59, "avg_line_length": 23.2, "alnum_prop": 0.49137931034482757, "repo_name": "packadic/jsdoc-template", "id": "9fb7543dc49f1f2b9e544b8a0c90f67de213e0e6", "size": "232", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "assets/scripts/fn/cre.js", "mode": "33188", "license": "mit", "language": [ { "name": "ABAP", "bytes": "1924" }, { "name": "ActionScript", "bytes": "38837" }, { "name": "Ada", "bytes": "198" }, { "name": "Assembly", "bytes": "1055" }, { "name": "AutoHotkey", "bytes": "1440" }, { "name": "Batchfile", "bytes": "5910" }, { "name": "C#", "bytes": "166" }, { "name": "C++", "bytes": "1522" }, { "name": "COBOL", "bytes": "8" }, { "name": "CSS", "bytes": "3636160" }, { "name": "Cirru", "bytes": "1040" }, { "name": "Clojure", "bytes": "1588" }, { "name": "CoffeeScript", "bytes": "73408" }, { "name": "ColdFusion", "bytes": "172" }, { "name": "Common Lisp", "bytes": "1264" }, { "name": "Cucumber", "bytes": "1394" }, { "name": "D", "bytes": "648" }, { "name": "Dart", "bytes": "978" }, { "name": "Eiffel", "bytes": "750" }, { "name": "Elixir", "bytes": "1384" }, { "name": "Elm", "bytes": "974" }, { "name": "Erlang", "bytes": "974" }, { "name": "Forth", "bytes": "1958" }, { "name": "GLSL", "bytes": "1024" }, { "name": "Go", "bytes": "1282" }, { "name": "Groff", "bytes": "2189" }, { "name": "Groovy", "bytes": "2160" }, { "name": "HTML", "bytes": "3559297" }, { "name": "Handlebars", "bytes": "346" }, { "name": "Haskell", "bytes": "1024" }, { "name": "Haxe", "bytes": "894" }, { "name": "Io", "bytes": "280" }, { "name": "JSONiq", "bytes": "8" }, { "name": "Java", "bytes": "3100" }, { "name": "JavaScript", "bytes": "43875190" }, { "name": "Julia", "bytes": "420" }, { "name": "LSL", "bytes": "4160" }, { "name": "Lean", "bytes": "426" }, { "name": "Liquid", "bytes": "3766" }, { "name": "LiveScript", "bytes": "11537" }, { "name": "Lua", "bytes": "1962" }, { "name": "Makefile", "bytes": "25293" }, { "name": "Mask", "bytes": "1194" }, { "name": "Matlab", "bytes": "406" }, { "name": "Nix", "bytes": "4424" }, { "name": "OCaml", "bytes": "1078" }, { "name": "Objective-C", "bytes": "5344" }, { "name": "OpenSCAD", "bytes": "666" }, { "name": "PHP", "bytes": "702" }, { "name": "Pascal", "bytes": "2824" }, { "name": "Perl", "bytes": "2993" }, { "name": "PowerShell", "bytes": "836" }, { "name": "Protocol Buffer", "bytes": "548" }, { "name": "Python", "bytes": "20237" }, { "name": "R", "bytes": "4890" }, { "name": "Ruby", "bytes": "4326" }, { "name": "Rust", "bytes": "990" }, { "name": "Scala", "bytes": "3082" }, { "name": "Scheme", "bytes": "1118" }, { "name": "Shell", "bytes": "13244" }, { "name": "Tcl", "bytes": "1798" }, { "name": "TeX", "bytes": "2690" }, { "name": "TypeScript", "bytes": "3214" }, { "name": "VHDL", "bytes": "1660" }, { "name": "Vala", "bytes": "970" }, { "name": "Verilog", "bytes": "548" }, { "name": "Visual Basic", "bytes": "1854" }, { "name": "XQuery", "bytes": "228" } ], "symlink_target": "" }
''' This is the Python version of the Random Search algorithm presented in "Clever Algorithms: Nature-Inspired Programming Recipes". Find the book and the Ruby source codes on GitHub: https://github.com/jbrownlee/CleverAlgorithm:s ''' import random def objective_function(vector): return sum([x ** 2.0 for x in vector]) def random_vector(minmax): return [minmax[i][0] + ((minmax[i][1] - minmax[i][0]) * random.random()) for i in range(len(minmax))] def search(search_space, max_iter): best = None for i in range(max_iter): candidate = {} candidate["pos"] = random_vector(search_space) candidate["cost"] = objective_function(candidate["pos"]) if best is None or candidate["cost"] < best["cost"]: best = candidate print " > iteration %i, best=%.4g" % (i, best["cost"]) return best if __name__ == "__main__": search_space = [[-5,5],[-5,5]] problem_size = 2 max_iter = 100 best = search(search_space, max_iter) print "Done! Best solution: f = %.4g, v =" % best["cost"], best["pos"]
{ "content_hash": "5e766210da1ac7e92817e9330d8f6518", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 105, "avg_line_length": 29.16216216216216, "alnum_prop": 0.623725671918443, "repo_name": "mkrapp/semic", "id": "b9bb45fa7cfff26a08c55d2309ac56dd0316eb87", "size": "1079", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "optimize/optimization_algorithms/random_search.py", "mode": "33188", "license": "mit", "language": [ { "name": "Fortran", "bytes": "55403" }, { "name": "Makefile", "bytes": "4803" }, { "name": "Python", "bytes": "46472" } ], "symlink_target": "" }
__name__ = 'jsonrpc2' __author__ = 'Max <[email protected]>' __version__ = 1, 0 __detail__ = 'Based on https://github.com/subutux/json-rpc2php' import logging logger = logging.getLogger(__name__) import json import requests import pprint class jsonrpc2(object): '''jsonrpc2 client''' host = '' default_options = { 'username': '', 'password': '', } currId = 0 apiMethods = [] headers = {'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0'} cookies = {} def __init__(self, api_url, options=None): self.host = api_url if options is not None: for i in options: self.default_options[i] = options[i] returned = self.rpc_list_available_commands() self.apiMethods = returned['services'] def rpc_list_available_commands(self): response = requests.get(self.host, auth=(self.default_options['username'], self.default_options['password']), headers=self.headers, data='') self.cookies = response.cookies return json.loads(response.content) def rpc_call(self, method, params=None, notification=False): """main function to call the rpc api""" request = { 'jsonrpc': '2.0', 'method': method, 'params': '', } if notification is False: self.currId += 1 request['id'] = self.currId if isinstance(params, str): request['params'] = [params] elif isinstance(params, dict): request['params'] = params elif isinstance(params, list): request['params'] = params jsonrequest = json.dumps(request) response = requests.post(self.host, auth=(self.default_options['username'], self.default_options['password']), headers=self.headers, data=jsonrequest) print 'RPC CALL:', method, pprint.pformat(params) if notification is False: f_obj = json.loads(response.content) if 'error' in f_obj.keys(): raise rpcException(f_obj['error']) else: print ' RPC RESPONSE:', pprint.pformat(f_obj) return f_obj def __getattr__(self, method): """Magic!""" arg = ['', False] if method in self.apiMethods: def function(*args): # Get the method arguments. If there are none provided, use the default. try: arg[0] = args[0] except IndexError: pass # check if notification param is set. If not, use default (False) try: arg[1] = args[1] except IndexError: pass return self.rpc_call(method, arg[0], arg[1]) return function else: raise rpcException("Unknown method: %s" % method) class rpcException(Exception): def __init__(self, jsonrpc2Error): if type(jsonrpc2Error) is not str: print jsonrpc2Error message = str(jsonrpc2Error["code"]) + " :: " + jsonrpc2Error["message"] self.errorCode = jsonrpc2Error["code"] self.message = jsonrpc2Error["message"] self.fullMessage = jsonrpc2Error['data'] else: message = jsonrpc2Error Exception.__init__(self, message)
{ "content_hash": "d238a56f6058f2ec8eabd11029c06a45", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 108, "avg_line_length": 32.78761061946903, "alnum_prop": 0.5201079622132254, "repo_name": "vesellov/callfeed.net", "id": "0c5333c0e38620e4f72120bacf361c05af511235", "size": "3705", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mainapp/utils/jsonrpc2.py", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "143" }, { "name": "CSS", "bytes": "349981" }, { "name": "HTML", "bytes": "289531" }, { "name": "JavaScript", "bytes": "767378" }, { "name": "Python", "bytes": "477690" }, { "name": "Shell", "bytes": "5323" } ], "symlink_target": "" }
package com.kong.zxreader.db; import java.sql.SQLException; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; import com.kong.zxreader.bean.Book; import com.kong.zxreader.bean.BookMarks; import com.kong.zxreader.bean.BookNotes; /** * Database helper class used to manage the creation and upgrading of your database. This class also usually provides * the DAOs used by the other classes. */ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // name of the database file for your application -- change to something appropriate for your app private static final String DATABASE_NAME = "zx.db"; // any time you make changes to your database objects, you may have to increase the database version private static final int DATABASE_VERSION = 35; // the DAO object we use to access the SimpleData table private Dao<Book, Integer> bookDao = null; private Dao<BookMarks, Integer> bookMarksDao = null; private Dao<BookNotes, Integer> bookNoteDao = null; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * This is called when the database is first created. Usually you should call createTable statements here to create * the tables that will store your data. */ @Override public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { try { // LogUtil.i(DatabaseHelper.class.getName(), "onCreate"); TableUtils.createTable(connectionSource, Book.class); TableUtils.createTable(connectionSource, BookMarks.class); TableUtils.createTable(connectionSource, BookNotes.class); } catch (SQLException e) { // LogUtil.e(DatabaseHelper.class.getName(), "Can't create database"); throw new RuntimeException(e); } } /** * This is called when your application is upgraded and it has a higher version number. This allows you to adjust * the various data to match the new version number. */ @Override public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { try { // LogUtil.i(DatabaseHelper.class.getName(), "onUpgrade"); TableUtils.dropTable(connectionSource, Book.class, true); TableUtils.dropTable(connectionSource, BookMarks.class, true); TableUtils.dropTable(connectionSource, BookNotes.class, true); // after we drop the old databases, we create the new ones onCreate(db, connectionSource); } catch (SQLException e) { Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e); throw new RuntimeException(e); } } /** * Returns the Database Access Object (DAO) for our SimpleData class. It will create it or just give the cached * value. */ public Dao<Book, Integer> getBookDao() throws SQLException { if (bookDao == null) { bookDao = getDao(Book.class); } return bookDao; } public Dao<BookMarks, Integer> getBookMarksDao() throws SQLException { if (bookMarksDao == null) { bookMarksDao = getDao(BookMarks.class); } return bookMarksDao; } public Dao<BookNotes, Integer> getBookNoteDao() throws SQLException { if (bookNoteDao == null) { bookNoteDao = getDao(BookNotes.class); } return bookNoteDao; } /** * Close the database connections and clear any cached DAOs. */ @Override public void close() { super.close(); bookDao = null; } }
{ "content_hash": "2725f954d958c00595fb3dd4ee17c58c", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 117, "avg_line_length": 33.11926605504587, "alnum_prop": 0.7462603878116344, "repo_name": "wh5355/zx-new", "id": "8298d2995447c54e65d915e065af5f1a1f30c6bf", "size": "3610", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/com/kong/zxreader/db/DatabaseHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "850091" } ], "symlink_target": "" }
#include "Languages.h" /** * */ Languages::Languages() {} /** * */ void Languages::init( cppcms::json::array langsJson, cppcms::json::array interfaceLangsJson ) { cppcms::json::array::const_iterator end = interfaceLangsJson.end(); // lines are in this form // code , locale , natural name // e.g // "en" , "en_GB.UTF-8", "English" for ( cppcms::json::array::const_iterator p=interfaceLangsJson.begin(); p!= end; ++p ) { cppcms::json::array lang = p->array(); std::string langCode = lang[0].str(); langToLocale[langCode] = lang[1].str(); interfaceCodeToName[langCode] = lang[2].str(); } } std::string Languages::get_locale_from_lang( const std::string &lang ) { return langToLocale[lang]; } bool Languages::is_interface_lang( const std::string &interfaceLang ) { return langToLocale.find(interfaceLang) != langToLocale.end(); } /** * */ void Languages::fill_interface_lang_select( cppcms::widgets::select &select ) { InterfaceCodeToName::const_iterator itr; for( itr = interfaceCodeToName.begin(); itr != interfaceCodeToName.end(); ++itr ) { select.add( itr->second, itr->first ); } }
{ "content_hash": "0f4f3a9de0090f91d1c514ee5ba1f209", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 73, "avg_line_length": 17.958904109589042, "alnum_prop": 0.5736079328756675, "repo_name": "allan-simon/tatoSSO", "id": "942cfe2ffb44ead10a9c4daedde24abd4bc28337", "size": "1587", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "local_template/generics/Languages.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "42390" }, { "name": "JavaScript", "bytes": "1015" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_23) on Sun Feb 26 06:28:55 CET 2012 --> <TITLE> EchoXML.NamespacePolicy (Apache Ant API) </TITLE> <META NAME="date" CONTENT="2012-02-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="EchoXML.NamespacePolicy (Apache Ant API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.html" title="class in org.apache.tools.ant.taskdefs"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/tools/ant/taskdefs/Exec.html" title="class in org.apache.tools.ant.taskdefs"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="EchoXML.NamespacePolicy.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.tools.ant.taskdefs</FONT> <BR> Class EchoXML.NamespacePolicy</H2> <PRE> java.lang.Object <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">org.apache.tools.ant.types.EnumeratedAttribute</A> <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.tools.ant.taskdefs.EchoXML.NamespacePolicy</B> </PRE> <DL> <DT><B>Enclosing class:</B><DD><A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.html" title="class in org.apache.tools.ant.taskdefs">EchoXML</A></DD> </DL> <HR> <DL> <DT><PRE>public static class <B>EchoXML.NamespacePolicy</B><DT>extends <A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">EnumeratedAttribute</A></DL> </PRE> <P> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html" title="class in org.apache.tools.ant.taskdefs">EchoXML.NamespacePolicy</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html#DEFAULT">DEFAULT</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_org.apache.tools.ant.types.EnumeratedAttribute"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Fields inherited from class org.apache.tools.ant.types.<A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">EnumeratedAttribute</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#value">value</A></CODE></TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html#EchoXML.NamespacePolicy()">EchoXML.NamespacePolicy</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html#EchoXML.NamespacePolicy(java.lang.String)">EchoXML.NamespacePolicy</A></B>(java.lang.String&nbsp;s)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../org/apache/tools/ant/util/DOMElementWriter.XmlNamespacePolicy.html" title="class in org.apache.tools.ant.util">DOMElementWriter.XmlNamespacePolicy</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html#getPolicy()">getPolicy</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String[]</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html#getValues()">getValues</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is the only method a subclass needs to implement.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.apache.tools.ant.types.EnumeratedAttribute"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class org.apache.tools.ant.types.<A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">EnumeratedAttribute</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#containsValue(java.lang.String)">containsValue</A>, <A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#getIndex()">getIndex</A>, <A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#getInstance(java.lang.Class, java.lang.String)">getInstance</A>, <A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#getValue()">getValue</A>, <A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#indexOfValue(java.lang.String)">indexOfValue</A>, <A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#setValue(java.lang.String)">setValue</A>, <A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#toString()">toString</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="DEFAULT"><!-- --></A><H3> DEFAULT</H3> <PRE> public static final <A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html" title="class in org.apache.tools.ant.taskdefs">EchoXML.NamespacePolicy</A> <B>DEFAULT</B></PRE> <DL> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="EchoXML.NamespacePolicy()"><!-- --></A><H3> EchoXML.NamespacePolicy</H3> <PRE> public <B>EchoXML.NamespacePolicy</B>()</PRE> <DL> </DL> <HR> <A NAME="EchoXML.NamespacePolicy(java.lang.String)"><!-- --></A><H3> EchoXML.NamespacePolicy</H3> <PRE> public <B>EchoXML.NamespacePolicy</B>(java.lang.String&nbsp;s)</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getValues()"><!-- --></A><H3> getValues</H3> <PRE> public java.lang.String[] <B>getValues</B>()</PRE> <DL> <DD>This is the only method a subclass needs to implement.. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html#getValues()">getValues</A></CODE> in class <CODE><A HREF="../../../../../org/apache/tools/ant/types/EnumeratedAttribute.html" title="class in org.apache.tools.ant.types">EnumeratedAttribute</A></CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>an array holding all possible values of the enumeration. The order of elements must be fixed so that <tt>indexOfValue(String)</tt> always return the same index for the same value.</DL> </DD> </DL> <HR> <A NAME="getPolicy()"><!-- --></A><H3> getPolicy</H3> <PRE> public <A HREF="../../../../../org/apache/tools/ant/util/DOMElementWriter.XmlNamespacePolicy.html" title="class in org.apache.tools.ant.util">DOMElementWriter.XmlNamespacePolicy</A> <B>getPolicy</B>()</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/tools/ant/taskdefs/EchoXML.html" title="class in org.apache.tools.ant.taskdefs"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/tools/ant/taskdefs/Exec.html" title="class in org.apache.tools.ant.taskdefs"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="EchoXML.NamespacePolicy.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "3410fd958fdb84eefe824d7887b26ceb", "timestamp": "", "source": "github", "line_count": 349, "max_line_length": 839, "avg_line_length": 45.40974212034384, "alnum_prop": 0.6392604745078243, "repo_name": "kolbasa/IaTestGen", "id": "c585b82c819a987dd70892c3e428d442f0d6672b", "size": "15848", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "build/files/apache_ant_1.8.3/manual/api/org/apache/tools/ant/taskdefs/EchoXML.NamespacePolicy.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "8599" }, { "name": "Java", "bytes": "383882" }, { "name": "Perl", "bytes": "9844" }, { "name": "Python", "bytes": "3299" }, { "name": "Shell", "bytes": "45576" }, { "name": "XML", "bytes": "221100" } ], "symlink_target": "" }
/* Module: LISTENER */ // EVENT LISTENERS function attachMenuEventListeners() { $('#start-game').click(function () { // hide menu $('.overlay').hide(); // retrieve all tank blueprints GLOBALS.tankSelection.blueprints = BLUEPRINT.getByType('tanks'); // update initial stats UTIL.gui.updateTankStats(); GLOBALS.map.current = maps[GLOBALS.map.index]; UTIL.gui.selectMap('init'); // show pre-game settings $('#prompt-pre-game-settings').show(); }); $('#multiplayer').click(function () { // hide menu $('.overlay').hide(); // connect to websocket server MULT.connect(); $('#multiplayer-screen').show(); }); $('.start-battle-ok').click(function () { // hide menu $('.overlay').hide(); // reset and show hud counters $('#text-overlay-top').html(''); $('#text-overlay-center').html(''); $('#kill-count').html('0'); $('#gold-count').html('0'); $('#ammo-count').html('0'); TANK.upgrade.reset(); TANK.consumable.reset(); $('.hud').show(); // start game start(); }); $('#tank-next').click(function () { UTIL.gui.updateTankStats('next'); }); $('#tank-prev').click(function () { UTIL.gui.updateTankStats('prev'); }); $('#ms-next').click(function () { UTIL.gui.selectMap('next'); }); $('#ms-prev').click(function () { UTIL.gui.selectMap('prev'); }); $('#hall-of-fame').click(function () { // hide menu $('.overlay').fadeOut(); $('#hof').show(); UTIL.getHighScores(); }); $('#map-builder').click(function () { // hide menu $('.overlay').fadeOut(); // start map editor startMapEditor(); }); $('.continue-game').click(function () { // hide menu $('.overlay').hide(); // continue what we were doing then = performance.now(); if (ui_location == 'game') { main(); // resume timers UTIL.timer.resumeAll(); UTIL.playMusic(backgroundMusic); } if (ui_location == 'editor') editor(); }); $('.main-menu').click(function() { UTIL.stopMusic(backgroundMusic); LOAD.worker.terminateAll(); cancelAnimationFrame(mainAnimation); cancelAnimationFrame(editorAnimation); clearInterval(waveCountDown); document.getElementById('combat-log').innerHTML = ''; // clear logs // hide menu $('.overlay').hide(); $('.hud').hide(); // goto menu menu(); }); $('#gamepedia').click(function () { $('.overlay').hide(); $('#gamepedia-screen').fadeIn(); }); $('#settings').click(function () { $('.overlay').hide(); $('#settings-screen').fadeIn(); }); } function attachEditorEventListeners() { $('#map-properties').click(function () { $('.overlay').hide(); $('#map-properties-screen').show(); }); $('#load-map').click(function () { // hide menu $('.overlay').hide(); // show prompt $('#prompt-map-load').show(); }); $('#load-map-ok').click(function () { // we have the map name, so we can load it to the editor. MAP.loadToEditor(); // hide menu editor(); $('.overlay').fadeOut(); }); $('#save-map').click(function () { // hide menu $('.overlay').hide(); // show save prompt $('#prompt-map-name').show(); }); $('#save-map-ok').click(function () { // we have the map name, so we can save it. var name = document.getElementById('map-name').value; var desc = document.getElementById('map-desc').value; name = name === '' ? 'Unnamed Map' : name; desc = desc === '' ? 'No description.' : desc; MAP.save(name, desc); // hide menu editor(); $('.overlay').fadeOut(); }); $('#export-map').click(function () { // hide menu $('.overlay').hide(); // show prompt $('#prompt-map-name-export').show(); }); $('#save-map-ex-ok').click(function () { // we have the map name, so we can save it. var name = document.getElementById('map-name-ex').value; var desc = document.getElementById('map-desc-ex').value; name = name === '' ? 'Unnamed Map' : name; desc = desc === '' ? 'No description.' : desc; //MAP.exportToString(name); MAP.exportToJSON(name, desc); // hide menu editor(); $('.overlay').fadeOut(); }); $('#import-map').click(function () { // hide menu $('.overlay').hide(); // show prompt $('#prompt-map-import').show(); }); $('#import-map-ok').click(function () { // we have the map name, so we can save it. var mapStr = document.getElementById('map-string').value; //MAP.importFromString(mapStr); MAP.importFromJSON(mapStr); // hide menu editor(); $('.overlay').fadeOut(); }); } function attachGameEventListeners() { addEventListener('keydown', gameKeyDownEvent, false); addEventListener('keyup', gameKeyUpEvent, false); canvas.addEventListener('mousemove', gameMouseMoveEvent, false); canvas.addEventListener('mousedown', gameMouseDownEvent, false); canvas.addEventListener('mouseup', gameMouseUpEvent, false); } function gameKeyDownEvent(e) { if (e.keyCode == 27) { pause(); // pause the game } else if (e.keyCode == 77) { UTIL.toggleMiniMap(); } else if (e.keyCode === 85 && e.altKey) { // letter u, show upgrades screen if in-game if (ui_location === 'game' && $('#upgrades-screen').css('display') === 'none' && GLOBALS.botCount === 0) { // show upgrades screen only in-game and when there are no active bots pause(); TANK.upgrade.refresh(); $('#upgrades-screen').show(); } } else if (e.keyCode === 67 && e.altKey) { // letter c, show upgrades screen if in-game if (ui_location === 'game' && $('#consumables-screen').css('display') === 'none' && GLOBALS.botCount === 0) { // show consumables screen only in-game and when there are no active bots pause(); TANK.consumable.refresh(); $('#consumables-screen').show(); } } else if (e.keyCode === 97 || e.keyCode === 98 || e.keyCode === 99 || e.keyCode === 100 || e.keyCode === 101 || (e.keyCode > 48 && e.keyCode < 54)) { switch (e.keyCode) { case 97: case 49: TANK.consumable.use(0); break; case 98: case 50: TANK.consumable.use(1); break; case 99: case 51: TANK.consumable.use(2); break; case 100: case 52: TANK.consumable.use(3); break; case 101: case 53: TANK.consumable.use(4); break; } } else if (e.keyCode === 78) { UTIL.followNextTank(); // n } else if (e.keyCode === 70) { UTIL.toggleFreeCameraMode(); // f } else { keysDown[e.keyCode] = true; } } function gameKeyUpEvent(e) { delete keysDown[e.keyCode]; } function gameMouseMoveEvent(evt) { mousePos = UTIL.getMousePos(canvas, evt); } function gameMouseDownEvent(e) { if (e.which == 1) { mouseDownLeft = true; } else { mouseDownRight = true; } } function gameMouseUpEvent(e) { mouseDownLeft = mouseDownRight = false; }
{ "content_hash": "0d5d2686d2c81f943fb0ae9652762e96", "timestamp": "", "source": "github", "line_count": 293, "max_line_length": 152, "avg_line_length": 27.948805460750854, "alnum_prop": 0.49090243008914397, "repo_name": "quarkdev/battletanks", "id": "3e61d9308b4c1c8e874f148932ffb233fdcea9f4", "size": "8189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/listener.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16288" }, { "name": "HTML", "bytes": "18840" }, { "name": "Hack", "bytes": "26" }, { "name": "JavaScript", "bytes": "407833" }, { "name": "PHP", "bytes": "13692" } ], "symlink_target": "" }
package org.graphwalker.core.generator; import org.junit.Test; import java.util.Random; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class SingletonRandomGeneratorTest { @Test public void instantiation() { assertThat(SingletonRandomGenerator.random(), is(instanceOf(Random.class))); } @Test public void seed() { SingletonRandomGenerator.setSeed(123); assertThat(SingletonRandomGenerator.nextInt(), is(-1188957731)); assertThat(SingletonRandomGenerator.nextInt(), is(1018954901)); assertThat(SingletonRandomGenerator.nextInt(), is(-39088943)); } @Test public void un_seeded() { assertThat(SingletonRandomGenerator.nextInt(), is(instanceOf(int.class))); } @Test public void seededBoundNextInt() { SingletonRandomGenerator.setSeed(123); assertThat(SingletonRandomGenerator.nextInt(1), is(0)); assertThat(SingletonRandomGenerator.nextInt(99), is(86)); assertThat(SingletonRandomGenerator.nextInt(999), is(245)); } @Test public void un_seededBoundNextInt() { assertThat(SingletonRandomGenerator.nextInt(999), is(instanceOf(int.class))); } }
{ "content_hash": "01dfacfe8b88ef73ad7927801e033c84", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 81, "avg_line_length": 28.6046511627907, "alnum_prop": 0.7528455284552845, "repo_name": "GraphWalker/graphwalker-project", "id": "bb006219bd943d8ed26c3f191dc3d1f986dcbb8a", "size": "1230", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "graphwalker-core/src/test/java/org/graphwalker/core/generator/SingletonRandomGeneratorTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "8311" }, { "name": "CSS", "bytes": "1884" }, { "name": "HTML", "bytes": "348" }, { "name": "Java", "bytes": "1121867" }, { "name": "JavaScript", "bytes": "46375" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/rna-transcription.iml" filepath="$PROJECT_DIR$/rna-transcription.iml" /> </modules> </component> </project>
{ "content_hash": "2bc37dc5f8023b8d017a6ea04e1ba8d4", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 116, "avg_line_length": 34.25, "alnum_prop": 0.6751824817518248, "repo_name": "enolive/exercism", "id": "a105d1c6c79b01ac910a1403768254f4ce947c83", "size": "274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "haskell/rna-transcription/.idea/modules.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1346" }, { "name": "Haskell", "bytes": "220732" }, { "name": "Java", "bytes": "28701" }, { "name": "Kotlin", "bytes": "78063" }, { "name": "TypeScript", "bytes": "92672" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>infotheo: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.15.1 / infotheo - 0.2</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> infotheo <small> 0.2 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-01 15:17:29 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-01 15:17:29 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.15.1 Formal proof management system dune 3.0.3 Fast, portable, and opinionated build system ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/affeldt-aist/infotheo&quot; bug-reports: &quot;https://github.com/affeldt-aist/infotheo/issues&quot; dev-repo: &quot;git+https://github.com/affeldt-aist/infotheo.git&quot; license: &quot;LGPL-2.1-or-later&quot; authors: [ &quot;Reynald Affeldt&quot; &quot;Manabu Hagiwara&quot; &quot;Jonas Senizergues&quot; &quot;Jacques Garrigue&quot; &quot;Kazuhiko Sakaguchi&quot; &quot;Taku Asai&quot; &quot;Takafumi Saikawa&quot; &quot;Naruomi Obata&quot; &quot;Erik Martin-Dorel&quot; &quot;Ryosuke Obi&quot; &quot;Mitsuharu Yamamoto&quot; ] build: [ [make &quot;-j%{jobs}%&quot;] [make &quot;-C&quot; &quot;extraction&quot; &quot;tests&quot;] {with-test} ] install: [ [make &quot;install&quot;] ] depends: [ &quot;coq&quot; {&gt;= &quot;8.11&quot; &amp; &lt; &quot;8.13~&quot;} &quot;coq-mathcomp-field&quot; {&gt;= &quot;1.11&quot; &amp; &lt; &quot;1.12~&quot;} &quot;coq-mathcomp-analysis&quot; {&gt;= &quot;0.3.2&quot; &amp; &lt; &quot;0.3.3~&quot;} ] synopsis: &quot;Infotheo&quot; description: &quot;&quot;&quot; a Coq formalization of information theory and linear error-correcting codes &quot;&quot;&quot; tags: [ &quot;category:Computer Science/Data Types and Data Structures&quot; &quot;keyword: information theory&quot; &quot;keyword: probability&quot; &quot;keyword: error-correcting codes&quot; &quot;logpath:infotheo&quot; &quot;date:2020-10-13&quot; ] url { http: &quot;https://github.com/affeldt-aist/infotheo/archive/0.2.tar.gz&quot; checksum: &quot;sha512=67cc4fe45ccc42736c3b15b53be07ed355a680619bebec9ba33d192da91594eb472c9501178d2dd87dbc653102c8d6d80b8892c3f7f60dd4d04e6b0b0104a136&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-infotheo.0.2 coq.8.15.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.15.1). The following dependencies couldn&#39;t be met: - coq-infotheo -&gt; coq &lt; 8.13~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-infotheo.0.2</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "4072c5d92b6e6e363ec434975bb9f308", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 159, "avg_line_length": 39.95238095238095, "alnum_prop": 0.5571447490398622, "repo_name": "coq-bench/coq-bench.github.io", "id": "d18c13128d8593dbf2d54a6016d7864c84a2a91e", "size": "7576", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.15.1/infotheo/0.2.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package ca.uhn.fhir.rest.gclient; import org.hl7.fhir.instance.model.api.IBaseConformance; public interface IFetchConformanceTyped<T extends IBaseConformance> extends IClientExecutable<IFetchConformanceTyped<T>, T> { }
{ "content_hash": "3e7af42de65f1e33e3cecff77df13e28", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 126, "avg_line_length": 25, "alnum_prop": 0.8177777777777778, "repo_name": "botunge/hapi-fhir", "id": "4ff951ffd099fd3dcf451cdb3cb362dd7a1a6af8", "size": "898", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/IFetchConformanceTyped.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3861" }, { "name": "CSS", "bytes": "228170" }, { "name": "HTML", "bytes": "208718" }, { "name": "Java", "bytes": "40432052" }, { "name": "JavaScript", "bytes": "23712" }, { "name": "Ruby", "bytes": "238454" }, { "name": "Shell", "bytes": "35414" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <!--basic styles--> <link href="asset/css/bootstrap.css" rel="stylesheet" /> <link rel="stylesheet" href="asset/css/dexter.min.css" /> <link rel="stylesheet" href="asset/css/font-awesome.min.css" /> <!--[if IE 7]> <link rel="stylesheet" href="asset/css/font-awesome-ie7.min.css"> <![endif]--> <link rel="stylesheet" href="asset/css/prettify.css" /> <script src="asset/js/jquery-2.0.3.min.js"></script> <!--[if IE]> <script src="asset/js/jquery.min.js"></script> <![endif]--> <script src="asset/js/prettify.js"></script> <script type="text/javascript"> $(function() { window.prettyPrint && prettyPrint(); $('#id-check-horizontal').removeAttr('checked').on('click', function(){ $('#dt-list-1').toggleClass('dl-horizontal').prev().html(this.checked ? '&lt;dl class="dl-horizontal"&gt;' : '&lt;dl&gt;'); }); }) </script> </head> <body> <div class="space-12"></div> <div class="table-grid-info table-grid-info-striped"> <div class="table-grid-row"> <div class="table-grid-label"> Checker Code</div> <div class="table-grid-value"><h5 class="header blue"><i class="fa fa-bug"></i>&nbsp; USLEEP</h5> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Description </div> <div class="table-grid-value-highlight"><i class="fa fa-th"></i>&nbsp; Calling risky function Usleep(). </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Severity </div> <div class="table-grid-value"> Critical </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Detector / Bug Pattern </div> <div class="table-grid-value"> Calling risky function "usleep()" (SECURE_CODING). </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> More Information </div> <div class="table-grid-value"> Calling risky function "usleep()" (SECURE_CODING). secure_coding:Using "usleep" can cause a performance problem when done incorrectly. For better performance , VD recommends NOT to use less than 10,000 us.' if you use 10,000 us or more you can ignore this warning. </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Bad Code </div> <div class="table-grid-value"> <pre class="prettyprint linenums warning"> void my_func(void) { usleep(500); int value =1000; usleep(value); } </pre> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Good Code </div> <div class="table-grid-value"> <pre class="prettyprint linenums correct"> void my_func(void) { usleep(50000); int value =20000; usleep(value); } </pre> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> CWE ID </div> <div class="table-grid-value"> <a href="asset/CWE_ID.html" target="_blank">0 </a> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> Code Review Asset </div> <div class="table-grid-value"> </div> </div> <div class="table-grid-row"> <div class="table-grid-label"> URLs </div> <div class="table-grid-value"> <i class="fa fa-link"></i>&nbsp; <!-- <a target="_blank" href="http://stackoverflow.com/questions/12721200/warnings-on-too-small-array-sizes-to-functions-in-c-c"> http://stackoverflow.com/questions/12721200/warnings-on-too-small-array-sizes-to-functions-in-c-c </a> --> </div> </div> </div> <div class="space-20"></div> </body> <html>
{ "content_hash": "ea23c78d2e230b9c1bd07952008aec1b", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 155, "avg_line_length": 27.37313432835821, "alnum_prop": 0.6142311886586695, "repo_name": "Samsung/Dexter", "id": "f4950eef32cee5bd1f2a4db832c921b82eb2c8cc", "size": "3668", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "project/dexter-server/public/tool/dexter-vd-cpp/CPP/help/USLEEP.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "246" }, { "name": "C", "bytes": "160649" }, { "name": "C#", "bytes": "803354" }, { "name": "C++", "bytes": "934804" }, { "name": "CSS", "bytes": "140317" }, { "name": "Dockerfile", "bytes": "250" }, { "name": "EmberScript", "bytes": "96193" }, { "name": "HTML", "bytes": "2858148" }, { "name": "Java", "bytes": "1777526" }, { "name": "JavaScript", "bytes": "2288146" }, { "name": "Perl", "bytes": "4890" }, { "name": "Python", "bytes": "9200" }, { "name": "Ruby", "bytes": "565" }, { "name": "Shell", "bytes": "10474" } ], "symlink_target": "" }
<?php /** * @version V4.50 6 July 2004 (c) 2000-2011 John Lim (jlim#natsoft.com). All rights reserved. * Released under both BSD license and Lesser GPL library license. * Whenever there is any discrepancy between the two licenses, * the BSD license will take precedence. * * Set tabs to 4 for best viewing. * * Latest version is available at http://php.weblogs.com * * Test GetUpdateSQL and GetInsertSQL. */ error_reporting(E_ALL); function testsql() { include('../adodb.inc.php'); include('../tohtml.inc.php'); global $ADODB_FORCE_TYPE; //========================== // This code tests an insert $sql = " SELECT * FROM ADOXYZ WHERE id = -1"; // Select an empty record from the database #$conn = ADONewConnection("mssql"); // create a connection #$conn->PConnect("", "sa", "natsoft", "northwind"); // connect to MySQL, testdb $conn = ADONewConnection("mysql"); // create a connection $conn->PConnect("localhost", "root", "", "test"); // connect to MySQL, testdb #$conn = ADONewConnection('oci8po'); #$conn->Connect('','scott','natsoft'); if (PHP_VERSION >= 5) { $connstr = "mysql:dbname=northwind"; $u = 'root';$p=''; $conn = ADONewConnection('pdo'); $conn->Connect($connstr, $u, $p); } //$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; $conn->debug=1; $conn->Execute("delete from adoxyz where lastname like 'Smi%'"); $rs = $conn->Execute($sql); // Execute the query and get the empty recordset $record = array(); // Initialize an array to hold the record data to insert if (strpos($conn->databaseType,'mysql')===false) $record['id'] = 751; $record["firstname"] = 'Jann'; $record["lastname"] = "Smitts"; $record["created"] = time(); $insertSQL = $conn->GetInsertSQL($rs, $record); $conn->Execute($insertSQL); // Insert the record into the database if (strpos($conn->databaseType,'mysql')===false) $record['id'] = 752; // Set the values for the fields in the record $record["firstname"] = 'anull'; $record["lastname"] = "Smith\$@//"; $record["created"] = time(); if (isset($_GET['f'])) $ADODB_FORCE_TYPE = $_GET['f']; //$record["id"] = -1; // Pass the empty recordset and the array containing the data to insert // into the GetInsertSQL function. The function will process the data and return // a fully formatted insert sql statement. $insertSQL = $conn->GetInsertSQL($rs, $record); $conn->Execute($insertSQL); // Insert the record into the database $insertSQL2 = $conn->GetInsertSQL($table='ADOXYZ', $record); if ($insertSQL != $insertSQL2) echo "<p><b>Walt's new stuff failed</b>: $insertSQL2</p>"; //========================== // This code tests an update $sql = " SELECT * FROM ADOXYZ WHERE lastname=".$conn->Param('var'). " ORDER BY 1"; // Select a record to update $varr = array('var'=>$record['lastname'].''); $rs = $conn->Execute($sql,$varr); // Execute the query and get the existing record to update if (!$rs || $rs->EOF) print "<p><b>No record found!</b></p>"; $record = array(); // Initialize an array to hold the record data to update // Set the values for the fields in the record $record["firstName"] = "Caroline".rand(); //$record["lasTname"] = ""; // Update Caroline's lastname from Miranda to Smith $record["creAted"] = '2002-12-'.(rand()%30+1); $record['num'] = ''; // Pass the single record recordset and the array containing the data to update // into the GetUpdateSQL function. The function will process the data and return // a fully formatted update sql statement. // If the data has not changed, no recordset is returned $updateSQL = $conn->GetUpdateSQL($rs, $record); $conn->Execute($updateSQL,$varr); // Update the record in the database if ($conn->Affected_Rows() != 1)print "<p><b>Error1 </b>: Rows Affected=".$conn->Affected_Rows().", should be 1</p>"; $record["firstName"] = "Caroline".rand(); $record["lasTname"] = "Smithy Jones"; // Update Caroline's lastname from Miranda to Smith $record["creAted"] = '2002-12-'.(rand()%30+1); $record['num'] = 331; $updateSQL = $conn->GetUpdateSQL($rs, $record); $conn->Execute($updateSQL,$varr); // Update the record in the database if ($conn->Affected_Rows() != 1)print "<p><b>Error 2</b>: Rows Affected=".$conn->Affected_Rows().", should be 1</p>"; $rs = $conn->Execute("select * from ADOXYZ where lastname like 'Sm%'"); //adodb_pr($rs); rs2html($rs); $record["firstName"] = "Carol-new-".rand(); $record["lasTname"] = "Smithy"; // Update Caroline's lastname from Miranda to Smith $record["creAted"] = '2002-12-'.(rand()%30+1); $record['num'] = 331; $conn->AutoExecute('ADOXYZ',$record,'UPDATE', "lastname like 'Sm%'"); $rs = $conn->Execute("select * from ADOXYZ where lastname like 'Sm%'"); //adodb_pr($rs); rs2html($rs); } testsql(); ?>
{ "content_hash": "2b30ed7c7e8baa6f55e02f6c2511bb63", "timestamp": "", "source": "github", "line_count": 143, "max_line_length": 117, "avg_line_length": 32.63636363636363, "alnum_prop": 0.6580244268266552, "repo_name": "hsarmiento/peoplelocator", "id": "ca2ac58e6c1d627e194ca36b70484031f4cabb1f", "size": "4667", "binary": false, "copies": "54", "ref": "refs/heads/master", "path": "3rd/adodb/tests/test4.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "327456" }, { "name": "Erlang", "bytes": "635" }, { "name": "HTML", "bytes": "1277273" }, { "name": "JavaScript", "bytes": "230779" }, { "name": "PHP", "bytes": "4840500" }, { "name": "Perl", "bytes": "13449" }, { "name": "Shell", "bytes": "2585" }, { "name": "XSLT", "bytes": "28086" } ], "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. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// when users type, we chain all those changes as incremental parsing requests /// but doesn't actually realize those changes. it is saved as a pending request. /// so if nobody asks for final parse tree, those chain can keep grow. /// we do this since Roslyn is lazy at the core (don't do work if nobody asks for it) /// /// but certain host such as VS, we have this (BackgroundParser) which preemptively /// trying to realize such trees for open/active files expecting users will use them soonish. /// </summary> internal sealed class BackgroundParser { private readonly Workspace _workspace; private readonly TaskQueue _taskQueue; private readonly IDocumentTrackingService _documentTrackingService; private readonly ReaderWriterLockSlim _stateLock = new(LockRecursionPolicy.NoRecursion); private readonly object _parseGate = new(); private ImmutableDictionary<DocumentId, CancellationTokenSource> _workMap = ImmutableDictionary.Create<DocumentId, CancellationTokenSource>(); public bool IsStarted { get; private set; } public BackgroundParser(Workspace workspace) { _workspace = workspace; var listenerProvider = workspace.Services.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>(); _taskQueue = new TaskQueue(listenerProvider.GetListener(), TaskScheduler.Default); _documentTrackingService = workspace.Services.GetRequiredService<IDocumentTrackingService>(); _documentTrackingService.ActiveDocumentChanged += OnActiveDocumentChanged; _workspace.WorkspaceChanged += OnWorkspaceChanged; workspace.DocumentOpened += OnDocumentOpened; workspace.DocumentClosed += OnDocumentClosed; } private void OnActiveDocumentChanged(object sender, DocumentId activeDocumentId) => Parse(_workspace.CurrentSolution.GetDocument(activeDocumentId)); private void OnDocumentOpened(object sender, DocumentEventArgs args) => Parse(args.Document); private void OnDocumentClosed(object sender, DocumentEventArgs args) => CancelParse(args.Document.Id); private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { switch (args.Kind) { case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionAdded: CancelAllParses(); break; case WorkspaceChangeKind.DocumentRemoved: CancelParse(args.DocumentId); break; case WorkspaceChangeKind.DocumentChanged: ParseIfOpen(args.NewSolution.GetDocument(args.DocumentId)); break; case WorkspaceChangeKind.ProjectChanged: var oldProject = args.OldSolution.GetProject(args.ProjectId); var newProject = args.NewSolution.GetProject(args.ProjectId); // Perf optimization: don't rescan the new project if parse options didn't change. When looking // at the perf of changing configurations that resulted in many reference additions/removals, // this consumed around 2%-3% of the trace after some other optimizations I did. Most of that // was actually walking the documents list since this was causing all the Documents to be realized. // Since this is on the UI thread, it's best just to not do the work if we don't need it. if (oldProject.SupportsCompilation && !object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { foreach (var doc in newProject.Documents) { ParseIfOpen(doc); } } break; } } public void Start() { using (_stateLock.DisposableRead()) { if (!IsStarted) { IsStarted = true; } } } public void Stop() { using (_stateLock.DisposableWrite()) { if (IsStarted) { CancelAllParses_NoLock(); IsStarted = false; } } } public void CancelAllParses() { using (_stateLock.DisposableWrite()) { CancelAllParses_NoLock(); } } private void CancelAllParses_NoLock() { _stateLock.AssertCanWrite(); foreach (var tuple in _workMap) { tuple.Value.Cancel(); } _workMap = ImmutableDictionary.Create<DocumentId, CancellationTokenSource>(); } public void CancelParse(DocumentId documentId) { if (documentId != null) { using (_stateLock.DisposableWrite()) { if (_workMap.TryGetValue(documentId, out var cancellationTokenSource)) { cancellationTokenSource.Cancel(); _workMap = _workMap.Remove(documentId); } } } } public void Parse(Document document) { if (document != null) { lock (_parseGate) { CancelParse(document.Id); if (SolutionCrawlerOptions.GetBackgroundAnalysisScope(document.Project) == BackgroundAnalysisScope.ActiveFile && _documentTrackingService.TryGetActiveDocument() != document.Id) { // Avoid performing any background parsing for non-active files // if the user has explicitly set the background analysis scope // to only analyze active files. // Note that we bail out after executing CancelParse to ensure // all the current background parsing tasks are cancelled. return; } if (IsStarted) { _ = ParseDocumentAsync(document); } } } } private void ParseIfOpen(Document document) { if (document != null && document.IsOpen()) { Parse(document); } } private Task ParseDocumentAsync(Document document) { var cancellationTokenSource = new CancellationTokenSource(); using (_stateLock.DisposableWrite()) { _workMap = _workMap.Add(document.Id, cancellationTokenSource); } var cancellationToken = cancellationTokenSource.Token; // We end up creating a chain of parsing tasks that each attempt to produce // the appropriate syntax tree for any given document. Once we start work to create // the syntax tree for a given document, we don't want to stop. // Otherwise we can end up in the unfortunate scenario where we keep cancelling work, // and then having the next task re-do the work we were just in the middle of. // By not cancelling, we can reuse the useful results of previous tasks when performing later steps in the chain. // // we still cancel whole task if the task didn't start yet. we just don't cancel if task is started but not finished yet. var task = _taskQueue.ScheduleTask( "BackgroundParser.ParseDocumentAsync", () => document.GetSyntaxTreeAsync(CancellationToken.None), cancellationToken); // Always ensure that we mark this work as done from the workmap. return task.SafeContinueWith( _ => { using (_stateLock.DisposableWrite()) { // Check that we are still the active parse in the workmap before we remove it. // Concievably if this continuation got delayed and another parse was put in, we might // end up removing the tracking for another in-flight task. if (_workMap.TryGetValue(document.Id, out var sourceInMap) && sourceInMap == cancellationTokenSource) { _workMap = _workMap.Remove(document.Id); } } }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); } } }
{ "content_hash": "d50775dc4953306bd1616519c3b6d568", "timestamp": "", "source": "github", "line_count": 238, "max_line_length": 150, "avg_line_length": 40.37394957983193, "alnum_prop": 0.5695701946092205, "repo_name": "wvdd007/roslyn", "id": "9f70d143d7a9cf574a8b6258fa92604af110424c", "size": "9611", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Features/Core/Portable/Workspace/BackgroundParser.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8935" }, { "name": "C#", "bytes": "72612993" }, { "name": "C++", "bytes": "3744" }, { "name": "F#", "bytes": "421" }, { "name": "PowerShell", "bytes": "8550" }, { "name": "Shell", "bytes": "7164" }, { "name": "Visual Basic", "bytes": "58468283" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2010-2013 Evolveum ~ ~ 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. --> <!-- Object modification description that is changing user "jack" by adding a new account --> <objectDelta xmlns:c='http://midpoint.evolveum.com/xml/ns/public/common/common-3' xmlns="http://prism.evolveum.com/xml/ns/public/types-3"> <changeType>modify</changeType> <objectType>c:UserType</objectType> <oid>will-be-replaced</oid> <!-- Let's honor Jack with a proper title --> <itemDelta> <modificationType>replace</modificationType> <path>c:employeeType</path> <value>boss</value> </itemDelta> <itemDelta> <modificationType>replace</modificationType> <path>c:givenName</path> <value>don</value> </itemDelta> </objectDelta>
{ "content_hash": "9ae3027668c759e08c919c04f21c95cd", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 93, "avg_line_length": 36.21621621621622, "alnum_prop": 0.6992537313432836, "repo_name": "rpudil/midpoint", "id": "71d5be564ec0d566962d0d687cfeaf61f2150f7f", "size": "1340", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "testing/consistency-mechanism/src/test/resources/request/user-modify-employeeType-givenName.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "232572" }, { "name": "HTML", "bytes": "590602" }, { "name": "Java", "bytes": "22468226" }, { "name": "JavaScript", "bytes": "15908" }, { "name": "PLSQL", "bytes": "2171" }, { "name": "PLpgSQL", "bytes": "7936" }, { "name": "Shell", "bytes": "52" } ], "symlink_target": "" }
/** * Toolbar * * @param {Object} parent Reference to instance of Editor instance * @param {Element} container Reference to the toolbar container element * * @example * <div id="toolbar"> * <a data-wysihtml5-command="createLink">insert link</a> * <a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1">insert h1</a> * </div> * * <script> * var toolbar = new wysihtml5.toolbar.Toolbar(editor, document.getElementById("toolbar")); * </script> */ (function(wysihtml5) { var CLASS_NAME_COMMAND_DISABLED = "wysihtml5-command-disabled", CLASS_NAME_COMMANDS_DISABLED = "wysihtml5-commands-disabled", CLASS_NAME_COMMAND_ACTIVE = "wysihtml5-command-active", CLASS_NAME_ACTION_ACTIVE = "wysihtml5-action-active", dom = wysihtml5.dom; wysihtml5.toolbar.Toolbar = Base.extend( /** @scope wysihtml5.toolbar.Toolbar.prototype */ { constructor: function(editor, container, showOnInit) { this.editor = editor; this.container = typeof(container) === "string" ? document.getElementById(container) : container; this.composer = editor.composer; this._getLinks("command"); this._getLinks("action"); this._observe(); if (showOnInit) { this.show(); } if (editor.config.classNameCommandDisabled != null) { CLASS_NAME_COMMAND_DISABLED = editor.config.classNameCommandDisabled; } if (editor.config.classNameCommandsDisabled != null) { CLASS_NAME_COMMANDS_DISABLED = editor.config.classNameCommandsDisabled; } if (editor.config.classNameCommandActive != null) { CLASS_NAME_COMMAND_ACTIVE = editor.config.classNameCommandActive; } if (editor.config.classNameActionActive != null) { CLASS_NAME_ACTION_ACTIVE = editor.config.classNameActionActive; } var speechInputLinks = this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"), length = speechInputLinks.length, i = 0; for (; i<length; i++) { new wysihtml5.toolbar.Speech(this, speechInputLinks[i]); } }, _getLinks: function(type) { var links = this[type + "Links"] = wysihtml5.lang.array(this.container.querySelectorAll("[data-wysihtml5-" + type + "]")).get(), length = links.length, i = 0, mapping = this[type + "Mapping"] = {}, link, group, name, value, dialog, tracksBlankValue; for (; i<length; i++) { link = links[i]; name = link.getAttribute("data-wysihtml5-" + type); value = link.getAttribute("data-wysihtml5-" + type + "-value"); tracksBlankValue = link.getAttribute("data-wysihtml5-" + type + "-blank-value"); group = this.container.querySelector("[data-wysihtml5-" + type + "-group='" + name + "']"); dialog = this._getDialog(link, name); mapping[name + ":" + value] = { link: link, group: group, name: name, value: value, tracksBlankValue: tracksBlankValue, dialog: dialog, state: false }; } }, _getDialog: function(link, command) { var that = this, dialogElement = this.container.querySelector("[data-wysihtml5-dialog='" + command + "']"), dialog, caretBookmark; if (dialogElement) { if (wysihtml5.toolbar["Dialog_" + command]) { dialog = new wysihtml5.toolbar["Dialog_" + command](link, dialogElement); } else { dialog = new wysihtml5.toolbar.Dialog(link, dialogElement); } dialog.on("show", function() { caretBookmark = that.composer.selection.getBookmark(); that.editor.fire("show:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); dialog.on("save", function(attributes) { if (caretBookmark) { that.composer.selection.setBookmark(caretBookmark); } that._execCommand(command, attributes); that.editor.fire("save:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); dialog.on("cancel", function() { that.editor.focus(false); that.editor.fire("cancel:dialog", { command: command, dialogContainer: dialogElement, commandLink: link }); }); } return dialog; }, /** * @example * var toolbar = new wysihtml5.Toolbar(); * // Insert a <blockquote> element or wrap current selection in <blockquote> * toolbar.execCommand("formatBlock", "blockquote"); */ execCommand: function(command, commandValue) { if (this.commandsDisabled) { return; } var commandObj = this.commandMapping[command + ":" + commandValue]; // Show dialog when available if (commandObj && commandObj.dialog && !commandObj.state) { commandObj.dialog.show(); } else { this._execCommand(command, commandValue); } }, _execCommand: function(command, commandValue) { // Make sure that composer is focussed (false => don't move caret to the end) this.editor.focus(false); this.composer.commands.exec(command, commandValue); this._updateLinkStates(); }, execAction: function(action) { var editor = this.editor; if (action === "change_view") { if (editor.currentView === editor.textarea || editor.currentView === "source") { editor.fire("change_view", "composer"); } else { editor.fire("change_view", "textarea"); } } if (action == "showSource") { editor.fire("showSource"); } }, _observe: function() { var that = this, editor = this.editor, container = this.container, links = this.commandLinks.concat(this.actionLinks), length = links.length, i = 0; for (; i<length; i++) { // 'javascript:;' and unselectable=on Needed for IE, but done in all browsers to make sure that all get the same css applied // (you know, a:link { ... } doesn't match anchors with missing href attribute) if (links[i].nodeName === "A") { dom.setAttributes({ href: "javascript:;", unselectable: "on" }).on(links[i]); } else { dom.setAttributes({ unselectable: "on" }).on(links[i]); } } // Needed for opera and chrome dom.delegate(container, "[data-wysihtml5-command], [data-wysihtml5-action]", "mousedown", function(event) { event.preventDefault(); }); dom.delegate(container, "[data-wysihtml5-command]", "click", function(event) { var link = this, command = link.getAttribute("data-wysihtml5-command"), commandValue = link.getAttribute("data-wysihtml5-command-value"); that.execCommand(command, commandValue); event.preventDefault(); }); dom.delegate(container, "[data-wysihtml5-action]", "click", function(event) { var action = this.getAttribute("data-wysihtml5-action"); that.execAction(action); event.preventDefault(); }); editor.on("interaction:composer", function() { that._updateLinkStates(); }); editor.on("focus:composer", function() { that.bookmark = null; }); if (this.editor.config.handleTables) { editor.on("tableselect:composer", function() { that.container.querySelectorAll('[data-wysihtml5-hiddentools="table"]')[0].style.display = ""; }); editor.on("tableunselect:composer", function() { that.container.querySelectorAll('[data-wysihtml5-hiddentools="table"]')[0].style.display = "none"; }); } editor.on("change_view", function(currentView) { // Set timeout needed in order to let the blur event fire first setTimeout(function() { that.commandsDisabled = (currentView !== "composer"); that._updateLinkStates(); if (that.commandsDisabled) { dom.addClass(container, CLASS_NAME_COMMANDS_DISABLED); } else { dom.removeClass(container, CLASS_NAME_COMMANDS_DISABLED); } }, 0); }); }, _updateLinkStates: function() { var commandMapping = this.commandMapping, commandblankMapping = this.commandblankMapping, actionMapping = this.actionMapping, i, state, action, command; // every millisecond counts... this is executed quite often for (i in commandMapping) { command = commandMapping[i]; if (this.commandsDisabled) { state = false; dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { command.dialog.hide(); } } else { state = this.composer.commands.state(command.name, command.value); dom.removeClass(command.link, CLASS_NAME_COMMAND_DISABLED); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_DISABLED); } } if (command.state === state && !command.tracksBlankValue) { continue; } command.state = state; if (state) { if (command.tracksBlankValue) { dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); } else { dom.addClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.addClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { if (typeof(state) === "object" || wysihtml5.lang.object(state).isArray()) { if (!command.dialog.multiselect && wysihtml5.lang.object(state).isArray()) { // Grab first and only object/element in state array, otherwise convert state into boolean // to avoid showing a dialog for multiple selected elements which may have different attributes // eg. when two links with different href are selected, the state will be an array consisting of both link elements // but the dialog interface can only update one state = state.length === 1 ? state[0] : true; command.state = state; } command.dialog.show(state); } else { command.dialog.hide(); } } } } else { if (command.tracksBlankValue) { dom.addClass(command.link, CLASS_NAME_COMMAND_ACTIVE); } else { dom.removeClass(command.link, CLASS_NAME_COMMAND_ACTIVE); if (command.group) { dom.removeClass(command.group, CLASS_NAME_COMMAND_ACTIVE); } if (command.dialog) { command.dialog.hide(); } } } } for (i in actionMapping) { action = actionMapping[i]; if (action.name === "change_view") { action.state = this.editor.currentView === this.editor.textarea || this.editor.currentView === "source"; if (action.state) { dom.addClass(action.link, CLASS_NAME_ACTION_ACTIVE); } else { dom.removeClass(action.link, CLASS_NAME_ACTION_ACTIVE); } } } }, show: function() { this.container.style.display = ""; }, hide: function() { this.container.style.display = "none"; } }); })(wysihtml5);
{ "content_hash": "1f6cd6b31f13e9e2b48e94b2edf0fc2d", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 141, "avg_line_length": 36.00898203592814, "alnum_prop": 0.5700507192150993, "repo_name": "uxtx/wysihtml", "id": "805c99bb8dd805d07b530e2326fa7eab89593b0c", "size": "12027", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/toolbar/toolbar.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1567" }, { "name": "HTML", "bytes": "55116" }, { "name": "JavaScript", "bytes": "1782296" } ], "symlink_target": "" }
var Cell = require('./Cell'); function Food() { Cell.apply(this, Array.prototype.slice.call(arguments)); this.cellType = 1; } module.exports = Food; Food.prototype = new Cell(); // Main Functions Food.prototype.onAdd = function (gameServer) { gameServer.nodesFood.push(this); }; Food.prototype.onRemove = function (gameServer) { // Remove from list of foods var index = gameServer.nodesFood.indexOf(this); if (index != -1) { gameServer.nodesFood.splice(index, 1); } };
{ "content_hash": "591605f85ff675b59d56941c143e82db", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 60, "avg_line_length": 21.458333333333332, "alnum_prop": 0.6563106796116505, "repo_name": "proxiemind/MultiOgar-Edited", "id": "086505e8c6c78dad1431119863bb8a69be5c8c51", "size": "515", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/entity/Food.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "219" }, { "name": "HTML", "bytes": "6234" }, { "name": "JavaScript", "bytes": "283142" }, { "name": "Shell", "bytes": "6599" } ], "symlink_target": "" }
package edu.wisc.mum.status.dao; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.List; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.UnmarshalException; import javax.xml.bind.Unmarshaller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; import org.springframework.util.Assert; /** * Base logic for loading unmarshalling an XML document via JAXB and only reloading the cached object model when needed. * The class attempts to monitor the lastModified date of the {@link Resource} to determine when to reload. If that fails * the resource is reloaded periodically as specified by the {@link #setNoLastModifiedReloadPeriod(long)} property. * * The class determines the return type and the base package to use for the {@link JAXBContext#newInstance(String)} call * via the loadedType parameter provided to the constructor. * * @author Eric Dalquist * @version $Revision: 297 $ */ public abstract class AbstractCachingJaxbLoader<T> implements InitializingBean, DisposableBean { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private final JAXBContext jaxbContext; private final Class<T> loadedType; private final ReadWriteLock lock = new ReentrantReadWriteLock(); private Resource mappedXmlResource; private WatchService watchService; private T unmarshalledObject; protected AbstractCachingJaxbLoader(Class<T> loadedType) { Assert.notNull(loadedType, "loadedType can not be null"); this.loadedType = loadedType; final String filterDisplayPackage = this.loadedType.getPackage().getName(); try { jaxbContext = JAXBContext.newInstance(filterDisplayPackage); } catch (JAXBException e) { throw new RuntimeException("Failed to create " + JAXBContext.class + " to unmarshal " + this.loadedType, e); } } public Resource getMappedXmlResource() { return mappedXmlResource; } /** * The XML resource to load. */ public void setMappedXmlResource(Resource mappedXmlResource) { this.mappedXmlResource = mappedXmlResource; } @Override public void afterPropertiesSet() throws Exception { //Setup file watcher final URI xmlUri = this.mappedXmlResource.getURI(); final Path xmlParentPath = Paths.get(xmlUri).getParent(); watchService = FileSystems.getDefault().newWatchService(); xmlParentPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY); } @Override public void destroy() throws Exception { watchService.close(); } /** * Loads and unmarshalls the XML as needed, returning the unmarshalled object */ protected final T getUnmarshalledObject() { final WatchKey changedKey = watchService.poll(); try { if (changedKey != null || this.unmarshalledObject == null) { //Read all pending events List<WatchEvent<?>> watchEvents = null; if (changedKey != null) { watchEvents = changedKey.pollEvents(); } if (this.logger.isDebugEnabled()) { if (this.unmarshalledObject == null) { this.logger.debug("Performing first load of {}", this.loadedType.getName()); } else { this.logger.debug("Load of {} triggered by WatchKey {} for events {}", this.loadedType.getName(), changedKey, watchEvents); } } this.lock.writeLock().lock(); try { this.unmarshalledObject = readAndUnmarshall(); return this.unmarshalledObject; } finally { this.lock.writeLock().unlock(); } } else { this.lock.readLock().lock(); try { this.logger.trace("Returning cached instance of {}", this.loadedType.getName()); return this.unmarshalledObject; } finally { this.lock.readLock().unlock(); } } } finally { if (changedKey != null) { changedKey.reset(); } } } private final T readAndUnmarshall() { final long start = System.currentTimeMillis(); final Unmarshaller unmarshaller; try { unmarshaller = jaxbContext.createUnmarshaller(); } catch (JAXBException e) { throw new RuntimeException("Failed to create " + Unmarshaller.class + " to unmarshal " + this.loadedType, e); } try (final InputStream xmlInputStream = this.mappedXmlResource.getInputStream()) { @SuppressWarnings("unchecked") final T unmarshalledObject = (T)unmarshaller.unmarshal(xmlInputStream); this.postProcessUnmarshalling(unmarshalledObject); this.logger.debug("Loaded {} in {}ms", this.loadedType.getName(), System.currentTimeMillis() - start); return unmarshalledObject; } catch (IOException e) { throw new RuntimeException("Failed to read XML from " + this.mappedXmlResource, e); } catch (UnmarshalException e) { throw new RuntimeException("Failed to unmarshal XML in " + this.mappedXmlResource + " to " + this.loadedType, e); } catch (JAXBException e) { throw new RuntimeException("Unexpected JAXB error while unmarshalling " + this.mappedXmlResource, e); } } /** * Allow sub-classes to do specific handling of of the unmarshalled object before it is returned by a call to * {@link #getUnmarshalledObject()} that triggered a reload. If this method throws an exception the reload will * fail, the object will not be cached, and the exception will be propagated to the caller of {@link #getUnmarshalledObject()}. * * This method is called within the synchronization block of {@link #getUnmarshalledObject()}. */ protected void postProcessUnmarshalling(T unmarshalledObject) { } }
{ "content_hash": "0b6586b380e9683f3aced110c480293a", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 146, "avg_line_length": 38.729281767955804, "alnum_prop": 0.6332382310984308, "repo_name": "UW-Madison-DoIT/mumstatus", "id": "7ef4931f7dcf031e4f883b0984148070d65e28df", "size": "7836", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/edu/wisc/mum/status/dao/AbstractCachingJaxbLoader.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2110" }, { "name": "Java", "bytes": "50176" } ], "symlink_target": "" }
<?php namespace SvnPQA\controller; use Lite\Core\Hooker; use Lite\CRUD\AbstractController; use Lite\DB\Query; use Lite\DB\Record; use Lite\Logger\Logger; use Lite\Logger\Message\CommonMessage; use function Lite\func\dump; abstract class BaseController extends AbstractController { public function __construct($ctrl=null, $act=null){ Hooker::add(Record::EVENT_AFTER_DB_QUERY, function($sql){ if(Query::isWriteOperation($sql)){ Logger::instance('CMS')->info(new CommonMessage('DB WRITE', array( 'sql' => $sql ))); } }); } /** * rebind auto template * @param $ctrl * @param $act * @return string */ public static function __getTemplate($ctrl, $act){ $f = parent::__getTemplate($ctrl, $act); if(!is_file($f)){ $class = get_called_class(); $interfaces = class_implements($class, true); if($interfaces['Lite\CRUD\ControllerInterface']){ $f = parent::__getTemplate('crud', $act); } } return $f; } }
{ "content_hash": "ea4087a69faff8c0f08c4d5f7e64b5b2", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 70, "avg_line_length": 26.94871794871795, "alnum_prop": 0.60418648905804, "repo_name": "sasumi/SvnPQA", "id": "74eabdf83530bd24151904b686e77353a94c2e97", "size": "1051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Controller/BaseController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "422" }, { "name": "CSS", "bytes": "6404" }, { "name": "JavaScript", "bytes": "66747" }, { "name": "PHP", "bytes": "617525" } ], "symlink_target": "" }
package org.apache.river.test.spec.activation.util; import java.util.logging.Logger; import java.util.logging.Level; import net.jini.activation.arg.ActivationSystem; import net.jini.activation.arg.ActivationDesc; import net.jini.activation.arg.ActivationID; import net.jini.activation.arg.ActivationGroupDesc; import net.jini.activation.arg.ActivationGroupID; import net.jini.activation.arg.ActivationInstantiator; import net.jini.activation.arg.ActivationMonitor; import net.jini.activation.arg.ActivationException; import net.jini.activation.arg.UnknownGroupException; import net.jini.activation.arg.UnknownObjectException; import java.rmi.RemoteException; /** * A fake implementation of the <code>ActivationSystem</code> * abstract class for test purposes. */ public class FakeActivationSystem implements ActivationSystem { Logger logger; public FakeActivationSystem(Logger logger) { super(); this.logger = logger; logger.log(Level.FINEST, "(" + logger + ")"); } public ActivationID registerObject(ActivationDesc desc) throws ActivationException, UnknownGroupException, RemoteException { logger.log(Level.FINEST, ""); return null; }; public void unregisterObject(ActivationID id) throws ActivationException, UnknownObjectException, RemoteException { logger.log(Level.FINEST, ""); }; public ActivationGroupID registerGroup(ActivationGroupDesc desc) throws ActivationException, RemoteException { logger.log(Level.FINEST, ""); return null; }; public ActivationMonitor activeGroup(ActivationGroupID id, ActivationInstantiator group, long incarnation) throws UnknownGroupException, ActivationException, RemoteException { logger.log(Level.FINEST, ""); return null; }; public void unregisterGroup(ActivationGroupID id) throws ActivationException, UnknownGroupException, RemoteException { logger.log(Level.FINEST, ""); return; }; public void shutdown() throws RemoteException { }; public ActivationDesc setActivationDesc(ActivationID id, ActivationDesc desc) throws ActivationException, UnknownObjectException, UnknownGroupException, RemoteException { logger.log(Level.FINEST, ""); return null; }; public ActivationGroupDesc setActivationGroupDesc(ActivationGroupID id, ActivationGroupDesc desc) throws ActivationException, UnknownGroupException, RemoteException { logger.log(Level.FINEST, ""); return null; }; public ActivationDesc getActivationDesc(ActivationID id) throws ActivationException, UnknownObjectException, RemoteException { logger.log(Level.FINEST, ""); return null; }; public ActivationGroupDesc getActivationGroupDesc(ActivationGroupID id) throws ActivationException, UnknownGroupException, RemoteException { logger.log(Level.FINEST, ""); return null; }; }
{ "content_hash": "2215f6b2b05d3e014eaa1d9d22095dbd", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 80, "avg_line_length": 34.20879120879121, "alnum_prop": 0.7076774815290716, "repo_name": "pfirmstone/JGDMS", "id": "5ab91fb12ceadbc0d122bf4dd9e17376c0cba413", "size": "3919", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "qa/src/org/apache/river/test/spec/activation/util/FakeActivationSystem.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "38260" }, { "name": "Groovy", "bytes": "30510" }, { "name": "HTML", "bytes": "107806458" }, { "name": "Java", "bytes": "24863323" }, { "name": "JavaScript", "bytes": "1702" }, { "name": "Makefile", "bytes": "3032" }, { "name": "Roff", "bytes": "863" }, { "name": "Shell", "bytes": "68247" } ], "symlink_target": "" }
import tests.expsmooth.expsmooth_dataset_test as exps exps.analyze_dataset("frexport.csv" , 2); exps.analyze_dataset("frexport.csv" , 4); exps.analyze_dataset("frexport.csv" , 8); exps.analyze_dataset("frexport.csv" , 12);
{ "content_hash": "23b40d0919d22219d242f73e61063f61", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 53, "avg_line_length": 22.8, "alnum_prop": 0.7324561403508771, "repo_name": "antoinecarme/pyaf", "id": "5ed92c5c4a30c0144b5e10e5cd4cc90eabd0ed81", "size": "228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/expsmooth/expsmooth_dataset_frexport.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "6773299" }, { "name": "Procfile", "bytes": "24" }, { "name": "Python", "bytes": "54209093" }, { "name": "R", "bytes": "807" }, { "name": "Shell", "bytes": "3619" } ], "symlink_target": "" }
class UpdateVoteIp < ActiveRecord::Migration def change change_column :votes, :ip, :integer, :limit => 8 end end
{ "content_hash": "c49602d49dff10c7f52fdce8e4cd000a", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 51, "avg_line_length": 24, "alnum_prop": 0.7083333333333334, "repo_name": "nike-17/grape-voter", "id": "b5df9dee068005a55a325b90d84d25eadf88e417", "size": "120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20160103164029_update_vote_ip.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "34153" }, { "name": "Shell", "bytes": "380" } ], "symlink_target": "" }
package gov.hhs.onc.dcdt.utils; import javax.annotation.Nullable; public abstract class ToolNumberUtils { public static <T extends Number> boolean isNegative(@Nullable T num) { return (num != null) && (num.doubleValue() < 0); } public static <T extends Number> boolean isPositive(@Nullable T num) { return (num != null) && (num.doubleValue() > 0); } }
{ "content_hash": "887e5a6b961e76aa82230ff66ef8decd", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 74, "avg_line_length": 29.76923076923077, "alnum_prop": 0.6563307493540051, "repo_name": "esacinc/dcdt", "id": "106f2a45887d37c4b4c643842a5248bcb0d6bc8a", "size": "387", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dcdt-core/src/main/java/gov/hhs/onc/dcdt/utils/ToolNumberUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "7846" }, { "name": "Groovy", "bytes": "18146" }, { "name": "Java", "bytes": "1541901" }, { "name": "JavaScript", "bytes": "54163" } ], "symlink_target": "" }
#ifndef QMITKUSNAVIGATIONSTEPTUMOURSELECTION_H #define QMITKUSNAVIGATIONSTEPTUMOURSELECTION_H #include "QmitkUSAbstractNavigationStep.h" namespace itk { template<class T> class SmartPointer; } namespace mitk { class NavigationDataSource; class DataStorage; class DataNode; class USZonesInteractor; class NodeDisplacementFilter; class Surface; } namespace Ui { class QmitkUSNavigationStepTumourSelection; } class USNavigationMarkerPlacement; class QmitkUSNavigationStepCombinedModality; /** * \brief Navigation step for marking the tumor position and extent. * The user can mark the position by interacting with the render windows. The * tumor size can be changed afterwards and the tumor can be removed. */ class QmitkUSNavigationStepTumourSelection : public QmitkUSAbstractNavigationStep { Q_OBJECT protected slots: /** * \brief Activates or deactivates the ineractor for tumour creation. */ void OnFreeze(bool freezed); /** * \brief Updates the surface of the tumor node according to the new size. */ void OnTumourSizeChanged(int); /** * \brief Just restarts the navigation step for deleting the tumour. */ void OnDeleteButtonClicked(); public: explicit QmitkUSNavigationStepTumourSelection(QWidget* parent = 0); ~QmitkUSNavigationStepTumourSelection(); void SetTargetSelectionOptional (bool t); /** * \brief Initializes tumour and target surface. * \return always true */ virtual bool OnStartStep(); /** * \brief Removes target surface and tumour node from the data storage. * Additionally an unfreeze is done and the node displacement filter is * resetted. * \return always true */ virtual bool OnStopStep(); /** * \brief Reinitializes buttons and sliders in addition of calling the default implementation. * \return result of the superclass implementation */ virtual bool OnRestartStep(); /** * \brief (Re)creates the target surface. * \return always true */ virtual bool OnFinishStep(); /** * \brief Initializes (but not activates) the interactor for tumour selection. * \return always true */ virtual bool OnActivateStep(); /** * \brief Deactivates the interactor for tumour selection * and removes data of the tumour node if selection wasn't finished yet. * * \return always true */ virtual bool OnDeactivateStep(); /** * \brief Updates tracking validity status and checks tumour node for the end of tumour creation. */ virtual void OnUpdate(); /** * The properties "settings.security-distance" and * "settings.interaction-concept" are used. */ virtual void OnSettingsChanged(const itk::SmartPointer<mitk::DataNode> settingsNode); virtual QString GetTitle(); /** * @return a node displacement filter for tumour and target surfaces */ virtual FilterVector GetFilter(); void SetTumorColor(mitk::Color c); /** @return Returns the current NodeDisplacementFilter which ist used for updating the targets pose. */ itk::SmartPointer<mitk::NodeDisplacementFilter> GetTumourNodeDisplacementFilter(); protected: virtual void OnSetCombinedModality(); void TumourNodeChanged(const mitk::DataNode*); itk::SmartPointer<mitk::Surface> CreateTargetSurface(); void UpdateReferenceSensorName(); itk::SmartPointer<mitk::NavigationDataSource> m_NavigationDataSource; bool m_targetSelectionOptional; float m_SecurityDistance; itk::SmartPointer<mitk::USZonesInteractor> m_Interactor; itk::SmartPointer<mitk::DataNode> m_TumourNode; itk::SmartPointer<mitk::DataNode> m_TargetSurfaceNode; itk::SmartPointer<mitk::NodeDisplacementFilter> m_NodeDisplacementFilter; std::string m_StateMachineFilename; std::string m_ReferenceSensorName; unsigned int m_ReferenceSensorIndex; mitk::Color m_SphereColor; private: mitk::MessageDelegate1<QmitkUSNavigationStepTumourSelection, const mitk::DataNode*> m_ListenerChangeNode; Ui::QmitkUSNavigationStepTumourSelection *ui; }; #endif // QMITKUSNAVIGATIONSTEPTUMOURSELECTION_H
{ "content_hash": "f98052df3888d9914bac74ac7d418b59", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 107, "avg_line_length": 27.655844155844157, "alnum_prop": 0.7128433904672459, "repo_name": "iwegner/MITK", "id": "9d7a7f814ad2af884066680af68bcd91f7f03fa2", "size": "4757", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/NavigationStepWidgets/QmitkUSNavigationStepTumourSelection.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "3340295" }, { "name": "C++", "bytes": "31705331" }, { "name": "CMake", "bytes": "985642" }, { "name": "CSS", "bytes": "118558" }, { "name": "HTML", "bytes": "102168" }, { "name": "JavaScript", "bytes": "162600" }, { "name": "Jupyter Notebook", "bytes": "228462" }, { "name": "Makefile", "bytes": "25077" }, { "name": "Objective-C", "bytes": "26578" }, { "name": "Python", "bytes": "275885" }, { "name": "QML", "bytes": "28009" }, { "name": "QMake", "bytes": "5583" }, { "name": "Shell", "bytes": "1261" } ], "symlink_target": "" }
package bytebuf import ( "encoding/binary" "math" ) // PutBool put a bool at given position func (b *ByteBuf) PutBool(i int, val bool) error { if i+1 > b.capacity { return ErrOutOfBound } if val { b.buf[i] = 0x01 } else { b.buf[i] = 0x00 } return nil } // PutByte put a byte at given position func (b *ByteBuf) PutByte(i int, val byte) error { if i+1 > b.capacity { return ErrOutOfBound } b.buf[i] = val return nil } // PutBytes put a bool at given position func (b *ByteBuf) PutBytes(i int, p []byte) error { if len(p)+i > b.capacity { return ErrOutOfBound } copy(b.buf[i:], p) return nil } // PutUInt8 put an uint8 at given position func (b *ByteBuf) PutUInt8(i int, val uint8) error { if i+1 > b.capacity { return ErrOutOfBound } b.buf[i] = byte(val) return nil } // PutInt8 put an int8 at given position func (b *ByteBuf) PutInt8(i int, val int8) error { if i+1 > b.capacity { return ErrOutOfBound } b.buf[i] = byte(val) return nil } // PutUInt16BE put an uint16 at given position in big endian func (b *ByteBuf) PutUInt16BE(i int, val uint16) error { if i+2 > b.capacity { return ErrOutOfBound } binary.BigEndian.PutUint16(b.buf[i:], val) return nil } // PutUInt16LE put an uint16 at given position in little endian func (b *ByteBuf) PutUInt16LE(i int, val uint16) error { if i+2 > b.capacity { return ErrOutOfBound } binary.LittleEndian.PutUint16(b.buf[i:], val) return nil } // PutInt16BE put an int16 at given position in big endian func (b *ByteBuf) PutInt16BE(i int, val int16) error { if i+2 > b.capacity { return ErrOutOfBound } binary.BigEndian.PutUint16(b.buf[i:], uint16(val)) return nil } // PutInt16LE put an int16 at given position in little endian func (b *ByteBuf) PutInt16LE(i int, val int16) error { if i+2 > b.capacity { return ErrOutOfBound } binary.LittleEndian.PutUint16(b.buf[i:], uint16(val)) return nil } // PutUInt32BE put an uint32 at given position in big endian func (b *ByteBuf) PutUInt32BE(i int, val uint32) error { if i+4 > b.capacity { return ErrOutOfBound } binary.BigEndian.PutUint32(b.buf[i:], val) return nil } // PutUInt32LE put an uint32 at given position in little endian func (b *ByteBuf) PutUInt32LE(i int, val uint32) error { if i+4 > b.capacity { return ErrOutOfBound } binary.LittleEndian.PutUint32(b.buf[i:], val) return nil } // PutInt32BE put an int32 at given position in big endian func (b *ByteBuf) PutInt32BE(i int, val int32) error { if i+4 > b.capacity { return ErrOutOfBound } binary.BigEndian.PutUint32(b.buf[i:], uint32(val)) return nil } // PutInt32LE put an int32 at given position in little endian func (b *ByteBuf) PutInt32LE(i int, val int32) error { if i+4 > b.capacity { return ErrOutOfBound } binary.LittleEndian.PutUint32(b.buf[i:], uint32(val)) return nil } // PutUInt64BE put an uint64 at given position in big endian func (b *ByteBuf) PutUInt64BE(i int, val uint64) error { if i+8 > b.capacity { return ErrOutOfBound } binary.BigEndian.PutUint64(b.buf[i:], val) return nil } // PutUInt64LE put an uint64 at given position in little endian func (b *ByteBuf) PutUInt64LE(i int, val uint64) error { if i+8 > b.capacity { return ErrOutOfBound } binary.LittleEndian.PutUint64(b.buf[i:], val) return nil } // PutInt64BE put an int64 at given position in big endian func (b *ByteBuf) PutInt64BE(i int, val int64) error { if i+8 > b.capacity { return ErrOutOfBound } binary.BigEndian.PutUint64(b.buf[i:], uint64(val)) return nil } // PutInt64LE put an int64 at given position in little endian func (b *ByteBuf) PutInt64LE(i int, val int64) error { if i+8 > b.capacity { return ErrOutOfBound } binary.LittleEndian.PutUint64(b.buf[i:], uint64(val)) return nil } // PutFloat32BE put a float32 at given position in big endian func (b *ByteBuf) PutFloat32BE(i int, val float32) error { if i+4 > b.capacity { return ErrOutOfBound } binary.BigEndian.PutUint32(b.buf[i:], math.Float32bits(val)) return nil } // PutFloat32LE put a float32 at given position in little endian func (b *ByteBuf) PutFloat32LE(i int, val float32) error { if i+4 > b.capacity { return ErrOutOfBound } binary.LittleEndian.PutUint32(b.buf[i:], math.Float32bits(val)) return nil } // PutFloat64BE put a float64 at given position in big endian func (b *ByteBuf) PutFloat64BE(i int, val float64) error { if i+8 > b.capacity { return ErrOutOfBound } binary.BigEndian.PutUint64(b.buf[i:], math.Float64bits(val)) return nil } // PutFloat64LE put a float64 at given position in little endian func (b *ByteBuf) PutFloat64LE(i int, val float64) error { if i+8 > b.capacity { return ErrOutOfBound } binary.LittleEndian.PutUint64(b.buf[i:], math.Float64bits(val)) return nil }
{ "content_hash": "ce77e19888786fbc8c8e868652d32dc4", "timestamp": "", "source": "github", "line_count": 199, "max_line_length": 64, "avg_line_length": 23.889447236180903, "alnum_prop": 0.708876735380732, "repo_name": "joesonw/bytebuf.go", "id": "4ddea3f771d9977bcb5f7e0e716d871822f821b2", "size": "4754", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "put.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "58526" } ], "symlink_target": "" }
<?php namespace Selective\Database\Test; use Selective\Database\DeleteQuery; /** * @coversDefaultClass \Selective\Database\DeleteQuery */ class DeleteQueryTest extends BaseTest { /** * Test create object. * * @return void */ public function testInstance(): void { $this->assertInstanceOf(DeleteQuery::class, $this->delete()); } /** * @return DeleteQuery */ protected function delete(): DeleteQuery { return new DeleteQuery($this->getConnection()); } /** * Test. */ public function testFrom(): void { $delete = $this->delete()->from('test'); $this->assertSame('DELETE FROM `test`;', $delete->build()); $this->assertTrue($delete->execute()); } /** * Test. */ public function testLowPriority(): void { $delete = $this->delete()->lowPriority()->from('test'); $this->assertSame('DELETE LOW_PRIORITY FROM `test`;', $delete->build()); } /** * Test. */ public function testIgnore(): void { $delete = $this->delete()->ignore()->from('test')->where('id', '=', '1'); $this->assertSame("DELETE IGNORE FROM `test` WHERE `id` = '1';", $delete->build()); $delete = $this->delete()->lowPriority()->ignore()->from('test')->where('id', '=', '1'); $this->assertSame("DELETE LOW_PRIORITY IGNORE FROM `test` WHERE `id` = '1';", $delete->build()); } /** * Test. */ public function testQuick(): void { $delete = $this->delete()->quick()->from('test')->where('id', '=', '1'); $this->assertSame("DELETE QUICK FROM `test` WHERE `id` = '1';", $delete->build()); } /** * Test. */ public function testOrderBy(): void { $delete = $this->delete()->from('test')->where('id', '=', '1')->orderBy('id'); $this->assertSame("DELETE FROM `test` WHERE `id` = '1' ORDER BY `id`;", $delete->build()); $delete = $this->delete()->from('test')->where('id', '=', '1')->orderBy('id DESC'); $this->assertSame("DELETE FROM `test` WHERE `id` = '1' ORDER BY `id` DESC;", $delete->build()); $delete = $this->delete()->from('test')->where('id', '=', '1')->orderBy('test.id ASC'); $this->assertSame("DELETE FROM `test` WHERE `id` = '1' ORDER BY `test`.`id` ASC;", $delete->build()); $delete = $this->delete()->from('test')->where('id', '=', '1')->orderBy('db.test.id ASC'); $this->assertSame("DELETE FROM `test` WHERE `id` = '1' ORDER BY `db`.`test`.`id` ASC;", $delete->build()); } /** * Test. */ public function testLimit(): void { $delete = $this->delete()->from('test')->where('id', '>', '1')->limit(10); $this->assertSame("DELETE FROM `test` WHERE `id` > '1' LIMIT 10;", $delete->build()); } /** * Test. */ public function testWhere(): void { $delete = $this->delete()->from('test')->where('id', '=', '1') ->where('test.id', '=', 1) ->orWhere('db.test.id', '>', 2); $this->assertSame("DELETE FROM `test` WHERE `id` = '1' AND `test`.`id` = '1' OR `db`.`test`.`id` > '2';", $delete->build()); } /** * Test. */ public function testTruncate(): void { $delete = $this->delete()->from('test')->truncate(); $this->assertSame('TRUNCATE TABLE `test`;', $delete->build()); } protected function setUp(): void { parent::setUp(); $this->createTestTable(); } }
{ "content_hash": "8db4295dc30dff5424c6dcba5f28da45", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 132, "avg_line_length": 29.147540983606557, "alnum_prop": 0.5177165354330708, "repo_name": "odan/database", "id": "383e08a3fbd0c10e99c319186ba733784154bed0", "size": "3556", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/DeleteQueryTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "130838" } ], "symlink_target": "" }
from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/space/weapon/shared_wpn_medium_blaster.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
{ "content_hash": "6ceabc68575c056119ac32d16203ee2f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 86, "avg_line_length": 24.23076923076923, "alnum_prop": 0.6984126984126984, "repo_name": "obi-two/Rebelion", "id": "04674734c0d9a1fe1cc042cb52bc21a3b8eb2a58", "size": "460", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "data/scripts/templates/object/draft_schematic/space/weapon/shared_wpn_medium_blaster.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "11818" }, { "name": "C", "bytes": "7699" }, { "name": "C++", "bytes": "2293610" }, { "name": "CMake", "bytes": "39727" }, { "name": "PLSQL", "bytes": "42065" }, { "name": "Python", "bytes": "7499185" }, { "name": "SQLPL", "bytes": "41864" } ], "symlink_target": "" }
package org.hammerlab.args import caseapp.{ ValueDescription, HelpMessage ⇒ M, Name ⇒ O } case class PostPartitionArgs( @O("p") @ValueDescription("num=100000") @M("After running eager and/or seqdoop checkers over a BAM file and filtering to just the contested positions, repartition to have this many records per partition. Typically there are far fewer records at this stage, so it's useful to coalesce down to avoid 1,000's of empty partitions") resultsPerPartition: Int = 100000 )
{ "content_hash": "13e2d34da98dc46733277b49e6c7b41f", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 291, "avg_line_length": 50.2, "alnum_prop": 0.7569721115537849, "repo_name": "ryan-williams/spark-bam", "id": "827675d6045794ed1d9b2df25531774cd7961f2e", "size": "506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "check/src/main/scala/org/hammerlab/args/PostPartitionArgs.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "241730" } ], "symlink_target": "" }
(function(global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', 'rxjs': 'node_modules/rxjs', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', '@angular': 'node_modules/@angular' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'app.component.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { defaultExtension: 'js' }, }; var packageNames = [ '@angular/common', '@angular/compiler', '@angular/core', '@angular/http', '@angular/platform-browser', '@angular/platform-browser-dynamic', '@angular/router', '@angular/router-deprecated', '@angular/testing', '@angular/upgrade', ]; // add package entries for angular packages in the form '@angular/common': // { main: 'index.js', defaultExtension: 'js' } packageNames.forEach(function(pkgName) { packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; }); var config = { map: map, packages: packages } // filterSystemConfig - index.html's chance // to modify config before we register it. if (global.filterSystemConfig) { global.filterSystemConfig(config); } System.config(config); })(this);
{ "content_hash": "7a201244fbe991762adeee2eae6c0ad8", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 88, "avg_line_length": 30.666666666666668, "alnum_prop": 0.5910326086956522, "repo_name": "spugachev/DevCon2016", "id": "5b7197895d22c3ff8b4aaf9f7cb68ba6eadac2a5", "size": "1472", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "simple/start/systemjs.config.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "8930" }, { "name": "CSS", "bytes": "600" }, { "name": "HTML", "bytes": "4127" }, { "name": "JavaScript", "bytes": "216362" }, { "name": "PowerShell", "bytes": "468" }, { "name": "TypeScript", "bytes": "6243" } ], "symlink_target": "" }
namespace GroundSteel { // forward declarations struct EllipsOffsetPos; struct TruncEllipseOffset; ////////////////////////////////////////////////////////////////////// // we gradually poke the values in until the functions can be called. struct Ellipse { P2 ecen; // ellipse centre P2 j; // major axis P2 n; // minor axis double nlen; // length of n double eccen; // eccentricity (length of j / nlen) double eccensq; // Square(eccensq) // the coordinates of the place where the ellipse is parallel to the y axis. double tang_s; double tang_t; // the coordinates of the place where the ellipse is perp to the y axis double perp_s; double perp_t; void SetEllipseVals(const P2& lecen, // ellipse center const P2& lj, // major axis const P2& ln, // minor axis double lnlen, // length of minor axis double leccen); // eccentricity #ifdef MDEBUG P2 D_EEval(double s, double t) const; P2 D_Norm(double s, double t) const; #endif }; ////////////////////////////////////////////////////////////////////// // we gradually poke the values in until the functions can be called. struct EllipseOffset : Ellipse { double offrad; // offset radius we will apply double radrat; // offrad / nlen; // tiny function to make the reloading in the test harness easier. void SetOffsetRadius(double loffrad); // interface used by the edge torus function void SetOffsetEllipseVals(const P2& lecen, // ellipse center const P2& veaxis, double veaxislen, double crad, // cutter radius (torus tube radius??) double jlenfac, double loffrad); // offset radius (torus radius?) #ifdef MDEBUG P2 D_Eval(double s, double t) const; #endif // solves for points (positions) on the offset ellipse where eopm.p.u == 0 double EllInters(EllipsOffsetPos& eopm, EllipsOffsetPos& eopa, EllipsOffsetPos& eopb, bool bjp, bool bnp); double EllIntersMono(EllipsOffsetPos& eopm, EllipsOffsetPos& eopa, EllipsOffsetPos& eopb, bool bjp, bool bnp); bool EllIntersMonoByHalf(EllipsOffsetPos& eopa, bool bst, EllipsOffsetPos& eopb, bool bjp, bool bnp); bool EllIntersMonoByParap(EllipsOffsetPos& eopa, EllipsOffsetPos& eopb, bool bjp, bool bnp); double EllIntersMonoByNR(EllipsOffsetPos& eopm, EllipsOffsetPos& eopa, EllipsOffsetPos& eopb, bool bjp, bool bnp); }; ////////////////////////////////////////////////////////////////////// struct EllipsOffsetPos { // (s, t) where: s^2 + t^2 = 1 // point of ellipse is: ecen + j s + n t // tangent at point is: -j t + n s // normal at point is: j (s / eccen) + n (t * eccen) // point on offset-ellipse: point on ellipse + offrad*normal double s; double t; double k; // 1.0 / sqrt(eoff.eccensq * tsq + ssq); P2 p; // a point on the offset-ellipse? #ifdef MDEBUG bool D_CheckVal(const EllipseOffset& eoff); #endif // doing these by constructors rather than create function presents to problem that // we can't give them distinctive names, so we hope we get to the right one. // generating positions at the cardinal points of tangency and so forth. void SetPosCardinal(const EllipseOffset& eoff, bool btangnorm, bool bgopos); void SetPosGirth(const EllipseOffset& eoff, bool bnposgirth); // set s=0, t=1 if bnposgirth=true and t=-1 if false // generates the points are the truncated sides void SetPosFromTruncatedCorner(const TruncEllipseOffset& teoff, bool boffup, bool bsidepn); // generates position for s value here that's a midpoint between the two here. void SetPos(const EllipseOffset& eoff, bool bst, bool bgopos, double lam, EllipsOffsetPos& eopa, EllipsOffsetPos& eopb); // calculates the derivative by ds at this position double dpds(const EllipseOffset& eoff, bool bgopos); }; ////////////////////////////////////////////////////////////////////// struct TruncEllipseOffset : EllipseOffset { // the truncated values double s0; double t0; double s1; double t1; bool SetS01(double ls0, double ls1); // corners of the truncations (or of the ends of the ellipse if the truncation is none). double upoffrat; P2 offupflatmid; // the flat part in the middle of the s1 P2 offupflat0; P2 offupflat1; double downoffrat; P2 offdownflatmid; // the flat part in the middle of the s0 P2 offdownflat0; P2 offdownflat1; // signals for which way the flats face, and whether the extend is defined by a corner or a tangency to one side of the ellipse. int npellup; // lower side (adding n positively) int nmellup; // upper side // corresponding points of the tangencies P2 npinfx; // valid only if npellup == 0, coords are tang_s, tang_t P2 nminfx; void SetTruncateCorners(const P3& a, const P3& b, const P3& v, double veaxissq, double tipcenz); bool HitsExtentsZero(); // this is the hitting the x=0 line // solving for the position eopm.p.u == 0, wherein it returns eopm.p.v double UpperIntersectZero(EllipsOffsetPos& eopm, int& ionfaceupper); // this is the hitting the x=0 line double LowerIntersectZero(EllipsOffsetPos& eopm, int& ionfacelower); // this is the hitting the x=0 line }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// struct AlignedEllipseOffset; // forward declaration struct AlignedEllipsOffsetPos { double s; double ssq; double t; double tsq; double l; P2 p; double dubds; double dubdt; // set by normal being parallel to this pair of squares of a vector void SetPosFN(const AlignedEllipseOffset& aeoff, double hxsq, double hysq); void SetPos(const AlignedEllipseOffset& aeoff, double lst, bool bIsS); void SetPosHalfNR(const AlignedEllipseOffset& aeoff, AlignedEllipsOffsetPos& aeopa, AlignedEllipsOffsetPos& aeopb, double u); }; ////////////////////////////////////////////////////////////////////// struct AlignedEllipseOffset { double j; // major radius (along u) double n; // minor radius (along v) double offrad; // offset radius double jsq; // squares? double nsq; double osq; double uprecision; // ? int aeoiterations; // ? solver iterations? AlignedEllipseOffset(double lj, double ln, double loffrad); void LowerIntersectU(AlignedEllipsOffsetPos& aeopm, double u); }; }; // end namespace #endif
{ "content_hash": "be8123157b823cf0c063cb8dd35e64fb", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 131, "avg_line_length": 33.12444444444444, "alnum_prop": 0.560579632362807, "repo_name": "JohnyEngine/CNC", "id": "c6e42bf27c27fd11d25d22774c7eaad86d1e40ee", "size": "7913", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "opencamlib/src/attic/OffsetEllipse_awcomments.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "30017" }, { "name": "Batchfile", "bytes": "10126" }, { "name": "C", "bytes": "209705" }, { "name": "C++", "bytes": "7311456" }, { "name": "CMake", "bytes": "92171" }, { "name": "Inno Setup", "bytes": "29066" }, { "name": "Makefile", "bytes": "16079" }, { "name": "Objective-C", "bytes": "8124" }, { "name": "Python", "bytes": "1182253" }, { "name": "Shell", "bytes": "9694" } ], "symlink_target": "" }
/*global setInterval, clearInterval */ (function (global) { "use strict"; var ProtocolManager = global._Brackets_LiveDev_ProtocolManager; var _document = null; var _transport; /** * Retrieves related documents (external CSS and JS files) * * @return {{scripts: object, stylesheets: object}} Related scripts and stylesheets */ function related() { var rel = { scripts: {}, stylesheets: {} }; var i; // iterate on document scripts (HTMLCollection doesn't provide forEach iterator). for (i = 0; i < _document.scripts.length; i++) { // add only external scripts if (_document.scripts[i].src) { rel.scripts[_document.scripts[i].src] = true; } } var s, j; //traverse @import rules var traverseRules = function _traverseRules(sheet, base) { var i, href, cssRules; // Deal with cases where we have not sheet, don't crash. if(!sheet) { return; } href = sheet.href; // Deal with Firefox's SecurityError when accessing sheets // from other domains. Chrome will safely return `undefined`. // IE gives an "Access Denied" error (-2147024891), which we also need to catch. try { cssRules = sheet.cssRules; } catch (e) { if (!(e.name === "SecurityError" || e.number === -2147024891)) { throw e; } } if (href && cssRules) { if (rel.stylesheets[href] === undefined) { rel.stylesheets[href] = []; } rel.stylesheets[href].push(base); for (i = 0; i < cssRules.length; i++) { if (cssRules[i].href) { traverseRules(cssRules[i].styleSheet, base); } } } }; //iterate on document.stylesheets (StyleSheetList doesn't provide forEach iterator). for (j = 0; j < window.document.styleSheets.length; j++) { s = window.document.styleSheets[j]; traverseRules(s, s.href); } return rel; } /** * Common functions. */ var Utils = { isExternalStylesheet: function (node) { return (node.nodeName.toUpperCase() === "LINK" && node.rel === "stylesheet" && node.href); }, isExternalScript: function (node) { return (node.nodeName.toUpperCase() === "SCRIPT" && node.src); } }; /** * CSS related commands and notifications */ var CSS = { /** * Maintains a map of stylesheets loaded thorugh @import rules and their parents. * Populated by extractImports, consumed by notifyImportsAdded / notifyImportsRemoved. * @type { */ stylesheets : {}, /** * Check the stylesheet that was just added be really loaded * to be able to extract potential import-ed stylesheets. * It invokes notifyStylesheetAdded once the sheet is loaded. * @param {string} href Absolute URL of the stylesheet. */ checkForStylesheetLoaded : function (href) { var self = this; // Inspect CSSRules for @imports: // styleSheet obejct is required to scan CSSImportRules but // browsers differ on the implementation of MutationObserver interface. // Webkit triggers notifications before stylesheets are loaded, // Firefox does it after loading. // There are also differences on when 'load' event is triggered for // the 'link' nodes. Webkit triggers it before stylesheet is loaded. // Some references to check: // http://www.phpied.com/when-is-a-stylesheet-really-loaded/ // http://stackoverflow.com/questions/17747616/webkit-dynamically-created-stylesheet-when-does-it-really-load // http://stackoverflow.com/questions/11425209/are-dom-mutation-observers-slower-than-dom-mutation-events // // TODO: This is just a temporary 'cross-browser' solution, it needs optimization. var loadInterval = setInterval(function () { var i; for (i = 0; i < window.document.styleSheets.length; i++) { if (window.document.styleSheets[i].href === href) { //clear interval clearInterval(loadInterval); // notify stylesheets added self.notifyStylesheetAdded(href); break; } } }, 50); }, onStylesheetRemoved : function (url) { // get style node created when setting new text for stylesheet. var s = window.document.getElementById(url); // remove if (s && s.parentNode && s.parentNode.removeChild) { s.parentNode.removeChild(s); } }, /** * Send a notification for the stylesheet added and * its import-ed styleshets based on document.stylesheets diff * from previous status. It also updates stylesheets status. */ notifyStylesheetAdded : function () { var added = {}, current, newStatus; current = this.stylesheets; newStatus = related().stylesheets; Object.keys(newStatus).forEach(function (v, i) { if (!current[v]) { added[v] = newStatus[v]; } }); Object.keys(added).forEach(function (v, i) { _transport.send(JSON.stringify({ method: "StylesheetAdded", href: v, roots: [added[v]] })); }); this.stylesheets = newStatus; }, /** * Send a notification for the removed stylesheet and * its import-ed styleshets based on document.stylesheets diff * from previous status. It also updates stylesheets status. */ notifyStylesheetRemoved : function () { var self = this; var removed = {}, newStatus, current; current = self.stylesheets; newStatus = related().stylesheets; Object.keys(current).forEach(function (v, i) { if (!newStatus[v]) { removed[v] = current[v]; // remove node created by setStylesheetText if any self.onStylesheetRemoved(current[v]); } }); Object.keys(removed).forEach(function (v, i) { _transport.send(JSON.stringify({ method: "StylesheetRemoved", href: v, roots: [removed[v]] })); }); self.stylesheets = newStatus; } }; /* process related docs added */ function _onNodesAdded(nodes) { var i; for (i = 0; i < nodes.length; i++) { //check for Javascript files if (Utils.isExternalScript(nodes[i])) { _transport.send(JSON.stringify({ method: 'ScriptAdded', src: nodes[i].src })); } //check for stylesheets if (Utils.isExternalStylesheet(nodes[i])) { CSS.checkForStylesheetLoaded(nodes[i].href); } } } /* process related docs removed */ function _onNodesRemoved(nodes) { var i; //iterate on removed nodes for (i = 0; i < nodes.length; i++) { // check for external JS files if (Utils.isExternalScript(nodes[i])) { _transport.send(JSON.stringify({ method: 'ScriptRemoved', src: nodes[i].src })); } //check for external StyleSheets if (Utils.isExternalStylesheet(nodes[i])) { CSS.notifyStylesheetRemoved(nodes[i].href); } } } function _enableListeners() { // enable MutationOberver if it's supported var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; if (MutationObserver) { var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation.addedNodes.length > 0) { _onNodesAdded(mutation.addedNodes); } if (mutation.removedNodes.length > 0) { _onNodesRemoved(mutation.removedNodes); } }); }); observer.observe(_document, { childList: true, subtree: true }); } else { // use MutationEvents as fallback window.document.addEventListener('DOMNodeInserted', function niLstnr(e) { _onNodesAdded([e.target]); }); window.document.addEventListener('DOMNodeRemoved', function nrLstnr(e) { _onNodesRemoved([e.target]); }); } } /** * Start listening for events and send initial related documents message. * * @param {HTMLDocument} document * @param {object} transport Live development transport connection */ function start(document, transport) { _transport = transport; _document = document; // start listening to node changes _enableListeners(); var rel = related(); // send the current status of related docs. _transport.send(JSON.stringify({ method: "DocumentRelated", related: rel })); // initialize stylesheets with current status for further notifications. CSS.stylesheets = rel.stylesheets; } /** * Stop listening. * TODO currently a no-op. */ function stop() { } var DocumentObserver = { start: start, stop: stop, related: related }; ProtocolManager.setDocumentObserver(DocumentObserver); }(this));
{ "content_hash": "daa6d01b8ba7ff067c478f645e8d33d6", "timestamp": "", "source": "github", "line_count": 322, "max_line_length": 130, "avg_line_length": 34.409937888198755, "alnum_prop": 0.4942238267148014, "repo_name": "Th30/brackets", "id": "057112a0c4c3d4a2b3667477403a170a64de3e11", "size": "12245", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "src/LiveDevelopment/MultiBrowserImpl/protocol/remote/DocumentObserver.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "422115" }, { "name": "Clojure", "bytes": "28" }, { "name": "HTML", "bytes": "2071819" }, { "name": "JavaScript", "bytes": "12735436" }, { "name": "Makefile", "bytes": "2186" }, { "name": "PHP", "bytes": "28796" }, { "name": "Ruby", "bytes": "9040" }, { "name": "Shell", "bytes": "9759" } ], "symlink_target": "" }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) : typeof define === 'function' && define.amd ? define(['jquery'], factory) : (global = global || self, factory(global.jQuery)); }(this, function ($) { 'use strict'; $ = $ && $.hasOwnProperty('default') ? $['default'] : $; var toString = {}.toString; var classofRaw = function (it) { return toString.call(it).slice(8, -1); }; // `IsArray` abstract operation // https://tc39.github.io/ecma262/#sec-isarray var isArray = Array.isArray || function isArray(arg) { return classofRaw(arg) == 'Array'; }; var isObject = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; // `RequireObjectCoercible` abstract operation // https://tc39.github.io/ecma262/#sec-requireobjectcoercible var requireObjectCoercible = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; // `ToObject` abstract operation // https://tc39.github.io/ecma262/#sec-toobject var toObject = function (argument) { return Object(requireObjectCoercible(argument)); }; var ceil = Math.ceil; var floor = Math.floor; // `ToInteger` abstract operation // https://tc39.github.io/ecma262/#sec-tointeger var toInteger = function (argument) { return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); }; var min = Math.min; // `ToLength` abstract operation // https://tc39.github.io/ecma262/#sec-tolength var toLength = function (argument) { return argument > 0 ? min(toInteger(argument), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; // 7.1.1 ToPrimitive(input [, PreferredType]) // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var toPrimitive = function (it, S) { if (!isObject(it)) return it; var fn, val; if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; throw TypeError("Can't convert object to primitive value"); }; var fails = function (exec) { try { return !!exec(); } catch (e) { return true; } }; // Thank's IE8 for his funny defineProperty var descriptors = !fails(function () { return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; }); // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = typeof window == 'object' && window && window.Math == Math ? window : typeof self == 'object' && self && self.Math == Math ? self // eslint-disable-next-line no-new-func : Function('return this')(); var document = global.document; // typeof document.createElement is 'object' in old IE var exist = isObject(document) && isObject(document.createElement); var documentCreateElement = function (it) { return exist ? document.createElement(it) : {}; }; // Thank's IE8 for his funny defineProperty var ie8DomDefine = !descriptors && !fails(function () { return Object.defineProperty(documentCreateElement('div'), 'a', { get: function () { return 7; } }).a != 7; }); var anObject = function (it) { if (!isObject(it)) { throw TypeError(String(it) + ' is not an object'); } return it; }; var nativeDefineProperty = Object.defineProperty; var f = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (ie8DomDefine) try { return nativeDefineProperty(O, P, Attributes); } catch (e) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; var objectDefineProperty = { f: f }; var createPropertyDescriptor = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var createProperty = function (object, key, value) { var propertyKey = toPrimitive(key); if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value)); else object[propertyKey] = value; }; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var hide = descriptors ? function (object, key, value) { return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var setGlobal = function (key, value) { try { hide(global, key, value); } catch (e) { global[key] = value; } return value; }; var shared = createCommonjsModule(function (module) { var SHARED = '__core-js_shared__'; var store = global[SHARED] || setGlobal(SHARED, {}); (module.exports = function (key, value) { return store[key] || (store[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.0.0', mode: 'global', copyright: '© 2019 Denis Pushkarev (zloirock.ru)' }); }); var id = 0; var postfix = Math.random(); var uid = function (key) { return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + postfix).toString(36)); }; // Chrome 38 Symbol has incorrect toString conversion var nativeSymbol = !fails(function () { }); var store = shared('wks'); var Symbol = global.Symbol; var wellKnownSymbol = function (name) { return store[name] || (store[name] = nativeSymbol && Symbol[name] || (nativeSymbol ? Symbol : uid)('Symbol.' + name)); }; var SPECIES = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation // https://tc39.github.io/ecma262/#sec-arrayspeciescreate var arraySpeciesCreate = function (originalArray, length) { var C; if (isArray(originalArray)) { C = originalArray.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; else if (isObject(C)) { C = C[SPECIES]; if (C === null) C = undefined; } } return new (C === undefined ? Array : C)(length === 0 ? 0 : length); }; var SPECIES$1 = wellKnownSymbol('species'); var arrayMethodHasSpeciesSupport = function (METHOD_NAME) { return !fails(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES$1] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; var nativePropertyIsEnumerable = {}.propertyIsEnumerable; var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = nativeGetOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); var f$1 = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = nativeGetOwnPropertyDescriptor(this, V); return !!descriptor && descriptor.enumerable; } : nativePropertyIsEnumerable; var objectPropertyIsEnumerable = { f: f$1 }; // fallback for non-array-like ES3 and non-enumerable old V8 strings var split = ''.split; var indexedObject = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins return !Object('z').propertyIsEnumerable(0); }) ? function (it) { return classofRaw(it) == 'String' ? split.call(it, '') : Object(it); } : Object; // toObject with fallback for non-array-like ES3 strings var toIndexedObject = function (it) { return indexedObject(requireObjectCoercible(it)); }; var hasOwnProperty = {}.hasOwnProperty; var has = function (it, key) { return hasOwnProperty.call(it, key); }; var nativeGetOwnPropertyDescriptor$1 = Object.getOwnPropertyDescriptor; var f$2 = descriptors ? nativeGetOwnPropertyDescriptor$1 : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (ie8DomDefine) try { return nativeGetOwnPropertyDescriptor$1(O, P); } catch (e) { /* empty */ } if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]); }; var objectGetOwnPropertyDescriptor = { f: f$2 }; var functionToString = shared('native-function-to-string', Function.toString); var WeakMap = global.WeakMap; var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(functionToString.call(WeakMap)); var shared$1 = shared('keys'); var sharedKey = function (key) { return shared$1[key] || (shared$1[key] = uid(key)); }; var hiddenKeys = {}; var WeakMap$1 = global.WeakMap; var set, get, has$1; var enforce = function (it) { return has$1(it) ? get(it) : set(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (nativeWeakMap) { var store$1 = new WeakMap$1(); var wmget = store$1.get; var wmhas = store$1.has; var wmset = store$1.set; set = function (it, metadata) { wmset.call(store$1, it, metadata); return metadata; }; get = function (it) { return wmget.call(store$1, it) || {}; }; has$1 = function (it) { return wmhas.call(store$1, it); }; } else { var STATE = sharedKey('state'); hiddenKeys[STATE] = true; set = function (it, metadata) { hide(it, STATE, metadata); return metadata; }; get = function (it) { return has(it, STATE) ? it[STATE] : {}; }; has$1 = function (it) { return has(it, STATE); }; } var internalState = { set: set, get: get, has: has$1, enforce: enforce, getterFor: getterFor }; var redefine = createCommonjsModule(function (module) { var getInternalState = internalState.get; var enforceInternalState = internalState.enforce; var TEMPLATE = String(functionToString).split('toString'); shared('inspectSource', function (it) { return functionToString.call(it); }); (module.exports = function (O, key, value, options) { var unsafe = options ? !!options.unsafe : false; var simple = options ? !!options.enumerable : false; var noTargetGet = options ? !!options.noTargetGet : false; if (typeof value == 'function') { if (typeof key == 'string' && !has(value, 'name')) hide(value, 'name', key); enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); } if (O === global) { if (simple) O[key] = value; else setGlobal(key, value); return; } else if (!unsafe) { delete O[key]; } else if (!noTargetGet && O[key]) { simple = true; } if (simple) O[key] = value; else hide(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState(this).source || functionToString.call(this); }); }); var max = Math.max; var min$1 = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(length, length). var toAbsoluteIndex = function (index, length) { var integer = toInteger(index); return integer < 0 ? max(integer + length, 0) : min$1(integer, length); }; // `Array.prototype.{ indexOf, includes }` methods implementation // false -> Array#indexOf // https://tc39.github.io/ecma262/#sec-array.prototype.indexof // true -> Array#includes // https://tc39.github.io/ecma262/#sec-array.prototype.includes var arrayIncludes = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) if (IS_INCLUDES || index in O) { if (O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; var arrayIndexOf = arrayIncludes(false); var objectKeysInternal = function (object, names) { var O = toIndexedObject(object); var i = 0; var result = []; var key; for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~arrayIndexOf(result, key) || result.push(key); } return result; }; // IE8- don't enum bug keys var enumBugKeys = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype'); var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return objectKeysInternal(O, hiddenKeys$1); }; var objectGetOwnPropertyNames = { f: f$3 }; var f$4 = Object.getOwnPropertySymbols; var objectGetOwnPropertySymbols = { f: f$4 }; var Reflect = global.Reflect; // all object keys, includes non-enumerable and symbols var ownKeys = Reflect && Reflect.ownKeys || function ownKeys(it) { var keys = objectGetOwnPropertyNames.f(anObject(it)); var getOwnPropertySymbols = objectGetOwnPropertySymbols.f; return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; }; var copyConstructorProperties = function (target, source) { var keys = ownKeys(source); var defineProperty = objectDefineProperty.f; var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } }; var replacement = /#|\.prototype\./; var isForced = function (feature, detection) { var value = data[normalize(feature)]; return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection; }; var normalize = isForced.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced.data = {}; var NATIVE = isForced.NATIVE = 'N'; var POLYFILL = isForced.POLYFILL = 'P'; var isForced_1 = isForced; var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ var _export = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global; } else if (STATIC) { target = global[TARGET] || setGlobal(TARGET, {}); } else { target = (global[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { hide(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } }; var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); var MAX_SAFE_INTEGER = 0x1fffffffffffff; var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; var IS_CONCAT_SPREADABLE_SUPPORT = !fails(function () { var array = []; array[IS_CONCAT_SPREADABLE] = false; return array.concat()[0] !== array; }); var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); var isConcatSpreadable = function (O) { if (!isObject(O)) return false; var spreadable = O[IS_CONCAT_SPREADABLE]; return spreadable !== undefined ? !!spreadable : isArray(O); }; var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method // https://tc39.github.io/ecma262/#sec-array.prototype.concat // with adding support of @@isConcatSpreadable and @@species _export({ target: 'Array', proto: true, forced: FORCED }, { concat: function concat(arg) { // eslint-disable-line no-unused-vars var O = toObject(this); var A = arraySpeciesCreate(O, 0); var n = 0; var i, k, length, len, E; for (i = -1, length = arguments.length; i < length; i++) { E = i === -1 ? O : arguments[i]; if (isConcatSpreadable(E)) { len = toLength(E.length); if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); } else { if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); createProperty(A, n++, E); } } A.length = n; return A; } }); /** * Bootstrap Table Hebrew translation * Author: legshooter */ $.fn.bootstrapTable.locales['he-IL'] = { formatLoadingMessage: function formatLoadingMessage() { return 'טוען, נא להמתין'; }, formatRecordsPerPage: function formatRecordsPerPage(pageNumber) { return "".concat(pageNumber, " \u05E9\u05D5\u05E8\u05D5\u05EA \u05D1\u05E2\u05DE\u05D5\u05D3"); }, formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows, totalNotFiltered) { if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) { return "\u05DE\u05E6\u05D9\u05D2 ".concat(pageFrom, " \u05E2\u05D3 ").concat(pageTo, " \u05DE-").concat(totalRows, "\u05E9\u05D5\u05E8\u05D5\u05EA").concat(totalNotFiltered, " total rows)"); } return "\u05DE\u05E6\u05D9\u05D2 ".concat(pageFrom, " \u05E2\u05D3 ").concat(pageTo, " \u05DE-").concat(totalRows, " \u05E9\u05D5\u05E8\u05D5\u05EA"); }, formatSRPaginationPreText: function formatSRPaginationPreText() { return 'previous page'; }, formatSRPaginationPageText: function formatSRPaginationPageText(page) { return "to page ".concat(page); }, formatSRPaginationNextText: function formatSRPaginationNextText() { return 'next page'; }, formatDetailPagination: function formatDetailPagination(totalRows) { return "Showing ".concat(totalRows, " rows"); }, formatClearSearch: function formatClearSearch() { return 'Clear Search'; }, formatSearch: function formatSearch() { return 'חיפוש'; }, formatNoMatches: function formatNoMatches() { return 'לא נמצאו רשומות תואמות'; }, formatPaginationSwitch: function formatPaginationSwitch() { return 'הסתר/הצג מספור דפים'; }, formatPaginationSwitchDown: function formatPaginationSwitchDown() { return 'Show pagination'; }, formatPaginationSwitchUp: function formatPaginationSwitchUp() { return 'Hide pagination'; }, formatRefresh: function formatRefresh() { return 'רענן'; }, formatToggle: function formatToggle() { return 'החלף תצוגה'; }, formatToggleOn: function formatToggleOn() { return 'Show card view'; }, formatToggleOff: function formatToggleOff() { return 'Hide card view'; }, formatColumns: function formatColumns() { return 'עמודות'; }, formatColumnsToggleAll: function formatColumnsToggleAll() { return 'Toggle all'; }, formatFullscreen: function formatFullscreen() { return 'Fullscreen'; }, formatAllRows: function formatAllRows() { return 'הכל'; }, formatAutoRefresh: function formatAutoRefresh() { return 'Auto Refresh'; }, formatExport: function formatExport() { return 'Export data'; }, formatJumpTo: function formatJumpTo() { return 'GO'; }, formatAdvancedSearch: function formatAdvancedSearch() { return 'Advanced search'; }, formatAdvancedCloseButton: function formatAdvancedCloseButton() { return 'Close'; } }; $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['he-IL']); }));
{ "content_hash": "25129339b4fb3b33d7b2ccd0c199f91b", "timestamp": "", "source": "github", "line_count": 693, "max_line_length": 198, "avg_line_length": 32.56421356421357, "alnum_prop": 0.6395621925820889, "repo_name": "extend1994/cdnjs", "id": "6fa43c6e4244137b5dc7d06197b3f6d42752c011", "size": "22642", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "ajax/libs/bootstrap-table/1.15.0/locale/bootstrap-table-he-IL.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace Symfony\Component\Console\Tests\Output; use Symfony\Component\Console\Output\Output; use Symfony\Component\Console\Formatter\OutputFormatterStyle; class OutputTest extends \PHPUnit_Framework_TestCase { public function testConstructor() { $output = new TestOutput(Output::VERBOSITY_QUIET, true); $this->assertEquals(Output::VERBOSITY_QUIET, $output->getVerbosity(), '__construct() takes the verbosity as its first argument'); $this->assertTrue($output->isDecorated(), '__construct() takes the decorated flag as its second argument'); } public function testSetIsDecorated() { $output = new TestOutput(); $output->setDecorated(true); $this->assertTrue($output->isDecorated(), 'setDecorated() sets the decorated flag'); } public function testSetGetVerbosity() { $output = new TestOutput(); $output->setVerbosity(Output::VERBOSITY_QUIET); $this->assertEquals(Output::VERBOSITY_QUIET, $output->getVerbosity(), '->setVerbosity() sets the verbosity'); } public function testWrite() { $fooStyle = new OutputFormatterStyle('yellow', 'red', array('blink')); $output = new TestOutput(Output::VERBOSITY_QUIET); $output->writeln('foo'); $this->assertEquals('', $output->output, '->writeln() outputs nothing if verbosity is set to VERBOSITY_QUIET'); $output = new TestOutput(); $output->writeln(array('foo', 'bar')); $this->assertEquals("foo\nbar\n", $output->output, '->writeln() can take an array of messages to output'); $output = new TestOutput(); $output->writeln('<info>foo</info>', Output::OUTPUT_RAW); $this->assertEquals("<info>foo</info>\n", $output->output, '->writeln() outputs the raw message if OUTPUT_RAW is specified'); $output = new TestOutput(); $output->writeln('<info>foo</info>', Output::OUTPUT_PLAIN); $this->assertEquals("foo\n", $output->output, '->writeln() strips decoration tags if OUTPUT_PLAIN is specified'); $output = new TestOutput(); $output->setDecorated(false); $output->writeln('<info>foo</info>'); $this->assertEquals("foo\n", $output->output, '->writeln() strips decoration tags if decoration is set to false'); $output = new TestOutput(); $output->getFormatter()->setStyle('FOO', $fooStyle); $output->setDecorated(true); $output->writeln('<foo>foo</foo>'); $this->assertEquals("\033[33;41;5mfoo\033[0m\n", $output->output, '->writeln() decorates the output'); try { $output->writeln('<foo>foo</foo>', 24); $this->fail('->writeln() throws an \InvalidArgumentException when the type does not exist'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->writeln() throws an \InvalidArgumentException when the type does not exist'); $this->assertEquals('Unknown output type given (24)', $e->getMessage()); } $output->clear(); $output->write('<bar>foo</bar>'); $this->assertEquals('<bar>foo</bar>', $output->output, '->write() do nothing when a style does not exist'); $output->clear(); $output->writeln('<bar>foo</bar>'); $this->assertEquals("<bar>foo</bar>\n", $output->output, '->writeln() do nothing when a style does not exist'); } } class TestOutput extends Output { public $output = ''; public function clear() { $this->output = ''; } protected function doWrite($message, $newline) { $this->output .= $message.($newline ? "\n" : ''); } }
{ "content_hash": "d766d5e89bfaa83da28a600f72920ab1", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 149, "avg_line_length": 40.276595744680854, "alnum_prop": 0.6061806656101426, "repo_name": "jonathanfvb/AnoteTudo", "id": "02b75ba57e08630244d85d84b7ac5f6266b9a856", "size": "4022", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/symfony/console/Symfony/Component/Console/Tests/Output/OutputTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "280457" }, { "name": "JavaScript", "bytes": "4018374" }, { "name": "PHP", "bytes": "55996" } ], "symlink_target": "" }
package com.volokh.danylo.video_player_manager.ui; import android.media.MediaPlayer; public class MediaPlayerWrapperImpl extends MediaPlayerWrapper{ public MediaPlayerWrapperImpl() { super(new MediaPlayer()); } }
{ "content_hash": "4d894dd1e55a9e29d9224063f955eb8b", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 63, "avg_line_length": 23.2, "alnum_prop": 0.7586206896551724, "repo_name": "cowthan/AyoWeibo", "id": "d76a639cefe2f11eb4d7240dfa79c9cf6327f621", "size": "232", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vedio-player-manager/src/main/java/com/volokh/danylo/video_player_manager/ui/MediaPlayerWrapperImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1510" }, { "name": "HTML", "bytes": "992741" }, { "name": "Java", "bytes": "5838792" } ], "symlink_target": "" }
module FeatureGate class << self attr_reader :configuration def configuration @configuration ||= Configuration.new end end def self.setup yield(configuration) end class Configuration attr_accessor :time_to_stale def initialize @time_to_stale = 1.month end end end require 'feature_gate/engine'
{ "content_hash": "1dbb4a526458e5fa93540b3a0d19ffd3", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 42, "avg_line_length": 15.26086956521739, "alnum_prop": 0.6752136752136753, "repo_name": "tiffling/feature_gate", "id": "d0e611f69e6fc72e57c3ae485a0936c7def4ac19", "size": "351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/feature_gate.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "595" }, { "name": "HTML", "bytes": "2254" }, { "name": "JavaScript", "bytes": "641" }, { "name": "Ruby", "bytes": "17094" } ], "symlink_target": "" }
package jp.co.acroquest.endosnipe.javelin.jdbc.stats.oracle; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import jp.co.acroquest.endosnipe.common.db.AbstractExecutePlanChecker; import jp.co.acroquest.endosnipe.common.db.OracleExecutePlanChecker; import jp.co.acroquest.endosnipe.common.logger.SystemLogger; import jp.co.acroquest.endosnipe.javelin.jdbc.common.JdbcJavelinConfig; import jp.co.acroquest.endosnipe.javelin.jdbc.stats.AbstractProcessor; import jp.co.acroquest.endosnipe.javelin.jdbc.stats.JdbcJavelinRecorder; /** * Oracle用 * @author akiba * */ public class OracleProcessor extends AbstractProcessor { /** JDBC接続URLがこの文字列で始まるとき、実行計画を取得する(Oracle Thin ドライバ) */ public static final String EXPLAIN_TARGET_ORACLE = "jdbc:oracle"; /** JDBC接続URLがこの文字列で始まるとき、実行計画を取得する(BEA WebLogic Type 4 JDBC Oracle ドライバ) */ public static final String EXPLAIN_TARGET_BEA_ORACLE = "jdbc:bea:oracle:"; /** * {@inheritDoc} */ public boolean isTarget(final String jdbcUrl) { return jdbcUrl.startsWith(EXPLAIN_TARGET_ORACLE) || jdbcUrl.startsWith(EXPLAIN_TARGET_BEA_ORACLE); } /** * Oracleで実行計画を取得する。 * * @param stmt ステートメント * @param originalSql SQL文 * @param args 引数。 * @return 実行計画 * @throws SQLException Statementクローズ時にエラーが発生したとき */ public String getOneExecPlan(final Statement stmt, final String originalSql, final List<?> args) throws SQLException { JdbcJavelinConfig config = new JdbcJavelinConfig(); // 実行計画取得に失敗した場合にargsにセットする文字列 StringBuilder execPlanText = null; // 実行計画生成SQL文の生成 StringBuilder sql = new StringBuilder(); sql.append("EXPLAIN PLAN FOR "); sql.append(originalSql); // 実行計画整形・取得SQLの生成。 StringBuilder planTable = new StringBuilder(); planTable.append("SELECT PLAN_TABLE_OUTPUT FROM TABLE" + "(DBMS_XPLAN.DISPLAY('PLAN_TABLE',NULL,'"); planTable.append(config.getOutputOption()); planTable.append("'))"); // 実行計画を生成(PLANテーブルに展開) ResultSet resultSet = null; Statement planStmt = null; try { planStmt = stmt.getConnection().createStatement(); planStmt.execute(sql.toString()); // 実行計画を整形・取得 resultSet = planStmt.executeQuery(planTable.toString()); // 検索された行数分ループ execPlanText = new StringBuilder(""); while (resultSet.next()) { // PLAN_TABLE_OUTPUTを取得 String planTableOutput = resultSet.getString(1); // 結合 execPlanText.append(planTableOutput); execPlanText.append('\n'); } } catch (SQLException ex) { execPlanText = new StringBuilder(JdbcJavelinRecorder.EXPLAIN_PLAN_FAILED); // DBアクセスエラー/想定外の例外が発生した場合はエラーログに出力しておく。 SystemLogger.getInstance().warn(ex); } finally { // リソース解放 try { if (resultSet != null) { resultSet.close(); } } finally { if (planStmt != null) { planStmt.close(); } } } return execPlanText.toString(); } /** * SQLトレース取得用SQLを発行する。 * @param connection コネクション */ @Override public void startSqlTrace(final Connection connection) { // SQLトレースのトレースIDを設定する。 SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String id = Thread.currentThread().getId() + "_" + dataFormat.format(new Date()); Statement stmt = null; try { // SQLトレース取得用のSQLを実行する。 stmt = connection.createStatement(); stmt.execute(SET_TRACE_ID + id + "'"); // 現時点までのSQLトレースを一旦すべて出力してから、再度開始する // ※OracleのSQLトレースは、最後の出力停止時点から現時点までを出力する(動きに見える) stmt.execute(START_SQL_TRACE); } catch (Exception ex) { SystemLogger.getInstance().warn(ex); } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception ex) { SystemLogger.getInstance().warn(ex); } } } /** * SQLトレース終了用のSQLを発行する。 * @param connection コネクション */ public static void stopSqlTrace(final Connection connection) { Statement stmt = null; try { // SQLトレース終了用のSQLを実行する。 stmt = connection.createStatement(); stmt.execute(STOP_SQL_TRACE); } catch (Exception ex) { SystemLogger.getInstance().warn(ex); } finally { try { if (stmt != null) { stmt.close(); } } catch (Exception ex) { SystemLogger.getInstance().warn(ex); } } } /** SQLトレースのID */ private static final String SET_TRACE_ID = "alter session set tracefile_identifier='"; /** SQLトレース取得用SQL */ private static final String START_SQL_TRACE = "alter session set sql_trace=true"; /** SQLトレース終了用SQL */ private static final String STOP_SQL_TRACE = "alter session set sql_trace=false"; /** * {@inheritDoc} */ public boolean needsLock() { return true; } /** * {@inheritDoc} */ public AbstractExecutePlanChecker<?> getExecutePlanChecker() { return new OracleExecutePlanChecker(); } }
{ "content_hash": "b570a7f39320de5b4e99a66a9a3609b7", "timestamp": "", "source": "github", "line_count": 220, "max_line_length": 100, "avg_line_length": 28.522727272727273, "alnum_prop": 0.5378486055776892, "repo_name": "t-hiramatsu/ENdoSnipe", "id": "372c17382ecaec3f79181f3cb7b7193273c360aa", "size": "8457", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Javelin/src/main/java/jp/co/acroquest/endosnipe/javelin/jdbc/stats/oracle/OracleProcessor.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5222" }, { "name": "C", "bytes": "44081" }, { "name": "C++", "bytes": "19064" }, { "name": "CSS", "bytes": "67590" }, { "name": "Groff", "bytes": "1052204" }, { "name": "HTML", "bytes": "45464" }, { "name": "IDL", "bytes": "1634" }, { "name": "Java", "bytes": "7980621" }, { "name": "JavaScript", "bytes": "1770372" }, { "name": "Makefile", "bytes": "320" }, { "name": "PowerShell", "bytes": "1218" }, { "name": "Shell", "bytes": "7462" } ], "symlink_target": "" }
/* * SingleSignal2.cpp * * Created on: 2016年4月16日 * Author: fasiondog */ #include "../../../indicator/crt/KDATA.h" #include "../../../indicator/crt/DIFF.h" #include "../../../indicator/crt/STDEV.h" #include "../../../indicator/crt/HHV.h" #include "../../../indicator/crt/LLV.h" #include "../../../indicator/crt/REF.h" #include "SingleSignal2.h" namespace hku { SingleSignal2::SingleSignal2() : SignalBase("SG_Single2") { setParam<int>("filter_n", 10); setParam<double>("filter_p", 0.1); setParam<string>("kpart", "CLOSE"); } SingleSignal2::SingleSignal2(const Indicator& ind) : SignalBase("SG_Single2"), m_ind(ind) { setParam<int>("filter_n", 10); setParam<double>("filter_p", 0.1); setParam<string>("kpart", "CLOSE"); } SingleSignal2::~SingleSignal2() {} SignalPtr SingleSignal2::_clone() { SingleSignal2* p = new SingleSignal2(); p->m_ind = m_ind; return SignalPtr(p); } void SingleSignal2::_calculate() { int filter_n = getParam<int>("filter_n"); double filter_p = getParam<double>("filter_p"); string kpart(getParam<string>("kpart")); Indicator ind = m_ind(KDATA_PART(m_kdata, kpart)); Indicator dev = REF(STDEV(DIFF(ind), filter_n), 1); size_t start = dev.discard(); HKU_IF_RETURN(start < 3, void()); Indicator buy = ind - REF(LLV(ind, filter_n), 1); Indicator sell = REF(HHV(ind, filter_n), 1) - ind; size_t total = dev.size(); for (size_t i = start; i < total; ++i) { double filter = filter_p * dev[i]; if (buy[i] > filter) { _addBuySignal(m_kdata[i].datetime); } else if (sell[i] > filter) { _addSellSignal(m_kdata[i].datetime); } } } SignalPtr HKU_API SG_Single2(const Indicator& ind, int filter_n, double filter_p, const string& kpart) { SingleSignal2* p = new SingleSignal2(ind); p->setParam<int>("filter_n", filter_n); p->setParam<double>("filter_p", filter_p); p->setParam<string>("kpart", kpart); return SignalPtr(p); } } /* namespace hku */
{ "content_hash": "5456d1d114769072494c9c8725bf451a", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 91, "avg_line_length": 29.12676056338028, "alnum_prop": 0.601063829787234, "repo_name": "fasiondog/hikyuu", "id": "dbfa238cf8f782bfeb96b19585117839ffc22102", "size": "2074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hikyuu_cpp/hikyuu/trade_sys/signal/imp/SingleSignal2.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "422" }, { "name": "C++", "bytes": "3954032" }, { "name": "Jupyter Notebook", "bytes": "2063922" }, { "name": "Lua", "bytes": "28945" } ], "symlink_target": "" }
cask 'marvin' do version '1.51.1' sha256 '80b5d001ebc8b1f77eb7da47b867dfc77c144785962f6df784839a0694f0d863' # amazingmarvin.s3.amazonaws.com/ was verified as official when first introduced to the cask url "https://amazingmarvin.s3.amazonaws.com/Marvin-#{version}.dmg" appcast 'https://macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=http://amazingmarvin.s3-website-us-east-1.amazonaws.com/Marvin.dmg' name 'Amazing Marvin' homepage 'https://www.amazingmarvin.com/' app 'Marvin.app' end
{ "content_hash": "9e7e70e92b7b8e8d068fd69039727f05", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 147, "avg_line_length": 43.083333333333336, "alnum_prop": 0.7736943907156673, "repo_name": "morganestes/homebrew-cask", "id": "99068c8123bf4b985b6ce27171a3be4ad182cd26", "size": "517", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Casks/marvin.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "2152638" }, { "name": "Shell", "bytes": "70817" } ], "symlink_target": "" }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Client.Http; using Microsoft.AspNetCore.SignalR.Client.Infrastructure; using Microsoft.AspNetCore.SignalR.Client.Transports.WebSockets; namespace Microsoft.AspNetCore.SignalR.Client.Transports { public class WebSocketTransport : ClientTransportBase { private readonly ClientWebSocketHandler _webSocketHandler; private CancellationToken _disconnectToken; private IConnection _connection; private string _connectionData; private CancellationTokenSource _webSocketTokenSource; private ClientWebSocket _webSocket; private int _disposed; public WebSocketTransport() : this(new DefaultHttpClient()) { } public WebSocketTransport(IHttpClient client) : base(client, "webSockets") { _disconnectToken = CancellationToken.None; ReconnectDelay = TimeSpan.FromSeconds(2); _webSocketHandler = new ClientWebSocketHandler(this); } // intended for testing internal WebSocketTransport(ClientWebSocketHandler webSocketHandler) : this() { _webSocketHandler = webSocketHandler; } /// <summary> /// The time to wait after a connection drops to try reconnecting. /// </summary> public TimeSpan ReconnectDelay { get; set; } /// <summary> /// Indicates whether or not the transport supports keep alive /// </summary> public override bool SupportsKeepAlive => true; protected override void OnStart(IConnection connection, string connectionData, CancellationToken disconnectToken) { _disconnectToken = disconnectToken; _connection = connection; _connectionData = connectionData; // We don't need to await this task PerformConnect().ContinueWith(task => { if (task.IsFaulted) { TransportFailed(task.Exception); } else if (task.IsCanceled) { TransportFailed(null); } }, TaskContinuationOptions.NotOnRanToCompletion); } // For testing public virtual Task PerformConnect() { return PerformConnect(UrlBuilder.BuildConnect(_connection, Name, _connectionData)); } private async Task PerformConnect(string url) { var uri = UrlBuilder.ConvertToWebSocketUri(url); _connection.Trace(TraceLevels.Events, "WS Connecting to: {0}", uri); // TODO: Revisit thread safety of this assignment _webSocketTokenSource = new CancellationTokenSource(); _webSocket = new ClientWebSocket(); _connection.PrepareRequest(new WebSocketWrapperRequest(_webSocket, _connection)); CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(_webSocketTokenSource.Token, _disconnectToken); CancellationToken token = linkedCts.Token; await _webSocket.ConnectAsync(uri, token); await _webSocketHandler.ProcessWebSocketRequestAsync(_webSocket, token); } protected override void OnStartFailed() { // if the transport failed to start we want to stop it silently. Dispose(); } public override Task Send(IConnection connection, string data, string connectionData) { if (connection == null) { throw new ArgumentNullException(nameof(connection)); } // If we don't throw here when the WebSocket isn't open, WebSocketHander.SendAsync will noop. if (_webSocketHandler.WebSocket.State != WebSocketState.Open) { // Make this a faulted task and trigger the OnError even to maintain consistency with the HttpBasedTransports var ex = new InvalidOperationException(Resources.Error_DataCannotBeSentDuringWebSocketReconnect); connection.OnError(ex); return TaskAsyncHelper.FromError(ex); } return _webSocketHandler.SendAsync(data); } // virtual for testing internal virtual void OnMessage(string message) { _connection.Trace(TraceLevels.Messages, "WS: OnMessage({0})", message); ProcessResponse(_connection, message); } // virtual for testing internal virtual void OnOpen() { // This will noop if we're not in the reconnecting state if (_connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected)) { _connection.OnReconnected(); } } // virtual for testing internal virtual void OnClose() { _connection.Trace(TraceLevels.Events, "WS: OnClose()"); if (_disconnectToken.IsCancellationRequested) { return; } if (AbortHandler.TryCompleteAbort()) { return; } DoReconnect(); } // fire and forget private async void DoReconnect() { var reconnectUrl = UrlBuilder.BuildReconnect(_connection, Name, _connectionData); while (TransportHelper.VerifyLastActive(_connection) && _connection.EnsureReconnecting()) { try { await PerformConnect(reconnectUrl); break; } catch (OperationCanceledException) { break; } catch (Exception ex) { if (ExceptionHelper.IsRequestAborted(ex)) { break; } _connection.OnError(ex); } await Task.Delay(ReconnectDelay); } } // virtual for testing internal virtual void OnError(Exception error) { _connection.OnError(error); } public override void LostConnection(IConnection connection) { _connection.Trace(TraceLevels.Events, "WS: LostConnection"); _webSocketTokenSource?.Cancel(); } protected override void Dispose(bool disposing) { if (disposing) { if (Interlocked.Exchange(ref _disposed, 1) == 1) { base.Dispose(disposing); return; } // Gracefully close the websocket message loop _webSocketTokenSource?.Cancel(); _webSocket?.Dispose(); _webSocketTokenSource?.Dispose(); } base.Dispose(disposing); } } }
{ "content_hash": "67b6779dda73fa8e2ba8887b6bbe0983", "timestamp": "", "source": "github", "line_count": 225, "max_line_length": 143, "avg_line_length": 32.62222222222222, "alnum_prop": 0.5713896457765668, "repo_name": "sai4ninja/sai", "id": "044b4451f68d5716781f49a1c72f22766ca875d7", "size": "7342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Sai/Microsoft.AspNetCore.SignalR.Client/Transports/WebSocketTransport.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "39" }, { "name": "C#", "bytes": "428777" }, { "name": "CSS", "bytes": "730092" }, { "name": "HTML", "bytes": "97952" }, { "name": "JavaScript", "bytes": "325911" }, { "name": "LOLCODE", "bytes": "1122" } ], "symlink_target": "" }
package org.apache.camel.component.cxf; import java.util.HashMap; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.component.cxf.jaxws.CxfEndpoint; import org.apache.camel.spring.SpringCamelContext; import org.apache.camel.test.spring.junit5.MockEndpoints; import org.apache.cxf.message.Message; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = CxfComponentEnableMtomTest.TestConfig.class) @MockEndpoints public class CxfComponentEnableMtomTest { @Autowired private CamelContext context; @Test public void testIsMtomEnabledEnabledThroughBeanSetter() throws InterruptedException { Endpoint endpoint = context.getEndpoint("cxf:bean:mtomByBeanSetter"); if (endpoint instanceof CxfEndpoint) { CxfEndpoint cxfEndpoint = (CxfEndpoint) endpoint; assertTrue(cxfEndpoint.isMtomEnabled(), "Mtom should be enabled"); } else { fail("CXF Endpoint not found"); } } @Test public void testIsMtomEnabledEnabledThroughBeanProperties() throws InterruptedException { Endpoint endpoint = context.getEndpoint("cxf:bean:mtomByBeanProperties"); if (endpoint instanceof CxfEndpoint) { CxfEndpoint cxfEndpoint = (CxfEndpoint) endpoint; assertTrue(cxfEndpoint.isMtomEnabled(), "Mtom should be enabled"); } else { fail("CXF Endpoint not found"); } } @Test public void testIsMtomEnabledEnabledThroughURIProperties() throws InterruptedException { Endpoint endpoint = context.getEndpoint("cxf:bean:mtomByURIProperties?properties.mtom-enabled=true"); if (endpoint instanceof CxfEndpoint) { CxfEndpoint cxfEndpoint = (CxfEndpoint) endpoint; assertTrue(cxfEndpoint.isMtomEnabled(), "Mtom should be enabled"); } else { fail("CXF Endpoint not found"); } } @Test public void testIsMtomEnabledEnabledThroughQueryParameters() throws InterruptedException { Endpoint endpoint = context.getEndpoint("cxf:bean:mtomByQueryParameters?mtomEnabled=true"); if (endpoint instanceof CxfEndpoint) { CxfEndpoint cxfEndpoint = (CxfEndpoint) endpoint; assertTrue(cxfEndpoint.isMtomEnabled(), "Mtom should be enabled"); } else { fail("CXF Endpoint not found"); } } @Configuration static class TestConfig { @Bean public CamelContext context() { return new SpringCamelContext(); } @Bean("mtomByQueryParameters") public CxfEndpoint mtomByQueryParameters(CamelContext context) { CxfEndpoint endpoint = new CxfEndpoint(); endpoint.setCamelContext(context); return endpoint; } @Bean("mtomByURIProperties") public CxfEndpoint mtomByURIProperties() { return new CxfEndpoint(); } @Bean("mtomByBeanProperties") public CxfEndpoint mtomByBeanProperties() { CxfEndpoint endpoint = new CxfEndpoint(); Map<String, Object> properties = new HashMap<>(); properties.put(Message.MTOM_ENABLED, true); endpoint.setProperties(properties); return endpoint; } @Bean("mtomByBeanSetter") public CxfEndpoint mtomByBeanSetter() { CxfEndpoint endpoint = new CxfEndpoint(); endpoint.setMtomEnabled(true); return endpoint; } } }
{ "content_hash": "e92bc5c38450b3dac87de60e8028a26e", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 109, "avg_line_length": 34.252100840336134, "alnum_prop": 0.6894013738959764, "repo_name": "tadayosi/camel", "id": "8949ecd16d1685b50d77a6b07307403cf4d59c7d", "size": "4878", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "components/camel-cxf/camel-cxf-spring-soap/src/test/java/org/apache/camel/component/cxf/CxfComponentEnableMtomTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6695" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Dockerfile", "bytes": "5676" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "405043" }, { "name": "HTML", "bytes": "212954" }, { "name": "Java", "bytes": "114726986" }, { "name": "JavaScript", "bytes": "103655" }, { "name": "Jsonnet", "bytes": "1734" }, { "name": "Kotlin", "bytes": "41869" }, { "name": "Mustache", "bytes": "525" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Ruby", "bytes": "88" }, { "name": "Shell", "bytes": "15327" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "699" }, { "name": "XSLT", "bytes": "276597" } ], "symlink_target": "" }
module Replay module Router def self.included(base) base.class_exec do include Replay::Subscriptions extend ClassMethods if base.include?(Singleton) end end def add_observer(observer, *events) add_subscriber observer end module ClassMethods def add_observer(observer, *events) instance.add_subscriber(observer) end def published(envelope) instance.published( envelope) end end end end
{ "content_hash": "92ae661821853c3b76d291c4b55b2c76", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 55, "avg_line_length": 20.416666666666668, "alnum_prop": 0.6469387755102041, "repo_name": "karmajunkie/replay", "id": "6b83683ed8e96408152cc9d97bb14fa09075ca31", "size": "490", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/replay/router.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "34264" } ], "symlink_target": "" }
import { ColumnView } from '../scene/view/column.view'; import { TemplatePath } from '../template/template.path'; import { DataColumnModel } from './data.column.model'; TemplatePath.register('group-summary-cell', (template, column) => ({ model: template.for, resource: column.key, })); export class GroupSummaryColumnModel extends DataColumnModel { constructor() { super('group-summary'); this.key = '$group.summary'; this.category = 'control'; this.canEdit = false; this.canResize = false; this.canHighlight = false; this.canFilter = false; this.canSort = false; this.canMove = false; } } export class GroupSummaryColumn extends ColumnView { constructor(model) { super(model); } static model(model) { return model ? GroupSummaryColumn.assign(model) : new GroupSummaryColumnModel(); } }
{ "content_hash": "3c33070bd28ceb31767089423db48bb1", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 84, "avg_line_length": 25.08823529411765, "alnum_prop": 0.6858147713950762, "repo_name": "qgrid/ng2", "id": "713c0d1827ca05470a0675890c8fa2b132deff0f", "size": "853", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/qgrid-core/src/column-type/group.summary.column.js", "mode": "33188", "license": "mit", "language": [ { "name": "Gherkin", "bytes": "82564" }, { "name": "HTML", "bytes": "225314" }, { "name": "JavaScript", "bytes": "669142" }, { "name": "SCSS", "bytes": "76745" }, { "name": "TypeScript", "bytes": "581689" } ], "symlink_target": "" }
package fr.inra.maiage.bibliome.alvisir.core.expand.explanation; import java.io.IOException; import java.util.Collections; import java.util.List; import fr.inra.maiage.bibliome.alvisir.core.AlvisIRIndex; import fr.inra.maiage.bibliome.alvisir.core.SearchConfig; import fr.inra.maiage.bibliome.alvisir.core.query.AlvisIROrQueryNode; import fr.inra.maiage.bibliome.alvisir.core.query.AlvisIRQueryNode; /** * Match explanation for a disjunction of explanations. * @author rbossy * */ public class CompositeExpansionExplanation extends MatchExplanation { private final List<MatchExplanation> explanations; public CompositeExpansionExplanation(String fieldName, List<MatchExplanation> explanations) { super(fieldName); this.explanations = explanations; } @Override public AlvisIRQueryNode getQueryNode() { AlvisIROrQueryNode result = new AlvisIROrQueryNode(); for (MatchExplanation ex : explanations) { result.addClause(ex.getQueryNode()); } return result; } public List<MatchExplanation> getexplanations() { return Collections.unmodifiableList(explanations); } @Override protected PayloadDecoder getPayloadDecoder() { return new MatchExplanationPayloadDecoder(); } @Override public String toString() { StringBuilder sb = new StringBuilder("CompositeExpansionExplanation("); boolean notFirst = false; for (MatchExplanation e : explanations) { if (notFirst) sb.append(", "); else notFirst = true; sb.append(e); } return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((explanations == null) ? 0 : explanations.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CompositeExpansionExplanation other = (CompositeExpansionExplanation) obj; if (explanations == null) { if (other.explanations != null) return false; } else if (!explanations.equals(other.explanations)) return false; return true; } @Override public int computeProductivity(AlvisIRIndex index, SearchConfig searchConfig) throws IOException { for (MatchExplanation expl : explanations) { expl.computeProductivity(index, searchConfig); } return super.computeProductivity(index, searchConfig); } }
{ "content_hash": "30195011f3a78d1901101037bba947ef", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 99, "avg_line_length": 26.522222222222222, "alnum_prop": 0.744449099287809, "repo_name": "Bibliome/alvisir", "id": "5a53f464a438c92109a322da8472033d1ca34fe5", "size": "2387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alvisir-core/src/main/java/fr/inra/maiage/bibliome/alvisir/core/expand/explanation/CompositeExpansionExplanation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "482406" }, { "name": "HTML", "bytes": "3857" }, { "name": "Java", "bytes": "373216" }, { "name": "JavaScript", "bytes": "53350" }, { "name": "Shell", "bytes": "1225" }, { "name": "XSLT", "bytes": "54808" } ], "symlink_target": "" }
@interface PodsDummy_BGMapPreview : NSObject @end @implementation PodsDummy_BGMapPreview @end
{ "content_hash": "d1d95e1bd72346d78948453b60f3712f", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 44, "avg_line_length": 23.5, "alnum_prop": 0.8404255319148937, "repo_name": "bartguminiak/BGMapPreview", "id": "e6ee47ade4d07f2c7f1d8c4d1c96c409df89539b", "size": "128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/BGMapPreview/BGMapPreview-dummy.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "49628" }, { "name": "Ruby", "bytes": "924" } ], "symlink_target": "" }
package com.netflix.atlas.core.model import java.util.concurrent.TimeUnit import java.util.stream.Collectors import com.netflix.atlas.core.stacklang.Interpreter import com.netflix.spectator.api.Counter import com.netflix.spectator.api.DefaultRegistry import com.netflix.spectator.api.histogram.PercentileBuckets import com.netflix.spectator.api.histogram.PercentileDistributionSummary import com.netflix.spectator.api.histogram.PercentileTimer import munit.FunSuite import scala.language.postfixOps class PercentilesSuite extends FunSuite { private val interpreter = Interpreter(MathVocabulary.allWords) private val start = 0L private val step = 60000L private val context = EvalContext(start, start + step * 2, step) def ts(bucket: String, values: Double*): TimeSeries = { val seq = new ArrayTimeSeq(DsType.Gauge, start, step, values.toArray) val mode = if (Integer.parseInt(bucket.substring(1), 16) % 2 == 0) "even" else "odd" TimeSeries(Map("name" -> "test", "mode" -> mode, "percentile" -> bucket), seq) } def eval(str: String, input: List[TimeSeries]): List[TimeSeries] = { val expr = interpreter.execute(str).stack match { case (v: TimeSeriesExpr) :: _ => v case _ => throw new IllegalArgumentException("invalid expr") } expr.eval(context, input).data } private val input100 = { (0 until 100).map { i => val bucket = f"D${PercentileBuckets.indexOf(i)}%04X" val v = 1.0 / 60.0 ts(bucket, v, v) } toList } private val inputBad100 = { // simulates bad client that incorrectly encodes the percentile tag (0 until 100).map { i => val bucket = f"D${PercentileBuckets.indexOf(i)}%04x" val v = 1.0 / 60.0 ts(bucket, v, v) } toList } private val inputTimer100 = { (0 until 100).map { i => val bucket = f"T${PercentileBuckets.indexOf(i)}%04X" val v = 1.0 / 60.0 ts(bucket, v, v) } toList } private val inputNaN = { (0 until 100).map { i => val bucket = f"D${PercentileBuckets.indexOf(i)}%04X" val v = Double.NaN ts(bucket, v, v) } toList } private val inputSpectatorTimer = { import scala.jdk.CollectionConverters._ val r = new DefaultRegistry() val t = PercentileTimer.get(r, r.createId("test")) (0 until 100).foreach { i => t.record(i, TimeUnit.MILLISECONDS) } val counters = r.counters.collect(Collectors.toList[Counter]).asScala.toList counters.map { c => val v = c.count / 60.0 val seq = new ArrayTimeSeq(DsType.Gauge, start, step, Array(v, v)) val tags = c.id.tags.asScala.map(t => t.key -> t.value).toMap + ("name" -> c.id.name) TimeSeries(tags, seq) } } private val inputSpectatorDistSummary = { import scala.jdk.CollectionConverters._ val r = new DefaultRegistry() val t = PercentileDistributionSummary.get(r, r.createId("test")) (0 until 100).foreach { i => t.record(i) } val counters = r.counters.collect(Collectors.toList[Counter]).asScala.toList counters.map { c => val v = c.count / 60.0 val seq = new ArrayTimeSeq(DsType.Gauge, start, step, Array(v, v)) val tags = c.id.tags.asScala.map(t => t.key -> t.value).toMap + ("name" -> c.id.name) TimeSeries(tags, seq) } } test("distribution summary :sum") { val data = eval("name,test,:eq,(,9,25,50,90,100,),:percentiles", input100) assertEquals(data.size, 5) List(9.0, 25.0, 50.0, 90.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile(name=test, $p%5.1f)") assertEqualsDouble(p, estimate, 2.0) } assertEquals(data.last.label, f"percentile(name=test, 100.0)") } test("distribution summary, bad data") { val e = intercept[IllegalArgumentException] { eval("name,test,:eq,(,9,25,50,90,100,),:percentiles", input100 ::: inputBad100) } assertEquals(e.getMessage, "requirement failed: invalid percentile encoding: [D000A,D000a]") } test("timer :sum") { val data = eval("name,test,:eq,(,25,50,90,),:percentiles", inputTimer100) assertEquals(data.size, 3) List(25.0, 50.0, 90.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile(name=test, $p%5.1f)") assertEqualsDouble(p / 1e9, estimate, 2.0e-9) } } test("spectator distribution summary :sum") { val data = eval("name,test,:eq,(,9,25,50,90,100,),:percentiles", inputSpectatorDistSummary) assertEquals(data.size, 5) List(9.0, 25.0, 50.0, 90.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile(name=test, $p%5.1f)") assertEqualsDouble(p, estimate, 2.0) } assertEquals(data.last.label, f"percentile(name=test, 100.0)") } test("spectator timer :sum") { val data = eval("name,test,:eq,(,25,50,90,),:percentiles", inputSpectatorTimer) assertEquals(data.size, 3) List(25.0, 50.0, 90.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile(name=test, $p%5.1f)") // Values were 0 ot 100 recorded in milliseconds, should be reported in seconds assertEqualsDouble(p / 1e3, estimate, 2.0e-3) } } private def checkPercentile(v: Double, s: String): Unit = { val data = eval(s"name,test,:eq,(,$v,),:percentiles", inputSpectatorTimer) assertEquals(data.size, 1) List(v).zip(data).foreach { case (p, t) => assertEquals(t.tags, Map("name" -> "test", "percentile" -> s)) assertEquals(t.label, f"percentile(name=test, $s)") } } test("9.99999999th percentile") { checkPercentile(9.99999999, " 9.99999999") } test("99.99th percentile") { checkPercentile(99.99, " 99.99") } test("99.999999th percentile") { checkPercentile(99.999999, " 99.999999") } test("distribution summary :max") { val data = eval("name,test,:eq,:max,(,25,50,90,),:percentiles", input100) assertEquals(data.size, 3) List(25.0, 50.0, 90.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile(name=test, $p%5.1f)") assertEqualsDouble(p, estimate, 2.0) } } test("distribution summary :median") { val data = eval("name,test,:eq,:median", input100) assertEquals(data.size, 1) List(50.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile(name=test, $p%5.1f)") assertEqualsDouble(p, estimate, 2.0) } } test("group by empty") { val data = eval("name,test,:eq,(,foo,),:by,(,25,50,90,),:percentiles", input100) assertEquals(data.size, 0) } test("group by with single result") { val data = eval("name,test,:eq,(,name,),:by,(,25,50,90,),:percentiles", input100) assertEquals(data.size, 3) List(25.0, 50.0, 90.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile((name=test), $p%5.1f)") assertEqualsDouble(p, estimate, 2.0) } } test("group by with multiple results") { val data = eval("name,test,:eq,(,mode,),:by,(,25,50,90,),:percentiles", input100) assertEquals(data.size, 6) List(25.0, 50.0, 90.0).zip(data.filter(_.tags("mode") == "even")).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "mode" -> "even", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile((mode=even), $p%5.1f)") assertEqualsDouble(p, estimate, 10.0) } List(25.0, 50.0, 90.0).zip(data.filter(_.tags("mode") == "odd")).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "mode" -> "odd", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile((mode=odd), $p%5.1f)") assertEqualsDouble(p, estimate, 10.0) } } test("group by multi-level") { val data = eval( "name,test,:eq,(,mode,),:by,(,25,50,90,),:percentiles,:max,(,percentile,),:by", input100 ) assertEquals(data.size, 3) List(25.0, 50.0, 90.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("name" -> "test", "percentile" -> f"$p%5.1f")) assertEquals(t.label, f"(percentile=$p%5.1f)") assertEqualsDouble(p, estimate, 10.0) } } test("distribution summary empty") { val data = eval(":false,(,25,50,90,),:percentiles", input100) assertEquals(data.size, 0) } test("distribution summary NaN") { val data = eval(":true,(,25,50,90,),:percentiles", inputNaN) assertEquals(data.size, 3) List(25.0, 50.0, 90.0).zip(data).foreach { case (p, t) => val estimate = t.data(0L) assertEquals(t.tags, Map("percentile" -> f"$p%5.1f")) assertEquals(t.label, f"percentile(true, $p%5.1f)") assert(estimate.isNaN) } } test("bad input: too small") { intercept[IllegalArgumentException] { eval("name,test,:eq,(,-1,),:percentiles", input100) } } test("bad input: too big") { intercept[IllegalArgumentException] { eval("name,test,:eq,(,100.1,),:percentiles", input100) } } test("bad input: string in list") { intercept[IllegalStateException] { eval("name,test,:eq,(,50,foo,),:percentiles", input100) } } test("bad input: unsupported :head") { intercept[IllegalStateException] { eval("name,test,:eq,(,mode,),:by,4,:head,(,50,),:percentiles", input100) } } test("bad input: unsupported :all") { intercept[IllegalStateException] { eval("name,test,:eq,:all,(,50,),:percentiles", input100) } } test("bad input: response data does not have percentile tag") { val input = input100.map(t => t.withTags(t.tags - TagKey.percentile)) val data = eval("name,test,:eq,(,50,),:percentiles", input) assert(data.isEmpty) } test("bad input: no matches") { val data = eval("name,test,:eq,(,50,),:percentiles", Nil) assert(data.isEmpty) } test("bad input: DataExpr -> NoDataLine") { val by = DataExpr.GroupBy(DataExpr.Sum(Query.True), List("percentile")) val expr = MathExpr.Percentiles(by, List(50.0)) val input = Map[DataExpr, List[TimeSeries]](by -> List(TimeSeries.noData(step))) val ts = expr.eval(context, input).data assertEquals(ts.size, 1) assertEquals(ts.head.tags, Map("name" -> "NO_DATA")) assertEquals(ts.head.label, "NO DATA") } }
{ "content_hash": "25cfd19a133cb48d9bd009a52bab4f93", "timestamp": "", "source": "github", "line_count": 340, "max_line_length": 97, "avg_line_length": 33.04117647058823, "alnum_prop": 0.6124265622218266, "repo_name": "Netflix/atlas", "id": "1bc1a95b73b644af7adae6dc68ee1af97678b74e", "size": "11835", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "atlas-core/src/test/scala/com/netflix/atlas/core/model/PercentilesSuite.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "99" }, { "name": "Java", "bytes": "38162" }, { "name": "Makefile", "bytes": "2344" }, { "name": "Scala", "bytes": "2309396" }, { "name": "Shell", "bytes": "2427" } ], "symlink_target": "" }
#import "PNChannel.h" #import "PNString.h" #import "PNArray.h" #pragma mark Static /** @brief Reference on suffix which is used to mark channel as presence channel. @since 4.0 */ static NSString * const kPubNubPresenceChannelNameSuffix = @"-pnpres"; #pragma mark Interface implementation @implementation PNChannel #pragma mark - Lists encoding + (nullable NSString *)namesForRequest:(NSArray<NSString *> *)names { return [self namesForRequest:names defaultString:nil]; } + (nullable NSString *)namesForRequest:(NSArray<NSString *> *)names defaultString:(nullable NSString *)defaultString { NSString *namesForRequest = defaultString; if (names.count) { NSArray *escapedNames = [PNArray mapObjects:names usingBlock:^NSString *(NSString *object){ return [PNString percentEscapedString:object]; }]; namesForRequest = [escapedNames componentsJoinedByString:@","]; } return namesForRequest; } #pragma mark - Lists decoding + (NSArray<NSString *> *)namesFromRequest:(NSString *)response { return [response componentsSeparatedByString:@","]; } #pragma mark - Subscriber helper + (BOOL)isPresenceObject:(NSString *)object { return [object hasSuffix:kPubNubPresenceChannelNameSuffix]; } + (NSString *)channelForPresence:(NSString *)presenceChannel { return [presenceChannel stringByReplacingOccurrencesOfString:kPubNubPresenceChannelNameSuffix withString:@""]; } + (NSArray<NSString *> *)presenceChannelsFrom:(NSArray<NSString *> *)names { NSMutableSet *presenceNames = [[NSMutableSet alloc] initWithCapacity:names.count]; for (NSString *name in names) { NSString *targetName = name; if (![name hasSuffix:kPubNubPresenceChannelNameSuffix]) { targetName = [name stringByAppendingString:kPubNubPresenceChannelNameSuffix]; } [presenceNames addObject:targetName]; } return [presenceNames.allObjects copy]; } + (NSArray<NSString *> *)objectsWithOutPresenceFrom:(NSArray<NSString *> *)names { NSMutableSet *filteredNames = [[NSMutableSet alloc] initWithCapacity:names.count]; for (NSString *name in names) { if (![name hasSuffix:kPubNubPresenceChannelNameSuffix]) { [filteredNames addObject:name]; } } return [filteredNames.allObjects copy]; } #pragma mark - @end
{ "content_hash": "7d39d9e97a327ad693bdacbca02ed446", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 99, "avg_line_length": 25.4, "alnum_prop": 0.6614173228346457, "repo_name": "iOS-Connect/Connect", "id": "e50dea9901e7959d4fac1f44cd39341bf3caa1c4", "size": "2622", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Pods/PubNub/PubNub/Misc/Helpers/PNChannel.m", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "2861" }, { "name": "Swift", "bytes": "31807" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- You may freely edit this file. See commented blocks below for --> <!-- some examples of how to customize the build. --> <!-- (If you delete it and reopen the project it will be recreated.) --> <!-- By default, only the Clean and Build commands use this build script. --> <!-- Commands such as Run, Debug, and Test only use this build script if --> <!-- the Compile on Save feature is turned off for the project. --> <!-- You can turn off the Compile on Save (or Deploy on Save) setting --> <!-- in the project's Project Properties dialog box.--> <project name="fs-aisystem" default="default" basedir="."> <description>Builds, tests, and runs the project fs-aisystem.</description> <import file="nbproject/build-impl.xml"/> <!-- There exist several targets which are by default empty and which can be used for execution of your tasks. These targets are usually executed before and after some main targets. They are: -pre-init: called before initialization of project properties -post-init: called after initialization of project properties -pre-compile: called before javac compilation -post-compile: called after javac compilation -pre-compile-single: called before javac compilation of single file -post-compile-single: called after javac compilation of single file -pre-compile-test: called before javac compilation of JUnit tests -post-compile-test: called after javac compilation of JUnit tests -pre-compile-test-single: called before javac compilation of single JUnit test -post-compile-test-single: called after javac compilation of single JUunit test -pre-jar: called before JAR building -post-jar: called after JAR building -post-clean: called after cleaning build products (Targets beginning with '-' are not intended to be called on their own.) Example of inserting an obfuscator after compilation could look like this: <target name="-post-compile"> <obfuscate> <fileset dir="${build.classes.dir}"/> </obfuscate> </target> For list of available properties check the imported nbproject/build-impl.xml file. Another way to customize the build is by overriding existing main targets. The targets of interest are: -init-macrodef-javac: defines macro for javac compilation -init-macrodef-junit: defines macro for junit execution -init-macrodef-debug: defines macro for class debugging -init-macrodef-java: defines macro for class execution -do-jar-with-manifest: JAR building (if you are using a manifest) -do-jar-without-manifest: JAR building (if you are not using a manifest) run: execution of project -javadoc-build: Javadoc generation test-report: JUnit report generation An example of overriding the target for project execution could look like this: <target name="run" depends="fs-aisystem-impl.jar"> <exec dir="bin" executable="launcher.exe"> <arg file="${dist.jar}"/> </exec> </target> Notice that the overridden target depends on the jar target and not only on the compile target as the regular run target does. Again, for a list of available properties which you can use, check the target you are overriding in the nbproject/build-impl.xml file. --> </project>
{ "content_hash": "68191555b9cb145cbe67b25695f6eecc", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 86, "avg_line_length": 50.37837837837838, "alnum_prop": 0.6456545064377682, "repo_name": "ForgottenSpace/FS-GameEngine", "id": "0428c23c7958434344de6ccf3a9744016618f8b8", "size": "3728", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fs-libraries/fs-aisystem/build.xml", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE html> <title>Credential Manager: store() basics.</title> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> <script> function stubResolverChecker(c) { assert_equals(c, undefined, "FIXME: We're currently always returning 'undefined'."); this.done(); } function stubRejectionChecker(reason) { assert_unreached("store() should not reject, but did: " + reason.name); } var local = new PasswordCredential('id', 'pencil', 'name', 'https://example.com/icon.png'); var federated = new FederatedCredential({ 'id': 'id', 'provider': 'https://federation.test/', 'name': 'name', 'iconURL': 'https://example.test/icon.png' }); async_test(function () { navigator.credentials.store().then( this.step_func(function () { assert_unreached("store() should reject."); }), this.step_func(function (reason) { assert_equals(reason.name, "TypeError"); this.done(); })); }, "Verify the basics of store(): PasswordCredential."); async_test(function () { navigator.credentials.store("not a credential").then( this.step_func(function () { assert_unreached("store([string]) should reject."); }), this.step_func(function (reason) { assert_equals(reason.name, "TypeError"); this.done(); })); }, "Verify the basics of store(): PasswordCredential."); async_test(function () { navigator.credentials.store(local).then( this.step_func(stubResolverChecker.bind(this)), this.step_func(stubRejectionChecker.bind(this))); }, "Verify the basics of store(): PasswordCredential."); async_test(function () { navigator.credentials.store(federated).then( this.step_func(stubResolverChecker.bind(this)), this.step_func(stubRejectionChecker.bind(this))); }, "Verify the basics of store(): FederatedCredential."); </script>
{ "content_hash": "acb4e3e57d3666bca79e31a496edda16", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 92, "avg_line_length": 36.96153846153846, "alnum_prop": 0.6571279916753382, "repo_name": "vadimtk/chrome4sdp", "id": "a5ca87b7c72b1609eed95a5b6f0bb4c62352d7c3", "size": "1922", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/WebKit/LayoutTests/http/tests/credentialmanager/credentialscontainer-store-basics.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php namespace NilPortugues\SchemaOrg\Classes; use NilPortugues\SchemaOrg\SchemaClass; /** * METHODSTART. * * @method static \NilPortugues\SchemaOrg\Properties\BranchCodeProperty branchCode() * @method static \NilPortugues\SchemaOrg\Properties\BranchOfProperty branchOf() * @method static \NilPortugues\SchemaOrg\Properties\CurrenciesAcceptedProperty currenciesAccepted() * @method static \NilPortugues\SchemaOrg\Properties\OpeningHoursProperty openingHours() * @method static \NilPortugues\SchemaOrg\Properties\PaymentAcceptedProperty paymentAccepted() * @method static \NilPortugues\SchemaOrg\Properties\PriceRangeProperty priceRange() * @method static \NilPortugues\SchemaOrg\Properties\HasOfferCatalogProperty hasOfferCatalog() * @method static \NilPortugues\SchemaOrg\Properties\AddressProperty address() * @method static \NilPortugues\SchemaOrg\Properties\AggregateRatingProperty aggregateRating() * @method static \NilPortugues\SchemaOrg\Properties\AlumniProperty alumni() * @method static \NilPortugues\SchemaOrg\Properties\AreaServedProperty areaServed() * @method static \NilPortugues\SchemaOrg\Properties\AwardProperty award() * @method static \NilPortugues\SchemaOrg\Properties\AwardsProperty awards() * @method static \NilPortugues\SchemaOrg\Properties\ParentOrganizationProperty parentOrganization() * @method static \NilPortugues\SchemaOrg\Properties\BrandProperty brand() * @method static \NilPortugues\SchemaOrg\Properties\ContactPointProperty contactPoint() * @method static \NilPortugues\SchemaOrg\Properties\ContactPointsProperty contactPoints() * @method static \NilPortugues\SchemaOrg\Properties\DepartmentProperty department() * @method static \NilPortugues\SchemaOrg\Properties\DunsProperty duns() * @method static \NilPortugues\SchemaOrg\Properties\EmailProperty email() * @method static \NilPortugues\SchemaOrg\Properties\EmployeeProperty employee() * @method static \NilPortugues\SchemaOrg\Properties\EmployeesProperty employees() * @method static \NilPortugues\SchemaOrg\Properties\EventProperty event() * @method static \NilPortugues\SchemaOrg\Properties\EventsProperty events() * @method static \NilPortugues\SchemaOrg\Properties\FaxNumberProperty faxNumber() * @method static \NilPortugues\SchemaOrg\Properties\FounderProperty founder() * @method static \NilPortugues\SchemaOrg\Properties\FoundersProperty founders() * @method static \NilPortugues\SchemaOrg\Properties\DissolutionDateProperty dissolutionDate() * @method static \NilPortugues\SchemaOrg\Properties\FoundingDateProperty foundingDate() * @method static \NilPortugues\SchemaOrg\Properties\GlobalLocationNumberProperty globalLocationNumber() * @method static \NilPortugues\SchemaOrg\Properties\HasPOSProperty hasPOS() * @method static \NilPortugues\SchemaOrg\Properties\IsicV4Property isicV4() * @method static \NilPortugues\SchemaOrg\Properties\LegalNameProperty legalName() * @method static \NilPortugues\SchemaOrg\Properties\LocationProperty location() * @method static \NilPortugues\SchemaOrg\Properties\LogoProperty logo() * @method static \NilPortugues\SchemaOrg\Properties\MakesOfferProperty makesOffer() * @method static \NilPortugues\SchemaOrg\Properties\MemberProperty member() * @method static \NilPortugues\SchemaOrg\Properties\MemberOfProperty memberOf() * @method static \NilPortugues\SchemaOrg\Properties\MembersProperty members() * @method static \NilPortugues\SchemaOrg\Properties\NaicsProperty naics() * @method static \NilPortugues\SchemaOrg\Properties\NumberOfEmployeesProperty numberOfEmployees() * @method static \NilPortugues\SchemaOrg\Properties\OwnsProperty owns() * @method static \NilPortugues\SchemaOrg\Properties\ReviewProperty review() * @method static \NilPortugues\SchemaOrg\Properties\ReviewsProperty reviews() * @method static \NilPortugues\SchemaOrg\Properties\SeeksProperty seeks() * @method static \NilPortugues\SchemaOrg\Properties\ServiceAreaProperty serviceArea() * @method static \NilPortugues\SchemaOrg\Properties\SubOrganizationProperty subOrganization() * @method static \NilPortugues\SchemaOrg\Properties\TaxIDProperty taxID() * @method static \NilPortugues\SchemaOrg\Properties\TelephoneProperty telephone() * @method static \NilPortugues\SchemaOrg\Properties\VatIDProperty vatID() * @method static \NilPortugues\SchemaOrg\Properties\AdditionalTypeProperty additionalType() * @method static \NilPortugues\SchemaOrg\Properties\AlternateNameProperty alternateName() * @method static \NilPortugues\SchemaOrg\Properties\DescriptionProperty description() * @method static \NilPortugues\SchemaOrg\Properties\ImageProperty image() * @method static \NilPortugues\SchemaOrg\Properties\MainEntityOfPageProperty mainEntityOfPage() * @method static \NilPortugues\SchemaOrg\Properties\NameProperty name() * @method static \NilPortugues\SchemaOrg\Properties\SameAsProperty sameAs() * @method static \NilPortugues\SchemaOrg\Properties\UrlProperty url() * @method static \NilPortugues\SchemaOrg\Properties\PotentialActionProperty potentialAction() * @method static \NilPortugues\SchemaOrg\Properties\ContainedInPlaceProperty containedInPlace() * @method static \NilPortugues\SchemaOrg\Properties\ContainsPlaceProperty containsPlace() * @method static \NilPortugues\SchemaOrg\Properties\ContainedInProperty containedIn() * @method static \NilPortugues\SchemaOrg\Properties\GeoProperty geo() * @method static \NilPortugues\SchemaOrg\Properties\HasMapProperty hasMap() * @method static \NilPortugues\SchemaOrg\Properties\MapProperty map() * @method static \NilPortugues\SchemaOrg\Properties\MapsProperty maps() * @method static \NilPortugues\SchemaOrg\Properties\OpeningHoursSpecificationProperty openingHoursSpecification() * @method static \NilPortugues\SchemaOrg\Properties\PhotoProperty photo() * @method static \NilPortugues\SchemaOrg\Properties\PhotosProperty photos() * @method static \NilPortugues\SchemaOrg\Properties\AdditionalPropertyProperty additionalProperty() * METHODEND. * * A men's clothing store. */ class MensClothingStore extends SchemaClass { /** * @var string */ protected static $schemaUrl = 'http://schema.org/MensClothingStore'; /** * @var array */ protected static $supportedMethods = [ 'additionalProperty' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AdditionalPropertyProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'additionalType' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AdditionalTypeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'address' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AddressProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'aggregateRating' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AggregateRatingProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'alternateName' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AlternateNameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'alumni' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AlumniProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'areaServed' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AreaServedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'award' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AwardProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'awards' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AwardsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'branchCode' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BranchCodeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'branchOf' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BranchOfProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'brand' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BrandProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'contactPoint' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContactPointProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'contactPoints' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContactPointsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'containedIn' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainedInProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'containedInPlace' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainedInPlaceProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'containsPlace' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainsPlaceProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'currenciesAccepted' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\CurrenciesAcceptedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'department' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DepartmentProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'description' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DescriptionProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'dissolutionDate' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DissolutionDateProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'duns' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DunsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'email' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmailProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'employee' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmployeeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'employees' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmployeesProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'event' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EventProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'events' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EventsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'faxNumber' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FaxNumberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'founder' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FounderProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'founders' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FoundersProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'foundingDate' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FoundingDateProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'geo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\GeoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'globalLocationNumber' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\GlobalLocationNumberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'hasMap' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasMapProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'hasOfferCatalog' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasOfferCatalogProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'hasPOS' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasPOSProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'image' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ImageProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'isicV4' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\IsicV4Property', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'legalName' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LegalNameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'location' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LocationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'logo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LogoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'mainEntityOfPage' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MainEntityOfPageProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'makesOffer' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MakesOfferProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'map' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MapProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'maps' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MapsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'member' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MemberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'memberOf' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MemberOfProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'members' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MembersProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'naics' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NaicsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'name' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'numberOfEmployees' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NumberOfEmployeesProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'openingHours' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OpeningHoursProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'openingHoursSpecification' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OpeningHoursSpecificationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'owns' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OwnsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'parentOrganization' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ParentOrganizationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'paymentAccepted' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PaymentAcceptedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'photo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PhotoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'photos' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PhotosProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'potentialAction' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PotentialActionProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'priceRange' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PriceRangeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'review' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ReviewProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'reviews' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ReviewsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'sameAs' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SameAsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'seeks' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SeeksProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'serviceArea' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ServiceAreaProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'subOrganization' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SubOrganizationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'taxID' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\TaxIDProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'telephone' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\TelephoneProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'url' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\UrlProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'vatID' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\VatIDProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], ]; }
{ "content_hash": "0d249d272eee95a83a1b60590098edbb", "timestamp": "", "source": "github", "line_count": 377, "max_line_length": 114, "avg_line_length": 53.281167108753316, "alnum_prop": 0.6684920595409967, "repo_name": "nilportugues/php-schema.org-mapping", "id": "a5fe408365da62c5f369f39b2212cbf50ea1a322", "size": "20323", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Classes/MensClothingStore.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "13275991" } ], "symlink_target": "" }
#pragma once #include "ImageDevice.h" #include "AudioDevice.h" #include <XnCppWrapper.h> namespace nui{ class Xtion : public AudioInputDevice , public ImageDevice { static const XnUInt16 MAX_DEPTH_NUM = 10000; xn::ImageGenerator m_imageGenerator; xn::DepthGenerator m_depthGenerator; xn::AudioGenerator m_audioGenerator; void initDepthGenerator(const xn::Context &context); void initImageGenerator(const xn::Context &context); void initAudioGenerator(xn::Context &context); public: bool isValid(); NIMat rgbImage(); NIMat depthImage(); void convertRealWorldToProjective(float &x,float &y, float &z); Xtion(xn::Context &context); void setAudioConfig(const AudioConfig &config); AudioConfig audioConfig(); const unsigned char* audioBuffer(){ return m_audioGenerator.GetAudioBuffer(); } }; } //namespace nui
{ "content_hash": "bab1cf6043ebb6784bc3242c098a7617", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 87, "avg_line_length": 29.757575757575758, "alnum_prop": 0.6456211812627292, "repo_name": "RoboticsDevelopmentProjects/spp-base-library", "id": "42f1c95ab91b6c3357494cd2573fcf8e66feb18a", "size": "1264", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/RDP/UserRecognition/Xtion.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "24868" }, { "name": "C++", "bytes": "81711" }, { "name": "Python", "bytes": "2849" } ], "symlink_target": "" }
here=`pwd` if test $? -ne 0; then exit 2; fi tmp=/tmp/$$ mkdir $tmp if test $? -ne 0; then exit 2; fi cd $tmp if test $? -ne 0; then exit 2; fi fail() { echo "FAILED" 1>&2 cd $here chmod -R u+w $tmp rm -rf $tmp killall /usr/bin/X11/Xvfb exit 1 } pass() { echo "PASSED" 1>&2 cd $here chmod -R u+w $tmp rm -rf $tmp killall /usr/bin/X11/Xvfb exit 0 } trap "fail" 1 2 3 15 if [ -n "$AEGIS_ARCH" ]; then XECOLAB=`aefind -resolve $here/include -name Xecolab.tcl -print` else XECOLAB=$here/include/Xecolab.tcl fi # insert ecolab script code here # use \$ in place of $ to refer to variable contents # exit 0 to indicate pass, and exit 1 to indicate failure cat >input.tcl <<EOF set ecolab_library [file dirname $XECOLAB] GUI urand gen gen.set_gen mt19937(19863) histogram ran [gen.rand] histogram ran [gen.rand] exit_ecolab EOF # for some reason this test fails at integration # crude test of being in integration mode if [ "${here%delta*}" != $here ]; then pass; fi if [ ! -x /usr/bin/X11/Xvfb ]; then pass; fi DISPLAY=:30 export DISPLAY killall /usr/bin/X11/Xvfb /usr/bin/X11/Xvfb $DISPLAY & #startx -- /usr/bin/Xvfb :2& sleep 1 $here/models/ecolab input.tcl if test $? -ne 0; then fail; fi pass
{ "content_hash": "0efa16902d4bc40a5cb3b815fbd93c28", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 66, "avg_line_length": 18.202898550724637, "alnum_prop": 0.6544585987261147, "repo_name": "highperformancecoder/ecolab", "id": "1567b433613f63ceb6ce02e13c00a54ed36f540b", "size": "1446", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/00/t0012a.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "206" }, { "name": "C", "bytes": "229388" }, { "name": "C++", "bytes": "788864" }, { "name": "Dockerfile", "bytes": "92" }, { "name": "Makefile", "bytes": "31272" }, { "name": "Perl", "bytes": "774" }, { "name": "Shell", "bytes": "58756" }, { "name": "Tcl", "bytes": "108574" } ], "symlink_target": "" }
pub const RGN_AND: ::c_int = 1; pub const RGN_OR: ::c_int = 2; pub const RGN_XOR: ::c_int = 3; pub const RGN_DIFF: ::c_int = 4; pub const RGN_COPY: ::c_int = 5; pub const RGN_MIN: ::c_int = RGN_AND; pub const RGN_MAX: ::c_int = RGN_COPY; //572 (Win 7 SDK) #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct BITMAP { pub bmType: ::LONG, pub bmWidth: ::LONG, pub bmHeight: ::LONG, pub bmWidthBytes: ::LONG, pub bmPlanes: ::WORD, pub bmBitsPixel: ::WORD, pub bmBits: ::LPVOID, } pub type PBITMAP = *mut BITMAP; pub type NPBITMAP = *mut BITMAP; pub type LPBITMAP = *mut BITMAP; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct RGBQUAD { pub rgbBlue: ::BYTE, pub rgbGreen: ::BYTE, pub rgbRed: ::BYTE, pub rgbReserved: ::BYTE, } pub type LPRGBQUAD = *mut RGBQUAD; pub const CS_ENABLE: ::DWORD = 0x00000001; pub const CS_DISABLE: ::DWORD = 0x00000002; pub const CS_DELETE_TRANSFORM: ::DWORD = 0x00000003; pub const LCS_SIGNATURE: ::DWORD = 0x5053_4F43; // 'PSOC' pub const LCS_sRGB: LCSCSTYPE = 0x7352_4742; // 'sRGB' pub const LCS_WINDOWS_COLOR_SPACE: LCSCSTYPE = 0x5769_6E20; // 'Win ' pub type LCSCSTYPE = ::LONG; pub const LCS_CALIBRATED_RGB: LCSCSTYPE = 0x00000000; pub type LCSGAMUTMATCH = ::LONG; pub const LCS_GM_BUSINESS: LCSGAMUTMATCH = 0x00000001; pub const LCS_GM_GRAPHICS: LCSGAMUTMATCH = 0x00000002; pub const LCS_GM_IMAGES: LCSGAMUTMATCH = 0x00000004; pub const LCS_GM_ABS_COLORIMETRIC: LCSGAMUTMATCH = 0x00000008; pub const CM_OUT_OF_GAMUT: ::BYTE = 255; pub const CM_IN_GAMUT: ::BYTE = 0; pub const ICM_ADDPROFILE: ::UINT = 1; pub const ICM_DELETEPROFILE: ::UINT = 2; pub const ICM_QUERYPROFILE: ::UINT = 3; pub const ICM_SETDEFAULTPROFILE: ::UINT = 4; pub const ICM_REGISTERICMATCHER: ::UINT = 5; pub const ICM_UNREGISTERICMATCHER: ::UINT = 6; pub const ICM_QUERYMATCH: ::UINT = 7; pub type FXPT16DOT16 = ::c_long; pub type LPFXPT16DOT16 = *mut ::c_long; pub type FXPT2DOT30 = ::c_long; pub type LPFXPT2DOT30 = *mut ::c_long; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct CIEXYZ { pub ciexyzX: FXPT2DOT30, pub ciexyzY: FXPT2DOT30, pub ciexyzZ: FXPT2DOT30, } pub type LPCIEXYZ = *mut CIEXYZ; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct CIEXYZTRIPLE { pub ciexyzRed: CIEXYZ, pub ciexyzGreen: CIEXYZ, pub ciexyzBlue: CIEXYZ, } pub type LPCIEXYZTRIPLE = *mut CIEXYZTRIPLE; //716 (Win 7 SDK) #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct BITMAPINFOHEADER { pub biSize: ::DWORD, pub biWidth: ::LONG, pub biHeight: ::LONG, pub biPlanes: ::WORD, pub biBitCount: ::WORD, pub biCompression: ::DWORD, pub biSizeImage: ::DWORD, pub biXPelsPerMeter: ::LONG, pub biYPelsPerMeter: ::LONG, pub biClrUsed: ::DWORD, pub biClrImportant: ::DWORD, } pub type LPBITMAPINFOHEADER = *mut BITMAPINFOHEADER; pub type PBITMAPINFOHEADER = *mut BITMAPINFOHEADER; #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct BITMAPV5HEADER { pub bV5Size: ::DWORD, pub bV5Width: ::LONG, pub bV5Height: ::LONG, pub bV5Planes: ::WORD, pub bV5BitCount: ::WORD, pub bV5Compression: ::DWORD, pub bV5SizeImage: ::DWORD, pub bV5XPelsPerMeter: ::LONG, pub bV5YPelsPerMeter: ::LONG, pub bV5ClrUsed: ::DWORD, pub bV5ClrImportant: ::DWORD, pub bV5RedMask: ::DWORD, pub bV5GreenMask: ::DWORD, pub bV5BlueMask: ::DWORD, pub bV5AlphaMask: ::DWORD, pub bV5CSType: ::LONG, // LONG to match LOGCOLORSPACE pub bV5Endpoints: CIEXYZTRIPLE, pub bV5GammaRed: ::DWORD, pub bV5GammaGreen: ::DWORD, pub bV5GammaBlue: ::DWORD, pub bV5Intent: ::LONG, // LONG to match LOGCOLORSPACE pub bV5ProfileData: ::DWORD, pub bV5ProfileSize: ::DWORD, pub bV5Reserved: ::DWORD, } pub type LPBITMAPV5HEADER = *mut BITMAPV5HEADER; pub type PBITMAPV5HEADER = *mut BITMAPV5HEADER; pub const PROFILE_LINKED: ::LONG = 0x4C49_4E4B; // 'LINK' pub const PROFILE_EMBEDDED: ::LONG = 0x4D42_4544; // 'MBED' pub const BI_RGB: ::DWORD = 0; pub const BI_RLE8: ::DWORD = 1; pub const BI_RLE4: ::DWORD = 2; pub const BI_BITFIELDS: ::DWORD = 3; pub const BI_JPEG: ::DWORD = 4; pub const BI_PNG: ::DWORD = 5; #[repr(C)] // no Clone, Copy, or Debug because last field is special pub struct BITMAPINFO { pub bmiHeader: BITMAPINFOHEADER, pub bmiColors: [RGBQUAD; 1usize], } pub type LPBITMAPINFO = *mut BITMAPINFO; pub type PBITMAPINFO = *mut BITMAPINFO; //1438 pub const LF_FACESIZE: usize = 32; #[repr(C)] #[derive(Copy, Clone)] pub struct LOGFONTA { pub lfHeight: ::LONG, pub lfWidth: ::LONG, pub lfEscapement: ::LONG, pub lfOrientation: ::LONG, pub lfWeight: ::LONG, pub lfItalic: ::BYTE, pub lfUnderline: ::BYTE, pub lfStrikeOut: ::BYTE, pub lfCharSet: ::BYTE, pub lfOutPrecision: ::BYTE, pub lfClipPrecision: ::BYTE, pub lfQuality: ::BYTE, pub lfPitchAndFamily: ::BYTE, pub lfFaceName: [::CHAR; LF_FACESIZE], } pub type LPLOGFONTA = *mut LOGFONTA; #[repr(C)] #[derive(Copy, Clone)] pub struct LOGFONTW { pub lfHeight: ::LONG, pub lfWidth: ::LONG, pub lfEscapement: ::LONG, pub lfOrientation: ::LONG, pub lfWeight: ::LONG, pub lfItalic: ::BYTE, pub lfUnderline: ::BYTE, pub lfStrikeOut: ::BYTE, pub lfCharSet: ::BYTE, pub lfOutPrecision: ::BYTE, pub lfClipPrecision: ::BYTE, pub lfQuality: ::BYTE, pub lfPitchAndFamily: ::BYTE, pub lfFaceName: [::WCHAR; LF_FACESIZE], } pub type LPLOGFONTW = *mut LOGFONTW; //1595 #[inline] pub fn RGB (r: ::BYTE, g: ::BYTE, b: ::BYTE) -> ::COLORREF { r as ::COLORREF | ((g as ::COLORREF) << 8) | ((b as ::COLORREF) << 16) } //1906 (Win 7 SDK) pub const DIB_RGB_COLORS: ::UINT = 0; pub const DIB_PAL_COLORS: ::UINT = 1; // this type is weird because it's a hacky "unsized type" #[repr(C)] pub struct RGNDATA; #[repr(C)] #[derive(Copy, Clone)] pub struct PALETTEENTRY { peRed: ::BYTE, peGreen: ::BYTE, peBlue: ::BYTE, peFlags: ::BYTE } //3581 pub type LINEDDAPROC = Option<unsafe extern "system" fn(::c_int, ::c_int, ::LPARAM)>; pub const COINIT_APARTMENTTHREADED: ::DWORD = 0x2; pub const COINIT_MULTITHREADED: ::DWORD = 0x0; pub const COINIT_DISABLE_OLE1DDE: ::DWORD = 0x4; pub const COINIT_SPEED_OVER_MEMORY: ::DWORD = 0x8;
{ "content_hash": "82784da835ff9b3ab5744d226add4dd0", "timestamp": "", "source": "github", "line_count": 200, "max_line_length": 85, "avg_line_length": 31.255, "alnum_prop": 0.6664533674612062, "repo_name": "roblabla/winapi-rs", "id": "12cc97232df5bb82ddbf2a42e1cd295ee8898e1e", "size": "6444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/wingdi.rs", "mode": "33188", "license": "mit", "language": [ { "name": "RenderScript", "bytes": "532542" }, { "name": "Rust", "bytes": "1254697" } ], "symlink_target": "" }
sed -i 's|connectionString = "localhost"|connectionString = "'"${DBHOST}"'"|g' hello_mongo.go fw_depends mongodb go libsasl2-dev go get gopkg.in/mgo.v2 go run hello_mongo.go &
{ "content_hash": "50b2ae649c1b5a494e41e296937ead88", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 93, "avg_line_length": 25.714285714285715, "alnum_prop": 0.7111111111111111, "repo_name": "steveklabnik/FrameworkBenchmarks", "id": "447a1b14385d86de51a5fa582c620f37d142365f", "size": "193", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "frameworks/Go/go-std/setup_mongo.sh", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "838" }, { "name": "Batchfile", "bytes": "1326" }, { "name": "C", "bytes": "148190" }, { "name": "C#", "bytes": "241452" }, { "name": "C++", "bytes": "86996" }, { "name": "CMake", "bytes": "8236" }, { "name": "CSS", "bytes": "174439" }, { "name": "Clojure", "bytes": "70419" }, { "name": "Crystal", "bytes": "10213" }, { "name": "D", "bytes": "11767" }, { "name": "Dart", "bytes": "36881" }, { "name": "Elixir", "bytes": "12344" }, { "name": "Erlang", "bytes": "41367" }, { "name": "Go", "bytes": "79623" }, { "name": "Groovy", "bytes": "20518" }, { "name": "HTML", "bytes": "145519" }, { "name": "Haskell", "bytes": "35546" }, { "name": "Java", "bytes": "554734" }, { "name": "JavaScript", "bytes": "437387" }, { "name": "Kotlin", "bytes": "48036" }, { "name": "Lua", "bytes": "14599" }, { "name": "Makefile", "bytes": "5519" }, { "name": "Meson", "bytes": "846" }, { "name": "MoonScript", "bytes": "2405" }, { "name": "Nim", "bytes": "253" }, { "name": "Objective-C", "bytes": "659" }, { "name": "PHP", "bytes": "710023" }, { "name": "Perl", "bytes": "8520" }, { "name": "Perl 6", "bytes": "3505" }, { "name": "PowerShell", "bytes": "36603" }, { "name": "Python", "bytes": "303188" }, { "name": "QMake", "bytes": "2301" }, { "name": "Ruby", "bytes": "104975" }, { "name": "Rust", "bytes": "15968" }, { "name": "Scala", "bytes": "67188" }, { "name": "Shell", "bytes": "238523" }, { "name": "Smarty", "bytes": "1338" }, { "name": "Swift", "bytes": "26887" }, { "name": "UrWeb", "bytes": "65535" }, { "name": "Vala", "bytes": "1572" }, { "name": "Volt", "bytes": "769" } ], "symlink_target": "" }
<div class="formulaire_spip formulaire_configurer formulaire_#FORM"> [<p class="reponse_formulaire reponse_formulaire_ok">(#ENV*{message_ok})</p>] [<p class="reponse_formulaire reponse_formulaire_erreur">(#ENV*{message_erreur})</p>] <form method="post" action="#ENV{action}"> <div> #ACTION_FORMULAIRE{#ENV{action}} <ul> <li class="fieldset"> <fieldset> <legend><:mailjet:list_properties:></legend> <ul> <li class="editer editer_mailjet_list_label"> <label for="mailjet_list_label"><:mailjet:list_label:>:</label> [<span class='erreur_message'>(#ENV**{erreurs}|table_valeur{mailjet_list_label})</span>] <input type="text" name="mailjet_list_label" class="text" value="[(#ENV**{list}|table_valeur{label})]" id="mailjet_list_label"> </li> <li class="editer editer_mailjet_adresse_envoi_perso editer_mailjet_adresse_envoi_email "> <label for="mailjet_list_name"><:mailjet:list_name:>: :</label> [<span class='erreur_message'>(#ENV**{erreurs}|table_valeur{mailjet_list_name})</span>] <input type="text" name="mailjet_list_name" class="text" value="[(#ENV**{list}|table_valeur{name})]" id="mailjet_list_name"> </li> </ul> </fieldset> </li> </ul> <p class="boutons"> <input type="submit" name="save" class="submit" value="[(#ENV**{save_button_label})]"> <span><:mailjet:or:> <a href="?exec=mailjet_lists"><:mailjet:cancel:></a></span> </p> [(#ENV**{list}|=={''}|?{'', ' '}) <INCLURE{fond=formulaires/edit_list}{env}> ] </div> </form> </div> <script type="text/javascript"> jQuery(function(){ jQuery('input[name=mailjet_smtp_secure]').change(function(){ if (jQuery(this).attr('value')=='non'){ jQuery('#mailjet_smtp_port').find('option').hide().removeAttr('selected'); jQuery('#mailjet_smtp_port').find('option[value=25]').show().attr('selected',"selected"); jQuery('#mailjet_smtp_port').find('option[value=587]').show(); }else if(jQuery(this).attr('value')=='ssl'){ jQuery('#mailjet_smtp_port').find('option').hide().removeAttr('selected'); jQuery('#mailjet_smtp_port').find('option[value=465]').show().attr('selected',"selected"); }else if(jQuery(this).attr('value')=='tls'){ jQuery('#mailjet_smtp_port').find('option').hide().removeAttr('selected'); jQuery('#mailjet_smtp_port').find('option[value=587]').show().attr('selected',"selected"); } }); jQuery('input[name=mailjet_adresse_envoi]').change(function(){ if (jQuery(this).attr('value')=='oui'){ jQuery('.editer_mailjet_adresse_envoi_perso').show('fast') }else{ jQuery('.editer_mailjet_adresse_envoi_perso').hide('fast') } }); }) </script>
{ "content_hash": "ff620d3bcdf1787054b3ea9c1bcb8df5", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 159, "avg_line_length": 47.36231884057971, "alnum_prop": 0.5201958384332925, "repo_name": "CharlesCollas/spip-mailjet-plugin", "id": "d4bfabb2a5482103e60229ffa2cb7e85a945a34c", "size": "3268", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mailjet/formulaires/create_list.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#include "DepositionGeant4Module.hpp" #include <limits> #include <string> #include <utility> #include <G4EmParameters.hh> #include <G4HadronicProcessStore.hh> #include <G4LogicalVolume.hh> #include <G4PhysListFactory.hh> #include <G4RadioactiveDecayPhysics.hh> #include <G4RunManager.hh> #include <G4StepLimiterPhysics.hh> #include <G4UImanager.hh> #include <G4UserLimits.hh> #include "G4FieldManager.hh" #include "G4TransportationManager.hh" #include "G4UniformMagField.hh" #include "core/config/exceptions.h" #include "core/geometry/GeometryManager.hpp" #include "core/module/exceptions.h" #include "core/utils/log.h" #include "objects/DepositedCharge.hpp" #include "tools/ROOT.h" #include "tools/geant4.h" #include "GeneratorActionG4.hpp" #include "SensitiveDetectorActionG4.hpp" #include "SetTrackInfoUserHookG4.hpp" #define G4_NUM_SEEDS 10 using namespace allpix; /** * Includes the particle source point to the geometry using \ref GeometryManager::addPoint. */ DepositionGeant4Module::DepositionGeant4Module(Configuration& config, Messenger* messenger, GeometryManager* geo_manager) : Module(config), messenger_(messenger), geo_manager_(geo_manager), last_event_num_(1), run_manager_g4_(nullptr) { // Create user limits for maximum step length in the sensor user_limits_ = std::make_unique<G4UserLimits>(config_.get<double>("max_step_length", Units::get(1.0, "um"))); // Set default physics list config_.setDefault("physics_list", "FTFP_BERT_LIV"); config_.setDefault("source_type", "beam"); config_.setDefault<bool>("output_plots", false); config_.setDefault<int>("output_plots_scale", Units::get(100, "ke")); // Set alias for support of old particle source definition config_.setAlias("source_position", "beam_position"); config_.setAlias("source_energy", "beam_energy"); config_.setAlias("source_energy_spread", "beam_energy_spread"); // If macro, parse for positions of sources and add these as points to the GeoManager to extend the world: if(config.get<std::string>("source_type") == "macro") { std::ifstream file(config.getPath("file_name", true)); std::string line; while(std::getline(file, line)) { if(line.rfind("/gps/position", 0) == 0 || line.rfind("/gps/pos/centre") == 0) { LOG(TRACE) << "Macro contains source position: \"" << line << "\""; std::stringstream sstr(line); std::string command, units; double pos_x, pos_y, pos_z; sstr >> command >> pos_x >> pos_y >> pos_z >> units; ROOT::Math::XYZPoint source_position( Units::get(pos_x, units), Units::get(pos_y, units), Units::get(pos_z, units)); LOG(DEBUG) << "Found source positioned at " << Units::display(source_position, {"mm", "cm"}); geo_manager_->addPoint(source_position); } } } // Add the particle source position to the geometry geo_manager_->addPoint(config_.get<ROOT::Math::XYZPoint>("source_position", ROOT::Math::XYZPoint())); } /** * Module depends on \ref GeometryBuilderGeant4Module loaded first, because it owns the pointer to the Geant4 run manager. */ void DepositionGeant4Module::init() { // Load the G4 run manager (which is owned by the geometry builder) run_manager_g4_ = G4RunManager::GetRunManager(); if(run_manager_g4_ == nullptr) { throw ModuleError("Cannot deposit charges using Geant4 without a Geant4 geometry builder"); } // Suppress all output from G4 SUPPRESS_STREAM(G4cout); // Get UI manager for sending commands G4UImanager* ui_g4 = G4UImanager::GetUIpointer(); // Apply optional PAI model if(config_.get<bool>("enable_pai", false)) { LOG(TRACE) << "Enabling PAI model on all detectors"; G4EmParameters::Instance(); for(auto& detector : geo_manager_->getDetectors()) { // Get logical volume auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Create region G4Region* region = new G4Region(detector->getName() + "_sensor_region"); region->AddRootLogicalVolume(logical_volume.get()); auto pai_model = config_.get<std::string>("pai_model", "pai"); auto lcase_model = pai_model; std::transform(lcase_model.begin(), lcase_model.end(), lcase_model.begin(), ::tolower); if(lcase_model == "pai") { pai_model = "PAI"; } else if(lcase_model == "paiphoton") { pai_model = "PAIphoton"; } else { throw InvalidValueError(config_, "pai_model", "model has to be either 'pai' or 'paiphoton'"); } ui_g4->ApplyCommand("/process/em/AddPAIRegion all " + region->GetName() + " " + pai_model); } } // Find the physics list G4PhysListFactory physListFactory; G4VModularPhysicsList* physicsList = physListFactory.GetReferencePhysList(config_.get<std::string>("physics_list")); if(physicsList == nullptr) { std::string message = "specified physics list does not exists"; std::vector<G4String> base_lists = physListFactory.AvailablePhysLists(); message += " (available base lists are "; for(auto& base_list : base_lists) { message += base_list; message += ", "; } message = message.substr(0, message.size() - 2); message += " with optional suffixes for electromagnetic lists "; std::vector<G4String> em_lists = physListFactory.AvailablePhysListsEM(); for(auto& em_list : em_lists) { if(em_list.empty()) { continue; } message += em_list; message += ", "; } message = message.substr(0, message.size() - 2); message += ")"; throw InvalidValueError(config_, "physics_list", message); } else { LOG(INFO) << "Using G4 physics list \"" << config_.get<std::string>("physics_list") << "\""; } // Register a step limiter (uses the user limits defined earlier) physicsList->RegisterPhysics(new G4StepLimiterPhysics()); // Register radioactive decay physics lists physicsList->RegisterPhysics(new G4RadioactiveDecayPhysics()); // Set the range-cut off threshold for secondary production: double production_cut; if(config_.has("range_cut")) { production_cut = config_.get<double>("range_cut"); LOG(INFO) << "Setting configured G4 production cut to " << Units::display(production_cut, {"mm", "um"}); } else { // Define the production cut as one fifth of the minimum size (thickness, pitch) among the detectors double min_size = std::numeric_limits<double>::max(); std::string min_detector; for(auto& detector : geo_manager_->getDetectors()) { auto model = detector->getModel(); double prev_min_size = min_size; min_size = std::min({min_size, model->getPixelSize().x(), model->getPixelSize().y(), model->getSensorSize().z()}); if(min_size != prev_min_size) { min_detector = detector->getName(); } } production_cut = min_size / 5; LOG(INFO) << "Setting G4 production cut to " << Units::display(production_cut, {"mm", "um"}) << ", derived from properties of detector \"" << min_detector << "\""; } ui_g4->ApplyCommand("/run/setCut " + std::to_string(production_cut)); // Initialize the physics list LOG(TRACE) << "Initializing physics processes"; run_manager_g4_->SetUserInitialization(physicsList); run_manager_g4_->InitializePhysics(); // Initialize the full run manager to ensure correct state flags run_manager_g4_->Initialize(); // Build particle generator LOG(TRACE) << "Constructing particle source"; auto generator = new GeneratorActionG4(config_); run_manager_g4_->SetUserAction(generator); track_info_manager_ = std::make_unique<TrackInfoManager>(); // User hook to store additional information at track initialization and termination as well as custom track ids auto userTrackIDHook = new SetTrackInfoUserHookG4(track_info_manager_.get()); run_manager_g4_->SetUserAction(userTrackIDHook); if(geo_manager_->hasMagneticField()) { MagneticFieldType magnetic_field_type_ = geo_manager_->getMagneticFieldType(); if(magnetic_field_type_ == MagneticFieldType::CONSTANT) { ROOT::Math::XYZVector b_field = geo_manager_->getMagneticField(ROOT::Math::XYZPoint(0., 0., 0.)); G4MagneticField* magField = new G4UniformMagField(G4ThreeVector(b_field.x(), b_field.y(), b_field.z())); G4FieldManager* globalFieldMgr = G4TransportationManager::GetTransportationManager()->GetFieldManager(); globalFieldMgr->SetDetectorField(magField); globalFieldMgr->CreateChordFinder(magField); } else { throw ModuleError("Magnetic field enabled, but not constant. This can't be handled by this module yet."); } } // Get the creation energy for charge (default is silicon electron hole pair energy) auto charge_creation_energy = config_.get<double>("charge_creation_energy", Units::get(3.64, "eV")); auto fano_factor = config_.get<double>("fano_factor", 0.115); // Prepare seeds for Geant4: // NOTE Assumes this is the only Geant4 module using random numbers std::string seed_command = "/random/setSeeds "; for(int i = 0; i < G4_NUM_SEEDS; ++i) { seed_command += std::to_string(static_cast<uint32_t>(getRandomSeed() % INT_MAX)); if(i != G4_NUM_SEEDS - 1) { seed_command += " "; } } // Loop through all detectors and set the sensitive detector action that handles the particle passage bool useful_deposition = false; for(auto& detector : geo_manager_->getDetectors()) { // Do not add sensitive detector for detectors that have no listeners for the deposited charges // FIXME Probably the MCParticle has to be checked as well if(!messenger_->hasReceiver(this, std::make_shared<DepositedChargeMessage>(std::vector<DepositedCharge>(), detector))) { LOG(INFO) << "Not depositing charges in " << detector->getName() << " because there is no listener for its output"; continue; } useful_deposition = true; // Get model of the sensitive device auto sensitive_detector_action = new SensitiveDetectorActionG4( this, detector, messenger_, track_info_manager_.get(), charge_creation_energy, fano_factor, getRandomSeed()); auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Apply the user limits to this element logical_volume->SetUserLimits(user_limits_.get()); // Add the sensitive detector action logical_volume->SetSensitiveDetector(sensitive_detector_action); sensors_.push_back(sensitive_detector_action); // If requested, prepare output plots if(config_.get<bool>("output_plots")) { LOG(TRACE) << "Creating output plots"; // Plot axis are in kilo electrons - convert from framework units! int maximum = static_cast<int>(Units::convert(config_.get<int>("output_plots_scale"), "ke")); int nbins = 5 * maximum; // Create histograms if needed std::string plot_name = "deposited_charge_" + sensitive_detector_action->getName(); charge_per_event_[sensitive_detector_action->getName()] = new TH1D(plot_name.c_str(), "deposited charge per event;deposited charge [ke];events", nbins, 0, maximum); } } if(!useful_deposition) { LOG(ERROR) << "Not a single listener for deposited charges, module is useless!"; } // Disable verbose messages from processes ui_g4->ApplyCommand("/process/verbose 0"); ui_g4->ApplyCommand("/process/em/verbose 0"); ui_g4->ApplyCommand("/process/eLoss/verbose 0"); G4HadronicProcessStore::Instance()->SetVerbose(0); // Set the random seed for Geant4 generation ui_g4->ApplyCommand(seed_command); // Release the output stream RELEASE_STREAM(G4cout); } void DepositionGeant4Module::run(unsigned int event_num) { // Suppress output stream if not in debugging mode IFLOG(DEBUG); else { SUPPRESS_STREAM(G4cout); } // Start a single event from the beam LOG(TRACE) << "Enabling beam"; run_manager_g4_->BeamOn(static_cast<int>(config_.get<unsigned int>("number_of_particles", 1))); last_event_num_ = event_num; // Release the stream (if it was suspended) RELEASE_STREAM(G4cout); track_info_manager_->createMCTracks(); // Dispatch the necessary messages for(auto& sensor : sensors_) { sensor->dispatchMessages(); // Fill output plots if requested: if(config_.get<bool>("output_plots")) { double charge = static_cast<double>(Units::convert(sensor->getDepositedCharge(), "ke")); charge_per_event_[sensor->getName()]->Fill(charge); } } track_info_manager_->dispatchMessage(this, messenger_); track_info_manager_->resetTrackInfoManager(); } void DepositionGeant4Module::finalize() { size_t total_charges = 0; for(auto& sensor : sensors_) { total_charges += sensor->getTotalDepositedCharge(); } if(config_.get<bool>("output_plots")) { // Write histograms LOG(TRACE) << "Writing output plots to file"; for(auto& plot : charge_per_event_) { plot.second->Write(); } } // Print summary or warns if module did not output any charges if(!sensors_.empty() && total_charges > 0 && last_event_num_ > 0) { size_t average_charge = total_charges / sensors_.size() / last_event_num_; LOG(INFO) << "Deposited total of " << total_charges << " charges in " << sensors_.size() << " sensor(s) (average of " << average_charge << " per sensor for every event)"; } else { LOG(WARNING) << "No charges deposited"; } }
{ "content_hash": "a52c92a7ae478f575ef9a109a267afa3", "timestamp": "", "source": "github", "line_count": 347, "max_line_length": 125, "avg_line_length": 42.371757925072046, "alnum_prop": 0.6323879480378154, "repo_name": "Koensw/allpix-squared", "id": "e78b815f89b053c69e4aa013a241a0497814fcb9", "size": "15198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/modules/DepositionGeant4/DepositionGeant4Module.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "15474" }, { "name": "C++", "bytes": "1075347" }, { "name": "CMake", "bytes": "143638" }, { "name": "Dockerfile", "bytes": "770" }, { "name": "Python", "bytes": "14219" }, { "name": "Shell", "bytes": "26174" } ], "symlink_target": "" }
@interface ViewController () @end @implementation ViewController @synthesize gridView = gridView_; - (void)dealloc { self.gridView.cellCreationHandler = nil; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.gridView = [[MUKGridView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:self.gridView]; // // MUKGridCellSize *cellSize = [[MUKGridCellSize alloc] initWithSize:CGSizeMake(self.gridView.frame.size.width/4.0, self.gridView.frame.size.width/4.0)]; MUKGridCellSize *cellSize = [[MUKGridCellSize alloc] initWithSize:CGSizeMake(1.0, 1.0)]; cellSize.kind = MUKGridCellSizeKindProportional; self.gridView.cellSize = cellSize; self.gridView.direction = MUKGridDirectionHorizontal; self.gridView.numberOfCells = 1002; __unsafe_unretained MUKGridView *weakGridView = self.gridView; [self.gridView setCellCreationHandler:^UIView<MUKRecyclable> *(NSInteger index) { LabelCellView *cellView = (LabelCellView *)[weakGridView dequeueViewWithIdentifier:@"LabelCellView"]; if (cellView == nil) { CGRect rect = CGRectZero; rect.size = cellSize.size; cellView = [[LabelCellView alloc] initWithFrame:rect]; cellView.recycleIdentifier = @"LabelCellView"; } cellView.label.text = [NSString stringWithFormat:@"%i", index]; return cellView; }]; [self.gridView reloadData]; } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. self.gridView = nil; } @end
{ "content_hash": "ffab66cf9bc13a902c305c07e3846842", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 156, "avg_line_length": 31.203703703703702, "alnum_prop": 0.6795252225519288, "repo_name": "muccy/MUKScrolling", "id": "a931d539a9aecf7a24fc1fc60b8bf99fb539c38f", "size": "1902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/MUKScrollingExample/MUKScrollingExample/ViewController.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Objective-C", "bytes": "292290" } ], "symlink_target": "" }
*This project is currently in **alpha**. The API should be considered unstable and likely to change* PGV is a protoc plugin to generate polyglot message validators. While protocol buffers effectively guarantee the types of structured data, they cannot enforce semantic rules for values. This plugin adds support to protoc-generated code to validate such constraints. Developers import the PGV extension and annotate the messages and fields in their proto files with constraint rules: ```protobuf syntax = "proto3"; package examplepb; import "validate/validate.proto"; message Person { uint64 id = 1 [(validate.rules).uint64.gt = 999]; string email = 2 [(validate.rules).string.email = true]; string name = 3 [(validate.rules).string = { pattern: "^[^[0-9]A-Za-z]+( [^[0-9]A-Za-z]+)*$", max_bytes: 256, }]; Location home = 4 [(validate.rules).message.required = true]; message Location { double lat = 1 [(validate.rules).double = { gte: -90, lte: 90 }]; double lng = 2 [(validate.rules).double = { gte: -180, lte: 180 }]; } } ``` Executing `protoc` with PGV and the target language's default plugin will create `Validate` methods on the generated types: ```go p := new(Person) err := p.Validate() // err: Id must be greater than 999 p.Id = 1000 err = p.Validate() // err: Email must be a valid email address p.Email = "[email protected]" err = p.Validate() // err: Name must match pattern '^[^\d\s]+( [^\d\s]+)*$' p.Name = "Protocol Buffer" err = p.Validate() // err: Home is required p.Home = &Location{37.7, 999} err = p.Validate() // err: Home.Lng must be within [-180, 180] p.Home.Lng = -122.4 err = p.Validate() // err: nil ``` ## Usage ### Dependencies - `go` toolchain (≥ v1.7) - `protoc` compiler in `$PATH` - `protoc-gen-validate` in `$PATH` - official language-specific plugin for target language(s) - **Only `proto3` syntax is currently supported.** `proto2` syntax support is planned. ### Installation Installing PGV can currently only be done from source: ```sh # fetches this repo into $GOPATH go get -d github.com/envoyproxy/protoc-gen-validate # installs PGV into $GOPATH/bin make build ``` ### Parameters - **`lang`**: specify the target language to generate. Currently, the only supported options are: - `go` - `cc` for c++ (partially implemented) - `java` - Note: Python works via runtime code generation. There's no compile-time generation. See the Python section for details. ### Examples #### Go Go generation should occur into the same output path as the official plugin. For a proto file `example.proto`, the corresponding validation code is generated into `../generated/example.pb.validate.go`: ```sh protoc \ -I . \ -I ${GOPATH}/src \ -I ${GOPATH}/src/github.com/envoyproxy/protoc-gen-validate \ --go_out=":../generated" \ --validate_out="lang=go:../generated" \ example.proto ``` All messages generated include the following methods: - `Validate() error` which returns the first error encountered during validation. - `ValidateAll() error` which returns all errors encountered during validation. PGV requires no additional runtime dependencies from the existing generated code. **Note**: by default **example.pb.validate.go** is nested in a directory structure that matches your `option go_package` name. You can change this using the protoc parameter `paths=source_relative:.`. Then `--validate_out` will output the file where it is expected. See Google's protobuf documentation or [packages and input paths](https://github.com/golang/protobuf#packages-and-input-paths) or [parameters](https://github.com/golang/protobuf#parameters) for more information. There's also support for the `module=example.com/foo` flag [described here](https://developers.google.com/protocol-buffers/docs/reference/go-generated#invocation). #### Java Java generation is integrated with the existing protobuf toolchain for java projects. For Maven projects, add the following to your pom.xml or build.gradle. ```xml <dependencies> <dependency> <groupId> io.envoyproxy.protoc-gen-validate</groupId> <artifactId>pgv-java-stub</artifactId> <version>${pgv.version}</version> </dependency> </dependencies> <build> <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.4.1.Final</version> </extension> </extensions> <plugins> <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.6.1</version> <configuration> <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact> </configuration> <executions> <execution> <id>protoc-java-pgv</id> <goals> <goal>compile-custom</goal> </goals> <configuration> <pluginParameter>lang=java</pluginParameter> <pluginId>java-pgv</pluginId> <pluginArtifact>io.envoyproxy.protoc-gen-validate:protoc-gen-validate:${pgv.version}:exe:${os.detected.classifier}</pluginArtifact> </configuration> </execution> </executions> </plugin> </plugins> </build> ``` ```gradle plugins { ... id "com.google.protobuf" version "${protobuf.version}" ... } protobuf { protoc { artifact = "com.google.protobuf:protoc:${protoc.version}" } plugins { javapgv { artifact = "io.envoyproxy.protoc-gen-validate:protoc-gen-validate:${pgv.version}" } } generateProtoTasks { all()*.plugins { javapgv { option "lang=java" } } } } ``` ```java // Create a validator index that reflectively loads generated validators ValidatorIndex index = new ReflectiveValidatorIndex(); // Assert that a message is valid index.validatorFor(message.getClass()).assertValid(message); // Create a gRPC client and server interceptor to automatically validate messages (requires pgv-java-grpc module) clientStub = clientStub.withInterceptors(new ValidatingClientInterceptor(index)); serverBuilder.addService(ServerInterceptors.intercept(svc, new ValidatingServerInterceptor(index))); ``` #### Python The python implementation works via JIT code generation. In other words, the `validate(msg)` function is written on-demand and [exec-ed](https://docs.python.org/3/library/functions.html#exec). An LRU-cache improves performance by storing generated functions per descriptor. The python package is available on [PyPI](https://pypi.org/project/protoc-gen-validate). To run `validate()`, do the following: ```python from entities_pb2 import Person from protoc_gen_validate.validator import validate, ValidationFailed p = Person(first_name="Foo", last_name="Bar", age=42) try: validate(p) except ValidationFailed as err: print(err) ``` You can view what code has been generated by using the `print_validate()` function. ## Constraint Rules [The provided constraints](validate/validate.proto) are modeled largerly after those in JSON Schema. PGV rules can be mixed for the same field; the plugin ensures the rules applied to a field cannot contradict before code generation. Check the [constraint rule comparison matrix](rule_comparison.md) for language-specific constraint capabilities. ### Numerics > All numeric types (`float`, `double`, `int32`, `int64`, `uint32`, `uint64`, `sint32`, `sint64`, `fixed32`, `fixed64`, `sfixed32`, `sfixed64`) share the same rules. - **const**: the field must be _exactly_ the specified value. ```protobuf // x must equal 1.23 exactly float x = 1 [(validate.rules).float.const = 1.23]; ``` - **lt/lte/gt/gte**: these inequalities (`<`, `<=`, `>`, `>=`, respectively) allow for deriving ranges in which the field must reside. ```protobuf // x must be less than 10 int32 x = 1 [(validate.rules).int32.lt = 10]; // x must be greater than or equal to 20 uint64 x = 1 [(validate.rules).uint64.gte = 20]; // x must be in the range [30, 40) fixed32 x = 1 [(validate.rules).fixed32 = {gte:30, lt: 40}]; ``` Inverting the values of `lt(e)` and `gt(e)` is valid and creates an exclusive range. ```protobuf // x must be outside the range [30, 40) double x = 1 [(validate.rules).double = {lt:30, gte:40}]; ``` - **in/not_in**: these two rules permit specifying allow/denylists for the values of a field. ```protobuf // x must be either 1, 2, or 3 uint32 x = 1 [(validate.rules).uint32 = {in: [1,2,3]}]; // x cannot be 0 nor 0.99 float x = 1 [(validate.rules).float = {not_in: [0, 0.99]}]; ``` - **ignore_empty**: this rule specifies that if field is empty or set to the default value, to ignore any validation rules. These are typically useful where being able to unset a field in an update request, or to skip validation for optional fields where switching to WKTs is not feasible. ```protobuf unint32 x = 1 [(validate.rules).uint32 = {ignore_empty: true, gte: 200}]; ``` ### Bools - **const**: the field must be _exactly_ the specified value. ```protobuf // x must be set to true bool x = 1 [(validate.rules).bool.const = true]; // x cannot be set to true bool x = 1 [(validate.rules).bool.const = false]; ``` ### Strings - **const**: the field must be _exactly_ the specified value. ```protobuf // x must be set to "foo" string x = 1 [(validate.rules).string.const = "foo"]; ``` - **len/min_len/max_len**: these rules constrain the number of characters (Unicode code points) in the field. Note that the number of characters may differ from the number of bytes in the string. The string is considered as-is, and does not normalize. ```protobuf // x must be exactly 5 characters long string x = 1 [(validate.rules).string.len = 5]; // x must be at least 3 characters long string x = 1 [(validate.rules).string.min_len = 3]; // x must be between 5 and 10 characters, inclusive string x = 1 [(validate.rules).string = {min_len: 5, max_len: 10}]; ``` - **min_bytes/max_bytes**: these rules constrain the number of bytes in the field. ```protobuf // x must be at most 15 bytes long string x = 1 [(validate.rules).string.max_bytes = 15]; // x must be between 128 and 1024 bytes long string x = 1 [(validate.rules).string = {min_bytes: 128, max_bytes: 1024}]; ``` - **pattern**: the field must match the specified [RE2-compliant][re2] regular expression. The included expression should elide any delimiters (ie, `/\d+/` should just be `\d+`). ```protobuf // x must be a non-empty, case-insensitive hexadecimal string string x = 1 [(validate.rules).string.pattern = "(?i)^[0-9a-f]+$"]; ``` - **prefix/suffix/contains/not_contains**: the field must contain the specified substring in an optionally explicit location, or not contain the specified substring. ```protobuf // x must begin with "foo" string x = 1 [(validate.rules).string.prefix = "foo"]; // x must end with "bar" string x = 1 [(validate.rules).string.suffix = "bar"]; // x must contain "baz" anywhere inside it string x = 1 [(validate.rules).string.contains = "baz"]; // x cannot contain "baz" anywhere inside it string x = 1 [(validate.rules).string.not_contains = "baz"]; // x must begin with "fizz" and end with "buzz" string x = 1 [(validate.rules).string = {prefix: "fizz", suffix: "buzz"}]; // x must end with ".proto" and be less than 64 characters string x = 1 [(validate.rules).string = {suffix: ".proto", max_len:64}]; ``` - **in/not_in**: these two rules permit specifying allow/denylists for the values of a field. ```protobuf // x must be either "foo", "bar", or "baz" string x = 1 [(validate.rules).string = {in: ["foo", "bar", "baz"]}]; // x cannot be "fizz" nor "buzz" string x = 1 [(validate.rules).string = {not_in: ["fizz", "buzz"]}]; ``` - **ignore_empty**: this rule specifies that if field is empty or set to the default value, to ignore any validation rules. These are typically useful where being able to unset a field in an update request, or to skip validation for optional fields where switching to WKTs is not feasible. ```protobuf string CountryCode = 1 [(validate.rules).string = {ignore_empty: true, len: 2}]; ``` - **well-known formats**: these rules provide advanced constraints for common string patterns. These constraints will typically be more permissive and performant than equivalent regular expression patterns, while providing more explanatory failure descriptions. ```protobuf // x must be a valid email address (via RFC 5322) string x = 1 [(validate.rules).string.email = true]; // x must be a valid address (IP or Hostname). string x = 1 [(validate.rules).string.address = true]; // x must be a valid hostname (via RFC 1034) string x = 1 [(validate.rules).string.hostname = true]; // x must be a valid IP address (either v4 or v6) string x = 1 [(validate.rules).string.ip = true]; // x must be a valid IPv4 address // eg: "192.168.0.1" string x = 1 [(validate.rules).string.ipv4 = true]; // x must be a valid IPv6 address // eg: "fe80::3" string x = 1 [(validate.rules).string.ipv6 = true]; // x must be a valid absolute URI (via RFC 3986) string x = 1 [(validate.rules).string.uri = true]; // x must be a valid URI reference (either absolute or relative) string x = 1 [(validate.rules).string.uri_ref = true]; // x must be a valid UUID (via RFC 4122) string x = 1 [(validate.rules).string.uuid = true]; // x must conform to a well known regex for HTTP header names (via RFC 7230) string x = 1 [(validate.rules).string.well_known_regex = HTTP_HEADER_NAME] // x must conform to a well known regex for HTTP header values (via RFC 7230) string x = 1 [(validate.rules).string.well_known_regex = HTTP_HEADER_VALUE]; // x must conform to a well known regex for headers, disallowing \r\n\0 characters. string x = 1 [(validate.rules).string {well_known_regex: HTTP_HEADER_VALUE, strict: false}]; ``` ### Bytes > Literal values should be expressed with strings, using escaping where necessary. - **const**: the field must be _exactly_ the specified value. ```protobuf // x must be set to "foo" ("\x66\x6f\x6f") bytes x = 1 [(validate.rules).bytes.const = "foo"]; // x must be set to "\xf0\x90\x28\xbc" bytes x = 1 [(validate.rules).bytes.const = "\xf0\x90\x28\xbc"]; ``` - **len/min_len/max_len**: these rules constrain the number of bytes in the field. ```protobuf // x must be exactly 3 bytes bytes x = 1 [(validate.rules).bytes.len = 3]; // x must be at least 3 bytes long bytes x = 1 [(validate.rules).bytes.min_len = 3]; // x must be between 5 and 10 bytes, inclusive bytes x = 1 [(validate.rules).bytes = {min_len: 5, max_len: 10}]; ``` - **pattern**: the field must match the specified [RE2-compliant][re2] regular expression. The included expression should elide any delimiters (ie, `/\d+/` should just be `\d+`). ```protobuf // x must be a non-empty, ASCII byte sequence bytes x = 1 [(validate.rules).bytes.pattern = "^[\x00-\x7F]+$"]; ``` - **prefix/suffix/contains**: the field must contain the specified byte sequence in an optionally explicit location. ```protobuf // x must begin with "\x99" bytes x = 1 [(validate.rules).bytes.prefix = "\x99"]; // x must end with "buz\x7a" bytes x = 1 [(validate.rules).bytes.suffix = "buz\x7a"]; // x must contain "baz" anywhere inside it bytes x = 1 [(validate.rules).bytes.contains = "baz"]; ``` - **in/not_in**: these two rules permit specifying allow/denylists for the values of a field. ```protobuf // x must be either "foo", "bar", or "baz" bytes x = 1 [(validate.rules).bytes = {in: ["foo", "bar", "baz"]}]; // x cannot be "fizz" nor "buzz" bytes x = 1 [(validate.rules).bytes = {not_in: ["fizz", "buzz"]}]; ``` - **ignore_empty**: this rule specifies that if field is empty or set to the default value, to ignore any validation rules. These are typically useful where being able to unset a field in an update request, or to skip validation for optional fields where switching to WKTs is not feasible. ```protobuf bytes x = 1 [(validate.rules).bytes = {ignore_empty: true, in: ["foo", "bar", "baz"]}]; ``` - **well-known formats**: these rules provide advanced constraints for common patterns. These constraints will typically be more permissive and performant than equivalent regular expression patterns, while providing more explanatory failure descriptions. ```protobuf // x must be a valid IP address (either v4 or v6) in byte format bytes x = 1 [(validate.rules).bytes.ip = true]; // x must be a valid IPv4 address in byte format // eg: "\xC0\xA8\x00\x01" bytes x = 1 [(validate.rules).bytes.ipv4 = true]; // x must be a valid IPv6 address in byte format // eg: "\x20\x01\x0D\xB8\x85\xA3\x00\x00\x00\x00\x8A\x2E\x03\x70\x73\x34" bytes x = 1 [(validate.rules).bytes.ipv6 = true]; ``` ### Enums > All literal values should use the numeric (int32) value as defined in the enum descriptor. The following examples use this `State` enum ```protobuf enum State { INACTIVE = 0; PENDING = 1; ACTIVE = 2; } ``` - **const**: the field must be _exactly_ the specified value. ```protobuf // x must be set to ACTIVE (2) State x = 1 [(validate.rules).enum.const = 2]; ``` - **defined_only**: the field must be one of the specified values in the enum descriptor. ```protobuf // x can only be INACTIVE, PENDING, or ACTIVE State x = 1 [(validate.rules).enum.defined_only = true]; ``` - **in/not_in**: these two rules permit specifying allow/denylists for the values of a field. ```protobuf // x must be either INACTIVE (0) or ACTIVE (2) State x = 1 [(validate.rules).enum = {in: [0,2]}]; // x cannot be PENDING (1) State x = 1 [(validate.rules).enum = {not_in: [1]}]; ``` ### Messages > If a field contains a message and the message has been generated with PGV, validation will be performed recursively. Message's not generated with PGV are skipped. ```protobuf // if Person was generated with PGV and x is set, // x's fields will be validated. Person x = 1; ``` - **skip**: this rule specifies that the validation rules of this field should not be evaluated. ```protobuf // The fields on Person x will not be validated. Person x = 1 [(validate.rules).message.skip = true]; ``` - **required**: this rule specifies that the field cannot be unset. ```protobuf // x cannot be unset Person x = 1 [(validate.rules).message.required = true]; // x cannot be unset, but the validations on x will not be performed Person x = 1 [(validate.rules).message = {required: true, skip: true}]; ``` ### Repeated - **min_items/max_items**: these rules control how many elements are contained in the field ```protobuf // x must contain at least 3 elements repeated int32 x = 1 [(validate.rules).repeated.min_items = 3]; // x must contain between 5 and 10 Persons, inclusive repeated Person x = 1 [(validate.rules).repeated = {min_items: 5, max_items: 10}]; // x must contain exactly 7 elements repeated double x = 1 [(validate.rules).repeated = {min_items: 7, max_items: 7}]; ``` - **unique**: this rule requires that all elements in the field must be unique. This rule does not support repeated messages. ```protobuf // x must contain unique int64 values repeated int64 x = 1 [(validate.rules).repeated.unique = true]; ``` - **items**: this rule specifies constraints that should be applied to each element in the field. Repeated message fields also have their validation rules applied unless `skip` is specified on this constraint. ```protobuf // x must contain positive float values repeated float x = 1 [(validate.rules).repeated.items.float.gt = 0]; // x must contain Persons but don't validate them repeated Person x = 1 [(validate.rules).repeated.items.message.skip = true]; ``` - **ignore_empty**: this rule specifies that if field is empty or set to the default value, to ignore any validation rules. These are typically useful where being able to unset a field in an update request, or to skip validation for optional fields where switching to WKTs is not feasible. ```protobuf repeated int64 x = 1 [(validate.rules).repeated = {ignore_empty: true, items: {int64: {gt: 200}}}]; ``` ### Maps - **min_pairs/max_pairs**: these rules control how many KV pairs are contained in this field ```protobuf // x must contain at least 3 KV pairs map<string, uint64> x = 1 [(validate.rules).map.min_pairs = 3]; // x must contain between 5 and 10 KV pairs map<string, string> x = 1 [(validate.rules)].map = {min_pairs: 5, max_pairs: 10}]; // x must contain exactly 7 KV pairs map<string, Person> x = 1 [(validate.rules)].map = {min_pairs: 7, max_pairs: 7}]; ``` - **no_sparse**: for map fields with message values, setting this rule to true disallows keys with unset values. ```protobuf // all values in x must be set map<uint64, Person> x = 1 [(validate.rules).map.no_sparse = true]; ``` - **keys**: this rule specifies constraints that are applied to the keys in the field. ```protobuf // x's keys must all be negative <sint32, string> x = [(validate.rules).map.keys.sint32.lt = 0]; ``` - **values**: this rule specifies constraints that are be applied to each value in the field. Repeated message fields also have their validation rules applied unless `skip` is specified on this constraint. ```protobuf // x must contain strings of at least 3 characters map<string, string> x = 1 [(validate.rules).map.values.string.min_len = 3]; // x must contain Persons but doesn't validate them map<string, Person> x = 1 [(validate.rules).map.values.message.skip = true]; ``` - **ignore_empty**: this rule specifies that if field is empty or set to the default value, to ignore any validation rules. These are typically useful where being able to unset a field in an update request, or to skip validation for optional fields where switching to WKTs is not feasible. ```protobuf map<string, string> x = 1 [(validate.rules).map = {ignore_empty: true, values: {string: {min_len: 3}}}]; ``` ### Well-Known Types (WKTs) A set of [WKTs][wkts] are packaged with protoc and common message patterns useful in many domains. #### Scalar Value Wrappers In the `proto3` syntax, there is no way of distinguishing between unset and the zero value of a scalar field. The value WKTs permit this differentiation by wrapping them in a message. PGV permits using the same scalar rules that the wrapper encapsulates. ```protobuf // if it is set, x must be greater than 3 google.protobuf.Int32Value x = 1 [(validate.rules).int32.gt = 3]; ``` Message Rules can also be used with scalar Well-Known Types (WKTs): ```protobuf // Ensures that if a value is not set for age, it would not pass the validation despite its zero value being 0. message X { google.protobuf.Int32Value age = 1 [(validate.rules).int32.gt = -1, (validate.rules).message.required = true]; } ``` #### Anys - **required**: this rule specifies that the field must be set ```protobuf // x cannot be unset google.protobuf.Any x = 1 [(validate.rules).any.required = true]; ``` - **in/not_in**: these two rules permit specifying allow/denylists for the `type_url` value in this field. Consider using a `oneof` union instead of `in` if possible. ```protobuf // x must not be the Duration or Timestamp WKT google.protobuf.Any x = 1 [(validate.rules).any = {not_in: [ "type.googleapis.com/google.protobuf.Duration", "type.googleapis.com/google.protobuf.Timestamp" ]}]; ``` #### Durations - **required**: this rule specifies that the field must be set ```protobuf // x cannot be unset google.protobuf.Duration x = 1 [(validate.rules).duration.required = true]; ``` - **const**: the field must be _exactly_ the specified value. ```protobuf // x must equal 1.5s exactly google.protobuf.Duration x = 1 [(validate.rules).duration.const = { seconds: 1, nanos: 500000000 }]; ``` - **lt/lte/gt/gte**: these inequalities (`<`, `<=`, `>`, `>=`, respectively) allow for deriving ranges in which the field must reside. ```protobuf // x must be less than 10s google.protobuf.Duration x = 1 [(validate.rules).duration.lt.seconds = 10]; // x must be greater than or equal to 20ns google.protobuf.Duration x = 1 [(validate.rules).duration.gte.nanos = 20]; // x must be in the range [0s, 1s) google.protobuf.Duration x = 1 [(validate.rules).duration = { gte: {}, lt: {seconds: 1} }]; ``` Inverting the values of `lt(e)` and `gt(e)` is valid and creates an exclusive range. ```protobuf // x must be outside the range [0s, 1s) google.protobuf.Duration x = 1 [(validate.rules).duration = { lt: {}, gte: {seconds: 1} }]; ``` - **in/not_in**: these two rules permit specifying allow/denylists for the values of a field. ```protobuf // x must be either 0s or 1s google.protobuf.Duration x = 1 [(validate.rules).duration = {in: [ {}, {seconds: 1} ]}]; // x cannot be 20s nor 500ns google.protobuf.Duration x = 1 [(validate.rules).duration = {not_in: [ {seconds: 20}, {nanos: 500} ]}]; ``` #### Timestamps - **required**: this rule specifies that the field must be set ```protobuf // x cannot be unset google.protobuf.Timestamp x = 1 [(validate.rules).timestamp.required = true]; ``` - **const**: the field must be _exactly_ the specified value. ```protobuf // x must equal 2009/11/10T23:00:00.500Z exactly google.protobuf.Timestamp x = 1 [(validate.rules).timestamp.const = { seconds: 63393490800, nanos: 500000000 }]; ``` - **lt/lte/gt/gte**: these inequalities (`<`, `<=`, `>`, `>=`, respectively) allow for deriving ranges in which the field must reside. ```protobuf // x must be less than the Unix Epoch google.protobuf.Timestamp x = 1 [(validate.rules).timestamp.lt.seconds = 0]; // x must be greater than or equal to 2009/11/10T23:00:00Z google.protobuf.Timestamp x = 1 [(validate.rules).timestamp.gte.seconds = 63393490800]; // x must be in the range [epoch, 2009/11/10T23:00:00Z) google.protobuf.Timestamp x = 1 [(validate.rules).timestamp = { gte: {}, lt: {seconds: 63393490800} }]; ``` Inverting the values of `lt(e)` and `gt(e)` is valid and creates an exclusive range. ```protobuf // x must be outside the range [epoch, 2009/11/10T23:00:00Z) google.protobuf.Timestamp x = 1 [(validate.rules).timestamp = { lt: {}, gte: {seconds: 63393490800} }]; ``` - **lt_now/gt_now**: these inequalities allow for ranges relative to the current time. These rules cannot be used with the absolute rules above. ```protobuf // x must be less than the current timestamp google.protobuf.Timestamp x = 1 [(validate.rules).timestamp.lt_now = true]; ``` - **within**: this rule specifies that the field's value should be within a duration of the current time. This rule can be used in conjunction with `lt_now` and `gt_now` to control those ranges. ```protobuf // x must be within ±1s of the current time google.protobuf.Timestamp x = 1 [(validate.rules).timestamp.within.seconds = 1]; // x must be within the range (now, now+1h) google.protobuf.Timestamp x = 1 [(validate.rules).timestamp = { gt_now: true, within: {seconds: 3600} }]; ``` ### Message-Global - **disabled**: All validation rules for the fields on a message can be nullified, including any message fields that support validation themselves. ```protobuf message Person { option (validate.disabled) = true; // x will not be required to be greater than 123 uint64 x = 1 [(validate.rules).uint64.gt = 123]; // y's fields will not be validated Person y = 2; } ``` - **ignored**: Don't generate a validate method or any related validation code for this message. ```protobuf message Person { option (validate.ignored) = true; // x will not be required to be greater than 123 uint64 x = 1 [(validate.rules).uint64.gt = 123]; // y's fields will not be validated Person y = 2; } ``` ### OneOfs - **required**: require that one of the fields in a `oneof` must be set. By default, none or one of the unioned fields can be set. Enabling this rules disallows having all of them unset. ```protobuf oneof id { // either x, y, or z must be set. option (validate.required) = true; string x = 1; int32 y = 2; Person z = 3; } ``` ## Development PGV is written in Go on top of the [protoc-gen-star][pg*] framework and compiles to a standalone binary. ### Dependencies All PGV dependencies are currently checked into the project. To test PGV, `protoc` must be installed, either from [source][protoc-source], the provided [releases][protoc-releases], or a package manager. The official protoc plugin for the target language(s) should be installed as well. ### Make Targets - **`make build`**: generates the constraints proto and compiles PGV into `$GOPATH/bin` - **`make lint`**: runs static-analysis rules against the PGV codebase, including `golint`, `go vet`, and `gofmt -s` - **`make testcases`**: generates the proto files in [`/tests/harness/cases`](/tests/harness/cases). These are used by the test harness to verify the validation rules generated for each language. - **`make harness`**: executes the test-cases against each language's test harness. ### Run all tests under Bazel Ensure that your `PATH` is setup to include `protoc-gen-go` and `protoc`, then: ``` bazel test //tests/... ``` ### Docker PGV comes with a [Dockerfile](/Dockerfile) for consistent development tooling and CI. The main entrypoint is `make` with `quick` as the default target. This repo should be volumed into `/go/src/github.com/envoyproxy/protoc-gen-validate` for the proper behavior. ```sh # build the image docker build -t lyft/protoc-gen-validate . # executes the default make target: quick docker run --rm \ -v $(PWD):/go/src/github.com/envoyproxy/protoc-gen-validate \ lyft/protoc-gen-validate # executes the 'build' & 'generate-testdata' make targets docker run --rm \ -v $(PWD):/go/src/github.com/envoyproxy/protoc-gen-validate \ lyft/protoc-gen-validate \ build generate-testdata ``` [protoc-source]: https://github.com/google/protobuf [protoc-releases]: https://github.com/google/protobuf/releases [pg*]: https://github.com/lyft/protoc-gen-star [re2]: https://github.com/google/re2/wiki/Syntax [wkts]: https://developers.google.com/protocol-buffers/docs/reference/google.protobuf
{ "content_hash": "5840b3c9347ceb8bbf382876332544b2", "timestamp": "", "source": "github", "line_count": 890, "max_line_length": 477, "avg_line_length": 34.96067415730337, "alnum_prop": 0.6739836091917082, "repo_name": "envoyproxy/protoc-gen-validate", "id": "c89228c27c3a72c5af38bed79b65a06adf6a180c", "size": "31147", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "17276" }, { "name": "Dockerfile", "bytes": "2163" }, { "name": "Go", "bytes": "264082" }, { "name": "Java", "bytes": "102625" }, { "name": "Makefile", "bytes": "7406" }, { "name": "PowerShell", "bytes": "231" }, { "name": "Python", "bytes": "61080" }, { "name": "Shell", "bytes": "185" }, { "name": "Starlark", "bytes": "88491" } ], "symlink_target": "" }
package render import "net/http" type Render interface { Render(http.ResponseWriter) error } var ( _ Render = JSON{} _ Render = IndentedJSON{} _ Render = XML{} _ Render = String{} _ Render = Redirect{} _ Render = Data{} _ Render = HTML{} _ HTMLRender = HTMLDebug{} _ HTMLRender = HTMLProduction{} )
{ "content_hash": "efe8a0ff84f05f48ee35ef02bd5f0104", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 34, "avg_line_length": 17.894736842105264, "alnum_prop": 0.5970588235294118, "repo_name": "michelangelo13/gin", "id": "eadc31b83a0f6850dba762ec5f55fcc492ca777b", "size": "508", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "render/render.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "188402" }, { "name": "HTML", "bytes": "10283" }, { "name": "JavaScript", "bytes": "3490" } ], "symlink_target": "" }
<?php /** * base include file for SimpleTest * @package SimpleTest * @subpackage UnitTester * @version $Id: reflection_php4.php,v 1.9 2005/11/22 02:07:32 lastcraft Exp $ */ /** * Version specific reflection API. * @package SimpleTest * @subpackage UnitTester */ class SimpleReflection { var $_interface; /** * Stashes the class/interface. * @param string $interface Class or interface * to inspect. */ function SimpleReflection($interface) { $this->_interface = $interface; } /** * Checks that a class has been declared. * @return boolean True if defined. * @access public */ function classExists() { return class_exists($this->_interface); } /** * Needed to kill the autoload feature in PHP5 * for classes created dynamically. * @return boolean True if defined. * @access public */ function classExistsSansAutoload() { return class_exists($this->_interface); } /** * Checks that a class or interface has been * declared. * @return boolean True if defined. * @access public */ function classOrInterfaceExists() { return class_exists($this->_interface); } /** * Needed to kill the autoload feature in PHP5 * for classes created dynamically. * @return boolean True if defined. * @access public */ function classOrInterfaceExistsSansAutoload() { return class_exists($this->_interface); } /** * Gets the list of methods on a class or * interface. * @returns array List of method names. * @access public */ function getMethods() { return get_class_methods($this->_interface); } /** * Gets the list of interfaces from a class. If the * class name is actually an interface then just that * interface is returned. * @returns array List of interfaces. * @access public */ function getInterfaces() { return array(); } /** * Finds the parent class name. * @returns string Parent class name. * @access public */ function getParent() { return strtolower(get_parent_class($this->_interface)); } /** * Determines if the class is abstract, which for PHP 4 * will never be the case. * @returns boolean True if abstract. * @access public */ function isAbstract() { return false; } /** * Gets the source code matching the declaration * of a method. * @param string $method Method name. * @access public */ function getSignature($method) { return "function &$method()"; } } ?>
{ "content_hash": "0ea3ef79697357951b91fbf7f3585dc6", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 82, "avg_line_length": 28.921739130434784, "alnum_prop": 0.48947684906794947, "repo_name": "cerad/appirm", "id": "4ad4b249f10cc4eb2cb4bd170765805602042d6c", "size": "3326", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "irm-1.6-b3/testing/simpletest/reflection_php4.php", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "71990" }, { "name": "CSS", "bytes": "150826" }, { "name": "ColdFusion", "bytes": "58518" }, { "name": "JavaScript", "bytes": "3102856" }, { "name": "Lasso", "bytes": "34002" }, { "name": "PHP", "bytes": "7055384" }, { "name": "Perl", "bytes": "145414" }, { "name": "Python", "bytes": "43812" }, { "name": "Shell", "bytes": "3586" } ], "symlink_target": "" }
/* ----------------- * ScaleFreeGraphGenerator.java * ----------------- * (C) Copyright 2008-2008, by Ilya Razenshteyn and Contributors. * * Original Author: Ilya Razenshteyn * Contributor(s): - * * $Id$ * * Changes * ------- */ package org.jgrapht.generate; import java.util.*; import org.jgrapht.*; /** * Generates directed or undirected <a href = * "http://mathworld.wolfram.com/Scale-FreeNetwork.html">scale-free network</a> * of any size. Scale-free network is a connected graph, where degrees of * vertices are distributed in unusual way. There are many vertices with small * degrees and only small amount of vertices with big degrees. * * @author Ilya Razenshteyn */ public class ScaleFreeGraphGenerator<V, E> implements GraphGenerator<V, E, V> { private int size; // size of graphs, generated by this instance of generator private long seed; // initial seed private Random random; // the source of randomness /** * Constructs a new <tt>ScaleFreeGraphGenerator</tt>. * * @param size number of vertices to be generated */ public ScaleFreeGraphGenerator( int size) { if (size < 0) { throw new IllegalArgumentException( "invalid size: " + size + " (must be non-negative)"); } this.size = size; random = new Random(); seed = random.nextLong(); } /** * Constructs a new <tt>ScaleFreeGraphGenerator</tt> using fixed <tt> * seed</tt> for the random generator. * * @param size number of vertices to be generated * @param seed initial seed for the random generator */ public ScaleFreeGraphGenerator( int size, long seed) { if (size < 0) { throw new IllegalArgumentException( "invalid size: " + size + " (must be non-negative)"); } this.size = size; random = new Random(); this.seed = seed; } /** * Generates scale-free network with <tt>size</tt> passed to the * constructor. Each call of this method produces identical output (but if * <tt>target</tt> is an undirected graph, the directions of edges will be * lost). * * @param target receives the generated edges and vertices; if this is * non-empty on entry, the result will be a disconnected graph since * generated elements will not be connected to existing elements * @param vertexFactory called to produce new vertices * @param resultMap unused parameter */ public void generateGraph( Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap) { random.setSeed(seed); List<V> vertexList = new ArrayList<V>(); List<Integer> degrees = new ArrayList<Integer>(); int degreeSum = 0; for (int i = 0; i < size; i++) { V newVertex = vertexFactory.createVertex(); target.addVertex(newVertex); int newDegree = 0; while ((newDegree == 0) && (i != 0)) // we want our graph to be // connected { for (int j = 0; j < vertexList.size(); j++) { if ((degreeSum == 0) || (random.nextInt(degreeSum) < degrees.get(j))) { degrees.set(j, degrees.get(j) + 1); newDegree++; degreeSum += 2; if (random.nextInt(2) == 0) { target.addEdge(vertexList.get(j), newVertex); } else { target.addEdge(newVertex, vertexList.get(j)); } } } } vertexList.add(newVertex); degrees.add(newDegree); } } } // End ScaleFreeGraphGenerator.java
{ "content_hash": "e2c37d92cab8ed6ece72bc0883aaa40a", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 80, "avg_line_length": 30.404580152671755, "alnum_prop": 0.5473261360783329, "repo_name": "AdrianAlan/kmax", "id": "2046132e39e82510f3e79aad8f8d87c840bee920", "size": "4702", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/org/jgrapht/generate/ScaleFreeGraphGenerator.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "957654" }, { "name": "Python", "bytes": "4154" } ], "symlink_target": "" }
package org.jcodec.movtool.streaming.tracks; import java.io.IOException; import org.jcodec.movtool.streaming.CodecMeta; import org.jcodec.movtool.streaming.VirtualPacket; import org.jcodec.movtool.streaming.VirtualTrack; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * @author The JCodec project * */ public class ToVorbisTrack implements VirtualTrack { @Override public VirtualPacket nextPacket() throws IOException { // TODO Auto-generated method stub return null; } @Override public CodecMeta getCodecMeta() { // TODO Auto-generated method stub return null; } @Override public VirtualEdit[] getEdits() { // TODO Auto-generated method stub return null; } @Override public int getPreferredTimescale() { // TODO Auto-generated method stub return 0; } @Override public void close() throws IOException { // TODO Auto-generated method stub } }
{ "content_hash": "db6ce689114b1e6eb213edd49e982727", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 79, "avg_line_length": 22.574468085106382, "alnum_prop": 0.6663524976437323, "repo_name": "Dacaspex/Fractal", "id": "472ad9c6996e35b2417617ad666efd5327bb5eda", "size": "1061", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "org/jcodec/movtool/streaming/tracks/ToVorbisTrack.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2941335" } ], "symlink_target": "" }
<?php namespace Mpociot\ApiDoc\Tests; use Dingo\Api\Provider\LaravelServiceProvider; use Mpociot\ApiDoc\Tests\Fixtures\DingoTestController; use Orchestra\Testbench\TestCase; use Mpociot\ApiDoc\Generators\DingoGenerator; use Mpociot\ApiDoc\Tests\Fixtures\TestRequest; use Mpociot\ApiDoc\Tests\Fixtures\TestController; class DingoGeneratorTest extends TestCase { /** * @var \Mpociot\ApiDoc\Generators\DingoGenerator */ protected $generator; protected function getPackageProviders($app) { return [ LaravelServiceProvider::class, ]; } /** * Setup the test environment. */ public function setUp() { parent::setUp(); $this->generator = new DingoGenerator(); } public function testCanParseMethodDescription() { $api = app('Dingo\Api\Routing\Router'); $api->version('v1', function ($api) { $api->get('/api/test', TestController::class.'@parseMethodDescription'); }); $route = app('Dingo\Api\Routing\Router')->getRoutes()['v1']->getRoutes()[0]; $parsed = $this->generator->processRoute($route); $this->assertSame('Example title.', $parsed['title']); $this->assertSame("This will be the long description.\nIt can also be multiple lines long.", $parsed['description']); } public function testCanParseRouteMethods() { $api = app('Dingo\Api\Routing\Router'); $api->version('v1', function ($api) { $api->get('/get', TestController::class.'@dummy'); $api->post('/post', TestController::class.'@dummy'); $api->put('/put', TestController::class.'@dummy'); $api->delete('/delete', TestController::class.'@dummy'); }); $route = app('Dingo\Api\Routing\Router')->getRoutes()['v1']->getRoutes()[0]; $parsed = $this->generator->processRoute($route); $this->assertSame(['GET', 'HEAD'], $parsed['methods']); $route = app('Dingo\Api\Routing\Router')->getRoutes()['v1']->getRoutes()[1]; $parsed = $this->generator->processRoute($route); $this->assertSame(['POST'], $parsed['methods']); $route = app('Dingo\Api\Routing\Router')->getRoutes()['v1']->getRoutes()[2]; $parsed = $this->generator->processRoute($route); $this->assertSame(['PUT'], $parsed['methods']); $route = app('Dingo\Api\Routing\Router')->getRoutes()['v1']->getRoutes()[3]; $parsed = $this->generator->processRoute($route); $this->assertSame(['DELETE'], $parsed['methods']); } public function testCanParseFormRequestRules() { $api = app('Dingo\Api\Routing\Router'); $api->version('v1', function ($api) { $api->post('/post', DingoTestController::class.'@parseFormRequestRules'); }); $route = app('Dingo\Api\Routing\Router')->getRoutes()['v1']->getRoutes()[0]; $parsed = $this->generator->processRoute($route); $parameters = $parsed['parameters']; $testRequest = new TestRequest(); $rules = $testRequest->rules(); foreach ($rules as $name => $rule) { $attribute = $parameters[$name]; switch ($name) { case 'required': $this->assertTrue($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'accepted': $this->assertTrue($attribute['required']); $this->assertSame('boolean', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'active_url': $this->assertFalse($attribute['required']); $this->assertSame('url', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'alpha': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Only alphabetic characters allowed', $attribute['description'][0]); break; case 'alpha_dash': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Allowed: alpha-numeric characters, as well as dashes and underscores.', $attribute['description'][0]); break; case 'alpha_num': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Only alpha-numeric characters allowed', $attribute['description'][0]); break; case 'array': $this->assertFalse($attribute['required']); $this->assertSame('array', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'between': $this->assertFalse($attribute['required']); $this->assertSame('numeric', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Between: `5` and `200`', $attribute['description'][0]); break; case 'before': $this->assertFalse($attribute['required']); $this->assertSame('date', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must be a date preceding: `Saturday, 23-Apr-16 14:31:00 UTC`', $attribute['description'][0]); break; case 'boolean': $this->assertFalse($attribute['required']); $this->assertSame('boolean', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'date': $this->assertFalse($attribute['required']); $this->assertSame('date', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'date_format': $this->assertFalse($attribute['required']); $this->assertSame('date', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Date format: `j.n.Y H:iP`', $attribute['description'][0]); break; case 'different': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must have a different value than parameter: `alpha_num`', $attribute['description'][0]); break; case 'digits': $this->assertFalse($attribute['required']); $this->assertSame('numeric', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must have an exact length of `2`', $attribute['description'][0]); break; case 'digits_between': $this->assertFalse($attribute['required']); $this->assertSame('numeric', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must have a length between `2` and `10`', $attribute['description'][0]); break; case 'email': $this->assertFalse($attribute['required']); $this->assertSame('email', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'exists': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Valid user firstname', $attribute['description'][0]); break; case 'image': $this->assertFalse($attribute['required']); $this->assertSame('image', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must be an image (jpeg, png, bmp, gif, or svg)', $attribute['description'][0]); break; case 'in': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('`jpeg`, `png`, `bmp`, `gif` or `svg`', $attribute['description'][0]); break; case 'integer': $this->assertFalse($attribute['required']); $this->assertSame('integer', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'ip': $this->assertFalse($attribute['required']); $this->assertSame('ip', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'json': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must be a valid JSON string.', $attribute['description'][0]); break; case 'max': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Maximum: `10`', $attribute['description'][0]); break; case 'min': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Minimum: `20`', $attribute['description'][0]); break; case 'mimes': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Allowed mime types: `jpeg`, `bmp` or `png`', $attribute['description'][0]); break; case 'not_in': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Not in: `foo` or `bar`', $attribute['description'][0]); break; case 'numeric': $this->assertFalse($attribute['required']); $this->assertSame('numeric', $attribute['type']); $this->assertCount(0, $attribute['description']); break; case 'regex': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must match this regular expression: `(.*)`', $attribute['description'][0]); break; case 'required_if': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Required if `foo` is `bar`', $attribute['description'][0]); break; case 'required_unless': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Required unless `foo` is `bar`', $attribute['description'][0]); break; case 'required_with': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Required if the parameters `foo`, `bar` or `baz` are present.', $attribute['description'][0]); break; case 'required_with_all': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Required if the parameters `foo`, `bar` and `baz` are present.', $attribute['description'][0]); break; case 'required_without': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Required if the parameters `foo`, `bar` or `baz` are not present.', $attribute['description'][0]); break; case 'required_without_all': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Required if the parameters `foo`, `bar` and `baz` are not present.', $attribute['description'][0]); break; case 'same': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must be the same as `foo`', $attribute['description'][0]); break; case 'size': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must have the size of `51`', $attribute['description'][0]); break; case 'timezone': $this->assertFalse($attribute['required']); $this->assertSame('string', $attribute['type']); $this->assertCount(1, $attribute['description']); $this->assertSame('Must be a valid timezone identifier', $attribute['description'][0]); break; case 'url': $this->assertFalse($attribute['required']); $this->assertSame('url', $attribute['type']); $this->assertCount(0, $attribute['description']); break; } } } }
{ "content_hash": "68675b776d1cf600ab2ddf67968e2ac4", "timestamp": "", "source": "github", "line_count": 316, "max_line_length": 141, "avg_line_length": 51.36708860759494, "alnum_prop": 0.4982750123213406, "repo_name": "andela-joyebanji/laravel-apidoc-generator", "id": "2b7a8e71394c160257a175959b90faf7602a2171", "size": "16232", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/DingoGeneratorTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "68314" } ], "symlink_target": "" }
package com.yogee.zhebuy.modules.ebuy.service; import com.google.common.collect.Maps; import com.yogee.zhebuy.common.persistence.Page; import com.yogee.zhebuy.common.service.EbuyService; import com.yogee.zhebuy.common.utils.StringUtils; import com.yogee.zhebuy.modules.ebuy.dao.EbuyProCategoryDao; import com.yogee.zhebuy.modules.ebuy.entity.EbuyProCategory; import com.yogee.zhebuy.modules.ebuy.entity.EbuyProItem; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 商品类目Service * @author jackqth * @version 2017-06-02 */ @Service @Transactional(readOnly = true) public class EbuyProCategoryService extends EbuyService<EbuyProCategoryDao, EbuyProCategory> { @Autowired private EbuyProCategoryDao ebuyProCategoryDao; public EbuyProCategory get(String id) { return super.get(id); } public EbuyProCategory getByName(String name) { return ebuyProCategoryDao.getByName(name); } public List<EbuyProCategory> findList(EbuyProCategory ebuyProCategory) { return super.findList(ebuyProCategory); } public Page<EbuyProCategory> findPage(Page<EbuyProCategory> page, EbuyProCategory ebuyProCategory) { return super.findPage(page, ebuyProCategory); } //获取全部分类 public List<EbuyProCategory> findListAll() { return ebuyProCategoryDao.findListAll(); } //获取一级分类 public List<EbuyProCategory> findListTop(EbuyProCategory ebuyProCategory) { return ebuyProCategoryDao.findListTop(ebuyProCategory); } //获取二级分类 public List<EbuyProCategory> findListSecond(EbuyProCategory ebuyProCategory) { return ebuyProCategoryDao.findListSecond(ebuyProCategory); } //获取二级分类 public List<EbuyProCategory> findSecondByTopId(int topId) { return ebuyProCategoryDao.findSecondByTopId(topId); } @Transactional(readOnly = false) public int save(EbuyProCategory ebuyProCategory) { if(StringUtils.isEmpty(ebuyProCategory.getId())){ ebuyProCategory.setgmtCreate(new Date()); }else{ ebuyProCategory.setGmtModified(new Date()); } //没选择上级的话默认赋0 if(null == ebuyProCategory.getPId()){ ebuyProCategory.setPId(0L); } return super.save(ebuyProCategory); } @Transactional(readOnly = false) public void delete(EbuyProCategory ebuyProCategory) { super.delete(ebuyProCategory); } //获取一级分类 public List<EbuyProCategory> findTopCateList(String[] stringArray) { return ebuyProCategoryDao.findTopCateList(stringArray); } //获取一级分类 public List<EbuyProCategory> findTopCateListNo(String cityId) { Map map = new HashMap(); map.put("cityId",cityId); return ebuyProCategoryDao.findTopCateListNo(map); } public List<EbuyProCategory> findTopCateBySecs(String[] categoryId) { Map map = new HashMap(); map.put("categoryId",categoryId); return ebuyProCategoryDao.findTopCateBySecs(map); } public List<EbuyProCategory> findSecService(String topId, String[] categoryIds) { Map map = new HashMap(); map.put("topId",topId); map.put("categoryIds",categoryIds); return ebuyProCategoryDao.findSecService(map); } public List<EbuyProCategory> getCategory(String level, String pId) { EbuyProCategory category = new EbuyProCategory(); category.setPId(Long.parseLong(pId)); category.setLevel(level); return ebuyProCategoryDao.getCategory(category); } public List<EbuyProCategory> findCategoryName(String[] stringCategory) { Map<String,String[]> map =new HashMap<String, String[]>(); map.put("stringCategory",stringCategory); return ebuyProCategoryDao.findCategoryName(map); } //根据2级查1级 public String findPid(String id) { Map map = new HashMap(); map.put("id",id); return ebuyProCategoryDao.findPid(map); } }
{ "content_hash": "ada94e4b8a065120fe6d63945ab9f541", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 101, "avg_line_length": 29.41860465116279, "alnum_prop": 0.7794466403162056, "repo_name": "sunye520/zhebuy", "id": "4cdd57857e2224003389ad66a985abe3278cd9e6", "size": "4017", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/yogee/zhebuy/modules/ebuy/service/EbuyProCategoryService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "7506" }, { "name": "Batchfile", "bytes": "8608" }, { "name": "CSS", "bytes": "1778032" }, { "name": "HTML", "bytes": "4972204" }, { "name": "Java", "bytes": "4429124" }, { "name": "JavaScript", "bytes": "14081354" }, { "name": "PHP", "bytes": "16120" }, { "name": "PLSQL", "bytes": "73115" } ], "symlink_target": "" }
'use strict'; (function() { angular.module("VotingApp", ['ngRoute', 'ngCookies', 'ui.bootstrap', 'ngclipboard', 'ngAnimate' ]) .config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.withCredentials = true; }]); })();
{ "content_hash": "b30f458856aaa8ebaf840f074a79bc69", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 102, "avg_line_length": 40, "alnum_prop": 0.5821428571428572, "repo_name": "Will-is-Coding/fcc_voting-app", "id": "71a8e76a28fe6818dde0df292fcd3e0d928d21ff", "size": "280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/js/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9251" }, { "name": "HTML", "bytes": "56205" }, { "name": "JavaScript", "bytes": "90192" } ], "symlink_target": "" }
FROM balenalib/jetson-xavier-alpine:3.12-build # remove several traces of python RUN apk del python* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # key 63C7CC90: public key "Simon McVittie <[email protected]>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 # point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED. # https://www.python.org/dev/peps/pep-0476/#trust-database ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt ENV PYTHON_VERSION 3.6.12 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" \ && echo "0f2f79cec6173c11dd094e0da3b4b93148b6c7058fb7a8c3cb64acc96e29e368 Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install --no-cache-dir virtualenv ENV PYTHON_DBUS_VERSION 1.2.8 # install dbus-python dependencies RUN apk add --no-cache \ dbus-dev \ dbus-glib-dev # install dbus-python RUN set -x \ && mkdir -p /usr/src/dbus-python \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \ && gpg --verify dbus-python.tar.gz.asc \ && tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \ && rm dbus-python.tar.gz* \ && cd /usr/src/dbus-python \ && PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \ && make -j$(nproc) \ && make install -j$(nproc) \ && cd / \ && rm -rf /usr/src/dbus-python # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \ && echo "Running test-stack@python" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Alpine Linux 3.12 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.12, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && ln -f /bin/sh /bin/sh.real \ && ln -f /bin/sh-shim /bin/sh
{ "content_hash": "eaef22a3efa8ffdbceba38a6c6126171", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 716, "avg_line_length": 51.83870967741935, "alnum_prop": 0.7079444098734702, "repo_name": "nghiant2710/base-images", "id": "1549d1f08c6dee1d66e56e704e11834692883c81", "size": "4842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/jetson-xavier/alpine/3.12/3.6.12/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
using System; namespace BeverageLabels { public class BeverageLabels { public static void Main() { var name = Console.ReadLine(); var volume = int.Parse(Console.ReadLine()); var energyContent = double.Parse(Console.ReadLine()); var sugarContent = double.Parse(Console.ReadLine()); var energyResult = volume * energyContent / 100; var sugarResult = volume * sugarContent / 100; Console.WriteLine($"{volume}ml {name}:"); Console.WriteLine($"{energyResult}kcal, {sugarResult}g sugars"); } } }
{ "content_hash": "138a00cb6dfc44ba2663c09cbe575b83", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 76, "avg_line_length": 29.80952380952381, "alnum_prop": 0.5846645367412141, "repo_name": "vsaraminev/ProgrammingFundamentalsExtendedMay2017", "id": "30d1d900e7eb19a578dc200b5e4c33817139e06f", "size": "628", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "02.CIntroAndBasicSyntaxExerices/BeverageLabels/BeverageLabels.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "406986" } ], "symlink_target": "" }
package com.kotcrab.vis.editor.module.scene; import com.artemis.*; import com.artemis.EntitySubscription.SubscriptionListener; import com.artemis.annotations.Wire; import com.artemis.utils.IntBag; import com.badlogic.gdx.utils.ObjectMap; import com.kotcrab.vis.editor.entity.UUIDComponent; import java.util.UUID; @Wire public class VisUUIDManager extends Manager { private ComponentMapper<UUIDComponent> idCm; private AspectSubscriptionManager subscriptionManager; private EntitySubscription subscription; private ObjectMap<UUID, Entity> idStore = new ObjectMap<>(); @Override protected void initialize () { subscription = subscriptionManager.get(Aspect.all(UUIDComponent.class)); subscription.addSubscriptionListener(new SubscriptionListener() { @Override public void inserted (IntBag entities) { ObjectMap<UUID, Entity> tmpCache = new ObjectMap<>(); int[] data = entities.getData(); for (int i = 0; i < entities.size(); i++) { int entityId = data[i]; Entity entity = world.getEntity(entityId); tmpCache.put(idCm.get(entityId).getUUID(), entity); } idStore.putAll(tmpCache); } @Override public void removed (IntBag entities) { int[] data = entities.getData(); for (int i = 0; i < entities.size(); i++) { int entityId = data[i]; Entity entity = world.getEntity(entityId); idStore.remove(idCm.get(entity).getUUID()); } } }); } public Entity get (UUID uuid) { return idStore.get(uuid); } }
{ "content_hash": "79ab6b32a46e7694fcdaa35f96fd399b", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 74, "avg_line_length": 26.280701754385966, "alnum_prop": 0.7129506008010681, "repo_name": "intrigus/VisEditor", "id": "a8e723b80d2b2789f41c263b540828b290507461", "size": "2099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Editor/src/com/kotcrab/vis/editor/module/scene/VisUUIDManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "1252" }, { "name": "Java", "bytes": "2479594" } ], "symlink_target": "" }
package snmp import ( "encoding/asn1" "fmt" "io" "bosun.org/_third_party/github.com/mjibson/snmp/mib" ) // Walk is a wrapper for SNMP.Walk. func Walk(host, community string, oids ...string) (*Rows, error) { s, err := New(host, community) if err != nil { return nil, err } return s.Walk(oids...) } // Rows is the result of a walk. Its cursor starts before the first // row of the result set. Use Next to advance through the rows: // // rows, err := snmp.Walk(host, community, "ifName") // ... // for rows.Next() { // var name []byte // err = rows.Scan(&name) // ... // } // err = rows.Err() // get any error encountered during iteration // ... type Rows struct { avail []row last row walkFn walkFunc headText []string head []asn1.ObjectIdentifier err error request requestFunc } // row represents individual row. type row struct { instance []int bindings []binding } // Walk executes a query against host authenticated by the community string, // retrieving the MIB sub-tree defined by the the given root oids. func (s *SNMP) Walk(oids ...string) (*Rows, error) { rows := &Rows{ avail: nil, walkFn: walkN, headText: oids, head: lookup(oids...), request: s.do, } for _, oid := range rows.head { rows.last.bindings = append(rows.last.bindings, binding{Name: oid}) } return rows, nil } // Next prepares the next result row for reading with the Scan method. // It returns true on success, false if there is no next result row. // Every call to Scan, even the first one, must be preceded by a call // to Next. func (rows *Rows) Next() bool { if len(rows.avail) > 0 { return true } if rows.err != nil { if rows.err == io.EOF { rows.err = nil } return false } row, err := rows.walkFn(rows.last.bindings, rows.request) if err != nil { if err == io.EOF { rows.err = err } else { rows.err = fmt.Errorf("snmp.Walk: %v", err) } return false } rows.avail = row for i, r := range rows.avail { eof := 0 for i, b := range r.bindings { if !hasPrefix(b.Name, rows.head[i]) { eof++ } } if eof > 0 { if eof < len(r.bindings) { rows.err = fmt.Errorf("invalid response: pre-mature end of a column") return false } rows.avail = rows.avail[:i] rows.err = io.EOF break } } return len(rows.avail) > 0 } // Scan copies the columns in the current row into the values pointed at by v. // On success, the id return variable will hold the row id of the current row. // It is typically an integer or a string. func (rows *Rows) Scan(v ...interface{}) (id interface{}, err error) { if len(v) != len(rows.last.bindings) { panic("snmp.Scan: invalid argument count") } cur := rows.avail[0] rows.avail = rows.avail[1:] last := rows.last rows.last = cur for i, a := range last.bindings { b := cur.bindings[i] if !a.less(b) { return nil, fmt.Errorf("invalid response: %v: unordered binding: req=%+v >= resp=%+v", rows.headText[i], a.Name, b.Name) } } for i, b := range cur.bindings { if err := b.unmarshal(v[i]); err != nil { return nil, err } } var want []int for i, b := range cur.bindings { offset := len(rows.head[i]) // BUG: out of bounds access have := b.Name[offset:] if i == 0 { want = have continue } if len(have) != len(want) || !hasPrefix(have, want) { return nil, fmt.Errorf("invalid response: inconsistent instances") } } id = convertInstance(want) return id, nil } // convertInstance optionally converts the object instance id from the // general []byte form to simplified form: either a simple int, or a // string. func convertInstance(x []int) interface{} { switch { case len(x) == 1: return x[0] default: s, ok := toStringInt(x) if !ok { return x } return s } } // Err returns the error, if any, that was encountered during iteration. func (rows *Rows) Err() error { return rows.err } type requestFunc func(*request) (*response, error) // walkFunc is a function that can request one or more rows. type walkFunc func([]binding, requestFunc) ([]row, error) // walk1 requests one row. func walk1(have []binding, rf requestFunc) ([]row, error) { req := &request{ Type: "GetNext", ID: <-nextID, Bindings: have, } resp, err := rf(req) if err != nil { return nil, err } if err := check(resp, req); err != nil { return nil, err } r := row{bindings: resp.Bindings} return []row{r}, nil } // walkN requests a range of rows. func walkN(have []binding, rf requestFunc) ([]row, error) { req := &request{ Type: "GetBulk", ID: <-nextID, Bindings: have, NonRepeaters: 0, MaxRepetitions: 15, } resp, err := rf(req) if err != nil { return nil, err } if err := check(resp, req); err != nil { return nil, err } received := resp.Bindings sent := req.Bindings if len(received)%len(sent) != 0 { return nil, fmt.Errorf("invalid response: truncated bindings list") } var list []row for len(received) > 0 { list = append(list, row{bindings: received[:len(sent)]}) received = received[len(sent):] } if len(list) > req.MaxRepetitions { return nil, fmt.Errorf("invalid response: peer violated MaxRepetitions, received %d rows, expected at most %d", len(list), req.MaxRepetitions) } return list, nil } // lookup maps oids in their symbolic format into numeric format. func lookup(oids ...string) []asn1.ObjectIdentifier { list := make([]asn1.ObjectIdentifier, 0, len(oids)) for _, o := range oids { oid, err := mib.Lookup(o) if err != nil { panic(err) } list = append(list, oid) } return list }
{ "content_hash": "d15d758f78f80ec5ce3f2b996d0a9c39", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 113, "avg_line_length": 22.979674796747968, "alnum_prop": 0.6309923934194234, "repo_name": "vitorboschi/bosun", "id": "cc3cc33c18bdf5c60b8476e29183fe4ab3e62dbb", "size": "5653", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "_third_party/github.com/mjibson/snmp/walk.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "2391955" }, { "name": "HTML", "bytes": "43193" }, { "name": "JavaScript", "bytes": "79285" }, { "name": "Python", "bytes": "1866" }, { "name": "Shell", "bytes": "1790" }, { "name": "TypeScript", "bytes": "68704" } ], "symlink_target": "" }
<!DOCTYPE HTML> <!-- Tests the bootstrap variant where the bootstrap tag is part of the head and where the 'src' URL contains '/sap-ui-core.js' --> <html> <head> <meta charset="utf-8"> <title>Test Page for Resource Root when 'src' starts with 'resources/'</title> <!-- Initialization --> <link href="../../../../../../resources/sap/ui/thirdparty/qunit-2.css" rel="stylesheet" media="screen"> <script src="../../../../../../resources/sap/ui/thirdparty/qunit-2.js"></script> <script src="../../../../../../resources/sap/ui/qunit/qunit-junit.js"></script> <script src="../../shared-config.js"></script> <script id="sap-ui-bootstrap" src="../../../../../../resources/sap-ui-core.js" > </script> <!-- check that all expectations are met --> <script src="ResourceRoot.qunit.js" data-expected-root="../../../../../../resources/"></script> </head> <body class="sapUiBody"> <div id="qunit"></div> </body> </html>
{ "content_hash": "6852f8359ecc2ae188ea6f42f7b8fa44", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 106, "avg_line_length": 32.758620689655174, "alnum_prop": 0.6021052631578947, "repo_name": "SAP/openui5", "id": "f54fc10a779d938de174b392a9e335300b012a97", "size": "950", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sap.ui.core/test/sap/ui/core/qunit/bootstrap/ResourceRoot_ResourcesURL_Standard.qunit.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "294216" }, { "name": "Gherkin", "bytes": "17201" }, { "name": "HTML", "bytes": "6443688" }, { "name": "Java", "bytes": "83398" }, { "name": "JavaScript", "bytes": "109546491" }, { "name": "Less", "bytes": "8741757" }, { "name": "TypeScript", "bytes": "20918" } ], "symlink_target": "" }