text
stringlengths
2
1.04M
meta
dict
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Injectable } from 'angular2/src/core/di'; import { Map, MapWrapper } from 'angular2/src/facade/collection'; import { CONST, CONST_EXPR } from 'angular2/src/facade/lang'; import { BaseException } from 'angular2/src/facade/exceptions'; import { NgZone } from '../zone/ng_zone'; import { PromiseWrapper, ObservableWrapper } from 'angular2/src/facade/async'; /** * The Testability service provides testing hooks that can be accessed from * the browser and by services such as Protractor. Each bootstrapped Angular * application on the page will have an instance of Testability. */ export let Testability = class { constructor(_ngZone) { /** @internal */ this._pendingCount = 0; /** * Whether any work was done since the last 'whenStable' callback. This is * useful to detect if this could have potentially destabilized another * component while it is stabilizing. * @internal */ this._didWork = false; /** @internal */ this._callbacks = []; /** @internal */ this._isAngularEventPending = false; this._watchAngularEvents(_ngZone); } /** @internal */ _watchAngularEvents(_ngZone) { ObservableWrapper.subscribe(_ngZone.onTurnStart, (_) => { this._didWork = true; this._isAngularEventPending = true; }); _ngZone.runOutsideAngular(() => { ObservableWrapper.subscribe(_ngZone.onEventDone, (_) => { if (!_ngZone.hasPendingTimers) { this._isAngularEventPending = false; this._runCallbacksIfReady(); } }); }); } increasePendingRequestCount() { this._pendingCount += 1; this._didWork = true; return this._pendingCount; } decreasePendingRequestCount() { this._pendingCount -= 1; if (this._pendingCount < 0) { throw new BaseException('pending async requests below zero'); } this._runCallbacksIfReady(); return this._pendingCount; } isStable() { return this._pendingCount == 0 && !this._isAngularEventPending; } /** @internal */ _runCallbacksIfReady() { if (!this.isStable()) { this._didWork = true; return; // Not ready } // Schedules the call backs in a new frame so that it is always async. PromiseWrapper.resolve(null).then((_) => { while (this._callbacks.length !== 0) { (this._callbacks.pop())(this._didWork); } this._didWork = false; }); } whenStable(callback) { this._callbacks.push(callback); this._runCallbacksIfReady(); } getPendingRequestCount() { return this._pendingCount; } // This only accounts for ngZone, and not pending counts. Use `whenStable` to // check for stability. isAngularEventPending() { return this._isAngularEventPending; } findBindings(using, provider, exactMatch) { // TODO(juliemr): implement. return []; } findProviders(using, provider, exactMatch) { // TODO(juliemr): implement. return []; } }; Testability = __decorate([ Injectable(), __metadata('design:paramtypes', [NgZone]) ], Testability); /** * A global registry of {@link Testability} instances for specific elements. */ export let TestabilityRegistry = class { constructor() { /** @internal */ this._applications = new Map(); _testabilityGetter.addToWindow(this); } registerApplication(token, testability) { this._applications.set(token, testability); } getTestability(elem) { return this._applications.get(elem); } getAllTestabilities() { return MapWrapper.values(this._applications); } getAllRootElements() { return MapWrapper.keys(this._applications); } findTestabilityInTree(elem, findInAncestors = true) { return _testabilityGetter.findTestabilityInTree(this, elem, findInAncestors); } }; TestabilityRegistry = __decorate([ Injectable(), __metadata('design:paramtypes', []) ], TestabilityRegistry); let _NoopGetTestability = class { addToWindow(registry) { } findTestabilityInTree(registry, elem, findInAncestors) { return null; } }; _NoopGetTestability = __decorate([ CONST(), __metadata('design:paramtypes', []) ], _NoopGetTestability); /** * Set the {@link GetTestability} implementation used by the Angular testing framework. */ export function setTestabilityGetter(getter) { _testabilityGetter = getter; } var _testabilityGetter = CONST_EXPR(new _NoopGetTestability());
{ "content_hash": "7e64c29d85bcfe854fd2841f8bc54ffc", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 150, "avg_line_length": 39.659574468085104, "alnum_prop": 0.6037195994277539, "repo_name": "kmouakher/my-first-angular2-app", "id": "0d692e7522580d38b3d7dbe4749bbec2c9acd452", "size": "5592", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "node_modules/angular2/es6/prod/src/core/testability/testability.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "186" }, { "name": "HTML", "bytes": "1292" }, { "name": "JavaScript", "bytes": "29767" }, { "name": "TypeScript", "bytes": "6491" } ], "symlink_target": "" }
package bingo.odata.model; import bingo.lang.exceptions.ReadonlyException; import bingo.meta.edm.EdmParameter; import bingo.meta.edm.EdmType; public class ODataParameterImpl implements ODataParameter { private final EdmParameter metadata; private final Object value; public ODataParameterImpl(EdmParameter metadata,Object value) { this.metadata = metadata; this.value = value; } public EdmParameter getMetadata() { return metadata; } public EdmType getType() { return metadata.getType(); } public String getName() { return metadata.getName(); } public Object getValue() { return value; } public String getKey() { return getName(); } public Object setValue(Object value) { throw new ReadonlyException(); } }
{ "content_hash": "c78a8655c18ea4cc6b802aa0b29f5a12", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 64, "avg_line_length": 20.609756097560975, "alnum_prop": 0.6603550295857988, "repo_name": "bingo-open-source/bingo-odata", "id": "305e9af1942322efcab0cde5b8c886399a3bbb93", "size": "1474", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "odata-core/src/main/java/bingo/odata/model/ODataParameterImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "736490" } ], "symlink_target": "" }
Dynamic configuration with Kubernetes Custom Resource {: .subtitle } ## Definitions ```yaml tab="apiextensions.k8s.io/v1" --8<-- "content/reference/dynamic-configuration/kubernetes-crd-definition-v1.yml" ``` ```yaml tab="apiextensions.k8s.io/v1beta1" --8<-- "content/reference/dynamic-configuration/kubernetes-crd-definition-v1beta1.yml" ``` ## Resources ```yaml --8<-- "content/reference/dynamic-configuration/kubernetes-crd-resource.yml" ``` ## RBAC ```yaml --8<-- "content/reference/dynamic-configuration/kubernetes-crd-rbac.yml" ```
{ "content_hash": "ea676acb8a169277eac464986590996d", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 86, "avg_line_length": 22.666666666666668, "alnum_prop": 0.7352941176470589, "repo_name": "dtomcej/traefik", "id": "ccda41843cbdc2d6833f4653068cf48006bb081f", "size": "582", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/content/reference/dynamic-configuration/kubernetes-crd.md", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "3853" }, { "name": "Go", "bytes": "3074882" }, { "name": "HTML", "bytes": "1480" }, { "name": "JavaScript", "bytes": "83543" }, { "name": "Makefile", "bytes": "5890" }, { "name": "SCSS", "bytes": "6743" }, { "name": "Shell", "bytes": "9721" }, { "name": "Stylus", "bytes": "665" }, { "name": "Vue", "bytes": "171791" } ], "symlink_target": "" }
const { assertDataProperty } = Assert; function assertFunctionName(f, name) { return assertDataProperty(f, "name", {value: name, writable: false, enumerable: false, configurable: true}); } const GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor; // Function/GeneratorFunction constructor { let f = Function(""); assertFunctionName(f, "anonymous"); let g = GeneratorFunction(""); assertFunctionName(g, "anonymous"); }
{ "content_hash": "9a1f5d18907ad8b2e7096f17da1e1577", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 110, "avg_line_length": 23.842105263157894, "alnum_prop": 0.7240618101545254, "repo_name": "anba/es6draft", "id": "928479fce8068238c1b5f420f180db11460eb805", "size": "616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/scripts/suite/semantic/function/name/function_constructor.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1554" }, { "name": "FreeMarker", "bytes": "2627" }, { "name": "Java", "bytes": "7090661" }, { "name": "JavaScript", "bytes": "1796470" }, { "name": "Shell", "bytes": "3027" } ], "symlink_target": "" }
package com.amazonaws.services.kafkaconnect.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Workers can send worker logs to different destination types. This configuration specifies the details of these * destinations. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kafkaconnect-2021-09-14/WorkerLogDeliveryDescription" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class WorkerLogDeliveryDescription implements Serializable, Cloneable, StructuredPojo { /** * <p> * Details about delivering logs to Amazon CloudWatch Logs. * </p> */ private CloudWatchLogsLogDeliveryDescription cloudWatchLogs; /** * <p> * Details about delivering logs to Amazon Kinesis Data Firehose. * </p> */ private FirehoseLogDeliveryDescription firehose; /** * <p> * Details about delivering logs to Amazon S3. * </p> */ private S3LogDeliveryDescription s3; /** * <p> * Details about delivering logs to Amazon CloudWatch Logs. * </p> * * @param cloudWatchLogs * Details about delivering logs to Amazon CloudWatch Logs. */ public void setCloudWatchLogs(CloudWatchLogsLogDeliveryDescription cloudWatchLogs) { this.cloudWatchLogs = cloudWatchLogs; } /** * <p> * Details about delivering logs to Amazon CloudWatch Logs. * </p> * * @return Details about delivering logs to Amazon CloudWatch Logs. */ public CloudWatchLogsLogDeliveryDescription getCloudWatchLogs() { return this.cloudWatchLogs; } /** * <p> * Details about delivering logs to Amazon CloudWatch Logs. * </p> * * @param cloudWatchLogs * Details about delivering logs to Amazon CloudWatch Logs. * @return Returns a reference to this object so that method calls can be chained together. */ public WorkerLogDeliveryDescription withCloudWatchLogs(CloudWatchLogsLogDeliveryDescription cloudWatchLogs) { setCloudWatchLogs(cloudWatchLogs); return this; } /** * <p> * Details about delivering logs to Amazon Kinesis Data Firehose. * </p> * * @param firehose * Details about delivering logs to Amazon Kinesis Data Firehose. */ public void setFirehose(FirehoseLogDeliveryDescription firehose) { this.firehose = firehose; } /** * <p> * Details about delivering logs to Amazon Kinesis Data Firehose. * </p> * * @return Details about delivering logs to Amazon Kinesis Data Firehose. */ public FirehoseLogDeliveryDescription getFirehose() { return this.firehose; } /** * <p> * Details about delivering logs to Amazon Kinesis Data Firehose. * </p> * * @param firehose * Details about delivering logs to Amazon Kinesis Data Firehose. * @return Returns a reference to this object so that method calls can be chained together. */ public WorkerLogDeliveryDescription withFirehose(FirehoseLogDeliveryDescription firehose) { setFirehose(firehose); return this; } /** * <p> * Details about delivering logs to Amazon S3. * </p> * * @param s3 * Details about delivering logs to Amazon S3. */ public void setS3(S3LogDeliveryDescription s3) { this.s3 = s3; } /** * <p> * Details about delivering logs to Amazon S3. * </p> * * @return Details about delivering logs to Amazon S3. */ public S3LogDeliveryDescription getS3() { return this.s3; } /** * <p> * Details about delivering logs to Amazon S3. * </p> * * @param s3 * Details about delivering logs to Amazon S3. * @return Returns a reference to this object so that method calls can be chained together. */ public WorkerLogDeliveryDescription withS3(S3LogDeliveryDescription s3) { setS3(s3); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCloudWatchLogs() != null) sb.append("CloudWatchLogs: ").append(getCloudWatchLogs()).append(","); if (getFirehose() != null) sb.append("Firehose: ").append(getFirehose()).append(","); if (getS3() != null) sb.append("S3: ").append(getS3()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof WorkerLogDeliveryDescription == false) return false; WorkerLogDeliveryDescription other = (WorkerLogDeliveryDescription) obj; if (other.getCloudWatchLogs() == null ^ this.getCloudWatchLogs() == null) return false; if (other.getCloudWatchLogs() != null && other.getCloudWatchLogs().equals(this.getCloudWatchLogs()) == false) return false; if (other.getFirehose() == null ^ this.getFirehose() == null) return false; if (other.getFirehose() != null && other.getFirehose().equals(this.getFirehose()) == false) return false; if (other.getS3() == null ^ this.getS3() == null) return false; if (other.getS3() != null && other.getS3().equals(this.getS3()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCloudWatchLogs() == null) ? 0 : getCloudWatchLogs().hashCode()); hashCode = prime * hashCode + ((getFirehose() == null) ? 0 : getFirehose().hashCode()); hashCode = prime * hashCode + ((getS3() == null) ? 0 : getS3().hashCode()); return hashCode; } @Override public WorkerLogDeliveryDescription clone() { try { return (WorkerLogDeliveryDescription) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kafkaconnect.model.transform.WorkerLogDeliveryDescriptionMarshaller.getInstance().marshall(this, protocolMarshaller); } }
{ "content_hash": "1cbd913a3d0b3d3c90dcbe47024d4c38", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 148, "avg_line_length": 30.70689655172414, "alnum_prop": 0.6257720381807973, "repo_name": "aws/aws-sdk-java", "id": "db5110fe7d76059463658aaef07c1d64e96cb55e", "size": "7704", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-kafkaconnect/src/main/java/com/amazonaws/services/kafkaconnect/model/WorkerLogDeliveryDescription.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'jumanpp_ruby'
{ "content_hash": "6ee418c1666e9cb90ab12d4547bec390", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 58, "avg_line_length": 41, "alnum_prop": 0.6585365853658537, "repo_name": "EastResident/jumanpp_ruby", "id": "52dc3789d202e4812558c7d2a18ee866fd54e966", "size": "82", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4842" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
var model = require('../models/Model'); module.exports = ChooseCharacter = { view: function(){ return m(".pure.g", [ m("h2", "Choose a character"), m("ul", Object.getOwnPropertyNames(model.characters).map(function(cname){ return m("li", m("a", {href: "/" + cname, config: m.route}, model.characters[cname].name)); })) ]); } };
{ "content_hash": "0abc3a080eaf4433e56c1a9fca375d4b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 107, "avg_line_length": 33.666666666666664, "alnum_prop": 0.5247524752475248, "repo_name": "marmaluke/pf-char", "id": "9b9be55f59f37be68471118095dab84418df079a", "size": "404", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "app/components/ChooseCharacter.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "103" }, { "name": "HTML", "bytes": "316" }, { "name": "JavaScript", "bytes": "49915" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <groupId>io.takari</groupId> <artifactId>takari-swagger</artifactId> <version>0.1.2-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <packaging>takari-jar</packaging> <artifactId>takari-swagger-core</artifactId> <dependencies> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> <dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>com.thoughtworks.paranamer</groupId> <artifactId>paranamer</artifactId> <version>2.5.2</version> </dependency> </dependencies> </project>
{ "content_hash": "5c7c6de4670a1797ebb03d83d318f79c", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 108, "avg_line_length": 31.53846153846154, "alnum_prop": 0.6617886178861788, "repo_name": "Randgalt/takari-swagger", "id": "9c596bbbdcb780273770d512fce4a0be804384e7", "size": "1230", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "takari-swagger-core/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "43243" }, { "name": "HTML", "bytes": "4139" }, { "name": "Java", "bytes": "72789" }, { "name": "JavaScript", "bytes": "373706" } ], "symlink_target": "" }
import unittest from parameterized.parameterized import parameterized from conans.test.utils.tools import TestClient from conans.paths import CONANFILE import os from conans.util.files import load tool_conanfile = """from conans import ConanFile class Tool(ConanFile): name = "Tool" version = "0.1" def package_info(self): self.env_info.TOOL_PATH.append("MyToolPath") """ tool_conanfile2 = tool_conanfile.replace("0.1", "0.3") conanfile = """ import os from conans import ConanFile, tools class MyLib(ConanFile): name = "MyLib" version = "0.1" {} def build(self): self.output.info("ToolPath: %s" % os.getenv("TOOL_PATH")) """ requires = conanfile.format('build_requires = "Tool/0.1@lasote/stable"') requires_range = conanfile.format('build_requires = "Tool/[>0.0]@lasote/stable"') requirements = conanfile.format("""def build_requirements(self): self.build_requires("Tool/0.1@lasote/stable")""") override = conanfile.format("""build_requires = "Tool/0.2@user/channel" def build_requirements(self): self.build_requires("Tool/0.1@lasote/stable")""") profile = """ [build_requires] Tool/0.3@lasote/stable nonexistingpattern*: SomeTool/1.2@user/channel """ class BuildRequiresTest(unittest.TestCase): def test_dependents_txt(self): client = TestClient() boost = """from conans import ConanFile class Boost(ConanFile): def package_info(self): self.env_info.PATH.append("myboostpath") """ client.save({CONANFILE: boost}) client.run("create . Boost/1.0@user/channel") other = """[build_requires] Boost/1.0@user/channel """ client.save({"conanfile.txt": other}, clean_first=True) client.run("install .") self.assertIn("""Build requirements Boost/1.0@user/channel""", client.out) conanbuildinfo = load(os.path.join(client.current_folder, "conanbuildinfo.txt")) self.assertIn('PATH=["myboostpath"]', conanbuildinfo) def test_dependents(self): client = TestClient() boost = """from conans import ConanFile class Boost(ConanFile): def package_info(self): self.env_info.PATH.append("myboostpath") """ client.save({CONANFILE: boost}) client.run("create . Boost/1.0@user/channel") other = """from conans import ConanFile import os class Other(ConanFile): requires = "Boost/1.0@user/channel" def build(self): self.output.info("OTHER PATH FOR BUILD %s" % os.getenv("PATH")) def package_info(self): self.env_info.PATH.append("myotherpath") """ client.save({CONANFILE: other}) client.run("create . Other/1.0@user/channel") lib = """from conans import ConanFile import os class Lib(ConanFile): build_requires = "Boost/1.0@user/channel", "Other/1.0@user/channel" def build(self): self.output.info("LIB PATH FOR BUILD %s" % os.getenv("PATH")) """ client.save({CONANFILE: lib}) client.run("create . Lib/1.0@user/channel") self.assertIn("LIB PATH FOR BUILD myotherpath%smyboostpath" % os.pathsep, client.out) def test_transitive(self): client = TestClient() mingw = """from conans import ConanFile class Tool(ConanFile): def package_info(self): self.env_info.PATH.append("mymingwpath") """ myprofile = """ [build_requires] mingw/0.1@lasote/stable """ gtest = """from conans import ConanFile import os class Gtest(ConanFile): def build(self): self.output.info("GTEST PATH FOR BUILD %s" % os.getenv("PATH")) """ app = """from conans import ConanFile import os class App(ConanFile): build_requires = "gtest/0.1@lasote/stable" def build(self): self.output.info("APP PATH FOR BUILD %s" % os.getenv("PATH")) """ client.save({CONANFILE: mingw}) client.run("create . mingw/0.1@lasote/stable") client.save({CONANFILE: gtest}) client.run("export . gtest/0.1@lasote/stable") client.save({CONANFILE: app, "myprofile": myprofile}) client.run("create . app/0.1@lasote/stable --build=missing -pr=myprofile") self.assertIn("app/0.1@lasote/stable: APP PATH FOR BUILD mymingwpath", client.out) self.assertIn("gtest/0.1@lasote/stable: GTEST PATH FOR BUILD mymingwpath", client.out) def test_profile_order(self): client = TestClient() mingw = """from conans import ConanFile class Tool(ConanFile): def package_info(self): self.env_info.PATH.append("mymingwpath") """ msys = """from conans import ConanFile class Tool(ConanFile): def package_info(self): self.env_info.PATH.append("mymsyspath") """ myprofile1 = """ [build_requires] mingw/0.1@lasote/stable msys/0.1@lasote/stable """ myprofile2 = """ [build_requires] msys/0.1@lasote/stable mingw/0.1@lasote/stable """ app = """from conans import ConanFile import os class App(ConanFile): def build(self): self.output.info("APP PATH FOR BUILD %s" % os.getenv("PATH")) """ client.save({CONANFILE: mingw}) client.run("create . mingw/0.1@lasote/stable") client.save({CONANFILE: msys}) client.run("create . msys/0.1@lasote/stable") client.save({CONANFILE: app, "myprofile1": myprofile1, "myprofile2": myprofile2}) client.run("create . app/0.1@lasote/stable -pr=myprofile1") self.assertIn("app/0.1@lasote/stable: APP PATH FOR BUILD mymingwpath%smymsyspath" % os.pathsep, client.out) client.run("create . app/0.1@lasote/stable -pr=myprofile2") self.assertIn("app/0.1@lasote/stable: APP PATH FOR BUILD mymsyspath%smymingwpath" % os.pathsep, client.out) def test_require_itself(self): client = TestClient() mytool_conanfile = """from conans import ConanFile class Tool(ConanFile): def build(self): self.output.info("BUILDING MYTOOL") """ myprofile = """ [build_requires] Tool/0.1@lasote/stable """ client.save({CONANFILE: mytool_conanfile, "profile.txt": myprofile}) client.run("create . Tool/0.1@lasote/stable -pr=profile.txt") self.assertEqual(1, str(client.out).count("BUILDING MYTOOL")) @parameterized.expand([(requires, ), (requires_range, ), (requirements, ), (override, )]) def test_build_requires(self, conanfile): client = TestClient() client.save({CONANFILE: tool_conanfile}) client.run("export . lasote/stable") client.save({CONANFILE: conanfile}, clean_first=True) client.run("export . lasote/stable") client.run("install MyLib/0.1@lasote/stable --build missing") self.assertIn("Tool/0.1@lasote/stable: Generating the package", client.user_io.out) self.assertIn("ToolPath: MyToolPath", client.user_io.out) client.run("install MyLib/0.1@lasote/stable") self.assertNotIn("Tool", client.user_io.out) self.assertIn("MyLib/0.1@lasote/stable: Already installed!", client.user_io.out) @parameterized.expand([(requires, ), (requires_range, ), (requirements, ), (override, )]) def test_profile_override(self, conanfile): client = TestClient() client.save({CONANFILE: tool_conanfile2}, clean_first=True) client.run("export . lasote/stable") client.save({CONANFILE: conanfile, "profile.txt": profile, "profile2.txt": profile.replace("0.3", "[>0.2]")}, clean_first=True) client.run("export . lasote/stable") client.run("install MyLib/0.1@lasote/stable --profile ./profile.txt --build missing") self.assertNotIn("Tool/0.1", client.user_io.out) self.assertNotIn("Tool/0.2", client.user_io.out) self.assertIn("Tool/0.3@lasote/stable: Generating the package", client.user_io.out) self.assertIn("ToolPath: MyToolPath", client.user_io.out) client.run("install MyLib/0.1@lasote/stable") self.assertNotIn("Tool", client.user_io.out) self.assertIn("MyLib/0.1@lasote/stable: Already installed!", client.user_io.out) client.run("install MyLib/0.1@lasote/stable --profile ./profile2.txt --build") self.assertNotIn("Tool/0.1", client.user_io.out) self.assertNotIn("Tool/0.2", client.user_io.out) self.assertIn("Tool/0.3@lasote/stable: Generating the package", client.user_io.out) self.assertIn("ToolPath: MyToolPath", client.user_io.out) def options_test(self): conanfile = """from conans import ConanFile class package(ConanFile): name = "first" version = "0.0.0" options = {"coverage": [True, False]} default_options = "coverage=False" def build(self): self.output.info("Coverage: %s" % self.options.coverage) """ client = TestClient() client.save({"conanfile.py": conanfile}) client.run("export . lasote/stable") consumer = """from conans import ConanFile class package(ConanFile): name = "second" version = "0.0.0" default_options = "first:coverage=True" build_requires = "first/0.0.0@lasote/stable" """ client.save({"conanfile.py": consumer}) client.run("install . --build=missing -o Pkg:someoption=3") self.assertIn("first/0.0.0@lasote/stable: Coverage: True", client.user_io.out)
{ "content_hash": "41ffa6957dcae3548603df33f26a03c2", "timestamp": "", "source": "github", "line_count": 269, "max_line_length": 93, "avg_line_length": 35.446096654275095, "alnum_prop": 0.6321971683272155, "repo_name": "luckielordie/conan", "id": "56498b2ab7148a962e19d5a1d86d4c91598ce934", "size": "9535", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "conans/test/integration/build_requires_test.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1100" }, { "name": "Dockerfile", "bytes": "3392" }, { "name": "Groovy", "bytes": "7992" }, { "name": "Python", "bytes": "3232431" }, { "name": "Shell", "bytes": "1864" } ], "symlink_target": "" }
<div class="m-container"> <div class="m-row content007 g__one-line--top-bottom"> <div class="content007__title g__no-margin--top">Простые блоки без картинок и иконок</div><!--extend sass--> <div class="content007__nested"> <a href="/" class="content007__title-nested">Классное преимущество, всем нравится</a> <div class="content007__text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos suscipit officia quod quam illo in et beatae amet fuga, laudantium!</div> </div> <div class="content007__nested"> <a href="/" class="content007__title-nested">Классное преимущество, всем нравится</a> <div class="content007__text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos suscipit officia quod quam illo in et beatae amet fuga, laudantium!</div> </div> <div class="content007__nested"> <a href="/" class="content007__title-nested">Классное преимущество, всем нравится</a> <div class="content007__text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos suscipit officia quod quam illo in et beatae amet fuga, laudantium!</div> </div> <div class="content007__nested"> <a href="/" class="content007__title-nested">Классное преимущество, всем нравится</a> <div class="content007__text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos suscipit officia quod quam illo in et beatae amet fuga, laudantium!</div> </div> </div> <div class="m-row content007 content007--left g__one-line--top-bottom"> <div class="content007__title g__text--center g__no-margin--top">Простые блоки без картинок и иконок</div><!--extend sass--> <div class="content007__nested"> <a href="/" class="content007__title-nested">Классное преимущество, всем нравится</a> <div class="content007__text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos suscipit officia quod quam illo in et beatae amet fuga, laudantium!</div> </div> <div class="content007__nested"> <a href="/" class="content007__title-nested">Классное преимущество, всем нравится</a> <div class="content007__text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos suscipit officia quod quam illo in et beatae amet fuga, laudantium!</div> </div> <div class="content007__nested"> <a href="/" class="content007__title-nested">Классное преимущество, всем нравится</a> <div class="content007__text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos suscipit officia quod quam illo in et beatae amet fuga, laudantium!</div> </div> <div class="content007__nested"> <a href="/" class="content007__title-nested">Классное преимущество, всем нравится</a> <div class="content007__text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos suscipit officia quod quam illo in et beatae amet fuga, laudantium!</div> </div> </div> </div>
{ "content_hash": "49b4d6db5cd9085c21de6115a8f8cd5e", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 178, "avg_line_length": 77.6, "alnum_prop": 0.666881443298969, "repo_name": "DevGroup-ru/frontend-monster", "id": "313e91d5caf5525cd8c28e1244f9bfc7de0ecf53", "size": "3420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/materials/content-blocks/content-block--007.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "327607" }, { "name": "HTML", "bytes": "2561458" }, { "name": "JavaScript", "bytes": "255649" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/blackboard_courselist" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background_holo_light" android:orientation="vertical" > <include android:id="@+id/blackboard_progressbar_ll" layout="@layout/loading_content_layout" android:visibility="gone" /> <include android:id="@+id/blackboard_error" layout="@layout/error_message_view" /> <com.foound.widget.AmazingListView android:id="@+id/blackboard_class_listview" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/transparent" android:cacheColorHint="@android:color/transparent" /> </LinearLayout>
{ "content_hash": "720733ac6c78b538c1343e06df729f98", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 36.08, "alnum_prop": 0.6829268292682927, "repo_name": "huntj88/utexas-utilities", "id": "84d24fbd96304c2d8db48a1f2bfe3c8252abefc4", "size": "902", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/layout/blackboard_courselist_fragment.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "583861" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>dictionaries: 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.11.1 / dictionaries - 8.10.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> dictionaries <small> 8.10.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-13 21:39:51 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-13 21:39:51 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 coq 8.11.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic 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 # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/dictionaries&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Dictionaries&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword: modules&quot; &quot;keyword: functors&quot; &quot;keyword: search trees&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; &quot;category: Miscellaneous/Extracted Programs/Data structures&quot; &quot;date: 2003-02-6&quot; ] authors: [ &quot;Pierre Castéran &lt;casteran@labri.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/dictionaries/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/dictionaries.git&quot; synopsis: &quot;Dictionaries (with modules)&quot; description: &quot;&quot;&quot; This file contains a specification for dictionaries, and an implementation using binary search trees. Coq&#39;s module system, with module types and functors, is heavily used. It can be considered as a certified version of an example proposed by Paulson in Standard ML. A detailed description (in French) can be found in the chapter 11 of The Coq&#39;Art, the book written by Yves Bertot and Pierre Castéran (please follow the link http://coq.inria.fr/doc-eng.html)&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/dictionaries/archive/v8.10.0.tar.gz&quot; checksum: &quot;md5=f3526b8bd66cfea5d80f86ddda5a866f&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-dictionaries.8.10.0 coq.8.11.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.11.1). The following dependencies couldn&#39;t be met: - coq-dictionaries -&gt; coq &lt; 8.11~ -&gt; ocaml &lt; 4.10 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-dictionaries.8.10.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": "f2fb7db59f48b701bb68e911f5d34b3c", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 159, "avg_line_length": 41.1875, "alnum_prop": 0.5566285004828252, "repo_name": "coq-bench/coq-bench.github.io", "id": "ede41ab2204c705ba49e4bb425a846282f86f1ce", "size": "7276", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.11.1/dictionaries/8.10.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#ifndef STOYUTILS_H_ #define STOYUTILS_H_ #include <vector> #include "cell3DPosition.h" class Brick { public: Cell3DPosition p1; Cell3DPosition p2; }; class StoyUtils { vector<Brick> bricks; public: void readFile(string path_to_file); bool isInside(Cell3DPosition catomPosition); void setBricks(vector<Brick> b) { bricks = b; }; vector<Brick> getBricks() { return bricks; }; }; #endif /* STOYUTILS_H_ */
{ "content_hash": "ca8e6fba955b8ef7bf86d668f1f84ecd", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 52, "avg_line_length": 16.846153846153847, "alnum_prop": 0.680365296803653, "repo_name": "claytronics/visiblesim", "id": "22e13dcefc5344e4c0eb9917045373dc88322dd2", "size": "438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "applicationsSrc/csgCatoms3D/stoyUtils.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "BitBake", "bytes": "26309" }, { "name": "C", "bytes": "35223" }, { "name": "C++", "bytes": "1295688" }, { "name": "Common Lisp", "bytes": "935360" }, { "name": "GLSL", "bytes": "1618" }, { "name": "Makefile", "bytes": "52024" }, { "name": "Python", "bytes": "1688" }, { "name": "Shell", "bytes": "4986" } ], "symlink_target": "" }
package acpi import "fmt" const ( llDSDTAddr = 140 lDSDTAddr = 40 ) // BiosTable contains the information needed to create table images for // firmware such as coreboot or oreboot. It hence includes the RSDP, // [XR]SDT, and the raw table data. The *SDT is always Tables[0] // as in the real tables. type BiosTable struct { RSDP *RSDP Tables []Table } // ReadBiosTables reads tables that are not interpreted by the OS, // i.e. it goes straight to memory and gets them there. We optimistically // hope the bios has not stomped around in low memory messing around. func ReadBiosTables() (*BiosTable, error) { r, err := GetRSDPEBDA() if err != nil { r, err = GetRSDPMem() if err != nil { return nil, err } } Debug("Found an RSDP at %#x", r.base) x, err := NewSDTAddr(r.SDTAddr()) if err != nil { return nil, err } Debug("Found an SDT: %s", String(x)) bios := &BiosTable{ RSDP: r, Tables: []Table{x}, } for _, a := range x.Addrs { Debug("Check Table at %#x", a) t, err := ReadRawTable(a) if err != nil { return nil, fmt.Errorf("%#x:%v", a, err) } Debug("Add table %s", String(t)) bios.Tables = append(bios.Tables, t) // What I love about ACPI is its unchanging // consistency. One table, the FADT, points // to another table, the DSDT. There are // very good reasons for this: // (1) ACPI is a bad design // (2) see (1) // The signature of the FADT is "FACP". // Most appropriate that the names // start with F. So does Failure Of Vision. if t.Sig() != "FACP" { continue } // 64-bit CPUs had been around for 30 years when ACPI // was defined. Nevertheless, they filled it chock full // of 32-bit pointers, and then had to go back and paste // in 64-bit pointers. The mind reels. dsdt, err := getaddr(t.Data(), llDSDTAddr, lDSDTAddr) if err != nil { return nil, err } // This is sometimes a kernel virtual address. // Fix that. t, err = ReadRawTable(int64(uint32(dsdt))) if err != nil { return nil, fmt.Errorf("%#x:%v", uint64(dsdt), err) } Debug("Add table %s", String(t)) bios.Tables = append(bios.Tables, t) } return bios, nil } // RawTablesFromMem reads all the tables from Mem, using the SDT. func RawTablesFromMem() ([]Table, error) { x, err := ReadBiosTables() if err != nil { return nil, err } return x.Tables, err }
{ "content_hash": "ad320b442629e219bc83e86d839283cd", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 73, "avg_line_length": 26.625, "alnum_prop": 0.6500213401621853, "repo_name": "hugelgupf/u-root", "id": "cf104c57cec42b57a9a7ce298f30d3532b237f65", "size": "2506", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pkg/acpi/bios.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "2717" }, { "name": "C", "bytes": "598" }, { "name": "Dockerfile", "bytes": "11562" }, { "name": "Go", "bytes": "3924400" }, { "name": "Makefile", "bytes": "185" }, { "name": "Python", "bytes": "5194" }, { "name": "Shell", "bytes": "952" } ], "symlink_target": "" }
package org.springframework.context.annotation.configuration; import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ClassUtils; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class Spr7167Tests { @Test public void test() { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class); assertThat("someDependency was not post processed", ctx.getBeanFactory().getBeanDefinition("someDependency").getDescription(), equalTo("post processed by MyPostProcessor")); MyConfig config = ctx.getBean(MyConfig.class); assertTrue("Config class was not enhanced", ClassUtils.isCglibProxy(config)); } } @Configuration class MyConfig { @Bean public Dependency someDependency() { return new Dependency(); } @Bean public BeanFactoryPostProcessor thePostProcessor() { return new MyPostProcessor(someDependency()); } } class Dependency { } class MyPostProcessor implements BeanFactoryPostProcessor { public MyPostProcessor(Dependency someDependency) { } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { AbstractBeanDefinition bd = (AbstractBeanDefinition) beanFactory.getBeanDefinition("someDependency"); bd.setDescription("post processed by MyPostProcessor"); } }
{ "content_hash": "18e777d89b4d5077a373430948b79129", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 104, "avg_line_length": 30.672131147540984, "alnum_prop": 0.8214858364510956, "repo_name": "shivpun/spring-framework", "id": "0124e42915565ebfa058c7752616292db1891c30", "size": "2491", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spring-context/src/test/java/org/springframework/context/annotation/configuration/Spr7167Tests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GAP", "bytes": "6137" }, { "name": "Groovy", "bytes": "3685" }, { "name": "HTML", "bytes": "713" }, { "name": "Java", "bytes": "9777605" } ], "symlink_target": "" }
</div><!--EO gliverContainer--> </body> </html>
{ "content_hash": "50aaf7b659821cc61a70d05783640e1d", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 32, "avg_line_length": 16, "alnum_prop": 0.5833333333333334, "repo_name": "mudassar66/glivertest", "id": "d8e4439ef5beed218bc6ba04dce60aa3169af787", "size": "48", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/footer.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "324" }, { "name": "CSS", "bytes": "3504" }, { "name": "JavaScript", "bytes": "149673" }, { "name": "PHP", "bytes": "189572" } ], "symlink_target": "" }
module NanoApi::Client::Affiliate def affiliate affiliate_marker = self.class.extract_marker(marker) return unless affiliate_marker result = get('affiliates/%d' % affiliate_marker, signature: affilate_signature(affiliate_marker)) return unless result.has_key?('affiliate') result['affiliate'].merge(result['affiliate'].delete('info')) rescue RestClient::ResourceNotFound, RestClient::BadRequest, RestClient::Forbidden, RestClient::ServiceUnavailable, RestClient::MethodNotAllowed, RestClient::InternalServerError, JSON::ParserError nil end def affilate_signature affiliate_marker self.class.signature affiliate_marker, [] end end
{ "content_hash": "d10fdfb499f58eaac0235df5b7ca31a9", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 101, "avg_line_length": 29.083333333333332, "alnum_prop": 0.7349570200573066, "repo_name": "KosyanMedia/nano_api", "id": "6659cb1318a5eaf0136c49bd8a611e6838c8fb0f", "size": "698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/nano_api/client/affiliate.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "350" }, { "name": "HTML", "bytes": "8590" }, { "name": "JavaScript", "bytes": "463" }, { "name": "Ruby", "bytes": "110524" } ], "symlink_target": "" }
/*! tablesorter column reorder - beta testing * Requires tablesorter v2.8+ and jQuery 1.7+ * by Rob Garrison */ /*jshint browser:true, jquery:true, unused:false */ /*global jQuery: false */ ;(function($){ "use strict"; $.tablesorter.addWidget({ id: 'reorder', priority: 70, options : { reorder_axis : 'xy', // x or xy reorder_delay : 300, reorder_helperClass : 'tablesorter-reorder-helper', reorder_helperBar : 'tablesorter-reorder-helper-bar', reorder_noReorder : 'reorder-false', reorder_blocked : 'reorder-block-left reorder-block-end', reorder_complete : null // callback }, init: function(table, thisWidget, c, wo) { var i, timer, $helper, $bar, clickOffset, lastIndx = -1, ts = $.tablesorter, endIndex = -1, startIndex = -1, t = wo.reorder_blocked.split(' '), noReorderLeft = t[0] || 'reorder-block-left', noReorderLast = t[1] || 'reorder-block-end', lastOffset = c.$headers.not('.' + noReorderLeft).first(), offsets = c.$headers.map(function(i){ var s, $t = $(this); if ($t.hasClass(noReorderLeft)) { s = lastOffset; $t = s; //lastOffset = $t; } lastOffset = $t; return $t.offset().left; }).get(), len = offsets.length, startReorder = function(e, $th){ var p = $th.position(), r = $th.parent().position(), i = startIndex = $th.index(); clickOffset = [ e.pageX - p.left, e.pageY - r.top ]; $helper = c.$table.clone(); $helper.find('> thead > tr:first').children('[data-column!=' + i + ']').remove(); $helper.find('thead tr:gt(0), caption, colgroup, tbody, tfoot').remove(); $helper .css({ position: 'absolute', zIndex : 1, left: p.left - clickOffset[0], top: r.top - clickOffset[1], width: $th.outerWidth() }) .appendTo('body') .find('th, td').addClass(wo.reorder_helperClass); $bar = $('<div class="' + wo.reorder_helperBar + '" />') .css({ position : 'absolute', top : c.$table.find('thead').offset().top, height : $th.closest('thead').outerHeight() + c.$table.find('tbody').height() }) .appendTo('body'); positionBar(e); lastIndx = endIndex; }, positionBar = function(e){ for (i = 0; i <= len; i++) { if ( i > 0 && e.pageX < offsets[i-1] + (offsets[i] - offsets[i-1])/2 && !c.$headers.eq(i).hasClass(noReorderLeft) ) { endIndex = i - 1; // endIndex = offsets.lastIndexOf( offsets[i-1] ); // lastIndexOf not supported by IE8 and older if (endIndex >= 0 && lastIndx === endIndex) { return false; } lastIndx = endIndex; if (c.debug) { ts.log( endIndex === 0 ? 'target before column 0' : endIndex === len ? 'target after last column' : 'target between columns ' + startIndex + ' and ' + endIndex); } $bar.css('left', offsets[i-1]); return false; } } if (endIndex < 0) { endIndex = len; $bar.css('left', offsets[len]); } }, finishReorder = function(){ $helper.remove(); $bar.remove(); // finish reorder var adj, s = startIndex, rows = c.$table.find('tr'), cols; startIndex = -1; // stop mousemove updates if ( s > -1 && endIndex > -1 && s != endIndex && s + 1 !== endIndex ) { adj = endIndex !== 0; if (c.debug) { ts.log( 'Inserting column ' + s + (adj ? ' after' : ' before') + ' column ' + (endIndex - adj ? 1 : 0) ); } rows.each(function() { cols = $(this).children(); cols.eq(s)[ adj ? 'insertAfter' : 'insertBefore' ]( cols.eq( endIndex - (adj ? 1 : 0) ) ); }); cols = []; // stored header info needs to be modified too! for (i = 0; i < len; i++) { if (i === s) { continue; } if (i === endIndex - (adj ? 1 : 0)) { if (!adj) { cols.push(c.headerContent[s]); } cols.push(c.headerContent[i]); if (adj) { cols.push(c.headerContent[s]); } } else { cols.push(c.headerContent[i]); } } c.headerContent = cols; // cols = c.headerContent.splice(s, 1); // c.headerContent.splice(endIndex - (adj ? 1 : 0), 0, cols); c.$table.trigger('updateAll', [ true, wo.reorder_complete ]); } endIndex = -1; }, mdown = function(e, el){ var $t = $(el), evt = e; if ($t.hasClass(wo.reorder_noReorder)) { return; } timer = setTimeout(function(){ $t.addClass('tablesorter-reorder'); startReorder(evt, $t); }, wo.reorder_delay); }; console.log( c.$headers.last().hasClass(noReorderLast) ); if ( c.$headers.last().hasClass(noReorderLast) ) { offsets.push( offsets[ offsets.length - 1 ] ); } else { offsets.push( c.$table.offset().left + c.$table.outerWidth() ); } c.$headers.not('.' + wo.reorder_noReorder).bind('mousedown.reorder', function(e){ mdown(e, this); }); $(document) .bind('mousemove.reorder', function(e){ if (startIndex !== -1){ var c = { left : e.pageX - clickOffset[0] }; endIndex = -1; if (/y/.test(wo.reorder_axis)) { c.top = e.pageY - clickOffset[1]; } $helper.css(c); positionBar(e); } }) .add( c.$headers ) .bind('mouseup.reorder', function(){ clearTimeout(timer); if (startIndex !== -1 && endIndex !== -1){ finishReorder(); } else { startIndex = -1; } }); // has sticky headers? c.$table.bind('stickyHeadersInit', function(){ wo.$sticky.find('thead').children().not('.' + wo.reorder_noReorder).bind('mousedown.reorder', function(e){ mdown(e, this); }); }); } }); // add mouse coordinates $x = $('#main h1:last'); $(document).mousemove(function(e){ $x.html( e.pageX ); }); })(jQuery);
{ "content_hash": "01a6094b01f58a3f65ba9d1bc73f5984", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 173, "avg_line_length": 33.1978021978022, "alnum_prop": 0.5251572327044025, "repo_name": "jaredhowland/MARC-Record-Tracking-Database", "id": "16374a98107f68f28279f508018c9500f0dde330", "size": "6044", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/js/tablesorter/beta-testing/widget-reorder.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "146308" }, { "name": "HTML", "bytes": "1296920" }, { "name": "JavaScript", "bytes": "688253" }, { "name": "PHP", "bytes": "544902" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Clean Blog - About</title> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Theme CSS --> <link href="css/clean-blog.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <script type="text/javascript"> var pageTitle; var title = document.title; if(title.indexOf("About")>0){ pageTitle = "About"; }else if (title.indexOf("Post")>0) { pageTitle = "Blog"; }else if (title.indexOf("Contact")>0) { pageTitle = "Contact"; }else if (title.indexOf("Video")>0) { pageTitle = "Video"; }else{ pageTitle = "Home"; } var digitalData = { "page": { "pageInfo": { "pageName": pageTitle, "siteSection":pageTitle } } }; </script> </head> <body> <!-- Navigation --> <nav class="navbar navbar-default navbar-custom navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand" href="index.html">Start Bootstrap</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a href="index.html">Home</a> </li> <li> <a href="about.html">About</a> </li> <li> <a href="post.html">Sample Post</a> </li> <li> <a href="video.html">Video Page</a> </li> <li> <a href="contact.html">Contact</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Page Header --> <!-- Set your background image for this header on the line below. --> <header class="intro-header" style="background-image: url('img/about-bg.jpg')"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="page-heading"> <h1>About Me</h1> <hr class="small"> <span class="subheading">This is what I do.</span> </div> </div> </div> </div> </header> <!-- Main Content --> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe nostrum ullam eveniet pariatur voluptates odit, fuga atque ea nobis sit soluta odio, adipisci quas excepturi maxime quae totam ducimus consectetur?</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius praesentium recusandae illo eaque architecto error, repellendus iusto reprehenderit, doloribus, minus sunt. Numquam at quae voluptatum in officia voluptas voluptatibus, minus!</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nostrum molestiae debitis nobis, quod sapiente qui voluptatum, placeat magni repudiandae accusantium fugit quas labore non rerum possimus, corrupti enim modi! Et.</p> </div> </div> </div> <hr> <!-- Footer --> <footer> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <ul class="list-inline text-center"> <li> <a href="#"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-twitter fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="#"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-facebook fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="#"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> <p class="copyright text-muted">Copyright &copy; Your Website 2016</p> </div> </div> </div> </footer> <!-- jQuery --> <script src="vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Theme JavaScript --> <script src="js/clean-blog.min.js"></script> </body> </html>
{ "content_hash": "b1bc1ad52733aac17534fd8663fae9bb", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 261, "avg_line_length": 40.82386363636363, "alnum_prop": 0.4862908837856646, "repo_name": "parthasarma/dtm-demo", "id": "df77e736af986722218ab690ac2906ded789a396", "size": "7185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "about.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "17311" }, { "name": "HTML", "bytes": "56083" }, { "name": "JavaScript", "bytes": "43748" }, { "name": "PHP", "bytes": "1242" } ], "symlink_target": "" }
class CreateFavorites < ActiveRecord::Migration def change create_table :favorites do |t| t.integer :profile_id, null: false t.integer :favable_id, null: false t.string :favable_type, null: false, limit: 60 t.integer :favorite_folder_id, null: false t.datetime :created_at end add_index :favorites, :profile_id add_index :favorites, :favable_id add_index :favorites, :favable_type add_index :favorites, :favorite_folder_id end end
{ "content_hash": "b1e1dd83e4d76fcb53c7c3ce4047c4f2", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 62, "avg_line_length": 32.875, "alnum_prop": 0.6311787072243346, "repo_name": "chimerao/backend", "id": "00235899d890ae55d9a95ddf09fcd94eee262613", "size": "526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20140227235734_create_favorites.rb", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "56022" }, { "name": "Ruby", "bytes": "471140" } ], "symlink_target": "" }
* { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } /* * -- BASE STYLES -- * Most of these are inherited from Base, but I want to change a few. */ body { line-height: 1.7em; color: #7f8c8d; font-size: 13px; } h1, h2, h3, h4, h5, h6, label { color: #6E90B3; } .pure-img-responsive { max-width: 100%; height: auto; } /* * -- LAYOUT STYLES -- * These are some useful classes which I will need */ .l-box { padding: 1em; } .l-box-lrg { padding: 2em; border-bottom: 1px solid rgba(0,0,0,0.1); } .is-center { text-align: center; } /* * -- PURE FORM STYLES -- * Style the form inputs and labels */ .pure-form label { margin: 1em 0 0; font-weight: bold; font-size: 100%; } .pure-form input[type] { border: 2px solid #ddd; box-shadow: none; font-size: 100%; width: 100%; margin-bottom: 1em; } /* * -- PURE BUTTON STYLES -- * I want my pure-button elements to look a little different */ .pure-button { background-color: #1f8dd6; color: white; padding: 0.5em 2em; border-radius: 5px; } a.pure-button-primary { background: white; color: #1f8dd6; border-radius: 5px; font-size: 120%; } /* * -- MENU STYLES -- * I want to customize how my .pure-menu looks at the top of the page */ .home-menu { padding: 0.5em; text-align: center; box-shadow: 0 1px 1px rgba(0,0,0, 0.10); } .home-menu.pure-menu-open { background: #2d3e50; } .pure-menu.pure-menu-open.pure-menu-fixed { /* Fixed menus normally have a border at the bottom. */ border-bottom: none; /* I need a higher z-index here because of the scroll-over effect. */ z-index: 4; } .home-menu .pure-menu-heading { color: white; font-weight: 400; font-size: 120%; } .home-menu .pure-menu-selected a { color: white; } .home-menu a { color: #6FBEF3; } .home-menu li a:hover, .home-menu li a:focus { background: none; border: none; color: #AECFE5; } .map-pin-icon{ transition: 1s; opacity: 0.7; cursor: pointer; border: none; } .map-pin-icon:hover{ opacity: 1; } /* * -- SPLASH STYLES -- * This is the blue top section that appears on the page. */ .splash-container { background: #111; z-index: 1; overflow: hidden; /* The following styles are required for the "scroll-over" effect */ width: 100%; height: 88%; top: 0; left: 0; position: fixed !important; } .splash { /* absolute center .splash within .splash-container */ width: 80%; height: 50%; margin: auto; position: absolute; top: 100px; left: 0; bottom: 0; right: 0; text-align: center; text-transform: uppercase; } /* This is the subheading that appears on the blue section */ .splash-subhead { color: white; letter-spacing: 0.05em; opacity: 0.8; width: 302px; text-align: left; display: block; font-size: 12px; } /* * -- CONTENT STYLES -- * This represents the content area (everything below the blue section) */ .content-wrapper { /* These styles are required for the "scroll-over" effect */ position: absolute; top: 87%; width: 100%; min-height: 12%; z-index: 2; background: rgba(30, 54, 73, 0.82); opacity: 0.3; transition: 1s; } /* This is the class used for the main content headers (<h2>) */ .content-head { font-weight: 400; text-transform: uppercase; letter-spacing: 0.1em; margin: 2em 0 1em; } /* This is a modifier class used when the content-head is inside a ribbon */ .content-head-ribbon { color: white; } /* This is the class used for the content sub-headers (<h3>) */ .content-subhead { color: #1f8dd6; } .content-subhead i { margin-right: 7px; } /* This is the class used for the dark-background areas. */ .ribbon { background: rgba(45, 62, 80, 0.8); color: #aaa; } /* This is the class used for the footer */ .footer { background: #111; } .search-area{ font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; border: 3px solid rgba(250, 250, 250, 0.8); border-radius: 5px; } #autocomplete{ font-weight: 100; color: #fff; line-height: 58px; font-size: 2em; padding: 0.3em 10px 0.3em 0.6em; } /* * -- TABLET (AND UP) MEDIA QUERIES -- * On tablets and other medium-sized devices, we want to customize some * of the mobile styles. */ @media (min-width: 48em) { /* We increase the body font size */ body { font-size: 16px; } /* We want to give the content area some more padding */ .content { padding: 1em; } #autocomplete{ font-size: 3.3em; } /* We can align the menu header to the left, but float the menu items to the right. */ .home-menu { text-align: left; } .home-menu ul { float: right; } /* We increase the height of the splash-container */ /* .splash-container { height: 500px; }*/ /* We decrease the width of the .splash, since we have more width to work with */ .splash { width: 50%; height: 50%; } .splash-head { font-size: 250%; width: 56%; } .splash-subhead{ width: 99%; margin: 13px 5px 6px; } #myLocale{ margin: -8px 0 0 0; } /* We remove the border-separator assigned to .l-box-lrg */ .l-box-lrg { border: none; } } /* * -- DESKTOP (AND UP) MEDIA QUERIES -- * On desktops and other large devices, we want to over-ride some * of the mobile and tablet styles. */ @media (min-width: 78em) { /* We increase the header font size even more */ .splash-head { font-size: 300%; } .splash-subhead{ font-size: inherit; } }
{ "content_hash": "ba1d1e7ae4f9085b438cd56a8b7a73ea", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 76, "avg_line_length": 18.647435897435898, "alnum_prop": 0.5933310415950498, "repo_name": "NowSky/app", "id": "d4f6b2c6f1c35b0fb0c618399bf66f93e3401cdb", "size": "5818", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/css/layouts/marketing.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "35984" }, { "name": "HTML", "bytes": "185067" }, { "name": "JavaScript", "bytes": "21961" } ], "symlink_target": "" }
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'VirtualFile.content_type' db.add_column('seoutils_virtualfile', 'content_type', self.gf('django.db.models.fields.CharField')(default='text/plain', max_length=100), keep_default=False) def backwards(self, orm): # Deleting field 'VirtualFile.content_type' db.delete_column('seoutils_virtualfile', 'content_type') models = { 'seoutils.analytic': { 'Meta': {'object_name': 'Analytic'}, 'code': ('django.db.models.fields.TextField', [], {}), 'description': ('django.db.models.fields.CharField', [], {'default': "'Main Analytic'", 'max_length': '250', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}) }, 'seoutils.meta': { 'Meta': {'object_name': 'Meta'}, 'desc': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'desc_en': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'desc_fr': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'extra_js': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'keywords': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'keywords_en': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'keywords_fr': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'path_info': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '250', 'db_index': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'title_en': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}), 'title_fr': ('django.db.models.fields.CharField', [], {'max_length': '250', 'null': 'True', 'blank': 'True'}) }, 'seoutils.virtualfile': { 'Meta': {'object_name': 'VirtualFile'}, 'content': ('django.db.models.fields.TextField', [], {}), 'content_type': ('django.db.models.fields.CharField', [], {'default': "'text/plain'", 'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'url': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '250', 'db_index': 'True'}) } } complete_apps = ['seoutils']
{ "content_hash": "2d5fe2e3b0917445792da6a064b83576", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 155, "avg_line_length": 60.63461538461539, "alnum_prop": 0.5467808436409769, "repo_name": "h3/django-seoutils", "id": "1a1879a1daf7f0b02fcf29090d0d7e1ccfc316bd", "size": "3177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "seoutils/migrations/0008_auto__add_field_virtualfile_content_type.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "43370" } ], "symlink_target": "" }
#ifndef X264_THREADPOOL_H #define X264_THREADPOOL_H typedef struct x264_threadpool_t x264_threadpool_t; #if HAVE_THREAD #define x264_threadpool_init x264_template(threadpool_init) int x264_threadpool_init( x264_threadpool_t **p_pool, int threads, void (*init_func)(void *), void *init_arg ); #define x264_threadpool_run x264_template(threadpool_run) void x264_threadpool_run( x264_threadpool_t *pool, void *(*func)(void *), void *arg ); #define x264_threadpool_wait x264_template(threadpool_wait) void *x264_threadpool_wait( x264_threadpool_t *pool, void *arg ); #define x264_threadpool_delete x264_template(threadpool_delete) void x264_threadpool_delete( x264_threadpool_t *pool ); #else #define x264_threadpool_init(p,t,f,a) -1 #define x264_threadpool_run(p,f,a) #define x264_threadpool_wait(p,a) NULL #define x264_threadpool_delete(p) #endif #endif
{ "content_hash": "0b2dac45ae2128421e521e11e411e1ed", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 87, "avg_line_length": 35.72, "alnum_prop": 0.7312430011198209, "repo_name": "zhaozhencn/PushRTMPStreamSync", "id": "dc94a3f5e35c14b4aac7f2079ca286ecf6806554", "size": "2105", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "capture/libs/x264/common/threadpool.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1175677" }, { "name": "Batchfile", "bytes": "47" }, { "name": "C", "bytes": "5466725" }, { "name": "C++", "bytes": "4521971" }, { "name": "CMake", "bytes": "45569" }, { "name": "HTML", "bytes": "56345" }, { "name": "Makefile", "bytes": "15584" }, { "name": "Objective-C", "bytes": "39036" }, { "name": "Perl", "bytes": "43299" }, { "name": "Python", "bytes": "45639" }, { "name": "Shell", "bytes": "4104" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="JavadocGenerationManager"> <option name="OUTPUT_DIRECTORY" value="$PROJECT_DIR$/../JavaDoc" /> <option name="OPTION_SCOPE" value="private" /> </component> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8.0_181" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/out" /> </component> </project>
{ "content_hash": "e40552d6c4c8558e62bc9a2f49da033b", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 146, "avg_line_length": 46.3, "alnum_prop": 0.6825053995680346, "repo_name": "pollostrazon/HGMD_updates", "id": "e8143d38dce97c14b756201aa4d2cf386c69b642", "size": "463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HGMD_GeneDisease_update/.idea/misc.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "32363" } ], "symlink_target": "" }
package example.phan.sinh.imagepickerandpicasso.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.UUID; /** * Created by sinhpn on 12/9/2015. * Email: pnsinh.hg92@gmail.com */ public class ImagePicker implements ImagePickerConfig { private static final String TAG = "ImagePicker"; public enum ImageSource { GALLERY, CAMERA } public interface Callbacks { public void onImagePickerError(Exception e, ImageSource source); public void onImagePicked(File imageFile, ImageSource source); public void onImagePickedUri(Uri uri, ImageSource source); } private static final String KEY_PHOTO_URI = "photo_uri"; private static File tempImageDirectory(Context context) { File dir = new File(context.getApplicationContext().getCacheDir(), "Images"); if (!dir.exists()) dir.mkdirs(); return dir; } private static File publicImageDirectory() { File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Images"); if (!dir.exists()) dir.mkdirs(); return dir; } public static void openGalleryPicker(Activity activity) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); activity.startActivityForResult(intent, REQ_PICK_PICTURE_FROM_GALLERY); } private static File pickedGalleryPicture(Context context, Uri photoPath) throws IOException { InputStream pictureInputStream = context.getContentResolver().openInputStream(photoPath); File directory = ImagePicker.tempImageDirectory(context); File photoFile = new File(directory, UUID.randomUUID().toString() + ".jpg"); photoFile.createNewFile(); ImagePicker.writeToFile(pictureInputStream, photoFile); return photoFile; } private static void writeToFile(InputStream in, File file) { try { OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); in.close(); } catch (Exception e) { Log.e(TAG, e.getMessage()); } } public static void handleActivityResult(int requestCode, int resultCode, Intent data, Activity activity, Callbacks callbacks) { if (resultCode == Activity.RESULT_OK && requestCode == ImagePickerConfig.REQ_PICK_PICTURE_FROM_GALLERY && data != null) { Uri photoPath = data.getData(); try { callbacks.onImagePickedUri(photoPath, ImageSource.GALLERY); File photoFile = ImagePicker.pickedGalleryPicture(activity, photoPath); callbacks.onImagePicked(photoFile, ImageSource.GALLERY); } catch (Exception e) { Log.e(TAG, e.getMessage()); callbacks.onImagePickerError(e, ImageSource.GALLERY); } } } }
{ "content_hash": "9cf208a7bc8725eecfabadbf0bc18fa0", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 131, "avg_line_length": 35.528301886792455, "alnum_prop": 0.6585236325013276, "repo_name": "sinhpn92/ImagePickerAndPicassoExample", "id": "5578fdb7dd256b33e795f6e7ded1988479d9f1ce", "size": "3766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/example/phan/sinh/imagepickerandpicasso/utils/ImagePicker.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "6884" } ], "symlink_target": "" }
using System; using System.ComponentModel.Composition.Hosting; using System.IO; namespace ToolsManager { public class AutoRefreshDirectoryCatalog : DirectoryCatalog { public bool NotifyOnDirectoryChanged { get; private set; } public AutoRefreshDirectoryCatalog(string path) : this(path, false) { } public AutoRefreshDirectoryCatalog(string path, bool notifyOnDirectoryChanged) : base(path) { this.NotifyOnDirectoryChanged = notifyOnDirectoryChanged; if (notifyOnDirectoryChanged) { FileSystemWatcher fsw = new FileSystemWatcher(path, "*.dll"); fsw.EnableRaisingEvents = true; fsw.Created += (s, e) => { Refresh(); }; fsw.Changed += (s, e) => { Refresh(); }; fsw.Deleted += (s, e) => { Refresh(); }; } } public AutoRefreshDirectoryCatalog(string path, string searchPattern,Func<bool> func=null ) : this(path, searchPattern, false,func) { } public AutoRefreshDirectoryCatalog(string path, string searchPattern, bool notifyOnDirectoryChanged,Func<bool> func=null ):base(path,searchPattern) { this.NotifyOnDirectoryChanged = notifyOnDirectoryChanged; if (notifyOnDirectoryChanged) { FileSystemWatcher fsw = new FileSystemWatcher(path,searchPattern); fsw.EnableRaisingEvents = true; fsw.Created += (s, e) => { Refresh(); if (func != null) { func(); } }; fsw.Changed += (s, e) => { Refresh(); if (func != null) { func(); } }; fsw.Deleted += (s, e) => { Refresh(); if (func != null) { func(); } }; } } } }
{ "content_hash": "8df8c44e09da80ebe8b034d480ae8a39", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 155, "avg_line_length": 32.45070422535211, "alnum_prop": 0.4457465277777778, "repo_name": "idefav/ToolsManager", "id": "1ed4c3000c890fa150b5434abca5cb481ce09b51", "size": "2306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ToolsManager/AutoRefreshDirectoryCatalog.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "17580" } ], "symlink_target": "" }
import copy import logging import pytest from tests.common.test_vector import * from tests.common.impala_test_suite import ImpalaTestSuite from tests.common.test_dimensions import create_uncompressed_text_dimension from tests.util.test_file_parser import QueryTestSectionReader from tests.common.test_dimensions import create_exec_option_dimension class TestQueries(ImpalaTestSuite): @classmethod def add_test_dimensions(cls): super(TestQueries, cls).add_test_dimensions() if cls.exploration_strategy() == 'core': cls.TestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format == 'parquet') # Manually adding a test dimension here to test the small query opt # in exhaustive. # TODO Cleanup required, allow adding values to dimensions without having to # manually explode them if cls.exploration_strategy() == 'exhaustive': dim = cls.TestMatrix.dimensions["exec_option"] new_value = [] for v in dim: new_value.append(TestVector.Value(v.name, copy.copy(v.value))) new_value[-1].value["exec_single_node_rows_threshold"] = 100 dim.extend(new_value) cls.TestMatrix.add_dimension(dim) @classmethod def get_workload(cls): return 'functional-query' def test_exprs(self, vector): # TODO: Enable some of these tests for Avro if possible # Don't attempt to evaluate timestamp expressions with Avro tables (which) # don't support a timestamp type)" table_format = vector.get_value('table_format') if table_format.file_format == 'avro': pytest.skip() if table_format.file_format == 'hbase': pytest.xfail("A lot of queries check for NULLs, which hbase does not recognize") self.run_test_case('QueryTest/exprs', vector) # This will change the current database to matching table format and then execute # select current_database(). An error will be thrown if multiple values are returned. current_db = self.execute_scalar('select current_database()', vector=vector) assert current_db == QueryTestSectionReader.get_db_name(table_format) def test_hdfs_scan_node(self, vector): self.run_test_case('QueryTest/hdfs-scan-node', vector) def test_analytic_fns(self, vector): # TODO: Enable some of these tests for Avro if possible # Don't attempt to evaluate timestamp expressions with Avro tables which doesn't # support a timestamp type yet table_format = vector.get_value('table_format') if table_format.file_format == 'avro': pytest.skip() if table_format.file_format == 'hbase': pytest.xfail("A lot of queries check for NULLs, which hbase does not recognize") self.run_test_case('QueryTest/analytic-fns', vector) def test_file_partitions(self, vector): self.run_test_case('QueryTest/hdfs-partitions', vector) def test_limit(self, vector): if vector.get_value('table_format').file_format == 'hbase': pytest.xfail("IMPALA-283 - select count(*) produces inconsistent results") self.run_test_case('QueryTest/limit', vector) def test_top_n(self, vector): if vector.get_value('table_format').file_format == 'hbase': pytest.xfail(reason="IMPALA-283 - select count(*) produces inconsistent results") # QueryTest/top-n is also run in test_sort with disable_outermost_topn = 1 self.run_test_case('QueryTest/top-n', vector) def test_union(self, vector): self.run_test_case('QueryTest/union', vector) def test_sort(self, vector): if vector.get_value('table_format').file_format == 'hbase': pytest.xfail(reason="IMPALA-283 - select count(*) produces inconsistent results") vector.get_value('exec_option')['disable_outermost_topn'] = 1 self.run_test_case('QueryTest/sort', vector) # We can get the sort tests for free from the top-n file self.run_test_case('QueryTest/top-n', vector) def test_inline_view(self, vector): if vector.get_value('table_format').file_format == 'hbase': pytest.xfail("jointbl does not have columns with unique values, " "hbase collapses them") self.run_test_case('QueryTest/inline-view', vector) def test_inline_view_limit(self, vector): self.run_test_case('QueryTest/inline-view-limit', vector) def test_subquery(self, vector): self.run_test_case('QueryTest/subquery', vector) def test_empty(self, vector): self.run_test_case('QueryTest/empty', vector) def test_views(self, vector): if vector.get_value('table_format').file_format == "hbase": pytest.xfail("TODO: Enable views tests for hbase") self.run_test_case('QueryTest/views', vector) def test_with_clause(self, vector): if vector.get_value('table_format').file_format == "hbase": pytest.xfail("TODO: Enable with clause tests for hbase") self.run_test_case('QueryTest/with-clause', vector) def test_misc(self, vector): table_format = vector.get_value('table_format') if table_format.file_format in ['hbase', 'rc', 'parquet']: msg = ("Failing on rc/snap/block despite resolution of IMP-624,IMP-503. " "Failing on parquet because tables do not exist") pytest.xfail(msg) self.run_test_case('QueryTest/misc', vector) def test_null_data(self, vector): if vector.get_value('table_format').file_format == 'hbase': pytest.xfail("null data does not appear to work in hbase") self.run_test_case('QueryTest/null_data', vector) # Tests in this class are only run against text/none either because that's the only # format that is supported, or the tests don't exercise the file format. class TestQueriesTextTables(ImpalaTestSuite): @classmethod def add_test_dimensions(cls): super(TestQueriesTextTables, cls).add_test_dimensions() cls.TestMatrix.add_dimension(create_uncompressed_text_dimension(cls.get_workload())) @classmethod def get_workload(cls): return 'functional-query' def test_overflow(self, vector): self.run_test_case('QueryTest/overflow', vector) def test_data_source_tables(self, vector): self.run_test_case('QueryTest/data-source-tables', vector) def test_distinct_estimate(self, vector): # These results will vary slightly depending on how the values get split up # so only run with 1 node and on text. vector.get_value('exec_option')['num_nodes'] = 1 self.run_test_case('QueryTest/distinct-estimate', vector) def test_mixed_format(self, vector): self.run_test_case('QueryTest/mixed-format', vector) def test_values(self, vector): self.run_test_case('QueryTest/values', vector)
{ "content_hash": "58f24a99522d8d2266f56ac8f6e72d0d", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 89, "avg_line_length": 41.54430379746835, "alnum_prop": 0.7052102376599635, "repo_name": "grundprinzip/Impala", "id": "e953476a206b2fbae75dca0bc01645e19c481d8f", "size": "6674", "binary": false, "copies": "1", "ref": "refs/heads/cdh5-trunk", "path": "tests/query_test/test_queries.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Bison", "bytes": "78368" }, { "name": "C", "bytes": "15836" }, { "name": "C++", "bytes": "5673395" }, { "name": "CSS", "bytes": "86925" }, { "name": "Java", "bytes": "3202063" }, { "name": "PHP", "bytes": "361" }, { "name": "Python", "bytes": "1494608" }, { "name": "Shell", "bytes": "142106" }, { "name": "Thrift", "bytes": "238809" } ], "symlink_target": "" }
$(function () { $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['zh-CN']) var searchText = $('.search').find('input').val() var columns = [] columns.push({ title: '分类', field: 'category', align: 'center', valign: 'middle', width: '5%', formatter: function (value, row, index) { return value } }, { title: '图片', field: 'url', align: 'center', valign: 'middle', formatter: function (value, row, index) { return "<img data-original='" + value + "' onclick=slideShow(" + index + ") width='100%' src='" + value + "'>" } }, { title: ' 操作', field: 'id', align: 'center', width: '5%', formatter: function (value, row, index) { var html = "" html += "<div onclick='addFavorite(" + value + ")' name='addFavorite' id='addFavorite" + value + "' class='btn btn-success'>收藏</div><p>" html += "<div onclick='downloadImage(" + row.url + ")' class='btn btn-primary'>下载</div><p>" html += "<div onclick='deleteById(" + value + ")' name='delete' id='delete" + value + "' class='btn btn-warning'>删除</div>" return html } }) $('#sotu_table').bootstrapTable({ url: 'sotuSearchJson', sidePagination: "server", queryParamsType: 'page,size', contentType: "application/x-www-form-urlencoded", method: 'get', striped: false, //是否显示行间隔色 buttonsAlign: 'right', smartDisplay: true, cache: false, //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*) pagination: true, //是否显示分页(*) paginationLoop: true, paginationHAlign: 'right', //right, left paginationVAlign: 'bottom', //bottom, top, both paginationDetailHAlign: 'left', //right, left paginationPreText: ' 上一页', paginationNextText: '下一页', search: true, searchText: searchText, searchTimeOut: 500, searchAlign: 'right', searchOnEnterKey: false, trimOnSearch: true, sortable: true, //是否启用排序 sortOrder: "desc", //排序方式 sortName: "id", pageNumber: 1, //初始化加载第一页,默认第一页 pageSize: 10, //每页的记录行数(*) pageList: [20, 50, 100, 200, 500, 1000], // 可选的每页数据 totalField: 'totalElements', // 所有记录 count dataField: 'content', //后端 json 对应的表格List数据的 key columns: columns, queryParams: function (params) { return { size: params.pageSize, page: params.pageNumber - 1, sortName: params.sortName, sortOrder: params.sortOrder, searchText: params.searchText } }, classes: 'table table-responsive full-width', }) var keyWord = getKeyWord() $('.search').find('input').val(keyWord) }) function getKeyWord() { var url = decodeURI(location.href) var indexOfKeyWord = url.indexOf('?keyWord=') if (indexOfKeyWord != -1) { var start = indexOfKeyWord + '?keyWord='.length return url.substring(start) } else { return "" } }
{ "content_hash": "bf09909a39aad72f6485b1f121ef2fe1", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 148, "avg_line_length": 33.422680412371136, "alnum_prop": 0.5323874151758174, "repo_name": "EasySpringBoot/picture-crawler", "id": "c0ea66e344d27928c67f5dbd67ce44c00154ff3d", "size": "3478", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/static/sotu_table.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "97" }, { "name": "FreeMarker", "bytes": "4856" }, { "name": "JavaScript", "bytes": "24759" }, { "name": "Kotlin", "bytes": "28270" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; using System.Reflection; using Xamarin.Forms.CustomAttributes; #if UITEST using NUnit.Framework; using Xamarin.UITest; #endif namespace Xamarin.Forms.Controls { internal static class AppPaths { public static string ApkPath = "../../../Xamarin.Forms.ControlGallery.Android/bin/Debug/AndroidControlGallery.AndroidControlGallery-Signed.apk"; // Have to continue using the old BundleId for now; Test Cloud doesn't like // when you change the BundleId public static string BundleId = "com.xamarin.quickui.controlgallery"; } #if UITEST internal static class AppSetup { static IApp InitializeApp () { IApp app = null; #if __ANDROID__ app = InitializeAndroidApp(); #elif __IOS__ app = InitializeiOSApp(); #endif if (app == null) throw new NullReferenceException ("App was not initialized."); // Wrap the app in ScreenshotConditional so it only takes screenshots if the SCREENSHOTS symbol is specified return new ScreenshotConditionalApp(app); } #if __ANDROID__ static IApp InitializeAndroidApp() { return ConfigureApp.Android.ApkFile(AppPaths.ApkPath).Debug().StartApp(); } #endif #if __IOS__ static IApp InitializeiOSApp() { // Running on a device var app = ConfigureApp.iOS.InstalledApp(AppPaths.BundleId).Debug() //Uncomment to run from a specific iOS SIM, get the ID from XCode -> Devices .StartApp(); // Running on the simulator //var app = ConfigureApp.iOS // .PreferIdeSettings() // .AppBundle("../../../Xamarin.Forms.ControlGallery.iOS/bin/iPhoneSimulator/Debug/XamarinFormsControlGalleryiOS.app") // .Debug() // .StartApp(); return app; } #endif public static void NavigateToIssue (Type type, IApp app) { var typeIssueAttribute = type.GetTypeInfo ().GetCustomAttribute <IssueAttribute> (); string cellName = ""; if (typeIssueAttribute.IssueTracker.ToString () != "None" && typeIssueAttribute.IssueNumber != 1461 && typeIssueAttribute.IssueNumber != 342) { cellName = typeIssueAttribute.IssueTracker.ToString ().Substring(0, 1) + typeIssueAttribute.IssueNumber.ToString (); } else { cellName = typeIssueAttribute.Description; } int maxAttempts = 2; int attempts = 0; while (attempts < maxAttempts) { attempts += 1; try { // Attempt the direct way of navigating to the test page #if __ANDROID__ if (bool.Parse((string)app.Invoke("NavigateToTest", cellName))) { return; } #endif #if __IOS__ if (bool.Parse(app.Invoke("navigateToTest:", cellName).ToString())) { return; } #endif } catch (Exception ex) { var debugMessage = $"Could not directly invoke test; using UI navigation instead. {ex}"; System.Diagnostics.Debug.WriteLine(debugMessage); Console.WriteLine(debugMessage); } try { // Fall back to the "manual" navigation method app.Tap(q => q.Button("Go to Test Cases")); app.WaitForElement(q => q.Raw("* marked:'TestCasesIssueList'")); app.EnterText(q => q.Raw("* marked:'SearchBarGo'"), cellName); app.WaitForElement(q => q.Raw("* marked:'SearchButton'")); app.Tap(q => q.Raw("* marked:'SearchButton'")); return; } catch (Exception ex) { var debugMessage = $"Both navigation methods failed. {ex}"; System.Diagnostics.Debug.WriteLine(debugMessage); Console.WriteLine(debugMessage); if (attempts < maxAttempts) { // Something has failed and we're stuck in a place where we can't navigate // to the test. Usually this is because we're getting network/HTTP errors // communicating with the server on the device. So we'll try restarting the app. RunningApp = InitializeApp(); } else { // But if it's still not working after [maxAttempts], we've got assume this is a legit // problem that restarting won't fix throw; } } } } public static IApp Setup (Type pageType = null) { IApp runningApp = null; try { runningApp = InitializeApp (); } catch (Exception e) { Assert.Inconclusive ($"App did not start for some reason: {e}"); } if (pageType != null) NavigateToIssue (pageType, runningApp); return runningApp; } // Make sure the server on the device is still up and running; // if not, restart the app public static void EnsureConnection() { if (RunningApp != null) { try { RunningApp.TestServer.Get("version"); return; } catch (Exception ex) { } RunningApp = InitializeApp(); } } static int s_testsrun; const int ConsecutiveTestLimit = 10; // Until we get more of our memory leak issues worked out, restart the app // after a specified number of tests so we don't get bogged down in GC // (or booted by jetsam) public static void EnsureMemory() { if (RunningApp != null) { s_testsrun += 1; if (s_testsrun >= ConsecutiveTestLimit) { s_testsrun = 0; RunningApp = InitializeApp(); } } } // For tests which just don't play well with others, we can ensure // that they run in their own instance of the application public static void BeginIsolate() { if (RunningApp != null && s_testsrun > 0) { s_testsrun = 0; RunningApp = InitializeApp(); } } public static void EndIsolate() { s_testsrun = ConsecutiveTestLimit; } public static IApp RunningApp { get; set; } } #endif public abstract class TestPage : Page { #if UITEST public IApp RunningApp => AppSetup.RunningApp; protected virtual bool Isolate => false; #endif protected TestPage () { #if APP Init (); #endif } #if UITEST [SetUp] public void Setup() { if (Isolate) { AppSetup.BeginIsolate(); } else { AppSetup.EnsureMemory(); AppSetup.EnsureConnection(); } AppSetup.NavigateToIssue(GetType(), RunningApp); } [TearDown] public void TearDown() { if (Isolate) { AppSetup.EndIsolate(); } } #endif protected abstract void Init (); } public abstract class TestContentPage : ContentPage { #if UITEST public IApp RunningApp => AppSetup.RunningApp; protected virtual bool Isolate => false; #endif protected TestContentPage () { #if APP Init (); #endif } #if UITEST [SetUp] public void Setup () { if (Isolate) { AppSetup.BeginIsolate(); } else { AppSetup.EnsureMemory(); AppSetup.EnsureConnection(); } AppSetup.NavigateToIssue(GetType(), RunningApp); } [TearDown] public void TearDown() { if (Isolate) { AppSetup.EndIsolate(); } } #endif protected abstract void Init (); } public abstract class TestCarouselPage : CarouselPage { #if UITEST public IApp RunningApp => AppSetup.RunningApp; protected virtual bool Isolate => false; #endif protected TestCarouselPage () { #if APP Init (); #endif } #if UITEST [SetUp] public void Setup() { if (Isolate) { AppSetup.BeginIsolate(); } else { AppSetup.EnsureMemory(); AppSetup.EnsureConnection(); } AppSetup.NavigateToIssue(GetType(), RunningApp); } [TearDown] public void TearDown() { if (Isolate) { AppSetup.EndIsolate(); } } #endif protected abstract void Init (); } public abstract class TestMasterDetailPage : MasterDetailPage { #if UITEST public IApp RunningApp => AppSetup.RunningApp; protected virtual bool Isolate => false; #endif protected TestMasterDetailPage () { #if APP Init (); #endif } #if UITEST [SetUp] public void Setup() { if (Isolate) { AppSetup.BeginIsolate(); } else { AppSetup.EnsureMemory(); AppSetup.EnsureConnection(); } AppSetup.NavigateToIssue(GetType(), RunningApp); } [TearDown] public void TearDown() { if (Isolate) { AppSetup.EndIsolate(); } } #endif protected abstract void Init (); } public abstract class TestNavigationPage : NavigationPage { #if UITEST public IApp RunningApp => AppSetup.RunningApp; protected virtual bool Isolate => false; #endif protected TestNavigationPage () { #if APP Init (); #endif } #if UITEST [SetUp] public void Setup() { if (Isolate) { AppSetup.BeginIsolate(); } else { AppSetup.EnsureMemory(); AppSetup.EnsureConnection(); } AppSetup.NavigateToIssue(GetType(), RunningApp); } [TearDown] public void TearDown() { if (Isolate) { AppSetup.EndIsolate(); } } #endif protected abstract void Init (); } public abstract class TestTabbedPage : TabbedPage { #if UITEST public IApp RunningApp => AppSetup.RunningApp; protected virtual bool Isolate => false; #endif protected TestTabbedPage () { #if APP Init (); #endif } #if UITEST [SetUp] public void Setup() { if (Isolate) { AppSetup.BeginIsolate(); } else { AppSetup.EnsureMemory(); AppSetup.EnsureConnection(); } AppSetup.NavigateToIssue(GetType(), RunningApp); } [TearDown] public void TearDown() { if (Isolate) { AppSetup.EndIsolate(); } } #endif protected abstract void Init (); } } #if UITEST namespace Xamarin.Forms.Controls.Issues { using System; using NUnit.Framework; // Run setup once for all tests in the Xamarin.Forms.Controls.Issues namespace // (instead of once for each test) [SetUpFixture] public class IssuesSetup { [SetUp] public void RunBeforeAnyTests() { AppSetup.RunningApp = AppSetup.Setup(null); } } } #endif
{ "content_hash": "a02935b72b09ffdaf1ac602a44b40361", "timestamp": "", "source": "github", "line_count": 518, "max_line_length": 152, "avg_line_length": 18.66988416988417, "alnum_prop": 0.6492606762485782, "repo_name": "Hitcents/Xamarin.Forms", "id": "6400a2ac18f1a1d026bdff601e0c2992927c2c99", "size": "9673", "binary": false, "copies": "1", "ref": "refs/heads/hitcents", "path": "Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/TestPages/TestPages.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1761" }, { "name": "C#", "bytes": "5547104" }, { "name": "CSS", "bytes": "523" }, { "name": "HTML", "bytes": "1028" }, { "name": "Java", "bytes": "2022" }, { "name": "Makefile", "bytes": "1775" }, { "name": "PowerShell", "bytes": "8514" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "4f49fb98c78c4f17e1943dffb424f653", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "e3ebd27d4bfd577996437578a90579248c073b3a", "size": "193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Polystichum/Polystichum acrostichoides/Polystichum acrostichoides recurvatum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
all: pip install -r requirements.txt python setup.py install develop: pip install -r requirements-dev.txt python setup.py develop test: py.test -v --cov=pyret --cov-report=html tests lint: flake8 pyret/*.py clean: rm -rf htmlcov/ rm -rf pyret.egg-info rm -f pyret/*.pyc rm -rf pyret/__pycache__ rm -rf dist/ build: python setup.py bdist_wheel upload: python setup.py sdist upload
{ "content_hash": "02063827ddeabc75fecb5f64eb75b55d", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 47, "avg_line_length": 15.346153846153847, "alnum_prop": 0.7117794486215538, "repo_name": "baccuslab/pyret", "id": "e0e1029becf1bb4cd8ece5e0a6ff4e0788549925", "size": "399", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "399" }, { "name": "Python", "bytes": "110906" }, { "name": "TeX", "bytes": "1538" } ], "symlink_target": "" }
module Replicate # Simple OpenStruct style object that supports the dump and load protocols. # Useful in tests and also when you want to dump an object that doesn't # implement the dump and load methods. # # >> object = Replicate::Object.new :name => 'Joe', :age => 24 # >> object.age # >> 24 # >> object.attributes # { 'name' => 'Joe', 'age' => 24 } # class Object attr_accessor :id attr_accessor :attributes def initialize(id=nil, attributes={}) attributes, id = id, nil if id.is_a?(Hash) @id = id || self.class.generate_id self.attributes = attributes end def attributes=(hash) @attributes = {} hash.each { |key, value| write_attribute key, value } end def [](key) @attributes[key.to_s] end def []=(key, value) @attributes[key.to_s] = value end def write_attribute(key, value) meta = (class<<self;self;end) meta.send(:define_method, key) { value } meta.send(:define_method, "#{key}=") { |val| write_attribute(key, val) } @attributes[key.to_s] = value value end def dump_replicant(dumper, opts={}) dumper.write self.class, @id, @attributes, self end def self.load_replicant(type, id, attrs) object = new(generate_id, attrs) [object.id, object] end def self.generate_id @last_id ||= 0 @last_id += 1 end end end
{ "content_hash": "29e502a059863a0f84980bfb543029cf", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 78, "avg_line_length": 25.228070175438596, "alnum_prop": 0.586230876216968, "repo_name": "staqapp/replicate", "id": "eabe2c0aa1b4f08f79e8b5816bc9760d18d55a5b", "size": "1438", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/replicate/object.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "79244" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>cfgv: 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 / extra-dev</a></li> <li class="active"><a href="">8.11.dev / cfgv - 8.10.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> cfgv <small> 8.10.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-07-18 17:11:19 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-18 17:11:19 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-m4 1 Virtual package relying on m4 coq 8.11.dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/http://www.nuprl.org/html/CFGVLFMTP2014/&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/CFGV&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword: generic programming&quot; &quot;keyword: variable bindings&quot; &quot;keyword: context free grammars&quot; &quot;keyword: substitution&quot; &quot;keyword: alpha equality&quot; &quot;keyword: equivariance&quot; &quot;category: Computer Science/Lambda Calculi&quot; ] authors: [ &quot;Abhishek &lt;abhishek.anand.iitg@gmail.com&gt; [http://www.cs.cornell.edu/~aa755/]&quot; &quot;Vincent Rahli &lt;vincent.rahli@gmail.com&gt; [http://www.cs.cornell.edu/~rahli/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/cfgv/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/cfgv.git&quot; synopsis: &quot;Generic Proofs about Alpha Equality and Substitution&quot; description: &quot;&quot;&quot; Please read the following paper&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/cfgv/archive/v8.10.0.tar.gz&quot; checksum: &quot;md5=9376a8527f8b508f6db9faf8c7d0c960&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-cfgv.8.10.0 coq.8.11.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.dev). The following dependencies couldn&#39;t be met: - coq-cfgv -&gt; coq &lt; 8.11~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-cfgv.8.10.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": "3e9727c3d01fd576a147fa383033cd4d", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 159, "avg_line_length": 40.542857142857144, "alnum_prop": 0.5454545454545454, "repo_name": "coq-bench/coq-bench.github.io", "id": "495cc4c815814e5903b6db437d5c25bc49b48162", "size": "7120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/extra-dev/8.11.dev/cfgv/8.10.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var _ = require('lodash'); /* jshint ignore:line */ var Holodeck = require('../../../../../holodeck'); /* jshint ignore:line */ var Request = require( '../../../../../../../lib/http/request'); /* jshint ignore:line */ var Response = require( '../../../../../../../lib/http/response'); /* jshint ignore:line */ var RestException = require( '../../../../../../../lib/base/RestException'); /* jshint ignore:line */ var Twilio = require('../../../../../../../lib'); /* jshint ignore:line */ var client; var holodeck; describe('UserChannel', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'AUTHTOKEN', { httpClient: holodeck }); }); it('should generate valid list request', function() { holodeck.mock(new Response(500, '{}')); var promise = client.chat.v1.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .users('USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .userChannels.list(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(RestException.prototype.constructor); }); promise.done(); var solution = { serviceSid: 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', userSid: 'USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://chat.twilio.com/v1/Services/<%= serviceSid %>/Users/<%= userSid %>/Channels')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid read_full response', function() { var body = JSON.stringify({ 'meta': { 'page': 0, 'page_size': 50, 'first_page_url': 'https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0', 'previous_page_url': null, 'url': 'https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0', 'next_page_url': null, 'key': 'channels' }, 'channels': [ { 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'service_sid': 'ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'channel_sid': 'CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'member_sid': 'MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'status': 'joined', 'last_consumed_message_index': 5, 'unread_messages_count': 5, 'links': { 'channel': 'https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'member': 'https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels/CHaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Members/MBaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' } } ] }); holodeck.mock(new Response(200, body)); var promise = client.chat.v1.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .users('USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .userChannels.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid read_empty response', function() { var body = JSON.stringify({ 'meta': { 'page': 0, 'page_size': 50, 'first_page_url': 'https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0', 'previous_page_url': null, 'url': 'https://chat.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels?PageSize=50&Page=0', 'next_page_url': null, 'key': 'channels' }, 'channels': [] }); holodeck.mock(new Response(200, body)); var promise = client.chat.v1.services('ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .users('USaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .userChannels.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); });
{ "content_hash": "ca378569baa879c0b22f4d398229303b", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 191, "avg_line_length": 37.59090909090909, "alnum_prop": 0.5685207577589682, "repo_name": "wanjunsli/twilio-node", "id": "0aeb5d494c44375e212a212530fa359b62a91574", "size": "4962", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/integration/rest/chat/v1/service/user/userChannel.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "230013" }, { "name": "Makefile", "bytes": "95" } ], "symlink_target": "" }
<?php require_once(realpath(dirname(__FILE__)) . '/../../../../include/view/widgets/FormWidget.php'); /** * @access public * @author Di Pompeo Sacco * @package include.view.widgets.forms */ class longDateField extends FormWidget { public $time, $date, $disabled; /** * @access public * @param v * @param preload * @ParamType v * @ParamType preload */ public function build($preload) { /** * retrieving the field that has the same name of the graphic element that we're creating */ $field_to_modify = $this->form->entity->getField($this->name); if ($preload && $this->form->entity->loaded) { $dateObj =new DateTime($this->form->entity->instances[0]->getFieldValue($this->name)); $date = $dateObj->format("d/m/Y"); $time = $dateObj->format("H:i"); } else { if ($this->mandatory == MANDATORY) { $date = date("d/m/Y"); $time= date("H:i"); } else { $date = ""; $time = ""; } } $widgetSkinlet = new Skinlet("widget/LongDate"); $widgetSkinlet->setContent("widget",$content); $widgetSkinlet->setContent("label", $this->label); $widgetSkinlet->setContent("name", $this->name); $widgetSkinlet->setContent("date", $date); $widgetSkinlet->setContent("time", $time); //$widgetSkinlet->setContent("disabled", $disabled); return $widgetSkinlet->get(); } } /** * Factory for the checkbox widget * @author nicola * */ class LongDateFieldFactory implements FormWidgetFactory { public function create($form) { return new LongDateField($form); } } ?>
{ "content_hash": "c203164f7e12724ab05515ed0f0b6553", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 95, "avg_line_length": 23.424242424242426, "alnum_prop": 0.6332470892626132, "repo_name": "danieledipompeo/vecchiaposta", "id": "daf11833585e221dea28eb180ec88a4cb15d4d4b", "size": "1546", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/include/view/widgets/forms/longDateField.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "564426" }, { "name": "JavaScript", "bytes": "125631" }, { "name": "PHP", "bytes": "1786066" }, { "name": "Perl", "bytes": "3" }, { "name": "Shell", "bytes": "712" }, { "name": "TeX", "bytes": "112512" } ], "symlink_target": "" }
package org.apache.kylin.engine; import org.apache.kylin.cube.CubeSegment; import org.apache.kylin.job.execution.DefaultChainedExecutable; public interface IBatchCubingEngine { /** Build a new cube segment, typically its time range appends to the end of current cube. */ public DefaultChainedExecutable createBatchCubingJob(CubeSegment newSegment, String submitter); /** Merge multiple small segments into a big one. */ public DefaultChainedExecutable createBatchMergeJob(CubeSegment mergeSegment, String submitter); public Class<?> getSourceInterface(); public Class<?> getStorageInterface(); }
{ "content_hash": "91d6ff3fb2cf0b57cf34807a0f32f7da", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 100, "avg_line_length": 33.05263157894737, "alnum_prop": 0.7786624203821656, "repo_name": "haoch/kylin", "id": "556893c745cc0b78e508dea29e6c55cbae7ff14b", "size": "1434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core-job/src/main/java/org/apache/kylin/engine/IBatchCubingEngine.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "4736" }, { "name": "C++", "bytes": "595793" }, { "name": "CSS", "bytes": "134220" }, { "name": "HTML", "bytes": "293311" }, { "name": "Java", "bytes": "5355152" }, { "name": "JavaScript", "bytes": "343978" }, { "name": "Objective-C", "bytes": "27913" }, { "name": "PLSQL", "bytes": "905" }, { "name": "Protocol Buffer", "bytes": "5581" }, { "name": "Shell", "bytes": "43666" } ], "symlink_target": "" }
typedef NS_OPTIONS(NSInteger, BaseDictionaryStorageInitOptions) { initOptionsStorageTypeNSDictionary = 1 << 0, initOptionsStorageTypeNSMapTableWeakToWeak = 1 << 1 }; @interface AIKBaseDictionaryStorage : NSObject #pragma mark - Subscription - (instancetype)initWithOptions:(BaseDictionaryStorageInitOptions)options; - (id)objectForKeyedSubscript:(id <NSCopying>)key; - (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key; #pragma mark - Getters / Setters @property(nonatomic, strong) NSDictionary *items; - (void)setItem:(id)item forKey:(id <NSCopying>)key; - (id)itemForKey:(id <NSCopying>)key; - (void)removeItemForKey:(id <NSCopying>)key; @end
{ "content_hash": "fae848ca6e47d161b7b0cc8f597a039e", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 74, "avg_line_length": 26, "alnum_prop": 0.7662721893491125, "repo_name": "smartairkey/ios-message-based-network", "id": "f0096b115769fcc78a29b143f5e5821aaa7911f2", "size": "862", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iOSMessageBasedNetwork/Helpers/AIKBaseDictionaryStorage.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "80902" }, { "name": "Ruby", "bytes": "212" } ], "symlink_target": "" }
package com.yibh.fourgank.yonionyy.activity; import android.content.Context; import android.content.Intent; import android.support.v4.view.ViewCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.yibh.fourgank.R; import com.yibh.fourgank.utils.ToastSnackUtil; import com.yibh.fourgank.yonionyy.mvp_ganktest.FuliBean; import com.yibh.fourgank.yonionyy.mvp_ganktest.GankAdapter; import com.yibh.fourgank.yonionyy.mvp_ganktest.GankContract; import com.yibh.fourgank.yonionyy.mvp_ganktest.GankPresenter; import java.util.List; import butterknife.BindView; /** * Created by yibh on 2016/9/2 14:06 . */ public class GankTestActivity extends BaseActivity implements GankContract.View { @BindView(R.id.fuli_recy) RecyclerView mRecyclerView; private GankAdapter mGankAdapter; private GankPresenter mGankPresenter; private int currPage = 1; /** * 到本页面 */ public static void startGankTActivity(Context context) { Intent intent = new Intent(context, GankTestActivity.class); context.startActivity(intent); } @Override public int getContentViewId() { return R.layout.activity_gank_test; } @Override protected void initData() { mGankPresenter = new GankPresenter(this); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mGankAdapter = new GankAdapter(); mRecyclerView.setAdapter(mGankAdapter); mGankPresenter.getMeiz(10, currPage); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (!ViewCompat.canScrollVertically(recyclerView, 1)) { mGankPresenter.getMeiz(10, ++currPage); } } }); } @Override public void startLoad() { ToastSnackUtil.snackbarShort(mRecyclerView,"开始加载..."); } @Override public void endLoad() { } @Override public void onError(String errMsg) { ToastSnackUtil.snackbarLong(mRecyclerView, "出现异常,请求数据失败!" + errMsg); } @Override public void load(List<FuliBean.Meiz> meizList) { Log.w("load", "请求成功!"); mGankAdapter.onRefresh(meizList); } }
{ "content_hash": "564b4448d52fd3520a14330f3a502967", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 87, "avg_line_length": 28.25287356321839, "alnum_prop": 0.6903986981285598, "repo_name": "YTestGithub/FourGank", "id": "6e3c811653ec68fe705bd86b0312ce8366802476", "size": "2502", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/yibh/fourgank/yonionyy/activity/GankTestActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "26502" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="com.chariotsolutions.nfc.plugin" version="0.4.7"> <name>NFC</name> <description>Near Field Communication (NFC) Plugin. Read and write NDEF messages to tags or share NDEF messages with peers.</description> <license>MIT</license> <!-- temp remove engines tag due to bug CB-5139 in cli 3.1.0-0.2.0 for blackberry 10 <engines> <engine name="cordova" version=">=2.8.0" /> </engines> --> <js-module src="www/phonegap-nfc.js" name="NFC"> <runs /> </js-module> <platform name="android"> <!-- requires Cordova-2.8.0 --> <config-file target="res/xml/config.xml" parent="/widget"> <feature name="NfcPlugin"> <param name="android-package" value="com.chariotsolutions.nfc.plugin.NfcPlugin"/> </feature> </config-file> <source-file src="src/android/src/com/chariotsolutions/nfc/plugin/NfcPlugin.java" target-dir="src/com/chariotsolutions/nfc/plugin"/> <source-file src="src/android/src/com/chariotsolutions/nfc/plugin/Util.java" target-dir="src/com/chariotsolutions/nfc/plugin"/> <!-- kludge for 2.9 support --> <source-file src="src/android/org/apache/cordova/api/Dummy.java" target-dir="src/org/apache/cordova/api"/> <config-file target="AndroidManifest.xml" parent="/manifest"> <uses-permission android:name="android.permission.NFC"/> <uses-feature android:name="android.hardware.nfc" android:required="false"/> </config-file> </platform> <platform name="wp8"> <config-file target="config.xml" parent="/*"> <feature name="NfcPlugin"> <param name="wp-package" value="NfcPlugin"/> </feature> </config-file> <config-file target="Properties/WMAppManifest.xml" parent="/Deployment/App/Capabilities"> <Capability Name="ID_CAP_PROXIMITY" /> </config-file> <source-file src="src/windows-phone-8/Ndef.cs" /> <source-file src="src/windows-phone-8/NfcPlugin.cs" /> </platform> <platform name="blackberry10"> <!-- why does this need to be repeated? --> <js-module src="www/phonegap-nfc.js" name="NFC"> <runs /> </js-module> <!-- override defaults for BB10 --> <js-module src="www/phonegap-nfc-blackberry.js" name="NFCBB10"> <runs /> </js-module> <!-- "native" implementation --> <source-file src="src/blackberry10/index.js" /> <config-file target="www/config.xml" parent="/widget"> <!-- Note: mapping is broken in Cordova 3.1.0-0.2.0 --> <feature name="NfcPlugin" value="com.chariotsolutions.nfc.plugin" /> </config-file> </platform> </plugin>
{ "content_hash": "7d6735d5b8fb6391f1524adf7cd5be98", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 141, "avg_line_length": 35.151162790697676, "alnum_prop": 0.5931194177968905, "repo_name": "ShowingCloud/Alniyat", "id": "851699e57b9ba5ec88d73016dc02e148eba273b1", "size": "3023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/com.chariotsolutions.nfc.plugin/plugin.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4077" }, { "name": "C#", "bytes": "45021" }, { "name": "C++", "bytes": "868636" }, { "name": "CSS", "bytes": "307396" }, { "name": "D", "bytes": "33898" }, { "name": "Java", "bytes": "1558457" }, { "name": "JavaScript", "bytes": "835414" }, { "name": "Objective-C", "bytes": "228147" }, { "name": "Shell", "bytes": "11313" } ], "symlink_target": "" }
package com.jetbrains.python.psi; /** * @author yole */ public interface PyWithStatement extends PyStatement, NameDefiner { PyWithItem[] getWithItems(); }
{ "content_hash": "2ed7aeb18e0d0632c587dd57f31d110e", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 67, "avg_line_length": 17.88888888888889, "alnum_prop": 0.7391304347826086, "repo_name": "IllusionRom-deprecated/android_platform_tools_idea", "id": "201ae3046785fb045e0df26b19114000b671f884", "size": "761", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "python/psi-api/src/com/jetbrains/python/psi/PyWithStatement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "177802" }, { "name": "C#", "bytes": "390" }, { "name": "C++", "bytes": "78894" }, { "name": "CSS", "bytes": "102018" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "1906667" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "128322265" }, { "name": "JavaScript", "bytes": "123045" }, { "name": "Objective-C", "bytes": "22558" }, { "name": "Perl", "bytes": "6549" }, { "name": "Python", "bytes": "17760420" }, { "name": "Ruby", "bytes": "1213" }, { "name": "Shell", "bytes": "76554" }, { "name": "TeX", "bytes": "60798" }, { "name": "XSLT", "bytes": "113531" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Global rolling_count</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.rolling_count_hpp" title="Header &lt;boost/accumulators/statistics/rolling_count.hpp&gt;"> <link rel="prev" href="../featur_1_3_2_6_3_21_1_1_10.html" title="Struct template feature_of&lt;tag::weighted_pot_tail_mean_prob&lt; LeftRight &gt;&gt;"> <link rel="next" href="../tag/rolling_count.html" title="Struct rolling_count"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../featur_1_3_2_6_3_21_1_1_10.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.rolling_count_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../tag/rolling_count.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.accumulators.extract.rolling_count"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Global rolling_count</span></h2> <p>boost::accumulators::extract::rolling_count</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.rolling_count_hpp" title="Header &lt;boost/accumulators/statistics/rolling_count.hpp&gt;">boost/accumulators/statistics/rolling_count.hpp</a>&gt; </span><a class="link" href="../extractor.html" title="Struct template extractor">extractor</a><span class="special">&lt;</span> <a class="link" href="../tag/rolling_count.html" title="Struct rolling_count">tag::rolling_count</a> <span class="special">&gt;</span> <span class="keyword">const</span> rolling_count<span class="special">;</span></pre></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2005, 2006 Eric Niebler<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../featur_1_3_2_6_3_21_1_1_10.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.statistics.rolling_count_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../tag/rolling_count.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "8073860a16eb834944ca44c6e0b934a1", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 525, "avg_line_length": 85.62, "alnum_prop": 0.6605933193179164, "repo_name": "davehorton/drachtio-server", "id": "20729b8089597da1ecbd787731d207237e9047da", "size": "4282", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "deps/boost_1_77_0/doc/html/boost/accumulators/extract/rolling_count.html", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "662596" }, { "name": "Dockerfile", "bytes": "1330" }, { "name": "JavaScript", "bytes": "60639" }, { "name": "M4", "bytes": "35273" }, { "name": "Makefile", "bytes": "5960" }, { "name": "Shell", "bytes": "47298" } ], "symlink_target": "" }
require 'spec_helper' describe SeasonsController do describe "#index" do before { get :index } it { should respond_with(:success) } end describe "#show" do before do Season.stub(:find).with("200").and_return(double) get :show, id: 200 end it { should respond_with(:success) } end end
{ "content_hash": "f028744042dacbf48d37269ce9b32dc7", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 55, "avg_line_length": 16.5, "alnum_prop": 0.6272727272727273, "repo_name": "squidpunch/bass-bandits", "id": "325b193dd52d6167539000894c5360fb654745ca", "size": "330", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/controllers/seasons_controller_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "618" }, { "name": "CoffeeScript", "bytes": "29" }, { "name": "JavaScript", "bytes": "686" }, { "name": "Ruby", "bytes": "48226" } ], "symlink_target": "" }
<?php /** * Paradox Labs, Inc. * http://www.paradoxlabs.com * 717-431-3330 * * Need help? Open a ticket in our support system: * http://support.paradoxlabs.com * * @author Ryan Hoerr <magento@paradoxlabs.com> * @license http://store.paradoxlabs.com/license.html */ namespace ParadoxLabs\TokenBase\Api\Data; /** * Payment record storage * * @api */ interface CardInterface extends \Magento\Framework\Api\ExtensibleDataInterface { /** * Get ID * * @return int|null */ public function getId(); /** * Set ID * * @param int $cardId * @return CardInterface */ public function setId($cardId); /** * Set the method instance for this card. This is often necessary to route card data properly. * * @param \ParadoxLabs\TokenBase\Api\MethodInterface|\Magento\Payment\Model\MethodInterface $method * @return $this */ public function setMethodInstance($method); /** * Set the customer account (if any) for the card. * * @param \Magento\Customer\Api\Data\CustomerInterface $customer * @param \Magento\Payment\Model\InfoInterface|null $payment * @return $this */ public function setCustomer( \Magento\Customer\Api\Data\CustomerInterface $customer, \Magento\Payment\Model\InfoInterface $payment = null ); /** * Set card payment data from a quote or order payment instance. * * @param \Magento\Payment\Model\InfoInterface $payment * @return $this */ public function importPaymentInfo(\Magento\Payment\Model\InfoInterface $payment); /** * Check whether customer has permission to use/modify this card. * * @param int $customerId * @return bool */ public function hasOwner($customerId); /** * Check if card is connected to any pending orders. * * @return bool */ public function isInUse(); /** * Change last_use date to the current time. * * @return $this */ public function updateLastUse(); /** * Delete this card, or hide and queue for deletion after the refund period. * * @return $this */ public function queueDeletion(); /** * Get additional card data. * If $key is set, will return that value or null; * otherwise, will return an array of all additional date. * * @param string|null $key * @return mixed|null */ public function getAdditional($key = null); /** * Set additional card data. * Can pass in a key-value pair to set one value, * or a single parameter (associative array or CardAdditional instance) to overwrite all data. * * @param string|array|\ParadoxLabs\TokenBase\Api\Data\CardAdditionalInterface $key * @param string|null $value * @return $this */ public function setAdditional($key, $value = null); /** * Get additional card data, in object form. Used to expose keys to API. * * @return \ParadoxLabs\TokenBase\Api\Data\CardAdditionalInterface */ public function getAdditionalObject(); /** * Get billing address or some part thereof. * * @param string $key * @return mixed|null */ public function getAddress($key = ''); /** * Set the billing address for the card. * * @param \Magento\Customer\Api\Data\AddressInterface $address * @return $this */ public function setAddress(\Magento\Customer\Api\Data\AddressInterface $address); /** * Return a customer address object containing the card address data. * * @return \Magento\Customer\Api\Data\AddressInterface */ public function getAddressObject(); /** * Get customer email * * @return string */ public function getCustomerEmail(); /** * Set customer email * * @param string $email * @return $this */ public function setCustomerEmail($email); /** * Get customer id * * @return int */ public function getCustomerId(); /** * Set customer id * * @param int $id * @return $this */ public function setCustomerId($id); /** * Get customer ip * * @return string */ public function getCustomerIp(); /** * Set customer ip * * @param string $ip * @return $this */ public function setCustomerIp($ip); /** * Get profile id * * @return string */ public function getProfileId(); /** * Set profile id * * @param string $profileId * @return $this */ public function setProfileId($profileId); /** * Get payment id * * @return string */ public function getPaymentId(); /** * Set payment id * * @param string $paymentId * @return $this */ public function setPaymentId($paymentId); /** * Get method code * * @return string */ public function getMethod(); /** * Set method code * * @param string $method * @return $this */ public function setMethod($method); /** * Get hash, generate if necessary * * @return string */ public function getHash(); /** * Set hash * * @param string $hash * @return $this */ public function setHash($hash); /** * Get active * * @return string */ public function getActive(); /** * Set active * * @param int|bool $active * @return $this */ public function setActive($active); /** * Get created at date * * @return string */ public function getCreatedAt(); /** * Set created at date * * @param $createdAt * @return $this */ public function setCreatedAt($createdAt); /** * Get updated at date * * @return string */ public function getUpdatedAt(); /** * Set updated at date * * @param $updatedAt * @return $this */ public function setUpdatedAt($updatedAt); /** * Get last use date * * @return string */ public function getLastUse(); /** * Set last use date * * @param $lastUse * @return $this */ public function setLastUse($lastUse); /** * Get expires * * @return string */ public function getExpires(); /** * Set expires * * @param string $expires * @return $this */ public function setExpires($expires); /** * Set payment info instance * * @param \Magento\Payment\Model\InfoInterface $payment * @return $this */ public function setInfoInstance(\Magento\Payment\Model\InfoInterface $payment); /** * Get card label (formatted number). * * @param bool $includeType * @return string|\Magento\Framework\Phrase */ public function getLabel($includeType = true); /** * Retrieve existing extension attributes object or create a new one. * * @return \ParadoxLabs\TokenBase\Api\Data\CardExtensionInterface|null */ public function getExtensionAttributes(); /** * Set an extension attributes object. * * @param \ParadoxLabs\TokenBase\Api\Data\CardExtensionInterface $extensionAttributes * @return $this */ public function setExtensionAttributes(\ParadoxLabs\TokenBase\Api\Data\CardExtensionInterface $extensionAttributes); }
{ "content_hash": "143d3be488efc52b64b16a9d4d08b410", "timestamp": "", "source": "github", "line_count": 355, "max_line_length": 120, "avg_line_length": 21.428169014084506, "alnum_prop": 0.5843302221637965, "repo_name": "letunhatkong/tradebanner", "id": "3f28b29f653e631571f0ecae8d86d55bd0af69e5", "size": "7607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/code/ParadoxLabs/TokenBase/Api/Data/CardInterface.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "158924" }, { "name": "HTML", "bytes": "956313" }, { "name": "JavaScript", "bytes": "221669" }, { "name": "PHP", "bytes": "2473541" } ], "symlink_target": "" }
from __future__ import annotations from unittest import mock from airflow.callbacks.callback_requests import CallbackRequest from airflow.configuration import conf from airflow.executors.local_executor import LocalExecutor from airflow.executors.local_kubernetes_executor import LocalKubernetesExecutor class TestLocalKubernetesExecutor: def test_queued_tasks(self): local_executor_mock = mock.MagicMock() k8s_executor_mock = mock.MagicMock() local_kubernetes_executor = LocalKubernetesExecutor(local_executor_mock, k8s_executor_mock) local_queued_tasks = {("dag_id", "task_id", "2020-08-30", 1): "queued_command"} k8s_queued_tasks = {("dag_id_2", "task_id_2", "2020-08-30", 2): "queued_command"} local_executor_mock.queued_tasks = local_queued_tasks k8s_executor_mock.queued_tasks = k8s_queued_tasks expected_queued_tasks = {**local_queued_tasks, **k8s_queued_tasks} assert local_kubernetes_executor.queued_tasks == expected_queued_tasks assert len(local_kubernetes_executor.queued_tasks) == 2 def test_running(self): local_executor_mock = mock.MagicMock() k8s_executor_mock = mock.MagicMock() local_kubernetes_executor = LocalKubernetesExecutor(local_executor_mock, k8s_executor_mock) local_running_tasks = {("dag_id", "task_id", "2020-08-30", 1)} k8s_running_tasks = {} local_executor_mock.running = local_running_tasks k8s_executor_mock.running = k8s_running_tasks assert local_kubernetes_executor.running == local_running_tasks.union(k8s_running_tasks) assert len(local_kubernetes_executor.running) == 1 def test_slots_available(self): local_executor = LocalExecutor() k8s_executor_mock = mock.MagicMock() local_kubernetes_executor = LocalKubernetesExecutor(local_executor, k8s_executor_mock) # Should be equal to Local Executor default parallelism. assert local_kubernetes_executor.slots_available == conf.getint("core", "PARALLELISM") def test_kubernetes_executor_knows_its_queue(self): local_executor_mock = mock.MagicMock() k8s_executor_mock = mock.MagicMock() LocalKubernetesExecutor(local_executor_mock, k8s_executor_mock) assert k8s_executor_mock.kubernetes_queue == conf.get("local_kubernetes_executor", "kubernetes_queue") def test_send_callback(self): local_executor_mock = mock.MagicMock() k8s_executor_mock = mock.MagicMock() local_k8s_exec = LocalKubernetesExecutor(local_executor_mock, k8s_executor_mock) local_k8s_exec.callback_sink = mock.MagicMock() callback = CallbackRequest(full_filepath="fake") local_k8s_exec.send_callback(callback) local_k8s_exec.callback_sink.send.assert_called_once_with(callback)
{ "content_hash": "af315e06625bb47690858abf608a48b3", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 110, "avg_line_length": 43.13636363636363, "alnum_prop": 0.7024938531787847, "repo_name": "apache/airflow", "id": "4fc3ff07aea2ebfc9013f972ce4f50839909cf65", "size": "3634", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "tests/executors/test_local_kubernetes_executor.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "25980" }, { "name": "Dockerfile", "bytes": "71458" }, { "name": "HCL", "bytes": "3786" }, { "name": "HTML", "bytes": "172957" }, { "name": "JavaScript", "bytes": "143915" }, { "name": "Jinja", "bytes": "38911" }, { "name": "Jupyter Notebook", "bytes": "5482" }, { "name": "Mako", "bytes": "1339" }, { "name": "Python", "bytes": "23697738" }, { "name": "R", "bytes": "313" }, { "name": "Shell", "bytes": "211306" }, { "name": "TypeScript", "bytes": "521019" } ], "symlink_target": "" }
<!doctype html> <meta charset="utf-8" /> <title>Paragraphs</title> <p id="first"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. </p> <p id="second"> Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. </p> <p id="third"> Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. </p>
{ "content_hash": "5cbc0756894dd2828ee702430c89cc87", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 165, "avg_line_length": 37.46666666666667, "alnum_prop": 0.7402135231316725, "repo_name": "operasoftware/operawatir", "id": "02fadb204d7e23fde11e581de952ef740e16fbb5", "size": "562", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/operawatir/fixtures/paragraphs.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "356" }, { "name": "Ruby", "bytes": "614859" } ], "symlink_target": "" }
namespace Loon.Action.Sprite.Painting { using Loon.Core; using Loon.Core.Geom; using Loon.Core.Input; using Loon.Core.Timer; using Loon.Utils; public abstract class Drawable : LRelease { public bool IsPopup = false; public float transitionOnTime = 0; public float transitionOffTime = 0; public Vector2f bottomLeftPosition = new Vector2f(); public DrawableScreen drawableScreen; internal bool otherScreenHasFocus; protected internal float _transitionPosition = 1f; protected internal DrawableState _drawableState = Painting.DrawableState.TransitionOn; protected internal bool _enabled = true; protected internal bool _isExiting = false; public DrawableScreen GetDrawableScreen() { return drawableScreen; } public void ExitScreen() { if (this.transitionOffTime == 0f) { this.drawableScreen.RemoveDrawable(this); } else { this._isExiting = true; } } public Vector2f GetBottomLeftPosition() { return bottomLeftPosition; } public DrawableState GetDrawableState() { return _drawableState; } public void SetDrawableState(DrawableState state) { _drawableState = state; } public float GetTransitionAlpha() { return (1f - this._transitionPosition); } public float GetTransitionPosition() { return _transitionPosition; } public abstract void HandleInput(LInput input); public bool IsActive() { return !otherScreenHasFocus && (_drawableState == Painting.DrawableState.TransitionOn || _drawableState == Painting.DrawableState.Active); } public bool IsExiting() { return _isExiting; } public abstract void LoadContent(); public abstract void UnloadContent(); public abstract void Draw(SpriteBatch batch, GameTime elapsedTime); public abstract void Update(GameTime elapsedTime); public void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { this.otherScreenHasFocus = otherScreenHasFocus; if (this._isExiting) { this._drawableState = Painting.DrawableState.TransitionOff; if (!this.UpdateTransition(gameTime, this.transitionOffTime, 1)) { this.drawableScreen.RemoveDrawable(this); } } else if (coveredByOtherScreen) { if (this.UpdateTransition(gameTime, this.transitionOffTime, 1)) { this._drawableState = Painting.DrawableState.TransitionOff; } else { this._drawableState = Painting.DrawableState.Hidden; } } else if (this.UpdateTransition(gameTime, this.transitionOnTime, -1)) { this._drawableState = Painting.DrawableState.TransitionOn; } else { this._drawableState = Painting.DrawableState.Active; } Update(gameTime); } private bool UpdateTransition(GameTime gameTime, float time, int direction) { float num; if (time == 0f) { num = 1f; } else { num = (gameTime.GetElapsedGameTime() / time); } this._transitionPosition += num * direction; if (((direction < 0) && (this._transitionPosition <= 0f)) || ((direction > 0) && (this._transitionPosition >= 1f))) { this._transitionPosition = MathUtils.Clamp( this._transitionPosition, 0f, 1f); return false; } return true; } public abstract void Pressed(LTouch e); public abstract void Released(LTouch e); public abstract void Move(LTouch e); public abstract void Pressed(LKey e); public abstract void Released(LKey e); public bool IsEnabled() { return _enabled; } public void SetEnabled(bool e) { this._enabled = e; } public void Dispose() { this._enabled = false; } } }
{ "content_hash": "99ce373bdaed30ef1f241d2b08cdb09b", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 115, "avg_line_length": 24.726027397260275, "alnum_prop": 0.6972299168975069, "repo_name": "cping/LGame", "id": "f06b58c1afe09bc5cd50eab7b8812afe949e66c5", "size": "3610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "C#/WindowsPhone/LGame-XNA-lib/Loon.Action.Sprite.Painting/Drawable.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1472" }, { "name": "C", "bytes": "3901" }, { "name": "C#", "bytes": "3682953" }, { "name": "C++", "bytes": "24221" }, { "name": "CSS", "bytes": "115312" }, { "name": "HTML", "bytes": "1782" }, { "name": "Java", "bytes": "26857190" }, { "name": "JavaScript", "bytes": "177232" }, { "name": "Shell", "bytes": "236" } ], "symlink_target": "" }
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.funkierJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ module.exports = (function() { "use strict"; var curryModule = require('./curry'); var curry = curryModule.curry; var curryWithArity = curryModule.curryWithArity; var arityOf = curryModule.arityOf; var chooseCurryStyle = curryModule._chooseCurryStyle; var curryWithConsistentStyle = curryModule._curryWithConsistentStyle; var funcUtils = require('../funcUtils'); var checkFunction = funcUtils.checkFunction; var internalUtilities = require('../internalUtilities'); var checkPositiveIntegral = internalUtilities.checkPositiveIntegral; var isArrayLike = internalUtilities.isArrayLike; /* * <apifunction> * * compose * * Category: function * * Parameter: f: function * Parameter: g: function * Returns: function * * Composes the two functions, returning a new function that consumes one argument, which is passed to `g`. The result * of that call is then passed to `f`. That result is then returned. Throws if either parameter is not a function, or * has arity 0. * * The functions will be curried (using the standard [`curry`](#curry) if required. The resulting function will have * real arity of `arityOf(f)`. Note in particular, that if `g` has arity 1, it will be partially applied with 1 * argument: `f` will recieve a partially applied `g`, and any remaining arguments. * * If `g` was curried by one of the [`objectCurry`] variants, then the returned function will be too, and it will * supply `g` with the context the first time it is invoked. If `g` was curried by [`bind`], then the returned function * will also be considered as having been curried that way, with the correct bound context. * * Examples: * * var f1 = function(a) {return a + 1;}; * var f2 = function(b) {return b * 2;}; * var f = funkierJS.compose(f1, f2); // => f(x) = 2(x + 1)', * */ var compose = curry(function(f, g) { var gLen = arityOf(g); var fLen = arityOf(f); f = checkFunction(f, {arity: 1, minimum: true, message: 'function f must have arity ≥ 1'}); g = checkFunction(g, {arity: 1, minimum: true, message: 'function g must have arity ≥ 1'}); f = arityOf._isCurried(f) ? f : curry(f); g = arityOf._isCurried(g) ? g : curry(g); var curryTo = fLen; return chooseCurryStyle(f, g, function(x) { var args = [].slice.call(arguments); var gArgs = [args[0]]; var fArgs = args.slice(1); return f.apply(this, [g.apply(this, [args[0]])].concat(fArgs)); }, curryTo); }); /* * <apifunction> * * composeOn * * Category: function * * Parameter: argCount: positive * Parameter: f: function * Parameter: g: function * Returns: function * * Composes the two functions, returning a new function that consumes the specified number of arguments, which are * then passed to `g`. The result of that call is then passed to `f`. That result is then returned. Throws if the * first parameter is not an integer greater than zero, if either parameter is not a function, or if either parameter * has arity 0. * * The functions will be curried (using the standard [`curry`](#curry) if required. The resulting function will have * real arity of `arityOf(f)`. Note in particular, that if `g` has arity 1, it will be partially applied with 1 * argument: `f` will recieve a partially applied `g`, and any remaining arguments. * * If `g` was curried by one of the [`objectCurry`] variants, then the returned function will be too, and it will * supply `g` with the context the first time it is invoked. If `g` was curried by [`bind`], then the returned function * will also be considered as having been curried that way, with the correct bound context. * * This function is intended to afford an approximation of writing functions in a point-free style. * * Examples: * var f1 = function(a) {return a(2);}; * var f2 = function(c, d, e) {return c * d * e;}; * var f = funkierJS.composeOn(f1, f2); // => f(x, y) = 2(x * y); * */ var composeOn = curry(function(argCount, f, g) { argCount = checkPositiveIntegral(argCount, {errorMessage: 'argCount must be non-negative'}); f = checkFunction(f, {arity: 1, minimum: true, message: 'function f must have arity ≥ 1'}); g = checkFunction(g, {arity: argCount, minimum: true, message: 'function g must have arity ≥ ' + argCount}); f = arityOf._isCurried(f) ? f : curry(f); g = arityOf._isCurried(g) ? g : curry(g); var fLen = arityOf(f); var curryArity = fLen - 1 + argCount; return chooseCurryStyle(f, g, function() { var args = [].slice.call(arguments); var gArgs = args.slice(0, argCount); var fArgs = args.slice(argCount); return f.apply(this, [g.apply(this, gArgs)].concat(fArgs)); }, curryArity); }); /* * <apifunction> * * id * * Category: types * * Parameter: a: any * Returns: any * * Returns the supplied value. Superfluous values are ignored. * * Examples: * funkierJS.id([1, 2]); // => [1, 2] * */ var id = curry(function(x) { return x; }); /* * <apifunction> * * constant * * Category: function * * Parameter: a: any * Parameter: b: any * Returns: any * * Intended to be partially applied, first taking a value, returning a function that takes another parameter * and which always returns the first value. * * Examples: * var f = funkierJS.constant(42); * f(10); // => 42 * */ var constant = curry(function(x, y) { return x; }); /* * <apifunction> * * constant0 * * Category: function * * Parameter: a: any * Returns: function * * Returns a function of arity zero that when called always returns the supplied value. * * Examples: * var f = funkierJS.constant0(42); * f(); // => 42 * */ var constant0 = compose(curryWithArity(0), constant); /* * <apifunction> * * flip * * Category: function * * Parameter: f: function * Returns: function * * Takes a binary function f, and returns a curried function that takes the arguments in the opposite order. * * Examples: * var backwards = funkierJS.flip(funkierJS.subtract); * backwards(2, 3); // => 1 * */ var flip = curry(function(f) { f = checkFunction(f, {arity: 2, maximum: true, message: 'Value to be flipped must be a function of arity 2'}); f = arityOf._isCurried(f) ? f : curry(f); if (arityOf(f) < 2) return f; return curryWithConsistentStyle(f, function(a, b) { return f(b, a); }); }); /* * <apifunction> * * composeMany * * Category: types * * Parameter: fns: array * Returns: function * * Repeatedly composes the given array of functions, from right to left. All functions are curried where necessary. * Functions are curried from right to left. Throws an Error if any array member is not a function, if it has arity * zero, or if the value supplied is not an array. * * The result of calling composeMany([f1, f2, f3](x) is equal to f1(f2(f3(x))). * * Examples: * var square = function(x) {return x * x;}; * var double = function(x) {return 2 * x;}; * var plusOne = funkierJS.plus(1); * var f = funkierJS.composeMany([square, double, plusOne]); * f(2); // => 36 * */ var composeMany = curry(function(fnArray) { if (!isArrayLike(fnArray, true)) throw new TypeError('composeMany requires an array or array-like object of functions'); if (fnArray.length === 0) throw new TypeError('composeMany called with empty array'); // We need to explicitly check the arity for the last function, as reduceRight won't trigger compose if the // array has length 1 if (arityOf(fnArray[fnArray.length - 1]) === 0) throw new TypeError('Cannot compose functions of arity 0'); if (fnArray.length === 1) return curry(fnArray[0]); // We don't use our foldr to avoid creating a circular dependency return fnArray.reduceRight(flip(compose)); }); /* * <apifunction> * * sectionLeft * * Category: function * * Parameter: f: function * Parameter: x: any * Returns: function * * Partially applies the binary function f with the given argument x, with x being supplied as the first argument * to f. The given function f will be curried if necessary. Throws if f is not a binary function. * * Examples: * var f = function(x, y) {return x * y;};', * var g = funkierJS.sectionLeft(f, 2); * g(3); // => 6 (i.e. 2 * 3)', * */ var sectionLeft = curry(function(f, x) { f = checkFunction(f, {arity: 2, message: 'Value to be sectioned must be a function of arity 2'}); if (arityOf._isCurried(f)) return f.call(this, x); f = curry(f); return f(x); }); /* * <apifunction> * * sectionRight * * Category: function * * Parameter: f: function * Parameter: x: any * Returns: function * * Partially applies the binary function f with the given argument x, with x being supplied as the second argument * to f. The given function f will be curried if necessary. Throws if f is not a binary function. * * Examples: * var fn = funkierJS.sectionRight(funkierJS.subtract, 3); * fn(2); // => -1 * */ var sectionRight = curry(function(f, x) { f = checkFunction(f, {arity: 2, message: 'Value to be sectioned must be a function of arity 2'}); return sectionLeft(flip(f), x); }); return { compose: compose, composeMany: composeMany, composeOn: composeOn, constant: constant, constant0: constant0, flip: flip, id: id, sectionLeft: sectionLeft, sectionRight: sectionRight }; })(); },{"../funcUtils":9,"../internalUtilities":12,"./curry":2}],2:[function(require,module,exports){ module.exports = (function () { "use strict"; var checkPositiveIntegral = require('../internalUtilities').checkPositiveIntegral; // Property that will be installed on all curried functions reflecting 'real' arity. var arityProp = '_trueArity'; // Property that will be installed on curried functions that have not been partially applied var uncurriedProp = '_getOriginal'; // Property that records the context with which the function was curried var contextProp = '_context'; /* * Ostensibly an internal helper function to detect whether or not a function is curried. It does however, have to * be installed as a property of arityOf, as some of the auto-generated tests require it. * */ var isCurried = function(f) { return f.hasOwnProperty(arityProp); }; var decorate = function(f, arity, original, context) { var define = function(p, v) { Object.defineProperty(f, p, {value: v}); }; define(arityProp, arity); define(uncurriedProp, original); define(contextProp, context); return f; }; var curryInternal = function(initialContext, length, fn) { length = checkPositiveIntegral(length, {strict: true}); // We can't use checkFunction from the funcUtils module here: it depends on the base module, which in turn depends on // this module if (typeof(fn) !== 'function') throw new TypeError('Value to be curried is not a function'); // Check function hasn't already been curried using a different mechanism var context = fn.hasOwnProperty(contextProp) ? fn[contextProp] : initialContext; if (context !== initialContext) throw new Error('Cannot bind a curried function to a different execution context'); if (fn.hasOwnProperty(arityProp) && fn[arityProp] === length) return fn; fn = fn.hasOwnProperty(uncurriedProp) ? fn[uncurriedProp] : fn; // Handle the special case of length 0 if (length === 0) { return decorate(function() { // We need to use a fresh variable for the context rather than reusing context, or later object curried // functions will have the wrong context due to lexical scoping var callContext = context; // Acquire context if objectCurried if (callContext === undefined) { if (this === undefined) throw new Error('Object curried function called without a context'); callContext = this; } // Don't simply return fn: need to discard any arguments return fn.apply(callContext); }, 0, fn, initialContext); } // Note: 'a' is a dummy parameter to force the length property to be 1 return decorate(function(a) { var args = [].slice.call(arguments); var callContext = context; // Throw if we expected arguments and didn't receive any if (args.length === 0) { var errText = length === 1 ? '1 argument' : ('1 - ' + length + ' arguments'); throw new Error('This function requires ' + errText); } // If we have more arguments than we need, drop the extra ones on the floor // (the function will be called when we fall through to the next conditional) if (args.length > length) args = args.slice(0, length); // Acquire context if object-curried if (callContext === undefined) { if (this === undefined) throw new Error('Object curried function called without a context'); callContext = this; } // If we have enough arguments, call the underlying function if (args.length === length) return fn.apply(callContext, args); // We don't have enough arguments. Bind those that we already have var newFn = fn.bind.apply(fn, [callContext].concat(args)); var argsNeeded = length - args.length; // Continue currying if we can't yet return a function of length 1 if (argsNeeded > 1) return curryInternal({context: callContext}, argsNeeded, newFn); return decorate(function(b) { return newFn(b); }, 1, newFn, callContext); }, length, fn, context); }; /* * <apifunction> * * curryWithArity * * Category: function * * Parameter: n: strictNatural * Parameter: f: function * Returns: function * * Curries the given function f to the supplied arity, which need not equal the function's length. The function will * be called when that number of arguments have been supplied. Superfluous arguments are discarded. The original * function will be called with a null execution context. It is possible to partially apply the resulting function, * and indeed the further resulting function(s). The resulting function and its partial applications will throw if * they require at least one argument, but are invoked without any. `curryWithArity` throws if the arity is not a * natural number, or if the second parameter is not a function. It will also throw if the given function is known * to be bound to a specific execution context. * * The returned function will have a length of 1, unless an arity of 0 was requested, in which case this will be the * length. The [arityOf](#arityOf) function can be used to determine how many arguments are required before the * wrapped function will be invoked. * * As noted above, you are permitted to curry a function to a smaller arity than its length. Whether the resulting * function behaves in a useful manner will of course depend on the function. One use case of `curryWithArity` is * to create unique functions from functions that accept optional arguments. For example, one common error involves * mapping over an array with `parseInt`, which has an optional *radix* parameter. `Array.prototype.map` invokes * the mapping function with additional metadata such as the position of the current element; when these factors * collide, one ends up trying to convert to numbers whose radix equals the array index. Instead, one could use * `curryWithArity` with an arity of 1 to create a new function that guarantees `parseInt` will be called with only * one argument. * * It is possible to recurry functions that have been previously curried with [`curry`](#curry) or `curryWithArity`, * however generally it only makes sense to recurry a function that has not been partially applied: this will be * equivalent to currying the original function. Recurrying a partially applied function will likely not work as you * expect: the new function will be one that requires the given number of arguments before calling the original * function with the partially applied arguments and some of the ones supplied to the recurried function. * * You cannot however pass in functions that have been bound to a specific execution context using [`bind`](#bind), * or [`bindWithContextAndArity`](#bindWithContextAndArity): `curryWithArity` promises to invoke functions with a null * execution context, but those functions have a fixed execution context that cannot be overridden. For similar * reasons, functions curried with [`objectCurry`](#objectCurry) or [`objectCurryWithArity`](#objectCurryWithArity) * cannot be curried. An error is thrown if the function has been bound to an execution context in this way. * * Note however that funkierJS has no visibility into the execution contexts of functions bound using the native * function `bind` method. Attempting to curry these might lead to surprising results, and should be avoided. * * Examples: * var f = function(x, y) { console.log(x, y); } * * var g = funkierJS.curryWithArity(1, f); * * g(7); // => 1, undefined logged * * var h = funkierJS.curryWithArity(3, f); * * var j = h(2, 'a'); * * j(9); // => 2, 'a' logged * * h('fizz')('buzz', 'foo') // => 'fizz', 'buzz' logged * */ // TODO: More realistic examples required // TODO: The paragraph about not recurrying partially applied functions is not particularly clear // XXX Comment on the fact that we provide parseInt var curryWithArity = curryInternal.bind(null, null); /* * <apifunction> * * curry * * Category: function * * Parameter: f: function * Returns: function * * Curries the given function f, returning a function which accepts the same number of arguments as the original * function's length property, but which may be partially applied. The function can be partially applied by passing * arguments one at a time, or by passing several arguments at once. The function can also be called with more * arguments than the given function's length, but the superfluous arguments will be ignored, and will not be * passed to the original function. If the curried function or any subsequent partial applications require at least * one argument, then calling the function with no arguments will throw. `curry` throws if its argument is not a * function. It will also throw if the function is known to be bound to a specific execution context. * * Currying a function that has already been curried will return the exact same function, unless the function was * curried with a different mechanism - see below. * * The returned function will have a length of 1, unless the original function will have length 0, in which case * the result also has length 0. Note that when currying functions of length 0 and 1 that the results will be * different functions from those passed in. * * If you need a function which accepts an argument count that differs from the function's length property, * use `curryWithArity`. * * Note that you cannot pass in functions that have been bound to a specific execution context using [`bind`](#bind), * or [`bindWithContextAndArity`](#bindWithContextAndArity): allowing those would break the invariant that functions * curried with `curry` are invoked with a null execution context. Similarly, functions curried with * [`objectCurry`](#objectCurry) and [`objectCurryWithArity`](#objectCurryWithArity) cannot be recurried through * `curryWithArity`. Thus an error is thrown in such cases. (However, funkierJS cannot tell if a function has been * bound with the native `bind` method. Currying such functions might lead to unexpected results). * * Examples: * var f = function(x, y, z) { console.log(x, y, z); } * * var g = funkierJS.curry(f); * * g(4); // => a function awaiting two arguments * * g(4)(2); // => a function awaiting one argument * * g(4)(2)('z'); // => 4, 2, 'z' logged * * g('a', 'b')('c'); // => 'a', 'b' 'c' logged * * g('x')('y', 'z'); // => 'x', 'y' 'z' logged * * g('d', 'e', 'f'); // => 'd', 'e' 'f' logged * * funkierJS.curry(g) === g; // => true * */ // TODO: More realistic examples required var curry = function(fn) { var desiredLength = fn.hasOwnProperty(arityProp) ? fn[arityProp] : fn.length; return curryWithArity(desiredLength, fn); }; // Now that curry is defined, we can use it to curry itself curry = curry(curry); // curryWithArity should also be curried curryWithArity = curry(curryWithArity); /* * <apifunction> * * arityOf * * Category: function * * Synonyms: arity * Parameter: f: function * Returns: number * * Reports the real arity of a function. If the function has not been curried by funkier.js, this simply returns the * function's length property. For a function that has been curried, the arity of the original function will be * reported (the function's length property will always be 0 or 1 in this case). For a partially applied function, * the amount of arguments not yet supplied will be returned. * * Examples: * funkierJS.arityOf(function(x) {}); // => 1; * */ var arityOf = curry(function(f) { if (typeof(f) !== 'function') throw new TypeError('Cannot compute arity of non-function'); return f.hasOwnProperty(arityProp) ? f[arityProp] : f.length; }); arityOf._isCurried = isCurried; /* * <apifunction> * * bind * * Category: function * * Synonyms: bindWithContext * * Parameter: ctx: objectlike * Parameter: f: function * Returns: function * * Given an object and function, returns a curried function with the same arity as the original, and whose execution * context is permanently bound to the supplied object. The function will be called when sufficient arguments have * been supplied. Superfluous arguments are discarded. It is possible to partially apply the resulting function, and * indeed the further resulting function(s). The resulting function and its partial applications will throw if they * require at least one argument, but are invoked without any. `bind` throws if the first parameter is not an * an acceptable type for an execution context, or if the last parameter is not a function. * * The returned function will have a length of 1, unless an arity of 0 was requested, in which case this will be the * length. The [`arityOf`](#arityOf) function can be used to determine how many arguments are required before the * wrapped function will be invoked. * * `bind` will accept functions that have been previously been curried to the same execution context, as that being * provided, but will effectively be an identity function in such cases. However, attempting to curry a function * known to be bound to a different execution context is an error. In particular, functions curried * with [`curry`](#curry) or [`curryWithArity`](#curryWithArity) cannot be curried with an execution context: they * have already been bound with an implicit `null` execution context. Equally, functions curried with * [`objectCurry`](#objectCurry) and [`objectCurryWithArity`](#objectCurryWithArity) cannot be passed to `bind`, due * to the different way in which they acquire an execution context. `bind` will throw in such cases. * * Unfortunately, funkierJS has no visibility into functions bound with the native `bind` method; attempting to * curry such functions won't throw, but they will not work as expected. * * Examples: * var obj = {foo: 42}; * * var f = function(x, y) { return this.foo + x; }; * * var g = funkierJS.bind(obj, f); * * g(3)(2); // returns 45 * * g(5, 2); // returns 47 * * var obj2 = {foo: 10}; * var h = funkierJS.bindWithContextAndArity(3, obj2, f); * var j = funkierJS.bind(obj2, h); // OK, same context object * * var err = funkierJS.bind({foo: 1}, g); // throws: execution contexts don't match * */ var bind = curry(function(context, fn) { var desiredLength = fn.hasOwnProperty(arityProp) ? fn[arityProp] : fn.length; return bindWithContextAndArity(desiredLength, context, fn); }); /* * <apifunction> * * bindWithContextAndArity * * Category: function * * Parameter: n: strictNatural * Parameter: ctx: objectlike * Parameter: f: function * Returns: function * * Given an arity, object and function, returns a curried function whose execution context is permanently bound to * the supplied object, and whose arity equals the arity given. The supplied arity need not equal the function's * length. The function will be only called when the specified number of arguments have been supplied. Superfluous * arguments are discarded. It is possible to partially apply the resulting function, and indeed the further * resulting function(s). The resulting function and its partial applications will throw if they require at least * one argument, but are invoked without any. `bindWithContextAndArity` throws if the arity is not a natural * number, if the second parameter is not an acceptable type for an execution context, or if the last parameter is * not a function. * * The returned function will have a length of 1, unless an arity of 0 was requested, in which case this will be the * length. The [`arityOf`](#arityOf) function can be used to determine how many arguments are required before the * wrapped function will be invoked. * * As noted above, you are permitted to curry a function to a smaller arity than its length. Whether the resulting * function behaves in a useful manner will of course depend on the function. * * In some limited circumstances, it is possible to recurry previously curried functions, however generally it only * makes sense to recurry a function that has not been partially applied: this will be equivalent to currying the * original function. To be able to recurry a curried function to a different arity, the execution context given * must be the exact object that was previously used to create the function being recurried. It is an error to * try and recurry a curried function bound to one execution context to another. In particular, functions curried * with [`curry`](#curry) or [`curryWithArity`](#curryWithArity) cannot be curried with an execution context: they * have already been bound with an implicit `null` execution context. Likewise, functions that have been curried * using either [`objectCurry`](#objectCurry) or [`objectCurryWithArity`](#objectCurryWithArity) cannot be curried * using `bindWithContextAndArity`, due to the different mechanism they use to acquire an execution context. * `bindWithContextAndArity` will throw in that such cases. * * Unfortunately, funkierJS has no visibility into functions bound with the native `bind` method; attempting to * curry such functions won't throw, but they will not work as expected. * * Examples: * var obj = {foo: 42}; * * var f = function(x, y) { return this.foo + x; }; * * var g = funkierJS.bindWithContextAndArity(1, obj, f); * * g(3); // returns 45 * * var h = funkierJS.bindWithContextAndArity(3, obj, g); // OK, same context object * h(2)(3, 4); // returns 44 * * var err = funkierJS.bindWithContextAndArity(2, {foo: 1}, g); // throws: execution contexts don't match * * var ok = funkierJS.bindWithContextAndArity(2, {foo: 1}, f); // still ok to bind the original function though * */ var bindWithContextAndArity = curry(function(arity, context, fn) { return curryInternal(context, arity, fn); }); /* * <apifunction> * * objectCurry * * Category: function * * Parameter: f: function * Returns: function * * Given a function, returns a curried function which calls the underlying with the execution context active when the * first arguments are supplied. This means that when partially applying the function, the resulting functions will * have their execution context permanently bound. This method of binding is designed for currying functions that * exist on an object's prototype. The function will be only called when sufficient arguments have been supplied. * Superfluous arguments are discarded. The resulting function and its partial applications will throw if they * require at least one argument, but are invoked without any. `objectCurry` throws if its parameter is not a * function. The resulting function will throw if invoked with an undefined execution context. * * The returned function will have a length of 1, unless a function of arity of 0 was supplied, in which case this * will be the length. The [`arityOf`](#arityOf) function can be used to determine how many arguments are required * before the wrapped function will be invoked. * * One can pass in a function created by `objectCurry` or [`objectCurryWithArity`](#objectCurryWithArity) providing * it has not been partially applied. This will effectively be an identity operation. However, passing in a partially * applied function derived from an earlier currying call is an error, as the execution context has now been bound. * Similarly, functions returned from [`curry`](#curry), [`curryWithArity`](#curryWithArity), [`bind`](#bind) and * [`bindWithContextAndArity`](#bindWithContextAndArity) cannot be curried with this function, and will throw an * error, just as those functions curry functions and their partial applications returned from `objectCurry`. * `objectCurry` will throw when provided with an invalid function. * * Unfortunately, funkierJS has no visibility into functions bound with the native `bind` method; attempting to * curry such functions won't throw, but they will not work as expected. * * Examples: * * var proto = {foo: function(x, y) { return x + y + this.bar; }}; * proto.foo = funkierJS.objectCurry(proto.foo); * * var obj1 = Object.create(proto); * obj1.bar = 10; * * var g = obj1.foo(10); * g(22); // => 42 * * var obj2 = Object.create(proto); * obj2.bar = 100; * obj2.foo(10)(10); // => 120 * g(1); // => 21, the application using obj2 didn't affect the execution context of g * * var err = obj1.foo; * err(1, 2); // => throws * */ // TODO: Need better examples // TODO: Revisit examples in this file once object functions implemented (use funkierJS equivalents // rather than Object.create, [].slice, etc...) var objectCurry = curry(function(fn) { return objectCurryWithArity(arityOf(fn), fn); }); /* * <apifunction> * * objectCurryWithArity * * Category: function * * Parameter: n: strictNatural * Parameter: f: function * Returns: function * * Given an arity and function, returns a curried function which calls the underlying with the execution context * active when the first arguments are supplied. This means that when partially applying the function, the * resulting functions will have their execution context permanently bound. This method of binding is designed for * currying functions that exist on an object's prototype. The function will be only called when the specified number * of arguments have been supplied. Superfluous arguments are discarded. The resulting function and its partial * applications throw if they require at least one argument, but are invoked without any. `objectCurryWithArity` * throws if the arity is not a natural number or if the second parameter is not a function. The resulting function * will throw if invoked with an undefined execution context. * * The returned function will have a length of 1, unless an arity of 0 was requested, in which case this will be the * length. The [`arityOf`](#arityOf) function can be used to determine how many arguments are required before the * wrapped function will be invoked. * * As noted above, you are permitted to curry a function to a smaller arity than its length. Whether the resulting * function behaves in a useful manner will of course depend on the function. * * If one has a function that has been returned from [`objectCurry`](#objectCurry) or `objectCurryWithArity`, one can * recurry it to a different arity if required. However, one cannot recurry any partial applications derived from it, * as the execution context has now been bound. `objectCurryWithArity` also cannot curry functions returned from * [`curry`](#curry), [`curryWithArity`](#curryWithArity), [`bind`](#bind) or * [`bindWithContextAndArity`](#bindWithContextAndArity), and nor can those functions curry functions returned from * `objectCurryWithArity`, or their subsequent partial applications. `objectCurryWithArity` will throw when provided * with such a function. * * Unfortunately, funkierJS has no visibility into functions bound with the native `bind` method; attempting to * curry such functions won't throw, but they will not work as expected. * * Examples: * * var proto = {foo: function(x, y, z) { return x + y + this.bar; }}; * proto.foo = funkierJS.objectCurryWithArity(2, proto.foo); * * var obj1 = Object.create(proto); * obj1.bar = 10; * * var g = obj1.foo(10); * g(22); // => 42 * * var obj2 = Object.create(proto); * obj2.bar = 100; * obj2.foo(10)(10); // => 120 * g(1); // => 21, the application using obj2 didn't affect the execution context of g * * var err = obj1.foo; * err(1, 2); // => throws * */ // TODO: Need better examples // TODO: Revisit examples in this file once object functions implemented (use funkierJS equivalents // rather than Object.create, [].slice, etc...) var objectCurryWithArity = curry(curryInternal.bind(null, undefined)); /* * Where appropriate, funkierJS aims to preserve the currying style in functions that manipulate other functions * This function takes an existing curried function and a new function, and curries the new function in a compatible * way with the existing function. Thus, if the function was object curried, then so too is the new function. If it * is bound to a specific object then so too is the new function. Otherwise, the standard currying is applied. * * Of course, with the exception of object currying, the currying of the wrapper will not affect the operation * of the original function—which is presumably called within the wrapper function—as its context is already * bound. This function simply aims to enable manipulation of arities in a manner consistent with the original * functions. * */ var curryWithConsistentStyle = function(existing, newFn, arity) { arity = arity === undefined ? arityOf(newFn) : arity; return curryInternal(existing.hasOwnProperty(contextProp ? existing.contextProp : null), arity, newFn); }; /* * Where appropriate, funkierJS aims to preserve the currying style in functions that manipulate other functions * Whilst a simple question in the case of one function, this becomes more problematic when dealing with two or * more functions. This function takes two functions—the functions being wrapped—and the wrapping function, and * currys the wrapping function to the most appropriate choice for those functions. The wrapping function is assumed * to have the correct arity (so the plain currying function will be called, not a *WithArity function. * * So, what is the most appropriate style? If either function is object curried, then one would want another object * curried function for the purposes of passing the execution context to the wrapped functions. If both functions * are bound to the same context, then it makes sense to bind the result to the same context. If both functions * are curried to a null context, then again it is consistent to curry the wrapping function in the same manner. * * Things are more complicated when the functions have different currying styles, and neither of them is object * curried. Thus, either they are both bound to different contexts, or one is bound and one is null curried. For * maximum flexibility, I think the result should be null curried. * * Of course, with the exception of object currying, the currying of the wrapper will not affect the operation * of the original functions—which are presumably called within the wrapper function—as their contexts are already * bound. This function simply aims to enable manipulation of arities in a manner consistent with the original * functions. * */ var chooseCurryStyle = function(pred1, pred2, wrapper, arity) { arity = arity !== undefined ? arity : arityOf(wrapper); var contexts = [pred1, pred2].map(function(p) { return isCurried(p) ? p[contextProp] : null; }); var contextToApply; if (contexts.indexOf(undefined) !== -1) { contextToApply = undefined; } else if (contexts[0] === contexts[1]) { contextToApply = contexts[0]; } else { contextToApply = null; } return curryInternal(contextToApply, arity, wrapper); }; return { arity: arityOf, arityOf: arityOf, bind: bind, bindWithContext: bind, bindWithContextAndArity: bindWithContextAndArity, _chooseCurryStyle: chooseCurryStyle, curry: curry, curryWithArity: curryWithArity, _curryWithConsistentStyle: curryWithConsistentStyle, objectCurry: objectCurry, objectCurryWithArity: objectCurryWithArity, }; })(); },{"../internalUtilities":12}],3:[function(require,module,exports){ module.exports = (function() { "use strict"; var curryModule = require('./curry'); var curry = curryModule.curry; var chooseCurryStyle = curryModule._chooseCurryStyle; var curryWithConsistentStyle = curryModule._curryWithConsistentStyle; var funcUtils = require('../funcUtils'); var checkFunction = funcUtils.checkFunction; /* * <apifunction> * * not * * Category: Logical * * Parameter: b: boolean * Returns: boolean * * A wrapper around the logical not (!) operator. Returns the logical negation of the given argument. * * Examples: * * funkierJS.not(true); // => false * */ var not = curry(function(b) { return !b; }); /* * <apifunction> * * and * * Category: Logical * * Parameter: x: boolean * Parameter: y: boolean * Returns: boolean * * A wrapper around the logical and (&&) operator. Returns the logical and of the given arguments * * Examples: * * funkierJS.and(true, true); // => true * */ var and = curry(function(x, y) { return x && y; }); /* * <apifunction> * * or * * Category: Logical * * Parameter: x: boolean * Parameter: y: boolean * Returns: boolean * * A wrapper around the logical or (||) operator. Returns the logical or of the given arguments * * Examples: * * funkierJS.or(true, false); // => true * */ var or = curry(function(x, y) { return x || y; }); /* * <apifunction> * * xor * * Category: Logical * * Parameter: x: boolean * Parameter: y: boolean * Returns: boolean * * A wrapper around the logical xor operator. Returns the logical xor of the given arguments * * Examples: * * funkierJS.xor(true, true); // => false * */ var xor = curry(function(x, y) { return x ? x !== y : y; }); /* * <apifunction> * * notPred * * Category: Logical * * Parameter: f: function * Returns: function * * Takes a unary predicate function, and returns a new unary function that, when called, will call the original * function with the given argument, and return the negated result. Throws if f is not a function, or has an * arity other than 1. * * If the supplied predicate has been previously curried, then the resulting function will replicate the currying * style. In particular, if the original function was curried with one of the [`objectCurry'](#objectCurry) variants, * then the resulting function will be too, and where necessary will supply the execution context to the wrapped * function. * * Examples: * var c = funkierJS.constant(true);', * var f = funkierJS.notPred(c);', * f("foo"); // => false', * */ var notPred = curry(function(pred) { pred = checkFunction(pred, {arity: 1, message: 'Predicate must be a function of arity 1'}); return curryWithConsistentStyle(pred, function(x) { return !pred.call(this, x); }); }); /* * <apifunction> * * andPred * * Category: Logical * * Parameter: f1: function * Parameter: f2: function * Returns: function * * Takes two unary predicate functions, and returns a new unary function that, when called, will call the original * functions with the given argument, and logically and their results, returning that value. Throws if either * argument is not a function of arity 1. * * Where possible, funkierJS will aim to replicate the currying style of the function. If either function was * produced by one of the [`objectCurry'](#objectCurry) variants, then the resulting function will also be object * curried, and supply the correct execution context to the supplied functions. If neither was curried in that * manner, but one or more was curried with one of the [`bind`](#bind) variants, then the resulting function will * also be bound to the same context. Otherwise, the function will be curried with [`curry`]. (This is only provided * in case you need to give the resulting function to one of the `withArity` functions to change the arity). * * Examples: * var c = funkierJS.constant(true);', * var d = funkierJS.constant(false);', * var f = funkierJS.andPred(c, d);', * f("foo"); // => false', * */ var andPred = curry(function(pred1, pred2) { pred1 = checkFunction(pred1, {arity: 1, message: 'First predicate must be a function of arity 1'}); pred2 = checkFunction(pred2, {arity: 1, message: 'Second predicate must be a function of arity 1'}); return chooseCurryStyle(pred1, pred2, function(x) { return pred1.call(this, x) && pred2.call(this, x); }); }); /* * <apifunction> * * orPred * * Category: Logical * * Parameter: f1: function * Parameter: f2: function * Returns: function * * Takes two unary predicate functions, and returns a new unary function that, when called, will call the original * functions with the given argument, and logically or their results, returning that value. Throws if either * argument is not a function of arity 1. * * Where possible, funkierJS will aim to replicate the currying style of the function. If either function was * produced by one of the [`objectCurry'](#objectCurry) variants, then the resulting function will also be object * curried, and supply the correct execution context to the supplied functions. If neither was curried in that * manner, but one or more was curried with one of the [`bind`](#bind) variants, then the resulting function will * also be bound to the same context. Otherwise, the function will be curried with [`curry`]. (This is only provided * in case you need to give the resulting function to one of the `withArity` functions to change the arity). * * Examples: * var c = funkierJS.constant(true);', * var d = funkierJS.constant(false);', * var f = funkierJS.andPred(c, d);', * f("foo"); // => true', * */ var orPred = curry(function(pred1, pred2) { pred1 = checkFunction(pred1, {arity: 1, message: 'First predicate must be a function of arity 1'}); pred2 = checkFunction(pred2, {arity: 1, message: 'Second predicate must be a function of arity 1'}); return chooseCurryStyle(pred1, pred2, function(x) { return pred1.call(this, x) || pred2.call(this, x); }); }); /* * <apifunction> * * xorPred * * Category: Logical * * Parameter: f1: function * Parameter: f2: function * Returns: function * * Takes two unary predicate functions, and returns a new unary function that, when called, will call the original * functions with the given argument, and logically xor their results, returning that value. Throws if either * argument is not a function of arity 1. * * Where possible, funkierJS will aim to replicate the currying style of the function. If either function was * produced by one of the [`objectCurry'](#objectCurry) variants, then the resulting function will also be object * curried, and supply the correct execution context to the supplied functions. If neither was curried in that * manner, but one or more was curried with one of the [`bind`](#bind) variants, then the resulting function will * also be bound to the same context. Otherwise, the function will be curried with [`curry`]. (This is only provided * in case you need to give the resulting function to one of the `withArity` functions to change the arity). * * Examples: * var c = funkierJS.constant(true);', * var d = funkierJS.constant(true);', * var f = funkierJS.xorPred(c, d);', * f("foo"); // false', * */ var xorPred = curry(function(pred1, pred2) { pred1 = checkFunction(pred1, {arity: 1, message: 'First predicate must be a function of arity 1'}); pred2 = checkFunction(pred2, {arity: 1, message: 'Second predicate must be a function of arity 1'}); return chooseCurryStyle(pred1, pred2, function(x) { return xor(pred1.call(this, x), pred2.call(this, x)); }); }); return { and: and, andPred: andPred, not: not, notPred: notPred, or: or, orPred: orPred, xor: xor, xorPred: xorPred }; })(); },{"../funcUtils":9,"./curry":2}],4:[function(require,module,exports){ module.exports = (function() { "use strict"; var curry = require('./curry').curry; //var base = require('./base'); //var flip = base.flip; //var object = require('./object'); //var callProp = object.callProp; //var callPropWithArity = object.callPropWithArity; /* * <apifunction> * * add * * Category: maths * * Synonyms: plus * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the addition operator. * * Examples: * funkierJS.add(1, 1); // => 2 * */ var add = curry(function(x, y) { return x + y; }); /* * <apifunction> * * subtract * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the subtraction operator. * * Examples: * funkierJS.subtract(3, 1); // => 2; * */ var subtract = curry(function(x, y) { return x - y; }); /* * <apifunction> * * multiply * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the multiplication operator. * * Examples: * funkierJS.multiply(2, 2); // => 4; * */ var multiply = curry(function(x, y) { return x * y; }); /* * <apifunction> * * divide * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the division operator. * * Examples: * funkierJS.arityOf(4, 2); // => 2; * */ var divide = curry(function(x, y) { return x / y; }); /* * <apifunction> * * exp * * Category: maths * * Synonyms: pow * * Parameter: x: number * Parameter: y: number * Returns: number * * A curried wrapper around Math.pow. * * Examples: * funkierJS.exp(2, 3); // => 8 * */ var exp = curry(function(x, y) { return Math.pow(x, y); }); /* * <apifunction> * * log * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * Returns the logarithm of y in the given base x. Note that this function uses the change of base formula, so may * be subject to rounding errors. * * Examples: * funkierJS.log(2, 8); // => 3; * */ var log = curry(function(x, y) { return Math.log(y) / Math.log(x); }); /* * <apifunction> * * div * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * Returns the quotient on dividing x by y. * * Examples: * funkierJS.div(5, 2); // => 2 * */ var div = curry(function(x, y) { return Math.floor(x / y); }); /* * <apifunction> * * rem * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the remainder (%) operator. * * Examples: * funkierJS.rem(5, 2); // => 1; * */ var rem = curry(function(x, y) { return x % y; }); /* * <apifunction> * * lessThan * * Category: maths * * Synonyms: lt * * Parameter: x: number * Parameter: y: number * Returns: boolean * * A wrapper around the less than (<) operator. * * Examples: * funkierJS.lessThan(5, 2); // => false; * */ var lessThan = curry(function(x, y) { return x < y; }); /* * <apifunction> * * lessThanEqual * * Category: maths * * Synonyms: lte * * Parameter: x: number * Parameter: y: number * Returns: boolean * * A wrapper around the less than or equal (<=) operator. * * Examples: * funkierJS.lessThanEqual(2, 2); // => true; * */ var lessThanEqual = curry(function(x, y) { return x <= y; }); /* * <apifunction> * * greaterThan * * Category: maths * * Synonyms: gt * * Parameter: x: number * Parameter: y: number * Returns: boolean * * A wrapper around the less than or equal (<=) operator. * * Examples: * funkierJS.greaterThan(5, 2); // => true; * */ var greaterThan = curry(function(x, y) { return x > y; }); /* * <apifunction> * * greaterThanEqual * * Category: maths * * Synonyms: gte * * Parameter: x: number * Parameter: y: number * Returns: boolean * * A wrapper around the greater than or equal (=>) operator. * * Examples: * funkierJS.greaterThanEqual(2, 2); // => true; * */ var greaterThanEqual = curry(function(x, y) { return x >= y; }); /* * <apifunction> * * leftShift * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the left shift (<<) operator. * * Examples: * funkierJS.leftShift(1, 2); // => 4; * */ var leftShift = curry(function(x, y) { return x << y; }); /* * <apifunction> * * rightShift * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the right shift (>>) operator. * * Examples: * funkierJS.rightShift(-4, 2); // => -1; * */ var rightShift = curry(function(x, y) { return x >> y; }); /* * <apifunction> * * rightShiftZero * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the left shift (>>>) operator. * * Examples: * funkierJS.rightShiftZero(-4, 2); // => 1073741823; * */ var rightShiftZero = curry(function(x, y) { return x >>> y; }); /* * <apifunction> * * bitwiseAnd * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the bitwise and (&) operator. * * Examples: * funkierJS.bitwiseAnd(7, 21); // => 5; * */ var bitwiseAnd = curry(function(x, y) { return x & y; }); /* * <apifunction> * * bitwiseOr * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the bitwise or (&) operator. * * Examples: * funkierJS.bitwiseOr(7, 8); // => 15; * */ var bitwiseOr = curry(function(x, y) { return x | y; }); /* * <apifunction> * * bitwiseXor * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A wrapper around the bitwise xor (^) operator. * * Examples: * funkierJS.bitwiseAnd(7, 3); // => 4; * */ var bitwiseXor = curry(function(x, y) { return x ^ y; }); /* * <apifunction> * * bitwiseNot * * Category: maths * * Parameter: x: number * Returns: number * * A wrapper around the bitwise not (~) operator. * * Examples: * funkierJS.bitwiseNot(5); // => -6; * */ var bitwiseNot = curry(function(x) { return ~x; }); /* * <apifunction> * * min * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A curried wrapper around Math.min. Takes exactly two arguments. * * Examples: * funkierJS.min(5, 2); // => 2; * */ // min has a spec mandated length of 2, so we calling curry will do the right thing var min = curry(Math.min); /* * <apifunction> * * max * * Category: maths * * Parameter: x: number * Parameter: y: number * Returns: number * * A curried wrapper around Math.max. Takes exactly two arguments. * * Examples: * funkierJS.min(5, 2); // => 5; * */ // max has a spec mandated length of 2, so we can simply curry var max = curry(Math.max); /* var toFixed = defineValue( 'name: toFixed', 'signature: x: number, y: number', 'classification: maths', '', 'A curried wrapper around Number.prototype.toFixed. Takes the number of digits', 'after the decimal point (which should be between 0 and 20), and a number.', 'Returns a string representing the number but with the specified number of places', 'after the decimal point.', '--', 'toFixed(2, 1); // "1.00"', callPropWithArity('toFixed', 1) ); var toExponential = defineValue( 'name: toExponential', 'signature: x: number, y: number', 'classification: maths', '', 'A curried wrapper around Number.prototype.toExponential. Takes the number of', 'digits after the decimal point (which should be between 0 and 20), and a number.', 'Returns a string representing the number in exponential notation, with the', 'specified number of places after the decimal point.', '--', 'toExponential(3, 1); // "1.000e+0"', callPropWithArity('toExponential', 1) ); var toPrecision = defineValue( 'name: toPrecision', 'signature: x: number, y: number', 'classification: maths', '', 'A curried wrapper around Number.prototype.toPrecision. Takes the number of', 'significant digits (which should be between 1 and 21), and a number. Returns a', 'string representing the number, with the specified number of significant digits.', '--', 'toPrecision(3, 1); // "1.000"', callPropWithArity('toPrecision', 1) ); var toBaseAndString = defineValue( 'name: toBaseAndString', 'signature: x: number, y: number', 'classification: maths', '', 'A curried wrapper around Number.prototype.toString. Takes a base between 2 and', '36, and a number. Returns a string representing the given number in the given', 'base.', '--', 'toBaseAndString(2, 5); // "101"', callPropWithArity('toString', 1) ); var stringToInt = defineValue( 'name: stringToInt', 'signature: n: number, s: string', 'classification: maths', '', 'A curried wrapper around parseInt. Takes a base between 2 and 36, and a string,', 'and attempts to convert the string assuming it represents a number in the given', 'base. Returns NaN if the string does not represent a valid number given the base.', '--', 'stringToInt(16, "80"); // 128', flip(parseInt) ); */ /* * <apifunction> * * even * * Category: maths * * Parameter: x: number * Returns: boolean * * Given a number, returns true if it is divisible by 2, and false otherwise. * * Examples: * funkierJS.even(2); // => true * funkierJS.even(3); // => false * */ var even = curry(function(n) { return n % 2 === 0; }); /* * <apifunction> * * odd * * Category: maths * * Parameter: x: number * Returns: boolean * * Given a number, returns true if it is not divisible by 2, and false otherwise. * * Examples: * funkierJS.odd(2); // => false * funkierJS.odd(3); // => true * */ var odd = curry(function(n) { return n % 2 !== 0; }); return { add: add, bitwiseAnd: bitwiseAnd, bitwiseNot: bitwiseNot, bitwiseOr: bitwiseOr, bitwiseXor: bitwiseXor, div: div, divide: divide, even: even, exp: exp, greaterThan: greaterThan, greaterThanEqual: greaterThanEqual, gt: greaterThan, gte: greaterThanEqual, leftShift: leftShift, lessThan: lessThan, lessThanEqual: lessThanEqual, lt: lessThan, lte: lessThanEqual, log: log, min: min, max: max, multiply: multiply, odd: odd, plus: add, pow: exp, rem: rem, rightShift: rightShift, rightShiftZero: rightShiftZero, //stringToInt: stringToInt, subtract: subtract //toBaseAndString: toBaseAndString, //toExponential: toExponential, //toFixed: toFixed, //toPrecision: toPrecision }; })(); },{"./curry":2}],5:[function(require,module,exports){ module.exports = (function() { "use strict"; var curryModule = require('./curry'); var curry = curryModule.curry; var curryWithConsistentStyle = curryModule._curryWithConsistentStyle; var arityOf = curryModule.arityOf; var internalUtilities = require('../internalUtilities'); var valueStringifier = internalUtilities.valueStringifier; var funcUtils = require('../funcUtils'); var checkFunction = funcUtils.checkFunction; /* * Maybe encapsulates the idea of sentinel values returned by functions to represent an error or unusual condition. * Authors can return an instance of the Just constructor when a function runs successfully, and the Nothing object * when an error occurs or the computation is otherwise unsuccessful. */ /* * <apifunction> * * Maybe * * Category: DataTypes * * The Maybe type encapsulates the idea of sentinel values returned by functions to represent an error or unusual * conditions. Authors can return an instance of the Just constructor when a function executes successfully, and the * Nothing object when an error occurs, or the computation is otherwise unsuccessful. * * Maybe is the 'base class' of [`Just`](#Just) and [`Nothing`](#Nothing). It is provided only for the instanceof * operator. * * It is an error to call Maybe. * */ var Maybe = curry(function() { throw new Error('Maybe cannot be instantiated directly'); }); Maybe.prototype = {toString: function() {return 'Maybe';}, constructor: Maybe}; var nothingPrototype = Object.create(Maybe.prototype); nothingPrototype.toString = function() {return 'Maybe {Nothing}';}; /* * <apiobject> * * Nothing * * Category: DataTypes * * A Nothing is a type of Maybe representing an unsuccessful computation. * */ var Nothing = Object.create(nothingPrototype); Object.freeze(Nothing); /* * <apifunction> * * Just * * Category: DataTypes * * Parameter: a: any * Returns: Just * * A Just is a type of Maybe representing a successful computation. The constructor is new-agnostic. * Throws when called with no arguments. * * Examples: * var result = funkierJS.Just(42); * */ var Just = function(val) { if (arguments.length !== 1) throw new TypeError('Just called with incorrect number of arguments'); if (!(this instanceof Just)) return new Just(val); Object.defineProperty(this, 'value', {value: val}); }; Just.prototype = Object.create(Maybe.prototype); Just.prototype.toString = function() { return 'Maybe {Just ' + valueStringifier(this.value) + '}'; }; /* * <apifunction> * * isMaybe * * Category: DataTypes * * Parameter: a: any * Returns: boolean * * Returns true when the given value is a Maybe object, and false otherwise. * * Examples: * funkierJS.isMaybe(funkierJS.Nothing) && funkierJS.isMaybe(funkierJS.Just(42)); // => true * */ var isMaybe = curry(function(val) { return val === Maybe || val instanceof Maybe; }); /* * <apifunction> * * isNothing * * Category: DataTypes * * Parameter: a: any * Returns: boolean * * Returns true if the given value is the Nothing object, and false otherwise. * * Examples: * funkierJS.isNothing(funkierJS.Nothing); // => true * */ var isNothing = curry(function(val) { return val === Nothing; }); /* * <apifunction> * * isJust * * Category: DataTypes * * Parameter: a: any * Returns: boolean * * Returns true if the given value is a Just object, and false otherwise. * * Examples: * funkierJS.isJust(funkierJS.Just(42)); // => true * */ var isJust = curry(function(val) { return val instanceof Just; }); /* * <apifunction> * * getJustValue * * Category: DataTypes * * Parameter: j: Just * Returns: any * * Returns the value wrapped by the given Just instance j. Throws a TypeError if called with anything other than a * Just. * * Examples: * funkierJS.getJustValue(funkierJS.Just(3)); // => 3', * */ var getJustValue = curry(function(j) { if (!isJust(j)) throw new TypeError('Value is not a Just'); return j.value; }); /* * <apifunction> * * makeMaybeReturner * * Category: DataTypes * * Parameter: f: function * Returns: function * * Takes a function f. Returns a new function with the same arity as f. When called, the new function calls the * original. If the function f throws during execution, then the Nothing object is returned. Otherwise the result of * the function is wrapped in a Just and returned. * * The function will be curried in the same style as the original, or using [`curry`](#curry) if the function was not * curried. * * Examples: * var g = function(x) { * if (x < 10) * throw new Error('Bad value'); * return x; * }; * * var f = funkierJS.makeMaybeReturner(g); * f(11); // => Just(11) * f(5); // => Nothing * */ var makeMaybeReturner = curry(function(f) { f = checkFunction(f, {message: 'Value to be transformed must be a function'}); return curryWithConsistentStyle(f, function() { var args = [].slice.call(arguments); try { var result = f.apply(this, arguments); return Just(result); } catch (e) { return Nothing; } }, arityOf(f)); }); return { getJustValue: getJustValue, isJust: isJust, isMaybe: isMaybe, isNothing: isNothing, makeMaybeReturner: makeMaybeReturner, Just: Just, Maybe: Maybe, Nothing: Nothing }; })(); },{"../funcUtils":9,"../internalUtilities":12,"./curry":2}],6:[function(require,module,exports){ module.exports = (function() { "use strict"; var curryModule = require('./curry'); var curry = curryModule.curry; var utils = require('../internalUtilities'); var valueStringifier = utils.valueStringifier; /* * A Pair represents an immutable tuple. The constructor function takes two elements, * first, and second, and returns a new tuple. The contents of the tuple can be accessed * with the accessor functions fst and snd respectively. The constructor is new-agnostic. * When called with one argument, a function will be returned that expects a second argument; * supplying this function with a value will yield a Pair. Throws a TypeError if called with * zero arguments. * */ /* * <apifunction> * * Pair * * Category: DataTypes * * Parameter: a: any * Parameter: b: any * Returns: Pair * * A Pair represents an immutable tuple. The constructor function takes two elements, first and second. and returns a * new immutable tuple. The contents of the tuple can be accessed with the accessor functions fst and snd * respectively. The constructor is new-agnostic. * * The constructor is curried: when called with one argument, a function will be returned that expects a second * argument; supplying this function with a value will yield a Pair. Note that the constructor is internally curried * outside of the usual mechanisms. * * Throws a TypeError if called with zero arguments. * * Examples: * var p1 = new funkierJS.Pair(2, 3); * var p2 = funkierJS.Pair(2)(3); * var pairs = funkierJS.map(funkierJS.new Pair(3), [4, 5, 6]); * */ var Pair = function(a, b) { if (arguments.length === 0) throw new TypeError('Pair constructor takes two arguments'); if (arguments.length === 1) return pairMaker(a); if (!(this instanceof Pair)) return new Pair(a, b); Object.defineProperty(this, 'first', {enumerable: false, configurable: false, value: a}); Object.defineProperty(this, 'second', {enumerable: false, configurable: false, value: b}); }; Pair.prototype = { toString: function() { // We use coercion rather than an explicit toString call as it's permissible for the // values to be null or undefined return ['Pair (', valueStringifier(this.first), ', ', valueStringifier(this.second), ')'].join(''); }, constructor: Pair }; // Utility function for Pair to provide the illusion of currying var pairMaker = function(a) { var fn = curry(function(b) { return new Pair(a, b); }); // Lie to instanceof fn.prototype = Pair.prototype; return fn; }; /* * <apifunction> * * fst * * Category: DataTypes * * Synonyms: first * * Parameter: p: Pair * Returns: any * * Accessor function for pair tuples. Returns the first value that was supplied to the pair constructor. Throws if * called with a non-pair value. * * Examples: * var p = new funkierJS.Pair(2, 3); * funkierJS.fst(p); // => 2', * */ var fst = curry(function(pair) { if (!(pair instanceof Pair)) throw new TypeError('Not a pair'); return pair.first; }); /* * <apifunction> * * snd * * Category: DataTypes * * Synonyms: second * * Parameter: p: Pair * Returns: any * * Accessor function for pair tuples. Returns the second value that was supplied to the pair constructor. Throws if * called with a non-pair value. * * Examples: * var p = new funkierJS.Pair(2, 3); * funkierJS.cnd(p); // => 3', * */ var snd = curry(function(pair) { if (!(pair instanceof Pair)) throw new TypeError('Not a pair'); return pair.second; }); /* * <apifunction> * * isPair * * Category: DataTypes * * Parameter: a: any * Returns: boolean * * Returns true if the given value is a Pair, and false otherwise. * * Examples: * funkierJS.isPair(funkierJS.Pair(2, 3)); // => True * */ var isPair = curry(function(obj) { return obj instanceof Pair; }); /* * <apifunction> * * asArray * * Category: DataTypes * * Parameter: p: Pair * Returns: array * * Takes a pair, and returns a 2-element array containing the values contained in the given pair p. Specifically, if * the resulting array is named arr, then we have arr[0] === fst(p) and arr[1] === snd(p). Throws a TypeError if p is * not a pair. * * Examples: * funkierJS.asArray(funkierJS.Pair(7, 10)); // => [7, 10]', * */ var asArray = curry(function(p) { if (!(p instanceof Pair)) throw new TypeError('Not a pair'); return [fst(p), snd(p)]; }); return { Pair: Pair, asArray: asArray, first: fst, fst: fst, isPair: isPair, second: snd, snd: snd }; })(); },{"../internalUtilities":12,"./curry":2}],7:[function(require,module,exports){ module.exports = (function() { "use strict"; var curryModule = require('./curry'); var curry = curryModule.curry; var curryWithArity = curryModule.curryWithArity; var arityOf = curryModule.arityOf; var curryWithConsistentStyle = curryModule._curryWithConsistentStyle; var internalUtilities = require('../internalUtilities'); var valueStringifier = internalUtilities.valueStringifier; var checkArrayLike = internalUtilities.checkArrayLike; var funcUtils = require('../funcUtils'); var checkFunction = funcUtils.checkFunction; /* * Result encapsulates the idea of functions throwing errors. It can be considered equivalent * to the Either datatype from Haskell, or the Result type from Rust. */ /* * <apifunction> * * Result * * Category: DataTypes * * The Result type encapsulates the idea of functions throwing errors. It can be considered equivalent to the Either * datatype from Haskell, or the Result type from Rust. * * Result is the 'base class' of [`Ok`](#Ok) and [`Err`](#Err). It is provided only for the instanceof operator. * * It is an error to call Result. * */ var Result = function() { throw new Error('Result cannot be instantiated directly'); }; Result.prototype = {toString: function() {return 'Result';}, constructor: Result}; /* * <apifunction> * * Ok * * Category: DataTypes * * Parameter: a: any * Returns: Ok * * An Ok is a type of Result representing a successful computation. The constructor is new-agnostic. * Throws when called with no arguments. * * Examples: * var result = funkierJS.Ok(42); * */ var Ok = function(val) { if (arguments.length !== 1) throw new TypeError('Ok called with incorrect number of arguments'); if (!(this instanceof Ok)) return new Ok(val); Object.defineProperty(this, 'value', {configurable: false, writable: false, enumerable: false, value: val}); }; Ok.prototype = Object.create(Result.prototype); Ok.prototype.toString = function() { return 'Result {Ok ' + valueStringifier(this.value) + '}'; }; /* * <apifunction> * * Err * * Category: DataTypes * * Parameter: a: any * Returns: Just * * An Err is a type of Result representing a unsuccessful computation. The constructor is new-agnostic. * Throws if called without any arguments * * Examples: * var result = funkierJS.Err(new TypeError('boom'); * */ var Err = function(val) { if (arguments.length !== 1) throw new TypeError('Err called with incorrect number of arguments'); if (!(this instanceof Err)) return new Err(val); Object.defineProperty(this, 'value', {configurable: false, writable: false, enumerable: false, value: val}); }; Err.prototype = Object.create(Result.prototype); Err.prototype.toString = function() { return 'Result {Err ' + valueStringifier(this.value) + '}'; }; /* * <apifunction> * * isResult * * Category: DataTypes * * Parameter: a: any * Returns: boolean * * Returns true when the given value is a Result object, and false otherwise. * * Examples: * funkierJS.isResult(funkierJS.Ok(3)) && funkierJS.isResult(funkierJS.Err(false)); // => true * */ var isResult = curry(function(val) { return val === Result || val instanceof Result; }); /* * <apifunction> * * isErr * * Category: DataTypes * * Parameter: a: any * Returns: boolean * * Returns true when the given value is a Err object, and false otherwise. * * Examples: * funkierJS.isErr(funkierJS.Err(4)); // => true * */ var isErr = curry(function(val) { return val instanceof Err; }); /* * <apifunction> * * isOk * * Category: DataTypes * * Parameter: a: any * Returns: boolean * * Returns true when the given value is a Ok object, and false otherwise. * * Examples: * funkierJS.isOk(funkierJS.Ok('foo)); // => true * */ var isOk = curry(function(val) { return val instanceof Ok; }); /* * <apifunction> * * getOkValue * * Category: DataTypes * * Parameter: o: Ok * Returns: any * * Returns the value wrapped by the given Ok instance o. Throws a TypeError if called with anything other than an * Ok. * * Examples: * funkierJS.getOkValue(funkierJS.Ok(3)); // => 3', * */ var getOkValue = curry(function(val) { if (!isOk(val)) throw new TypeError('Value is not an Ok'); return val.value; }); /* * <apifunction> * * getErrValue * * Category: DataTypes * * Parameter: e: Err * Returns: any * * Returns the value wrapped by the given Err instance e. Throws a TypeError if called with anything other than an * Err. * * Examples: * funkierJS.getErrValue(funkierJS.Err(4)); // => 4', * */ var getErrValue = curry(function(val) { if (!isErr(val)) throw new TypeError('Value is not an Err'); return val.value; }); /* * <apifunction> * * makeResultReturner * * Category: DataTypes * * Parameter: f: function * Returns: function * * Takes a function f. Returns a new function with the same arity as f. When called, the new function calls the * original. If the function f throws during execution, then the exception will be caught, and an Err object * wrapping the exception is returned. Otherwise the result of the function is wrapped in an Ok and returned. * * The function will be curried in the same style as the original, or using [`curry`](#curry) if the function was not * curried. * * Examples: * var g = function(x) { * if (x < 10) * throw new Error('Bad value'); * return x; * }; * * var f = funkierJS.makeResultReturner(g); * f(11); // => Ok(11) * f(5); // => Err(Error('Bad value'); * */ var makeResultReturner = curry(function(f) { f = checkFunction(f, {message: 'Value to be transformed must be a function'}); return curryWithConsistentStyle(f, function() { var args = [].slice.call(arguments); try { var result = f.apply(this, arguments); return Ok(result); } catch (e) { return Err(e); } }, arityOf(f)); }); /* * <apifunction> * * either * * Category: DataTypes * * Parameter: f1: function * Parameter: f2: function * Parameter: r: Result * Returns: function * * Takes two functions of arity 1 or greater, and a Result. If the Result is an Ok value, the first function f1 will * be called with the unwrapped value. Otherwise, if the Result is an Err value, the second function is called * with the unwrapped value. In either case, the result of of the called function is returned. * * Throws a TypeError if either of the first two arguments is not a function of arity 1 or more, or if the given value * is not a Result. * * Examples: * var f = funkierJS.either(function(x) {console.log('Good: ' + x);}, function(x) {console.log('Bad: ' + x);}); * f(funkierJS.Ok(2)); // => logs 'Good: 2' to the console * f(funkierJS.Err(':(')); // logs 'Bad: :(' to the console * */ var either = curry(function(okFn, errFn, result) { okFn = checkFunction(okFn, {arity: 1, minimum: true, message: 'Ok value must be a function of arity 1 or more'}); errFn = checkFunction(errFn, {arity: 1, minimum: true, message: 'Err value must be a function of arity 1 or more'}); if (isOk(result)) return okFn(getOkValue(result)); if (isErr(result)) return errFn(getErrValue(result)); throw new TypeError('Invalid value'); }); return { either: either, getErrValue: getErrValue, getOkValue: getOkValue, isErr: isErr, isOk: isOk, isResult: isResult, makeResultReturner: makeResultReturner, Err: Err, Ok: Ok, Result: Result }; })(); },{"../funcUtils":9,"../internalUtilities":12,"./curry":2}],8:[function(require,module,exports){ module.exports = (function() { "use strict"; // var makeModule = function(require, exports) { // var curryModule = require('./curry'); var curry = require('./curry').curry; // var curryWithArity = curryModule.curryWithArity; // var getRealArity = curryModule.getRealArity; // // var funcUtils = require('./funcUtils'); // var checkFunction = funcUtils.checkFunction; // // var utils = require('./utils'); // var checkPositiveIntegral = utils.checkPositiveIntegral; // var defineValue = utils.defineValue; /* * <apifunction> * * equals * * Category: types * * Parameter: a: any * Parameter: b: any * Returns: boolean * * A wrapper around the non-strict equality (==) operator. * * Examples: * funkierJS.equals(1, '1'); // => true * */ var equals = curry(function(x, y) { return x == y; }); /* * <apifunction> * * strictEquals * * Category: types * * Parameter: a: any * Parameter: b: any * Returns: boolean * * A wrapper around the strict equality (===) operator. * * Examples: * funkierJS.strictEquals(1, '1'); // => false * */ var strictEquals = curry(function(x, y) { return x === y; }); /* * <apifunction> * * notEqual * * Category: types * * Synonyms: notEquals * * Parameter: a: any * Parameter: b: any * Returns: boolean * * A wrapper around the inequality (!=) operator. * * Examples: * funkierJS.notEqual({}, {}); // => true * */ var notEqual = curry(function(x, y) { return x != y; }); /* * <apifunction> * * strictNotEqual * * Category: types * * Synonyms: strictNotEquals | strictInequality * * Parameter: a: any * Parameter: b: any * Returns: boolean * * A wrapper around the strict inequality (!==) operator. * * Examples: * funkierJS.strictNotEqual(1, '1'); // => true * */ var strictNotEqual = curry(function(x, y) { return x !== y; }); // Helper function for deepEqual. Assumes both objects are arrays. var deepEqualArr = function(a, b, aStack, bStack) { if (a.length !== b.length) return false; for (var i = aStack.length - 1; i >= 0; i--) { if (aStack[i] === a) return bStack[i] === b || bStack[i] === a; if (bStack[i] === b) return false; } aStack.push(a); bStack.push(b); var ok = true; ok = ok && deepEqualInternal(a[i], b[i], aStack, bStack); // Can't just iterate over the indices: the array might have custom keys var aKeys = Object.keys(a); var bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) { ok = false; } else { aKeys.sort(); bKeys.sort(); ok = aKeys.every(function(k, i) { if (k !== bKeys[i]) return false; return deepEqualInternal(a[k], b[k], aStack, bStack); }); } aStack.pop(); bStack.pop(); return ok; }; // Helper function for deepEqual. Assumes identity has already been checked, and // that a check has been made for both objects being arrays. var deepEqualObj = function(a, b, aStack, bStack) { // Identity should have already been checked (ie a ==== b === null) if (a === null || b === null) return false; // Likewise, we should already have checked for arrays if (Array.isArray(a) || Array.isArray(b)) return false; if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; // Check for recursive objects for (var i = aStack.length - 1; i >= 0; i--) { if (aStack[i] === a) return bStack[i] === b || bStack[i] === a; if (bStack[i] === b) return false; } var aKeys = Object.keys(a); var bKeys = Object.keys(b); aKeys.sort(); bKeys.sort(); if (!deepEqualArr(aKeys, bKeys, aStack, bStack)) return false; aStack.push(a); bStack.push(b); var ok = true; for (i = 0; ok && i < aKeys.length; i++) ok = ok && deepEqualInternal(a[aKeys[i]], b[bKeys[i]], aStack, bStack); aStack.pop(); bStack.pop(); return ok; }; var deepEqualInternal = function(a, b, aStack, bStack) { if (strictEquals(a, b)) return true; if (typeof(a) !== typeof(b)) return false; if (typeof(a) !== 'object') return false; if (Array.isArray(a) && Array.isArray(b)) return deepEqualArr(a, b, aStack, bStack); return deepEqualObj(a, b, aStack, bStack); }; /* * <apifunction> * * deepEqual * * Category: types * * Synonyms: deepEquals * * Parameter: a: any * Parameter: b: any * Returns: boolean * * Check two values for deep equality. Deep equality holds if any of the following if the two values are the same * object, if both values are objects with the same object, the same prototype, the same enumerable properties * and those properties are themselves deeply equal (non-enumerable properties are not checked), or if both values * are arrays with the same length, any additional properties installed on the arrays are deeply equal, and the items * at each index are themselves deeply equal. * * Examples: * funkierJS.deepEqual({foo: 1, bar: [2, 3]}, {bar: [2, 3], foo: 1}); // => true * */ var deepEqual = curry(function(a, b) { return deepEqualInternal(a, b, [], []); }); /* * <apifunction> * * is * * Category: types * * Synonyms: hasType * * Parameter: type: string * Parameter: value: any * Returns: boolean * * Given a string that could be returned by the `typeof` operator, and a value, returns true if typeof the given * object equals the given string. Throws if the first argument is not a string. * * Examples: * funkierJS.is('number', 1); // => true * */ var is = curry(function(s, obj) { if (typeof(s) !== 'string') throw new TypeError('Type to be checked is not a string'); return typeof(obj) === s; }); /* * <apifunction> * * isNumber * * Category: types * * Parameter: a: any * Returns: boolean * * Returns true if typeof the given value equals "number", false otherwise. * * Examples: * funkierJS.isNumber(1); // => true * */ var isNumber = is('number'); /* * <apifunction> * * isString * * Category: types * * Parameter: a: any * Returns: boolean * * Returns true if typeof the given value equals "string", false otherwise. * * Examples: * funkierJS.isString('a'); // => true * */ var isString = is('string'); /* * <apifunction> * * isBoolean * * Category: types * * Parameter: a: any * Returns: boolean * * Returns true if typeof the given value equals "boolean", false otherwise. * * Examples: * funkierJS.isBoolean(false); // => true * */ var isBoolean = is('boolean'); /* * <apifunction> * * isUndefined * * Category: types * * Parameter: a: any * Returns: boolean * * Returns true if typeof the given value equals "undefined", false otherwise. * * Examples: * funkierJS.isUndefined(1); // => false * */ var isUndefined = is('undefined'); /* * <apifunction> * * isObject * * Category: types * * Parameter: a: any * Returns: boolean * * Returns true if typeof the given value equals "object", false otherwise. * * Examples: * funkierJS.isObject(null); // => true * */ var isObject = is('object'); /* * <apifunction> * * isArray * * Category: types * * Parameter: a: any * Returns: boolean * * Returns true if the given value is an array, false otherwise * * Examples: * funkierJS.isArray([]); // => true * */ var isArray = curry(function(obj) { return Array.isArray(obj); }); /* * <apifunction> * * isNull * * Category: types * * Parameter: a: any * Returns: boolean * * Returns true if the given object is null, false otherwise * * Examples: * funkierJS.isNull(null); // => true * */ var isNull = curry(function(obj) { return obj === null; }); /* * <apifunction> * * isRealObject * * Category: types * * Parameter: a: any * Returns: boolean * * Returns true if the value is a *real* Javascript object, i.e. an object for which `funkierJS.isObject(a) === true` * and `funkierJS.isNull(a) === false` and `funkierJS.isArray(a) === false`. * * Examples: * funkierJS.isRealObject(null); // => false * */ var isRealObject = curry(function(obj) { return isObject(obj) && !(isArray(obj) || isNull(obj)); }); /* * <apifunction> * * getType * * Category: types * * Parameter: a: any * Returns: string * * A functional wrapper around the typeof operator. Takes any Javascript value, and returns a string representing * the object"s type: the result will be one of "number", "string", "boolean", "function", "undefined", or "object". * * Examples: * funkierJS.getType({}); // => "object" * */ var getType = curry(function(val) { return typeof(val); }); return { deepEqual: deepEqual, deepEquals: deepEqual, equals: equals, getType: getType, hasType: is, is: is, isArray: isArray, isBoolean: isBoolean, isNumber: isNumber, isNull: isNull, isObject: isObject, isRealObject: isRealObject, isString: isString, isUndefined: isUndefined, notEqual: notEqual, notEquals: notEqual, strictEquals: strictEquals, strictInequality: strictNotEqual, strictNotEqual: strictNotEqual, strictNotEquals: strictNotEqual }; })(); },{"./curry":2}],9:[function(require,module,exports){ module.exports = (function() { "use strict"; /* * A collection of internal utilities. Not exported to consumers. * * These utilities are deliberately split out from those in utils.js. Some functions here * depend on arityOf from curry.js, and we want curry.js to be able to use the functions * in utils. * */ var curryModule = require('./components/curry'); var arityOf = curryModule.arityOf; /* * Takes a value. Throws a TypeError if the value is not a function, and possibly return the * function otherwise, after any optional checks. * * This function takes an optional options object. The following properties are recognised: * - message: the message the TypeError should contain if it proves necessary to throw * - arity: in isolation, will restrict to accepting functions of this arity * - minimum: when true, changes the meaning of arity to be the minimum accepted * */ var checkFunction = function(f, options) { options = options || {}; var message = options.message || 'Value is not a function'; var arity = 'arity' in options ? options.arity : null; var minimum = options.minimum || false; if (minimum && !options.message) message = 'Value is not a function of arity ≥ ' + arity; var maximum = options.maximum || false; if (maximum && !options.message) message = 'Value is not a function of arity ≤ ' + arity; if (typeof(f) !== 'function') throw new TypeError(message); if (arity !== null) { var fArity = arityOf(f); if ((minimum && fArity < arity) || (maximum && fArity > arity) || (!minimum && !maximum && fArity !== arity)) throw new TypeError(message); } return f; }; return { checkFunction: checkFunction }; })(); },{"./components/curry":2}],10:[function(require,module,exports){ module.exports = (function() { "use strict"; var funkier = {}; // Imports need to be explicit for browserify to find them var imports = { base: require('./components/base'), curry: require('./components/curry'), logical: require('./components/logical'), maths: require('./components/maths'), maybe: require('./components/maybe'), pair: require('./components/pair'), result: require('./components/result'), types: require('./components/types') }; // Export our imports Object.keys(imports).forEach(function(mod) { var m = imports[mod]; Object.keys(m).forEach(function(k) { if (k[0] === '_') return; funkier[k] = m[k]; }); }); // Intall auto-generated help require('./help')(funkier); return funkier; })(); //(function() { // "use strict"; // // // var makeModule = function(require, exports) { // var base = require('./base'); // var logical = require('./logical'); // var maths = require('./maths'); // var object = require('./object'); // var string = require('./string'); // var fn = require('./fn'); // var date = require('./date'); // var pair = require('./pair'); // var maybe = require('./maybe'); // var result = require('./result'); // var combinators = require('./combinators'); // var array = require('./array'); // // var utils = require('./utils'); // var help = utils.help; // // // // // Also export help // exportedFns.help = help; // // // module.exports = exportedFns; // }; // // // // AMD/CommonJS foo // if (typeof(define) === "function") { // define(function(require, exports, module) { // makeModule(require, exports, module); // }); // } else { // makeModule(require, exports, module); // } //})(); },{"./components/base":1,"./components/curry":2,"./components/logical":3,"./components/maths":4,"./components/maybe":5,"./components/pair":6,"./components/result":7,"./components/types":8,"./help":11}],11:[function(require,module,exports){ module.exports = (function() { "use strict"; /* NOTE: THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT MANUALLY */ return function(funkier) { var helpFn = function(value) { switch (value) { case helpFn: console.log('help:'); console.log('Displays useful help for funkierJS API values'); console.log(''); console.log('Usage: help(f);'); console.log(''); console.log('Find full help online at https://graememcc.github.io/funkierJS/docs/'); break; case funkier.Err: console.log('Err:'); console.log(''); console.log('An Err is a type of Result representing a unsuccessful computation. The constructor is new-agnostic.'); console.log('Throws if called without any arguments'); console.log(''); console.log('Usage: var x = Err(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#err'); break; case funkier.Just: console.log('Just:'); console.log(''); console.log('A Just is a type of Maybe representing a successful computation. The constructor is new-agnostic.'); console.log('Throws when called with no arguments.'); console.log(''); console.log('Usage: var x = Just(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#just'); break; case funkier.Maybe: console.log('Maybe:'); console.log(''); console.log('The Maybe type encapsulates the idea of sentinel values returned by functions to represent an error or unusual'); console.log('conditions. Authors can return an instance of the Just constructor when a function executes successfully, and the'); console.log('Nothing object when an error occurs, or the computation is otherwise unsuccessful.'); console.log(''); console.log('Usage: var x = Maybe()'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#maybe'); break; case funkier.Nothing: console.log('Nothing:'); console.log(''); console.log('A Nothing is a type of Maybe representing an unsuccessful computation.'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#nothing'); break; case funkier.Ok: console.log('Ok:'); console.log(''); console.log('An Ok is a type of Result representing a successful computation. The constructor is new-agnostic.'); console.log('Throws when called with no arguments.'); console.log(''); console.log('Usage: var x = Ok(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#ok'); break; case funkier.Pair: console.log('Pair:'); console.log(''); console.log('A Pair represents an immutable tuple. The constructor function takes two elements, first and second. and returns a'); console.log('new immutable tuple. The contents of the tuple can be accessed with the accessor functions fst and snd'); console.log('respectively. The constructor is new-agnostic.'); console.log(''); console.log('Usage: var x = Pair(a, b)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#pair'); break; case funkier.Result: console.log('Result:'); console.log(''); console.log('The Result type encapsulates the idea of functions throwing errors. It can be considered equivalent to the Either'); console.log('datatype from Haskell, or the Result type from Rust.'); console.log(''); console.log('Usage: var x = Result()'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#result'); break; case funkier.add: console.log('add:'); console.log(''); console.log('Synonyms: plus'); console.log(''); console.log('A wrapper around the addition operator.'); console.log(''); console.log('Usage: var x = add(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#add'); break; case funkier.and: console.log('and:'); console.log(''); console.log('A wrapper around the logical and (&&) operator. Returns the logical and of the given arguments'); console.log(''); console.log('Usage: var x = and(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#and'); break; case funkier.andPred: console.log('andPred:'); console.log(''); console.log('Takes two unary predicate functions, and returns a new unary function that, when called, will call the original'); console.log('functions with the given argument, and logically and their results, returning that value. Throws if either'); console.log('argument is not a function of arity 1.'); console.log(''); console.log('Usage: var x = andPred(f1, f2)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#andpred'); break; case funkier.arityOf: console.log('arityOf:'); console.log(''); console.log('Synonyms: arity'); console.log(''); console.log('Reports the real arity of a function. If the function has not been curried by funkier.js, this simply returns the'); console.log('function\'s length property. For a function that has been curried, the arity of the original function will be'); console.log('reported (the function\'s length property will always be 0 or 1 in this case). For a partially applied function,'); console.log('the amount of arguments not yet supplied will be returned.'); console.log(''); console.log('Usage: var x = arityOf(f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#arityof'); break; case funkier.asArray: console.log('asArray:'); console.log(''); console.log('Takes a pair, and returns a 2-element array containing the values contained in the given pair p. Specifically, if'); console.log('the resulting array is named arr, then we have arr[0] === fst(p) and arr[1] === snd(p). Throws a TypeError if p is'); console.log('not a pair.'); console.log(''); console.log('Usage: var x = asArray(p)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#asarray'); break; case funkier.bind: console.log('bind:'); console.log(''); console.log('Synonyms: bindWithContext'); console.log(''); console.log('Given an object and function, returns a curried function with the same arity as the original, and whose execution'); console.log('context is permanently bound to the supplied object. The function will be called when sufficient arguments have'); console.log('been supplied. Superfluous arguments are discarded. It is possible to partially apply the resulting function, and'); console.log('indeed the further resulting function(s). The resulting function and its partial applications will throw if they'); console.log('require at least one argument, but are invoked without any. `bind` throws if the first parameter is not an'); console.log('an acceptable type for an execution context, or if the last parameter is not a function.'); console.log(''); console.log('Usage: var x = bind(ctx, f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#bind'); break; case funkier.bindWithContextAndArity: console.log('bindWithContextAndArity:'); console.log(''); console.log('Given an arity, object and function, returns a curried function whose execution context is permanently bound to'); console.log('the supplied object, and whose arity equals the arity given. The supplied arity need not equal the function\'s'); console.log('length. The function will be only called when the specified number of arguments have been supplied. Superfluous'); console.log('arguments are discarded. It is possible to partially apply the resulting function, and indeed the further'); console.log('resulting function(s). The resulting function and its partial applications will throw if they require at least'); console.log('one argument, but are invoked without any. `bindWithContextAndArity` throws if the arity is not a natural'); console.log('number, if the second parameter is not an acceptable type for an execution context, or if the last parameter is'); console.log('not a function.'); console.log(''); console.log('Usage: var x = bindWithContextAndArity(n, ctx, f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#bindwithcontextandarity'); break; case funkier.bitwiseAnd: console.log('bitwiseAnd:'); console.log(''); console.log('A wrapper around the bitwise and (&) operator.'); console.log(''); console.log('Usage: var x = bitwiseAnd(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#bitwiseand'); break; case funkier.bitwiseNot: console.log('bitwiseNot:'); console.log(''); console.log('A wrapper around the bitwise not (~) operator.'); console.log(''); console.log('Usage: var x = bitwiseNot(x)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#bitwisenot'); break; case funkier.bitwiseOr: console.log('bitwiseOr:'); console.log(''); console.log('A wrapper around the bitwise or (&) operator.'); console.log(''); console.log('Usage: var x = bitwiseOr(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#bitwiseor'); break; case funkier.bitwiseXor: console.log('bitwiseXor:'); console.log(''); console.log('A wrapper around the bitwise xor (^) operator.'); console.log(''); console.log('Usage: var x = bitwiseXor(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#bitwisexor'); break; case funkier.compose: console.log('compose:'); console.log(''); console.log('Composes the two functions, returning a new function that consumes one argument, which is passed to `g`. The result'); console.log('of that call is then passed to `f`. That result is then returned. Throws if either parameter is not a function, or'); console.log('has arity 0.'); console.log(''); console.log('Usage: var x = compose(f, g)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#compose'); break; case funkier.composeMany: console.log('composeMany:'); console.log(''); console.log('Repeatedly composes the given array of functions, from right to left. All functions are curried where necessary.'); console.log('Functions are curried from right to left. Throws an Error if any array member is not a function, if it has arity'); console.log('zero, or if the value supplied is not an array.'); console.log(''); console.log('Usage: var x = composeMany(fns)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#composemany'); break; case funkier.composeOn: console.log('composeOn:'); console.log(''); console.log('Composes the two functions, returning a new function that consumes the specified number of arguments, which are'); console.log('then passed to `g`. The result of that call is then passed to `f`. That result is then returned. Throws if the'); console.log('first parameter is not an integer greater than zero, if either parameter is not a function, or if either parameter'); console.log('has arity 0.'); console.log(''); console.log('Usage: var x = composeOn(argCount, f, g)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#composeon'); break; case funkier.constant: console.log('constant:'); console.log(''); console.log('Intended to be partially applied, first taking a value, returning a function that takes another parameter'); console.log('and which always returns the first value.'); console.log(''); console.log('Usage: var x = constant(a, b)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#constant'); break; case funkier.constant0: console.log('constant0:'); console.log(''); console.log('Returns a function of arity zero that when called always returns the supplied value.'); console.log(''); console.log('Usage: var x = constant0(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#constant0'); break; case funkier.curry: console.log('curry:'); console.log(''); console.log('Curries the given function f, returning a function which accepts the same number of arguments as the original'); console.log('function\'s length property, but which may be partially applied. The function can be partially applied by passing'); console.log('arguments one at a time, or by passing several arguments at once. The function can also be called with more'); console.log('arguments than the given function\'s length, but the superfluous arguments will be ignored, and will not be'); console.log('passed to the original function. If the curried function or any subsequent partial applications require at least'); console.log('one argument, then calling the function with no arguments will throw. `curry` throws if its argument is not a'); console.log('function. It will also throw if the function is known to be bound to a specific execution context.'); console.log(''); console.log('Usage: var x = curry(f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#curry'); break; case funkier.curryWithArity: console.log('curryWithArity:'); console.log(''); console.log('Curries the given function f to the supplied arity, which need not equal the function\'s length. The function will'); console.log('be called when that number of arguments have been supplied. Superfluous arguments are discarded. The original'); console.log('function will be called with a null execution context. It is possible to partially apply the resulting function,'); console.log('and indeed the further resulting function(s). The resulting function and its partial applications will throw if'); console.log('they require at least one argument, but are invoked without any. `curryWithArity` throws if the arity is not a'); console.log('natural number, or if the second parameter is not a function. It will also throw if the given function is known'); console.log('to be bound to a specific execution context.'); console.log(''); console.log('Usage: var x = curryWithArity(n, f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#currywitharity'); break; case funkier.deepEqual: console.log('deepEqual:'); console.log(''); console.log('Synonyms: deepEquals'); console.log(''); console.log('Check two values for deep equality. Deep equality holds if any of the following if the two values are the same'); console.log('object, if both values are objects with the same object, the same prototype, the same enumerable properties'); console.log('and those properties are themselves deeply equal (non-enumerable properties are not checked), or if both values'); console.log('are arrays with the same length, any additional properties installed on the arrays are deeply equal, and the items'); console.log('at each index are themselves deeply equal.'); console.log(''); console.log('Usage: var x = deepEqual(a, b)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#deepequal'); break; case funkier.div: console.log('div:'); console.log(''); console.log('Returns the quotient on dividing x by y.'); console.log(''); console.log('Usage: var x = div(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#div'); break; case funkier.divide: console.log('divide:'); console.log(''); console.log('A wrapper around the division operator.'); console.log(''); console.log('Usage: var x = divide(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#divide'); break; case funkier.either: console.log('either:'); console.log(''); console.log('Takes two functions of arity 1 or greater, and a Result. If the Result is an Ok value, the first function f1 will'); console.log('be called with the unwrapped value. Otherwise, if the Result is an Err value, the second function is called'); console.log('with the unwrapped value. In either case, the result of of the called function is returned.'); console.log(''); console.log('Usage: var x = either(f1, f2, r)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#either'); break; case funkier.equals: console.log('equals:'); console.log(''); console.log('A wrapper around the non-strict equality (==) operator.'); console.log(''); console.log('Usage: var x = equals(a, b)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#equals'); break; case funkier.even: console.log('even:'); console.log(''); console.log('Given a number, returns true if it is divisible by 2, and false otherwise.'); console.log(''); console.log('Usage: var x = even(x)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#even'); break; case funkier.exp: console.log('exp:'); console.log(''); console.log('Synonyms: pow'); console.log(''); console.log('A curried wrapper around Math.pow.'); console.log(''); console.log('Usage: var x = exp(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#exp'); break; case funkier.flip: console.log('flip:'); console.log(''); console.log('Takes a binary function f, and returns a curried function that takes the arguments in the opposite order.'); console.log(''); console.log('Usage: var x = flip(f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#flip'); break; case funkier.fst: console.log('fst:'); console.log(''); console.log('Synonyms: first'); console.log(''); console.log('Accessor function for pair tuples. Returns the first value that was supplied to the pair constructor. Throws if'); console.log('called with a non-pair value.'); console.log(''); console.log('Usage: var x = fst(p)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#fst'); break; case funkier.getErrValue: console.log('getErrValue:'); console.log(''); console.log('Returns the value wrapped by the given Err instance e. Throws a TypeError if called with anything other than an'); console.log('Err.'); console.log(''); console.log('Usage: var x = getErrValue(e)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#geterrvalue'); break; case funkier.getJustValue: console.log('getJustValue:'); console.log(''); console.log('Returns the value wrapped by the given Just instance j. Throws a TypeError if called with anything other than a'); console.log('Just.'); console.log(''); console.log('Usage: var x = getJustValue(j)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#getjustvalue'); break; case funkier.getOkValue: console.log('getOkValue:'); console.log(''); console.log('Returns the value wrapped by the given Ok instance o. Throws a TypeError if called with anything other than an'); console.log('Ok.'); console.log(''); console.log('Usage: var x = getOkValue(o)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#getokvalue'); break; case funkier.getType: console.log('getType:'); console.log(''); console.log('A functional wrapper around the typeof operator. Takes any Javascript value, and returns a string representing'); console.log('the object"s type: the result will be one of "number", "string", "boolean", "function", "undefined", or "object".'); console.log(''); console.log('Usage: var x = getType(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#gettype'); break; case funkier.greaterThan: console.log('greaterThan:'); console.log(''); console.log('Synonyms: gt'); console.log(''); console.log('A wrapper around the less than or equal (<=) operator.'); console.log(''); console.log('Usage: var x = greaterThan(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#greaterthan'); break; case funkier.greaterThanEqual: console.log('greaterThanEqual:'); console.log(''); console.log('Synonyms: gte'); console.log(''); console.log('A wrapper around the greater than or equal (=>) operator.'); console.log(''); console.log('Usage: var x = greaterThanEqual(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#greaterthanequal'); break; case funkier.id: console.log('id:'); console.log(''); console.log('Returns the supplied value. Superfluous values are ignored.'); console.log(''); console.log('Usage: var x = id(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#id'); break; case funkier.is: console.log('is:'); console.log(''); console.log('Synonyms: hasType'); console.log(''); console.log('Given a string that could be returned by the `typeof` operator, and a value, returns true if typeof the given'); console.log('object equals the given string. Throws if the first argument is not a string.'); console.log(''); console.log('Usage: var x = is(type, value)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#is'); break; case funkier.isArray: console.log('isArray:'); console.log(''); console.log('Returns true if the given value is an array, false otherwise'); console.log(''); console.log('Usage: var x = isArray(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isarray'); break; case funkier.isBoolean: console.log('isBoolean:'); console.log(''); console.log('Returns true if typeof the given value equals "boolean", false otherwise.'); console.log(''); console.log('Usage: var x = isBoolean(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isboolean'); break; case funkier.isErr: console.log('isErr:'); console.log(''); console.log('Returns true when the given value is a Err object, and false otherwise.'); console.log(''); console.log('Usage: var x = isErr(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#iserr'); break; case funkier.isJust: console.log('isJust:'); console.log(''); console.log('Returns true if the given value is a Just object, and false otherwise.'); console.log(''); console.log('Usage: var x = isJust(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isjust'); break; case funkier.isMaybe: console.log('isMaybe:'); console.log(''); console.log('Returns true when the given value is a Maybe object, and false otherwise.'); console.log(''); console.log('Usage: var x = isMaybe(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#ismaybe'); break; case funkier.isNothing: console.log('isNothing:'); console.log(''); console.log('Returns true if the given value is the Nothing object, and false otherwise.'); console.log(''); console.log('Usage: var x = isNothing(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isnothing'); break; case funkier.isNull: console.log('isNull:'); console.log(''); console.log('Returns true if the given object is null, false otherwise'); console.log(''); console.log('Usage: var x = isNull(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isnull'); break; case funkier.isNumber: console.log('isNumber:'); console.log(''); console.log('Returns true if typeof the given value equals "number", false otherwise.'); console.log(''); console.log('Usage: var x = isNumber(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isnumber'); break; case funkier.isObject: console.log('isObject:'); console.log(''); console.log('Returns true if typeof the given value equals "object", false otherwise.'); console.log(''); console.log('Usage: var x = isObject(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isobject'); break; case funkier.isOk: console.log('isOk:'); console.log(''); console.log('Returns true when the given value is a Ok object, and false otherwise.'); console.log(''); console.log('Usage: var x = isOk(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isok'); break; case funkier.isPair: console.log('isPair:'); console.log(''); console.log('Returns true if the given value is a Pair, and false otherwise.'); console.log(''); console.log('Usage: var x = isPair(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#ispair'); break; case funkier.isRealObject: console.log('isRealObject:'); console.log(''); console.log('Returns true if the value is a *real* Javascript object, i.e. an object for which `funkierJS.isObject(a) === true`'); console.log('and `funkierJS.isNull(a) === false` and `funkierJS.isArray(a) === false`.'); console.log(''); console.log('Usage: var x = isRealObject(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isrealobject'); break; case funkier.isResult: console.log('isResult:'); console.log(''); console.log('Returns true when the given value is a Result object, and false otherwise.'); console.log(''); console.log('Usage: var x = isResult(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isresult'); break; case funkier.isString: console.log('isString:'); console.log(''); console.log('Returns true if typeof the given value equals "string", false otherwise.'); console.log(''); console.log('Usage: var x = isString(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isstring'); break; case funkier.isUndefined: console.log('isUndefined:'); console.log(''); console.log('Returns true if typeof the given value equals "undefined", false otherwise.'); console.log(''); console.log('Usage: var x = isUndefined(a)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#isundefined'); break; case funkier.leftShift: console.log('leftShift:'); console.log(''); console.log('A wrapper around the left shift (<<) operator.'); console.log(''); console.log('Usage: var x = leftShift(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#leftshift'); break; case funkier.lessThan: console.log('lessThan:'); console.log(''); console.log('Synonyms: lt'); console.log(''); console.log('A wrapper around the less than (<) operator.'); console.log(''); console.log('Usage: var x = lessThan(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#lessthan'); break; case funkier.lessThanEqual: console.log('lessThanEqual:'); console.log(''); console.log('Synonyms: lte'); console.log(''); console.log('A wrapper around the less than or equal (<=) operator.'); console.log(''); console.log('Usage: var x = lessThanEqual(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#lessthanequal'); break; case funkier.log: console.log('log:'); console.log(''); console.log('Returns the logarithm of y in the given base x. Note that this function uses the change of base formula, so may'); console.log('be subject to rounding errors.'); console.log(''); console.log('Usage: var x = log(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#log'); break; case funkier.makeMaybeReturner: console.log('makeMaybeReturner:'); console.log(''); console.log('Takes a function f. Returns a new function with the same arity as f. When called, the new function calls the'); console.log('original. If the function f throws during execution, then the Nothing object is returned. Otherwise the result of'); console.log('the function is wrapped in a Just and returned.'); console.log(''); console.log('Usage: var x = makeMaybeReturner(f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#makemaybereturner'); break; case funkier.makeResultReturner: console.log('makeResultReturner:'); console.log(''); console.log('Takes a function f. Returns a new function with the same arity as f. When called, the new function calls the'); console.log('original. If the function f throws during execution, then the exception will be caught, and an Err object'); console.log('wrapping the exception is returned. Otherwise the result of the function is wrapped in an Ok and returned.'); console.log(''); console.log('Usage: var x = makeResultReturner(f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#makeresultreturner'); break; case funkier.max: console.log('max:'); console.log(''); console.log('A curried wrapper around Math.max. Takes exactly two arguments.'); console.log(''); console.log('Usage: var x = max(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#max'); break; case funkier.min: console.log('min:'); console.log(''); console.log('A curried wrapper around Math.min. Takes exactly two arguments.'); console.log(''); console.log('Usage: var x = min(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#min'); break; case funkier.multiply: console.log('multiply:'); console.log(''); console.log('A wrapper around the multiplication operator.'); console.log(''); console.log('Usage: var x = multiply(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#multiply'); break; case funkier.not: console.log('not:'); console.log(''); console.log('A wrapper around the logical not (!) operator. Returns the logical negation of the given argument.'); console.log(''); console.log('Usage: var x = not(b)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#not'); break; case funkier.notEqual: console.log('notEqual:'); console.log(''); console.log('Synonyms: notEquals'); console.log(''); console.log('A wrapper around the inequality (!=) operator.'); console.log(''); console.log('Usage: var x = notEqual(a, b)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#notequal'); break; case funkier.notPred: console.log('notPred:'); console.log(''); console.log('Takes a unary predicate function, and returns a new unary function that, when called, will call the original'); console.log('function with the given argument, and return the negated result. Throws if f is not a function, or has an'); console.log('arity other than 1.'); console.log(''); console.log('Usage: var x = notPred(f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#notpred'); break; case funkier.objectCurry: console.log('objectCurry:'); console.log(''); console.log('Given a function, returns a curried function which calls the underlying with the execution context active when the'); console.log('first arguments are supplied. This means that when partially applying the function, the resulting functions will'); console.log('have their execution context permanently bound. This method of binding is designed for currying functions that'); console.log('exist on an object\'s prototype. The function will be only called when sufficient arguments have been supplied.'); console.log('Superfluous arguments are discarded. The resulting function and its partial applications will throw if they'); console.log('require at least one argument, but are invoked without any. `objectCurry` throws if its parameter is not a'); console.log('function. The resulting function will throw if invoked with an undefined execution context.'); console.log(''); console.log('Usage: var x = objectCurry(f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#objectcurry'); break; case funkier.objectCurryWithArity: console.log('objectCurryWithArity:'); console.log(''); console.log('Given an arity and function, returns a curried function which calls the underlying with the execution context'); console.log('active when the first arguments are supplied. This means that when partially applying the function, the'); console.log('resulting functions will have their execution context permanently bound. This method of binding is designed for'); console.log('currying functions that exist on an object\'s prototype. The function will be only called when the specified number'); console.log('of arguments have been supplied. Superfluous arguments are discarded. The resulting function and its partial'); console.log('applications throw if they require at least one argument, but are invoked without any. `objectCurryWithArity`'); console.log('throws if the arity is not a natural number or if the second parameter is not a function. The resulting function'); console.log('will throw if invoked with an undefined execution context.'); console.log(''); console.log('Usage: var x = objectCurryWithArity(n, f)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#objectcurrywitharity'); break; case funkier.odd: console.log('odd:'); console.log(''); console.log('Given a number, returns true if it is not divisible by 2, and false otherwise.'); console.log(''); console.log('Usage: var x = odd(x)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#odd'); break; case funkier.or: console.log('or:'); console.log(''); console.log('A wrapper around the logical or (||) operator. Returns the logical or of the given arguments'); console.log(''); console.log('Usage: var x = or(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#or'); break; case funkier.orPred: console.log('orPred:'); console.log(''); console.log('Takes two unary predicate functions, and returns a new unary function that, when called, will call the original'); console.log('functions with the given argument, and logically or their results, returning that value. Throws if either'); console.log('argument is not a function of arity 1.'); console.log(''); console.log('Usage: var x = orPred(f1, f2)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#orpred'); break; case funkier.rem: console.log('rem:'); console.log(''); console.log('A wrapper around the remainder (%) operator.'); console.log(''); console.log('Usage: var x = rem(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#rem'); break; case funkier.rightShift: console.log('rightShift:'); console.log(''); console.log('A wrapper around the right shift (>>) operator.'); console.log(''); console.log('Usage: var x = rightShift(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#rightshift'); break; case funkier.rightShiftZero: console.log('rightShiftZero:'); console.log(''); console.log('A wrapper around the left shift (>>>) operator.'); console.log(''); console.log('Usage: var x = rightShiftZero(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#rightshiftzero'); break; case funkier.sectionLeft: console.log('sectionLeft:'); console.log(''); console.log('Partially applies the binary function f with the given argument x, with x being supplied as the first argument'); console.log('to f. The given function f will be curried if necessary. Throws if f is not a binary function.'); console.log(''); console.log('Usage: var x = sectionLeft(f, x)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#sectionleft'); break; case funkier.sectionRight: console.log('sectionRight:'); console.log(''); console.log('Partially applies the binary function f with the given argument x, with x being supplied as the second argument'); console.log('to f. The given function f will be curried if necessary. Throws if f is not a binary function.'); console.log(''); console.log('Usage: var x = sectionRight(f, x)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#sectionright'); break; case funkier.snd: console.log('snd:'); console.log(''); console.log('Synonyms: second'); console.log(''); console.log('Accessor function for pair tuples. Returns the second value that was supplied to the pair constructor. Throws if'); console.log('called with a non-pair value.'); console.log(''); console.log('Usage: var x = snd(p)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#snd'); break; case funkier.strictEquals: console.log('strictEquals:'); console.log(''); console.log('A wrapper around the strict equality (===) operator.'); console.log(''); console.log('Usage: var x = strictEquals(a, b)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#strictequals'); break; case funkier.strictNotEqual: console.log('strictNotEqual:'); console.log(''); console.log('Synonyms: strictNotEquals, strictInequality'); console.log(''); console.log('A wrapper around the strict inequality (!==) operator.'); console.log(''); console.log('Usage: var x = strictNotEqual(a, b)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#strictnotequal'); break; case funkier.subtract: console.log('subtract:'); console.log(''); console.log('A wrapper around the subtraction operator.'); console.log(''); console.log('Usage: var x = subtract(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#subtract'); break; case funkier.xor: console.log('xor:'); console.log(''); console.log('A wrapper around the logical xor operator. Returns the logical xor of the given arguments'); console.log(''); console.log('Usage: var x = xor(x, y)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#xor'); break; case funkier.xorPred: console.log('xorPred:'); console.log(''); console.log('Takes two unary predicate functions, and returns a new unary function that, when called, will call the original'); console.log('functions with the given argument, and logically xor their results, returning that value. Throws if either'); console.log('argument is not a function of arity 1.'); console.log(''); console.log('Usage: var x = xorPred(f1, f2)'); console.log(''); console.log('See https://graememcc.github.io/funkierJS/docs/index.html#xorpred'); break; default: console.log('No help available'); } }; funkier.help = helpFn; }; })(); },{}],12:[function(require,module,exports){ module.exports = (function() { "use strict"; /* checkIntegral: Takes a value and an optional options object. In the following circumstances it will return * the supplied value (coerced to an integer if necessary): * - The value is an integer. * - The value can be coerced to an integer, and the options object does not contain a property * named "strict" that coerces to true. * * For all other values, a TypeError will be thrown. The message of the TypeError can be specified * by including an "errorMessage" property in the options object. * */ var checkIntegral = function(n, options) { options = options || {}; var message = options.errorMessage || 'Value is not an integer'; if (options.strict && typeof(n) !== 'number') throw new TypeError(message); n = n - 0; if (isNaN(n) || !isFinite(n)) throw new TypeError(message); if (n !== Math.round(n)) throw new TypeError(message); return n; }; /* checkPositiveIntegral: Takes a value and an optional options object. In the following circumstances it will return * the supplied value (coerced to an integer if necessary): * - The value is a positive integer. * - The value can be coerced to a positive integer, and the options object does not contain * a property named "strict" that coerces to true. * * For all other values, a TypeError will be thrown. The message of the TypeError can be * specified by including an "errorMessage" property in the options object. * */ var checkPositiveIntegral = function(n, options) { options = options || {}; var message = options.errorMessage || 'Value is not a positive integer'; // Don't mutate the supplied options var newOptions = Object.create(options); newOptions.errorMessage = message; n = checkIntegral(n, newOptions); if (n < 0) throw new TypeError(message); return n; }; /* * isArrayLike: returns true if the given value is a string, array, or 'array-like', and false otherwise. * Takes an optional 'noStrings' argument: strings will not be considered 'array-like' when * this is true. * */ var isArrayLike = function(v, noStrings) { noStrings = noStrings || false; if (typeof(v) === 'string') return !noStrings; if (typeof(v) !== 'object' || v === null) return false; if (Array.isArray(v)) return true; if (!v.hasOwnProperty('length')) return false; var l = v.length; return l === 0 || (v.hasOwnProperty('0') && v.hasOwnProperty('' + (l - 1))); }; /* * valueStringifier: Returns a string representation of the given value. * */ var valueStringifier = function(v) { switch (typeof(v)) { case 'number': case 'boolean': case 'undefined': return '' + v; case 'string': return '\'' + v + '\''; case 'function': return v.toString(); case 'object': if (v === null) return 'null'; if (Array.isArray(v)) return '[' + v.join(', ') + ']'; return '{' + v.toString() + '}'; default: return v.toString(); } }; return { checkIntegral: checkIntegral, checkPositiveIntegral: checkPositiveIntegral, isArrayLike: isArrayLike, valueStringifier: valueStringifier }; })(); //(function() { // // Double scope: we want this code to execute in a non-strict environment where this points to the global // var global = this; // // // return function() { // "use strict"; // // // /* // * A collection of internal utilities. Not exported to consumers. // * // */ // // // var makeModule = function(require, exports) { // /* // * isObjectLike: returns true if the given value is a string, array, function, or object, // * and false otherwise. // * // */ // // var isObjectLike = function(v, options) { // options = options || {}; // var strict = options.strict || false; // var allowNull = options.allowNull || false; // // var acceptable = strict ? ['object'] : ['string', 'function', 'object']; // if (strict && Array.isArray(v)) // return false; // // return (v === null && allowNull) || (v !== null && acceptable.indexOf(typeof(v)) !== -1); // }; // // // /* checkObjectLike: takes a value and throws if it is not object-like, otherwise return a copy. // * // */ // // var checkObjectLike = function(v, options) { // options = options || {}; // var message = options.message || 'Value is not an object'; // var allowNull = options.allowNull || false; // // if (!isObjectLike(v, options)) // throw new TypeError(message); // // return v; // }; // // // /* checkArrayLike: takes a value and throws if it is not array-like, otherwise // * return a copy. // * // */ // // var checkArrayLike = function(v, options) { // options = options || {}; // var message = options.message || 'Value is not a string or array'; // // if (!isArrayLike(v, options.noStrings)) // throw new TypeError(message); // // // We allow an optional 'dontSlice' option for arrays and arraylikes. For example, // // when implementing length, there is no need to copy the object, we can just read // // the property // if (typeof(v) === 'string' || ('dontSlice' in options && options.dontSlice)) // return v; // // return [].slice.call(v); // }; // // // var exported = { // checkArrayLike: checkArrayLike, // checkIntegral: checkIntegral, // checkObjectLike: checkObjectLike, // checkPositiveIntegral: checkPositiveIntegral, // isArrayLike: isArrayLike, // isObjectLike: isObjectLike, // valueStringifier: valueStringifier // }; // // // module.exports = exported; // }; // // // // AMD/CommonJS foo // if (typeof(define) === "function") { // define(function(require, exports, module) { // makeModule(require, exports, module); // }); // } else { // makeModule(require, exports, module); // } // }(); //})(); },{}]},{},[10])(10) });
{ "content_hash": "d0b6ec8eac5fa58402b0b648782a8b4e", "timestamp": "", "source": "github", "line_count": 4540, "max_line_length": 849, "avg_line_length": 32.23590308370044, "alnum_prop": 0.6211095243626623, "repo_name": "graememcc/funkierJS", "id": "3a9174f868fbf83086bf790ccbb547da4522ec9c", "size": "146375", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "dest/funkierJS.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9005" }, { "name": "HTML", "bytes": "1559548" }, { "name": "JavaScript", "bytes": "3700323" } ], "symlink_target": "" }
This application makes use of the following third party libraries: ## AFNetworking Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## FLEX Copyright (c) 2014, Flipboard All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Flipboard nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## JGProgressHUD The MIT License (MIT) Copyright (c) 2014 Jonas Gessner Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Mantle **Copyright (c) 2012 - 2014, GitHub, Inc.** **All rights reserved.** Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --- **This project uses portions of code from the Proton framework.** **Proton is copyright (c) 2012, Bitswift, Inc.** **All rights reserved.** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Neither the name of the Bitswift, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ## PureLayout This code is distributed under the terms and conditions of the MIT license. Copyright (c) 2014 Tyler Fox Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## SWRevealViewController Copyright (c) 2013 Joan Lluch <joan.lluch@sweetwilliamsl.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Early code inspired on a similar class by Philip Kluz (Philip.Kluz@zuui.org) Generated by CocoaPods - http://cocoapods.org
{ "content_hash": "f156ae8d5cd6c66c2b8598b42b96d2c3", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 755, "avg_line_length": 61.248226950354606, "alnum_prop": 0.7999073645206114, "repo_name": "kiokoo/YaleMobile", "id": "9a4a355a47bad81cacee29875b6486c9514918bd", "size": "8655", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pods/Pods-acknowledgements.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "480237" }, { "name": "Ruby", "bytes": "186" } ], "symlink_target": "" }
import sys from typing import Generator import pytest try: from pytest import CallInfo, Config, Parser, TestReport # type: ignore except ImportError: # For pytest < 7.0.0 from _pytest.config import Config from _pytest.config.argparsing import Parser from _pytest.reports import TestReport from _pytest.runner import CallInfo from pytest import Item from pytest_testdox import constants, terminal def pytest_addoption(parser: Parser): group = parser.getgroup('terminal reporting', 'reporting', after='general') group.addoption( '--testdox', action='store_true', dest='testdox', default=False, help='Report test progress in testdox format', ) group.addoption( '--force-testdox', action='store_true', dest='force_testdox', default=False, help='Force testdox output even when not in real terminal', ) parser.addini( 'testdox_format', help='TestDox report format (plaintext|utf8)', default='utf8', ) def should_enable_plugin(config: Config): return ( config.option.testdox and sys.stdout.isatty() ) or config.option.force_testdox @pytest.mark.trylast def pytest_configure(config: Config): config.addinivalue_line( "markers", "{}(title): Override testdox report test title".format( constants.TITLE_MARK ), ) config.addinivalue_line( "markers", "{}(title): Override testdox report class title".format( constants.CLASS_NAME_MARK ), ) if should_enable_plugin(config): # Get the standard terminal reporter plugin and replace it with ours standard_reporter = config.pluginmanager.getplugin('terminalreporter') testdox_reporter = terminal.TestdoxTerminalReporter( standard_reporter.config ) config.pluginmanager.unregister(standard_reporter) config.pluginmanager.register(testdox_reporter, 'terminalreporter') @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport( item: Item, call: CallInfo ) -> Generator[None, TestReport, None]: result = yield report = result.get_result() testdox_title = next( ( mark.args[0] for mark in item.iter_markers(name=constants.TITLE_MARK) ), None, ) testdox_class_name = next( ( mark.args[0] for mark in item.iter_markers(name=constants.CLASS_NAME_MARK) ), None, ) if testdox_title: report.testdox_title = testdox_title if testdox_class_name: report.testdox_class_name = testdox_class_name
{ "content_hash": "74e17d2bcaec1add254316bf0c41a573", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 79, "avg_line_length": 27.333333333333332, "alnum_prop": 0.6382113821138211, "repo_name": "renanivo/pytest-testdox", "id": "3adf08c6a4b46fd13c52a0457b5c7eb525cce82b", "size": "2706", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pytest_testdox/plugin.py", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "610" }, { "name": "Python", "bytes": "32291" } ], "symlink_target": "" }
package alluxio.security.authentication; import alluxio.conf.Configuration; import alluxio.conf.InstancedConfiguration; import alluxio.conf.PropertyKey; import alluxio.exception.status.UnauthenticatedException; import alluxio.grpc.GrpcChannel; import alluxio.grpc.GrpcChannelBuilder; import alluxio.grpc.GrpcServer; import alluxio.grpc.GrpcServerAddress; import alluxio.grpc.GrpcServerBuilder; import alluxio.security.User; import alluxio.security.user.UserState; import alluxio.util.CommonUtils; import alluxio.util.WaitForOptions; import alluxio.util.network.NetworkAddressUtils; import org.hamcrest.core.StringStartsWith; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.net.InetSocketAddress; import java.util.UUID; import javax.security.auth.Subject; import javax.security.sasl.AuthenticationException; /** * Unit test for {@link alluxio.grpc.GrpcChannelBuilder} and {@link alluxio.grpc.GrpcServerBuilder}. */ public class GrpcSecurityTest { /** Timeout waiting for a closed stream. */ private static final int S_AUTHENTICATION_PROPOGATE_TIMEOUT = 30000; /** * The exception expected to be thrown. */ @Rule public ExpectedException mThrown = ExpectedException.none(); private InstancedConfiguration mConfiguration; @Before public void before() { mConfiguration = Configuration.copyGlobal(); } @Test public void testServerUnsupportedAuthentication() { mThrown.expect(RuntimeException.class); mThrown.expectMessage(new StringStartsWith(false, "No factory could create a UserState with authType: " + AuthType.KERBEROS.name())); createServer(AuthType.KERBEROS); } @Test public void testSimpleAuthentication() throws Exception { GrpcServer server = createServer(AuthType.SIMPLE); try { server.start(); UserState us = UserState.Factory.create(mConfiguration); GrpcChannelBuilder channelBuilder = GrpcChannelBuilder .newBuilder(getServerConnectAddress(server), mConfiguration).setSubject(us.getSubject()); channelBuilder.build(); } finally { server.shutdown(); } } @Test public void testNoSaslAuthentication() throws Exception { GrpcServer server = createServer(AuthType.NOSASL); try { server.start(); GrpcChannelBuilder channelBuilder = GrpcChannelBuilder.newBuilder(getServerConnectAddress(server), mConfiguration); channelBuilder.build(); } finally { server.shutdown(); } } @Test public void testCustomAuthentication() throws Exception { mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.CUSTOM); mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_CUSTOM_PROVIDER_CLASS, ExactlyMatchAuthenticationProvider.class.getName()); GrpcServer server = createServer(AuthType.CUSTOM); try { server.start(); GrpcChannelBuilder channelBuilder = GrpcChannelBuilder.newBuilder(getServerConnectAddress(server), mConfiguration); channelBuilder.setSubject(createSubject(ExactlyMatchAuthenticationProvider.USERNAME, ExactlyMatchAuthenticationProvider.PASSWORD)).build(); } finally { server.shutdown(); } } @Test public void testCustomAuthenticationFails() throws Exception { mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.CUSTOM); mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_CUSTOM_PROVIDER_CLASS, ExactlyMatchAuthenticationProvider.class.getName()); GrpcServer server = createServer(AuthType.CUSTOM); try { server.start(); GrpcChannelBuilder channelBuilder = GrpcChannelBuilder.newBuilder(getServerConnectAddress(server), mConfiguration); mThrown.expect(UnauthenticatedException.class); channelBuilder.setSubject(createSubject("fail", "fail")).build(); } finally { server.shutdown(); } } @Test public void testDisabledAuthentication() throws Exception { GrpcServer server = createServer(AuthType.SIMPLE); try { server.start(); GrpcChannelBuilder channelBuilder = GrpcChannelBuilder.newBuilder(getServerConnectAddress(server), mConfiguration); channelBuilder.disableAuthentication().build(); } finally { server.shutdown(); } } @Test public void testAuthMismatch() throws Exception { GrpcServer server = createServer(AuthType.NOSASL); try { server.start(); mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE); GrpcChannelBuilder channelBuilder = GrpcChannelBuilder.newBuilder(getServerConnectAddress(server), mConfiguration); mThrown.expect(UnauthenticatedException.class); channelBuilder.build(); } finally { server.shutdown(); } } @Test public void testAuthenticationClosed() throws Exception { mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE); GrpcServer server = createServer(AuthType.SIMPLE); try { server.start(); UserState us = UserState.Factory.create(mConfiguration); GrpcChannel channel = GrpcChannelBuilder.newBuilder(getServerConnectAddress(server), mConfiguration) .setSubject(us.getSubject()).build(); // Grab internal channel-Id. UUID channelId = channel.getChannelKey().getChannelId(); // Assert that authentication server has a login info for the channel. Assert.assertNotNull(server.getAuthenticationServer().getUserInfoForChannel(channelId)); // Shutdown channel. channel.shutdown(); // Assert that authentication server doesn't contain login info for the channel anymore. // Wait in a loop. Because closing the authentication will propagate asynchronously. CommonUtils.waitFor("login state removed", () -> { try { server.getAuthenticationServer().getUserInfoForChannel(channelId); return false; } catch (UnauthenticatedException exc) { return true; } }, WaitForOptions.defaults().setTimeoutMs(S_AUTHENTICATION_PROPOGATE_TIMEOUT)); } finally { server.shutdown(); } } @Test public void testAuthenticationRevoked() throws Exception { mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, AuthType.SIMPLE); mConfiguration.set(PropertyKey.AUTHENTICATION_INACTIVE_CHANNEL_REAUTHENTICATE_PERIOD, "250ms"); GrpcServer server = createServer(AuthType.SIMPLE); try { server.start(); UserState us = UserState.Factory.create(mConfiguration); GrpcChannel channel = GrpcChannelBuilder.newBuilder(getServerConnectAddress(server), mConfiguration) .setSubject(us.getSubject()).build(); Assert.assertTrue(channel.isHealthy()); /* * Sleeping will ensure that authentication sessions for the channel will expire on the * server. This should have propagated back to the client and its health status should reflect * that. * * Sleep more than authentication revocation timeout. */ Thread.sleep(500); Assert.assertFalse(channel.isHealthy()); } finally { server.shutdown(); } } private GrpcServerAddress getServerConnectAddress(GrpcServer server) { return GrpcServerAddress.create(new InetSocketAddress( NetworkAddressUtils.getLocalHostName( (int) mConfiguration.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS)), server.getBindPort())); } private GrpcServer createServer(AuthType authType) { mConfiguration.set(PropertyKey.SECURITY_AUTHENTICATION_TYPE, authType); InetSocketAddress bindAddress = new InetSocketAddress(NetworkAddressUtils.getLocalHostName( (int) mConfiguration.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS)), 0); UserState us = UserState.Factory.create(mConfiguration); GrpcServerBuilder serverBuilder = GrpcServerBuilder .forAddress(GrpcServerAddress.create("localhost", bindAddress), mConfiguration); return serverBuilder.build(); } private Subject createSubject(String username, String password) { Subject subject = new Subject(); subject.getPrincipals().add(new User(username)); subject.getPrivateCredentials().add(password); return subject; } /** * This customized authentication provider is used in CUSTOM mode. It authenticates the user by * verifying the specific username:password pair. */ public static class ExactlyMatchAuthenticationProvider implements AuthenticationProvider { static final String USERNAME = "alluxio"; static final String PASSWORD = "correct-password"; @Override public void authenticate(String user, String password) throws AuthenticationException { if (!user.equals(USERNAME) || !password.equals(PASSWORD)) { throw new AuthenticationException("User authentication fails"); } } } }
{ "content_hash": "8bbba5a60e730543853c7159a9e7d539", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 100, "avg_line_length": 36.32258064516129, "alnum_prop": 0.7309058614564832, "repo_name": "wwjiang007/alluxio", "id": "8b696394f1e3bd3c78cd8051c5c3bfe035968f8d", "size": "9520", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/common/src/test/java/alluxio/security/authentication/GrpcSecurityTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7326" }, { "name": "C++", "bytes": "47930" }, { "name": "Dockerfile", "bytes": "12161" }, { "name": "Go", "bytes": "290492" }, { "name": "HTML", "bytes": "3412" }, { "name": "Handlebars", "bytes": "3633" }, { "name": "Java", "bytes": "15480256" }, { "name": "JavaScript", "bytes": "9992" }, { "name": "Makefile", "bytes": "6312" }, { "name": "Mustache", "bytes": "22163" }, { "name": "Python", "bytes": "18085" }, { "name": "Roff", "bytes": "5919" }, { "name": "Ruby", "bytes": "15044" }, { "name": "SCSS", "bytes": "12027" }, { "name": "Shell", "bytes": "278579" }, { "name": "TypeScript", "bytes": "324466" } ], "symlink_target": "" }
package org.infobip.mobile.messaging.chat.core; import static org.infobip.mobile.messaging.chat.core.InAppChatWidgetMethods.handleMessageDraftSend; import static org.infobip.mobile.messaging.chat.core.InAppChatWidgetMethods.handleMessageSend; import static org.infobip.mobile.messaging.chat.core.InAppChatWidgetMethods.handleMessageWithAttachmentSend; import static org.infobip.mobile.messaging.chat.core.InAppChatWidgetMethods.sendContextualData; import static org.infobip.mobile.messaging.chat.core.InAppChatWidgetMethods.setLanguage; import static org.infobip.mobile.messaging.chat.core.InAppChatWidgetMethods.showThreadList; import static org.infobip.mobile.messaging.chat.utils.CommonUtils.isOSOlderThanKitkat; import static org.infobip.mobile.messaging.util.StringUtils.isNotBlank; import org.infobip.mobile.messaging.chat.attachments.InAppChatMobileAttachment; import org.infobip.mobile.messaging.chat.view.InAppChatWebView; import org.infobip.mobile.messaging.logging.MobileMessagingLogger; import org.infobip.mobile.messaging.util.StringUtils; public class InAppChatClientImpl implements InAppChatClient { private final InAppChatWebView webView; private static final String TAG = InAppChatClient.class.getSimpleName(); public InAppChatClientImpl(InAppChatWebView webView) { this.webView = webView; } @Override public void sendChatMessage(String message) { if (canSendMessage(message)) { String script = buildWidgetMethodInvocation(handleMessageSend.name(), message); webView.evaluateJavascriptMethod(script, null); } } @Override public void sendChatMessage(String message, InAppChatMobileAttachment attachment) { String base64UrlString = attachment.base64UrlString(); String fileName = attachment.getFileName(); // message can be null - its OK if (canSendMessage(base64UrlString)) { String script = buildWidgetMethodInvocation(handleMessageWithAttachmentSend.name(), isOSOlderThanKitkat(), message, base64UrlString, fileName); webView.evaluateJavascriptMethod(script, null); } else { MobileMessagingLogger.e("[InAppChat] can't send attachment, base64 is empty"); } } @Override public void sendInputDraft(String draft) { if (webView != null) { String script = buildWidgetMethodInvocation(handleMessageDraftSend.name(), isOSOlderThanKitkat(), draft); webView.evaluateJavascriptMethod(script, null); } } @Override public void setLanguage(String language) { if (webView != null && !language.isEmpty()) { Language supportedLanguage = Language.findLanguage(language); String script = buildWidgetMethodInvocation(setLanguage.name(), isOSOlderThanKitkat(), supportedLanguage != null ? supportedLanguage.getLocale() : language); webView.evaluateJavascriptMethod(script, null); } } @Override public void sendContextualData(String data, InAppChatMultiThreadFlag multiThreadFlag) { if (webView != null && !data.isEmpty()) { StringBuilder script = new StringBuilder(); if (isOSOlderThanKitkat()) { script.append("javascript:"); } script.append(sendContextualData.name()).append("(").append(data).append(", '").append(multiThreadFlag).append("')"); webView.evaluateJavascriptMethod(script.toString(), value -> { if (value != null) { MobileMessagingLogger.d(TAG, value); } }); } } @Override public void showThreadList() { if (webView != null) { String script = buildWidgetMethodInvocation(showThreadList.name(), isOSOlderThanKitkat()); webView.evaluateJavascriptMethod(script, null); } } private boolean canSendMessage(String message) { return webView != null && isNotBlank(message); } private String buildWidgetMethodInvocation(String methodName, String... params) { return this.buildWidgetMethodInvocation(methodName, true, params); } private String buildWidgetMethodInvocation(String methodName, boolean withPrefix, String... params) { StringBuilder builder = new StringBuilder(); if (withPrefix) { builder.append("javascript:"); } builder.append(methodName); if (params.length > 0) { String resultParamsStr = StringUtils.join("','", "('", "')", params); builder.append(resultParamsStr); } else { builder.append("()"); } return builder.toString(); } }
{ "content_hash": "b3b03589a2d767fe9d680e6daeedbe76", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 169, "avg_line_length": 41.8141592920354, "alnum_prop": 0.691005291005291, "repo_name": "infobip/mobile-messaging-sdk-android", "id": "65f733fb98f4e92b3b517359f96f30c1a4f269ac", "size": "4725", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "infobip-mobile-messaging-android-chat-sdk/src/main/java/org/infobip/mobile/messaging/chat/core/InAppChatClientImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "6123" }, { "name": "Java", "bytes": "1643631" }, { "name": "Shell", "bytes": "2447" } ], "symlink_target": "" }
#ifndef PLASMA_WORLD_H #define PLASMA_WORLD_H #include <Plasma/StdDefs.h> #if MOTION_BULLET #include <MotionBullet/Attractor/BasicAttractors.h> #include <MotionBullet/Collision/CollisionInfo.h> #include <MotionBullet/World/MotionWorld.h> #else #include <Motion/Attractor/BasicAttractors.h> #include <Motion/Collision/CollisionInfo.h> #include <Motion/World/MotionWorld.h> #endif #include <Snd/Listener.h> #include <Snd/Source.h> #include <Fusion/Core/Animator.h> #include <Fusion/Core/Core.h> #include <CGMath/Vec3.h> #include <Base/ADT/HashTable.h> #include <Base/ADT/List.h> #include <Base/ADT/Map.h> #include <Base/ADT/Vector.h> #include <Base/MT/Lock.h> #include <Base/Util/Bits.h> #include <Base/Util/RCP.h> NAMESPACE_BEGIN class Animator; class Brain; class Camera; class Command; class ContactGroupReceptor; class ContactReceptor; class DebugGeometry; class Entity; class EntityGroup; class Light; class Observer; class Probe; class Receptor; class Renderable; class RigidEntity; class Selection; class SkeletalEntity; class Stimulus; /*============================================================================== CLASS SafeSet ==============================================================================*/ template< typename T > class SafeSet { public: /*----- types -----*/ typedef Set< T > Container; /*----- methods -----*/ inline void add( const T& t ); inline void drain( Container& c ); inline void clear() { LockGuard g( _lock ); _data.clear(); } protected: /*----- data members -----*/ Container _data; Lock _lock; private: }; //class SafeSet //----------------------------------------------------------------------------- //! template< typename T> void SafeSet<T>::add( const T& t ) { LockGuard g( _lock ); _data.add( t ); } //----------------------------------------------------------------------------- //! template< typename T> void SafeSet<T>::drain( Container& c ) { Container().swap(c); // We use this trick to guarantee the memory is deallocated; c.clear() doesn't. LockGuard g( _lock ); c.swap( _data ); } /*============================================================================== CLASS World ==============================================================================*/ //! Main Container for 3D. class World: public RCObject, public VMProxy { public: /*----- types and enumerations ----*/ typedef Vector< RCP<Entity> > EntityContainer; typedef SafeSet< RCP<Entity> > EntitySet; typedef Vector< RCP<EntityGroup> > GroupContainer; typedef Vector< Light* > LightContainer; typedef Vector< Camera* > CameraContainer; typedef Vector< RCP<Selection> > SelectionContainer; typedef Vector< Command > CommandContainer; typedef Vector< RCP<Renderable> > RenderableContainer; /*============================================================================== CLASS PickingData ==============================================================================*/ class PickingData { public: /*----- types -----*/ struct Entry { Entry(): _entity(NULL) {} inline const Rayf& ray() const { return _ray; } inline bool hasHit() const { return _entity != NULL; } inline Entity* entity() { return _entity; } inline const Entity* entity() const { return _entity; } inline const Vec3f& location() const { return _location; } Rayf _ray; Entity* _entity; Vec3f _location; }; /*----- methods -----*/ PickingData( uint numRays ): _entries( numRays ) {} inline size_t size() const { return _entries.size(); } inline void resize( size_t n ) { return _entries.resize(n); } inline Entry& entry( uint i ) { return _entries[i]; } inline Vector<Entry>::ConstIterator begin() const { return _entries.begin(); } inline Vector<Entry>::ConstIterator end() const { return _entries.end(); } inline void setRay( uint idx, const Rayf& ray ) { CHECK( idx < _entries.size() ); _entries[idx]._ray = ray; } inline void print() const { StdErr << size() << " entries:" << nl; for( auto c = begin(), e = end(); c != e; ++c ) { StdErr << " ... " << (*c).ray() << " --> " << (void*)(*c).entity() << " at " << (*c).location() << nl; } } protected: /*----- data members -----*/ Vector<Entry> _entries; }; //class PickingData /*----- static methods -----*/ static void initialize(); /*----- methods -----*/ PLASMA_DLL_API World(); PLASMA_DLL_API void clear(); // Entities. PLASMA_DLL_API void addEntity( Entity* e ); PLASMA_DLL_API void removeEntity( Entity* e ); PLASMA_DLL_API void removeAllEntities(); inline uint numEntities() const { return uint(_entities.size()); } inline Entity* entity( uint i ) const { return _entities[i].ptr(); } PLASMA_DLL_API Entity* entity( const ConstString& ) const; PLASMA_DLL_API AABBoxf boundingBox() const; // Lights. inline uint numLights() const { return uint(_lights.size()); } inline Light* light( uint i ) const { return _lights[i]; } PLASMA_DLL_API Light* light( const ConstString& ) const; // Cameras. inline uint numCameras() const { return uint(_cameras.size()); } inline Camera* camera( uint i ) const { return _cameras[i]; } PLASMA_DLL_API Camera* camera( const ConstString& ) const; // Groups. PLASMA_DLL_API void addGroup( EntityGroup* ); PLASMA_DLL_API void removeGroup( EntityGroup* ); PLASMA_DLL_API void removeAllGroups(); inline uint numGroups() const { return uint(_groups.size()); } inline EntityGroup* group( uint i ) const { return _groups[i].ptr(); } // Renderable. PLASMA_DLL_API void addRenderable( Renderable* ); PLASMA_DLL_API void removeRenderable( Renderable* ); PLASMA_DLL_API void removeAllRenderable(); inline uint numRenderables() const { return uint(_renderables.size()); } inline Renderable* renderable( uint i ) const { return _renderables[i].ptr(); } // Selection. PLASMA_DLL_API void addSelection( Selection* ); PLASMA_DLL_API void removeSelection( Selection* ); PLASMA_DLL_API void removeAllSelections(); inline uint numSelections() const { return uint(_selections.size()); } inline Selection* selection( uint i ) const { return _selections[i].ptr(); } // Constraint. PLASMA_DLL_API BallJoint* createBallJoint( RigidEntity*, RigidEntity* ); PLASMA_DLL_API HingeJoint* createHingeJoint( RigidEntity*, RigidEntity* ); PLASMA_DLL_API void addConstraint( Constraint* ); PLASMA_DLL_API void removeConstraint( Constraint* ); PLASMA_DLL_API void removeAllConstraints(); // Physics and simulation. PLASMA_DLL_API void startSimulation(); PLASMA_DLL_API void stopSimulation(); inline MotionWorld* motionWorld() const { return _world.ptr(); } PLASMA_DLL_API void gravity( const Vec3f& ); PLASMA_DLL_API const Vec3f& gravity() const; PLASMA_DLL_API void simulationSpeed( double speed ); inline double simulationSpeed() const { return _simulationSpeed; } inline double time() const { return _world->time(); } // Background. inline void backgroundColor( const Vec4f& c ) { _bgColor = c; } inline const Vec4f& backgroundColor() const { return _bgColor; } inline Table& attributes() const { return *_attributes; } // Animator. PLASMA_DLL_API void addAnimator( Animator* a ); PLASMA_DLL_API void addAnimator( Animator* a, double startTime ); PLASMA_DLL_API void removeAnimator( Animator* a ); // Brains. PLASMA_DLL_API void scheduleAnalyze( Entity* e ); PLASMA_DLL_API void registerReceptor( Entity* e, Receptor* r ); PLASMA_DLL_API void unregisterReceptor( Entity* e, Receptor* r ); PLASMA_DLL_API void handleCommands( const CommandContainer& cmds ); PLASMA_DLL_API void markForActionBefore( Entity* e ); PLASMA_DLL_API void markForActionAfter( Entity* e ); // Sounds. inline void addSoundSource ( Snd::Source* src ) { _sndSources[src].read(src); if( simulationSpeed() == 0.0 ) src->pause(); } inline void addSoundListener ( Snd::Listener* lis ) { _sndListeners.add(lis); } inline void removeSoundSource ( Snd::Source* src ) { _sndSources.erase(src); } inline void removeSoundListener( Snd::Listener* lis ) { _sndListeners.remove(lis); } inline RCP<Snd::Source> createSoundSource(); inline RCP<Snd::Listener> createSoundListener(); PLASMA_DLL_API void bind ( RigidEntity* e, Snd::Source* src ); PLASMA_DLL_API void bind ( RigidEntity* e, Snd::Listener* lis ); PLASMA_DLL_API void unbind( RigidEntity* e, Snd::Source* src ); PLASMA_DLL_API void unbind( RigidEntity* e, Snd::Listener* lis ); static inline Snd::Source* ALL_SND_SOURCES() { return (Snd::Source*)NULL; } static inline Snd::Listener* ALL_SND_LISTENERS() { return (Snd::Listener*)NULL; } // Probes. PLASMA_DLL_API void addProbe( Probe* p ); PLASMA_DLL_API void removeProbe( Probe* p ); inline uint numProbes() const { return uint(_probes.size()); } inline Probe* probe( uint idx ) const { return _probes[idx].ptr(); } PLASMA_DLL_API Probe* findBestProbe( const Vec3f& pos ) const; // State. inline bool silent() const { return getbits(_state, 0, 1) != 0; } inline void silent( bool v ) { _state = setbits(_state, 0, 1, v?1:0); } // Picking. PLASMA_DLL_API void pick( PickingData& data ); inline const RCP<DebugGeometry>& debugGeometry() const { return _debugGeometry; } PLASMA_DLL_API void debugGeometry( DebugGeometry* g ); // VM. virtual const char* meta() const; // Thread safe methods. PLASMA_DLL_API void submit( const Command& cmd ); //PLASMA_DLL_API void submit( const Vector< Command >& cmds ); protected: /*----- friends -----*/ friend class WorldAnimator; friend class Entity; /*----- methods -----*/ virtual ~World(); void updateID( Entity*, const ConstString& newID ); void runActions( double t, double d, bool afterPhysics ); void runPhysics( double step ); void runBrains( double step ); void runAnimators( double time, double delta ); void runCommandsAfterBrains(); void runCommandsAfterActions(); void runCommandsAfterPhysics(); //void emitSounds( double time, double delta ); void updateSounds(); void updateSoundStates( double oldSpeed, double newSpeed ); void newMotionWorld(); void sensationBeginCallback( const CollisionPair& cp ); void sensationEndCallback( const CollisionPair& cp ); static void getTransform( const void* userData, Reff& dstRef, Mat4f& dstMat ); static void setTransform( void* userData, const Reff& srcRef, const Mat4f& srcMat ); /*----- data types -----*/ // FIXME: Create a container class to hide the EntityReceptor pair class completely. // Template that class with only the Receptor class type. template< class R > struct EntityReceptor { Entity* _entity; R* _receptor; EntityReceptor( Entity* e, R* r ): _entity(e), _receptor(r) {} bool operator==( const EntityReceptor& er ) { return _entity == er._entity && _receptor == er._receptor; } }; typedef Vector< EntityReceptor<ContactReceptor> > ContactReceptorList; typedef HashTable< void*, ContactReceptorList > ContactReceptorContainer; typedef Vector< EntityReceptor<ContactGroupReceptor> > ContactGroupReceptorContainer; struct SndSourceData { bool _wasPlaying; float _oldPitch; SndSourceData(){} void read( const Snd::Source* src ) { _wasPlaying = src->playing(); _oldPitch = src->pitch(); } }; typedef Vector< RCP<Animator> > AnimatorContainer; typedef Map< RCP<Snd::Source>, SndSourceData > SndSourceContainer; typedef Set< RCP<Snd::Listener> > SndListenerContainer; typedef Map< RigidEntity*, List<Snd::Source*> > SndEntitySourceMap; typedef Map< RigidEntity*, List<Snd::Listener*> > SndEntityListenerMap; typedef Vector< Entity* > EntityPtrContainer; typedef Map< ConstString, Entity* > EntityIDContainer; typedef Vector< RCP<Probe> > ProbeContainer; /*----- data members -----*/ RCP<MotionWorld> _world; RCP<DirectionalAttractor> _gravityAttractor; // Descriptions. EntityContainer _entities; LightContainer _lights; CameraContainer _cameras; RenderableContainer _renderables; AnimatorContainer _animators; AnimatorContainer _newAnimators; GroupContainer _groups; SelectionContainer _selections; EntitySet _entitiesToAnalyze; EntityPtrContainer _entitiesWithActionsBefore; EntityPtrContainer _entitiesWithActionsAfter; EntityIDContainer _entityIDs; SndSourceContainer _sndSources; SndListenerContainer _sndListeners; SndEntitySourceMap _sndBoundSources; SndEntityListenerMap _sndBoundListeners; CommandContainer _commands; ProbeContainer _probes; // Receptors. ContactReceptorContainer _contactReceptors; ContactGroupReceptorContainer _contactGroupReceptors; bool _physicsLooped; // Parameters. Vec3f _gravity; Vec4f _bgColor; RCP<Table> _attributes; // Time. double _simulationSpeed; uint _state; //!< A series of bits packed together. //! silent (1) _state[ 0: 0] //!< Set when world should not emit any sound. Lock _lock; RCP<DebugGeometry> _debugGeometry; //!< Some points, lines, and triangles used to debug information. }; //------------------------------------------------------------------------------ //! RCP<Snd::Source> World::createSoundSource() { RCP<Snd::Source> src = Core::snd()->createSource(); addSoundSource( src.ptr() ); return src; } //------------------------------------------------------------------------------ //! RCP<Snd::Listener> World::createSoundListener() { RCP<Snd::Listener> lis = Core::snd()->createListener(); addSoundListener( lis.ptr() ); return lis; } NAMESPACE_END #endif
{ "content_hash": "82a81a7259739b628931c8d4d3738ad9", "timestamp": "", "source": "github", "line_count": 451, "max_line_length": 134, "avg_line_length": 32.791574279379155, "alnum_prop": 0.5976063290283319, "repo_name": "LudoSapiens/Dev", "id": "1769bfe907454d3f766fd2996d95ed1304bcd9e0", "size": "15057", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Projects/Plasma/World/World.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2481545" }, { "name": "C++", "bytes": "6397842" }, { "name": "Java", "bytes": "7734" }, { "name": "Lua", "bytes": "36688" }, { "name": "Objective-C", "bytes": "149497" }, { "name": "Python", "bytes": "137094" }, { "name": "Shell", "bytes": "2587" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_171-google-v7) on Mon Apr 08 11:10:15 PDT 2019 --> <title>ExtendableEntityUtil (Google App Engine API for Java)</title> <meta name="date" content="2019-04-08"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ExtendableEntityUtil (Google App Engine API for Java)"; } } catch(err) { } //--> var methods = {"i0":9,"i1":9,"i2":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/google/appengine/api/datastore/EntityTranslator.html" title="class in com.google.appengine.api.datastore"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/google/appengine/api/datastore/FetchOptions.html" title="class in com.google.appengine.api.datastore"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/google/appengine/api/datastore/ExtendableEntityUtil.html" target="_top">Frames</a></li> <li><a href="ExtendableEntityUtil.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.google.appengine.api.datastore</div> <h2 title="Class ExtendableEntityUtil" class="title">Class ExtendableEntityUtil</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.google.appengine.api.datastore.ExtendableEntityUtil</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public final class <span class="typeNameLabel">ExtendableEntityUtil</span> extends java.lang.Object</pre> <div class="block">Internal class that provides utility methods for extendable entity objects.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>static boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/datastore/ExtendableEntityUtil.html#areKeysEqual-com.google.appengine.api.datastore.Key-com.google.appengine.api.datastore.Key-">areKeysEqual</a></span>(<a href="../../../../../com/google/appengine/api/datastore/Key.html" title="class in com.google.appengine.api.datastore">Key</a>&nbsp;key1, <a href="../../../../../com/google/appengine/api/datastore/Key.html" title="class in com.google.appengine.api.datastore">Key</a>&nbsp;key2)</code> <div class="block">Check if the input <code>Key</code> objects are equal (including keys that are incomplete).</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/datastore/ExtendableEntityUtil.html#checkSupportedValue-java.lang.String-java.lang.Object-boolean-java.util.Set-">checkSupportedValue</a></span>(java.lang.String&nbsp;propertyName, java.lang.Object&nbsp;value, boolean&nbsp;valuePreChecked, java.util.Set&lt;java.lang.Class&lt;?&gt;&gt;&nbsp;supportedTypes)</code> <div class="block">If the specified object cannot be used as the value for a <code>Entity</code> property, throw an exception with the appropriate explanation.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/google/appengine/api/datastore/Key.html" title="class in com.google.appengine.api.datastore">Key</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/google/appengine/api/datastore/ExtendableEntityUtil.html#createKey-com.google.appengine.api.datastore.Key-java.lang.String-">createKey</a></span>(<a href="../../../../../com/google/appengine/api/datastore/Key.html" title="class in com.google.appengine.api.datastore">Key</a>&nbsp;parent, java.lang.String&nbsp;kind)</code> <div class="block">Creates a new <code>Key</code> with the provided parent and kind.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="createKey-com.google.appengine.api.datastore.Key-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createKey</h4> <pre>public static&nbsp;<a href="../../../../../com/google/appengine/api/datastore/Key.html" title="class in com.google.appengine.api.datastore">Key</a>&nbsp;createKey(<a href="../../../../../com/google/appengine/api/datastore/Key.html" title="class in com.google.appengine.api.datastore">Key</a>&nbsp;parent, java.lang.String&nbsp;kind)</pre> <div class="block">Creates a new <code>Key</code> with the provided parent and kind. The instantiated <code>Key</code> will be incomplete.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>parent</code> - the parent of the key to create, can be <code>null</code></dd> <dd><code>kind</code> - the kind of the key to create</dd> </dl> </li> </ul> <a name="areKeysEqual-com.google.appengine.api.datastore.Key-com.google.appengine.api.datastore.Key-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>areKeysEqual</h4> <pre>public static&nbsp;boolean&nbsp;areKeysEqual(<a href="../../../../../com/google/appengine/api/datastore/Key.html" title="class in com.google.appengine.api.datastore">Key</a>&nbsp;key1, <a href="../../../../../com/google/appengine/api/datastore/Key.html" title="class in com.google.appengine.api.datastore">Key</a>&nbsp;key2)</pre> <div class="block">Check if the input <code>Key</code> objects are equal (including keys that are incomplete).</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>key1</code> - the first input key</dd> <dd><code>key2</code> - the second input key</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd><code>true</code> if the keys are equal. <code>false</code> otherwise.</dd> </dl> </li> </ul> <a name="checkSupportedValue-java.lang.String-java.lang.Object-boolean-java.util.Set-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>checkSupportedValue</h4> <pre>public static&nbsp;void&nbsp;checkSupportedValue(java.lang.String&nbsp;propertyName, java.lang.Object&nbsp;value, boolean&nbsp;valuePreChecked, java.util.Set&lt;java.lang.Class&lt;?&gt;&gt;&nbsp;supportedTypes)</pre> <div class="block">If the specified object cannot be used as the value for a <code>Entity</code> property, throw an exception with the appropriate explanation.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>propertyName</code> - the name of the property.</dd> <dd><code>value</code> - value in question</dd> <dd><code>supportedTypes</code> - the types considered to be valid types for the value.</dd> <dd><code>valuePreChecked</code> - <code>true</code> if the value without the name has already been checked. <code>false</code> otherwise.</dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code>java.lang.IllegalArgumentException</code> - if the type is not supported, or if the object is in some other way invalid.</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage">Java is a registered trademark of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/google/appengine/api/datastore/EntityTranslator.html" title="class in com.google.appengine.api.datastore"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/google/appengine/api/datastore/FetchOptions.html" title="class in com.google.appengine.api.datastore"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/google/appengine/api/datastore/ExtendableEntityUtil.html" target="_top">Frames</a></li> <li><a href="ExtendableEntityUtil.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "2612b449c05e482e848a3cc606706fb1", "timestamp": "", "source": "github", "line_count": 308, "max_line_length": 396, "avg_line_length": 43.48376623376623, "alnum_prop": 0.6531023669080863, "repo_name": "googlearchive/caja", "id": "0bcb56c8810cced9e3df04087c5869d7e58f47d4", "size": "13393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/java/appengine/docs/javadoc/com/google/appengine/api/datastore/ExtendableEntityUtil.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "30715" }, { "name": "HTML", "bytes": "1086467" }, { "name": "Java", "bytes": "2541899" }, { "name": "JavaScript", "bytes": "2102219" }, { "name": "Perl", "bytes": "25768" }, { "name": "Python", "bytes": "150158" }, { "name": "Shell", "bytes": "13072" }, { "name": "XSLT", "bytes": "27472" } ], "symlink_target": "" }
import json import os import socket from django import forms from django.conf import settings from django.db.models import Q from django.forms.models import modelformset_factory from django.utils.safestring import mark_safe from django.utils.encoding import force_unicode import commonware import happyforms from tower import ugettext as _, ugettext_lazy as _lazy from quieter_formset.formset import BaseModelFormSet from access import acl import amo import addons.forms import paypal from addons.models import (Addon, AddonDependency, AddonUser, Charity, Preview) from amo.forms import AMOModelForm from amo.urlresolvers import reverse from applications.models import AppVersion from files.models import File, FileUpload from files.utils import parse_addon from translations.widgets import TranslationTextarea, TranslationTextInput from translations.fields import TransTextarea, TransField from translations.models import delete_translation, Translation from translations.forms import TranslationFormMixin from versions.models import (ApplicationsVersions, License, VALID_SOURCE_EXTENSIONS, Version) from . import tasks, utils paypal_log = commonware.log.getLogger('z.paypal') class AuthorForm(happyforms.ModelForm): class Meta: model = AddonUser exclude = ('addon',) class BaseModelFormSet(BaseModelFormSet): """ Override the parent's is_valid to prevent deleting all forms. """ def is_valid(self): # clean() won't get called in is_valid() if all the rows are getting # deleted. We can't allow deleting everything. rv = super(BaseModelFormSet, self).is_valid() return rv and not any(self.errors) and not bool(self.non_form_errors()) class BaseAuthorFormSet(BaseModelFormSet): def clean(self): if any(self.errors): return # cleaned_data could be None if it's the empty extra form. data = filter(None, [f.cleaned_data for f in self.forms if not f.cleaned_data.get('DELETE', False)]) if not any(d['role'] == amo.AUTHOR_ROLE_OWNER for d in data): raise forms.ValidationError(_('Must have at least one owner.')) if not any(d['listed'] for d in data): raise forms.ValidationError( _('At least one author must be listed.')) users = [d['user'] for d in data] if sorted(users) != sorted(set(users)): raise forms.ValidationError( _('An author can only be listed once.')) AuthorFormSet = modelformset_factory(AddonUser, formset=BaseAuthorFormSet, form=AuthorForm, can_delete=True, extra=0) class DeleteForm(happyforms.Form): password = forms.CharField() reason = forms.CharField(required=False) def __init__(self, request): self.user = request.user super(DeleteForm, self).__init__(request.POST) def clean_password(self): data = self.cleaned_data if not self.user.check_password(data['password']): raise forms.ValidationError(_('Password incorrect.')) class AnnotateFileForm(happyforms.Form): message = forms.CharField() ignore_duplicates = forms.BooleanField(required=False) def clean_message(self): msg = self.cleaned_data['message'] try: msg = json.loads(msg) except ValueError: raise forms.ValidationError(_('Invalid JSON object')) key = utils.ValidationComparator.message_key(msg) if key is None: raise forms.ValidationError( _('Message not eligible for annotation')) return msg class LicenseChoiceRadio(forms.widgets.RadioFieldRenderer): def __iter__(self): for i, choice in enumerate(self.choices): yield LicenseRadioInput(self.name, self.value, self.attrs.copy(), choice, i) class LicenseRadioInput(forms.widgets.RadioInput): def __init__(self, name, value, attrs, choice, index): super(LicenseRadioInput, self).__init__(name, value, attrs, choice, index) license = choice[1] # Choice is a tuple (object.id, object). link = u'<a class="xx extra" href="%s" target="_blank">%s</a>' if hasattr(license, 'url'): details = link % (license.url, _('Details')) self.choice_label = mark_safe(self.choice_label + details) class LicenseForm(AMOModelForm): builtin = forms.TypedChoiceField( choices=[], coerce=int, widget=forms.RadioSelect(attrs={'class': 'license'}, renderer=LicenseChoiceRadio)) name = forms.CharField(widget=TranslationTextInput(), label=_lazy(u"What is your license's name?"), required=False, initial=_lazy('Custom License')) text = forms.CharField(widget=TranslationTextarea(), required=False, label=_lazy(u'Provide the text of your license.')) def __init__(self, *args, **kw): addon = kw.pop('addon', None) self.version = None if addon: self.version = addon.latest_version if self.version: kw['instance'], kw['initial'] = self.version.license, None # Clear out initial data if it's a builtin license. if getattr(kw['instance'], 'builtin', None): kw['initial'] = {'builtin': kw['instance'].builtin} kw['instance'] = None super(LicenseForm, self).__init__(*args, **kw) cs = [(x.builtin, x) for x in License.objects.builtins().filter(on_form=True)] cs.append((License.OTHER, _('Other'))) self.fields['builtin'].choices = cs if addon and not addon.is_listed: self.fields['builtin'].required = False class Meta: model = License fields = ('builtin', 'name', 'text') def clean_name(self): name = self.cleaned_data['name'] return name.strip() or _('Custom License') def clean(self): data = self.cleaned_data if self.errors: return data elif data['builtin'] == License.OTHER and not data['text']: raise forms.ValidationError( _('License text is required when choosing Other.')) return data def get_context(self): """Returns a view context dict having keys license_urls, license_form, and license_other_val. """ license_urls = dict(License.objects.builtins() .values_list('builtin', 'url')) return dict(license_urls=license_urls, version=self.version, license_form=self.version and self, license_other_val=License.OTHER) def save(self, *args, **kw): """Save all form data. This will only create a new license if it's not one of the builtin ones. Keyword arguments **log=True** Set to False if you do not want to log this action for display on the developer dashboard. """ log = kw.pop('log', True) changed = self.changed_data builtin = self.cleaned_data['builtin'] if builtin == '': # No license chosen, it must be an unlisted add-on. return if builtin != License.OTHER: license = License.objects.get(builtin=builtin) else: # Save the custom license: license = super(LicenseForm, self).save(*args, **kw) if self.version: if changed or license != self.version.license: self.version.update(license=license) if log: amo.log(amo.LOG.CHANGE_LICENSE, license, self.version.addon) return license class PolicyForm(TranslationFormMixin, AMOModelForm): """Form for editing the add-ons EULA and privacy policy.""" has_eula = forms.BooleanField( required=False, label=_lazy(u'This add-on has an End-User License Agreement')) eula = TransField( widget=TransTextarea(), required=False, label=_lazy(u"Please specify your add-on's " "End-User License Agreement:")) has_priv = forms.BooleanField( required=False, label=_lazy(u"This add-on has a Privacy Policy")) privacy_policy = TransField( widget=TransTextarea(), required=False, label=_lazy(u"Please specify your add-on's Privacy Policy:")) def __init__(self, *args, **kw): self.addon = kw.pop('addon', None) if not self.addon: raise ValueError('addon keyword arg cannot be None') kw['instance'] = self.addon kw['initial'] = dict(has_priv=self._has_field('privacy_policy'), has_eula=self._has_field('eula')) super(PolicyForm, self).__init__(*args, **kw) def _has_field(self, name): # If there's a eula in any language, this addon has a eula. n = getattr(self.addon, u'%s_id' % name) return any(map(bool, Translation.objects.filter(id=n))) class Meta: model = Addon fields = ('eula', 'privacy_policy') def save(self, commit=True): ob = super(PolicyForm, self).save(commit) for k, field in (('has_eula', 'eula'), ('has_priv', 'privacy_policy')): if not self.cleaned_data[k]: delete_translation(self.instance, field) if 'privacy_policy' in self.changed_data: amo.log(amo.LOG.CHANGE_POLICY, self.addon, self.instance) return ob def ProfileForm(*args, **kw): # If the add-on takes contributions, then both fields are required. addon = kw['instance'] fields_required = (kw.pop('required', False) or bool(addon.takes_contributions)) the_reason_label = _('Why did you make this add-on?') the_future_label = _("What's next for this add-on?") class _Form(TranslationFormMixin, happyforms.ModelForm): the_reason = TransField(widget=TransTextarea(), required=fields_required, label=the_reason_label) the_future = TransField(widget=TransTextarea(), required=fields_required, label=the_future_label) class Meta: model = Addon fields = ('the_reason', 'the_future') return _Form(*args, **kw) class CharityForm(happyforms.ModelForm): url = Charity._meta.get_field('url').formfield() class Meta: model = Charity fields = ('name', 'url', 'paypal') def clean_paypal(self): check_paypal_id(self.cleaned_data['paypal']) return self.cleaned_data['paypal'] def save(self, commit=True): # We link to the charity row in contrib stats, so we force all charity # changes to create a new row so we don't forget old charities. if self.changed_data and self.instance.id: self.instance.id = None return super(CharityForm, self).save(commit) class ContribForm(TranslationFormMixin, happyforms.ModelForm): RECIPIENTS = (('dev', _lazy(u'The developers of this add-on')), ('moz', _lazy(u'The Mozilla Foundation')), ('org', _lazy(u'An organization of my choice'))) recipient = forms.ChoiceField( choices=RECIPIENTS, widget=forms.RadioSelect(attrs={'class': 'recipient'})) thankyou_note = TransField(widget=TransTextarea(), required=False) class Meta: model = Addon fields = ('paypal_id', 'suggested_amount', 'annoying', 'enable_thankyou', 'thankyou_note') widgets = { 'annoying': forms.RadioSelect(), 'suggested_amount': forms.TextInput(attrs={'class': 'short'}), 'paypal_id': forms.TextInput(attrs={'size': '50'}) } @staticmethod def initial(addon): if addon.charity: recip = 'moz' if addon.charity_id == amo.FOUNDATION_ORG else 'org' else: recip = 'dev' return {'recipient': recip, 'annoying': addon.annoying or amo.CONTRIB_PASSIVE} def clean(self): data = self.cleaned_data try: if not self.errors and data['recipient'] == 'dev': check_paypal_id(data['paypal_id']) except forms.ValidationError, e: self.errors['paypal_id'] = self.error_class(e.messages) # thankyou_note is a dict since it's a Translation. if not (data.get('enable_thankyou') and any(data.get('thankyou_note').values())): data['thankyou_note'] = {} data['enable_thankyou'] = False return data def clean_suggested_amount(self): amount = self.cleaned_data['suggested_amount'] if amount is not None and amount <= 0: msg = _(u'Please enter a suggested amount greater than 0.') raise forms.ValidationError(msg) if amount > settings.MAX_CONTRIBUTION: msg = _(u'Please enter a suggested amount less than ${0}.').format( settings.MAX_CONTRIBUTION) raise forms.ValidationError(msg) return amount def check_paypal_id(paypal_id): if not paypal_id: raise forms.ValidationError( _('PayPal ID required to accept contributions.')) try: valid, msg = paypal.check_paypal_id(paypal_id) if not valid: raise forms.ValidationError(msg) except socket.error: raise forms.ValidationError(_('Could not validate PayPal id.')) class WithSourceMixin(object): def clean_source(self): source = self.cleaned_data.get('source') if source and not source.name.endswith(VALID_SOURCE_EXTENSIONS): raise forms.ValidationError( _('Unsupported file type, please upload an archive file ' '{extensions}.'.format( extensions=VALID_SOURCE_EXTENSIONS)) ) return source class SourceFileInput(forms.widgets.ClearableFileInput): """ We need to customize the URL link. 1. Remove %(initial)% from template_with_initial 2. Prepend the new link (with customized text) """ template_with_initial = '%(clear_template)s<br />%(input_text)s: %(input)s' def render(self, name, value, attrs=None): output = super(SourceFileInput, self).render(name, value, attrs) if value and hasattr(value, 'instance'): url = reverse('downloads.source', args=(value.instance.pk, )) params = {'url': url, 'output': output, 'label': _('View current')} output = '<a href="%(url)s">%(label)s</a> %(output)s' % params return output class VersionForm(WithSourceMixin, happyforms.ModelForm): releasenotes = TransField( widget=TransTextarea(), required=False) approvalnotes = forms.CharField( widget=TranslationTextarea(attrs={'rows': 4}), required=False) source = forms.FileField(required=False, widget=SourceFileInput) class Meta: model = Version fields = ('releasenotes', 'approvalnotes', 'source') class AppVersionChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.version class CompatForm(happyforms.ModelForm): application = forms.TypedChoiceField(choices=amo.APPS_CHOICES, coerce=int, widget=forms.HiddenInput) min = AppVersionChoiceField(AppVersion.objects.none()) max = AppVersionChoiceField(AppVersion.objects.none()) class Meta: model = ApplicationsVersions fields = ('application', 'min', 'max') def __init__(self, *args, **kw): super(CompatForm, self).__init__(*args, **kw) if self.initial: app = self.initial['application'] else: app = self.data[self.add_prefix('application')] self.app = amo.APPS_ALL[int(app)] qs = AppVersion.objects.filter(application=app).order_by('version_int') self.fields['min'].queryset = qs.filter(~Q(version__contains='*')) self.fields['max'].queryset = qs.all() def clean(self): min = self.cleaned_data.get('min') max = self.cleaned_data.get('max') if not (min and max and min.version_int <= max.version_int): raise forms.ValidationError(_('Invalid version range.')) return self.cleaned_data class BaseCompatFormSet(BaseModelFormSet): def __init__(self, *args, **kw): super(BaseCompatFormSet, self).__init__(*args, **kw) # We always want a form for each app, so force extras for apps # the add-on does not already have. qs = kw['queryset'].values_list('application', flat=True) apps = [a for a in amo.APP_USAGE if a.id not in qs] self.initial = ([{} for _ in qs] + [{'application': a.id} for a in apps]) self.extra = len(amo.APP_GUIDS) - len(self.forms) # After these changes, the forms need to be rebuilt. `forms` # is a cached property, so we delete the existing cache and # ask for a new one to be built. del self.forms self.forms def clean(self): if any(self.errors): return apps = filter(None, [f.cleaned_data for f in self.forms if not f.cleaned_data.get('DELETE', False)]) if not apps: raise forms.ValidationError( _('Need at least one compatible application.')) CompatFormSet = modelformset_factory( ApplicationsVersions, formset=BaseCompatFormSet, form=CompatForm, can_delete=True, extra=0) class AddonUploadForm(WithSourceMixin, happyforms.Form): upload = forms.ModelChoiceField( widget=forms.HiddenInput, queryset=FileUpload.objects, error_messages={ 'invalid_choice': _lazy(u'There was an error with your ' u'upload. Please try again.') } ) admin_override_validation = forms.BooleanField( required=False, label=_lazy(u'Override failed validation')) source = forms.FileField(required=False) is_manual_review = forms.BooleanField( initial=False, required=False, label=_lazy(u'Submit my add-on for manual review.')) def __init__(self, *args, **kw): self.request = kw.pop('request') super(AddonUploadForm, self).__init__(*args, **kw) def _clean_upload(self): if not (self.cleaned_data['upload'].valid or self.cleaned_data['upload'].validation_timeout or self.cleaned_data['admin_override_validation'] and acl.action_allowed(self.request, 'ReviewerAdminTools', 'View')): raise forms.ValidationError(_(u'There was an error with your ' u'upload. Please try again.')) class NewAddonForm(AddonUploadForm): supported_platforms = forms.TypedMultipleChoiceField( choices=amo.SUPPORTED_PLATFORMS_CHOICES, widget=forms.CheckboxSelectMultiple(attrs={'class': 'platform'}), initial=[amo.PLATFORM_ALL.id], coerce=int, error_messages={'required': 'Need at least one platform.'} ) is_unlisted = forms.BooleanField( initial=False, required=False, label=_lazy(u'Do not list my add-on on this site (beta)'), help_text=_lazy( u'Check this option if you intend to distribute your add-on on ' u'your own and only need it to be signed by Mozilla.')) is_sideload = forms.BooleanField( initial=False, required=False, label=_lazy(u'This add-on will be bundled with an application ' u'installer.'), help_text=_lazy(u'Add-ons that are bundled with application ' u'installers will be code reviewed ' u'by Mozilla before they are signed and are held to a ' u'higher quality standard.')) def clean(self): if not self.errors: self._clean_upload() xpi = parse_addon(self.cleaned_data['upload']) # We don't enforce name uniqueness for unlisted add-ons. if not self.cleaned_data.get('is_unlisted', False): addons.forms.clean_name(xpi['name'], addon_type=xpi['type']) return self.cleaned_data class NewVersionForm(NewAddonForm): nomination_type = forms.TypedChoiceField( choices=( ('', ''), (amo.STATUS_NOMINATED, _lazy('Full Review')), (amo.STATUS_UNREVIEWED, _lazy('Preliminary Review')), ), coerce=int, empty_value=None, required=False, error_messages={ 'required': _lazy(u'Please choose a review nomination type') }) beta = forms.BooleanField( required=False, help_text=_lazy(u'A file with a version ending with ' u'a|alpha|b|beta|pre|rc and an optional number is ' u'detected as beta.')) def __init__(self, *args, **kw): self.addon = kw.pop('addon') super(NewVersionForm, self).__init__(*args, **kw) if self.addon.status == amo.STATUS_NULL: self.fields['nomination_type'].required = True def clean(self): if not self.errors: self._clean_upload() xpi = parse_addon(self.cleaned_data['upload'], self.addon) # Make sure we don't already have the same non-rejected version. if self.addon.versions.filter(version=xpi['version']).exclude( files__status=amo.STATUS_DISABLED): raise forms.ValidationError( _(u'Version %s already exists') % xpi['version']) return self.cleaned_data class NewFileForm(AddonUploadForm): platform = forms.TypedChoiceField( choices=amo.SUPPORTED_PLATFORMS_CHOICES, widget=forms.RadioSelect(attrs={'class': 'platform'}), coerce=int, # We don't want the id value of the field to be output to the user # when choice is invalid. Make a generic error message instead. error_messages={ 'invalid_choice': _lazy(u'Select a valid choice. That choice is ' u'not one of the available choices.') } ) beta = forms.BooleanField( required=False, help_text=_lazy(u'A file with a version ending with a|alpha|b|beta and' u' an optional number is detected as beta.')) def __init__(self, *args, **kw): self.addon = kw.pop('addon') self.version = kw.pop('version') super(NewFileForm, self).__init__(*args, **kw) # Reset platform choices to just those compatible with target app. field = self.fields['platform'] field.choices = sorted((p.id, p.name) for p in self.version.compatible_platforms().values()) # Don't allow platforms we already have. to_exclude = set(File.objects.filter(version=self.version) .values_list('platform', flat=True)) # Don't allow platform=ALL if we already have platform files. if len(to_exclude): to_exclude.add(amo.PLATFORM_ALL.id) field.choices = [p for p in field.choices if p[0] not in to_exclude] def clean(self): if not self.version.is_allowed_upload(): raise forms.ValidationError( _('You cannot upload any more files for this version.')) # Check for errors in the xpi. if not self.errors: xpi = parse_addon(self.cleaned_data['upload'], self.addon) if xpi['version'] != self.version.version: raise forms.ValidationError(_("Version doesn't match")) return self.cleaned_data class FileForm(happyforms.ModelForm): platform = File._meta.get_field('platform').formfield() class Meta: model = File fields = ('platform',) def __init__(self, *args, **kw): super(FileForm, self).__init__(*args, **kw) if kw['instance'].version.addon.type == amo.ADDON_SEARCH: del self.fields['platform'] else: compat = kw['instance'].version.compatible_platforms() pid = int(kw['instance'].platform) plats = [(p.id, p.name) for p in compat.values()] if pid not in compat: plats.append([pid, amo.PLATFORMS[pid].name]) self.fields['platform'].choices = plats def clean_DELETE(self): if any(self.errors): return delete = self.cleaned_data['DELETE'] if (delete and not self.instance.version.is_all_unreviewed): error = _('You cannot delete a file once the review process has ' 'started. You must delete the whole version.') raise forms.ValidationError(error) return delete class BaseFileFormSet(BaseModelFormSet): def clean(self): if any(self.errors): return files = [f.cleaned_data for f in self.forms if not f.cleaned_data.get('DELETE', False)] if self.forms and 'platform' in self.forms[0].fields: platforms = [f['platform'] for f in files] if amo.PLATFORM_ALL.id in platforms and len(files) > 1: raise forms.ValidationError( _('The platform All cannot be combined ' 'with specific platforms.')) if sorted(platforms) != sorted(set(platforms)): raise forms.ValidationError( _('A platform can only be chosen once.')) FileFormSet = modelformset_factory(File, formset=BaseFileFormSet, form=FileForm, can_delete=True, extra=0) class ReviewTypeForm(forms.Form): _choices = [(k, Addon.STATUS_CHOICES[k]) for k in (amo.STATUS_UNREVIEWED, amo.STATUS_NOMINATED)] review_type = forms.TypedChoiceField( choices=_choices, widget=forms.HiddenInput, coerce=int, empty_value=None, error_messages={'required': _lazy(u'A review type must be selected.')}) class Step3Form(addons.forms.AddonFormBasic): description = TransField(widget=TransTextarea, required=False) class Meta: model = Addon fields = ('name', 'slug', 'summary', 'tags', 'description', 'homepage', 'support_email', 'support_url') class PreviewForm(happyforms.ModelForm): caption = TransField(widget=TransTextarea, required=False) file_upload = forms.FileField(required=False) upload_hash = forms.CharField(required=False) def save(self, addon, commit=True): if self.cleaned_data: self.instance.addon = addon if self.cleaned_data.get('DELETE'): # Existing preview. if self.instance.id: self.instance.delete() # User has no desire to save this preview. return super(PreviewForm, self).save(commit=commit) if self.cleaned_data['upload_hash']: upload_hash = self.cleaned_data['upload_hash'] upload_path = os.path.join(settings.TMP_PATH, 'preview', upload_hash) tasks.resize_preview.delay(upload_path, self.instance, set_modified_on=[self.instance]) class Meta: model = Preview fields = ('caption', 'file_upload', 'upload_hash', 'id', 'position') class BasePreviewFormSet(BaseModelFormSet): def clean(self): if any(self.errors): return PreviewFormSet = modelformset_factory(Preview, formset=BasePreviewFormSet, form=PreviewForm, can_delete=True, extra=1) class AdminForm(happyforms.ModelForm): _choices = [(k, v) for k, v in amo.ADDON_TYPE.items() if k != amo.ADDON_ANY] type = forms.ChoiceField(choices=_choices) # Request is needed in other ajax forms so we're stuck here. def __init__(self, request=None, *args, **kw): super(AdminForm, self).__init__(*args, **kw) class Meta: model = Addon fields = ('trusted', 'type', 'guid', 'target_locale', 'locale_disambiguation') widgets = { 'guid': forms.TextInput(attrs={'size': '50'}) } class InlineRadioRenderer(forms.widgets.RadioFieldRenderer): def render(self): return mark_safe(''.join(force_unicode(w) for w in self)) class CheckCompatibilityForm(happyforms.Form): application = forms.ChoiceField( label=_lazy(u'Application'), choices=[(a.id, a.pretty) for a in amo.APP_USAGE]) app_version = forms.ChoiceField( label=_lazy(u'Version'), choices=[('', _lazy(u'Select an application first'))]) def __init__(self, *args, **kw): super(CheckCompatibilityForm, self).__init__(*args, **kw) w = self.fields['application'].widget # Get the URL after the urlconf has loaded. w.attrs['data-url'] = reverse('devhub.compat_application_versions') def version_choices_for_app_id(self, app_id): versions = AppVersion.objects.filter(application=app_id) return [(v.id, v.version) for v in versions] def clean_application(self): app_id = int(self.cleaned_data['application']) app = amo.APPS_IDS.get(app_id) self.cleaned_data['application'] = app choices = self.version_choices_for_app_id(app_id) self.fields['app_version'].choices = choices return self.cleaned_data['application'] def clean_app_version(self): v = self.cleaned_data['app_version'] return AppVersion.objects.get(pk=int(v)) def DependencyFormSet(*args, **kw): addon_parent = kw.pop('addon') # Add-ons: Required add-ons cannot include apps nor personas. # Apps: Required apps cannot include any add-ons. qs = (Addon.objects.reviewed().exclude(id=addon_parent.id). exclude(type__in=[amo.ADDON_PERSONA])) class _Form(happyforms.ModelForm): addon = forms.CharField(required=False, widget=forms.HiddenInput) dependent_addon = forms.ModelChoiceField(qs, widget=forms.HiddenInput) class Meta: model = AddonDependency fields = ('addon', 'dependent_addon') def clean_addon(self): return addon_parent class _FormSet(BaseModelFormSet): def clean(self): if any(self.errors): return form_count = len([f for f in self.forms if not f.cleaned_data.get('DELETE', False)]) if form_count > 3: error = _('There cannot be more than 3 required add-ons.') raise forms.ValidationError(error) FormSet = modelformset_factory(AddonDependency, formset=_FormSet, form=_Form, extra=0, can_delete=True) return FormSet(*args, **kw)
{ "content_hash": "2c6a9afbb4e6051f185dcde18be23772", "timestamp": "", "source": "github", "line_count": 841, "max_line_length": 79, "avg_line_length": 37.52794292508918, "alnum_prop": 0.5938975317638858, "repo_name": "mdaif/olympia", "id": "615e2d27eb188d1a70c808680c3013ce13955a74", "size": "31585", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apps/devhub/forms.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "249" }, { "name": "C", "bytes": "4145" }, { "name": "CSS", "bytes": "657480" }, { "name": "HTML", "bytes": "1635828" }, { "name": "JavaScript", "bytes": "1371668" }, { "name": "Makefile", "bytes": "3926" }, { "name": "PLSQL", "bytes": "74" }, { "name": "Python", "bytes": "4017646" }, { "name": "Shell", "bytes": "10337" }, { "name": "Smarty", "bytes": "2179" } ], "symlink_target": "" }
import codecs from ipywidgets import widgets, widget_serialization import traitlets class SVGLayoutBox(widgets.Box): """ A container that positions its `children` according to the bounding boxes of the inkscape layers in its TODO scale_mode: fit or stretch center? """ _view_name = traitlets.Unicode('SVGLayoutBoxView', sync=True) _view_module = traitlets.Unicode( "/nbextensions/ipylayoutwidgets/js/SVGLayoutBoxView.js", sync=True ) _model_name = traitlets.Unicode('SVGLayoutBoxModel', sync=True) _model_module = traitlets.Unicode( "/nbextensions/ipylayoutwidgets/js/SVGLayoutBoxModel.js", sync=True ) svg = traitlets.Unicode(sync=True) svg_file = traitlets.Unicode(sync=True) show_svg = traitlets.Bool(True, sync=True) widget_map = traitlets.Dict( sync=True, **widget_serialization, help="a dictionary of widget instances keyed by the inkscape:label of a layer. Accepts * as wildcard.") visible_layers = traitlets.Tuple( ["*"], sync=True, help="a list of inkscape:label for inkscape layers to show. Accepts * as wildcard.") def _svg_file_changed(self, name, old_val, new_val): with codecs.open(new_val, "r", "utf-8") as f: self.svg = f.read()
{ "content_hash": "2f2ce750a78d90279941e061d4c7a121", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 111, "avg_line_length": 33.175, "alnum_prop": 0.6593820648078372, "repo_name": "openseat/ipylayoutwidgets", "id": "f8f5d32378648851cbd46fba08ae674550ea752e", "size": "1327", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ipylayoutwidgets/widgets/widget_svg_layout.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "12887" }, { "name": "Jupyter Notebook", "bytes": "8558" }, { "name": "Python", "bytes": "4244" } ], "symlink_target": "" }
import { createContext } from 'react'; import type { IHybridContextProps } from './types'; export const HybridContext = createContext<IHybridContextProps>({ colorMode: { colorMode: 'light', toggleColorMode: () => {}, setColorMode: () => {}, accessibleColors: false, setAccessibleColors: () => {}, }, });
{ "content_hash": "69310b79aa7f2c2cf5ce66104af77557", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 65, "avg_line_length": 27.416666666666668, "alnum_prop": 0.6443768996960486, "repo_name": "GeekyAnts/NativeBase", "id": "1aa7b0d0b3f960bfa3347ed207dbf22eb7c452bd", "size": "329", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core/hybrid-overlay/Context.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2083" }, { "name": "Java", "bytes": "6282" }, { "name": "JavaScript", "bytes": "19861" }, { "name": "Objective-C", "bytes": "4511" }, { "name": "Ruby", "bytes": "826" }, { "name": "Shell", "bytes": "1654" }, { "name": "Starlark", "bytes": "602" }, { "name": "TypeScript", "bytes": "1420485" } ], "symlink_target": "" }
/* global define, it, describe, expect */ import { takeEvery } from 'redux-saga'; import { call, put, fork } from 'redux-saga/effects'; import booksSaga, { createBook, fetchBooks, watchCreateBook, watchFetchBooks, } from '../booksSaga'; import bookshelfApi from '../../services'; import * as actions from '../../actions/booksActions'; import { ADD_BOOK, FETCH_ALL_BOOKS, } from '../../constants'; describe('book sagas', () => { describe('*createBooks', () => { describe('with correct parameters', () => { const action = { type: ADD_BOOK, title: 'title', author: 'author' }; const generator = createBook(action); it('yields a call to bookshelfApi.createBook', () => { const next = generator.next(); expect(next.value).toEqual( call(bookshelfApi.createBook, action.title, action.author), ); }); it('yields a put actions.createdBook', () => { const success = true; const next = generator.next(success); expect(next.value).toEqual(put(actions.createdBook(success))); }); }); }); describe('*fetchBooks', () => { const generator = fetchBooks(); it('yields a call to bookshelfApi.getBooks', () => { const next = generator.next(); expect(next.value).toEqual(call(bookshelfApi.getBooks)); }); describe('when successful', () => { const books = [ { id: 1, title: 'title', author: 'author' }, ]; it('yields a put actions.receiveBooks', () => { const next = generator.next(books); expect(next.value).toEqual(put(actions.receiveBooks(books))); }); }); }); describe('*watchCreateBook', () => { const generator = watchCreateBook(); it('yields a call to createBook on action ADD_BOOK', () => { const next = generator.next(); expect(next.value) .toEqual(call(takeEvery, ADD_BOOK, createBook)); }); }); describe('*watchFetchBooks', () => { const generator = watchFetchBooks(); it('yields a call to fetchBooks on action FETCH_ALL_BOOKS', () => { const next = generator.next(); expect(next.value) .toEqual(call(takeEvery, FETCH_ALL_BOOKS, fetchBooks)); }); }); describe('*booksSaga', () => { const generator = booksSaga(); it('yields a fork of watchFetchBooks', () => { const next = generator.next(); expect(next.value).toEqual([ fork(watchFetchBooks), fork(watchCreateBook), ]); }); }); });
{ "content_hash": "10defaf90188901746172c4d31c91360", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 74, "avg_line_length": 28.179775280898877, "alnum_prop": 0.5889154704944178, "repo_name": "w1nston/bookshelf", "id": "2056fec7ab3dfd7991d3b8e9d77d049a655fa409", "size": "2508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/sagas/__tests__/bookSaga.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "277" }, { "name": "JavaScript", "bytes": "47876" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2014 The Android Open Source Project 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. --> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Menu item without a sub menu. --> <item android:id="@+id/menu_designer" android:title="@string/menu_designer" /> <!-- Menu item with a sub menu. --> <item android:id="@+id/menu_coder" android:title="@string/menu_coder"> <menu> <item android:id="@+id/menu_coder1" android:title="@string/menu_coder1" /> <item android:id="@+id/menu_coder2" android:title="@string/menu_coder2" /> <item android:id="@+id/menu_coder3" android:title="@string/menu_coder3" /> <item android:id="@+id/menu_coder4" android:title="@string/menu_coder4" /> <item android:id="@+id/menu_coder5" android:title="@string/menu_coder5" /> </menu> </item> <!-- Menu item without a sub menu. --> <item android:id="@+id/menu_product" android:title="@string/menu_product" /> </menu> <!-- From: file:/Users/Test/gdk-apidemo-sample-master/app/src/main/res/menu/voice_menu.xml -->
{ "content_hash": "b9bfcef836e956f81279d2c5182aac35", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 94, "avg_line_length": 35.464285714285715, "alnum_prop": 0.5584088620342397, "repo_name": "Hankay/gdk-apidemo-sample-master", "id": "4acd64cd40d2d38e100e7495520e194ebeeb1cd0", "size": "1986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/build/intermediates/res/debug/menu/voice_menu.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "97265" } ], "symlink_target": "" }
#include "lapacke_utils.h" lapack_int LAPACKE_chegv( int matrix_layout, lapack_int itype, char jobz, char uplo, lapack_int n, lapack_complex_float* a, lapack_int lda, lapack_complex_float* b, lapack_int ldb, float* w ) { lapack_int info = 0; lapack_int lwork = -1; float* rwork = NULL; lapack_complex_float* work = NULL; lapack_complex_float work_query; if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { LAPACKE_xerbla( "LAPACKE_chegv", -1 ); return -1; } #ifndef LAPACK_DISABLE_NAN_CHECK if( LAPACKE_get_nancheck() ) { /* Optionally check input matrices for NaNs */ if( LAPACKE_cge_nancheck( matrix_layout, n, n, a, lda ) ) { return -6; } if( LAPACKE_cge_nancheck( matrix_layout, n, n, b, ldb ) ) { return -8; } } #endif /* Allocate memory for working array(s) */ rwork = (float*)LAPACKE_malloc( sizeof(float) * MAX(1,3*n-2) ); if( rwork == NULL ) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_0; } /* Query optimal working array(s) size */ info = LAPACKE_chegv_work( matrix_layout, itype, jobz, uplo, n, a, lda, b, ldb, w, &work_query, lwork, rwork ); if( info != 0 ) { goto exit_level_1; } lwork = LAPACK_C2INT( work_query ); /* Allocate memory for work arrays */ work = (lapack_complex_float*) LAPACKE_malloc( sizeof(lapack_complex_float) * lwork ); if( work == NULL ) { info = LAPACK_WORK_MEMORY_ERROR; goto exit_level_1; } /* Call middle-level interface */ info = LAPACKE_chegv_work( matrix_layout, itype, jobz, uplo, n, a, lda, b, ldb, w, work, lwork, rwork ); /* Release memory and exit */ LAPACKE_free( work ); exit_level_1: LAPACKE_free( rwork ); exit_level_0: if( info == LAPACK_WORK_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_chegv", info ); } return info; }
{ "content_hash": "ac4f2b1bd357c4cba6684b8964a3dd06", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 82, "avg_line_length": 33.91935483870968, "alnum_prop": 0.5534950071326676, "repo_name": "kortschak/OpenBLAS", "id": "15d052987c4ae9e59570a390ecb4e53e7dd3eb9d", "size": "4004", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "lapack-netlib/LAPACKE/src/lapacke_chegv.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "23981985" }, { "name": "C", "bytes": "15190595" }, { "name": "C++", "bytes": "1099781" }, { "name": "CMake", "bytes": "134766" }, { "name": "Fortran", "bytes": "43527138" }, { "name": "Makefile", "bytes": "776579" }, { "name": "Matlab", "bytes": "9066" }, { "name": "PHP", "bytes": "85" }, { "name": "Perl", "bytes": "95075" }, { "name": "Perl 6", "bytes": "1924" }, { "name": "Python", "bytes": "25590" }, { "name": "R", "bytes": "3213" }, { "name": "Shell", "bytes": "3049" }, { "name": "TeX", "bytes": "71758" } ], "symlink_target": "" }
#include "tclInt.h" #include <ctype.h> #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif #ifndef NULL #define NULL 0 #endif static int maxExponent = 511; /* Largest possible base 10 exponent. Any * exponent larger than this will already * produce underflow or overflow, so there's * no need to worry about additional digits. */ static double powersOf10[] = { /* Table giving binary powers of 10. Entry */ 10., /* is 10^2^i. Used to convert decimal */ 100., /* exponents into floating-point numbers. */ 1.0e4, 1.0e8, 1.0e16, 1.0e32, 1.0e64, 1.0e128, 1.0e256 }; /* *---------------------------------------------------------------------- * * strtod -- * * This procedure converts a floating-point number from an ASCII * decimal representation to internal double-precision format. * * Results: * The return value is the double-precision floating-point * representation of the characters in string. If endPtr isn't * NULL, then *endPtr is filled in with the address of the * next character after the last one that was part of the * floating-point number. * * Side effects: * None. * *---------------------------------------------------------------------- */ double strtod( CONST char *string, /* A decimal ASCII floating-point number, * optionally preceded by white space. Must * have form "-I.FE-X", where I is the integer * part of the mantissa, F is the fractional * part of the mantissa, and X is the * exponent. Either of the signs may be "+", * "-", or omitted. Either I or F may be * omitted, or both. The decimal point isn't * necessary unless F is present. The "E" may * actually be an "e". E and X may both be * omitted (but not just one). */ char **endPtr) /* If non-NULL, store terminating character's * address here. */ { int sign, expSign = FALSE; double fraction, dblExp, *d; register CONST char *p; register int c; int exp = 0; /* Exponent read from "EX" field. */ int fracExp = 0; /* Exponent that derives from the fractional * part. Under normal circumstatnces, it is * the negative of the number of digits in F. * However, if I is very long, the last digits * of I get dropped (otherwise a long I with a * large negative exponent could cause an * unnecessary overflow on I alone). In this * case, fracExp is incremented one for each * dropped digit. */ int mantSize; /* Number of digits in mantissa. */ int decPt; /* Number of mantissa digits BEFORE decimal * point. */ CONST char *pExp; /* Temporarily holds location of exponent in * string. */ /* * Strip off leading blanks and check for a sign. */ p = string; while (isspace(UCHAR(*p))) { p += 1; } if (*p == '-') { sign = TRUE; p += 1; } else { if (*p == '+') { p += 1; } sign = FALSE; } /* * Count the number of digits in the mantissa (including the decimal * point), and also locate the decimal point. */ decPt = -1; for (mantSize = 0; ; mantSize += 1) { c = *p; if (!isdigit(c)) { if ((c != '.') || (decPt >= 0)) { break; } decPt = mantSize; } p += 1; } /* * Now suck up the digits in the mantissa. Use two integers to collect 9 * digits each (this is faster than using floating-point). If the mantissa * has more than 18 digits, ignore the extras, since they can't affect the * value anyway. */ pExp = p; p -= mantSize; if (decPt < 0) { decPt = mantSize; } else { mantSize -= 1; /* One of the digits was the point. */ } if (mantSize > 18) { fracExp = decPt - 18; mantSize = 18; } else { fracExp = decPt - mantSize; } if (mantSize == 0) { fraction = 0.0; p = string; goto done; } else { int frac1, frac2; frac1 = 0; for ( ; mantSize > 9; mantSize -= 1) { c = *p; p += 1; if (c == '.') { c = *p; p += 1; } frac1 = 10*frac1 + (c - '0'); } frac2 = 0; for (; mantSize > 0; mantSize -= 1) { c = *p; p += 1; if (c == '.') { c = *p; p += 1; } frac2 = 10*frac2 + (c - '0'); } fraction = (1.0e9 * frac1) + frac2; } /* * Skim off the exponent. */ p = pExp; if ((*p == 'E') || (*p == 'e')) { p += 1; if (*p == '-') { expSign = TRUE; p += 1; } else { if (*p == '+') { p += 1; } expSign = FALSE; } if (!isdigit(UCHAR(*p))) { p = pExp; goto done; } while (isdigit(UCHAR(*p))) { exp = exp * 10 + (*p - '0'); p += 1; } } if (expSign) { exp = fracExp - exp; } else { exp = fracExp + exp; } /* * Generate a floating-point number that represents the exponent. Do this * by processing the exponent one bit at a time to combine many powers of * 2 of 10. Then combine the exponent with the fraction. */ if (exp < 0) { expSign = TRUE; exp = -exp; } else { expSign = FALSE; } if (exp > maxExponent) { exp = maxExponent; errno = ERANGE; } dblExp = 1.0; for (d = powersOf10; exp != 0; exp >>= 1, d += 1) { if (exp & 01) { dblExp *= *d; } } if (expSign) { fraction /= dblExp; } else { fraction *= dblExp; } done: if (endPtr != NULL) { *endPtr = (char *) p; } if (sign) { return -fraction; } return fraction; }
{ "content_hash": "464f52f53c4b93bcbc0d5403e4382dac", "timestamp": "", "source": "github", "line_count": 243, "max_line_length": 78, "avg_line_length": 22.54320987654321, "alnum_prop": 0.5397955458196422, "repo_name": "neverpanic/macports-base", "id": "1147825afb05e95991623071a7d3b3add3f88fe2", "size": "5810", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/tcl8.5.19/compat/strtod.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1021718" }, { "name": "M4", "bytes": "92664" }, { "name": "Makefile", "bytes": "27709" }, { "name": "Rich Text Format", "bytes": "6806" }, { "name": "Shell", "bytes": "39105" }, { "name": "Tcl", "bytes": "1504725" } ], "symlink_target": "" }
import { Provider } from 'mobx-react' import { ROUTE, ARTICLE_THREAD, METRIC } from '@/constant' import { ssrBaseStates, ssrFetchPrepare, ssrError, articleSEO, ssrGetParam, refreshIfneed, } from '@/utils' import { useStore } from '@/stores/init' import GlobalLayout from '@/containers/layout/GlobalLayout' import ArticleDigest from '@/containers/digest/ArticleDigest' import ArticleContent from '@/containers/content/ArticleContent' import { P } from '@/schemas' const loader = async (context, opt = {}) => { const id = ssrGetParam(context, 'id') const { gqClient, userHasLogin } = ssrFetchPrepare(context, opt) // query data const sessionState = gqClient.request(P.sessionState) const blog = gqClient.request(P.blog, { id, userHasLogin }) const subscribedCommunities = gqClient.request(P.subscribedCommunities, { filter: { page: 1, size: 30, }, }) return { ...(await sessionState), ...(await blog), ...(await subscribedCommunities), } } export const getServerSideProps = async (context) => { let resp try { resp = await loader(context) const { blog, sessionState } = resp refreshIfneed(sessionState, `/blog/${blog.id}`, context) } catch (e) { console.log('#### error from server: ', e) return ssrError(context, 'fetch', 500) } const { blog } = resp const initProps = { ...ssrBaseStates(resp), route: { mainPath: ROUTE.BLOG, subPath: blog.id }, viewing: { blog, activeThread: ARTICLE_THREAD.BLOG, }, } return { props: { errorCode: null, ...initProps } } } const BlogPage = (props) => { const store = useStore(props) const { viewing } = props const { blog } = viewing const seoConfig = articleSEO(ARTICLE_THREAD.BLOG, blog) return ( <Provider store={store}> <GlobalLayout metric={METRIC.BLOG_ARTICLE} seoConfig={seoConfig} noSidebar > <ArticleDigest /> <ArticleContent /> </GlobalLayout> </Provider> ) } export default BlogPage
{ "content_hash": "55d744035d284ea0c5b8694e4f27cab5", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 75, "avg_line_length": 23.25, "alnum_prop": 0.6456500488758553, "repo_name": "mydearxym/mastani", "id": "107fa256e16567a8c6f7ef6c298089e0ba3d3148", "size": "2046", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/pages/blog/[id].tsx", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "5475" }, { "name": "JavaScript", "bytes": "449787" } ], "symlink_target": "" }
# # # /* See http://www.boost.org for most recent version. */ # # include <boost/preprocessor/slot/detail/shared.hpp> # # undef BOOST_PP_ITERATION_START_2 # # undef BOOST_PP_ITERATION_START_2_DIGIT_1 # undef BOOST_PP_ITERATION_START_2_DIGIT_2 # undef BOOST_PP_ITERATION_START_2_DIGIT_3 # undef BOOST_PP_ITERATION_START_2_DIGIT_4 # undef BOOST_PP_ITERATION_START_2_DIGIT_5 # undef BOOST_PP_ITERATION_START_2_DIGIT_6 # undef BOOST_PP_ITERATION_START_2_DIGIT_7 # undef BOOST_PP_ITERATION_START_2_DIGIT_8 # undef BOOST_PP_ITERATION_START_2_DIGIT_9 # undef BOOST_PP_ITERATION_START_2_DIGIT_10 # # if BOOST_PP_SLOT_TEMP_3 == 0 # define BOOST_PP_ITERATION_START_2_DIGIT_3 0 # elif BOOST_PP_SLOT_TEMP_3 == 1 # define BOOST_PP_ITERATION_START_2_DIGIT_3 1 # elif BOOST_PP_SLOT_TEMP_3 == 2 # define BOOST_PP_ITERATION_START_2_DIGIT_3 2 # elif BOOST_PP_SLOT_TEMP_3 == 3 # define BOOST_PP_ITERATION_START_2_DIGIT_3 3 # elif BOOST_PP_SLOT_TEMP_3 == 4 # define BOOST_PP_ITERATION_START_2_DIGIT_3 4 # elif BOOST_PP_SLOT_TEMP_3 == 5 # define BOOST_PP_ITERATION_START_2_DIGIT_3 5 # elif BOOST_PP_SLOT_TEMP_3 == 6 # define BOOST_PP_ITERATION_START_2_DIGIT_3 6 # elif BOOST_PP_SLOT_TEMP_3 == 7 # define BOOST_PP_ITERATION_START_2_DIGIT_3 7 # elif BOOST_PP_SLOT_TEMP_3 == 8 # define BOOST_PP_ITERATION_START_2_DIGIT_3 8 # elif BOOST_PP_SLOT_TEMP_3 == 9 # define BOOST_PP_ITERATION_START_2_DIGIT_3 9 # endif # # if BOOST_PP_SLOT_TEMP_2 == 0 # define BOOST_PP_ITERATION_START_2_DIGIT_2 0 # elif BOOST_PP_SLOT_TEMP_2 == 1 # define BOOST_PP_ITERATION_START_2_DIGIT_2 1 # elif BOOST_PP_SLOT_TEMP_2 == 2 # define BOOST_PP_ITERATION_START_2_DIGIT_2 2 # elif BOOST_PP_SLOT_TEMP_2 == 3 # define BOOST_PP_ITERATION_START_2_DIGIT_2 3 # elif BOOST_PP_SLOT_TEMP_2 == 4 # define BOOST_PP_ITERATION_START_2_DIGIT_2 4 # elif BOOST_PP_SLOT_TEMP_2 == 5 # define BOOST_PP_ITERATION_START_2_DIGIT_2 5 # elif BOOST_PP_SLOT_TEMP_2 == 6 # define BOOST_PP_ITERATION_START_2_DIGIT_2 6 # elif BOOST_PP_SLOT_TEMP_2 == 7 # define BOOST_PP_ITERATION_START_2_DIGIT_2 7 # elif BOOST_PP_SLOT_TEMP_2 == 8 # define BOOST_PP_ITERATION_START_2_DIGIT_2 8 # elif BOOST_PP_SLOT_TEMP_2 == 9 # define BOOST_PP_ITERATION_START_2_DIGIT_2 9 # endif # # if BOOST_PP_SLOT_TEMP_1 == 0 # define BOOST_PP_ITERATION_START_2_DIGIT_1 0 # elif BOOST_PP_SLOT_TEMP_1 == 1 # define BOOST_PP_ITERATION_START_2_DIGIT_1 1 # elif BOOST_PP_SLOT_TEMP_1 == 2 # define BOOST_PP_ITERATION_START_2_DIGIT_1 2 # elif BOOST_PP_SLOT_TEMP_1 == 3 # define BOOST_PP_ITERATION_START_2_DIGIT_1 3 # elif BOOST_PP_SLOT_TEMP_1 == 4 # define BOOST_PP_ITERATION_START_2_DIGIT_1 4 # elif BOOST_PP_SLOT_TEMP_1 == 5 # define BOOST_PP_ITERATION_START_2_DIGIT_1 5 # elif BOOST_PP_SLOT_TEMP_1 == 6 # define BOOST_PP_ITERATION_START_2_DIGIT_1 6 # elif BOOST_PP_SLOT_TEMP_1 == 7 # define BOOST_PP_ITERATION_START_2_DIGIT_1 7 # elif BOOST_PP_SLOT_TEMP_1 == 8 # define BOOST_PP_ITERATION_START_2_DIGIT_1 8 # elif BOOST_PP_SLOT_TEMP_1 == 9 # define BOOST_PP_ITERATION_START_2_DIGIT_1 9 # endif # # if BOOST_PP_ITERATION_START_2_DIGIT_3 # define BOOST_PP_ITERATION_START_2 BOOST_PP_SLOT_CC_3(BOOST_PP_ITERATION_START_2_DIGIT_3, BOOST_PP_ITERATION_START_2_DIGIT_2, BOOST_PP_ITERATION_START_2_DIGIT_1) # elif BOOST_PP_ITERATION_START_2_DIGIT_2 # define BOOST_PP_ITERATION_START_2 BOOST_PP_SLOT_CC_2(BOOST_PP_ITERATION_START_2_DIGIT_2, BOOST_PP_ITERATION_START_2_DIGIT_1) # else # define BOOST_PP_ITERATION_START_2 BOOST_PP_ITERATION_START_2_DIGIT_1 # endif
{ "content_hash": "5b0010c74bbed9de3db4d55fbf2fa9c9", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 165, "avg_line_length": 38.5, "alnum_prop": 0.6998870694522868, "repo_name": "OLR-xray/OLR-3.0", "id": "f05a229af62196743d10bd1e3f915286082ae2cd", "size": "4260", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/3rd party/boost/boost/preprocessor/iteration/detail/bounds/lower2.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "24445" }, { "name": "Batchfile", "bytes": "25756" }, { "name": "C", "bytes": "24938895" }, { "name": "C++", "bytes": "47400139" }, { "name": "CMake", "bytes": "6042" }, { "name": "Cuda", "bytes": "36172" }, { "name": "Groff", "bytes": "287360" }, { "name": "HTML", "bytes": "67830" }, { "name": "MAXScript", "bytes": "975" }, { "name": "Makefile", "bytes": "16965" }, { "name": "Objective-C", "bytes": "181404" }, { "name": "Pascal", "bytes": "2978785" }, { "name": "Perl", "bytes": "13337" }, { "name": "PostScript", "bytes": "10774" }, { "name": "Python", "bytes": "5517" }, { "name": "Shell", "bytes": "956624" }, { "name": "TeX", "bytes": "762124" }, { "name": "xBase", "bytes": "151778" } ], "symlink_target": "" }
<?php /*-----------------------------------------------------------------------------------------------------// /* Theme Setup /*-----------------------------------------------------------------------------------------------------*/ if ( ! function_exists( 'swelllite_setup' ) ) : function swelllite_setup() { // Make theme available for translation load_theme_textdomain( 'swelllite', get_template_directory() . '/languages' ); // Add default posts and comments RSS feed links to head add_theme_support( 'automatic-feed-links' ); // Enable support for Post Thumbnails add_theme_support( 'post-thumbnails' ); // Enable support for site title tag add_theme_support( 'title-tag' ); add_image_size( 'swell-featured-large', 1800, 1200, true ); // Large Featured Image add_image_size( 'swell-featured-medium', 1200, 800, true ); // Medium Featured Image add_image_size( 'swell-featured-small', 640, 640, true ); // Small Featured Image // Create Menus register_nav_menus( array( 'fixed-menu' => __( 'Fixed Menu', 'swelllite' ), 'main-menu' => __( 'Main Menu', 'swelllite' ), 'social-menu' => __( 'Social Menu', 'swelllite' ), )); // Custom Header $defaults = array( 'width' => 1800, 'height' => 480, 'flex-height' => true, 'flex-width' => true, 'default-text-color' => '333333', 'header-text' => false, 'uploads' => true, ); add_theme_support( 'custom-header', $defaults ); // Custom Background $defaults = array( 'default-color' => 'eeeeee', ); add_theme_support( 'custom-background', $defaults ); } endif; // swelllite_setup add_action( 'after_setup_theme', 'swelllite_setup' ); /*-----------------------------------------------------------------------------------------------------// Category ID to Name -------------------------------------------------------------------------------------------------------*/ function swelllite_cat_id_to_name( $id ) { $cat = get_category( $id ); if ( is_wp_error( $cat ) ) return false; return $cat->cat_name; } /*-----------------------------------------------------------------------------------------------------// Register Scripts -------------------------------------------------------------------------------------------------------*/ if( !function_exists('swelllite_enqueue_scripts') ) { function swelllite_enqueue_scripts() { // Enqueue Styles wp_enqueue_style( 'swell-style', get_stylesheet_uri() ); wp_enqueue_style( 'swell-style-mobile', get_template_directory_uri() . '/css/style-mobile.css', array( 'swell-style' ), '1.0' ); wp_enqueue_style( 'font-awesome', get_template_directory_uri() . '/css/font-awesome.css', array( 'swell-style' ), '1.0' ); // Enqueue Scripts wp_enqueue_script( 'swell-html5shiv', get_template_directory_uri() . '/js/html5shiv.js' ); wp_enqueue_script( 'swell-fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array( 'jquery' ), '20130729' ); wp_enqueue_script( 'swell-hover', get_template_directory_uri() . '/js/hoverIntent.js', array( 'jquery' ), '20130729' ); wp_enqueue_script( 'swell-superfish', get_template_directory_uri() . '/js/superfish.js', array( 'jquery', 'swell-hover' ), '20130729' ); wp_enqueue_script( 'swell-custom', get_template_directory_uri() . '/js/jquery.custom.js', array( 'jquery', 'swell-superfish', 'swell-fitvids' ), '20130729', true ); wp_enqueue_script( 'swell-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20130729', true ); // IE Conditional Scripts global $wp_scripts; $wp_scripts->add_data( 'swell-html5shiv', 'conditional', 'lt IE 9' ); // Load single scripts only on single pages if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } } add_action('wp_enqueue_scripts', 'swelllite_enqueue_scripts'); /*-----------------------------------------------------------------------------------------------------// Register Sidebars -------------------------------------------------------------------------------------------------------*/ function swelllite_widgets_init() { register_sidebar(array( 'name'=> __( "Default Sidebar", 'swelllite' ), 'id' => 'default-sidebar', 'before_widget'=>'<div id="%1$s" class="widget %2$s">', 'after_widget'=>'</div>', 'before_title'=>'<h6 class="title">', 'after_title'=>'</h6>' )); register_sidebar(array( 'name'=> __( "Blog Sidebar", 'swelllite' ), 'id' => 'blog-sidebar', 'before_widget'=>'<div id="%1$s" class="widget %2$s">', 'after_widget'=>'</div>', 'before_title'=>'<h6 class="title">', 'after_title'=>'</h6>' )); register_sidebar(array( 'name'=> __( "Footer Widgets", 'swelllite' ), 'id' => 'footer', 'before_widget'=>'<div id="%1$s" class="widget %2$s"><div class="footer-widget">', 'after_widget'=>'</div></div>', 'before_title'=>'<h6 class="title">', 'after_title'=>'</h6>' )); } add_action( 'widgets_init', 'swelllite_widgets_init' ); /*-----------------------------------------------------------------------------------------------------// Add Stylesheet To Visual Editor -------------------------------------------------------------------------------------------------------*/ add_action( 'widgets_init', 'swelllite_add_editor_styles' ); /** * Apply theme's stylesheet to the visual editor. * * @uses add_editor_style() Links a stylesheet to visual editor * @uses get_stylesheet_uri() Returns URI of theme stylesheet */ function swelllite_add_editor_styles() { add_editor_style( 'css/style-editor.css' ); } /*----------------------------------------------------------------------------------------------------// /* Content Width /*----------------------------------------------------------------------------------------------------*/ if ( ! isset( $content_width ) ) $content_width = 640; /** * Adjust content_width value based on the presence of widgets */ function swelllite_content_width() { if ( ! is_active_sidebar( 'post-sidebar' ) || is_active_sidebar( 'page-sidebar' ) || is_active_sidebar( 'blog-sidebar' ) ) { global $content_width; $content_width = 960; } } add_action( 'template_redirect', 'swelllite_content_width' ); /*-----------------------------------------------------------------------------------------------------// Comments Function -------------------------------------------------------------------------------------------------------*/ if ( ! function_exists( 'swelllite_comment' ) ) : function swelllite_comment( $comment, $args, $depth ) { $GLOBALS['comment'] = $comment; switch ( $comment->comment_type ) : case 'pingback' : case 'trackback' : ?> <li class="post pingback"> <p><?php _e( 'Pingback:', 'swelllite' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( 'Edit', 'swelllite' ), '<span class="edit-link">', '</span>' ); ?></p> <?php break; default : ?> <li <?php comment_class(); ?> id="<?php echo esc_attr( 'li-comment-' . get_comment_ID() ); ?>"> <article id="<?php echo esc_attr( 'comment-' . get_comment_ID() ); ?>" class="comment"> <footer class="comment-meta"> <div class="comment-author vcard"> <?php $avatar_size = 72; if ( '0' != $comment->comment_parent ) $avatar_size = 48; echo get_avatar( $comment, $avatar_size ); /* translators: 1: comment author, 2: date and time */ printf( __( '%1$s <br/> %2$s <br/>', 'swelllite' ), sprintf( '<span class="fn">%s</span>', wp_kses_post( get_comment_author_link() ) ), sprintf( '<a href="%1$s"><time pubdate datetime="%2$s">%3$s</time></a>', esc_url( get_comment_link( $comment->comment_ID ) ), get_comment_time( 'c' ), /* translators: 1: date, 2: time */ sprintf( __( '%1$s', 'swelllite' ), get_comment_date(), get_comment_time() ) ) ); ?> </div><!-- .comment-author .vcard --> </footer> <div class="comment-content"> <?php if ( $comment->comment_approved == '0' ) : ?> <em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'swelllite' ); ?></em> <br /> <?php endif; ?> <?php comment_text(); ?> <div class="reply"> <?php comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply', 'swelllite' ), 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> </div><!-- .reply --> <?php edit_comment_link( __( 'Edit', 'swelllite' ), '<span class="edit-link">', '</span>' ); ?> </div> </article><!-- #comment-## --> <?php break; endswitch; } endif; // ends check for swelllite_comment() /*-----------------------------------------------------------------------------------------------------// Comments Disabled On Pages By Default -------------------------------------------------------------------------------------------------------*/ function swelllite_default_comments_off( $data ) { if( $data['post_type'] == 'page' && $data['post_status'] == 'auto-draft' ) { $data['comment_status'] = 0; } return $data; } add_filter( 'wp_insert_post_data', 'swelllite_default_comments_off' ); /*-----------------------------------------------------------------------------------------------------// Custom Excerpt Length -------------------------------------------------------------------------------------------------------*/ function swelllite_excerpt_length( $length ) { return 38; } add_filter( 'excerpt_length', 'swelllite_excerpt_length', 999 ); function swelllite_excerpt_more( $more ) { return '... <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">'. __('Read More', 'swelllite') .'</a>'; } add_filter('excerpt_more', 'swelllite_excerpt_more'); /*-----------------------------------------------------------------------------------------------------// Add Excerpt To Pages -------------------------------------------------------------------------------------------------------*/ add_action( 'init', 'swelllite_add_excerpts_to_pages' ); function swelllite_add_excerpts_to_pages() { add_post_type_support( 'page', 'excerpt' ); } /*-----------------------------------------------------------------------------------------------------// /* Pagination Function /*-----------------------------------------------------------------------------------------------------*/ function swelllite_get_pagination_links() { global $wp_query; $big = 999999999; echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'prev_text' => __('&laquo;', 'swelllite'), 'next_text' => __('&raquo;', 'swelllite'), 'total' => $wp_query->max_num_pages ) ); } /*-----------------------------------------------------------------------------------------------------// /* Custom Page Links /*-----------------------------------------------------------------------------------------------------*/ function swelllite_wp_link_pages_args_prevnext_add($args) { global $page, $numpages, $more, $pagenow; if (!$args['next_or_number'] == 'next_and_number') return $args; $args['next_or_number'] = 'number'; // Keep numbering for the main part if (!$more) return $args; if($page-1) // There is a previous page $args['before'] .= _wp_link_page($page-1) . $args['link_before']. $args['previouspagelink'] . $args['link_after'] . '</a>'; if ($page<$numpages) // There is a next page $args['after'] = _wp_link_page($page+1) . $args['link_before'] . $args['nextpagelink'] . $args['link_after'] . '</a>' . $args['after']; return $args; } add_filter('wp_link_pages_args', 'swelllite_wp_link_pages_args_prevnext_add'); /*-----------------------------------------------------------------------------------------------------// Add Home Link To Custom Menu -------------------------------------------------------------------------------------------------------*/ function home_page_menu_args( $args ) { $args['show_home'] = true; return $args; } add_filter('wp_page_menu_args', 'home_page_menu_args'); /*-----------------------------------------------------------------------------------------------------// Strip inline width and height attributes from WP generated images -------------------------------------------------------------------------------------------------------*/ function remove_thumbnail_dimensions( $html ) { $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html ); return $html; } add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10 ); add_filter( 'image_send_to_editor', 'remove_thumbnail_dimensions', 10 ); /*-----------------------------------------------------------------------------------------------------// Body Class -------------------------------------------------------------------------------------------------------*/ function swelllite_body_class( $classes ) { if ( is_singular() ) $classes[] = 'swell-singular'; if ( is_active_sidebar( 'right-sidebar' ) ) $classes[] = 'swell-right-sidebar'; if ( '' != get_theme_mod( 'background_image' ) ) { // This class will render when a background image is set // regardless of whether the user has set a color as well. $classes[] = 'swell-background-image'; } else if ( ! in_array( get_background_color(), array( '', get_theme_support( 'custom-background', 'default-color' ) ) ) ) { // This class will render when a background color is set // but no image is set. In the case the content text will // Adjust relative to the background color. $classes[] = 'swell-relative-text'; } return $classes; } add_action( 'body_class', 'swelllite_body_class' ); /*-----------------------------------------------------------------------------------------------------// Includes -------------------------------------------------------------------------------------------------------*/ require_once( get_template_directory() . '/includes/jetpack.php' ); require_once( get_template_directory() . '/includes/customizer.php' ); require_once( get_template_directory() . '/includes/typefaces.php' );
{ "content_hash": "14f6b056eab2e9508727e727ef356504", "timestamp": "", "source": "github", "line_count": 360, "max_line_length": 176, "avg_line_length": 40.05277777777778, "alnum_prop": 0.46674526666204313, "repo_name": "ManueReva13/fantine", "id": "2383407e43b47c73fe5979f0aa0e4fe409d008eb", "size": "14419", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "wordpress/wp-content/themes/swell-lite/functions.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1704757" }, { "name": "HTML", "bytes": "47427" }, { "name": "JavaScript", "bytes": "1860761" }, { "name": "PHP", "bytes": "9214834" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Package com.google.zxing.aztec.encoder (ZXing 3.4.1 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package com.google.zxing.aztec.encoder (ZXing 3.4.1 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/google/zxing/aztec/encoder/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package com.google.zxing.aztec.encoder" class="title">Uses of Package<br>com.google.zxing.aztec.encoder</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/google/zxing/aztec/encoder/package-summary.html">com.google.zxing.aztec.encoder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.google.zxing.aztec.encoder">com.google.zxing.aztec.encoder</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.google.zxing.aztec.encoder"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../com/google/zxing/aztec/encoder/package-summary.html">com.google.zxing.aztec.encoder</a> used by <a href="../../../../../com/google/zxing/aztec/encoder/package-summary.html">com.google.zxing.aztec.encoder</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../com/google/zxing/aztec/encoder/class-use/AztecCode.html#com.google.zxing.aztec.encoder">AztecCode</a> <div class="block">Aztec 2D code representation</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/google/zxing/aztec/encoder/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2007&#x2013;2020. All rights reserved.</small></p> </body> </html>
{ "content_hash": "63715138f35a56d36aed9c4ee6f863ab", "timestamp": "", "source": "github", "line_count": 160, "max_line_length": 308, "avg_line_length": 35.5625, "alnum_prop": 0.6267135325131811, "repo_name": "tanelihuuskonen/zxing", "id": "948d6218fe455e5072ba6ed65d98f0ca6b097e01", "size": "5690", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/apidocs/com/google/zxing/aztec/encoder/package-use.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3419" }, { "name": "HTML", "bytes": "98457" }, { "name": "Java", "bytes": "2343865" } ], "symlink_target": "" }
require 'aws-sdk' module CSI module AWS # This module provides a client for making API requests to Amazon CloudWatch Logs. module CloudWatchLogs @@logger = CSI::Plugins::CSILogger.create # Supported Method Parameters:: # CSI::AWS::CloudWatchLogs.connect( # region: 'required - region name to connect (eu-west-1, ap-southeast-1, ap-southeast-2, eu-central-1, ap-northeast-2, ap-northeast-1, us-east-1, sa-east-1, us-west-1, us-west-2)', # access_key_id: 'required - Use AWS STS for best privacy (i.e. temporary access key id)', # secret_access_key: 'required - Use AWS STS for best privacy (i.e. temporary secret access key', # sts_session_token: 'optional - Temporary token returned by STS client for best privacy' # ) public_class_method def self.connect(opts = {}) region = opts[:region].to_s.scrub.chomp.strip access_key_id = opts[:access_key_id].to_s.scrub.chomp.strip secret_access_key = opts[:secret_access_key].to_s.scrub.chomp.strip sts_session_token = opts[:sts_session_token].to_s.scrub.chomp.strip @@logger.info('Connecting to AWS CloudWatchLogs...') if sts_session_token == '' cloud_watch_logs_obj = Aws::CloudWatchLogs::Client.new( region: region, access_key_id: access_key_id, secret_access_key: secret_access_key ) else cloud_watch_logs_obj = Aws::CloudWatchLogs::Client.new( region: region, access_key_id: access_key_id, secret_access_key: secret_access_key, session_token: sts_session_token ) end @@logger.info("complete.\n") cloud_watch_logs_obj rescue StandardError => e raise e end # Supported Method Parameters:: # CSI::AWS::CloudWatchLogs.disconnect( # cloud_watch_logs_obj: 'required - cloud_watch_logs_obj returned from #connect method' # ) public_class_method def self.disconnect(opts = {}) cloud_watch_logs_obj = opts[:cloud_watch_logs_obj] @@logger.info('Disconnecting...') cloud_watch_logs_obj = nil @@logger.info("complete.\n") cloud_watch_logs_obj rescue StandardError => e raise e end # Author(s):: Jacob Hoopes <jake.hoopes@gmail.com> public_class_method def self.authors "AUTHOR(S): Jacob Hoopes <jake.hoopes@gmail.com> " end # Display Usage for this Module public_class_method def self.help puts "USAGE: cloud_watch_logs_obj = #{self}.connect( region: 'required - region name to connect (eu-west-1, ap-southeast-1, ap-southeast-2, eu-central-1, ap-northeast-2, ap-northeast-1, us-east-1, sa-east-1, us-west-1, us-west-2)', access_key_id: 'required - Use AWS STS for best privacy (i.e. temporary access key id)', secret_access_key: 'required - Use AWS STS for best privacy (i.e. temporary secret access key', sts_session_token: 'optional - Temporary token returned by STS client for best privacy' ) puts cloud_watch_logs_obj.public_methods #{self}.disconnect( cloud_watch_logs_obj: 'required - cloud_watch_logs_obj returned from #connect method' ) #{self}.authors " end end end end
{ "content_hash": "a776629375ab963460025c9a29c3a755", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 190, "avg_line_length": 38.01111111111111, "alnum_prop": 0.6112247880736627, "repo_name": "ninp0/csi", "id": "95b21c842b4579934fec316dedf55523634369e7", "size": "3452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/csi/aws/cloud_watch_logs.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "1351941" }, { "name": "Shell", "bytes": "72652" } ], "symlink_target": "" }
namespace Google.Cloud.AutoML.V1.Snippets { // [START automl_v1_generated_PredictionService_Predict_sync_flattened] using Google.Cloud.AutoML.V1; using System.Collections.Generic; public sealed partial class GeneratedPredictionServiceClientSnippets { /// <summary>Snippet for Predict</summary> /// <remarks> /// This snippet has been automatically generated and should be regarded as a code template only. /// It will require modifications to work: /// - It may require correct/in-range values for request initialization. /// - It may require specifying regional endpoints when creating the service client as shown in /// https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint. /// </remarks> public void Predict() { // Create client PredictionServiceClient predictionServiceClient = PredictionServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/models/[MODEL]"; ExamplePayload payload = new ExamplePayload(); IDictionary<string, string> @params = new Dictionary<string, string> { { "", "" }, }; // Make the request PredictResponse response = predictionServiceClient.Predict(name, payload, @params); } } // [END automl_v1_generated_PredictionService_Predict_sync_flattened] }
{ "content_hash": "eaba256d4f2e399977ae45501ca0427e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 105, "avg_line_length": 49.3, "alnum_prop": 0.665314401622718, "repo_name": "googleapis/google-cloud-dotnet", "id": "76dd49cb82694008f3f8f61769b19243111aef65", "size": "2101", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "apis/Google.Cloud.AutoML.V1/Google.Cloud.AutoML.V1.GeneratedSnippets/PredictionServiceClient.PredictSnippet.g.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "767" }, { "name": "C#", "bytes": "319820004" }, { "name": "Dockerfile", "bytes": "3415" }, { "name": "PowerShell", "bytes": "3303" }, { "name": "Python", "bytes": "2744" }, { "name": "Shell", "bytes": "65881" } ], "symlink_target": "" }
{-# OPTIONS -cpp #-} {-# OPTIONS_GHC -O -funbox-strict-fields #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- -- (c) The University of Glasgow 2002-2006 -- -- Binary I/O library, with special tweaks for GHC -- -- Based on the nhc98 Binary library, which is copyright -- (c) Malcolm Wallace and Colin Runciman, University of York, 1998. -- Under the terms of the license for that software, we must tell you -- where you can obtain the original version of the Binary library, namely -- http://www.cs.york.ac.uk/fp/nhc98/ module Binary ( {-type-} Bin, {-class-} Binary(..), {-type-} BinHandle, SymbolTable, Dictionary, openBinMem, -- closeBin, seekBin, seekBy, tellBin, castBin, writeBinMem, readBinMem, fingerprintBinMem, computeFingerprint, isEOFBin, putAt, getAt, -- for writing instances: putByte, getByte, -- lazy Bin I/O lazyGet, lazyPut, #ifdef __GLASGOW_HASKELL__ -- GHC only: ByteArray(..), getByteArray, putByteArray, #endif UserData(..), getUserData, setUserData, newReadState, newWriteState, putDictionary, getDictionary, putFS, ) where #include "HsVersions.h" -- The *host* architecture version: #include "../includes/MachDeps.h" import {-# SOURCE #-} Name (Name) import FastString import Panic import UniqFM import FastMutInt import Fingerprint import BasicTypes import Foreign import Data.Array import Data.ByteString (ByteString) import qualified Data.ByteString.Internal as BS import qualified Data.ByteString.Unsafe as BS import Data.IORef import Data.Char ( ord, chr ) import Data.Time import Data.Typeable import Data.Typeable.Internal import Control.Monad ( when ) import System.IO as IO import System.IO.Unsafe ( unsafeInterleaveIO ) import System.IO.Error ( mkIOError, eofErrorType ) import GHC.Real ( Ratio(..) ) import ExtsCompat46 import GHC.Word ( Word8(..) ) import GHC.IO ( IO(..) ) type BinArray = ForeignPtr Word8 --------------------------------------------------------------- -- BinHandle --------------------------------------------------------------- data BinHandle = BinMem { -- binary data stored in an unboxed array bh_usr :: UserData, -- sigh, need parameterized modules :-) _off_r :: !FastMutInt, -- the current offset _sz_r :: !FastMutInt, -- size of the array (cached) _arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1)) } -- XXX: should really store a "high water mark" for dumping out -- the binary data to a file. getUserData :: BinHandle -> UserData getUserData bh = bh_usr bh setUserData :: BinHandle -> UserData -> BinHandle setUserData bh us = bh { bh_usr = us } --------------------------------------------------------------- -- Bin --------------------------------------------------------------- newtype Bin a = BinPtr Int deriving (Eq, Ord, Show, Bounded) castBin :: Bin a -> Bin b castBin (BinPtr i) = BinPtr i --------------------------------------------------------------- -- class Binary --------------------------------------------------------------- class Binary a where put_ :: BinHandle -> a -> IO () put :: BinHandle -> a -> IO (Bin a) get :: BinHandle -> IO a -- define one of put_, put. Use of put_ is recommended because it -- is more likely that tail-calls can kick in, and we rarely need the -- position return value. put_ bh a = do _ <- put bh a; return () put bh a = do p <- tellBin bh; put_ bh a; return p putAt :: Binary a => BinHandle -> Bin a -> a -> IO () putAt bh p x = do seekBin bh p; put_ bh x; return () getAt :: Binary a => BinHandle -> Bin a -> IO a getAt bh p = do seekBin bh p; get bh openBinMem :: Int -> IO BinHandle openBinMem size | size <= 0 = error "Data.Binary.openBinMem: size must be >= 0" | otherwise = do arr <- mallocForeignPtrBytes size arr_r <- newIORef arr ix_r <- newFastMutInt writeFastMutInt ix_r 0 sz_r <- newFastMutInt writeFastMutInt sz_r size return (BinMem noUserData ix_r sz_r arr_r) tellBin :: BinHandle -> IO (Bin a) tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix) seekBin :: BinHandle -> Bin a -> IO () seekBin h@(BinMem _ ix_r sz_r _) (BinPtr p) = do sz <- readFastMutInt sz_r if (p >= sz) then do expandBin h p; writeFastMutInt ix_r p else writeFastMutInt ix_r p seekBy :: BinHandle -> Int -> IO () seekBy h@(BinMem _ ix_r sz_r _) off = do sz <- readFastMutInt sz_r ix <- readFastMutInt ix_r let ix' = ix + off if (ix' >= sz) then do expandBin h ix'; writeFastMutInt ix_r ix' else writeFastMutInt ix_r ix' isEOFBin :: BinHandle -> IO Bool isEOFBin (BinMem _ ix_r sz_r _) = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r return (ix >= sz) writeBinMem :: BinHandle -> FilePath -> IO () writeBinMem (BinMem _ ix_r _ arr_r) fn = do h <- openBinaryFile fn WriteMode arr <- readIORef arr_r ix <- readFastMutInt ix_r withForeignPtr arr $ \p -> hPutBuf h p ix hClose h readBinMem :: FilePath -> IO BinHandle -- Return a BinHandle with a totally undefined State readBinMem filename = do h <- openBinaryFile filename ReadMode filesize' <- hFileSize h let filesize = fromIntegral filesize' arr <- mallocForeignPtrBytes (filesize*2) count <- withForeignPtr arr $ \p -> hGetBuf h p filesize when (count /= filesize) $ error ("Binary.readBinMem: only read " ++ show count ++ " bytes") hClose h arr_r <- newIORef arr ix_r <- newFastMutInt writeFastMutInt ix_r 0 sz_r <- newFastMutInt writeFastMutInt sz_r filesize return (BinMem noUserData ix_r sz_r arr_r) fingerprintBinMem :: BinHandle -> IO Fingerprint fingerprintBinMem (BinMem _ ix_r _ arr_r) = do arr <- readIORef arr_r ix <- readFastMutInt ix_r withForeignPtr arr $ \p -> fingerprintData p ix computeFingerprint :: Binary a => (BinHandle -> Name -> IO ()) -> a -> IO Fingerprint computeFingerprint put_name a = do bh <- openBinMem (3*1024) -- just less than a block bh <- return $ setUserData bh $ newWriteState put_name putFS put_ bh a fingerprintBinMem bh -- expand the size of the array to include a specified offset expandBin :: BinHandle -> Int -> IO () expandBin (BinMem _ _ sz_r arr_r) off = do sz <- readFastMutInt sz_r let sz' = head (dropWhile (<= off) (iterate (* 2) sz)) arr <- readIORef arr_r arr' <- mallocForeignPtrBytes sz' withForeignPtr arr $ \old -> withForeignPtr arr' $ \new -> copyBytes new old sz writeFastMutInt sz_r sz' writeIORef arr_r arr' -- ----------------------------------------------------------------------------- -- Low-level reading/writing of bytes putWord8 :: BinHandle -> Word8 -> IO () putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r -- double the size of the array if it overflows if (ix >= sz) then do expandBin h ix putWord8 h w else do arr <- readIORef arr_r withForeignPtr arr $ \p -> pokeByteOff p ix w writeFastMutInt ix_r (ix+1) return () getWord8 :: BinHandle -> IO Word8 getWord8 (BinMem _ ix_r sz_r arr_r) = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r when (ix >= sz) $ ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing) arr <- readIORef arr_r w <- withForeignPtr arr $ \p -> peekByteOff p ix writeFastMutInt ix_r (ix+1) return w putByte :: BinHandle -> Word8 -> IO () putByte bh w = put_ bh w getByte :: BinHandle -> IO Word8 getByte = getWord8 -- ----------------------------------------------------------------------------- -- Primitve Word writes instance Binary Word8 where put_ = putWord8 get = getWord8 instance Binary Word16 where put_ h w = do -- XXX too slow.. inline putWord8? putByte h (fromIntegral (w `shiftR` 8)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2) instance Binary Word32 where put_ h w = do putByte h (fromIntegral (w `shiftR` 24)) putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h w3 <- getWord8 h w4 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 24) .|. (fromIntegral w2 `shiftL` 16) .|. (fromIntegral w3 `shiftL` 8) .|. (fromIntegral w4)) instance Binary Word64 where put_ h w = do putByte h (fromIntegral (w `shiftR` 56)) putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h w3 <- getWord8 h w4 <- getWord8 h w5 <- getWord8 h w6 <- getWord8 h w7 <- getWord8 h w8 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 56) .|. (fromIntegral w2 `shiftL` 48) .|. (fromIntegral w3 `shiftL` 40) .|. (fromIntegral w4 `shiftL` 32) .|. (fromIntegral w5 `shiftL` 24) .|. (fromIntegral w6 `shiftL` 16) .|. (fromIntegral w7 `shiftL` 8) .|. (fromIntegral w8)) -- ----------------------------------------------------------------------------- -- Primitve Int writes instance Binary Int8 where put_ h w = put_ h (fromIntegral w :: Word8) get h = do w <- get h; return $! (fromIntegral (w::Word8)) instance Binary Int16 where put_ h w = put_ h (fromIntegral w :: Word16) get h = do w <- get h; return $! (fromIntegral (w::Word16)) instance Binary Int32 where put_ h w = put_ h (fromIntegral w :: Word32) get h = do w <- get h; return $! (fromIntegral (w::Word32)) instance Binary Int64 where put_ h w = put_ h (fromIntegral w :: Word64) get h = do w <- get h; return $! (fromIntegral (w::Word64)) -- ----------------------------------------------------------------------------- -- Instances for standard types instance Binary () where put_ _ () = return () get _ = return () instance Binary Bool where put_ bh b = putByte bh (fromIntegral (fromEnum b)) get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x)) instance Binary Char where put_ bh c = put_ bh (fromIntegral (ord c) :: Word32) get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word32))) instance Binary Int where put_ bh i = put_ bh (fromIntegral i :: Int64) get bh = do x <- get bh return $! (fromIntegral (x :: Int64)) instance Binary a => Binary [a] where put_ bh l = do let len = length l if (len < 0xff) then putByte bh (fromIntegral len :: Word8) else do putByte bh 0xff; put_ bh (fromIntegral len :: Word32) mapM_ (put_ bh) l get bh = do b <- getByte bh len <- if b == 0xff then get bh else return (fromIntegral b :: Word32) let loop 0 = return [] loop n = do a <- get bh; as <- loop (n-1); return (a:as) loop len instance (Binary a, Binary b) => Binary (a,b) where put_ bh (a,b) = do put_ bh a; put_ bh b get bh = do a <- get bh b <- get bh return (a,b) instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c get bh = do a <- get bh b <- get bh c <- get bh return (a,b,c) instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d get bh = do a <- get bh b <- get bh c <- get bh d <- get bh return (a,b,c,d) instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a,b,c,d, e) where put_ bh (a,b,c,d, e) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh return (a,b,c,d,e) instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f) => Binary (a,b,c,d, e, f) where put_ bh (a,b,c,d, e, f) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; put_ bh f; get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh f <- get bh return (a,b,c,d,e,f) instance Binary a => Binary (Maybe a) where put_ bh Nothing = putByte bh 0 put_ bh (Just a) = do putByte bh 1; put_ bh a get bh = do h <- getWord8 bh case h of 0 -> return Nothing _ -> do x <- get bh; return (Just x) instance (Binary a, Binary b) => Binary (Either a b) where put_ bh (Left a) = do putByte bh 0; put_ bh a put_ bh (Right b) = do putByte bh 1; put_ bh b get bh = do h <- getWord8 bh case h of 0 -> do a <- get bh ; return (Left a) _ -> do b <- get bh ; return (Right b) instance Binary UTCTime where put_ bh u = do put_ bh (utctDay u) put_ bh (utctDayTime u) get bh = do day <- get bh dayTime <- get bh return $ UTCTime { utctDay = day, utctDayTime = dayTime } instance Binary Day where put_ bh d = put_ bh (toModifiedJulianDay d) get bh = do i <- get bh return $ ModifiedJulianDay { toModifiedJulianDay = i } instance Binary DiffTime where put_ bh dt = put_ bh (toRational dt) get bh = do r <- get bh return $ fromRational r #if defined(__GLASGOW_HASKELL__) || 1 --to quote binary-0.3 on this code idea, -- -- TODO This instance is not architecture portable. GMP stores numbers as -- arrays of machine sized words, so the byte format is not portable across -- architectures with different endianess and word size. -- -- This makes it hard (impossible) to make an equivalent instance -- with code that is compilable with non-GHC. Do we need any instance -- Binary Integer, and if so, does it have to be blazing fast? Or can -- we just change this instance to be portable like the rest of the -- instances? (binary package has code to steal for that) -- -- yes, we need Binary Integer and Binary Rational in basicTypes/Literal.lhs instance Binary Integer where -- XXX This is hideous put_ bh i = put_ bh (show i) get bh = do str <- get bh case reads str of [(i, "")] -> return i _ -> fail ("Binary Integer: got " ++ show str) {- put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#) put_ bh (J# s# a#) = do putByte bh 1 put_ bh (I# s#) let sz# = sizeofByteArray# a# -- in *bytes* put_ bh (I# sz#) -- in *bytes* putByteArray bh a# sz# get bh = do b <- getByte bh case b of 0 -> do (I# i#) <- get bh return (S# i#) _ -> do (I# s#) <- get bh sz <- get bh (BA a#) <- getByteArray bh sz return (J# s# a#) -} -- As for the rest of this code, even though this module -- exports it, it doesn't seem to be used anywhere else -- in GHC! putByteArray :: BinHandle -> ByteArray# -> Int# -> IO () putByteArray bh a s# = loop 0# where loop n# | n# ==# s# = return () | otherwise = do putByte bh (indexByteArray a n#) loop (n# +# 1#) getByteArray :: BinHandle -> Int -> IO ByteArray getByteArray bh (I# sz) = do (MBA arr) <- newByteArray sz let loop n | n ==# sz = return () | otherwise = do w <- getByte bh writeByteArray arr n w loop (n +# 1#) loop 0# freezeByteArray arr data ByteArray = BA ByteArray# data MBA = MBA (MutableByteArray# RealWorld) newByteArray :: Int# -> IO MBA newByteArray sz = IO $ \s -> case newByteArray# sz s of { (# s, arr #) -> (# s, MBA arr #) } freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray freezeByteArray arr = IO $ \s -> case unsafeFreezeByteArray# arr s of { (# s, arr #) -> (# s, BA arr #) } writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO () writeByteArray arr i (W8# w) = IO $ \s -> case writeWord8Array# arr i w s of { s -> (# s, () #) } indexByteArray :: ByteArray# -> Int# -> Word8 indexByteArray a# n# = W8# (indexWord8Array# a# n#) instance (Integral a, Binary a) => Binary (Ratio a) where put_ bh (a :% b) = do put_ bh a; put_ bh b get bh = do a <- get bh; b <- get bh; return (a :% b) #endif instance Binary (Bin a) where put_ bh (BinPtr i) = put_ bh (fromIntegral i :: Int32) get bh = do i <- get bh; return (BinPtr (fromIntegral (i :: Int32))) -- ----------------------------------------------------------------------------- -- Instances for Data.Typeable stuff instance Binary TyCon where put_ bh (TyCon _ p m n) = do put_ bh (p,m,n) get bh = do (p,m,n) <- get bh return (mkTyCon3 p m n) instance Binary TypeRep where put_ bh type_rep = do let (ty_con, child_type_reps) = splitTyConApp type_rep put_ bh ty_con put_ bh child_type_reps get bh = do ty_con <- get bh child_type_reps <- get bh return (mkTyConApp ty_con child_type_reps) -- ----------------------------------------------------------------------------- -- Lazy reading/writing lazyPut :: Binary a => BinHandle -> a -> IO () lazyPut bh a = do -- output the obj with a ptr to skip over it: pre_a <- tellBin bh put_ bh pre_a -- save a slot for the ptr put_ bh a -- dump the object q <- tellBin bh -- q = ptr to after object putAt bh pre_a q -- fill in slot before a with ptr to q seekBin bh q -- finally carry on writing at q lazyGet :: Binary a => BinHandle -> IO a lazyGet bh = do p <- get bh -- a BinPtr p_a <- tellBin bh a <- unsafeInterleaveIO $ do -- NB: Use a fresh off_r variable in the child thread, for thread -- safety. off_r <- newFastMutInt getAt bh { _off_r = off_r } p_a seekBin bh p -- skip over the object for now return a -- ----------------------------------------------------------------------------- -- UserData -- ----------------------------------------------------------------------------- data UserData = UserData { -- for *deserialising* only: ud_get_name :: BinHandle -> IO Name, ud_get_fs :: BinHandle -> IO FastString, -- for *serialising* only: ud_put_name :: BinHandle -> Name -> IO (), ud_put_fs :: BinHandle -> FastString -> IO () } newReadState :: (BinHandle -> IO Name) -> (BinHandle -> IO FastString) -> UserData newReadState get_name get_fs = UserData { ud_get_name = get_name, ud_get_fs = get_fs, ud_put_name = undef "put_name", ud_put_fs = undef "put_fs" } newWriteState :: (BinHandle -> Name -> IO ()) -> (BinHandle -> FastString -> IO ()) -> UserData newWriteState put_name put_fs = UserData { ud_get_name = undef "get_name", ud_get_fs = undef "get_fs", ud_put_name = put_name, ud_put_fs = put_fs } noUserData :: a noUserData = undef "UserData" undef :: String -> a undef s = panic ("Binary.UserData: no " ++ s) --------------------------------------------------------- -- The Dictionary --------------------------------------------------------- type Dictionary = Array Int FastString -- The dictionary -- Should be 0-indexed putDictionary :: BinHandle -> Int -> UniqFM (Int,FastString) -> IO () putDictionary bh sz dict = do put_ bh sz mapM_ (putFS bh) (elems (array (0,sz-1) (eltsUFM dict))) getDictionary :: BinHandle -> IO Dictionary getDictionary bh = do sz <- get bh elems <- sequence (take sz (repeat (getFS bh))) return (listArray (0,sz-1) elems) --------------------------------------------------------- -- The Symbol Table --------------------------------------------------------- -- On disk, the symbol table is an array of IfaceExtName, when -- reading it in we turn it into a SymbolTable. type SymbolTable = Array Int Name --------------------------------------------------------- -- Reading and writing FastStrings --------------------------------------------------------- putFS :: BinHandle -> FastString -> IO () putFS bh fs = putBS bh $ fastStringToByteString fs getFS :: BinHandle -> IO FastString getFS bh = do bs <- getBS bh mkFastStringByteString bs putBS :: BinHandle -> ByteString -> IO () putBS bh bs = BS.unsafeUseAsCStringLen bs $ \(ptr, l) -> do put_ bh l let go n | n == l = return () | otherwise = do b <- peekElemOff (castPtr ptr) n putByte bh b go (n+1) go 0 {- -- possible faster version, not quite there yet: getBS bh@BinMem{} = do (I# l) <- get bh arr <- readIORef (arr_r bh) off <- readFastMutInt (off_r bh) return $! (mkFastSubBytesBA# arr off l) -} getBS :: BinHandle -> IO ByteString getBS bh = do l <- get bh fp <- mallocForeignPtrBytes l withForeignPtr fp $ \ptr -> do let go n | n == l = return $ BS.fromForeignPtr fp 0 l | otherwise = do b <- getByte bh pokeElemOff ptr n b go (n+1) -- go 0 instance Binary ByteString where put_ bh f = putBS bh f get bh = getBS bh instance Binary FastString where put_ bh f = case getUserData bh of UserData { ud_put_fs = put_fs } -> put_fs bh f get bh = case getUserData bh of UserData { ud_get_fs = get_fs } -> get_fs bh -- Here to avoid loop instance Binary Fingerprint where put_ h (Fingerprint w1 w2) = do put_ h w1; put_ h w2 get h = do w1 <- get h; w2 <- get h; return (Fingerprint w1 w2) instance Binary FunctionOrData where put_ bh IsFunction = putByte bh 0 put_ bh IsData = putByte bh 1 get bh = do h <- getByte bh case h of 0 -> return IsFunction 1 -> return IsData _ -> panic "Binary FunctionOrData" instance Binary TupleSort where put_ bh BoxedTuple = putByte bh 0 put_ bh UnboxedTuple = putByte bh 1 put_ bh ConstraintTuple = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return BoxedTuple 1 -> do return UnboxedTuple _ -> do return ConstraintTuple instance Binary Activation where put_ bh NeverActive = do putByte bh 0 put_ bh AlwaysActive = do putByte bh 1 put_ bh (ActiveBefore aa) = do putByte bh 2 put_ bh aa put_ bh (ActiveAfter ab) = do putByte bh 3 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do return NeverActive 1 -> do return AlwaysActive 2 -> do aa <- get bh return (ActiveBefore aa) _ -> do ab <- get bh return (ActiveAfter ab) instance Binary InlinePragma where put_ bh (InlinePragma a b c d) = do put_ bh a put_ bh b put_ bh c put_ bh d get bh = do a <- get bh b <- get bh c <- get bh d <- get bh return (InlinePragma a b c d) instance Binary RuleMatchInfo where put_ bh FunLike = putByte bh 0 put_ bh ConLike = putByte bh 1 get bh = do h <- getByte bh if h == 1 then return ConLike else return FunLike instance Binary InlineSpec where put_ bh EmptyInlineSpec = putByte bh 0 put_ bh Inline = putByte bh 1 put_ bh Inlinable = putByte bh 2 put_ bh NoInline = putByte bh 3 get bh = do h <- getByte bh case h of 0 -> return EmptyInlineSpec 1 -> return Inline 2 -> return Inlinable _ -> return NoInline instance Binary DefMethSpec where put_ bh NoDM = putByte bh 0 put_ bh VanillaDM = putByte bh 1 put_ bh GenericDM = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> return NoDM 1 -> return VanillaDM _ -> return GenericDM instance Binary RecFlag where put_ bh Recursive = do putByte bh 0 put_ bh NonRecursive = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do return Recursive _ -> do return NonRecursive instance Binary OverlapFlag where put_ bh (NoOverlap b) = putByte bh 0 >> put_ bh b put_ bh (OverlapOk b) = putByte bh 1 >> put_ bh b put_ bh (Incoherent b) = putByte bh 2 >> put_ bh b get bh = do h <- getByte bh b <- get bh case h of 0 -> return $ NoOverlap b 1 -> return $ OverlapOk b 2 -> return $ Incoherent b _ -> panic ("get OverlapFlag " ++ show h) instance Binary FixityDirection where put_ bh InfixL = do putByte bh 0 put_ bh InfixR = do putByte bh 1 put_ bh InfixN = do putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return InfixL 1 -> do return InfixR _ -> do return InfixN instance Binary Fixity where put_ bh (Fixity aa ab) = do put_ bh aa put_ bh ab get bh = do aa <- get bh ab <- get bh return (Fixity aa ab) instance Binary WarningTxt where put_ bh (WarningTxt w) = do putByte bh 0 put_ bh w put_ bh (DeprecatedTxt d) = do putByte bh 1 put_ bh d get bh = do h <- getByte bh case h of 0 -> do w <- get bh return (WarningTxt w) _ -> do d <- get bh return (DeprecatedTxt d)
{ "content_hash": "3a06490c94e7a0cbc63b41b8b57e02da", "timestamp": "", "source": "github", "line_count": 888, "max_line_length": 101, "avg_line_length": 30.92454954954955, "alnum_prop": 0.5307891191143804, "repo_name": "hferreiro/replay", "id": "332bfc8e0cc6de21210600467f7c4dabac727097", "size": "27461", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "compiler/utils/Binary.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "5276" }, { "name": "C", "bytes": "2355689" }, { "name": "C++", "bytes": "80959" }, { "name": "CSS", "bytes": "947" }, { "name": "DTrace", "bytes": "3887" }, { "name": "Emacs Lisp", "bytes": "570" }, { "name": "Gnuplot", "bytes": "103851" }, { "name": "Groff", "bytes": "3840" }, { "name": "HTML", "bytes": "6144" }, { "name": "Haskell", "bytes": "14088459" }, { "name": "Haxe", "bytes": "218" }, { "name": "Logos", "bytes": "109853" }, { "name": "M4", "bytes": "36043" }, { "name": "Makefile", "bytes": "438147" }, { "name": "Objective-C", "bytes": "21535" }, { "name": "Objective-C++", "bytes": "535" }, { "name": "Pascal", "bytes": "98406" }, { "name": "Perl", "bytes": "51154" }, { "name": "Perl6", "bytes": "27854" }, { "name": "PostScript", "bytes": "63" }, { "name": "Python", "bytes": "102283" }, { "name": "Shell", "bytes": "30762" }, { "name": "TeX", "bytes": "667" }, { "name": "Terra", "bytes": "290317" }, { "name": "Yacc", "bytes": "74671" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <workflow-app xmlns="uri:oozie:workflow:0.4" name="test-wf"> <start to="a"/> <action name="a"> <hive xmlns="uri:oozie:hive-action:0.2"> <prepare> <delete path="/tmp"/> <mkdir path="/tmp"/> </prepare> <name-node>bar</name-node> <configuration> <property> <name>c</name> <value>C</value> </property> </configuration> <script>script.q</script> <param>INPUT=/tmp/table</param> <param>OUTPUT=/tmp/hive</param> </hive> <ok to="b2"/> <error to="b1"/> </action> <action name="b1"> <email xmlns="uri:oozie:email-action:0.2"> <to>foo@bar.com</to> <subject>foo</subject> <body>bar</body> </email> <ok to="b2"/> <error to="b2"/> </action> <kill name="b2"> <message>fail</message> </kill> <end name="c"/> </workflow-app>
{ "content_hash": "d718a89ac721be848d17d5f2573e52fb", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 74, "avg_line_length": 32.35087719298246, "alnum_prop": 0.5802603036876356, "repo_name": "cbaenziger/oozie", "id": "2eea7342fe2e82ee699cfd124a08ba9087bd7390", "size": "1844", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/test/resources/wf-schema-no-jobtracker.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "16115" }, { "name": "CSS", "bytes": "27272" }, { "name": "HTML", "bytes": "8786" }, { "name": "Java", "bytes": "10168055" }, { "name": "JavaScript", "bytes": "143427" }, { "name": "PowerShell", "bytes": "9356" }, { "name": "Python", "bytes": "1349" }, { "name": "Shell", "bytes": "114386" } ], "symlink_target": "" }
module CanTango class Ability def can?(action, subject, *extra_args) stamper("#can?") { match = relevant_rules_for_match(action, subject).detect do |rule| rule.matches_conditions?(action, subject, extra_args) end match ? match.base_behavior : false } end end end
{ "content_hash": "a472368fd13cce8b5b290f9901290c1d", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 72, "avg_line_length": 26.083333333333332, "alnum_prop": 0.6293929712460063, "repo_name": "kristianmandrup/cantango", "id": "23f1866427ad119c1233d9e70c46757e46bce89e", "size": "313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/integration/performance/helpers/rules.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "12852" }, { "name": "Ruby", "bytes": "413453" } ], "symlink_target": "" }
/* TODO: * - implement WINMM (32bit) multitasking and use it in all MCI drivers * instead of the home grown one * - 16bit mmTaskXXX functions are currently broken because the 16 * loader does not support binary command lines => provide Wine's * own mmtask.tsk not using binary command line. * - correctly handle the MCI_ALL_DEVICE_ID in functions. * - finish mapping 16 <=> 32 of MCI structures and commands * - implement auto-open feature (ie, when a string command is issued * for a not yet opened device, MCI automatically opens it) * - use a default registry setting to replace the [mci] section in * configuration file (layout of info in registry should be compatible * with all Windows' version - which use different layouts of course) * - implement automatic open * + only works on string interface, on regular devices (don't work on all * nor custom devices) * - command table handling isn't thread safe */ #include "config.h" #include "wine/port.h" #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include "windef.h" #include "winbase.h" #include "wingdi.h" #include "mmsystem.h" #include "winuser.h" #include "winnls.h" #include "winreg.h" #include "wownt32.h" #include "digitalv.h" #include "winemm.h" #include "wine/debug.h" #include "wine/unicode.h" WINE_DEFAULT_DEBUG_CHANNEL(mci); /* First MCI valid device ID (0 means error) */ #define MCI_MAGIC 0x0001 /* MCI settings */ static const WCHAR wszHklmMci [] = {'S','o','f','t','w','a','r','e','\\','M','i','c','r','o','s','o','f','t','\\','W','i','n','d','o','w','s',' ','N','T','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\','M','C','I',0}; static const WCHAR wszNull [] = {0}; static const WCHAR wszAll [] = {'A','L','L',0}; static const WCHAR wszMci [] = {'M','C','I',0}; static const WCHAR wszOpen [] = {'o','p','e','n',0}; static const WCHAR wszSystemIni[] = {'s','y','s','t','e','m','.','i','n','i',0}; static WINE_MCIDRIVER *MciDrivers; static UINT WINAPI MCI_DefYieldProc(MCIDEVICEID wDevID, DWORD data); static UINT MCI_SetCommandTable(HGLOBAL hMem, UINT uDevType); /* dup a string and uppercase it */ static inline LPWSTR str_dup_upper( LPCWSTR str ) { INT len = (strlenW(str) + 1) * sizeof(WCHAR); LPWSTR p = HeapAlloc( GetProcessHeap(), 0, len ); if (p) { memcpy( p, str, len ); CharUpperW( p ); } return p; } /************************************************************************** * MCI_GetDriver [internal] */ static LPWINE_MCIDRIVER MCI_GetDriver(UINT wDevID) { LPWINE_MCIDRIVER wmd = 0; EnterCriticalSection(&WINMM_cs); for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) { if (wmd->wDeviceID == wDevID) break; } LeaveCriticalSection(&WINMM_cs); return wmd; } /************************************************************************** * MCI_GetDriverFromString [internal] */ static UINT MCI_GetDriverFromString(LPCWSTR lpstrName) { LPWINE_MCIDRIVER wmd; UINT ret = 0; if (!lpstrName) return 0; if (!strcmpiW(lpstrName, wszAll)) return MCI_ALL_DEVICE_ID; EnterCriticalSection(&WINMM_cs); for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) { if (wmd->lpstrAlias && strcmpiW(wmd->lpstrAlias, lpstrName) == 0) { ret = wmd->wDeviceID; break; } } LeaveCriticalSection(&WINMM_cs); return ret; } /************************************************************************** * MCI_MessageToString [internal] */ static const char* MCI_MessageToString(UINT wMsg) { #define CASE(s) case (s): return #s switch (wMsg) { CASE(DRV_LOAD); CASE(DRV_ENABLE); CASE(DRV_OPEN); CASE(DRV_CLOSE); CASE(DRV_DISABLE); CASE(DRV_FREE); CASE(DRV_CONFIGURE); CASE(DRV_QUERYCONFIGURE); CASE(DRV_INSTALL); CASE(DRV_REMOVE); CASE(DRV_EXITSESSION); CASE(DRV_EXITAPPLICATION); CASE(DRV_POWER); CASE(MCI_BREAK); CASE(MCI_CLOSE); CASE(MCI_CLOSE_DRIVER); CASE(MCI_COPY); CASE(MCI_CUE); CASE(MCI_CUT); CASE(MCI_DELETE); CASE(MCI_ESCAPE); CASE(MCI_FREEZE); CASE(MCI_PAUSE); CASE(MCI_PLAY); CASE(MCI_GETDEVCAPS); CASE(MCI_INFO); CASE(MCI_LOAD); CASE(MCI_OPEN); CASE(MCI_OPEN_DRIVER); CASE(MCI_PASTE); CASE(MCI_PUT); CASE(MCI_REALIZE); CASE(MCI_RECORD); CASE(MCI_RESUME); CASE(MCI_SAVE); CASE(MCI_SEEK); CASE(MCI_SET); CASE(MCI_SOUND); CASE(MCI_SPIN); CASE(MCI_STATUS); CASE(MCI_STEP); CASE(MCI_STOP); CASE(MCI_SYSINFO); CASE(MCI_UNFREEZE); CASE(MCI_UPDATE); CASE(MCI_WHERE); CASE(MCI_WINDOW); /* constants for digital video */ CASE(MCI_CAPTURE); CASE(MCI_MONITOR); CASE(MCI_RESERVE); CASE(MCI_SETAUDIO); CASE(MCI_SIGNAL); CASE(MCI_SETVIDEO); CASE(MCI_QUALITY); CASE(MCI_LIST); CASE(MCI_UNDO); CASE(MCI_CONFIGURE); CASE(MCI_RESTORE); #undef CASE default: return wine_dbg_sprintf("MCI_<<%04X>>", wMsg); } } static LPWSTR MCI_strdupAtoW( LPCSTR str ) { LPWSTR ret; INT len; if (!str) return NULL; len = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 ); ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ); if (ret) MultiByteToWideChar( CP_ACP, 0, str, -1, ret, len ); return ret; } static int MCI_MapMsgAtoW(UINT msg, DWORD_PTR dwParam1, DWORD_PTR *dwParam2) { if (msg < DRV_RESERVED) return 0; switch (msg) { case MCI_CLOSE: case MCI_CONFIGURE: case MCI_PLAY: case MCI_SEEK: case MCI_STOP: case MCI_PAUSE: case MCI_GETDEVCAPS: case MCI_SPIN: case MCI_SET: case MCI_STEP: case MCI_RECORD: case MCI_BREAK: case MCI_STATUS: case MCI_CUE: case MCI_REALIZE: case MCI_PUT: case MCI_WHERE: case MCI_FREEZE: case MCI_UNFREEZE: case MCI_CUT: case MCI_COPY: case MCI_PASTE: case MCI_UPDATE: case MCI_RESUME: case MCI_DELETE: case MCI_MONITOR: case MCI_SIGNAL: case MCI_UNDO: return 0; case MCI_OPEN: { /* MCI_ANIM_OPEN_PARMS is the largest known MCI_OPEN_PARMS * structure, larger than MCI_WAVE_OPEN_PARMS */ MCI_ANIM_OPEN_PARMSA *mci_openA = (MCI_ANIM_OPEN_PARMSA*)*dwParam2; MCI_ANIM_OPEN_PARMSW *mci_openW; DWORD_PTR *ptr; ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(DWORD_PTR) + sizeof(*mci_openW)); if (!ptr) return -1; *ptr++ = *dwParam2; /* save the previous pointer */ *dwParam2 = (DWORD_PTR)ptr; mci_openW = (MCI_ANIM_OPEN_PARMSW *)ptr; if (dwParam1 & MCI_NOTIFY) mci_openW->dwCallback = mci_openA->dwCallback; if (dwParam1 & MCI_OPEN_TYPE) { if (dwParam1 & MCI_OPEN_TYPE_ID) mci_openW->lpstrDeviceType = (LPCWSTR)mci_openA->lpstrDeviceType; else mci_openW->lpstrDeviceType = MCI_strdupAtoW(mci_openA->lpstrDeviceType); } if (dwParam1 & MCI_OPEN_ELEMENT) { if (dwParam1 & MCI_OPEN_ELEMENT_ID) mci_openW->lpstrElementName = (LPCWSTR)mci_openA->lpstrElementName; else mci_openW->lpstrElementName = MCI_strdupAtoW(mci_openA->lpstrElementName); } if (dwParam1 & MCI_OPEN_ALIAS) mci_openW->lpstrAlias = MCI_strdupAtoW(mci_openA->lpstrAlias); /* We don't know how many DWORD follow, as * the structure depends on the device. */ if (HIWORD(dwParam1)) memcpy(&mci_openW->dwStyle, &mci_openA->dwStyle, sizeof(MCI_ANIM_OPEN_PARMSW) - sizeof(MCI_OPEN_PARMSW)); } return 1; case MCI_WINDOW: if (dwParam1 & MCI_ANIM_WINDOW_TEXT) { MCI_ANIM_WINDOW_PARMSA *mci_windowA = (MCI_ANIM_WINDOW_PARMSA *)*dwParam2; MCI_ANIM_WINDOW_PARMSW *mci_windowW; mci_windowW = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_windowW)); if (!mci_windowW) return -1; *dwParam2 = (DWORD_PTR)mci_windowW; mci_windowW->lpstrText = MCI_strdupAtoW(mci_windowA->lpstrText); if (dwParam1 & MCI_NOTIFY) mci_windowW->dwCallback = mci_windowA->dwCallback; if (dwParam1 & MCI_ANIM_WINDOW_HWND) mci_windowW->hWnd = mci_windowA->hWnd; if (dwParam1 & MCI_ANIM_WINDOW_STATE) mci_windowW->nCmdShow = mci_windowA->nCmdShow; return 1; } return 0; case MCI_SYSINFO: if (dwParam1 & (MCI_SYSINFO_INSTALLNAME | MCI_SYSINFO_NAME)) { MCI_SYSINFO_PARMSA *mci_sysinfoA = (MCI_SYSINFO_PARMSA *)*dwParam2; MCI_SYSINFO_PARMSW *mci_sysinfoW; DWORD_PTR *ptr; ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_sysinfoW) + sizeof(DWORD_PTR)); if (!ptr) return -1; *ptr++ = *dwParam2; /* save the previous pointer */ *dwParam2 = (DWORD_PTR)ptr; mci_sysinfoW = (MCI_SYSINFO_PARMSW *)ptr; if (dwParam1 & MCI_NOTIFY) mci_sysinfoW->dwCallback = mci_sysinfoA->dwCallback; /* Size is measured in numbers of characters, despite what MSDN says. */ mci_sysinfoW->dwRetSize = mci_sysinfoA->dwRetSize; mci_sysinfoW->lpstrReturn = HeapAlloc(GetProcessHeap(), 0, mci_sysinfoW->dwRetSize * sizeof(WCHAR)); mci_sysinfoW->dwNumber = mci_sysinfoA->dwNumber; mci_sysinfoW->wDeviceType = mci_sysinfoA->wDeviceType; return 1; } return 0; case MCI_INFO: { MCI_DGV_INFO_PARMSA *mci_infoA = (MCI_DGV_INFO_PARMSA *)*dwParam2; MCI_DGV_INFO_PARMSW *mci_infoW; DWORD_PTR *ptr; ptr = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_infoW) + sizeof(DWORD_PTR)); if (!ptr) return -1; *ptr++ = *dwParam2; /* save the previous pointer */ *dwParam2 = (DWORD_PTR)ptr; mci_infoW = (MCI_DGV_INFO_PARMSW *)ptr; if (dwParam1 & MCI_NOTIFY) mci_infoW->dwCallback = mci_infoA->dwCallback; /* Size is measured in numbers of characters. */ mci_infoW->dwRetSize = mci_infoA->dwRetSize; mci_infoW->lpstrReturn = HeapAlloc(GetProcessHeap(), 0, mci_infoW->dwRetSize * sizeof(WCHAR)); if (dwParam1 & MCI_DGV_INFO_ITEM) mci_infoW->dwItem = mci_infoA->dwItem; return 1; } case MCI_SAVE: case MCI_LOAD: case MCI_CAPTURE: case MCI_RESTORE: { /* All these commands have the same layout: callback + string + optional rect */ MCI_OVLY_LOAD_PARMSA *mci_loadA = (MCI_OVLY_LOAD_PARMSA *)*dwParam2; MCI_OVLY_LOAD_PARMSW *mci_loadW; mci_loadW = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_loadW)); if (!mci_loadW) return -1; *dwParam2 = (DWORD_PTR)mci_loadW; if (dwParam1 & MCI_NOTIFY) mci_loadW->dwCallback = mci_loadA->dwCallback; mci_loadW->lpfilename = MCI_strdupAtoW(mci_loadA->lpfilename); if ((MCI_SAVE == msg && dwParam1 & MCI_DGV_RECT) || (MCI_LOAD == msg && dwParam1 & MCI_OVLY_RECT) || (MCI_CAPTURE == msg && dwParam1 & MCI_DGV_CAPTURE_AT) || (MCI_RESTORE == msg && dwParam1 & MCI_DGV_RESTORE_AT)) mci_loadW->rc = mci_loadA->rc; return 1; } case MCI_SOUND: case MCI_ESCAPE: { /* All these commands have the same layout: callback + string */ MCI_VD_ESCAPE_PARMSA *mci_vd_escapeA = (MCI_VD_ESCAPE_PARMSA *)*dwParam2; MCI_VD_ESCAPE_PARMSW *mci_vd_escapeW; mci_vd_escapeW = HeapAlloc(GetProcessHeap(), 0, sizeof(*mci_vd_escapeW)); if (!mci_vd_escapeW) return -1; *dwParam2 = (DWORD_PTR)mci_vd_escapeW; if (dwParam1 & MCI_NOTIFY) mci_vd_escapeW->dwCallback = mci_vd_escapeA->dwCallback; mci_vd_escapeW->lpstrCommand = MCI_strdupAtoW(mci_vd_escapeA->lpstrCommand); return 1; } case MCI_SETAUDIO: case MCI_SETVIDEO: if (!(dwParam1 & (MCI_DGV_SETVIDEO_QUALITY | MCI_DGV_SETVIDEO_ALG | MCI_DGV_SETAUDIO_QUALITY | MCI_DGV_SETAUDIO_ALG))) return 0; /* fall through to default */ case MCI_RESERVE: case MCI_QUALITY: case MCI_LIST: default: FIXME("Message %s needs translation\n", MCI_MessageToString(msg)); return 0; /* pass through untouched */ } } static void MCI_UnmapMsgAtoW(UINT msg, DWORD_PTR dwParam1, DWORD_PTR dwParam2, DWORD result) { switch (msg) { case MCI_OPEN: { DWORD_PTR *ptr = (DWORD_PTR *)dwParam2 - 1; MCI_OPEN_PARMSA *mci_openA = (MCI_OPEN_PARMSA *)*ptr; MCI_OPEN_PARMSW *mci_openW = (MCI_OPEN_PARMSW *)dwParam2; mci_openA->wDeviceID = mci_openW->wDeviceID; if (dwParam1 & MCI_OPEN_TYPE) { if (!(dwParam1 & MCI_OPEN_TYPE_ID)) HeapFree(GetProcessHeap(), 0, (LPWSTR)mci_openW->lpstrDeviceType); } if (dwParam1 & MCI_OPEN_ELEMENT) { if (!(dwParam1 & MCI_OPEN_ELEMENT_ID)) HeapFree(GetProcessHeap(), 0, (LPWSTR)mci_openW->lpstrElementName); } if (dwParam1 & MCI_OPEN_ALIAS) HeapFree(GetProcessHeap(), 0, (LPWSTR)mci_openW->lpstrAlias); HeapFree(GetProcessHeap(), 0, ptr); } break; case MCI_WINDOW: if (dwParam1 & MCI_ANIM_WINDOW_TEXT) { MCI_ANIM_WINDOW_PARMSW *mci_windowW = (MCI_ANIM_WINDOW_PARMSW *)dwParam2; HeapFree(GetProcessHeap(), 0, (void*)mci_windowW->lpstrText); HeapFree(GetProcessHeap(), 0, mci_windowW); } break; case MCI_SYSINFO: if (dwParam1 & (MCI_SYSINFO_INSTALLNAME | MCI_SYSINFO_NAME)) { DWORD_PTR *ptr = (DWORD_PTR *)dwParam2 - 1; MCI_SYSINFO_PARMSA *mci_sysinfoA = (MCI_SYSINFO_PARMSA *)*ptr; MCI_SYSINFO_PARMSW *mci_sysinfoW = (MCI_SYSINFO_PARMSW *)dwParam2; if (!result) { WideCharToMultiByte(CP_ACP, 0, mci_sysinfoW->lpstrReturn, -1, mci_sysinfoA->lpstrReturn, mci_sysinfoA->dwRetSize, NULL, NULL); } HeapFree(GetProcessHeap(), 0, mci_sysinfoW->lpstrReturn); HeapFree(GetProcessHeap(), 0, ptr); } break; case MCI_INFO: { DWORD_PTR *ptr = (DWORD_PTR *)dwParam2 - 1; MCI_INFO_PARMSA *mci_infoA = (MCI_INFO_PARMSA *)*ptr; MCI_INFO_PARMSW *mci_infoW = (MCI_INFO_PARMSW *)dwParam2; if (!result) { WideCharToMultiByte(CP_ACP, 0, mci_infoW->lpstrReturn, -1, mci_infoA->lpstrReturn, mci_infoA->dwRetSize, NULL, NULL); } HeapFree(GetProcessHeap(), 0, mci_infoW->lpstrReturn); HeapFree(GetProcessHeap(), 0, ptr); } break; case MCI_SAVE: case MCI_LOAD: case MCI_CAPTURE: case MCI_RESTORE: { /* All these commands have the same layout: callback + string + optional rect */ MCI_OVLY_LOAD_PARMSW *mci_loadW = (MCI_OVLY_LOAD_PARMSW *)dwParam2; HeapFree(GetProcessHeap(), 0, (void*)mci_loadW->lpfilename); HeapFree(GetProcessHeap(), 0, mci_loadW); } break; case MCI_SOUND: case MCI_ESCAPE: { /* All these commands have the same layout: callback + string */ MCI_VD_ESCAPE_PARMSW *mci_vd_escapeW = (MCI_VD_ESCAPE_PARMSW *)dwParam2; HeapFree(GetProcessHeap(), 0, (void*)mci_vd_escapeW->lpstrCommand); HeapFree(GetProcessHeap(), 0, mci_vd_escapeW); } break; default: FIXME("Message %s needs unmapping\n", MCI_MessageToString(msg)); break; } } /************************************************************************** * MCI_GetDevTypeFromFileName [internal] */ static DWORD MCI_GetDevTypeFromFileName(LPCWSTR fileName, LPWSTR buf, UINT len) { LPCWSTR tmp; HKEY hKey; static const WCHAR keyW[] = {'S','O','F','T','W','A','R','E','\\','M','i','c','r','o','s','o','f','t','\\', 'W','i','n','d','o','w','s',' ','N','T','\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\', 'M','C','I',' ','E','x','t','e','n','s','i','o','n','s',0}; if ((tmp = strrchrW(fileName, '.'))) { if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, keyW, 0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) { DWORD dwLen = len; LONG lRet = RegQueryValueExW( hKey, tmp + 1, 0, 0, (void*)buf, &dwLen ); RegCloseKey( hKey ); if (lRet == ERROR_SUCCESS) return 0; } TRACE("No ...\\MCI Extensions entry for %s found.\n", debugstr_w(tmp)); } return MCIERR_EXTENSION_NOT_FOUND; } /************************************************************************** * MCI_GetDevTypeFromResource [internal] */ static UINT MCI_GetDevTypeFromResource(LPCWSTR lpstrName) { WCHAR buf[32]; UINT uDevType; for (uDevType = MCI_DEVTYPE_FIRST; uDevType <= MCI_DEVTYPE_LAST; uDevType++) { if (LoadStringW(hWinMM32Instance, uDevType, buf, sizeof(buf) / sizeof(WCHAR))) { /* FIXME: ignore digits suffix */ if (!strcmpiW(buf, lpstrName)) return uDevType; } } return 0; } #define MAX_MCICMDTABLE 20 #define MCI_COMMAND_TABLE_NOT_LOADED 0xFFFE typedef struct tagWINE_MCICMDTABLE { UINT uDevType; HGLOBAL hMem; const BYTE* lpTable; UINT nVerbs; /* number of verbs in command table */ LPCWSTR* aVerbs; /* array of verbs to speed up the verb look up process */ } WINE_MCICMDTABLE, *LPWINE_MCICMDTABLE; static WINE_MCICMDTABLE S_MciCmdTable[MAX_MCICMDTABLE]; /************************************************************************** * MCI_IsCommandTableValid [internal] */ static BOOL MCI_IsCommandTableValid(UINT uTbl) { const BYTE* lmem; LPCWSTR str; DWORD flg; WORD eid; int idx = 0; BOOL inCst = FALSE; TRACE("Dumping cmdTbl=%d [lpTable=%p devType=%d]\n", uTbl, S_MciCmdTable[uTbl].lpTable, S_MciCmdTable[uTbl].uDevType); if (uTbl >= MAX_MCICMDTABLE || !S_MciCmdTable[uTbl].lpTable) return FALSE; lmem = S_MciCmdTable[uTbl].lpTable; do { str = (LPCWSTR)lmem; lmem += (strlenW(str) + 1) * sizeof(WCHAR); flg = *(const DWORD*)lmem; eid = *(const WORD*)(lmem + sizeof(DWORD)); lmem += sizeof(DWORD) + sizeof(WORD); idx ++; /* TRACE("cmd=%s %08lx %04x\n", debugstr_w(str), flg, eid); */ switch (eid) { case MCI_COMMAND_HEAD: if (!*str || !flg) return FALSE; idx = 0; break; /* check unicity of str in table */ case MCI_STRING: if (inCst) return FALSE; break; case MCI_HWND: /* Occurs inside MCI_CONSTANT as in "window handle default" */ case MCI_HPAL: case MCI_HDC: case MCI_INTEGER: if (!*str) return FALSE; break; case MCI_END_COMMAND: if (*str || flg || idx == 0) return FALSE; idx = 0; break; case MCI_RETURN: if (*str || idx != 1) return FALSE; break; case MCI_FLAG: if (!*str) return FALSE; break; case MCI_END_COMMAND_LIST: if (*str || flg) return FALSE; idx = 0; break; case MCI_RECT: if (!*str || inCst) return FALSE; break; case MCI_CONSTANT: if (inCst) return FALSE; inCst = TRUE; break; case MCI_END_CONSTANT: if (*str || flg || !inCst) return FALSE; inCst = FALSE; break; default: return FALSE; } } while (eid != MCI_END_COMMAND_LIST); return TRUE; } /************************************************************************** * MCI_DumpCommandTable [internal] */ static BOOL MCI_DumpCommandTable(UINT uTbl) { const BYTE* lmem; LPCWSTR str; WORD eid; if (!MCI_IsCommandTableValid(uTbl)) { ERR("Ooops: %d is not valid\n", uTbl); return FALSE; } lmem = S_MciCmdTable[uTbl].lpTable; do { do { /* DWORD flg; */ str = (LPCWSTR)lmem; lmem += (strlenW(str) + 1) * sizeof(WCHAR); /* flg = *(const DWORD*)lmem; */ eid = *(const WORD*)(lmem + sizeof(DWORD)); /* TRACE("cmd=%s %08lx %04x\n", debugstr_w(str), flg, eid); */ lmem += sizeof(DWORD) + sizeof(WORD); } while (eid != MCI_END_COMMAND && eid != MCI_END_COMMAND_LIST); /* EPP TRACE(" => end of command%s\n", (eid == MCI_END_COMMAND_LIST) ? " list" : ""); */ } while (eid != MCI_END_COMMAND_LIST); return TRUE; } /************************************************************************** * MCI_GetCommandTable [internal] */ static UINT MCI_GetCommandTable(UINT uDevType) { UINT uTbl; WCHAR buf[32]; LPCWSTR str = NULL; /* first look up existing for existing devType */ for (uTbl = 0; uTbl < MAX_MCICMDTABLE; uTbl++) { if (S_MciCmdTable[uTbl].lpTable && S_MciCmdTable[uTbl].uDevType == uDevType) return uTbl; } /* well try to load id */ if (uDevType >= MCI_DEVTYPE_FIRST && uDevType <= MCI_DEVTYPE_LAST) { if (LoadStringW(hWinMM32Instance, uDevType, buf, sizeof(buf) / sizeof(WCHAR))) { str = buf; } } else if (uDevType == 0) { static const WCHAR wszCore[] = {'C','O','R','E',0}; str = wszCore; } uTbl = MCI_NO_COMMAND_TABLE; if (str) { HRSRC hRsrc = FindResourceW(hWinMM32Instance, str, (LPCWSTR)RT_RCDATA); HANDLE hMem = 0; if (hRsrc) hMem = LoadResource(hWinMM32Instance, hRsrc); if (hMem) { uTbl = MCI_SetCommandTable(hMem, uDevType); } else { WARN("No command table found in resource %p[%s]\n", hWinMM32Instance, debugstr_w(str)); } } TRACE("=> %d\n", uTbl); return uTbl; } /************************************************************************** * MCI_SetCommandTable [internal] */ static UINT MCI_SetCommandTable(HGLOBAL hMem, UINT uDevType) { int uTbl; static BOOL bInitDone = FALSE; /* <HACK> * The CORE command table must be loaded first, so that MCI_GetCommandTable() * can be called with 0 as a uDevType to retrieve it. * </HACK> */ if (!bInitDone) { bInitDone = TRUE; MCI_GetCommandTable(0); } TRACE("(%p, %u)\n", hMem, uDevType); for (uTbl = 0; uTbl < MAX_MCICMDTABLE; uTbl++) { if (!S_MciCmdTable[uTbl].lpTable) { const BYTE* lmem; LPCWSTR str; WORD eid; WORD count; S_MciCmdTable[uTbl].uDevType = uDevType; S_MciCmdTable[uTbl].lpTable = LockResource(hMem); S_MciCmdTable[uTbl].hMem = hMem; if (TRACE_ON(mci)) { MCI_DumpCommandTable(uTbl); } /* create the verbs table */ /* get # of entries */ lmem = S_MciCmdTable[uTbl].lpTable; count = 0; do { str = (LPCWSTR)lmem; lmem += (strlenW(str) + 1) * sizeof(WCHAR); eid = *(const WORD*)(lmem + sizeof(DWORD)); lmem += sizeof(DWORD) + sizeof(WORD); if (eid == MCI_COMMAND_HEAD) count++; } while (eid != MCI_END_COMMAND_LIST); S_MciCmdTable[uTbl].aVerbs = HeapAlloc(GetProcessHeap(), 0, count * sizeof(LPCWSTR)); S_MciCmdTable[uTbl].nVerbs = count; lmem = S_MciCmdTable[uTbl].lpTable; count = 0; do { str = (LPCWSTR)lmem; lmem += (strlenW(str) + 1) * sizeof(WCHAR); eid = *(const WORD*)(lmem + sizeof(DWORD)); lmem += sizeof(DWORD) + sizeof(WORD); if (eid == MCI_COMMAND_HEAD) S_MciCmdTable[uTbl].aVerbs[count++] = str; } while (eid != MCI_END_COMMAND_LIST); /* assert(count == S_MciCmdTable[uTbl].nVerbs); */ return uTbl; } } return MCI_NO_COMMAND_TABLE; } /************************************************************************** * MCI_UnLoadMciDriver [internal] */ static BOOL MCI_UnLoadMciDriver(LPWINE_MCIDRIVER wmd) { LPWINE_MCIDRIVER* tmp; if (!wmd) return TRUE; CloseDriver(wmd->hDriver, 0, 0); if (wmd->dwPrivate != 0) WARN("Unloading mci driver with non nul dwPrivate field\n"); EnterCriticalSection(&WINMM_cs); for (tmp = &MciDrivers; *tmp; tmp = &(*tmp)->lpNext) { if (*tmp == wmd) { *tmp = wmd->lpNext; break; } } LeaveCriticalSection(&WINMM_cs); HeapFree(GetProcessHeap(), 0, wmd->lpstrDeviceType); HeapFree(GetProcessHeap(), 0, wmd->lpstrAlias); HeapFree(GetProcessHeap(), 0, wmd); return TRUE; } /************************************************************************** * MCI_OpenMciDriver [internal] */ static BOOL MCI_OpenMciDriver(LPWINE_MCIDRIVER wmd, LPCWSTR drvTyp, DWORD_PTR lp) { WCHAR libName[128]; if (!DRIVER_GetLibName(drvTyp, wszMci, libName, sizeof(libName))) return FALSE; /* First load driver */ wmd->hDriver = (HDRVR)DRIVER_TryOpenDriver32(libName, lp); return wmd->hDriver != NULL; } /************************************************************************** * MCI_LoadMciDriver [internal] */ static DWORD MCI_LoadMciDriver(LPCWSTR _strDevTyp, LPWINE_MCIDRIVER* lpwmd) { LPWSTR strDevTyp = str_dup_upper(_strDevTyp); LPWINE_MCIDRIVER wmd = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wmd)); MCI_OPEN_DRIVER_PARMSW modp; DWORD dwRet = 0; if (!wmd || !strDevTyp) { dwRet = MCIERR_OUT_OF_MEMORY; goto errCleanUp; } wmd->lpfnYieldProc = MCI_DefYieldProc; wmd->dwYieldData = VK_CANCEL; wmd->CreatorThread = GetCurrentThreadId(); EnterCriticalSection(&WINMM_cs); /* wmd must be inserted in list before sending opening the driver, because it * may want to lookup at wDevID */ wmd->lpNext = MciDrivers; MciDrivers = wmd; for (modp.wDeviceID = MCI_MAGIC; MCI_GetDriver(modp.wDeviceID) != 0; modp.wDeviceID++); wmd->wDeviceID = modp.wDeviceID; LeaveCriticalSection(&WINMM_cs); TRACE("wDevID=%04X\n", modp.wDeviceID); modp.lpstrParams = NULL; if (!MCI_OpenMciDriver(wmd, strDevTyp, (DWORD_PTR)&modp)) { /* silence warning if all is used... some bogus program use commands like * 'open all'... */ if (strcmpiW(strDevTyp, wszAll) == 0) { dwRet = MCIERR_CANNOT_USE_ALL; } else { FIXME("Couldn't load driver for type %s.\n", debugstr_w(strDevTyp)); dwRet = MCIERR_DEVICE_NOT_INSTALLED; } goto errCleanUp; } /* FIXME: should also check that module's description is of the form * MODULENAME:[MCI] comment */ /* some drivers will return 0x0000FFFF, some others 0xFFFFFFFF */ wmd->uSpecificCmdTable = LOWORD(modp.wCustomCommandTable); wmd->uTypeCmdTable = MCI_COMMAND_TABLE_NOT_LOADED; TRACE("Loaded driver %p (%s), type is %d, cmdTable=%08x\n", wmd->hDriver, debugstr_w(strDevTyp), modp.wType, modp.wCustomCommandTable); wmd->lpstrDeviceType = strDevTyp; wmd->wType = modp.wType; TRACE("mcidev=%d, uDevTyp=%04X wDeviceID=%04X !\n", modp.wDeviceID, modp.wType, modp.wDeviceID); *lpwmd = wmd; return 0; errCleanUp: MCI_UnLoadMciDriver(wmd); HeapFree(GetProcessHeap(), 0, strDevTyp); *lpwmd = 0; return dwRet; } /************************************************************************** * MCI_SendCommandFrom32 [internal] */ static DWORD MCI_SendCommandFrom32(MCIDEVICEID wDevID, UINT16 wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2) { DWORD dwRet = MCIERR_INVALID_DEVICE_ID; LPWINE_MCIDRIVER wmd = MCI_GetDriver(wDevID); if (wmd) { dwRet = SendDriverMessage(wmd->hDriver, wMsg, dwParam1, dwParam2); } return dwRet; } /************************************************************************** * MCI_FinishOpen [internal] * * Three modes of operation: * 1 open foo.ext ... -> OPEN_ELEMENT with lpstrElementName=foo.ext * open sequencer!foo.ext same with lpstrElementName=foo.ext * 2 open new type waveaudio -> OPEN_ELEMENT with empty ("") lpstrElementName * 3 open sequencer -> OPEN_ELEMENT unset, and * capability sequencer (auto-open) likewise */ static DWORD MCI_FinishOpen(LPWINE_MCIDRIVER wmd, LPMCI_OPEN_PARMSW lpParms, DWORD dwParam) { LPCWSTR alias = NULL; /* Open always defines an alias for further reference */ if (dwParam & MCI_OPEN_ALIAS) { /* open ... alias */ alias = lpParms->lpstrAlias; if (MCI_GetDriverFromString(alias)) return MCIERR_DUPLICATE_ALIAS; } else { if ((dwParam & MCI_OPEN_ELEMENT) /* open file.wav */ && !(dwParam & MCI_OPEN_ELEMENT_ID)) alias = lpParms->lpstrElementName; else if (dwParam & MCI_OPEN_TYPE ) /* open cdaudio */ alias = wmd->lpstrDeviceType; if (alias && MCI_GetDriverFromString(alias)) return MCIERR_DEVICE_OPEN; } if (alias) { wmd->lpstrAlias = HeapAlloc(GetProcessHeap(), 0, (strlenW(alias)+1) * sizeof(WCHAR)); if (!wmd->lpstrAlias) return MCIERR_OUT_OF_MEMORY; strcpyW( wmd->lpstrAlias, alias); /* In most cases, natives adds MCI_OPEN_ALIAS to the flags passed to the driver. * Don't. The drivers don't care about the winmm alias. */ } lpParms->wDeviceID = wmd->wDeviceID; return MCI_SendCommandFrom32(wmd->wDeviceID, MCI_OPEN_DRIVER, dwParam, (DWORD_PTR)lpParms); } /************************************************************************** * MCI_FindCommand [internal] */ static LPCWSTR MCI_FindCommand(UINT uTbl, LPCWSTR verb) { UINT idx; if (uTbl >= MAX_MCICMDTABLE || !S_MciCmdTable[uTbl].lpTable) return NULL; /* another improvement would be to have the aVerbs array sorted, * so that we could use a dichotomic search on it, rather than this dumb * array look up */ for (idx = 0; idx < S_MciCmdTable[uTbl].nVerbs; idx++) { if (strcmpiW(S_MciCmdTable[uTbl].aVerbs[idx], verb) == 0) return S_MciCmdTable[uTbl].aVerbs[idx]; } return NULL; } /************************************************************************** * MCI_GetReturnType [internal] */ static DWORD MCI_GetReturnType(LPCWSTR lpCmd) { lpCmd = (LPCWSTR)((const BYTE*)(lpCmd + strlenW(lpCmd) + 1) + sizeof(DWORD) + sizeof(WORD)); if (*lpCmd == '\0' && *(const WORD*)((const BYTE*)(lpCmd + 1) + sizeof(DWORD)) == MCI_RETURN) { return *(const DWORD*)(lpCmd + 1); } return 0L; } /************************************************************************** * MCI_GetMessage [internal] */ static WORD MCI_GetMessage(LPCWSTR lpCmd) { return (WORD)*(const DWORD*)(lpCmd + strlenW(lpCmd) + 1); } /************************************************************************** * MCI_GetDWord [internal] * * Accept 0 -1 255 255:0 255:255:255:255 :::1 1::: 2::3 ::4: 12345678 * Refuse -1:0 0:-1 :: 256:0 1:256 0::::1 */ static BOOL MCI_GetDWord(DWORD* data, LPWSTR* ptr) { LPWSTR ret = *ptr; DWORD total = 0, shift = 0; BOOL sign = FALSE, digits = FALSE; while (*ret == ' ' || *ret == '\t') ret++; if (*ret == '-') { ret++; sign = TRUE; } for(;;) { DWORD val = 0; while ('0' <= *ret && *ret <= '9') { val = *ret++ - '0' + 10 * val; digits = TRUE; } switch (*ret) { case '\0': break; case '\t': case ' ': ret++; break; default: return FALSE; case ':': if ((val >= 256) || (shift >= 24)) return FALSE; total |= val << shift; shift += 8; ret++; continue; } if (!digits) return FALSE; if (shift && (val >= 256 || sign)) return FALSE; total |= val << shift; *data = sign ? -total : total; *ptr = ret; return TRUE; } } /************************************************************************** * MCI_GetString [internal] */ static DWORD MCI_GetString(LPWSTR* str, LPWSTR* args) { LPWSTR ptr = *args; /* see if we have a quoted string */ if (*ptr == '"') { ptr = strchrW(*str = ptr + 1, '"'); if (!ptr) return MCIERR_NO_CLOSING_QUOTE; /* FIXME: shall we escape \" from string ?? */ if (ptr[-1] == '\\') TRACE("Ooops: un-escaped \"\n"); *ptr++ = '\0'; /* remove trailing " */ if (*ptr != ' ' && *ptr != '\0') return MCIERR_EXTRA_CHARACTERS; } else { ptr = strchrW(ptr, ' '); if (ptr) { *ptr++ = '\0'; } else { ptr = *args + strlenW(*args); } *str = *args; } *args = ptr; return 0; } #define MCI_DATA_SIZE 16 /************************************************************************** * MCI_ParseOptArgs [internal] */ static DWORD MCI_ParseOptArgs(DWORD* data, int _offset, LPCWSTR lpCmd, LPWSTR args, LPDWORD dwFlags) { int len, offset; const char* lmem; LPCWSTR str; DWORD dwRet, flg, cflg = 0; WORD eid; BOOL inCst, found; /* loop on arguments */ while (*args) { lmem = (const char*)lpCmd; found = inCst = FALSE; offset = _offset; /* skip any leading white space(s) */ while (*args == ' ') args++; TRACE("args=%s\n", debugstr_w(args)); do { /* loop on options for command table for the requested verb */ str = (LPCWSTR)lmem; lmem += ((len = strlenW(str)) + 1) * sizeof(WCHAR); flg = *(const DWORD*)lmem; eid = *(const WORD*)(lmem + sizeof(DWORD)); lmem += sizeof(DWORD) + sizeof(WORD); /* TRACE("\tcmd=%s inCst=%c eid=%04x\n", debugstr_w(str), inCst ? 'Y' : 'N', eid); */ switch (eid) { case MCI_CONSTANT: inCst = TRUE; cflg = flg; break; case MCI_END_CONSTANT: /* there may be additional integral values after flag in constant */ if (inCst && MCI_GetDWord(&(data[offset]), &args)) { *dwFlags |= cflg; } inCst = FALSE; cflg = 0; break; case MCI_RETURN: if (offset != _offset) { FIXME("MCI_RETURN not in first position\n"); return MCIERR_PARSER_INTERNAL; } } if (strncmpiW(args, str, len) == 0 && ((eid == MCI_STRING && len == 0) || args[len] == 0 || args[len] == ' ')) { /* store good values into data[] */ args += len; while (*args == ' ') args++; found = TRUE; switch (eid) { case MCI_COMMAND_HEAD: case MCI_RETURN: case MCI_END_COMMAND: case MCI_END_COMMAND_LIST: case MCI_CONSTANT: /* done above */ case MCI_END_CONSTANT: /* done above */ break; case MCI_FLAG: *dwFlags |= flg; TRACE("flag=%08x\n", flg); break; case MCI_HWND: case MCI_HPAL: case MCI_HDC: case MCI_INTEGER: if (inCst) { data[offset] |= flg; *dwFlags |= cflg; inCst = FALSE; TRACE("flag=%08x constant=%08x\n", cflg, flg); } else { *dwFlags |= flg; if (!MCI_GetDWord(&(data[offset]), &args)) { return MCIERR_BAD_INTEGER; } TRACE("flag=%08x int=%d\n", flg, data[offset]); } break; case MCI_RECT: /* store rect in data (offset..offset+3) */ *dwFlags |= flg; if (!MCI_GetDWord(&(data[offset+0]), &args) || !MCI_GetDWord(&(data[offset+1]), &args) || !MCI_GetDWord(&(data[offset+2]), &args) || !MCI_GetDWord(&(data[offset+3]), &args)) { return MCIERR_BAD_INTEGER; } TRACE("flag=%08x for rectangle\n", flg); break; case MCI_STRING: *dwFlags |= flg; if ((dwRet = MCI_GetString((LPWSTR*)&data[offset], &args))) return dwRet; TRACE("flag=%08x string=%s\n", flg, debugstr_w(*(LPWSTR*)&data[offset])); break; default: ERR("oops\n"); } /* exit inside while loop, except if just entered in constant area definition */ if (!inCst || eid != MCI_CONSTANT) eid = MCI_END_COMMAND; } else { /* have offset incremented if needed */ switch (eid) { case MCI_COMMAND_HEAD: case MCI_RETURN: case MCI_END_COMMAND: case MCI_END_COMMAND_LIST: case MCI_CONSTANT: case MCI_FLAG: break; case MCI_HWND: case MCI_HPAL: case MCI_HDC: if (!inCst) offset += sizeof(HANDLE)/sizeof(DWORD); break; case MCI_INTEGER: if (!inCst) offset++; break; case MCI_END_CONSTANT: offset++; break; case MCI_STRING: offset += sizeof(LPWSTR)/sizeof(DWORD); break; case MCI_RECT: offset += 4; break; default: ERR("oops\n"); } } } while (eid != MCI_END_COMMAND); if (!found) { WARN("Optarg %s not found\n", debugstr_w(args)); return MCIERR_UNRECOGNIZED_COMMAND; } if (offset == MCI_DATA_SIZE) { FIXME("Internal data[] buffer overflow\n"); return MCIERR_PARSER_INTERNAL; } } return 0; } /************************************************************************** * MCI_HandleReturnValues [internal] */ static DWORD MCI_HandleReturnValues(DWORD dwRet, LPWINE_MCIDRIVER wmd, DWORD retType, MCI_GENERIC_PARMS *params, LPWSTR lpstrRet, UINT uRetLen) { static const WCHAR fmt_d [] = {'%','d',0}; static const WCHAR fmt_d4 [] = {'%','d',' ','%','d',' ','%','d',' ','%','d',0}; static const WCHAR wszCol3[] = {'%','0','2','d',':','%','0','2','d',':','%','0','2','d',0}; static const WCHAR wszCol4[] = {'%','0','2','d',':','%','0','2','d',':','%','0','2','d',':','%','0','2','d',0}; if (lpstrRet) { switch (retType) { case 0: /* nothing to return */ break; case MCI_INTEGER: { DWORD data = *(DWORD *)(params + 1); switch (dwRet & 0xFFFF0000ul) { case 0: case MCI_INTEGER_RETURNED: snprintfW(lpstrRet, uRetLen, fmt_d, data); break; case MCI_RESOURCE_RETURNED: /* return string which ID is HIWORD(data), * string is loaded from mmsystem.dll */ LoadStringW(hWinMM32Instance, HIWORD(data), lpstrRet, uRetLen); break; case MCI_RESOURCE_RETURNED|MCI_RESOURCE_DRIVER: /* return string which ID is HIWORD(data), * string is loaded from driver */ /* FIXME: this is wrong for a 16 bit handle */ LoadStringW(GetDriverModuleHandle(wmd->hDriver), HIWORD(data), lpstrRet, uRetLen); break; case MCI_COLONIZED3_RETURN: snprintfW(lpstrRet, uRetLen, wszCol3, LOBYTE(LOWORD(data)), HIBYTE(LOWORD(data)), LOBYTE(HIWORD(data))); break; case MCI_COLONIZED4_RETURN: snprintfW(lpstrRet, uRetLen, wszCol4, LOBYTE(LOWORD(data)), HIBYTE(LOWORD(data)), LOBYTE(HIWORD(data)), HIBYTE(HIWORD(data))); break; default: ERR("Ooops (%04X)\n", HIWORD(dwRet)); } break; } #ifdef MCI_INTEGER64 case MCI_INTEGER64: { static const WCHAR fmt_ld [] = {'%','l','d',0}; DWORD_PTR data = *(DWORD_PTR *)(params + 1); switch (dwRet & 0xFFFF0000ul) { case 0: case MCI_INTEGER_RETURNED: snprintfW(lpstrRet, uRetLen, fmt_ld, data); break; case MCI_RESOURCE_RETURNED: /* return string which ID is HIWORD(data), * string is loaded from mmsystem.dll */ LoadStringW(hWinMM32Instance, HIWORD(data), lpstrRet, uRetLen); break; case MCI_RESOURCE_RETURNED|MCI_RESOURCE_DRIVER: /* return string which ID is HIWORD(data), * string is loaded from driver */ /* FIXME: this is wrong for a 16 bit handle */ LoadStringW(GetDriverModuleHandle(wmd->hDriver), HIWORD(data), lpstrRet, uRetLen); break; case MCI_COLONIZED3_RETURN: snprintfW(lpstrRet, uRetLen, wszCol3, LOBYTE(LOWORD(data)), HIBYTE(LOWORD(data)), LOBYTE(HIWORD(data))); break; case MCI_COLONIZED4_RETURN: snprintfW(lpstrRet, uRetLen, wszCol4, LOBYTE(LOWORD(data)), HIBYTE(LOWORD(data)), LOBYTE(HIWORD(data)), HIBYTE(HIWORD(data))); break; default: ERR("Ooops (%04X)\n", HIWORD(dwRet)); } break; } #endif case MCI_STRING: switch (dwRet & 0xFFFF0000ul) { case 0: /* nothing to do data[0] == lpstrRet */ break; case MCI_INTEGER_RETURNED: { DWORD *data = (DWORD *)(params + 1); *data = *(LPDWORD)lpstrRet; snprintfW(lpstrRet, uRetLen, fmt_d, *data); break; } default: WARN("Oooch. MCI_STRING and HIWORD(dwRet)=%04x\n", HIWORD(dwRet)); break; } break; case MCI_RECT: { DWORD *data = (DWORD *)(params + 1); if (dwRet & 0xFFFF0000ul) WARN("Oooch. MCI_STRING and HIWORD(dwRet)=%04x\n", HIWORD(dwRet)); snprintfW(lpstrRet, uRetLen, fmt_d4, data[0], data[1], data[2], data[3]); break; } default: FIXME("Unknown MCI return type %d\n", retType); } } return LOWORD(dwRet); } /************************************************************************** * mciSendStringW [WINMM.@] */ DWORD WINAPI mciSendStringW(LPCWSTR lpstrCommand, LPWSTR lpstrRet, UINT uRetLen, HWND hwndCallback) { LPWSTR verb, dev, args; LPWINE_MCIDRIVER wmd = 0; MCIDEVICEID uDevID, auto_open = 0; DWORD dwFlags = 0, dwRet = 0; int offset = 0; DWORD retType; LPCWSTR lpCmd = 0; WORD wMsg = 0; static const WCHAR wszNew[] = {'n','e','w',0}; static const WCHAR wszSAliasS[] = {' ','a','l','i','a','s',' ',0}; static const WCHAR wszTypeS[] = {'t','y','p','e',' ',0}; union { MCI_GENERIC_PARMS generic; MCI_OPEN_PARMSW open; MCI_SOUND_PARMSW sound; MCI_SYSINFO_PARMSW sysinfo; DWORD dw[MCI_DATA_SIZE]; } data; TRACE("(%s, %p, %d, %p)\n", debugstr_w(lpstrCommand), lpstrRet, uRetLen, hwndCallback); if (lpstrRet && uRetLen) *lpstrRet = '\0'; /* format is <command> <device> <optargs> */ if (!(verb = HeapAlloc(GetProcessHeap(), 0, (strlenW(lpstrCommand)+1) * sizeof(WCHAR)))) return MCIERR_OUT_OF_MEMORY; strcpyW( verb, lpstrCommand ); CharLowerW(verb); memset(&data, 0, sizeof(data)); if (!(args = strchrW(verb, ' '))) { dwRet = MCIERR_MISSING_DEVICE_NAME; goto errCleanUp; } *args++ = '\0'; if ((dwRet = MCI_GetString(&dev, &args))) { goto errCleanUp; } uDevID = strcmpiW(dev, wszAll) ? 0 : MCI_ALL_DEVICE_ID; /* Determine devType from open */ if (!strcmpW(verb, wszOpen)) { LPWSTR devType, tmp; WCHAR buf[128]; /* case dev == 'new' has to be handled */ if (!strcmpW(dev, wszNew)) { dev = 0; if ((devType = strstrW(args, wszTypeS)) != NULL) { devType += 5; tmp = strchrW(devType, ' '); if (tmp) *tmp = '\0'; devType = str_dup_upper(devType); if (tmp) *tmp = ' '; /* dwFlags and data[2] will be correctly set in ParseOpt loop */ } else { WARN("open new requires device type\n"); dwRet = MCIERR_MISSING_DEVICE_NAME; goto errCleanUp; } dwFlags |= MCI_OPEN_ELEMENT; data.open.lpstrElementName = &wszNull[0]; } else if ((devType = strchrW(dev, '!')) != NULL) { *devType++ = '\0'; tmp = devType; devType = dev; dev = tmp; dwFlags |= MCI_OPEN_TYPE; data.open.lpstrDeviceType = devType; devType = str_dup_upper(devType); dwFlags |= MCI_OPEN_ELEMENT; data.open.lpstrElementName = dev; } else if (DRIVER_GetLibName(dev, wszMci, buf, sizeof(buf))) { /* this is the name of a mci driver's type */ tmp = strchrW(dev, ' '); if (tmp) *tmp = '\0'; data.open.lpstrDeviceType = dev; devType = str_dup_upper(dev); if (tmp) *tmp = ' '; dwFlags |= MCI_OPEN_TYPE; } else { if ((devType = strstrW(args, wszTypeS)) != NULL) { devType += 5; tmp = strchrW(devType, ' '); if (tmp) *tmp = '\0'; devType = str_dup_upper(devType); if (tmp) *tmp = ' '; /* dwFlags and lpstrDeviceType will be correctly set in ParseOpt loop */ } else { if ((dwRet = MCI_GetDevTypeFromFileName(dev, buf, sizeof(buf)))) goto errCleanUp; devType = str_dup_upper(buf); } dwFlags |= MCI_OPEN_ELEMENT; data.open.lpstrElementName = dev; } if (MCI_ALL_DEVICE_ID == uDevID) { dwRet = MCIERR_CANNOT_USE_ALL; goto errCleanUp; } if (!strstrW(args, wszSAliasS) && !dev) { dwRet = MCIERR_NEW_REQUIRES_ALIAS; goto errCleanUp; } dwRet = MCI_LoadMciDriver(devType, &wmd); if (dwRet == MCIERR_DEVICE_NOT_INSTALLED) dwRet = MCIERR_INVALID_DEVICE_NAME; HeapFree(GetProcessHeap(), 0, devType); if (dwRet) goto errCleanUp; } else if ((MCI_ALL_DEVICE_ID != uDevID) && !(wmd = MCI_GetDriver(mciGetDeviceIDW(dev))) && (lpCmd = MCI_FindCommand(MCI_GetCommandTable(0), verb))) { /* auto-open uses the core command table */ switch (MCI_GetMessage(lpCmd)) { case MCI_SOUND: /* command does not use a device name */ case MCI_SYSINFO: break; case MCI_CLOSE: /* don't auto-open for close */ case MCI_BREAK: /* no auto-open for system commands */ dwRet = MCIERR_INVALID_DEVICE_NAME; goto errCleanUp; break; default: { static const WCHAR wszOpenWait[] = {'o','p','e','n',' ','%','s',' ','w','a','i','t',0}; WCHAR buf[138], retbuf[6]; snprintfW(buf, sizeof(buf)/sizeof(WCHAR), wszOpenWait, dev); /* open via mciSendString handles quoting, dev!file syntax and alias creation */ if ((dwRet = mciSendStringW(buf, retbuf, sizeof(retbuf)/sizeof(WCHAR), 0)) != 0) goto errCleanUp; auto_open = strtoulW(retbuf, NULL, 10); TRACE("auto-opened %u for %s\n", auto_open, debugstr_w(dev)); /* FIXME: test for notify flag (how to preparse?) before opening */ wmd = MCI_GetDriver(auto_open); if (!wmd) { ERR("No auto-open device %u\n", auto_open); dwRet = MCIERR_INVALID_DEVICE_ID; goto errCleanUp; } } } } /* get the verb in the different command tables */ if (wmd) { /* try the device specific command table */ lpCmd = MCI_FindCommand(wmd->uSpecificCmdTable, verb); if (!lpCmd) { /* try the type specific command table */ if (wmd->uTypeCmdTable == MCI_COMMAND_TABLE_NOT_LOADED) wmd->uTypeCmdTable = MCI_GetCommandTable(wmd->wType); if (wmd->uTypeCmdTable != MCI_NO_COMMAND_TABLE) lpCmd = MCI_FindCommand(wmd->uTypeCmdTable, verb); } } /* try core command table */ if (!lpCmd) lpCmd = MCI_FindCommand(MCI_GetCommandTable(0), verb); if (!lpCmd) { TRACE("Command %s not found!\n", debugstr_w(verb)); dwRet = MCIERR_UNRECOGNIZED_COMMAND; goto errCleanUp; } wMsg = MCI_GetMessage(lpCmd); /* set return information */ offset = sizeof(data.generic); switch (retType = MCI_GetReturnType(lpCmd)) { case 0: break; case MCI_INTEGER: offset += sizeof(DWORD); break; case MCI_STRING: data.sysinfo.lpstrReturn = lpstrRet; data.sysinfo.dwRetSize = uRetLen; offset = FIELD_OFFSET( MCI_SYSINFO_PARMSW, dwNumber ); break; case MCI_RECT: offset += 4 * sizeof(DWORD); break; #ifdef MCI_INTEGER64 case MCI_INTEGER64: offset += sizeof(DWORD_PTR); break; #endif default: FIXME("Unknown MCI return type %d\n", retType); dwRet = MCIERR_PARSER_INTERNAL; goto errCleanUp; } TRACE("verb=%s on dev=%s; offset=%d\n", debugstr_w(verb), debugstr_w(dev), offset); if ((dwRet = MCI_ParseOptArgs(data.dw, offset / sizeof(DWORD), lpCmd, args, &dwFlags))) goto errCleanUp; /* set up call back */ if (auto_open) { if (dwFlags & MCI_NOTIFY) { dwRet = MCIERR_NOTIFY_ON_AUTO_OPEN; goto errCleanUp; } /* FIXME: the command should get its own notification window set up and * ask for device closing while processing the notification mechanism. * hwndCallback = ... * dwFlags |= MCI_NOTIFY; * In the meantime special-case all commands but PLAY and RECORD below. */ } if (dwFlags & MCI_NOTIFY) { data.generic.dwCallback = (DWORD_PTR)hwndCallback; } switch (wMsg) { case MCI_OPEN: if (strcmpW(verb, wszOpen)) { FIXME("Cannot open with command %s\n", debugstr_w(verb)); dwRet = MCIERR_DRIVER_INTERNAL; wMsg = 0; goto errCleanUp; } break; case MCI_SYSINFO: /* Requirements on dev depend on the flags: * alias with INSTALLNAME, name like "digitalvideo" * with QUANTITY and NAME. */ { data.sysinfo.wDeviceType = MCI_ALL_DEVICE_ID; if (uDevID != MCI_ALL_DEVICE_ID) { if (dwFlags & MCI_SYSINFO_INSTALLNAME) wmd = MCI_GetDriver(mciGetDeviceIDW(dev)); else if (!(data.sysinfo.wDeviceType = MCI_GetDevTypeFromResource(dev))) { dwRet = MCIERR_DEVICE_TYPE_REQUIRED; goto errCleanUp; } } } break; case MCI_SOUND: /* FIXME: name is optional, "sound" is a valid command. * FIXME: Parse "sound notify" as flag, not as name. */ data.sound.lpstrSoundName = dev; dwFlags |= MCI_SOUND_NAME; break; } TRACE("[%d, %s, %08x, %08x %08x %08x %08x %08x %08x %08x %08x %08x %08x]\n", wmd ? wmd->wDeviceID : uDevID, MCI_MessageToString(wMsg), dwFlags, data.dw[0], data.dw[1], data.dw[2], data.dw[3], data.dw[4], data.dw[5], data.dw[6], data.dw[7], data.dw[8], data.dw[9]); if (wMsg == MCI_OPEN) { if ((dwRet = MCI_FinishOpen(wmd, &data.open, dwFlags))) goto errCleanUp; /* FIXME: notification is not properly shared across two opens */ } else { dwRet = MCI_SendCommand(wmd ? wmd->wDeviceID : uDevID, wMsg, dwFlags, (DWORD_PTR)&data); } if (!LOWORD(dwRet)) { TRACE("=> 1/ %x (%s)\n", dwRet, debugstr_w(lpstrRet)); dwRet = MCI_HandleReturnValues(dwRet, wmd, retType, &data.generic, lpstrRet, uRetLen); TRACE("=> 2/ %x (%s)\n", dwRet, debugstr_w(lpstrRet)); } else TRACE("=> %x\n", dwRet); errCleanUp: if (auto_open) { /* PLAY and RECORD are the only known non-immediate commands */ if (LOWORD(dwRet) || !(wMsg == MCI_PLAY || wMsg == MCI_RECORD)) MCI_SendCommand(auto_open, MCI_CLOSE, 0, 0); else FIXME("leaking auto-open device %u\n", auto_open); } if (wMsg == MCI_OPEN && LOWORD(dwRet) && wmd) MCI_UnLoadMciDriver(wmd); HeapFree(GetProcessHeap(), 0, verb); return dwRet; } /************************************************************************** * mciSendStringA [WINMM.@] */ DWORD WINAPI mciSendStringA(LPCSTR lpstrCommand, LPSTR lpstrRet, UINT uRetLen, HWND hwndCallback) { LPWSTR lpwstrCommand; LPWSTR lpwstrRet = NULL; UINT ret; INT len; /* FIXME: is there something to do with lpstrReturnString ? */ len = MultiByteToWideChar( CP_ACP, 0, lpstrCommand, -1, NULL, 0 ); lpwstrCommand = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ); MultiByteToWideChar( CP_ACP, 0, lpstrCommand, -1, lpwstrCommand, len ); if (lpstrRet) { if (uRetLen) *lpstrRet = '\0'; /* NT-w2k3 use memset(lpstrRet, 0, uRetLen); */ lpwstrRet = HeapAlloc(GetProcessHeap(), 0, uRetLen * sizeof(WCHAR)); if (!lpwstrRet) { HeapFree( GetProcessHeap(), 0, lpwstrCommand ); return MCIERR_OUT_OF_MEMORY; } } ret = mciSendStringW(lpwstrCommand, lpwstrRet, uRetLen, hwndCallback); if (!ret && lpwstrRet) WideCharToMultiByte( CP_ACP, 0, lpwstrRet, -1, lpstrRet, uRetLen, NULL, NULL ); HeapFree(GetProcessHeap(), 0, lpwstrCommand); HeapFree(GetProcessHeap(), 0, lpwstrRet); return ret; } /************************************************************************** * mciExecute [WINMM.@] */ BOOL WINAPI mciExecute(LPCSTR lpstrCommand) { char strRet[256]; DWORD ret; TRACE("(%s)!\n", lpstrCommand); ret = mciSendStringA(lpstrCommand, strRet, sizeof(strRet), 0); if (ret != 0) { if (!mciGetErrorStringA(ret, strRet, sizeof(strRet))) { sprintf(strRet, "Unknown MCI error (%d)", ret); } MessageBoxA(0, strRet, "Error in mciExecute()", MB_OK); } /* FIXME: what shall I return ? */ return TRUE; } /************************************************************************** * mciLoadCommandResource [WINMM.@] * * Strangely, this function only exists as a UNICODE one. */ UINT WINAPI mciLoadCommandResource(HINSTANCE hInst, LPCWSTR resNameW, UINT type) { UINT ret = MCI_NO_COMMAND_TABLE; HRSRC hRsrc = 0; HGLOBAL hMem; TRACE("(%p, %s, %d)!\n", hInst, debugstr_w(resNameW), type); /* if a file named "resname.mci" exits, then load resource "resname" from it * otherwise directly from driver * We don't support it (who uses this feature ?), but we check anyway */ if (!type) { #if 0 /* FIXME: we should put this back into order, but I never found a program * actually using this feature, so we may not need it */ char buf[128]; OFSTRUCT ofs; strcat(strcpy(buf, resname), ".mci"); if (OpenFile(buf, &ofs, OF_EXIST) != HFILE_ERROR) { FIXME("NIY: command table to be loaded from '%s'\n", ofs.szPathName); } #endif } if ((hRsrc = FindResourceW(hInst, resNameW, (LPWSTR)RT_RCDATA)) && (hMem = LoadResource(hInst, hRsrc))) { ret = MCI_SetCommandTable(hMem, type); FreeResource(hMem); } else WARN("No command table found in module for %s\n", debugstr_w(resNameW)); TRACE("=> %04x\n", ret); return ret; } /************************************************************************** * mciFreeCommandResource [WINMM.@] */ BOOL WINAPI mciFreeCommandResource(UINT uTable) { TRACE("(%08x)!\n", uTable); if (uTable >= MAX_MCICMDTABLE || !S_MciCmdTable[uTable].lpTable) return FALSE; FreeResource(S_MciCmdTable[uTable].hMem); S_MciCmdTable[uTable].hMem = NULL; S_MciCmdTable[uTable].lpTable = NULL; HeapFree(GetProcessHeap(), 0, S_MciCmdTable[uTable].aVerbs); S_MciCmdTable[uTable].aVerbs = 0; S_MciCmdTable[uTable].nVerbs = 0; return TRUE; } /************************************************************************** * MCI_Open [internal] */ static DWORD MCI_Open(DWORD dwParam, LPMCI_OPEN_PARMSW lpParms) { WCHAR strDevTyp[128]; DWORD dwRet; LPWINE_MCIDRIVER wmd = NULL; TRACE("(%08X, %p)\n", dwParam, lpParms); if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; /* only two low bytes are generic, the other ones are dev type specific */ #define WINE_MCIDRIVER_SUPP (0xFFFF0000|MCI_OPEN_SHAREABLE|MCI_OPEN_ELEMENT| \ MCI_OPEN_ALIAS|MCI_OPEN_TYPE|MCI_OPEN_TYPE_ID| \ MCI_NOTIFY|MCI_WAIT) if ((dwParam & ~WINE_MCIDRIVER_SUPP) != 0) FIXME("Unsupported yet dwFlags=%08X\n", dwParam & ~WINE_MCIDRIVER_SUPP); #undef WINE_MCIDRIVER_SUPP strDevTyp[0] = 0; if (dwParam & MCI_OPEN_TYPE) { if (dwParam & MCI_OPEN_TYPE_ID) { WORD uDevType = LOWORD(lpParms->lpstrDeviceType); if (uDevType < MCI_DEVTYPE_FIRST || uDevType > MCI_DEVTYPE_LAST || !LoadStringW(hWinMM32Instance, uDevType, strDevTyp, sizeof(strDevTyp) / sizeof(WCHAR))) { dwRet = MCIERR_BAD_INTEGER; goto errCleanUp; } } else { LPWSTR ptr; if (lpParms->lpstrDeviceType == NULL) { dwRet = MCIERR_NULL_PARAMETER_BLOCK; goto errCleanUp; } strcpyW(strDevTyp, lpParms->lpstrDeviceType); ptr = strchrW(strDevTyp, '!'); if (ptr) { /* this behavior is not documented in windows. However, since, in * some occasions, MCI_OPEN handling is translated by WinMM into * a call to mciSendString("open <type>"); this code shall be correct */ if (dwParam & MCI_OPEN_ELEMENT) { ERR("Both MCI_OPEN_ELEMENT(%s) and %s are used\n", debugstr_w(lpParms->lpstrElementName), debugstr_w(strDevTyp)); dwRet = MCIERR_UNRECOGNIZED_KEYWORD; goto errCleanUp; } dwParam |= MCI_OPEN_ELEMENT; *ptr++ = 0; /* FIXME: not a good idea to write in user supplied buffer */ lpParms->lpstrElementName = ptr; } } TRACE("devType=%s !\n", debugstr_w(strDevTyp)); } if (dwParam & MCI_OPEN_ELEMENT) { TRACE("lpstrElementName=%s\n", debugstr_w(lpParms->lpstrElementName)); if (dwParam & MCI_OPEN_ELEMENT_ID) { FIXME("Unsupported yet flag MCI_OPEN_ELEMENT_ID\n"); dwRet = MCIERR_UNRECOGNIZED_KEYWORD; goto errCleanUp; } if (!lpParms->lpstrElementName) { dwRet = MCIERR_NULL_PARAMETER_BLOCK; goto errCleanUp; } /* type, if given as a parameter, supersedes file extension */ if (!strDevTyp[0] && MCI_GetDevTypeFromFileName(lpParms->lpstrElementName, strDevTyp, sizeof(strDevTyp))) { static const WCHAR wszCdAudio[] = {'C','D','A','U','D','I','O',0}; if (GetDriveTypeW(lpParms->lpstrElementName) != DRIVE_CDROM) { dwRet = MCIERR_EXTENSION_NOT_FOUND; goto errCleanUp; } /* FIXME: this will not work if several CDROM drives are installed on the machine */ strcpyW(strDevTyp, wszCdAudio); } } if (strDevTyp[0] == 0) { FIXME("Couldn't load driver\n"); dwRet = MCIERR_INVALID_DEVICE_NAME; goto errCleanUp; } if (dwParam & MCI_OPEN_ALIAS) { TRACE("Alias=%s !\n", debugstr_w(lpParms->lpstrAlias)); if (!lpParms->lpstrAlias) { dwRet = MCIERR_NULL_PARAMETER_BLOCK; goto errCleanUp; } } if ((dwRet = MCI_LoadMciDriver(strDevTyp, &wmd))) { goto errCleanUp; } if ((dwRet = MCI_FinishOpen(wmd, lpParms, dwParam))) { TRACE("Failed to open driver (MCI_OPEN_DRIVER) [%08x], closing\n", dwRet); /* FIXME: is dwRet the correct ret code ? */ goto errCleanUp; } /* only handled devices fall through */ TRACE("wDevID=%04X wDeviceID=%d dwRet=%d\n", wmd->wDeviceID, lpParms->wDeviceID, dwRet); return 0; errCleanUp: if (wmd) MCI_UnLoadMciDriver(wmd); return dwRet; } /************************************************************************** * MCI_Close [internal] */ static DWORD MCI_Close(UINT wDevID, DWORD dwParam, LPMCI_GENERIC_PARMS lpParms) { DWORD dwRet; LPWINE_MCIDRIVER wmd; TRACE("(%04x, %08X, %p)\n", wDevID, dwParam, lpParms); /* Every device must handle MCI_NOTIFY on its own. */ if ((UINT16)wDevID == (UINT16)MCI_ALL_DEVICE_ID) { while (MciDrivers) { /* Retrieve the device ID under lock, but send the message without, * the driver might be calling some winmm functions from another * thread before being fully stopped. */ EnterCriticalSection(&WINMM_cs); if (!MciDrivers) { LeaveCriticalSection(&WINMM_cs); break; } wDevID = MciDrivers->wDeviceID; LeaveCriticalSection(&WINMM_cs); MCI_Close(wDevID, dwParam, lpParms); } return 0; } if (!(wmd = MCI_GetDriver(wDevID))) { return MCIERR_INVALID_DEVICE_ID; } dwRet = MCI_SendCommandFrom32(wDevID, MCI_CLOSE_DRIVER, dwParam, (DWORD_PTR)lpParms); MCI_UnLoadMciDriver(wmd); return dwRet; } /************************************************************************** * MCI_WriteString [internal] */ static DWORD MCI_WriteString(LPWSTR lpDstStr, DWORD dstSize, LPCWSTR lpSrcStr) { DWORD ret = 0; if (lpSrcStr) { if (dstSize <= strlenW(lpSrcStr)) { ret = MCIERR_PARAM_OVERFLOW; } else { strcpyW(lpDstStr, lpSrcStr); } } else { *lpDstStr = 0; } return ret; } /************************************************************************** * MCI_Sysinfo [internal] */ static DWORD MCI_SysInfo(UINT uDevID, DWORD dwFlags, LPMCI_SYSINFO_PARMSW lpParms) { DWORD ret = MCIERR_INVALID_DEVICE_ID, cnt = 0; WCHAR buf[2048], *s, *p; LPWINE_MCIDRIVER wmd; HKEY hKey; if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; if (lpParms->lpstrReturn == NULL) return MCIERR_PARAM_OVERFLOW; TRACE("(%08x, %08X, %p[num=%d, wDevTyp=%u])\n", uDevID, dwFlags, lpParms, lpParms->dwNumber, lpParms->wDeviceType); if ((WORD)MCI_ALL_DEVICE_ID == LOWORD(uDevID)) uDevID = MCI_ALL_DEVICE_ID; /* Be compatible with Win9x */ switch (dwFlags & ~(MCI_SYSINFO_OPEN|MCI_NOTIFY|MCI_WAIT)) { case MCI_SYSINFO_QUANTITY: if (lpParms->dwRetSize < sizeof(DWORD)) return MCIERR_PARAM_OVERFLOW; /* Win9x returns 0 for 0 < uDevID < (UINT16)MCI_ALL_DEVICE_ID */ if (uDevID == MCI_ALL_DEVICE_ID) { /* wDeviceType == MCI_ALL_DEVICE_ID is not recognized. */ if (dwFlags & MCI_SYSINFO_OPEN) { TRACE("MCI_SYSINFO_QUANTITY: # of open MCI drivers\n"); EnterCriticalSection(&WINMM_cs); for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) { cnt++; } LeaveCriticalSection(&WINMM_cs); } else { TRACE("MCI_SYSINFO_QUANTITY: # of installed MCI drivers\n"); if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, wszHklmMci, 0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) { RegQueryInfoKeyW( hKey, 0, 0, 0, &cnt, 0, 0, 0, 0, 0, 0, 0); RegCloseKey( hKey ); } if (GetPrivateProfileStringW(wszMci, 0, wszNull, buf, sizeof(buf) / sizeof(buf[0]), wszSystemIni)) for (s = buf; *s; s += strlenW(s) + 1) cnt++; } } else { if (dwFlags & MCI_SYSINFO_OPEN) { TRACE("MCI_SYSINFO_QUANTITY: # of open MCI drivers of type %d\n", lpParms->wDeviceType); EnterCriticalSection(&WINMM_cs); for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) { if (wmd->wType == lpParms->wDeviceType) cnt++; } LeaveCriticalSection(&WINMM_cs); } else { TRACE("MCI_SYSINFO_QUANTITY: # of installed MCI drivers of type %d\n", lpParms->wDeviceType); FIXME("Don't know how to get # of MCI devices of a given type\n"); /* name = LoadStringW(hWinMM32Instance, LOWORD(lpParms->wDeviceType)) * then lookup registry and/or system.ini for name, ignoring digits suffix */ switch (LOWORD(lpParms->wDeviceType)) { case MCI_DEVTYPE_CD_AUDIO: case MCI_DEVTYPE_WAVEFORM_AUDIO: case MCI_DEVTYPE_SEQUENCER: cnt = 1; break; default: /* "digitalvideo" gets 0 because it's not in the registry */ cnt = 0; } } } *(DWORD*)lpParms->lpstrReturn = cnt; TRACE("(%d) => '%d'\n", lpParms->dwNumber, *(DWORD*)lpParms->lpstrReturn); ret = MCI_INTEGER_RETURNED; /* return ret; Only Win9x sends a notification in this case. */ break; case MCI_SYSINFO_INSTALLNAME: TRACE("MCI_SYSINFO_INSTALLNAME\n"); if ((wmd = MCI_GetDriver(uDevID))) { ret = MCI_WriteString(lpParms->lpstrReturn, lpParms->dwRetSize, wmd->lpstrDeviceType); } else { ret = (uDevID == MCI_ALL_DEVICE_ID) ? MCIERR_CANNOT_USE_ALL : MCIERR_INVALID_DEVICE_NAME; } TRACE("(%d) => %s\n", lpParms->dwNumber, debugstr_w(lpParms->lpstrReturn)); break; case MCI_SYSINFO_NAME: s = NULL; if (dwFlags & MCI_SYSINFO_OPEN) { /* Win9x returns 0 for 0 < uDevID < (UINT16)MCI_ALL_DEVICE_ID */ TRACE("MCI_SYSINFO_NAME: nth alias of type %d\n", uDevID == MCI_ALL_DEVICE_ID ? MCI_ALL_DEVICE_ID : lpParms->wDeviceType); EnterCriticalSection(&WINMM_cs); for (wmd = MciDrivers; wmd; wmd = wmd->lpNext) { /* wDeviceType == MCI_ALL_DEVICE_ID is not recognized. */ if (uDevID == MCI_ALL_DEVICE_ID || lpParms->wDeviceType == wmd->wType) { cnt++; if (cnt == lpParms->dwNumber) { s = wmd->lpstrAlias; break; } } } LeaveCriticalSection(&WINMM_cs); ret = s ? MCI_WriteString(lpParms->lpstrReturn, lpParms->dwRetSize, s) : MCIERR_OUTOFRANGE; } else if (MCI_ALL_DEVICE_ID == uDevID) { TRACE("MCI_SYSINFO_NAME: device #%d\n", lpParms->dwNumber); if (RegOpenKeyExW( HKEY_LOCAL_MACHINE, wszHklmMci, 0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) { if (RegQueryInfoKeyW( hKey, 0, 0, 0, &cnt, 0, 0, 0, 0, 0, 0, 0) == ERROR_SUCCESS && lpParms->dwNumber <= cnt) { DWORD bufLen = sizeof(buf)/sizeof(buf[0]); if (RegEnumKeyExW(hKey, lpParms->dwNumber - 1, buf, &bufLen, 0, 0, 0, 0) == ERROR_SUCCESS) s = buf; } RegCloseKey( hKey ); } if (!s) { if (GetPrivateProfileStringW(wszMci, 0, wszNull, buf, sizeof(buf) / sizeof(buf[0]), wszSystemIni)) { for (p = buf; *p; p += strlenW(p) + 1, cnt++) { TRACE("%d: %s\n", cnt, debugstr_w(p)); if (cnt == lpParms->dwNumber - 1) { s = p; break; } } } } ret = s ? MCI_WriteString(lpParms->lpstrReturn, lpParms->dwRetSize, s) : MCIERR_OUTOFRANGE; } else { FIXME("MCI_SYSINFO_NAME: nth device of type %d\n", lpParms->wDeviceType); /* Cheating: what is asked for is the nth device from the registry. */ if (1 != lpParms->dwNumber || /* Handle only one of each kind. */ lpParms->wDeviceType < MCI_DEVTYPE_FIRST || lpParms->wDeviceType > MCI_DEVTYPE_LAST) ret = MCIERR_OUTOFRANGE; else { LoadStringW(hWinMM32Instance, LOWORD(lpParms->wDeviceType), lpParms->lpstrReturn, lpParms->dwRetSize); ret = 0; } } TRACE("(%d) => %s\n", lpParms->dwNumber, debugstr_w(lpParms->lpstrReturn)); break; default: TRACE("Unsupported flag value=%08x\n", dwFlags); ret = MCIERR_UNRECOGNIZED_KEYWORD; } if ((dwFlags & MCI_NOTIFY) && HRESULT_CODE(ret)==0) mciDriverNotify((HWND)lpParms->dwCallback, uDevID, MCI_NOTIFY_SUCCESSFUL); return ret; } /************************************************************************** * MCI_Break [internal] */ static DWORD MCI_Break(UINT wDevID, DWORD dwFlags, LPMCI_BREAK_PARMS lpParms) { DWORD dwRet = 0; if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; FIXME("(%04x) vkey %04X stub\n", dwFlags, lpParms->nVirtKey); if (MMSYSERR_NOERROR==dwRet && (dwFlags & MCI_NOTIFY)) mciDriverNotify((HWND)lpParms->dwCallback, wDevID, MCI_NOTIFY_SUCCESSFUL); return dwRet; } /************************************************************************** * MCI_Sound [internal] */ static DWORD MCI_Sound(UINT wDevID, DWORD dwFlags, LPMCI_SOUND_PARMSW lpParms) { DWORD dwRet; if (dwFlags & MCI_SOUND_NAME) { if (lpParms == NULL) return MCIERR_NULL_PARAMETER_BLOCK; else dwRet = PlaySoundW(lpParms->lpstrSoundName, NULL, SND_ALIAS | (dwFlags & MCI_WAIT ? SND_SYNC : SND_ASYNC)) ? 0 : MCIERR_HARDWARE; } else dwRet = PlaySoundW((LPCWSTR)SND_ALIAS_SYSTEMDEFAULT, NULL, SND_ALIAS_ID | (dwFlags & MCI_WAIT ? SND_SYNC : SND_ASYNC)) ? 0 : MCIERR_HARDWARE; if (!dwRet && lpParms && (dwFlags & MCI_NOTIFY)) mciDriverNotify((HWND)lpParms->dwCallback, wDevID, MCI_NOTIFY_SUCCESSFUL); return dwRet; } /************************************************************************** * MCI_SendCommand [internal] */ DWORD MCI_SendCommand(UINT wDevID, UINT16 wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2) { DWORD dwRet = MCIERR_UNRECOGNIZED_COMMAND; switch (wMsg) { case MCI_OPEN: dwRet = MCI_Open(dwParam1, (LPMCI_OPEN_PARMSW)dwParam2); break; case MCI_CLOSE: dwRet = MCI_Close(wDevID, dwParam1, (LPMCI_GENERIC_PARMS)dwParam2); break; case MCI_SYSINFO: dwRet = MCI_SysInfo(wDevID, dwParam1, (LPMCI_SYSINFO_PARMSW)dwParam2); break; case MCI_BREAK: dwRet = MCI_Break(wDevID, dwParam1, (LPMCI_BREAK_PARMS)dwParam2); break; case MCI_SOUND: dwRet = MCI_Sound(wDevID, dwParam1, (LPMCI_SOUND_PARMSW)dwParam2); break; default: if ((UINT16)wDevID == (UINT16)MCI_ALL_DEVICE_ID) { FIXME("unhandled MCI_ALL_DEVICE_ID\n"); dwRet = MCIERR_CANNOT_USE_ALL; } else { dwRet = MCI_SendCommandFrom32(wDevID, wMsg, dwParam1, dwParam2); } break; } return dwRet; } /************************************************************************** * MCI_CleanUp [internal] * * Some MCI commands need to be cleaned-up (when not called from * mciSendString), because MCI drivers return extra information for string * transformation. This function gets rid of them. */ static LRESULT MCI_CleanUp(LRESULT dwRet, UINT wMsg, DWORD_PTR dwParam2) { if (LOWORD(dwRet)) return LOWORD(dwRet); switch (wMsg) { case MCI_GETDEVCAPS: switch (dwRet & 0xFFFF0000ul) { case 0: case MCI_COLONIZED3_RETURN: case MCI_COLONIZED4_RETURN: case MCI_INTEGER_RETURNED: /* nothing to do */ break; case MCI_RESOURCE_RETURNED: case MCI_RESOURCE_RETURNED|MCI_RESOURCE_DRIVER: { LPMCI_GETDEVCAPS_PARMS lmgp; lmgp = (LPMCI_GETDEVCAPS_PARMS)dwParam2; TRACE("Changing %08x to %08x\n", lmgp->dwReturn, LOWORD(lmgp->dwReturn)); lmgp->dwReturn = LOWORD(lmgp->dwReturn); } break; default: FIXME("Unsupported value for hiword (%04x) returned by DriverProc(%s)\n", HIWORD(dwRet), MCI_MessageToString(wMsg)); } break; case MCI_STATUS: switch (dwRet & 0xFFFF0000ul) { case 0: case MCI_COLONIZED3_RETURN: case MCI_COLONIZED4_RETURN: case MCI_INTEGER_RETURNED: /* nothing to do */ break; case MCI_RESOURCE_RETURNED: case MCI_RESOURCE_RETURNED|MCI_RESOURCE_DRIVER: { LPMCI_STATUS_PARMS lsp; lsp = (LPMCI_STATUS_PARMS)dwParam2; TRACE("Changing %08lx to %08x\n", lsp->dwReturn, LOWORD(lsp->dwReturn)); lsp->dwReturn = LOWORD(lsp->dwReturn); } break; default: FIXME("Unsupported value for hiword (%04x) returned by DriverProc(%s)\n", HIWORD(dwRet), MCI_MessageToString(wMsg)); } break; case MCI_SYSINFO: switch (dwRet & 0xFFFF0000ul) { case 0: case MCI_INTEGER_RETURNED: /* nothing to do */ break; default: FIXME("Unsupported value for hiword (%04x)\n", HIWORD(dwRet)); } break; default: if (HIWORD(dwRet)) { FIXME("Got non null hiword for dwRet=0x%08lx for command %s\n", dwRet, MCI_MessageToString(wMsg)); } break; } return LOWORD(dwRet); } /************************************************************************** * mciGetErrorStringW [WINMM.@] */ BOOL WINAPI mciGetErrorStringW(MCIERROR wError, LPWSTR lpstrBuffer, UINT uLength) { BOOL ret = FALSE; if (lpstrBuffer != NULL && uLength > 0 && wError >= MCIERR_BASE && wError <= MCIERR_CUSTOM_DRIVER_BASE) { if (LoadStringW(hWinMM32Instance, wError, lpstrBuffer, uLength) > 0) { ret = TRUE; } } return ret; } /************************************************************************** * mciGetErrorStringA [WINMM.@] */ BOOL WINAPI mciGetErrorStringA(MCIERROR dwError, LPSTR lpstrBuffer, UINT uLength) { BOOL ret = FALSE; if (lpstrBuffer != NULL && uLength > 0 && dwError >= MCIERR_BASE && dwError <= MCIERR_CUSTOM_DRIVER_BASE) { if (LoadStringA(hWinMM32Instance, dwError, lpstrBuffer, uLength) > 0) { ret = TRUE; } } return ret; } /************************************************************************** * mciDriverNotify [WINMM.@] */ BOOL WINAPI mciDriverNotify(HWND hWndCallBack, MCIDEVICEID wDevID, UINT wStatus) { TRACE("(%p, %04x, %04X)\n", hWndCallBack, wDevID, wStatus); return PostMessageW(hWndCallBack, MM_MCINOTIFY, wStatus, wDevID); } /************************************************************************** * mciGetDriverData [WINMM.@] */ DWORD_PTR WINAPI mciGetDriverData(MCIDEVICEID uDeviceID) { LPWINE_MCIDRIVER wmd; TRACE("(%04x)\n", uDeviceID); wmd = MCI_GetDriver(uDeviceID); if (!wmd) { WARN("Bad uDeviceID\n"); return 0L; } return wmd->dwPrivate; } /************************************************************************** * mciSetDriverData [WINMM.@] */ BOOL WINAPI mciSetDriverData(MCIDEVICEID uDeviceID, DWORD_PTR data) { LPWINE_MCIDRIVER wmd; TRACE("(%04x, %08lx)\n", uDeviceID, data); wmd = MCI_GetDriver(uDeviceID); if (!wmd) { WARN("Bad uDeviceID\n"); return FALSE; } wmd->dwPrivate = data; return TRUE; } /************************************************************************** * mciSendCommandW [WINMM.@] * */ DWORD WINAPI mciSendCommandW(MCIDEVICEID wDevID, UINT wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2) { DWORD dwRet; TRACE("(%08x, %s, %08lx, %08lx)\n", wDevID, MCI_MessageToString(wMsg), dwParam1, dwParam2); dwRet = MCI_SendCommand(wDevID, wMsg, dwParam1, dwParam2); dwRet = MCI_CleanUp(dwRet, wMsg, dwParam2); TRACE("=> %08x\n", dwRet); return dwRet; } /************************************************************************** * mciSendCommandA [WINMM.@] */ DWORD WINAPI mciSendCommandA(MCIDEVICEID wDevID, UINT wMsg, DWORD_PTR dwParam1, DWORD_PTR dwParam2) { DWORD ret; int mapped; TRACE("(%08x, %s, %08lx, %08lx)\n", wDevID, MCI_MessageToString(wMsg), dwParam1, dwParam2); mapped = MCI_MapMsgAtoW(wMsg, dwParam1, &dwParam2); if (mapped == -1) { FIXME("message %04x mapping failed\n", wMsg); return MCIERR_OUT_OF_MEMORY; } ret = mciSendCommandW(wDevID, wMsg, dwParam1, dwParam2); if (mapped) MCI_UnmapMsgAtoW(wMsg, dwParam1, dwParam2, ret); return ret; } /************************************************************************** * mciGetDeviceIDA [WINMM.@] */ UINT WINAPI mciGetDeviceIDA(LPCSTR lpstrName) { LPWSTR w = MCI_strdupAtoW(lpstrName); UINT ret = MCIERR_OUT_OF_MEMORY; if (w) { ret = mciGetDeviceIDW(w); HeapFree(GetProcessHeap(), 0, w); } return ret; } /************************************************************************** * mciGetDeviceIDW [WINMM.@] */ UINT WINAPI mciGetDeviceIDW(LPCWSTR lpwstrName) { return MCI_GetDriverFromString(lpwstrName); } /************************************************************************** * MCI_DefYieldProc [internal] */ static UINT WINAPI MCI_DefYieldProc(MCIDEVICEID wDevID, DWORD data) { INT16 ret; MSG msg; TRACE("(0x%04x, 0x%08x)\n", wDevID, data); if ((HIWORD(data) != 0 && HWND_16(GetActiveWindow()) != HIWORD(data)) || (GetAsyncKeyState(LOWORD(data)) & 1) == 0) { PeekMessageW(&msg, 0, 0, 0, PM_REMOVE | PM_QS_SENDMESSAGE); ret = 0; } else { msg.hwnd = HWND_32(HIWORD(data)); while (!PeekMessageW(&msg, msg.hwnd, WM_KEYFIRST, WM_KEYLAST, PM_REMOVE)); ret = -1; } return ret; } /************************************************************************** * mciSetYieldProc [WINMM.@] */ BOOL WINAPI mciSetYieldProc(MCIDEVICEID uDeviceID, YIELDPROC fpYieldProc, DWORD dwYieldData) { LPWINE_MCIDRIVER wmd; TRACE("(%u, %p, %08x)\n", uDeviceID, fpYieldProc, dwYieldData); if (!(wmd = MCI_GetDriver(uDeviceID))) { WARN("Bad uDeviceID\n"); return FALSE; } wmd->lpfnYieldProc = fpYieldProc; wmd->dwYieldData = dwYieldData; return TRUE; } /************************************************************************** * mciGetDeviceIDFromElementIDA [WINMM.@] */ UINT WINAPI mciGetDeviceIDFromElementIDA(DWORD dwElementID, LPCSTR lpstrType) { LPWSTR w = MCI_strdupAtoW(lpstrType); UINT ret = 0; if (w) { ret = mciGetDeviceIDFromElementIDW(dwElementID, w); HeapFree(GetProcessHeap(), 0, w); } return ret; } /************************************************************************** * mciGetDeviceIDFromElementIDW [WINMM.@] */ UINT WINAPI mciGetDeviceIDFromElementIDW(DWORD dwElementID, LPCWSTR lpstrType) { /* FIXME: that's rather strange, there is no * mciGetDeviceIDFromElementID32A in winmm.spec */ FIXME("(%u, %s) stub\n", dwElementID, debugstr_w(lpstrType)); return 0; } /************************************************************************** * mciGetYieldProc [WINMM.@] */ YIELDPROC WINAPI mciGetYieldProc(MCIDEVICEID uDeviceID, DWORD* lpdwYieldData) { LPWINE_MCIDRIVER wmd; TRACE("(%u, %p)\n", uDeviceID, lpdwYieldData); if (!(wmd = MCI_GetDriver(uDeviceID))) { WARN("Bad uDeviceID\n"); return NULL; } if (!wmd->lpfnYieldProc) { WARN("No proc set\n"); return NULL; } if (lpdwYieldData) *lpdwYieldData = wmd->dwYieldData; return wmd->lpfnYieldProc; } /************************************************************************** * mciGetCreatorTask [WINMM.@] */ HTASK WINAPI mciGetCreatorTask(MCIDEVICEID uDeviceID) { LPWINE_MCIDRIVER wmd; HTASK ret = 0; if ((wmd = MCI_GetDriver(uDeviceID))) ret = (HTASK)(DWORD_PTR)wmd->CreatorThread; TRACE("(%u) => %p\n", uDeviceID, ret); return ret; } /************************************************************************** * mciDriverYield [WINMM.@] */ UINT WINAPI mciDriverYield(MCIDEVICEID uDeviceID) { LPWINE_MCIDRIVER wmd; UINT ret = 0; TRACE("(%04x)\n", uDeviceID); if (!(wmd = MCI_GetDriver(uDeviceID)) || !wmd->lpfnYieldProc) { MSG msg; PeekMessageW(&msg, 0, 0, 0, PM_REMOVE | PM_QS_SENDMESSAGE); } else { ret = wmd->lpfnYieldProc(uDeviceID, wmd->dwYieldData); } return ret; }
{ "content_hash": "2971718f1f18cfff6f9d69ef4aef8be6", "timestamp": "", "source": "github", "line_count": 2454, "max_line_length": 236, "avg_line_length": 31.30766096169519, "alnum_prop": 0.574041052206849, "repo_name": "howard5888/wine", "id": "5c9104591edd397930aeea8b00c8af5e777a5e79", "size": "77638", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wine-1.7.7/dlls/winmm/mci.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "3308" }, { "name": "C", "bytes": "118195026" }, { "name": "C++", "bytes": "180964" }, { "name": "JavaScript", "bytes": "300874" }, { "name": "Logos", "bytes": "4941" }, { "name": "Objective-C", "bytes": "247341" }, { "name": "Perl", "bytes": "339801" }, { "name": "Ruby", "bytes": "10503" }, { "name": "Shell", "bytes": "83026" }, { "name": "Visual Basic", "bytes": "53047" }, { "name": "XSLT", "bytes": "544" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Color Picker</title> <meta name="description" content="Ajaxload - Ajax loading gif generator" /> <link href="styles.css" rel="stylesheet" media="screen" type="text/css" /> <!--[if IE]><link href="css/styles_ie.css" rel="stylesheet" media="screen" /><![endif]--> <script type="text/javascript" src="domel.js"></script> <script type="text/javascript" src="script.js"></script> <script type="text/javascript" src="color-picker.js"></script> </head> <body> <h1>Color Slider</h1> <p class="boxIndent">This application generates a color slider simular to photoshop, and updates the hex value in the input fileds.</p> <div id="pickerContainer"> <form action="#preview" id="generator" method="post"> <fieldset> <h2>Color Picker</h2> <div id="color-picker"></div> <!--<img id="indicator" src="indicator.gif" alt="Loading..." /> --> <div id="type"></div> <div style="clear:both;height:50px;"></div> <p> <label class="sort" for="color1">Color 1 :</label> <span>#</span> <input type="text" id="color1" name="color1" class="color" value="FFFFFF" /> </p> <p> <label class="sort" for="color2">Color 2 :</label> <span>#</span><input type="text" id="color2" name="color2" class="color" value="000000" /> </p> </fieldset> </form> <div style="clear:both;"></div> </div> <? $t = date("d/j/y - g:i:a",filemtime('index.php')); echo '<hr /><p align="center" style="font:9px verdana;color:#999;">Last modified: '.$t.'</p>'; ?> </body> </html>
{ "content_hash": "ca86f3c34a7f58aff4d52746fe03878f", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 135, "avg_line_length": 35.875, "alnum_prop": 0.6416957026713124, "repo_name": "adswebwork/genesis", "id": "ff8cde7af95db5f6aa9b4707d7d780e47d318715", "size": "1722", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_TODO/scripts/color-picker/index.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46685" }, { "name": "HTML", "bytes": "307187" }, { "name": "JavaScript", "bytes": "1072069" }, { "name": "PHP", "bytes": "2007568" }, { "name": "Shell", "bytes": "58" } ], "symlink_target": "" }
#include "Mesh.h" Mesh::Mesh(): num_indices(0) { glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); glGenBuffers(1, &ebo); } Mesh::~Mesh() { if(vao != 0) { glDeleteVertexArrays(1, &vao); vao = 0; } if (vbo != 0) { glDeleteBuffers(1, &vbo); vbo = 0; } if (ebo != 0) { glDeleteBuffers(1, &ebo); ebo = 0; } for (int i = 0; i < textures.size(); ++i) { delete textures[i]; } textures.clear(); } void Mesh::setupMesh(const std::vector<Vertex>& vertices, const std::vector<GLuint>& indices, const std::vector<Texture*>& textures) { this->textures = textures; num_indices = indices.size(); glBindVertexArray(vao); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), indices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, normal)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, texcoord)); glBindVertexArray(0); } void Mesh::draw() { GLuint diffuse_nr = 0; GLuint specular_nr = 3; for(GLuint i = 0; i < textures.size(); ++i) { if(textures[i]->getTypeName() == "texture_diffuse") { textures[i]->bind(diffuse_nr++); } if (textures[i]->getTypeName() == "texture_specular") { textures[i]->bind(specular_nr++); } } glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, num_indices, GL_UNSIGNED_INT, 0); }
{ "content_hash": "8f9aebb7ede86fcaff1b7b5e8e6473e9", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 132, "avg_line_length": 23.890243902439025, "alnum_prop": 0.5946911689637571, "repo_name": "Shot511/GLWorkshops", "id": "fb206fe71bbe4a8a28bdaf33daace79270fb3269", "size": "1961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Workshops/Workshops/src/Mesh.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1656170" }, { "name": "C++", "bytes": "2066925" }, { "name": "GLSL", "bytes": "543" }, { "name": "Objective-C", "bytes": "63082" } ], "symlink_target": "" }
package com.alibaba.druid.sql.ast.statement; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.SQLObjectImpl; import com.alibaba.druid.sql.visitor.SQLASTVisitor; public class SQLAssignItem extends SQLObjectImpl { private SQLExpr target; private SQLExpr value; public SQLAssignItem(){ } public SQLAssignItem(SQLExpr target, SQLExpr value){ setTarget(target); setValue(value); } public SQLExpr getTarget() { return target; } public void setTarget(SQLExpr target) { if (target != null) { target.setParent(this); } this.target = target; } public SQLExpr getValue() { return value; } public void setValue(SQLExpr value) { if (value != null) { value.setParent(this); } this.value = value; } public void output(StringBuffer buf) { target.output(buf); buf.append(" = "); value.output(buf); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, this.target); acceptChild(visitor, this.value); } visitor.endVisit(this); } }
{ "content_hash": "1667454118964f8a8968c419507174a3", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 56, "avg_line_length": 21.689655172413794, "alnum_prop": 0.6009538950715422, "repo_name": "xiaomozhang/druid", "id": "032af4fb55225ebcc96a205a12502e1b2b89d724", "size": "1873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "druid-1.0.9/src/main/java/com/alibaba/druid/sql/ast/statement/SQLAssignItem.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "822" }, { "name": "CSS", "bytes": "834" }, { "name": "HTML", "bytes": "107230" }, { "name": "Java", "bytes": "9452355" }, { "name": "JavaScript", "bytes": "27929" }, { "name": "PLSQL", "bytes": "3943" }, { "name": "Shell", "bytes": "439" } ], "symlink_target": "" }
package search import "math" type MinAggregationResult struct { Name string Value float64 //+inf means missing value } func (a *MinAggregationResult) GetName() string { return a.Name } func (a *MinAggregationResult) GetType() AggregationType { return AggregationMinType } func (a *MinAggregationResult) HasValue() bool { return a != nil && !math.IsInf(a.Value, 1) }
{ "content_hash": "903dfad2dc17e027a7c625509d010f1d", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 58, "avg_line_length": 18.75, "alnum_prop": 0.7413333333333333, "repo_name": "aliyun/aliyun-tablestore-go-sdk", "id": "4b2515aa7ab5250f8c6007332564dd9751667a92", "size": "375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tablestore/search/aggregation_min_result.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "950532" }, { "name": "Shell", "bytes": "67" } ], "symlink_target": "" }
package com.wordpress.tonytam.util; /** @author by tonytam on 6/15/14. Credit: http://stackoverflow.com/questions/937313/android-basic-gesture-detection Usage ActivitySwipeDetector swipe = new ActivitySwipeDetector(this); LinearLayout swipe_layout = (LinearLayout) findViewById(R.id.swipe_layout); swipe_layout.setOnTouchListener(swipe); @Override public void left2right(View v) { switch(v.getId()){ case R.id.swipe_layout: // do your stuff here break; } } */ import android.util.Log; import android.view.MotionEvent; import android.view.View; public class ActivitySwipeDetector implements View.OnTouchListener { static final String logTag = "ActivitySwipeDetector"; private SwipeInterface activity; static final int MIN_DISTANCE = 80; private float downX, downY, upX, upY; public ActivitySwipeDetector(SwipeInterface activity){ this.activity = activity; } public void onRightToLeftSwipe(View v){ Log.i(logTag, "RightToLeftSwipe!"); activity.right2left(v); } public void onLeftToRightSwipe(View v){ Log.i(logTag, "LeftToRightSwipe!"); activity.left2right(v); } public void onTopToBottomSwipe(View v){ Log.i(logTag, "onTopToBottomSwipe!"); activity.top2bottom(v); } public void onBottomToTopSwipe(View v){ Log.i(logTag, "onBottomToTopSwipe!"); activity.bottom2top(v); } public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_DOWN: { downX = event.getX(); downY = event.getY(); return true; } case MotionEvent.ACTION_UP: { upX = event.getX(); upY = event.getY(); float deltaX = downX - upX; float deltaY = downY - upY; // swipe horizontal? if(Math.abs(deltaX) > MIN_DISTANCE){ // left or right if(deltaX < 0) { this.onLeftToRightSwipe(v); return true; } if(deltaX > 0) { this.onRightToLeftSwipe(v); return true; } } else { Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE); } // swipe vertical? if(Math.abs(deltaY) > MIN_DISTANCE){ // top or down if(deltaY < 0) { this.onTopToBottomSwipe(v); return true; } if(deltaY > 0) { this.onBottomToTopSwipe(v); return true; } } else { Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE); v.performClick(); } } } return false; } }
{ "content_hash": "00f8221f2cb2d7ac2853f8d2799d89e2", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 113, "avg_line_length": 29.479591836734695, "alnum_prop": 0.564901349948079, "repo_name": "tonytamsf/android-Math-Get-To-24", "id": "fc05dbf50513eaf40fed2abede590bc051733f45", "size": "2889", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/wordpress/tonytam/util/ActivitySwipeDetector.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "73718" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>geocoq-main: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.14.0 / geocoq-main - 2.4.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> geocoq-main <small> 2.4.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-04 11:11:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-04 11:11:08 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.14.0 Formal proof management system dune 3.0.3 Fast, portable, and opinionated build system ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; synopsis: &quot;A formalization of foundations of geometry in Coq&quot; description: &quot;This subpackage contains the main developments from Hilbert&#39;s and Tarski&#39;s axiom systems.&quot; maintainer: &quot;Julien Narboux &lt;julien@narboux.fr&gt;&quot; authors: [&quot;Gabriel Braun &lt;gabriel.braun@unistra.fr&gt;&quot; &quot;Pierre Boutry &lt;pierre.boutry@inria.fr&gt;&quot; &quot;Charly Gries &lt;charly.gries@etu.unistra.fr&gt;&quot; &quot;Julien Narboux &lt;narboux@unistra.fr&gt;&quot; &quot;Pascal Schreck &lt;schreck@unistra.fr&gt;&quot;] license: &quot;LGPL 3&quot; homepage: &quot;http://geocoq.github.io/GeoCoq/&quot; bug-reports: &quot;https://github.com/GeoCoq/GeoCoq/issues&quot; dev-repo: &quot;git+https://github.com/GeoCoq/GeoCoq.git&quot; depends: [ &quot;coq-geocoq-axioms&quot; { = &quot;2.4.0&quot; } ] build: [ [&quot;mkdir&quot; &quot;main/&quot;] [&quot;mv&quot; &quot;main.v&quot; &quot;main/&quot;] [&quot;./configure-main.sh&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [[make &quot;install&quot;]] tags: [ &quot;keyword:geometry&quot; &quot;keyword:neutral geometry&quot; &quot;keyword:euclidean geometry&quot; &quot;keyword:foundations&quot; &quot;keyword:Tarski&quot; &quot;keyword:Hilbert&quot; &quot;keyword:Euclid&quot; &quot;keyword:Pappus&quot; &quot;keyword:Desargues&quot; &quot;keyword:arithmetization&quot; &quot;keyword:Pythagoras&quot; &quot;keyword:Thales&#39; intercept theorem&quot; &quot;keyword:continuity&quot; &quot;keyword:ruler and compass&quot; &quot;keyword:parallel postulates&quot; &quot;category:Mathematics/Geometry/General&quot; &quot;date:2018-06-13&quot; ] extra-files: [[&quot;Make.in&quot; &quot;md5=ee7f1852debd8d9621ebafa3c8b25dcc&quot;]] url { src: &quot;https://github.com/GeoCoq/GeoCoq/archive/v2.4.0.tar.gz&quot; checksum: &quot;md5=4a4ad33b4cad9b815a9b5c6308524c63&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-geocoq-main.2.4.0 coq.8.14.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.0). The following dependencies couldn&#39;t be met: - coq-geocoq-main -&gt; coq-geocoq-axioms -&gt; coq-geocoq-coinc -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-geocoq-main.2.4.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": "a8ee3a7ffae90c459bfb7d7dc9620989", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 159, "avg_line_length": 43.03804347826087, "alnum_prop": 0.5546154817527466, "repo_name": "coq-bench/coq-bench.github.io", "id": "b0fa01ba7e03b75191693fbc3d9caaa2bcb5d9aa", "size": "7944", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.14.0/geocoq-main/2.4.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
module Alchemy # ActiveRecord scopes for Alchemy::Page # module Page::PageScopes extend ActiveSupport::Concern included do # All language root pages # scope :language_roots, -> { where(language_root: true) } # All layout pages # scope :layoutpages, -> { where(layoutpage: true) } # All locked pages # scope :all_locked, -> { where(locked: true) } # All pages locked by given user # scope :all_locked_by, ->(user) { if user.class.respond_to? :primary_key all_locked.where(locked_by: user.send(user.class.primary_key)) end } # All not locked pages # scope :not_locked, -> { where(locked: false) } # All visible pages # scope :visible, -> { where(visible: true) } # All public pages # scope :published, -> { where(public: true) } # All not restricted pages # scope :not_restricted, -> { where(restricted: false) } # All restricted pages # scope :restricted, -> { where(restricted: true) } # All pages that are a published language root # scope :public_language_roots, -> { published.language_roots.where( language_code: Language.published.pluck(:code) ) } # Last 5 pages that where recently edited by given user # scope :all_last_edited_from, ->(user) { where(updater_id: user.id).order('updated_at DESC').limit(5) } # Returns all pages that have the given +language_id+ # scope :with_language, ->(language_id) { where(language_id: language_id) } # Returns all content pages. # scope :contentpages, -> { where(layoutpage: [false, nil]).where(Page.arel_table[:parent_id].not_eq(nil)) } # Returns all public contentpages that are not locked. # # Used for flushing all pages caches at once. # scope :flushables, -> { not_locked.published.contentpages } # Returns all layoutpages that are not locked. # # Used for flushing all pages caches at once. # scope :flushable_layoutpages, -> { not_locked.layoutpages.where.not(parent_id: Page.unscoped.root.id) } # All searchable pages # scope :searchables, -> { not_restricted.published.contentpages } # All pages from +Alchemy::Site.current+ # scope :from_current_site, -> { where(Language.table_name => {site_id: Site.current || Site.default}).joins(:language) } # All pages for xml sitemap # scope :sitemap, -> { from_current_site.published.contentpages.where(sitemap: true) } end end end
{ "content_hash": "d24b041b52ca3e85ae4350f75b3f510f", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 112, "avg_line_length": 26.563106796116504, "alnum_prop": 0.5855263157894737, "repo_name": "thomasjachmann/alchemy_cms", "id": "7309ade6caf141f9426507043f866ae329803d3c", "size": "2736", "binary": false, "copies": "1", "ref": "refs/heads/fixes", "path": "app/models/alchemy/page/page_scopes.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "152904" }, { "name": "CoffeeScript", "bytes": "76438" }, { "name": "HTML", "bytes": "155652" }, { "name": "JavaScript", "bytes": "10730" }, { "name": "Ruby", "bytes": "965816" }, { "name": "Shell", "bytes": "157" } ], "symlink_target": "" }
@import XCTest; @interface Tests : XCTestCase @end @implementation Tests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__); } @end
{ "content_hash": "38dfe7d03a770124e43bedd822d8a3a6", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 107, "avg_line_length": 17.444444444444443, "alnum_prop": 0.6815286624203821, "repo_name": "BunLV/TBCore", "id": "c132672e1e89c288c5e7b404f0f6d0bbdcf69961", "size": "602", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Tests/Tests.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6696" }, { "name": "Objective-C", "bytes": "1218583" }, { "name": "Ruby", "bytes": "2606" }, { "name": "Shell", "bytes": "26397" } ], "symlink_target": "" }
package gofakes3 import ( "encoding/xml" "fmt" "net/http" "time" ) // Error codes are documented here: // https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html // // If you add a code to this list, please also add it to ErrorCode.Status(). // const ( ErrNone ErrorCode = "" // The Content-MD5 you specified did not match what we received. ErrBadDigest ErrorCode = "BadDigest" ErrBucketAlreadyExists ErrorCode = "BucketAlreadyExists" // Raised when attempting to delete a bucket that still contains items. ErrBucketNotEmpty ErrorCode = "BucketNotEmpty" // "Indicates that the versioning configuration specified in the request is invalid" ErrIllegalVersioningConfiguration ErrorCode = "IllegalVersioningConfigurationException" // You did not provide the number of bytes specified by the Content-Length // HTTP header: ErrIncompleteBody ErrorCode = "IncompleteBody" // POST requires exactly one file upload per request. ErrIncorrectNumberOfFilesInPostRequest ErrorCode = "IncorrectNumberOfFilesInPostRequest" // InlineDataTooLarge occurs when using the PutObjectInline method of the // SOAP interface // (https://docs.aws.amazon.com/AmazonS3/latest/API/SOAPPutObjectInline.html). // This is not documented on the errors page; the error is included here // only for reference. ErrInlineDataTooLarge ErrorCode = "InlineDataTooLarge" ErrInvalidArgument ErrorCode = "InvalidArgument" // https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules ErrInvalidBucketName ErrorCode = "InvalidBucketName" // The Content-MD5 you specified is not valid. ErrInvalidDigest ErrorCode = "InvalidDigest" ErrInvalidRange ErrorCode = "InvalidRange" ErrInvalidToken ErrorCode = "InvalidToken" ErrKeyTooLong ErrorCode = "KeyTooLongError" // This is not a typo: Error is part of the string, but redundant in the constant name ErrMalformedPOSTRequest ErrorCode = "MalformedPOSTRequest" // One or more of the specified parts could not be found. The part might // not have been uploaded, or the specified entity tag might not have // matched the part's entity tag. ErrInvalidPart ErrorCode = "InvalidPart" // The list of parts was not in ascending order. Parts list must be // specified in order by part number. ErrInvalidPartOrder ErrorCode = "InvalidPartOrder" ErrInvalidURI ErrorCode = "InvalidURI" ErrMetadataTooLarge ErrorCode = "MetadataTooLarge" ErrMethodNotAllowed ErrorCode = "MethodNotAllowed" ErrMalformedXML ErrorCode = "MalformedXML" // You must provide the Content-Length HTTP header. ErrMissingContentLength ErrorCode = "MissingContentLength" // See BucketNotFound() for a helper function for this error: ErrNoSuchBucket ErrorCode = "NoSuchBucket" // See KeyNotFound() for a helper function for this error: ErrNoSuchKey ErrorCode = "NoSuchKey" // The specified multipart upload does not exist. The upload ID might be // invalid, or the multipart upload might have been aborted or completed. ErrNoSuchUpload ErrorCode = "NoSuchUpload" ErrNoSuchVersion ErrorCode = "NoSuchVersion" // No need to retransmit the object ErrNotModified ErrorCode = "NotModified" ErrRequestTimeTooSkewed ErrorCode = "RequestTimeTooSkewed" ErrTooManyBuckets ErrorCode = "TooManyBuckets" ErrNotImplemented ErrorCode = "NotImplemented" ErrInternal ErrorCode = "InternalError" ) // INTERNAL errors! These are not part of the S3 interface, they are codes // we have declared ourselves. Should all map to a 500 status code: const ( ErrInternalPageNotImplemented InternalErrorCode = "PaginationNotImplemented" ) // errorResponse should be implemented by any type that needs to be handled by // ensureErrorResponse. type errorResponse interface { Error enrich(requestID string) } func ensureErrorResponse(err error, requestID string) Error { switch err := err.(type) { case errorResponse: err.enrich(requestID) return err case ErrorCode: return &ErrorResponse{ Code: err, RequestID: requestID, Message: string(err), } default: return &ErrorResponse{ Code: ErrInternal, Message: "Internal Error", RequestID: requestID, } } } type Error interface { error ErrorCode() ErrorCode } // ErrorResponse is the base error type returned by S3 when any error occurs. // // Some errors contain their own additional fields in the response, for example // ErrRequestTimeTooSkewed, which contains the server time and the skew limit. // To create one of these responses, subclass it (but please don't export it): // // type notQuiteRightResponse struct { // ErrorResponse // ExtraField int // } // // Next, create a constructor that populates the error. Interfaces won't work // for this job as the error itself does double-duty as the XML response // object. Fill the struct out however you please, but don't forget to assign // Code and Message: // // func NotQuiteRight(at time.Time, max time.Duration) error { // code := ErrNotQuiteRight // return &notQuiteRightResponse{ // ErrorResponse{Code: code, Message: code.Message()}, // 123456789, // } // } // type ErrorResponse struct { XMLName xml.Name `xml:"Error"` Code ErrorCode Message string `xml:",omitempty"` RequestID string `xml:"RequestId,omitempty"` HostID string `xml:"HostId,omitempty"` } func (e *ErrorResponse) ErrorCode() ErrorCode { return e.Code } func (e *ErrorResponse) Error() string { return fmt.Sprintf("%s: %s", e.Code, e.Message) } func (r *ErrorResponse) enrich(requestID string) { r.RequestID = requestID } func ErrorMessage(code ErrorCode, message string) error { return &ErrorResponse{Code: code, Message: message} } func ErrorMessagef(code ErrorCode, message string, args ...interface{}) error { return &ErrorResponse{Code: code, Message: fmt.Sprintf(message, args...)} } type ErrorInvalidArgumentResponse struct { ErrorResponse ArgumentName string `xml:"ArgumentName"` ArgumentValue string `xml:"ArgumentValue"` } func ErrorInvalidArgument(name, value, message string) error { return &ErrorInvalidArgumentResponse{ ErrorResponse: ErrorResponse{Code: ErrInvalidArgument, Message: message}, ArgumentName: name, ArgumentValue: value} } // ErrorCode represents an S3 error code, documented here: // https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html type ErrorCode string func (e ErrorCode) ErrorCode() ErrorCode { return e } func (e ErrorCode) Error() string { return string(e) } // InternalErrorCode represents an GoFakeS3 error code. It maps to ErrInternal // when constructing a response. type InternalErrorCode string func (e InternalErrorCode) ErrorCode() ErrorCode { return ErrInternal } func (e InternalErrorCode) Error() string { return string(ErrInternal) } // Message tries to return the same string as S3 would return for the error // response, when it is known, or nothing when it is not. If you see the status // text for a code we don't have listed in here in the wild, please let us // know! func (e ErrorCode) Message() string { switch e { case ErrInvalidBucketName: return `Bucket name must match the regex "^[a-zA-Z0-9.\-_]{1,255}$"` case ErrNoSuchBucket: return "The specified bucket does not exist" case ErrRequestTimeTooSkewed: return "The difference between the request time and the current time is too large" case ErrMalformedXML: return "The XML you provided was not well-formed or did not validate against our published schema" default: return "" } } func (e ErrorCode) Status() int { switch e { case ErrBucketAlreadyExists, ErrBucketNotEmpty: return http.StatusConflict case ErrBadDigest, ErrIllegalVersioningConfiguration, ErrIncompleteBody, ErrIncorrectNumberOfFilesInPostRequest, ErrInlineDataTooLarge, ErrInvalidArgument, ErrInvalidBucketName, ErrInvalidDigest, ErrInvalidPart, ErrInvalidPartOrder, ErrInvalidToken, ErrInvalidURI, ErrKeyTooLong, ErrMetadataTooLarge, ErrMethodNotAllowed, ErrMalformedPOSTRequest, ErrMalformedXML, ErrTooManyBuckets: return http.StatusBadRequest case ErrRequestTimeTooSkewed: return http.StatusForbidden case ErrInvalidRange: return http.StatusRequestedRangeNotSatisfiable case ErrNoSuchBucket, ErrNoSuchKey, ErrNoSuchUpload, ErrNoSuchVersion: return http.StatusNotFound case ErrNotImplemented: return http.StatusNotImplemented case ErrNotModified: return http.StatusNotModified case ErrMissingContentLength: return http.StatusLengthRequired case ErrInternal: return http.StatusInternalServerError } return http.StatusInternalServerError } // HasErrorCode asserts that the error has a specific error code: // // if HasErrorCode(err, ErrNoSuchBucket) { // // handle condition // } // // If err is nil and code is ErrNone, HasErrorCode returns true. // func HasErrorCode(err error, code ErrorCode) bool { if err == nil && code == "" { return true } s3err, ok := err.(interface{ ErrorCode() ErrorCode }) if !ok { return false } return s3err.ErrorCode() == code } // IsAlreadyExists asserts that the error is a kind that indicates the resource // already exists, similar to os.IsExist. func IsAlreadyExists(err error) bool { return HasErrorCode(err, ErrBucketAlreadyExists) } type resourceErrorResponse struct { ErrorResponse Resource string } var _ errorResponse = &resourceErrorResponse{} func ResourceError(code ErrorCode, resource string) error { return &resourceErrorResponse{ ErrorResponse{Code: code, Message: code.Message()}, resource, } } func BucketNotFound(bucket string) error { return ResourceError(ErrNoSuchBucket, bucket) } func KeyNotFound(key string) error { return ResourceError(ErrNoSuchKey, key) } type requestTimeTooSkewedResponse struct { ErrorResponse ServerTime time.Time MaxAllowedSkewMilliseconds durationAsMilliseconds } var _ errorResponse = &requestTimeTooSkewedResponse{} func requestTimeTooSkewed(at time.Time, max time.Duration) error { code := ErrRequestTimeTooSkewed return &requestTimeTooSkewedResponse{ ErrorResponse{Code: code, Message: code.Message()}, at, durationAsMilliseconds(max), } } // durationAsMilliseconds tricks xml.Marsha into serialising a time.Duration as // truncated milliseconds instead of nanoseconds. type durationAsMilliseconds time.Duration func (m durationAsMilliseconds) MarshalXML(e *xml.Encoder, start xml.StartElement) error { var s = fmt.Sprintf("%d", time.Duration(m)/time.Millisecond) return e.EncodeElement(s, start) }
{ "content_hash": "a03b37118c7e3921402710c9fe63a581", "timestamp": "", "source": "github", "line_count": 352, "max_line_length": 141, "avg_line_length": 30.019886363636363, "alnum_prop": 0.7604807419324312, "repo_name": "tomcz/s3backup", "id": "668f81456bb3030d4d46ad2c74c242772e715bca", "size": "10567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/github.com/johannesboyne/gofakes3/error.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "40461" }, { "name": "Makefile", "bytes": "1836" } ], "symlink_target": "" }
type: tutorial layout: tutorial title: "Creating a RESTful Web Service with Spring Boot" description: "This tutorial walks us through the process of creating a simple REST controller with Spring Boot" authors: Hadi Hariri, Edoardo Vacchi, Sébastien Deleuze showAuthorInfo: true source: spring-boot-restful --- Kotlin works quite smoothly with Spring Boot and many of the steps found on the [Spring Guides](https://spring.io/guides) for creating a RESTful service can be followed verbatim for Kotlin. There are some minor differences however when it comes to defining the Gradle configuration and the project layout structure, as well as the initialization code. In this tutorial we'll walk through the steps required. For a more thorough explanation of Spring Boot and RESTful services, please see [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/). Note that all classes in this tutorial are in the `org.jetbrains.kotlin.demo` package. ### Defining the project and dependencies {{ site.text_using_gradle }} The Gradle file is pretty much standard for Spring Boot. The only differences are the structure layout for source folders for Kotlin, the required Kotlin dependencies and the [*kotlin-spring*](https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugi) Gradle plugin (CGLIB proxies used for example for `@Configuration` and `@Bean` processing require `open` classes). ``` groovy buildscript { ext.kotlin_version = '{{ site.data.releases.latest.version }}' // Required for Kotlin integration ext.spring_boot_version = '1.5.4.RELEASE' repositories { jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version" } } apply plugin: 'kotlin' // Required for Kotlin integration apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-plugin apply plugin: 'org.springframework.boot' jar { baseName = 'gs-rest-service' version = '0.1.0' } repositories { jcenter() } dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration compile 'org.springframework.boot:spring-boot-starter-web' testCompile('org.springframework.boot:spring-boot-starter-test') } ``` ### Creating a Greeting Data Class and Controller The next step is to create Greeting Data class that has two properties: *id* and a *content* ``` kotlin data class Greeting(val id: Long, val content: String) ``` We now define the *GreetingController* which serves requests of the form */greeting?name={value}* and returns a JSON object representing an instance of *Greeting* ``` kotlin @RestController class GreetingController { val counter = AtomicLong() @GetMapping("/greeting") fun greeting(@RequestParam(value = "name", defaultValue = "World") name: String) = Greeting(counter.incrementAndGet(), "Hello, $name") } ``` As can be seen, this is again pretty much a one-to-one translation of Java to Kotlin, with nothing special required for Kotlin. ### Creating the Application class Finally we need to define an Application class. As Spring Boot looks for a public static main method, we need to define this in Kotlin. It could be done with the *@JvmStatic* annotation and a companion object but here we prefer using a [top-level function]({{ url_for('page', page_path="docs/reference/functions") }}) defined outside Application class since it leads to more concise and clean code. No need to mark the Application class as *open* since we are using the *kotlin-spring* Gradle plugin which does that automatically. ``` kotlin @SpringBootApplication class Application fun main(args: Array<String>) { SpringApplication.run(Application::class.java, *args) } ``` ### Running the application We can now use the any of the standard Gradle tasks for Spring Boot to run the application. As such, running ./gradlew bootRun the application is compiled, resources bundled and launched, allowing us to access is via the browser (default port is 8080) ![Running App]({{ url_for('tutorial_img', filename='spring-boot-restful/running-app.png')}})
{ "content_hash": "9d52b289689fd064c37e8e6e2ca85fce", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 398, "avg_line_length": 43.33653846153846, "alnum_prop": 0.758597736853783, "repo_name": "madvirus/kotlin-web-site", "id": "b42de7c7912746f6b6f76ae34c9988ce526c34b5", "size": "4512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pages/docs/tutorials/spring-boot-restful.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "103120" }, { "name": "HTML", "bytes": "69721" }, { "name": "JavaScript", "bytes": "144519" }, { "name": "Python", "bytes": "46014" }, { "name": "XSLT", "bytes": "7674" } ], "symlink_target": "" }
layout: post title: Broadcast Input To Current Session date: 2015-10-26 13:46:19.000000000 +09:00 type: post categories: - Tmux --- ## Configuration ``` :setw synchronize-panes ``` ## Shortcut ``` bind-key 키 set-window-option synchronize-panes ``` ## References * http://blog.sanctum.geek.nz/sync-tmux-panes/ * https://github.com/elasticdog/dotfiles/blob/master/tmux.conf
{ "content_hash": "ff34f2353e1bb7cd9c0f5672a06faa92", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 62, "avg_line_length": 17.857142857142858, "alnum_prop": 0.7253333333333334, "repo_name": "kyungw00k/kyungw00k.github.io", "id": "e418303381284da6b9c8579ca9d5deb175d59daa", "size": "381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2015-10-26-tmux-broadcast-input-to-current-session.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12324" }, { "name": "HTML", "bytes": "17187" }, { "name": "JavaScript", "bytes": "1779" }, { "name": "Ruby", "bytes": "214" } ], "symlink_target": "" }
using System; using System.Threading.Tasks; using Elasticsearch.Net; namespace Nest { public partial class ElasticClient { /// <inheritdoc /> public ISearchResponse<T> Scroll<T>(Func<ScrollDescriptor<T>, ScrollDescriptor<T>> scrollSelector) where T : class { return this.Dispatch<ScrollDescriptor<T>, ScrollRequestParameters, SearchResponse<T>>( scrollSelector, (p, d) => { string scrollId = p.ScrollId; p.ScrollId = null; return this.RawDispatch.ScrollDispatch<SearchResponse<T>>(p, scrollId); } ); } /// <inheritdoc /> public Task<ISearchResponse<T>> ScrollAsync<T>(Func<ScrollDescriptor<T>, ScrollDescriptor<T>> scrollSelector) where T : class { return this.DispatchAsync<ScrollDescriptor<T>, ScrollRequestParameters, SearchResponse<T>, ISearchResponse<T>>( scrollSelector, (p, d) => { string scrollId = p.ScrollId; p.ScrollId = null; return this.RawDispatch.ScrollDispatchAsync<SearchResponse<T>>(p, scrollId); } ); } /// <inheritdoc /> public IEmptyResponse ClearScroll(Func<ClearScrollDescriptor, ClearScrollDescriptor> clearScrollSelector) { return this.Dispatch<ClearScrollDescriptor, ClearScrollRequestParameters, EmptyResponse>( clearScrollSelector, (p, d) => this.RawDispatch.ClearScrollDispatch<EmptyResponse>(p) ); } /// <inheritdoc /> public Task<IEmptyResponse> ClearScrollAsync(Func<ClearScrollDescriptor, ClearScrollDescriptor> clearScrollSelector) { return this.DispatchAsync<ClearScrollDescriptor, ClearScrollRequestParameters, EmptyResponse, IEmptyResponse>( clearScrollSelector, (p, d) => this.RawDispatch.ClearScrollDispatchAsync<EmptyResponse>(p) ); } } }
{ "content_hash": "c78b3c5289c6b101a173907b0a05273f", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 127, "avg_line_length": 31.75, "alnum_prop": 0.703599550056243, "repo_name": "NickCraver/NEST", "id": "cf84b5ab001e77ea5d6d085d10da45aa174ca306", "size": "1780", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Nest/ElasticClient-Scroll.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "6227186" }, { "name": "CSS", "bytes": "33078" }, { "name": "F#", "bytes": "8380" }, { "name": "JavaScript", "bytes": "20562" }, { "name": "PowerShell", "bytes": "106841" }, { "name": "Puppet", "bytes": "85615" }, { "name": "Shell", "bytes": "2405" }, { "name": "XSLT", "bytes": "9157" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Sphaeria gallae Schwein., 1832 ### Remarks null
{ "content_hash": "a6560f7445022dfec0bc9aa4e78d3961", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 12.23076923076923, "alnum_prop": 0.710691823899371, "repo_name": "mdoering/backbone", "id": "98bcddb663af5770d4a47e0961c96de8bcc04556", "size": "238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Sordariomycetes/Diaporthales/Botryodiplodia/Botryodiplodia gallae/ Syn. Sphaeropsis gallae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
""" @file @brief Various functions to install `MinGW <http://www.mingw.org/>`_. """ from __future__ import print_function import sys import os import re from .install_custom import download_page, download_file from ..installhelper.install_cmd_helper import unzip_files def install_operadriver(dest_folder=".", fLOG=print, install=True, version=None): """ Installs `operadriver <https://github.com/operasoftware/operachromiumdriver/releases>`_. @param dest_folder where to download the setup @param fLOG logging function @param install install (otherwise only download) @param version version to install (unused) @return zip file in a list or list of unzipped files This is required for `Selenium <https://selenium-python.readthedocs.io/>`_. """ if version is None: content = download_page( "https://github.com/operasoftware/operachromiumdriver/releases") reg = re.compile( "/tag/v([.][0-9]+[.][0-9]+([.][0-9]+)?([.][0-9]+)?)") f = reg.findall(content) if not f: raise Exception( "unable to get the last version number for OperaDriver") version = f[0][0] if sys.platform.startswith("win"): url = "https://github.com/operasoftware/operachromiumdriver/releases/download/v{0}/operadriver_win64.zip".format( version) elif sys.platform.startswith("mac"): url = "https://github.com/operasoftware/operachromiumdriver/releases/download/v{0}/operadriver_mac64.zip".format( version) else: url = "https://github.com/operasoftware/operachromiumdriver/releases/download/v{0}/operadriver_linux64.zip".format( version) name = url.split("/")[-1] outfile = os.path.join(dest_folder, name) fLOG("[pymy] operadriver, download from ", url) download_file(url, outfile, fLOG=fLOG) if install: return unzip_files(outfile, whereTo=dest_folder, fLOG=fLOG) else: return [outfile]
{ "content_hash": "bec5f5d242b3cfe291277981471bc444", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 123, "avg_line_length": 38.425925925925924, "alnum_prop": 0.6346987951807229, "repo_name": "sdpython/pymyinstall", "id": "155c8b656bf22b6b8c3a460a38608ba64d4ad144", "size": "2075", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/pymyinstall/installcustom/install_custom_operadriver.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "19179" }, { "name": "HTML", "bytes": "1294549" }, { "name": "Inno Setup", "bytes": "7565" }, { "name": "Julia", "bytes": "688" }, { "name": "Jupyter Notebook", "bytes": "38720" }, { "name": "Python", "bytes": "2387148" }, { "name": "R", "bytes": "4370" }, { "name": "Shell", "bytes": "623" } ], "symlink_target": "" }
package org.apache.geode.management.internal.cli.functions; import java.util.HashSet; import java.util.Set; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.execute.FunctionAdapter; import org.apache.geode.cache.execute.FunctionContext; import org.apache.geode.cache.query.Index; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.internal.InternalEntity; import org.apache.geode.management.internal.cli.domain.IndexDetails; /** * The ListIndexFunction class is a GemFire function used to collect all the index information on * all Regions across the entire GemFire Cache (distributed system). * </p> * * @see org.apache.geode.cache.Cache * @see org.apache.geode.cache.execute.Function * @see org.apache.geode.cache.execute.FunctionAdapter * @see org.apache.geode.cache.execute.FunctionContext * @see org.apache.geode.internal.InternalEntity * @see org.apache.geode.management.internal.cli.domain.IndexDetails * @since GemFire 7.0 */ @SuppressWarnings("unused") public class ListIndexFunction extends FunctionAdapter implements InternalEntity { protected Cache getCache() { return CacheFactory.getAnyInstance(); } public String getId() { return ListIndexFunction.class.getName(); } public void execute(final FunctionContext context) { try { final Set<IndexDetails> indexDetailsSet = new HashSet<IndexDetails>(); final Cache cache = getCache(); final DistributedMember member = cache.getDistributedSystem().getDistributedMember(); for (final Index index : cache.getQueryService().getIndexes()) { indexDetailsSet.add(new IndexDetails(member, index)); } context.getResultSender().lastResult(indexDetailsSet); } catch (Exception e) { context.getResultSender().sendException(e); } } }
{ "content_hash": "cd746605afb34af5f012d04b8029e003", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 97, "avg_line_length": 32.36206896551724, "alnum_prop": 0.7575919019712307, "repo_name": "shankarh/geode", "id": "f8d302c9eafba6ff10e4c4875e8e67de17151507", "size": "2666", "binary": false, "copies": "5", "ref": "refs/heads/develop", "path": "geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/ListIndexFunction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "106707" }, { "name": "Groovy", "bytes": "2928" }, { "name": "HTML", "bytes": "3989323" }, { "name": "Java", "bytes": "26692657" }, { "name": "JavaScript", "bytes": "1781013" }, { "name": "Ruby", "bytes": "6751" }, { "name": "Scala", "bytes": "236394" }, { "name": "Shell", "bytes": "43900" } ], "symlink_target": "" }
android_external_chromium-1 ===========================
{ "content_hash": "273c5ec58c61f973f3ba7bc7d54d9d18", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 27, "avg_line_length": 27.5, "alnum_prop": 0.43636363636363634, "repo_name": "pbeeler/android_external_chromium", "id": "ecd42fbe54218782e7b0bbd3af97e578b7109a5b", "size": "55", "binary": false, "copies": "1", "ref": "refs/heads/sm-jb-mr1", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php namespace Drupal\Tests\content_translation\Functional; use Drupal\Core\Entity\ContentEntityInterface; use Drupal\Core\Entity\Sql\SqlContentEntityStorage; use Drupal\field\Entity\FieldConfig; use Drupal\language\Entity\ConfigurableLanguage; use Drupal\Tests\BrowserTestBase; use Drupal\field\Entity\FieldStorageConfig; /** * Base class for content translation tests. */ abstract class ContentTranslationTestBase extends BrowserTestBase { /** * Modules to enable. * * @var array */ protected static $modules = ['text']; /** * The entity type being tested. * * @var string */ protected $entityTypeId = 'entity_test_mul'; /** * The bundle being tested. * * @var string */ protected $bundle; /** * The added languages. * * @var array */ protected $langcodes; /** * The account to be used to test translation operations. * * @var \Drupal\user\UserInterface */ protected $translator; /** * The account to be used to test multilingual entity editing. * * @var \Drupal\user\UserInterface */ protected $editor; /** * The account to be used to test access to both workflows. * * @var \Drupal\user\UserInterface */ protected $administrator; /** * The name of the field used to test translation. * * @var string */ protected $fieldName; /** * The translation controller for the current entity type. * * @var \Drupal\content_translation\ContentTranslationHandlerInterface */ protected $controller; /** * @var \Drupal\content_translation\ContentTranslationManagerInterface */ protected $manager; protected function setUp() { parent::setUp(); $this->setupLanguages(); $this->setupBundle(); $this->enableTranslation(); $this->setupUsers(); $this->setupTestFields(); $this->manager = $this->container->get('content_translation.manager'); $this->controller = $this->manager->getTranslationHandler($this->entityTypeId); // Rebuild the container so that the new languages are picked up by services // that hold a list of languages. $this->rebuildContainer(); } /** * Adds additional languages. */ protected function setupLanguages() { $this->langcodes = ['it', 'fr']; foreach ($this->langcodes as $langcode) { ConfigurableLanguage::createFromLangcode($langcode)->save(); } array_unshift($this->langcodes, \Drupal::languageManager()->getDefaultLanguage()->getId()); } /** * Returns an array of permissions needed for the translator. */ protected function getTranslatorPermissions() { return array_filter([$this->getTranslatePermission(), 'create content translations', 'update content translations', 'delete content translations']); } /** * Returns the translate permissions for the current entity and bundle. */ protected function getTranslatePermission() { $entity_type = \Drupal::entityTypeManager()->getDefinition($this->entityTypeId); if ($permission_granularity = $entity_type->getPermissionGranularity()) { return $permission_granularity == 'bundle' ? "translate {$this->bundle} {$this->entityTypeId}" : "translate {$this->entityTypeId}"; } } /** * Returns an array of permissions needed for the editor. */ protected function getEditorPermissions() { // Every entity-type-specific test needs to define these. return []; } /** * Returns an array of permissions needed for the administrator. */ protected function getAdministratorPermissions() { return array_merge($this->getEditorPermissions(), $this->getTranslatorPermissions(), ['administer languages', 'administer content translation']); } /** * Creates and activates translator, editor and admin users. */ protected function setupUsers() { $this->translator = $this->drupalCreateUser($this->getTranslatorPermissions(), 'translator'); $this->editor = $this->drupalCreateUser($this->getEditorPermissions(), 'editor'); $this->administrator = $this->drupalCreateUser($this->getAdministratorPermissions(), 'administrator'); $this->drupalLogin($this->translator); } /** * Creates or initializes the bundle date if needed. */ protected function setupBundle() { if (empty($this->bundle)) { $this->bundle = $this->entityTypeId; } } /** * Enables translation for the current entity type and bundle. */ protected function enableTranslation() { // Enable translation for the current entity type and ensure the change is // picked up. \Drupal::service('content_translation.manager')->setEnabled($this->entityTypeId, $this->bundle, TRUE); } /** * Creates the test fields. */ protected function setupTestFields() { if (empty($this->fieldName)) { $this->fieldName = 'field_test_et_ui_test'; } FieldStorageConfig::create([ 'field_name' => $this->fieldName, 'type' => 'string', 'entity_type' => $this->entityTypeId, 'cardinality' => 1, ])->save(); FieldConfig::create([ 'entity_type' => $this->entityTypeId, 'field_name' => $this->fieldName, 'bundle' => $this->bundle, 'label' => 'Test translatable text-field', ])->save(); /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */ $display_repository = \Drupal::service('entity_display.repository'); $display_repository->getFormDisplay($this->entityTypeId, $this->bundle, 'default') ->setComponent($this->fieldName, [ 'type' => 'string_textfield', 'weight' => 0, ]) ->save(); } /** * Creates the entity to be translated. * * @param array $values * An array of initial values for the entity. * @param string $langcode * The initial language code of the entity. * @param string $bundle_name * (optional) The entity bundle, if the entity uses bundles. Defaults to * NULL. If left NULL, $this->bundle will be used. * * @return string * The entity id. */ protected function createEntity($values, $langcode, $bundle_name = NULL) { $entity_values = $values; $entity_values['langcode'] = $langcode; $entity_type = \Drupal::entityTypeManager()->getDefinition($this->entityTypeId); if ($bundle_key = $entity_type->getKey('bundle')) { $entity_values[$bundle_key] = $bundle_name ?: $this->bundle; } $storage = $this->container->get('entity_type.manager')->getStorage($this->entityTypeId); if (!($storage instanceof SqlContentEntityStorage)) { foreach ($values as $property => $value) { if (is_array($value)) { $entity_values[$property] = [$langcode => $value]; } } } $entity = $this->container->get('entity_type.manager') ->getStorage($this->entityTypeId) ->create($entity_values); $entity->save(); return $entity->id(); } /** * Returns the edit URL for the specified entity. * * @param \Drupal\Core\Entity\ContentEntityInterface $entity * The entity being edited. * * @return \Drupal\Core\Url * The edit URL. */ protected function getEditUrl(ContentEntityInterface $entity) { if ($entity->access('update', $this->loggedInUser)) { $url = $entity->toUrl('edit-form'); } else { $url = $entity->toUrl('drupal:content-translation-edit'); $url->setRouteParameter('language', $entity->language()->getId()); } return $url; } }
{ "content_hash": "e7757632c5cc0d4816eded9f7dbb4d55", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 152, "avg_line_length": 29.07751937984496, "alnum_prop": 0.6528925619834711, "repo_name": "electric-eloquence/fepper-drupal", "id": "17d40b7a8bac301f4bc0fd9d281bc241e16142f0", "size": "7502", "binary": false, "copies": "11", "ref": "refs/heads/dev", "path": "backend/drupal/core/modules/content_translation/tests/src/Functional/ContentTranslationTestBase.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2300765" }, { "name": "HTML", "bytes": "68444" }, { "name": "JavaScript", "bytes": "2453602" }, { "name": "Mustache", "bytes": "40698" }, { "name": "PHP", "bytes": "41684915" }, { "name": "PowerShell", "bytes": "755" }, { "name": "Shell", "bytes": "72896" }, { "name": "Stylus", "bytes": "32803" }, { "name": "Twig", "bytes": "1820730" }, { "name": "VBScript", "bytes": "466" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>json-formater</groupId> <artifactId>json-formater</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Maven webapp template</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.2.0.RELEASE</spring.version> <mybatis.version>3.2.8</mybatis.version> <dbcp2.version>2.0.1</dbcp2.version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-ehcache</artifactId> <version>1.0.3</version> </dependency> <!-- DB --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>${dbcp2.version}</version> </dependency> <!-- Logger --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- JSON Support --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.15</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.0</version> </dependency> <!-- Unit Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <!-- Others --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>json-formater</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "8c88fde2312fb1b46acf954d399179ff", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 104, "avg_line_length": 30.71851851851852, "alnum_prop": 0.6276826621654208, "repo_name": "gdsglgf/json-formater", "id": "60eb1d82655609319f459d95c76458860467bf50", "size": "4147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21989" }, { "name": "HTML", "bytes": "526569" }, { "name": "Java", "bytes": "62524" }, { "name": "JavaScript", "bytes": "17027" } ], "symlink_target": "" }
/** * FormModelTransport */ var FormModelTransport = { create: { url: "",//reasign dataType: "json", type: "PUT" }, parameterMap: function(options, operation) { if (operation == "create") { return { models: kendo.stringify(options.models) }; } } }; /** * FormModelSchema */ var FormModelSchema = { window : null,//reasign model: { id: "id", fields: null//reasign }, afterClose : null,//reasign parse:function (data) { this.window.data("kendoWindow").close(); if($.isFunction(this.afterClose)) { this.afterClose(data); } return data; } }; /** * FormActions */ var FormActions = { formRef: "default", save: function(e) { e.preventDefault(); var options = FormBind.options[this.formRef]; FormModelTransport.create.url = options.url.create; FormModelSchema.window = options.window; FormModelSchema.model.fields = options.fields.model; FormModelSchema.afterClose = options.afterClose; var formModelStore = new kendo.data.DataSource({ batch: true, transport: FormModelTransport, schema: FormModelSchema }); var object = {}; for(var index in options.fields.model) { object[index] = this[index]; } formModelStore.add(object); formModelStore.sync(); }, cancel: function(e) { e.preventDefault(); FormBind.options[this.formRef].window.data("kendoWindow").close(); } }; /** * FormWindow */ var FormWindow = { visible: false, modal: true, title: "Create", actions: ["Close"] }; /** * FormBind */ var FormBind = { options : [], init : function(formOptions) { var form = $.extend({}, FormActions, formOptions.fields.form); form.formRef = formOptions.formRef; FormBind.options[form.formRef] = formOptions; kendo.bind(formOptions.form, kendo.observable(form)); formOptions.window.show(); FormWindow.title = formOptions.title; formOptions.window.kendoWindow(FormWindow); } };
{ "content_hash": "12cc9e01a39ba0b75c21617a3c46e7c1", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 74, "avg_line_length": 22.529411764705884, "alnum_prop": 0.5522193211488251, "repo_name": "asajin/sf_accounting_001", "id": "8e10c75d7bb100d8b62b439c366b19102b7542d0", "size": "2298", "binary": false, "copies": "1", "ref": "refs/heads/master_1.0", "path": "web/bundles/accounting/js/base/base.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "440031" }, { "name": "C#", "bytes": "1167846" }, { "name": "CSS", "bytes": "431993" }, { "name": "JavaScript", "bytes": "656406" }, { "name": "PHP", "bytes": "231242" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="alert_dialog_button_bar_height">54dip</dimen> </resources>
{ "content_hash": "67f4c7352977614cc7f9174b50974a60", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 60, "avg_line_length": 31.25, "alnum_prop": 0.696, "repo_name": "tasomaniac/OpenLinkWith", "id": "de6c0afdbd29e18522166d26163222f135f5dc6d", "size": "125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resolver/src/main/res/values-h720dp/dimens.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1800" }, { "name": "Java", "bytes": "107029" }, { "name": "Kotlin", "bytes": "153670" } ], "symlink_target": "" }
package com.streamsets.pipeline.stage.processor.fieldorder.config; import com.streamsets.pipeline.api.GenerateResourceBundle; import com.streamsets.pipeline.api.Label; @GenerateResourceBundle public enum Groups implements Label { ORDER("Order"), ; String label; Groups(String label) { this.label = label; } @Override public String getLabel() { return label; } }
{ "content_hash": "9b4d397c3715cdd0d508470e4f2f98ba", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 66, "avg_line_length": 17.818181818181817, "alnum_prop": 0.7372448979591837, "repo_name": "SandishKumarHN/datacollector", "id": "3acbcde1dc86b0b72e2d139a5f811de43ee8d788", "size": "990", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "basic-lib/src/main/java/com/streamsets/pipeline/stage/processor/fieldorder/config/Groups.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "101291" }, { "name": "CSS", "bytes": "120603" }, { "name": "Groovy", "bytes": "11876" }, { "name": "HTML", "bytes": "529889" }, { "name": "Java", "bytes": "20591845" }, { "name": "JavaScript", "bytes": "1073298" }, { "name": "Python", "bytes": "7413" }, { "name": "Scala", "bytes": "6347" }, { "name": "Shell", "bytes": "30090" } ], "symlink_target": "" }
package handlers import ( "fmt" "github.com/SkylakeCoder/go-web/web" "sync" ) type Count struct { visitCount int64 lock sync.Mutex } func (c *Count) HandleRequest(req *web.Request, res *web.Response) { c.lock.Lock() c.visitCount++ c.lock.Unlock() res.WriteString(fmt.Sprintf("count: %d\n", c.visitCount)) res.Flush() }
{ "content_hash": "4b730814cd06997fe2dcfd4777b0a832", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 68, "avg_line_length": 16.142857142857142, "alnum_prop": 0.6814159292035398, "repo_name": "SkylakeCoder/go-web", "id": "943d5d323bc816d59abaed3e4982751e42313202", "size": "339", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/hello/handlers/count.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "21392" } ], "symlink_target": "" }
import _ from 'lodash'; import ERRORS from '../errors'; import sortedObject from 'sorted-object'; export default class AutoCorrector { correct({ packageJson, results }) { const { changes, fixes } = this.getChanges(results); const updatedPackageJson = this.applyChanges({ changes, packageJson }); return { fixes, updatedPackageJson }; } getChanges(results) { const changes = []; const fixes = { dependencies: [], devDependencies: [] }; for (const type in results) { const modules = results[type]; for (const module of modules) { const change = this.getChange({ module, type }); if (change) { changes.push(change); fixes[type].push(module.name); } } } return { changes, fixes }; } getChange({ module, type }) { if (module.errorIgnored) { return; } switch (module.error) { case ERRORS.SHOULD_BE_DEPENDENCY: case ERRORS.SHOULD_BE_DEV_DEPENDENCY: return function(packageJson) { const newType = type === 'dependencies' ? 'devDependencies' : 'dependencies'; const version = packageJson[type][module.name]; delete packageJson[type][module.name]; if (!packageJson[newType]) { packageJson[newType] = {}; } packageJson[newType][module.name] = version; packageJson[newType] = sortedObject(packageJson[newType]); }; case ERRORS.UNUSED: return packageJson => delete packageJson[type][module.name]; } } applyChanges({ changes, packageJson }) { const updatedPackageJson = _.cloneDeep(packageJson); for (const change of changes) { change(updatedPackageJson); } return updatedPackageJson; } }
{ "content_hash": "59d3f9b72fb24e21978891498ae74af6", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 75, "avg_line_length": 30.5, "alnum_prop": 0.6122102882984737, "repo_name": "charlierudolph/dependency-lint", "id": "a2dc9bfd75ba5572f903d357cdf318c8d8f0cf27", "size": "1769", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/auto_corrector/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "Gherkin", "bytes": "27211" }, { "name": "JavaScript", "bytes": "72391" } ], "symlink_target": "" }
package ipmi.sm.events; import ipmi.coding.commands.PrivilegeLevel; import ipmi.coding.commands.session.GetChannelCipherSuites; import ipmi.coding.security.CipherSuite; import ipmi.sm.StateMachine; import ipmi.sm.states.CiphersWaiting; import ipmi.sm.states.State; /** * Performed in {@link CiphersWaiting} {@link State} indcates that not all * available {@link CipherSuite}s were received from the remote system and more * {@link GetChannelCipherSuites} commands are needed. * * @see StateMachine */ public class GetChannelCipherSuitesPending extends Default { public GetChannelCipherSuitesPending(int sequenceNumber) { super(CipherSuite.getEmpty(), sequenceNumber, PrivilegeLevel.MaximumAvailable); } }
{ "content_hash": "39a57f6b2e08df7119b6662b0c0cef9e", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 79, "avg_line_length": 29, "alnum_prop": 0.7931034482758621, "repo_name": "luolvming/ipmi", "id": "92cbf563489a2cd0e8730aad935610b3e68fdaa6", "size": "1036", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/ipmi/sm/events/GetChannelCipherSuitesPending.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "738678" } ], "symlink_target": "" }
namespace Magnet.Migrations { using System; using System.Data.Entity.Migrations; public partial class test : DbMigration { public override void Up() { AddColumn("dbo.Locations", "Distance", c => c.Double(nullable: false)); } public override void Down() { DropColumn("dbo.Locations", "Distance"); } } }
{ "content_hash": "be48693d6d57df5c43926566da8918cb", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 83, "avg_line_length": 22.666666666666668, "alnum_prop": 0.5441176470588235, "repo_name": "mwilters/Magnet", "id": "1590def3d015b7def10aa5faba33e8755fcb56a9", "size": "408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Migrations/201702072108516_test.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "97" }, { "name": "C#", "bytes": "27831" }, { "name": "CSS", "bytes": "3744" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "439355" } ], "symlink_target": "" }
"""`main` is the top level module for your Flask application.""" # Import the Flask Framework from flask import Flask, request import jinja2 import os import codecs app = Flask(__name__) app.config['DEBUG'] = True app.debug = True # Note: We don't need to call run() since our application is embedded within # the App Engine WSGI application server. loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')) env = jinja2.Environment(autoescape=True, loader=loader) template = env.get_template('template.html') @app.route('/', methods=["GET", "POST"]) def main_page(): if request.method == 'POST': text = codecs.encode(request.form['text'], 'rot_13') return template.render(text=text) else: return template.render(text='hi!') @app.errorhandler(404) def page_not_found(e): """Return a custom 404 error.""" return 'Sorry, Nothing at this URL.', 404
{ "content_hash": "b8941a825a8ce53ebf89b33865c9442e", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 86, "avg_line_length": 25.7027027027027, "alnum_prop": 0.668769716088328, "repo_name": "wd15/rot13", "id": "059d67d6a6a2331c318f2f3797e72363833a8cfb", "size": "951", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "4010" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MongoBlog.Areas.Admin.Models { public class jQueryDataTableRequestModel { public string sEcho { get; set; } public string sSearch { get; set; } public int iDisplayLength { get; set; } public int iDisplayStart { get; set; } public int iColumns { get; set; } public int iSortingCols { get; set; } public string sColumns { get; set; } } }
{ "content_hash": "3c7e252cb2938faf2e3cc1f580f53ec2", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 47, "avg_line_length": 21.083333333333332, "alnum_prop": 0.6363636363636364, "repo_name": "mbanagouro/mongoblog", "id": "56e49aa9d4dfbd322ab0611fd7c9d959797b31e9", "size": "508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/MongoBlog/Areas/Admin/Models/jQueryDataTableRequestModel.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "100" }, { "name": "C#", "bytes": "69302" }, { "name": "CSS", "bytes": "528087" }, { "name": "JavaScript", "bytes": "1098978" } ], "symlink_target": "" }
using System.Drawing; namespace LTag.Draw { public class DrawParams { private float _scaleX = 1f; private float _scaleY = 1f; private float _offsetX = 0f; private float _offsetY = 0f; private float _rotation = 0f; public float ScaleX { get { return _scaleX; } set { _scaleX = value; } } public float ScaleY { get { return _scaleY; } set { _scaleY = value; } } public float OffsetX { get { return _offsetX; } set { _offsetX = value; } } public float OffsetY { get { return _offsetY; } set { _offsetY = value; } } public float Rotation { get { return _rotation; } set { _rotation = value; } } public void Apply(Graphics g, int width, int height) { g.ResetTransform(); if(_rotation != 0) g.RotateTransform(_rotation); if(_scaleX != 1 || _scaleY != 1) g.ScaleTransform(_scaleX, _scaleY); g.TranslateTransform(_offsetX * width, _offsetY * height); } } }
{ "content_hash": "8da8f219b5f43ea30f7aa6f5533cbe26", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 71, "avg_line_length": 18.568627450980394, "alnum_prop": 0.6124604012671595, "repo_name": "akx/ltag", "id": "54fa02ece1c7d484e968927675004bd9b6b0eb4e", "size": "949", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LTag/Draw/DrawParams.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "81574" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Usuarios extends CI_Controller { public function __construct(){ parent::__construct(); $this->load->model('usuarios_model','usuarios'); } public function index(){ $this->load->helper('url'); $data = array(); $data['csslogin'] = false; if($this->session->userdata('logged_in')){ $session_data = $this->session->userdata('logged_in'); $data['username'] = $session_data['username']; $data['tipousu'] = $session_data['tipousu']; $data['permiso'] = $session_data['permiso']; $this->load->view('usuarios/usuarios_view',$data); }else{ redirect('/login/index'); } } public function perfil(){ $this->load->helper('url'); $data = array(); $data['csslogin'] = false; if($this->session->userdata('logged_in')){ $session_data = $this->session->userdata('logged_in'); $data['username'] = $session_data['username']; $data['id'] = $session_data['id']; $datos = $this->usuarios->obtenerUsuario($data['id']); $data['datosusu'] = $datos; $data['tipousu'] = $session_data['tipousu']; $data['permiso'] = $session_data['permiso']; $this->load->view('usuarios/perfil_view',$data); }else{ redirect('/login/index'); } } public function editar(){ $this->load->helper('url'); $data = array(); $data['csslogin'] = false; if($this->session->userdata('logged_in')){ $session_data = $this->session->userdata('logged_in'); $data['username'] = $session_data['username']; $data['id'] = $session_data['id']; $datos = $this->usuarios->obtenerUsuario($data['id']); $data['datosusu'] = $datos; $data['tipousu'] = $session_data['tipousu']; $data['permiso'] = $session_data['permiso']; $this->load->view('usuarios/editar_view',$data); }else{ redirect('/login/index'); } } public function registrar(){ $this->load->helper('url'); $data = array(); $data['csslogin'] = false; if($this->session->userdata('logged_in')){ $session_data = $this->session->userdata('logged_in'); $data['username'] = $session_data['username']; $data['tipousu'] = $session_data['tipousu']; $data['permiso'] = $session_data['permiso']; $this->load->view('usuarios/registrar_view',$data); }else{ redirect('/login/index'); } } public function json(){ $this->url_elements = explode('/', $_SERVER['PATH_INFO']); $case = $this->url_elements[4]; switch ($case): case 'add': case 'update': $msj = $this->usuarios->crud($_POST); break; endswitch; echo json_encode(array("msj" => $msj)); } }
{ "content_hash": "ba0a3990833af8c57f9e8e6b493a37d8", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 66, "avg_line_length": 35.35227272727273, "alnum_prop": 0.5049823207971713, "repo_name": "SergioRe/inventariopycas", "id": "910ae41c75ec30f71180234ebb967fb22f8f0663", "size": "3111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/Usuarios.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "11314" }, { "name": "HTML", "bytes": "5633" }, { "name": "JavaScript", "bytes": "4839" }, { "name": "PHP", "bytes": "1902812" } ], "symlink_target": "" }
package net.sf.mmm.code.api.member; import java.lang.reflect.Field; import net.sf.mmm.code.api.copy.CodeNodeItemCopyable; import net.sf.mmm.code.api.expression.CodeExpression; import net.sf.mmm.code.api.expression.CodeVariable; import net.sf.mmm.code.api.item.CodeMutableItemWithType; import net.sf.mmm.code.api.merge.CodeAdvancedMergeableItem; import net.sf.mmm.util.exception.api.ReadOnlyException; /** * {@link CodeMember} for a field of a {@link net.sf.mmm.code.api.type.CodeType}. * * @see java.lang.reflect.Field * @see net.sf.mmm.code.api.type.CodeType#getFields() * @see CodeFields#getDeclared() * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public abstract interface CodeField extends CodeMember, CodeMutableItemWithType, CodeVariable, CodeAdvancedMergeableItem<CodeField>, CodeNodeItemCopyable<CodeFields, CodeField> { /** * @return the {@link CodeExpression} assigned to this field on initialization or {@code null} for none. */ CodeExpression getInitializer(); /** * @param initializer the new {@link #getInitializer() initializer}. * @throws ReadOnlyException if {@link #isImmutable() immutable}. */ void setInitializer(CodeExpression initializer); @Override Field getReflectiveObject(); /** * @return the {@link CodeMethod} that acts as getter to read this field or {@code null} if there is no such method. */ CodeMethod getGetter(); /** * @return the {@link CodeMethod} that acts as getter to read this field. If it does not yet exist, it will be * created. */ CodeMethod getOrCreateGetter(); /** * @return the {@link CodeMethod} that acts as setter to write this field or {@code null} if there is no such method. */ CodeMethod getSetter(); /** * @return the {@link CodeMethod} that acts as setter to write this field. If it does not yet exist, it will be * created. */ CodeMethod getOrCreateSetter(); @Override CodeField copy(); }
{ "content_hash": "a488fcaa4f83aa228f7a4797f1d8fe13", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 119, "avg_line_length": 31.265625, "alnum_prop": 0.7161419290354822, "repo_name": "m-m-m/code", "id": "e829447f1fa9292829e0afdf052da9e1e73cd377", "size": "2129", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/src/main/java/net/sf/mmm/code/api/member/CodeField.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "22094" }, { "name": "Java", "bytes": "1146826" } ], "symlink_target": "" }